agent-nuvira 3.1.3 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/agents/reasoner.d.ts +8 -0
- package/dist/agents/agents/reasoner.d.ts.map +1 -1
- package/dist/agents/agents/reasoner.js +53 -2
- package/dist/agents/agents/reasoner.js.map +1 -1
- package/dist/agents/agents/writer.d.ts +24 -0
- package/dist/agents/agents/writer.d.ts.map +1 -1
- package/dist/agents/agents/writer.js +194 -0
- package/dist/agents/agents/writer.js.map +1 -1
- package/dist/agents/composite-plan.d.ts +143 -0
- package/dist/agents/composite-plan.d.ts.map +1 -0
- package/dist/agents/composite-plan.js +399 -0
- package/dist/agents/composite-plan.js.map +1 -0
- package/dist/agents/long-form-plan.d.ts +156 -0
- package/dist/agents/long-form-plan.d.ts.map +1 -0
- package/dist/agents/long-form-plan.js +274 -0
- package/dist/agents/long-form-plan.js.map +1 -0
- package/dist/agents/orchestrator.d.ts +107 -0
- package/dist/agents/orchestrator.d.ts.map +1 -1
- package/dist/agents/orchestrator.js +501 -35
- package/dist/agents/orchestrator.js.map +1 -1
- package/dist/agents/prompt-assembly.d.ts +8 -0
- package/dist/agents/prompt-assembly.d.ts.map +1 -1
- package/dist/agents/prompt-assembly.js +17 -0
- package/dist/agents/prompt-assembly.js.map +1 -1
- package/dist/cli/chat.d.ts +27 -0
- package/dist/cli/chat.d.ts.map +1 -1
- package/dist/cli/chat.js +116 -6
- package/dist/cli/chat.js.map +1 -1
- package/dist/cli/execute.d.ts +12 -0
- package/dist/cli/execute.d.ts.map +1 -1
- package/dist/cli/execute.js +105 -2
- package/dist/cli/execute.js.map +1 -1
- package/dist/cli/models.d.ts.map +1 -1
- package/dist/cli/models.js +10 -0
- package/dist/cli/models.js.map +1 -1
- package/dist/cli/trace.d.ts.map +1 -1
- package/dist/cli/trace.js +27 -0
- package/dist/cli/trace.js.map +1 -1
- package/dist/gateway/registry.d.ts +31 -0
- package/dist/gateway/registry.d.ts.map +1 -1
- package/dist/gateway/registry.js +143 -13
- package/dist/gateway/registry.js.map +1 -1
- package/dist/inference/model-entitlement.d.ts +46 -0
- package/dist/inference/model-entitlement.d.ts.map +1 -0
- package/dist/inference/model-entitlement.js +98 -0
- package/dist/inference/model-entitlement.js.map +1 -0
- package/dist/learning/autonomy-policy.d.ts +334 -0
- package/dist/learning/autonomy-policy.d.ts.map +1 -0
- package/dist/learning/autonomy-policy.js +500 -0
- package/dist/learning/autonomy-policy.js.map +1 -0
- package/dist/learning/credential-fingerprint.d.ts +58 -0
- package/dist/learning/credential-fingerprint.d.ts.map +1 -0
- package/dist/learning/credential-fingerprint.js +126 -0
- package/dist/learning/credential-fingerprint.js.map +1 -0
- package/dist/learning/deliverable-class.d.ts +130 -0
- package/dist/learning/deliverable-class.d.ts.map +1 -0
- package/dist/learning/deliverable-class.js +432 -0
- package/dist/learning/deliverable-class.js.map +1 -0
- package/dist/learning/long-form.d.ts +252 -0
- package/dist/learning/long-form.d.ts.map +1 -0
- package/dist/learning/long-form.js +510 -0
- package/dist/learning/long-form.js.map +1 -0
- package/dist/learning/model-first-router.d.ts +17 -0
- package/dist/learning/model-first-router.d.ts.map +1 -1
- package/dist/learning/model-first-router.js +27 -0
- package/dist/learning/model-first-router.js.map +1 -1
- package/dist/learning/model-registry.d.ts +66 -4
- package/dist/learning/model-registry.d.ts.map +1 -1
- package/dist/learning/model-registry.js +67 -6
- package/dist/learning/model-registry.js.map +1 -1
- package/dist/learning/model-warmup.d.ts +97 -2
- package/dist/learning/model-warmup.d.ts.map +1 -1
- package/dist/learning/model-warmup.js +165 -60
- package/dist/learning/model-warmup.js.map +1 -1
- package/dist/learning/prompt-layers.d.ts +61 -0
- package/dist/learning/prompt-layers.d.ts.map +1 -0
- package/dist/learning/prompt-layers.js +140 -0
- package/dist/learning/prompt-layers.js.map +1 -0
- package/dist/learning/provider-limits.d.ts +66 -0
- package/dist/learning/provider-limits.d.ts.map +1 -0
- package/dist/learning/provider-limits.js +184 -0
- package/dist/learning/provider-limits.js.map +1 -0
- package/dist/learning/reasoning-trace.d.ts +36 -1
- package/dist/learning/reasoning-trace.d.ts.map +1 -1
- package/dist/learning/reasoning-trace.js +36 -2
- package/dist/learning/reasoning-trace.js.map +1 -1
- package/dist/learning/resilient-call.d.ts +36 -1
- package/dist/learning/resilient-call.d.ts.map +1 -1
- package/dist/learning/resilient-call.js +80 -5
- package/dist/learning/resilient-call.js.map +1 -1
- package/dist/learning/unattended-job.d.ts +293 -0
- package/dist/learning/unattended-job.d.ts.map +1 -0
- package/dist/learning/unattended-job.js +544 -0
- package/dist/learning/unattended-job.js.map +1 -0
- package/dist/learning/unattended-progress.d.ts +95 -0
- package/dist/learning/unattended-progress.d.ts.map +1 -0
- package/dist/learning/unattended-progress.js +147 -0
- package/dist/learning/unattended-progress.js.map +1 -0
- package/dist/learning/working-state.d.ts +109 -0
- package/dist/learning/working-state.d.ts.map +1 -0
- package/dist/learning/working-state.js +244 -0
- package/dist/learning/working-state.js.map +1 -0
- package/dist/nlu/conversation-gate.d.ts +24 -0
- package/dist/nlu/conversation-gate.d.ts.map +1 -1
- package/dist/nlu/conversation-gate.js +47 -3
- package/dist/nlu/conversation-gate.js.map +1 -1
- package/dist/tools/coding-tools.d.ts.map +1 -1
- package/dist/tools/coding-tools.js +95 -19
- package/dist/tools/coding-tools.js.map +1 -1
- package/dist/tools/edit-verification.d.ts +125 -0
- package/dist/tools/edit-verification.d.ts.map +1 -0
- package/dist/tools/edit-verification.js +237 -0
- package/dist/tools/edit-verification.js.map +1 -0
- package/dist/tools/git-tool.d.ts.map +1 -1
- package/dist/tools/git-tool.js +37 -4
- package/dist/tools/git-tool.js.map +1 -1
- package/dist/tools/registry.d.ts +30 -2
- package/dist/tools/registry.d.ts.map +1 -1
- package/dist/tools/registry.js +40 -11
- package/dist/tools/registry.js.map +1 -1
- package/dist/tools/run-cli.d.ts.map +1 -1
- package/dist/tools/run-cli.js +40 -13
- package/dist/tools/run-cli.js.map +1 -1
- package/dist/tools/run-terminal.d.ts +6 -1
- package/dist/tools/run-terminal.d.ts.map +1 -1
- package/dist/tools/run-terminal.js +158 -18
- package/dist/tools/run-terminal.js.map +1 -1
- package/dist/tools/tool-loop.d.ts +35 -0
- package/dist/tools/tool-loop.d.ts.map +1 -1
- package/dist/tools/tool-loop.js +141 -1
- package/dist/tools/tool-loop.js.map +1 -1
- package/dist/web-dashboard/chat-console.d.ts +6 -0
- package/dist/web-dashboard/chat-console.d.ts.map +1 -1
- package/dist/web-dashboard/chat-console.js.map +1 -1
- package/dist/web-dashboard/chat-retry.d.ts.map +1 -1
- package/dist/web-dashboard/chat-retry.js +10 -2
- package/dist/web-dashboard/chat-retry.js.map +1 -1
- package/dist/web-dashboard/server.d.ts.map +1 -1
- package/dist/web-dashboard/server.js +80 -8
- package/dist/web-dashboard/server.js.map +1 -1
- package/dist/web-dashboard/src/types.d.ts +81 -4
- package/dist/web-dashboard/src/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/web-dashboard/public/assets/{index-Co7Hk2FT.js → index-kCUkORm7.js} +2 -2
- package/src/web-dashboard/public/assets/{index-Co7Hk2FT.js.map → index-kCUkORm7.js.map} +1 -1
- package/src/web-dashboard/public/index.html +1 -1
|
@@ -131,7 +131,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
131
131
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ane(e,t){if(e){if(typeof e=="string")return IE(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return IE(e,t)}}function IE(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function sne(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,a,o,l=[],c=!0,u=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,i=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw i}}return l}}function one(e){if(Array.isArray(e))return e}function Ov(){return Ov=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Ov.apply(this,arguments)}var lne=function(t,n){var r;return W.isValidElement(t)?r=W.cloneElement(t,n):$e(t)?r=t(n):r=W.createElement("line",Ov({},n,{className:"recharts-reference-line-line"})),r},cne=function(t,n,r,i,a,o,l,c,u){var d=a.x,f=a.y,h=a.width,p=a.height;if(r){var g=u.y,m=t.y.apply(g,{position:o});if(Gr(u,"discard")&&!t.y.isInRange(m))return null;var v=[{x:d+h,y:m},{x:d,y:m}];return c==="left"?v.reverse():v}if(n){var y=u.x,b=t.x.apply(y,{position:o});if(Gr(u,"discard")&&!t.x.isInRange(b))return null;var x=[{x:b,y:f+p},{x:b,y:f}];return l==="top"?x.reverse():x}if(i){var k=u.segment,S=k.map(function(w){return t.apply(w,{position:o})});return Gr(u,"discard")&&Pee(S,function(w){return!t.isInRange(w)})?null:S}return null};function une(e){var t=e.x,n=e.y,r=e.segment,i=e.xAxisId,a=e.yAxisId,o=e.shape,l=e.className,c=e.alwaysShow,u=Hte(),d=EP(i),f=_P(a),h=Kte();if(!u||!h)return null;di(c===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.');var p=t0({x:d.scale,y:f.scale}),g=Ut(t),m=Ut(n),v=r&&r.length===2,y=cne(p,g,m,v,h,e.position,d.orientation,f.orientation,e);if(!y)return null;var b=rne(y,2),x=b[0],k=x.x,S=x.y,w=b[1],_=w.x,N=w.y,C=Gr(e,"hidden")?"url(#".concat(u,")"):void 0,T=RE(RE({clipPath:C},qe(e,!0)),{},{x1:k,y1:S,x2:_,y2:N});return W.createElement(Yt,{className:Ke("recharts-reference-line",l)},lne(o,T),mn.renderCallByParent(e,wte({x1:k,y1:S,x2:_,y2:N})))}var o0=function(e){function t(){return Yte(this,t),Qte(this,t,arguments)}return tne(t,e),Zte(t,[{key:"render",value:function(){return W.createElement(une,this.props)}}])}(W.Component);s0(o0,"displayName","ReferenceLine");s0(o0,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,fill:"none",stroke:"#ccc",fillOpacity:1,strokeWidth:1,position:"middle"});function Pv(){return Pv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Pv.apply(this,arguments)}function Ro(e){"@babel/helpers - typeof";return Ro=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ro(e)}function $E(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function LE(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?$E(Object(n),!0).forEach(function(r){Ap(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$E(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function dne(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function fne(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,TP(r.key),r)}}function hne(e,t,n){return t&&fne(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function pne(e,t,n){return t=ch(t),mne(e,AP()?Reflect.construct(t,n||[],ch(e).constructor):t.apply(e,n))}function mne(e,t){if(t&&(Ro(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return gne(e)}function gne(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function AP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(AP=function(){return!!e})()}function ch(e){return ch=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},ch(e)}function yne(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Mv(e,t)}function Mv(e,t){return Mv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,i){return r.__proto__=i,r},Mv(e,t)}function Ap(e,t,n){return t=TP(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function TP(e){var t=vne(e,"string");return Ro(t)=="symbol"?t:t+""}function vne(e,t){if(Ro(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Ro(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var bne=function(t){var n=t.x,r=t.y,i=t.xAxis,a=t.yAxis,o=t0({x:i.scale,y:a.scale}),l=o.apply({x:n,y:r},{bandAware:!0});return Gr(t,"discard")&&!o.isInRange(l)?null:l},Tp=function(e){function t(){return dne(this,t),pne(this,t,arguments)}return yne(t,e),hne(t,[{key:"render",value:function(){var r=this.props,i=r.x,a=r.y,o=r.r,l=r.alwaysShow,c=r.clipPathId,u=Ut(i),d=Ut(a);if(di(l===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.'),!u||!d)return null;var f=bne(this.props);if(!f)return null;var h=f.x,p=f.y,g=this.props,m=g.shape,v=g.className,y=Gr(this.props,"hidden")?"url(#".concat(c,")"):void 0,b=LE(LE({clipPath:y},qe(this.props,!0)),{},{cx:h,cy:p});return W.createElement(Yt,{className:Ke("recharts-reference-dot",v)},t.renderDot(m,b),mn.renderCallByParent(this.props,{x:h-o,y:p-o,width:2*o,height:2*o}))}}])}(W.Component);Ap(Tp,"displayName","ReferenceDot");Ap(Tp,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,r:10,fill:"#fff",stroke:"#ccc",fillOpacity:1,strokeWidth:1});Ap(Tp,"renderDot",function(e,t){var n;return W.isValidElement(e)?n=W.cloneElement(e,t):$e(e)?n=e(t):n=W.createElement(sP,Pv({},t,{cx:t.cx,cy:t.cy,className:"recharts-reference-dot-dot"})),n});function Rv(){return Rv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Rv.apply(this,arguments)}function Io(e){"@babel/helpers - typeof";return Io=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Io(e)}function DE(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function BE(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?DE(Object(n),!0).forEach(function(r){Cp(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):DE(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function xne(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function wne(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,OP(r.key),r)}}function Sne(e,t,n){return t&&wne(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function kne(e,t,n){return t=uh(t),Ene(e,CP()?Reflect.construct(t,n||[],uh(e).constructor):t.apply(e,n))}function Ene(e,t){if(t&&(Io(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _ne(e)}function _ne(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function CP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(CP=function(){return!!e})()}function uh(e){return uh=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},uh(e)}function Nne(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Iv(e,t)}function Iv(e,t){return Iv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,i){return r.__proto__=i,r},Iv(e,t)}function Cp(e,t,n){return t=OP(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function OP(e){var t=jne(e,"string");return Io(t)=="symbol"?t:t+""}function jne(e,t){if(Io(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Io(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var Ane=function(t,n,r,i,a){var o=a.x1,l=a.x2,c=a.y1,u=a.y2,d=a.xAxis,f=a.yAxis;if(!d||!f)return null;var h=t0({x:d.scale,y:f.scale}),p={x:t?h.x.apply(o,{position:"start"}):h.x.rangeMin,y:r?h.y.apply(c,{position:"start"}):h.y.rangeMin},g={x:n?h.x.apply(l,{position:"end"}):h.x.rangeMax,y:i?h.y.apply(u,{position:"end"}):h.y.rangeMax};return Gr(a,"discard")&&(!h.isInRange(p)||!h.isInRange(g))?null:yP(p,g)},Op=function(e){function t(){return xne(this,t),kne(this,t,arguments)}return Nne(t,e),Sne(t,[{key:"render",value:function(){var r=this.props,i=r.x1,a=r.x2,o=r.y1,l=r.y2,c=r.className,u=r.alwaysShow,d=r.clipPathId;di(u===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.');var f=Ut(i),h=Ut(a),p=Ut(o),g=Ut(l),m=this.props.shape;if(!f&&!h&&!p&&!g&&!m)return null;var v=Ane(f,h,p,g,this.props);if(!v&&!m)return null;var y=Gr(this.props,"hidden")?"url(#".concat(d,")"):void 0;return W.createElement(Yt,{className:Ke("recharts-reference-area",c)},t.renderRect(m,BE(BE({clipPath:y},qe(this.props,!0)),v)),mn.renderCallByParent(this.props,v))}}])}(W.Component);Cp(Op,"displayName","ReferenceArea");Cp(Op,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,r:10,fill:"#ccc",fillOpacity:.5,stroke:"none",strokeWidth:1});Cp(Op,"renderRect",function(e,t){var n;return W.isValidElement(e)?n=W.cloneElement(e,t):$e(e)?n=e(t):n=W.createElement(e0,Rv({},t,{className:"recharts-reference-area-rect"})),n});function PP(e,t,n){if(t<1)return[];if(t===1&&n===void 0)return e;for(var r=[],i=0;i<e.length;i+=t)r.push(e[i]);return r}function Tne(e,t,n){var r={width:e.width+t.width,height:e.height+t.height};return kte(r,n)}function Cne(e,t,n){var r=n==="width",i=e.x,a=e.y,o=e.width,l=e.height;return t===1?{start:r?i:a,end:r?i+o:a+l}:{start:r?i+o:a+l,end:r?i:a}}function dh(e,t,n,r,i){if(e*t<e*r||e*t>e*i)return!1;var a=n();return e*(t-e*a/2-r)>=0&&e*(t+e*a/2-i)<=0}function One(e,t){return PP(e,t+1)}function Pne(e,t,n,r,i){for(var a=(r||[]).slice(),o=t.start,l=t.end,c=0,u=1,d=o,f=function(){var g=r==null?void 0:r[c];if(g===void 0)return{v:PP(r,u)};var m=c,v,y=function(){return v===void 0&&(v=n(g,m)),v},b=g.coordinate,x=c===0||dh(e,b,y,d,l);x||(c=0,d=o,u+=1),x&&(d=b+e*(y()/2+i),c+=u)},h;u<=a.length;)if(h=f(),h)return h.v;return[]}function su(e){"@babel/helpers - typeof";return su=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},su(e)}function zE(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function dn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?zE(Object(n),!0).forEach(function(r){Mne(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):zE(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Mne(e,t,n){return t=Rne(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Rne(e){var t=Ine(e,"string");return su(t)=="symbol"?t:t+""}function Ine(e,t){if(su(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(su(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function $ne(e,t,n,r,i){for(var a=(r||[]).slice(),o=a.length,l=t.start,c=t.end,u=function(h){var p=a[h],g,m=function(){return g===void 0&&(g=n(p,h)),g};if(h===o-1){var v=e*(p.coordinate+e*m()/2-c);a[h]=p=dn(dn({},p),{},{tickCoord:v>0?p.coordinate-v*e:p.coordinate})}else a[h]=p=dn(dn({},p),{},{tickCoord:p.coordinate});var y=dh(e,p.tickCoord,m,l,c);y&&(c=p.tickCoord-e*(m()/2+i),a[h]=dn(dn({},p),{},{isShow:!0}))},d=o-1;d>=0;d--)u(d);return a}function Lne(e,t,n,r,i,a){var o=(r||[]).slice(),l=o.length,c=t.start,u=t.end;if(a){var d=r[l-1],f=n(d,l-1),h=e*(d.coordinate+e*f/2-u);o[l-1]=d=dn(dn({},d),{},{tickCoord:h>0?d.coordinate-h*e:d.coordinate});var p=dh(e,d.tickCoord,function(){return f},c,u);p&&(u=d.tickCoord-e*(f/2+i),o[l-1]=dn(dn({},d),{},{isShow:!0}))}for(var g=a?l-1:l,m=function(b){var x=o[b],k,S=function(){return k===void 0&&(k=n(x,b)),k};if(b===0){var w=e*(x.coordinate-e*S()/2-c);o[b]=x=dn(dn({},x),{},{tickCoord:w<0?x.coordinate-w*e:x.coordinate})}else o[b]=x=dn(dn({},x),{},{tickCoord:x.coordinate});var _=dh(e,x.tickCoord,S,c,u);_&&(c=x.tickCoord+e*(S()/2+i),o[b]=dn(dn({},x),{},{isShow:!0}))},v=0;v<g;v++)m(v);return o}function l0(e,t,n){var r=e.tick,i=e.ticks,a=e.viewBox,o=e.minTickGap,l=e.orientation,c=e.interval,u=e.tickFormatter,d=e.unit,f=e.angle;if(!i||!i.length||!r)return[];if(ue(c)||wu.isSsr)return One(i,typeof c=="number"&&ue(c)?c:0);var h=[],p=l==="top"||l==="bottom"?"width":"height",g=d&&p==="width"?ec(d,{fontSize:t,letterSpacing:n}):{width:0,height:0},m=function(x,k){var S=$e(u)?u(x.value,k):x.value;return p==="width"?Tne(ec(S,{fontSize:t,letterSpacing:n}),g,f):ec(S,{fontSize:t,letterSpacing:n})[p]},v=i.length>=2?Sr(i[1].coordinate-i[0].coordinate):1,y=Cne(a,v,p);return c==="equidistantPreserveStart"?Pne(v,y,m,i,o):(c==="preserveStart"||c==="preserveStartEnd"?h=Lne(v,y,m,i,o,c==="preserveStartEnd"):h=$ne(v,y,m,i,o),h.filter(function(b){return b.isShow}))}var Dne=["viewBox"],Bne=["viewBox"],zne=["ticks"];function $o(e){"@babel/helpers - typeof";return $o=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$o(e)}function Qs(){return Qs=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Qs.apply(this,arguments)}function FE(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function Dt(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?FE(Object(n),!0).forEach(function(r){c0(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):FE(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Km(e,t){if(e==null)return{};var n=Fne(e,t),r,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)r=a[i],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function Fne(e,t){if(e==null)return{};var n={};for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){if(t.indexOf(r)>=0)continue;n[r]=e[r]}return n}function Une(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function UE(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,RP(r.key),r)}}function Wne(e,t,n){return t&&UE(e.prototype,t),n&&UE(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function Hne(e,t,n){return t=fh(t),Gne(e,MP()?Reflect.construct(t,n||[],fh(e).constructor):t.apply(e,n))}function Gne(e,t){if(t&&($o(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return qne(e)}function qne(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function MP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(MP=function(){return!!e})()}function fh(e){return fh=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},fh(e)}function Kne(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&$v(e,t)}function $v(e,t){return $v=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,i){return r.__proto__=i,r},$v(e,t)}function c0(e,t,n){return t=RP(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function RP(e){var t=Vne(e,"string");return $o(t)=="symbol"?t:t+""}function Vne(e,t){if($o(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if($o(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var sl=function(e){function t(n){var r;return Une(this,t),r=Hne(this,t,[n]),r.state={fontSize:"",letterSpacing:""},r}return Kne(t,e),Wne(t,[{key:"shouldComponentUpdate",value:function(r,i){var a=r.viewBox,o=Km(r,Dne),l=this.props,c=l.viewBox,u=Km(l,Bne);return!oo(a,c)||!oo(o,u)||!oo(i,this.state)}},{key:"componentDidMount",value:function(){var r=this.layerReference;if(r){var i=r.getElementsByClassName("recharts-cartesian-axis-tick-value")[0];i&&this.setState({fontSize:window.getComputedStyle(i).fontSize,letterSpacing:window.getComputedStyle(i).letterSpacing})}}},{key:"getTickLineCoord",value:function(r){var i=this.props,a=i.x,o=i.y,l=i.width,c=i.height,u=i.orientation,d=i.tickSize,f=i.mirror,h=i.tickMargin,p,g,m,v,y,b,x=f?-1:1,k=r.tickSize||d,S=ue(r.tickCoord)?r.tickCoord:r.coordinate;switch(u){case"top":p=g=r.coordinate,v=o+ +!f*c,m=v-x*k,b=m-x*h,y=S;break;case"left":m=v=r.coordinate,g=a+ +!f*l,p=g-x*k,y=p-x*h,b=S;break;case"right":m=v=r.coordinate,g=a+ +f*l,p=g+x*k,y=p+x*h,b=S;break;default:p=g=r.coordinate,v=o+ +f*c,m=v+x*k,b=m+x*h,y=S;break}return{line:{x1:p,y1:m,x2:g,y2:v},tick:{x:y,y:b}}}},{key:"getTickTextAnchor",value:function(){var r=this.props,i=r.orientation,a=r.mirror,o;switch(i){case"left":o=a?"start":"end";break;case"right":o=a?"end":"start";break;default:o="middle";break}return o}},{key:"getTickVerticalAnchor",value:function(){var r=this.props,i=r.orientation,a=r.mirror,o="end";switch(i){case"left":case"right":o="middle";break;case"top":o=a?"start":"end";break;default:o=a?"end":"start";break}return o}},{key:"renderAxisLine",value:function(){var r=this.props,i=r.x,a=r.y,o=r.width,l=r.height,c=r.orientation,u=r.mirror,d=r.axisLine,f=Dt(Dt(Dt({},qe(this.props,!1)),qe(d,!1)),{},{fill:"none"});if(c==="top"||c==="bottom"){var h=+(c==="top"&&!u||c==="bottom"&&u);f=Dt(Dt({},f),{},{x1:i,y1:a+h*l,x2:i+o,y2:a+h*l})}else{var p=+(c==="left"&&!u||c==="right"&&u);f=Dt(Dt({},f),{},{x1:i+p*o,y1:a,x2:i+p*o,y2:a+l})}return W.createElement("line",Qs({},f,{className:Ke("recharts-cartesian-axis-line",or(d,"className"))}))}},{key:"renderTicks",value:function(r,i,a){var o=this,l=this.props,c=l.tickLine,u=l.stroke,d=l.tick,f=l.tickFormatter,h=l.unit,p=l0(Dt(Dt({},this.props),{},{ticks:r}),i,a),g=this.getTickTextAnchor(),m=this.getTickVerticalAnchor(),v=qe(this.props,!1),y=qe(d,!1),b=Dt(Dt({},v),{},{fill:"none"},qe(c,!1)),x=p.map(function(k,S){var w=o.getTickLineCoord(k),_=w.line,N=w.tick,C=Dt(Dt(Dt(Dt({textAnchor:g,verticalAnchor:m},v),{},{stroke:"none",fill:u},y),N),{},{index:S,payload:k,visibleTicksCount:p.length,tickFormatter:f});return W.createElement(Yt,Qs({className:"recharts-cartesian-axis-tick",key:"tick-".concat(k.value,"-").concat(k.coordinate,"-").concat(k.tickCoord)},vf(o.props,k,S)),c&&W.createElement("line",Qs({},b,_,{className:Ke("recharts-cartesian-axis-tick-line",or(c,"className"))})),d&&t.renderTickItem(d,C,"".concat($e(f)?f(k.value,S):k.value).concat(h||"")))});return W.createElement("g",{className:"recharts-cartesian-axis-ticks"},x)}},{key:"render",value:function(){var r=this,i=this.props,a=i.axisLine,o=i.width,l=i.height,c=i.ticksGenerator,u=i.className,d=i.hide;if(d)return null;var f=this.props,h=f.ticks,p=Km(f,zne),g=h;return $e(c)&&(g=h&&h.length>0?c(this.props):c(p)),o<=0||l<=0||!g||!g.length?null:W.createElement(Yt,{className:Ke("recharts-cartesian-axis",u),ref:function(v){r.layerReference=v}},a&&this.renderAxisLine(),this.renderTicks(g,this.state.fontSize,this.state.letterSpacing),mn.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(r,i,a){var o,l=Ke(i.className,"recharts-cartesian-axis-tick-value");return W.isValidElement(r)?o=W.cloneElement(r,Dt(Dt({},i),{},{className:l})):$e(r)?o=r(Dt(Dt({},i),{},{className:l})):o=W.createElement(Pf,Qs({},i,{className:"recharts-cartesian-axis-tick-value"}),a),o}}])}(E.Component);c0(sl,"displayName","CartesianAxis");c0(sl,"defaultProps",{x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:"bottom",ticks:[],stroke:"#666",tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:"preserveEnd"});var Yne=["x1","y1","x2","y2","key"],Xne=["offset"];function ss(e){"@babel/helpers - typeof";return ss=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ss(e)}function WE(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function gn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?WE(Object(n),!0).forEach(function(r){Zne(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):WE(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Zne(e,t,n){return t=Qne(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Qne(e){var t=Jne(e,"string");return ss(t)=="symbol"?t:t+""}function Jne(e,t){if(ss(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(ss(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Fa(){return Fa=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Fa.apply(this,arguments)}function HE(e,t){if(e==null)return{};var n=ere(e,t),r,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)r=a[i],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function ere(e,t){if(e==null)return{};var n={};for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){if(t.indexOf(r)>=0)continue;n[r]=e[r]}return n}var tre=function(t){var n=t.fill;if(!n||n==="none")return null;var r=t.fillOpacity,i=t.x,a=t.y,o=t.width,l=t.height,c=t.ry;return W.createElement("rect",{x:i,y:a,ry:c,width:o,height:l,stroke:"none",fill:n,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function IP(e,t){var n;if(W.isValidElement(e))n=W.cloneElement(e,t);else if($e(e))n=e(t);else{var r=t.x1,i=t.y1,a=t.x2,o=t.y2,l=t.key,c=HE(t,Yne),u=qe(c,!1);u.offset;var d=HE(u,Xne);n=W.createElement("line",Fa({},d,{x1:r,y1:i,x2:a,y2:o,fill:"none",key:l}))}return n}function nre(e){var t=e.x,n=e.width,r=e.horizontal,i=r===void 0?!0:r,a=e.horizontalPoints;if(!i||!a||!a.length)return null;var o=a.map(function(l,c){var u=gn(gn({},e),{},{x1:t,y1:l,x2:t+n,y2:l,key:"line-".concat(c),index:c});return IP(i,u)});return W.createElement("g",{className:"recharts-cartesian-grid-horizontal"},o)}function rre(e){var t=e.y,n=e.height,r=e.vertical,i=r===void 0?!0:r,a=e.verticalPoints;if(!i||!a||!a.length)return null;var o=a.map(function(l,c){var u=gn(gn({},e),{},{x1:l,y1:t,x2:l,y2:t+n,key:"line-".concat(c),index:c});return IP(i,u)});return W.createElement("g",{className:"recharts-cartesian-grid-vertical"},o)}function ire(e){var t=e.horizontalFill,n=e.fillOpacity,r=e.x,i=e.y,a=e.width,o=e.height,l=e.horizontalPoints,c=e.horizontal,u=c===void 0?!0:c;if(!u||!t||!t.length)return null;var d=l.map(function(h){return Math.round(h+i-i)}).sort(function(h,p){return h-p});i!==d[0]&&d.unshift(0);var f=d.map(function(h,p){var g=!d[p+1],m=g?i+o-h:d[p+1]-h;if(m<=0)return null;var v=p%t.length;return W.createElement("rect",{key:"react-".concat(p),y:h,x:r,height:m,width:a,stroke:"none",fill:t[v],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return W.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},f)}function are(e){var t=e.vertical,n=t===void 0?!0:t,r=e.verticalFill,i=e.fillOpacity,a=e.x,o=e.y,l=e.width,c=e.height,u=e.verticalPoints;if(!n||!r||!r.length)return null;var d=u.map(function(h){return Math.round(h+a-a)}).sort(function(h,p){return h-p});a!==d[0]&&d.unshift(0);var f=d.map(function(h,p){var g=!d[p+1],m=g?a+l-h:d[p+1]-h;if(m<=0)return null;var v=p%r.length;return W.createElement("rect",{key:"react-".concat(p),x:h,y:o,width:m,height:c,stroke:"none",fill:r[v],fillOpacity:i,className:"recharts-cartesian-grid-bg"})});return W.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},f)}var sre=function(t,n){var r=t.xAxis,i=t.width,a=t.height,o=t.offset;return HO(l0(gn(gn(gn({},sl.defaultProps),r),{},{ticks:li(r,!0),viewBox:{x:0,y:0,width:i,height:a}})),o.left,o.left+o.width,n)},ore=function(t,n){var r=t.yAxis,i=t.width,a=t.height,o=t.offset;return HO(l0(gn(gn(gn({},sl.defaultProps),r),{},{ticks:li(r,!0),viewBox:{x:0,y:0,width:i,height:a}})),o.top,o.top+o.height,n)},Os={horizontal:!0,vertical:!0,stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function Wi(e){var t,n,r,i,a,o,l=i0(),c=a0(),u=Vte(),d=gn(gn({},e),{},{stroke:(t=e.stroke)!==null&&t!==void 0?t:Os.stroke,fill:(n=e.fill)!==null&&n!==void 0?n:Os.fill,horizontal:(r=e.horizontal)!==null&&r!==void 0?r:Os.horizontal,horizontalFill:(i=e.horizontalFill)!==null&&i!==void 0?i:Os.horizontalFill,vertical:(a=e.vertical)!==null&&a!==void 0?a:Os.vertical,verticalFill:(o=e.verticalFill)!==null&&o!==void 0?o:Os.verticalFill,x:ue(e.x)?e.x:u.left,y:ue(e.y)?e.y:u.top,width:ue(e.width)?e.width:u.width,height:ue(e.height)?e.height:u.height}),f=d.x,h=d.y,p=d.width,g=d.height,m=d.syncWithTicks,v=d.horizontalValues,y=d.verticalValues,b=Gte(),x=qte();if(!ue(p)||p<=0||!ue(g)||g<=0||!ue(f)||f!==+f||!ue(h)||h!==+h)return null;var k=d.verticalCoordinatesGenerator||sre,S=d.horizontalCoordinatesGenerator||ore,w=d.horizontalPoints,_=d.verticalPoints;if((!w||!w.length)&&$e(S)){var N=v&&v.length,C=S({yAxis:x?gn(gn({},x),{},{ticks:N?v:x.ticks}):void 0,width:l,height:c,offset:u},N?!0:m);di(Array.isArray(C),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(ss(C),"]")),Array.isArray(C)&&(w=C)}if((!_||!_.length)&&$e(k)){var T=y&&y.length,$=k({xAxis:b?gn(gn({},b),{},{ticks:T?y:b.ticks}):void 0,width:l,height:c,offset:u},T?!0:m);di(Array.isArray($),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(ss($),"]")),Array.isArray($)&&(_=$)}return W.createElement("g",{className:"recharts-cartesian-grid"},W.createElement(tre,{fill:d.fill,fillOpacity:d.fillOpacity,x:d.x,y:d.y,width:d.width,height:d.height,ry:d.ry}),W.createElement(nre,Fa({},d,{offset:u,horizontalPoints:w,xAxis:b,yAxis:x})),W.createElement(rre,Fa({},d,{offset:u,verticalPoints:_,xAxis:b,yAxis:x})),W.createElement(ire,Fa({},d,{horizontalPoints:w})),W.createElement(are,Fa({},d,{verticalPoints:_})))}Wi.displayName="CartesianGrid";function Lo(e){"@babel/helpers - typeof";return Lo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Lo(e)}function lre(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function cre(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,DP(r.key),r)}}function ure(e,t,n){return t&&cre(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function dre(e,t,n){return t=hh(t),fre(e,$P()?Reflect.construct(t,n||[],hh(e).constructor):t.apply(e,n))}function fre(e,t){if(t&&(Lo(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return hre(e)}function hre(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function $P(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return($P=function(){return!!e})()}function hh(e){return hh=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},hh(e)}function pre(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Lv(e,t)}function Lv(e,t){return Lv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,i){return r.__proto__=i,r},Lv(e,t)}function LP(e,t,n){return t=DP(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function DP(e){var t=mre(e,"string");return Lo(t)=="symbol"?t:t+""}function mre(e,t){if(Lo(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Lo(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}function Dv(){return Dv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Dv.apply(this,arguments)}function gre(e){var t=e.xAxisId,n=i0(),r=a0(),i=EP(t);return i==null?null:E.createElement(sl,Dv({},i,{className:Ke("recharts-".concat(i.axisType," ").concat(i.axisType),i.className),viewBox:{x:0,y:0,width:n,height:r},ticksGenerator:function(o){return li(o,!0)}}))}var Br=function(e){function t(){return lre(this,t),dre(this,t,arguments)}return pre(t,e),ure(t,[{key:"render",value:function(){return E.createElement(gre,this.props)}}])}(E.Component);LP(Br,"displayName","XAxis");LP(Br,"defaultProps",{allowDecimals:!0,hide:!1,orientation:"bottom",width:0,height:30,mirror:!1,xAxisId:0,tickCount:5,type:"category",padding:{left:0,right:0},allowDataOverflow:!1,scale:"auto",reversed:!1,allowDuplicatedCategory:!0});function Do(e){"@babel/helpers - typeof";return Do=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Do(e)}function yre(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function vre(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,FP(r.key),r)}}function bre(e,t,n){return t&&vre(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function xre(e,t,n){return t=ph(t),wre(e,BP()?Reflect.construct(t,n||[],ph(e).constructor):t.apply(e,n))}function wre(e,t){if(t&&(Do(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Sre(e)}function Sre(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function BP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(BP=function(){return!!e})()}function ph(e){return ph=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},ph(e)}function kre(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Bv(e,t)}function Bv(e,t){return Bv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,i){return r.__proto__=i,r},Bv(e,t)}function zP(e,t,n){return t=FP(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function FP(e){var t=Ere(e,"string");return Do(t)=="symbol"?t:t+""}function Ere(e,t){if(Do(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Do(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}function zv(){return zv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},zv.apply(this,arguments)}var _re=function(t){var n=t.yAxisId,r=i0(),i=a0(),a=_P(n);return a==null?null:E.createElement(sl,zv({},a,{className:Ke("recharts-".concat(a.axisType," ").concat(a.axisType),a.className),viewBox:{x:0,y:0,width:r,height:i},ticksGenerator:function(l){return li(l,!0)}}))},zr=function(e){function t(){return yre(this,t),xre(this,t,arguments)}return kre(t,e),bre(t,[{key:"render",value:function(){return E.createElement(_re,this.props)}}])}(E.Component);zP(zr,"displayName","YAxis");zP(zr,"defaultProps",{allowDuplicatedCategory:!0,allowDecimals:!0,hide:!1,orientation:"left",width:60,height:0,mirror:!1,yAxisId:0,tickCount:5,type:"number",padding:{top:0,bottom:0},allowDataOverflow:!1,scale:"auto",reversed:!1});function GE(e){return Tre(e)||Are(e)||jre(e)||Nre()}function Nre(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
132
132
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function jre(e,t){if(e){if(typeof e=="string")return Fv(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Fv(e,t)}}function Are(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Tre(e){if(Array.isArray(e))return Fv(e)}function Fv(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var Uv=function(t,n,r,i,a){var o=_r(t,o0),l=_r(t,Tp),c=[].concat(GE(o),GE(l)),u=_r(t,Op),d="".concat(i,"Id"),f=i[0],h=n;if(c.length&&(h=c.reduce(function(m,v){if(v.props[d]===r&&Gr(v.props,"extendDomain")&&ue(v.props[f])){var y=v.props[f];return[Math.min(m[0],y),Math.max(m[1],y)]}return m},h)),u.length){var p="".concat(f,"1"),g="".concat(f,"2");h=u.reduce(function(m,v){if(v.props[d]===r&&Gr(v.props,"extendDomain")&&ue(v.props[p])&&ue(v.props[g])){var y=v.props[p],b=v.props[g];return[Math.min(m[0],y,b),Math.max(m[1],y,b)]}return m},h)}return a&&a.length&&(h=a.reduce(function(m,v){return ue(v)?[Math.min(m[0],v),Math.max(m[1],v)]:m},h)),h},UP={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function i(c,u,d){this.fn=c,this.context=u,this.once=d||!1}function a(c,u,d,f,h){if(typeof d!="function")throw new TypeError("The listener must be a function");var p=new i(d,f||c,h),g=n?n+u:u;return c._events[g]?c._events[g].fn?c._events[g]=[c._events[g],p]:c._events[g].push(p):(c._events[g]=p,c._eventsCount++),c}function o(c,u){--c._eventsCount===0?c._events=new r:delete c._events[u]}function l(){this._events=new r,this._eventsCount=0}l.prototype.eventNames=function(){var u=[],d,f;if(this._eventsCount===0)return u;for(f in d=this._events)t.call(d,f)&&u.push(n?f.slice(1):f);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(d)):u},l.prototype.listeners=function(u){var d=n?n+u:u,f=this._events[d];if(!f)return[];if(f.fn)return[f.fn];for(var h=0,p=f.length,g=new Array(p);h<p;h++)g[h]=f[h].fn;return g},l.prototype.listenerCount=function(u){var d=n?n+u:u,f=this._events[d];return f?f.fn?1:f.length:0},l.prototype.emit=function(u,d,f,h,p,g){var m=n?n+u:u;if(!this._events[m])return!1;var v=this._events[m],y=arguments.length,b,x;if(v.fn){switch(v.once&&this.removeListener(u,v.fn,void 0,!0),y){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,d),!0;case 3:return v.fn.call(v.context,d,f),!0;case 4:return v.fn.call(v.context,d,f,h),!0;case 5:return v.fn.call(v.context,d,f,h,p),!0;case 6:return v.fn.call(v.context,d,f,h,p,g),!0}for(x=1,b=new Array(y-1);x<y;x++)b[x-1]=arguments[x];v.fn.apply(v.context,b)}else{var k=v.length,S;for(x=0;x<k;x++)switch(v[x].once&&this.removeListener(u,v[x].fn,void 0,!0),y){case 1:v[x].fn.call(v[x].context);break;case 2:v[x].fn.call(v[x].context,d);break;case 3:v[x].fn.call(v[x].context,d,f);break;case 4:v[x].fn.call(v[x].context,d,f,h);break;default:if(!b)for(S=1,b=new Array(y-1);S<y;S++)b[S-1]=arguments[S];v[x].fn.apply(v[x].context,b)}}return!0},l.prototype.on=function(u,d,f){return a(this,u,d,f,!1)},l.prototype.once=function(u,d,f){return a(this,u,d,f,!0)},l.prototype.removeListener=function(u,d,f,h){var p=n?n+u:u;if(!this._events[p])return this;if(!d)return o(this,p),this;var g=this._events[p];if(g.fn)g.fn===d&&(!h||g.once)&&(!f||g.context===f)&&o(this,p);else{for(var m=0,v=[],y=g.length;m<y;m++)(g[m].fn!==d||h&&!g[m].once||f&&g[m].context!==f)&&v.push(g[m]);v.length?this._events[p]=v.length===1?v[0]:v:o(this,p)}return this},l.prototype.removeAllListeners=function(u){var d;return u?(d=n?n+u:u,this._events[d]&&o(this,d)):(this._events=new r,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=n,l.EventEmitter=l,e.exports=l})(UP);var Cre=UP.exports;const Ore=Xe(Cre);var Vm=new Ore,Ym="recharts.syncMouseEvents";function ou(e){"@babel/helpers - typeof";return ou=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ou(e)}function Pre(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Mre(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,WP(r.key),r)}}function Rre(e,t,n){return t&&Mre(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Xm(e,t,n){return t=WP(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function WP(e){var t=Ire(e,"string");return ou(t)=="symbol"?t:t+""}function Ire(e,t){if(ou(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(ou(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var $re=function(){function e(){Pre(this,e),Xm(this,"activeIndex",0),Xm(this,"coordinateList",[]),Xm(this,"layout","horizontal")}return Rre(e,[{key:"setDetails",value:function(n){var r,i=n.coordinateList,a=i===void 0?null:i,o=n.container,l=o===void 0?null:o,c=n.layout,u=c===void 0?null:c,d=n.offset,f=d===void 0?null:d,h=n.mouseHandlerCallback,p=h===void 0?null:h;this.coordinateList=(r=a??this.coordinateList)!==null&&r!==void 0?r:[],this.container=l??this.container,this.layout=u??this.layout,this.offset=f??this.offset,this.mouseHandlerCallback=p??this.mouseHandlerCallback,this.activeIndex=Math.min(Math.max(this.activeIndex,0),this.coordinateList.length-1)}},{key:"focus",value:function(){this.spoofMouse()}},{key:"keyboardEvent",value:function(n){if(this.coordinateList.length!==0)switch(n.key){case"ArrowRight":{if(this.layout!=="horizontal")return;this.activeIndex=Math.min(this.activeIndex+1,this.coordinateList.length-1),this.spoofMouse();break}case"ArrowLeft":{if(this.layout!=="horizontal")return;this.activeIndex=Math.max(this.activeIndex-1,0),this.spoofMouse();break}}}},{key:"setIndex",value:function(n){this.activeIndex=n}},{key:"spoofMouse",value:function(){var n,r;if(this.layout==="horizontal"&&this.coordinateList.length!==0){var i=this.container.getBoundingClientRect(),a=i.x,o=i.y,l=i.height,c=this.coordinateList[this.activeIndex].coordinate,u=((n=window)===null||n===void 0?void 0:n.scrollX)||0,d=((r=window)===null||r===void 0?void 0:r.scrollY)||0,f=a+c+u,h=o+this.offset.top+l/2+d;this.mouseHandlerCallback({pageX:f,pageY:h})}}}])}();function Lre(e,t,n){if(n==="number"&&t===!0&&Array.isArray(e)){var r=e==null?void 0:e[0],i=e==null?void 0:e[1];if(r&&i&&ue(r)&&ue(i))return!0}return!1}function Dre(e,t,n,r){var i=r/2;return{stroke:"none",fill:"#ccc",x:e==="horizontal"?t.x-i:n.left+.5,y:e==="horizontal"?n.top+.5:t.y-i,width:e==="horizontal"?r:n.width-1,height:e==="horizontal"?n.height-1:r}}function HP(e){var t=e.cx,n=e.cy,r=e.radius,i=e.startAngle,a=e.endAngle,o=rn(t,n,r,i),l=rn(t,n,r,a);return{points:[o,l],cx:t,cy:n,radius:r,startAngle:i,endAngle:a}}function Bre(e,t,n){var r,i,a,o;if(e==="horizontal")r=t.x,a=r,i=n.top,o=n.top+n.height;else if(e==="vertical")i=t.y,o=i,r=n.left,a=n.left+n.width;else if(t.cx!=null&&t.cy!=null)if(e==="centric"){var l=t.cx,c=t.cy,u=t.innerRadius,d=t.outerRadius,f=t.angle,h=rn(l,c,u,f),p=rn(l,c,d,f);r=h.x,i=h.y,a=p.x,o=p.y}else return HP(t);return[{x:r,y:i},{x:a,y:o}]}function lu(e){"@babel/helpers - typeof";return lu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},lu(e)}function qE(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function fd(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?qE(Object(n),!0).forEach(function(r){zre(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):qE(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function zre(e,t,n){return t=Fre(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Fre(e){var t=Ure(e,"string");return lu(t)=="symbol"?t:t+""}function Ure(e,t){if(lu(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(lu(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Wre(e){var t,n,r=e.element,i=e.tooltipEventType,a=e.isActive,o=e.activeCoordinate,l=e.activePayload,c=e.offset,u=e.activeTooltipIndex,d=e.tooltipAxisBandSize,f=e.layout,h=e.chartName,p=(t=r.props.cursor)!==null&&t!==void 0?t:(n=r.type.defaultProps)===null||n===void 0?void 0:n.cursor;if(!r||!p||!a||!o||h!=="ScatterChart"&&i!=="axis")return null;var g,m=qk;if(h==="ScatterChart")g=o,m=nJ;else if(h==="BarChart")g=Dre(f,o,c,d),m=e0;else if(f==="radial"){var v=HP(o),y=v.cx,b=v.cy,x=v.radius,k=v.startAngle,S=v.endAngle;g={cx:y,cy:b,startAngle:k,endAngle:S,innerRadius:x,outerRadius:x},m=YO}else g={points:Bre(f,o,c)},m=qk;var w=fd(fd(fd(fd({stroke:"#ccc",pointerEvents:"none"},c),g),qe(p,!1)),{},{payload:l,payloadIndex:u,className:Ke("recharts-tooltip-cursor",p.className)});return E.isValidElement(p)?E.cloneElement(p,w):E.createElement(m,w)}var Hre=["item"],Gre=["children","className","width","height","style","compact","title","desc"];function Bo(e){"@babel/helpers - typeof";return Bo=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Bo(e)}function Js(){return Js=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Js.apply(this,arguments)}function KE(e,t){return Vre(e)||Kre(e,t)||qP(e,t)||qre()}function qre(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
133
133
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Kre(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,i,a,o,l=[],c=!0,u=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,i=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw i}}return l}}function Vre(e){if(Array.isArray(e))return e}function VE(e,t){if(e==null)return{};var n=Yre(e,t),r,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)r=a[i],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function Yre(e,t){if(e==null)return{};var n={};for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){if(t.indexOf(r)>=0)continue;n[r]=e[r]}return n}function Xre(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Zre(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,KP(r.key),r)}}function Qre(e,t,n){return t&&Zre(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Jre(e,t,n){return t=mh(t),eie(e,GP()?Reflect.construct(t,n||[],mh(e).constructor):t.apply(e,n))}function eie(e,t){if(t&&(Bo(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return tie(e)}function tie(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function GP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(GP=function(){return!!e})()}function mh(e){return mh=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},mh(e)}function nie(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Wv(e,t)}function Wv(e,t){return Wv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,i){return r.__proto__=i,r},Wv(e,t)}function zo(e){return aie(e)||iie(e)||qP(e)||rie()}function rie(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
134
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function qP(e,t){if(e){if(typeof e=="string")return Hv(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Hv(e,t)}}function iie(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function aie(e){if(Array.isArray(e))return Hv(e)}function Hv(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function YE(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function Q(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?YE(Object(n),!0).forEach(function(r){Ae(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):YE(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Ae(e,t,n){return t=KP(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function KP(e){var t=sie(e,"string");return Bo(t)=="symbol"?t:t+""}function sie(e,t){if(Bo(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Bo(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var oie={xAxis:["bottom","top"],yAxis:["left","right"]},lie={width:"100%",height:"100%"},VP={x:0,y:0};function hd(e){return e}var cie=function(t,n){return n==="horizontal"?t.x:n==="vertical"?t.y:n==="centric"?t.angle:t.radius},uie=function(t,n,r,i){var a=n.find(function(d){return d&&d.index===r});if(a){if(t==="horizontal")return{x:a.coordinate,y:i.y};if(t==="vertical")return{x:i.x,y:a.coordinate};if(t==="centric"){var o=a.coordinate,l=i.radius;return Q(Q(Q({},i),rn(i.cx,i.cy,l,o)),{},{angle:o,radius:l})}var c=a.coordinate,u=i.angle;return Q(Q(Q({},i),rn(i.cx,i.cy,c,u)),{},{angle:u,radius:c})}return VP},Pp=function(t,n){var r=n.graphicalItems,i=n.dataStartIndex,a=n.dataEndIndex,o=(r??[]).reduce(function(l,c){var u=c.props.data;return u&&u.length?[].concat(zo(l),zo(u)):l},[]);return o.length>0?o:t&&t.length&&ue(i)&&ue(a)?t.slice(i,a+1):[]};function YP(e){return e==="number"?[0,"auto"]:void 0}var Gv=function(t,n,r,i){var a=t.graphicalItems,o=t.tooltipAxis,l=Pp(n,t);return r<0||!a||!a.length||r>=l.length?null:a.reduce(function(c,u){var d,f=(d=u.props.data)!==null&&d!==void 0?d:n;f&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=r&&(f=f.slice(t.dataStartIndex,t.dataEndIndex+1));var h;if(o.dataKey&&!o.allowDuplicatedCategory){var p=f===void 0?l:f;h=Ey(p,o.dataKey,i)}else h=f&&f[r]||l[r];return h?[].concat(zo(c),[qO(u,h)]):c},[])},XE=function(t,n,r,i){var a=i||{x:t.chartX,y:t.chartY},o=cie(a,r),l=t.orderedTooltipTicks,c=t.tooltipAxis,u=t.tooltipTicks,d=RY(o,l,u,c);if(d>=0&&u){var f=u[d]&&u[d].value,h=Gv(t,n,d,f),p=uie(r,l,d,a);return{activeTooltipIndex:d,activeLabel:f,activePayload:h,activeCoordinate:p}}return null},die=function(t,n){var r=n.axes,i=n.graphicalItems,a=n.axisType,o=n.axisIdKey,l=n.stackGroups,c=n.dataStartIndex,u=n.dataEndIndex,d=t.layout,f=t.children,h=t.stackOffset,p=WO(d,a);return r.reduce(function(g,m){var v,y=m.type.defaultProps!==void 0?Q(Q({},m.type.defaultProps),m.props):m.props,b=y.type,x=y.dataKey,k=y.allowDataOverflow,S=y.allowDuplicatedCategory,w=y.scale,_=y.ticks,N=y.includeHidden,C=y[o];if(g[C])return g;var T=Pp(t.data,{graphicalItems:i.filter(function(K){var M,le=o in K.props?K.props[o]:(M=K.type.defaultProps)===null||M===void 0?void 0:M[o];return le===C}),dataStartIndex:c,dataEndIndex:u}),$=T.length,R,L,I;Lre(y.domain,k,b)&&(R=dv(y.domain,null,k),p&&(b==="number"||w!=="auto")&&(I=nc(T,x,"category")));var z=YP(b);if(!R||R.length===0){var D,F=(D=y.domain)!==null&&D!==void 0?D:z;if(x){if(R=nc(T,x,b),b==="category"&&p){var O=S3(R);S&&O?(L=R,R=rh(0,$)):S||(R=Mk(F,R,m).reduce(function(K,M){return K.indexOf(M)>=0?K:[].concat(zo(K),[M])},[]))}else if(b==="category")S?R=R.filter(function(K){return K!==""&&!Ve(K)}):R=Mk(F,R,m).reduce(function(K,M){return K.indexOf(M)>=0||M===""||Ve(M)?K:[].concat(zo(K),[M])},[]);else if(b==="number"){var P=BY(T,i.filter(function(K){var M,le,be=o in K.props?K.props[o]:(M=K.type.defaultProps)===null||M===void 0?void 0:M[o],me="hide"in K.props?K.props.hide:(le=K.type.defaultProps)===null||le===void 0?void 0:le.hide;return be===C&&(N||!me)}),x,a,d);P&&(R=P)}p&&(b==="number"||w!=="auto")&&(I=nc(T,x,"category"))}else p?R=rh(0,$):l&&l[C]&&l[C].hasStack&&b==="number"?R=h==="expand"?[0,1]:GO(l[C].stackGroups,c,u):R=UO(T,i.filter(function(K){var M=o in K.props?K.props[o]:K.type.defaultProps[o],le="hide"in K.props?K.props.hide:K.type.defaultProps.hide;return M===C&&(N||!le)}),b,d,!0);if(b==="number")R=Uv(f,R,C,a,_),F&&(R=dv(F,R,k));else if(b==="category"&&F){var A=F,Y=R.every(function(K){return A.indexOf(K)>=0});Y&&(R=A)}}return Q(Q({},g),{},Ae({},C,Q(Q({},y),{},{axisType:a,domain:R,categoricalDomain:I,duplicateDomain:L,originalDomain:(v=y.domain)!==null&&v!==void 0?v:z,isCategorical:p,layout:d})))},{})},fie=function(t,n){var r=n.graphicalItems,i=n.Axis,a=n.axisType,o=n.axisIdKey,l=n.stackGroups,c=n.dataStartIndex,u=n.dataEndIndex,d=t.layout,f=t.children,h=Pp(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:u}),p=h.length,g=WO(d,a),m=-1;return r.reduce(function(v,y){var b=y.type.defaultProps!==void 0?Q(Q({},y.type.defaultProps),y.props):y.props,x=b[o],k=YP("number");if(!v[x]){m++;var S;return g?S=rh(0,p):l&&l[x]&&l[x].hasStack?(S=GO(l[x].stackGroups,c,u),S=Uv(f,S,x,a)):(S=dv(k,UO(h,r.filter(function(w){var _,N,C=o in w.props?w.props[o]:(_=w.type.defaultProps)===null||_===void 0?void 0:_[o],T="hide"in w.props?w.props.hide:(N=w.type.defaultProps)===null||N===void 0?void 0:N.hide;return C===x&&!T}),"number",d),i.defaultProps.allowDataOverflow),S=Uv(f,S,x,a)),Q(Q({},v),{},Ae({},x,Q(Q({axisType:a},i.defaultProps),{},{hide:!0,orientation:or(oie,"".concat(a,".").concat(m%2),null),domain:S,originalDomain:k,isCategorical:g,layout:d})))}return v},{})},hie=function(t,n){var r=n.axisType,i=r===void 0?"xAxis":r,a=n.AxisComp,o=n.graphicalItems,l=n.stackGroups,c=n.dataStartIndex,u=n.dataEndIndex,d=t.children,f="".concat(i,"Id"),h=_r(d,a),p={};return h&&h.length?p=die(t,{axes:h,graphicalItems:o,axisType:i,axisIdKey:f,stackGroups:l,dataStartIndex:c,dataEndIndex:u}):o&&o.length&&(p=fie(t,{Axis:a,graphicalItems:o,axisType:i,axisIdKey:f,stackGroups:l,dataStartIndex:c,dataEndIndex:u})),p},pie=function(t){var n=Ui(t),r=li(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:Nx(r,function(i){return i.coordinate}),tooltipAxis:n,tooltipAxisBandSize:Kf(n,r)}},ZE=function(t){var n=t.children,r=t.defaultShowTooltip,i=Wn(n,Oo),a=0,o=0;return t.data&&t.data.length!==0&&(o=t.data.length-1),i&&i.props&&(i.props.startIndex>=0&&(a=i.props.startIndex),i.props.endIndex>=0&&(o=i.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:a,dataEndIndex:o,activeTooltipIndex:-1,isTooltipActive:!!r}},mie=function(t){return!t||!t.length?!1:t.some(function(n){var r=ui(n&&n.type);return r&&r.indexOf("Bar")>=0})},QE=function(t){return t==="horizontal"?{numericAxisName:"yAxis",cateAxisName:"xAxis"}:t==="vertical"?{numericAxisName:"xAxis",cateAxisName:"yAxis"}:t==="centric"?{numericAxisName:"radiusAxis",cateAxisName:"angleAxis"}:{numericAxisName:"angleAxis",cateAxisName:"radiusAxis"}},gie=function(t,n){var r=t.props,i=t.graphicalItems,a=t.xAxisMap,o=a===void 0?{}:a,l=t.yAxisMap,c=l===void 0?{}:l,u=r.width,d=r.height,f=r.children,h=r.margin||{},p=Wn(f,Oo),g=Wn(f,Ga),m=Object.keys(c).reduce(function(S,w){var _=c[w],N=_.orientation;return!_.mirror&&!_.hide?Q(Q({},S),{},Ae({},N,S[N]+_.width)):S},{left:h.left||0,right:h.right||0}),v=Object.keys(o).reduce(function(S,w){var _=o[w],N=_.orientation;return!_.mirror&&!_.hide?Q(Q({},S),{},Ae({},N,or(S,"".concat(N))+_.height)):S},{top:h.top||0,bottom:h.bottom||0}),y=Q(Q({},v),m),b=y.bottom;p&&(y.bottom+=p.props.height||Oo.defaultProps.height),g&&n&&(y=LY(y,i,r,n));var x=u-y.left-y.right,k=d-y.top-y.bottom;return Q(Q({brushBottom:b},y),{},{width:Math.max(x,0),height:Math.max(k,0)})},yie=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},vie=function(t){var n=t.chartName,r=t.GraphicalChild,i=t.defaultTooltipEventType,a=i===void 0?"axis":i,o=t.validateTooltipEventTypes,l=o===void 0?["axis"]:o,c=t.axisComponents,u=t.legendContent,d=t.formatAxisMap,f=t.defaultProps,h=function(y,b){var x=b.graphicalItems,k=b.stackGroups,S=b.offset,w=b.updateId,_=b.dataStartIndex,N=b.dataEndIndex,C=y.barSize,T=y.layout,$=y.barGap,R=y.barCategoryGap,L=y.maxBarSize,I=QE(T),z=I.numericAxisName,D=I.cateAxisName,F=mie(x),O=[];return x.forEach(function(P,A){var Y=Pp(y.data,{graphicalItems:[P],dataStartIndex:_,dataEndIndex:N}),K=P.type.defaultProps!==void 0?Q(Q({},P.type.defaultProps),P.props):P.props,M=K.dataKey,le=K.maxBarSize,be=K["".concat(z,"Id")],me=K["".concat(D,"Id")],Pe={},H=c.reduce(function(Oe,Ze){var Me=b["".concat(Ze.axisType,"Map")],Qt=K["".concat(Ze.axisType,"Id")];Me&&Me[Qt]||Ze.axisType==="zAxis"||as();var $t=Me[Qt];return Q(Q({},Oe),{},Ae(Ae({},Ze.axisType,$t),"".concat(Ze.axisType,"Ticks"),li($t)))},Pe),X=H[D],oe=H["".concat(D,"Ticks")],ce=k&&k[be]&&k[be].hasStack&&ZY(P,k[be].stackGroups),Z=ui(P.type).indexOf("Bar")>=0,_e=Kf(X,oe),we=[],Ne=F&&IY({barSize:C,stackGroups:k,totalSize:yie(H,D)});if(Z){var ge,Be,pe=Ve(le)?L:le,Ct=(ge=(Be=Kf(X,oe,!0))!==null&&Be!==void 0?Be:pe)!==null&&ge!==void 0?ge:0;we=$Y({barGap:$,barCategoryGap:R,bandSize:Ct!==_e?Ct:_e,sizeList:Ne[me],maxBarSize:pe}),Ct!==_e&&(we=we.map(function(Oe){return Q(Q({},Oe),{},{position:Q(Q({},Oe.position),{},{offset:Oe.position.offset-Ct/2})})}))}var We=P&&P.type&&P.type.getComposedData;We&&O.push({props:Q(Q({},We(Q(Q({},H),{},{displayedData:Y,props:y,dataKey:M,item:P,bandSize:_e,barPosition:we,offset:S,stackedData:ce,layout:T,dataStartIndex:_,dataEndIndex:N}))),{},Ae(Ae(Ae({key:P.key||"item-".concat(A)},z,H[z]),D,H[D]),"animationId",w)),childIndex:R3(P,y.children),item:P})}),O},p=function(y,b){var x=y.props,k=y.dataStartIndex,S=y.dataEndIndex,w=y.updateId;if(!j1({props:x}))return null;var _=x.children,N=x.layout,C=x.stackOffset,T=x.data,$=x.reverseStackOrder,R=QE(N),L=R.numericAxisName,I=R.cateAxisName,z=_r(_,r),D=VY(T,z,"".concat(L,"Id"),"".concat(I,"Id"),C,$),F=c.reduce(function(K,M){var le="".concat(M.axisType,"Map");return Q(Q({},K),{},Ae({},le,hie(x,Q(Q({},M),{},{graphicalItems:z,stackGroups:M.axisType===L&&D,dataStartIndex:k,dataEndIndex:S}))))},{}),O=gie(Q(Q({},F),{},{props:x,graphicalItems:z}),b==null?void 0:b.legendBBox);Object.keys(F).forEach(function(K){F[K]=d(x,F[K],O,K.replace("Map",""),n)});var P=F["".concat(I,"Map")],A=pie(P),Y=h(x,Q(Q({},F),{},{dataStartIndex:k,dataEndIndex:S,updateId:w,graphicalItems:z,stackGroups:D,offset:O}));return Q(Q({formattedGraphicalItems:Y,graphicalItems:z,offset:O,stackGroups:D},A),F)},g=function(v){function y(b){var x,k,S;return Xre(this,y),S=Jre(this,y,[b]),Ae(S,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),Ae(S,"accessibilityManager",new $re),Ae(S,"handleLegendBBoxUpdate",function(w){if(w){var _=S.state,N=_.dataStartIndex,C=_.dataEndIndex,T=_.updateId;S.setState(Q({legendBBox:w},p({props:S.props,dataStartIndex:N,dataEndIndex:C,updateId:T},Q(Q({},S.state),{},{legendBBox:w}))))}}),Ae(S,"handleReceiveSyncEvent",function(w,_,N){if(S.props.syncId===w){if(N===S.eventEmitterSymbol&&typeof S.props.syncMethod!="function")return;S.applySyncEvent(_)}}),Ae(S,"handleBrushChange",function(w){var _=w.startIndex,N=w.endIndex;if(_!==S.state.dataStartIndex||N!==S.state.dataEndIndex){var C=S.state.updateId;S.setState(function(){return Q({dataStartIndex:_,dataEndIndex:N},p({props:S.props,dataStartIndex:_,dataEndIndex:N,updateId:C},S.state))}),S.triggerSyncEvent({dataStartIndex:_,dataEndIndex:N})}}),Ae(S,"handleMouseEnter",function(w){var _=S.getMouseInfo(w);if(_){var N=Q(Q({},_),{},{isTooltipActive:!0});S.setState(N),S.triggerSyncEvent(N);var C=S.props.onMouseEnter;$e(C)&&C(N,w)}}),Ae(S,"triggeredAfterMouseMove",function(w){var _=S.getMouseInfo(w),N=_?Q(Q({},_),{},{isTooltipActive:!0}):{isTooltipActive:!1};S.setState(N),S.triggerSyncEvent(N);var C=S.props.onMouseMove;$e(C)&&C(N,w)}),Ae(S,"handleItemMouseEnter",function(w){S.setState(function(){return{isTooltipActive:!0,activeItem:w,activePayload:w.tooltipPayload,activeCoordinate:w.tooltipPosition||{x:w.cx,y:w.cy}}})}),Ae(S,"handleItemMouseLeave",function(){S.setState(function(){return{isTooltipActive:!1}})}),Ae(S,"handleMouseMove",function(w){w.persist(),S.throttleTriggeredAfterMouseMove(w)}),Ae(S,"handleMouseLeave",function(w){S.throttleTriggeredAfterMouseMove.cancel();var _={isTooltipActive:!1};S.setState(_),S.triggerSyncEvent(_);var N=S.props.onMouseLeave;$e(N)&&N(_,w)}),Ae(S,"handleOuterEvent",function(w){var _=M3(w),N=or(S.props,"".concat(_));if(_&&$e(N)){var C,T;/.*touch.*/i.test(_)?T=S.getMouseInfo(w.changedTouches[0]):T=S.getMouseInfo(w),N((C=T)!==null&&C!==void 0?C:{},w)}}),Ae(S,"handleClick",function(w){var _=S.getMouseInfo(w);if(_){var N=Q(Q({},_),{},{isTooltipActive:!0});S.setState(N),S.triggerSyncEvent(N);var C=S.props.onClick;$e(C)&&C(N,w)}}),Ae(S,"handleMouseDown",function(w){var _=S.props.onMouseDown;if($e(_)){var N=S.getMouseInfo(w);_(N,w)}}),Ae(S,"handleMouseUp",function(w){var _=S.props.onMouseUp;if($e(_)){var N=S.getMouseInfo(w);_(N,w)}}),Ae(S,"handleTouchMove",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&S.throttleTriggeredAfterMouseMove(w.changedTouches[0])}),Ae(S,"handleTouchStart",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&S.handleMouseDown(w.changedTouches[0])}),Ae(S,"handleTouchEnd",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&S.handleMouseUp(w.changedTouches[0])}),Ae(S,"handleDoubleClick",function(w){var _=S.props.onDoubleClick;if($e(_)){var N=S.getMouseInfo(w);_(N,w)}}),Ae(S,"handleContextMenu",function(w){var _=S.props.onContextMenu;if($e(_)){var N=S.getMouseInfo(w);_(N,w)}}),Ae(S,"triggerSyncEvent",function(w){S.props.syncId!==void 0&&Vm.emit(Ym,S.props.syncId,w,S.eventEmitterSymbol)}),Ae(S,"applySyncEvent",function(w){var _=S.props,N=_.layout,C=_.syncMethod,T=S.state.updateId,$=w.dataStartIndex,R=w.dataEndIndex;if(w.dataStartIndex!==void 0||w.dataEndIndex!==void 0)S.setState(Q({dataStartIndex:$,dataEndIndex:R},p({props:S.props,dataStartIndex:$,dataEndIndex:R,updateId:T},S.state)));else if(w.activeTooltipIndex!==void 0){var L=w.chartX,I=w.chartY,z=w.activeTooltipIndex,D=S.state,F=D.offset,O=D.tooltipTicks;if(!F)return;if(typeof C=="function")z=C(O,w);else if(C==="value"){z=-1;for(var P=0;P<O.length;P++)if(O[P].value===w.activeLabel){z=P;break}}var A=Q(Q({},F),{},{x:F.left,y:F.top}),Y=Math.min(L,A.x+A.width),K=Math.min(I,A.y+A.height),M=O[z]&&O[z].value,le=Gv(S.state,S.props.data,z),be=O[z]?{x:N==="horizontal"?O[z].coordinate:Y,y:N==="horizontal"?K:O[z].coordinate}:VP;S.setState(Q(Q({},w),{},{activeLabel:M,activeCoordinate:be,activePayload:le,activeTooltipIndex:z}))}else S.setState(w)}),Ae(S,"renderCursor",function(w){var _,N=S.state,C=N.isTooltipActive,T=N.activeCoordinate,$=N.activePayload,R=N.offset,L=N.activeTooltipIndex,I=N.tooltipAxisBandSize,z=S.getTooltipEventType(),D=(_=w.props.active)!==null&&_!==void 0?_:C,F=S.props.layout,O=w.key||"_recharts-cursor";return W.createElement(Wre,{key:O,activeCoordinate:T,activePayload:$,activeTooltipIndex:L,chartName:n,element:w,isActive:D,layout:F,offset:R,tooltipAxisBandSize:I,tooltipEventType:z})}),Ae(S,"renderPolarAxis",function(w,_,N){var C=or(w,"type.axisType"),T=or(S.state,"".concat(C,"Map")),$=w.type.defaultProps,R=$!==void 0?Q(Q({},$),w.props):w.props,L=T&&T[R["".concat(C,"Id")]];return E.cloneElement(w,Q(Q({},L),{},{className:Ke(C,L.className),key:w.key||"".concat(_,"-").concat(N),ticks:li(L,!0)}))}),Ae(S,"renderPolarGrid",function(w){var _=w.props,N=_.radialLines,C=_.polarAngles,T=_.polarRadius,$=S.state,R=$.radiusAxisMap,L=$.angleAxisMap,I=Ui(R),z=Ui(L),D=z.cx,F=z.cy,O=z.innerRadius,P=z.outerRadius;return E.cloneElement(w,{polarAngles:Array.isArray(C)?C:li(z,!0).map(function(A){return A.coordinate}),polarRadius:Array.isArray(T)?T:li(I,!0).map(function(A){return A.coordinate}),cx:D,cy:F,innerRadius:O,outerRadius:P,key:w.key||"polar-grid",radialLines:N})}),Ae(S,"renderLegend",function(){var w=S.state.formattedGraphicalItems,_=S.props,N=_.children,C=_.width,T=_.height,$=S.props.margin||{},R=C-($.left||0)-($.right||0),L=zO({children:N,formattedGraphicalItems:w,legendWidth:R,legendContent:u});if(!L)return null;var I=L.item,z=VE(L,Hre);return E.cloneElement(I,Q(Q({},z),{},{chartWidth:C,chartHeight:T,margin:$,onBBoxUpdate:S.handleLegendBBoxUpdate}))}),Ae(S,"renderTooltip",function(){var w,_=S.props,N=_.children,C=_.accessibilityLayer,T=Wn(N,hn);if(!T)return null;var $=S.state,R=$.isTooltipActive,L=$.activeCoordinate,I=$.activePayload,z=$.activeLabel,D=$.offset,F=(w=T.props.active)!==null&&w!==void 0?w:R;return E.cloneElement(T,{viewBox:Q(Q({},D),{},{x:D.left,y:D.top}),active:F,label:z,payload:F?I:[],coordinate:L,accessibilityLayer:C})}),Ae(S,"renderBrush",function(w){var _=S.props,N=_.margin,C=_.data,T=S.state,$=T.offset,R=T.dataStartIndex,L=T.dataEndIndex,I=T.updateId;return E.cloneElement(w,{key:w.key||"_recharts-brush",onChange:ld(S.handleBrushChange,w.props.onChange),data:C,x:ue(w.props.x)?w.props.x:$.left,y:ue(w.props.y)?w.props.y:$.top+$.height+$.brushBottom-(N.bottom||0),width:ue(w.props.width)?w.props.width:$.width,startIndex:R,endIndex:L,updateId:"brush-".concat(I)})}),Ae(S,"renderReferenceElement",function(w,_,N){if(!w)return null;var C=S,T=C.clipPathId,$=S.state,R=$.xAxisMap,L=$.yAxisMap,I=$.offset,z=w.type.defaultProps||{},D=w.props,F=D.xAxisId,O=F===void 0?z.xAxisId:F,P=D.yAxisId,A=P===void 0?z.yAxisId:P;return E.cloneElement(w,{key:w.key||"".concat(_,"-").concat(N),xAxis:R[O],yAxis:L[A],viewBox:{x:I.left,y:I.top,width:I.width,height:I.height},clipPathId:T})}),Ae(S,"renderActivePoints",function(w){var _=w.item,N=w.activePoint,C=w.basePoint,T=w.childIndex,$=w.isRange,R=[],L=_.props.key,I=_.item.type.defaultProps!==void 0?Q(Q({},_.item.type.defaultProps),_.item.props):_.item.props,z=I.activeDot,D=I.dataKey,F=Q(Q({index:T,dataKey:D,cx:N.x,cy:N.y,r:4,fill:Jx(_.item),strokeWidth:2,stroke:"#fff",payload:N.payload,value:N.value},qe(z,!1)),yf(z));return R.push(y.renderActiveDot(z,F,"".concat(L,"-activePoint-").concat(T))),C?R.push(y.renderActiveDot(z,Q(Q({},F),{},{cx:C.x,cy:C.y}),"".concat(L,"-basePoint-").concat(T))):$&&R.push(null),R}),Ae(S,"renderGraphicChild",function(w,_,N){var C=S.filterFormatItem(w,_,N);if(!C)return null;var T=S.getTooltipEventType(),$=S.state,R=$.isTooltipActive,L=$.tooltipAxis,I=$.activeTooltipIndex,z=$.activeLabel,D=S.props.children,F=Wn(D,hn),O=C.props,P=O.points,A=O.isRange,Y=O.baseLine,K=C.item.type.defaultProps!==void 0?Q(Q({},C.item.type.defaultProps),C.item.props):C.item.props,M=K.activeDot,le=K.hide,be=K.activeBar,me=K.activeShape,Pe=!!(!le&&R&&F&&(M||be||me)),H={};T!=="axis"&&F&&F.props.trigger==="click"?H={onClick:ld(S.handleItemMouseEnter,w.props.onClick)}:T!=="axis"&&(H={onMouseLeave:ld(S.handleItemMouseLeave,w.props.onMouseLeave),onMouseEnter:ld(S.handleItemMouseEnter,w.props.onMouseEnter)});var X=E.cloneElement(w,Q(Q({},C.props),H));function oe(Ze){return typeof L.dataKey=="function"?L.dataKey(Ze.payload):null}if(Pe)if(I>=0){var ce,Z;if(L.dataKey&&!L.allowDuplicatedCategory){var _e=typeof L.dataKey=="function"?oe:"payload.".concat(L.dataKey.toString());ce=Ey(P,_e,z),Z=A&&Y&&Ey(Y,_e,z)}else ce=P==null?void 0:P[I],Z=A&&Y&&Y[I];if(me||be){var we=w.props.activeIndex!==void 0?w.props.activeIndex:I;return[E.cloneElement(w,Q(Q(Q({},C.props),H),{},{activeIndex:we})),null,null]}if(!Ve(ce))return[X].concat(zo(S.renderActivePoints({item:C,activePoint:ce,basePoint:Z,childIndex:I,isRange:A})))}else{var Ne,ge=(Ne=S.getItemByXY(S.state.activeCoordinate))!==null&&Ne!==void 0?Ne:{graphicalItem:X},Be=ge.graphicalItem,pe=Be.item,Ct=pe===void 0?w:pe,We=Be.childIndex,Oe=Q(Q(Q({},C.props),H),{},{activeIndex:We});return[E.cloneElement(Ct,Oe),null,null]}return A?[X,null,null]:[X,null]}),Ae(S,"renderCustomized",function(w,_,N){return E.cloneElement(w,Q(Q({key:"recharts-customized-".concat(N)},S.props),S.state))}),Ae(S,"renderMap",{CartesianGrid:{handler:hd,once:!0},ReferenceArea:{handler:S.renderReferenceElement},ReferenceLine:{handler:hd},ReferenceDot:{handler:S.renderReferenceElement},XAxis:{handler:hd},YAxis:{handler:hd},Brush:{handler:S.renderBrush,once:!0},Bar:{handler:S.renderGraphicChild},Line:{handler:S.renderGraphicChild},Area:{handler:S.renderGraphicChild},Radar:{handler:S.renderGraphicChild},RadialBar:{handler:S.renderGraphicChild},Scatter:{handler:S.renderGraphicChild},Pie:{handler:S.renderGraphicChild},Funnel:{handler:S.renderGraphicChild},Tooltip:{handler:S.renderCursor,once:!0},PolarGrid:{handler:S.renderPolarGrid,once:!0},PolarAngleAxis:{handler:S.renderPolarAxis},PolarRadiusAxis:{handler:S.renderPolarAxis},Customized:{handler:S.renderCustomized}}),S.clipPathId="".concat((x=b.id)!==null&&x!==void 0?x:sp("recharts"),"-clip"),S.throttleTriggeredAfterMouseMove=FC(S.triggeredAfterMouseMove,(k=b.throttleDelay)!==null&&k!==void 0?k:1e3/60),S.state={},S}return nie(y,v),Qre(y,[{key:"componentDidMount",value:function(){var x,k;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(x=this.props.margin.left)!==null&&x!==void 0?x:0,top:(k=this.props.margin.top)!==null&&k!==void 0?k:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var x=this.props,k=x.children,S=x.data,w=x.height,_=x.layout,N=Wn(k,hn);if(N){var C=N.props.defaultIndex;if(!(typeof C!="number"||C<0||C>this.state.tooltipTicks.length-1)){var T=this.state.tooltipTicks[C]&&this.state.tooltipTicks[C].value,$=Gv(this.state,S,C,T),R=this.state.tooltipTicks[C].coordinate,L=(this.state.offset.top+w)/2,I=_==="horizontal",z=I?{x:R,y:L}:{y:R,x:L},D=this.state.formattedGraphicalItems.find(function(O){var P=O.item;return P.type.name==="Scatter"});D&&(z=Q(Q({},z),D.props.points[C].tooltipPosition),$=D.props.points[C].tooltipPayload);var F={activeTooltipIndex:C,isTooltipActive:!0,activeLabel:T,activePayload:$,activeCoordinate:z};this.setState(F),this.renderCursor(N),this.accessibilityManager.setIndex(C)}}}},{key:"getSnapshotBeforeUpdate",value:function(x,k){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==k.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==x.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==x.margin){var S,w;this.accessibilityManager.setDetails({offset:{left:(S=this.props.margin.left)!==null&&S!==void 0?S:0,top:(w=this.props.margin.top)!==null&&w!==void 0?w:0}})}return null}},{key:"componentDidUpdate",value:function(x){Ny([Wn(x.children,hn)],[Wn(this.props.children,hn)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var x=Wn(this.props.children,hn);if(x&&typeof x.props.shared=="boolean"){var k=x.props.shared?"axis":"item";return l.indexOf(k)>=0?k:a}return a}},{key:"getMouseInfo",value:function(x){if(!this.container)return null;var k=this.container,S=k.getBoundingClientRect(),w=sq(S),_={chartX:Math.round(x.pageX-w.left),chartY:Math.round(x.pageY-w.top)},N=S.width/k.offsetWidth||1,C=this.inRange(_.chartX,_.chartY,N);if(!C)return null;var T=this.state,$=T.xAxisMap,R=T.yAxisMap,L=this.getTooltipEventType(),I=XE(this.state,this.props.data,this.props.layout,C);if(L!=="axis"&&$&&R){var z=Ui($).scale,D=Ui(R).scale,F=z&&z.invert?z.invert(_.chartX):null,O=D&&D.invert?D.invert(_.chartY):null;return Q(Q({},_),{},{xValue:F,yValue:O},I)}return I?Q(Q({},_),I):null}},{key:"inRange",value:function(x,k){var S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,w=this.props.layout,_=x/S,N=k/S;if(w==="horizontal"||w==="vertical"){var C=this.state.offset,T=_>=C.left&&_<=C.left+C.width&&N>=C.top&&N<=C.top+C.height;return T?{x:_,y:N}:null}var $=this.state,R=$.angleAxisMap,L=$.radiusAxisMap;if(R&&L){var I=Ui(R);return $k({x:_,y:N},I)}return null}},{key:"parseEventsOfWrapper",value:function(){var x=this.props.children,k=this.getTooltipEventType(),S=Wn(x,hn),w={};S&&k==="axis"&&(S.props.trigger==="click"?w={onClick:this.handleClick}:w={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var _=yf(this.props,this.handleOuterEvent);return Q(Q({},_),w)}},{key:"addListener",value:function(){Vm.on(Ym,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){Vm.removeListener(Ym,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(x,k,S){for(var w=this.state.formattedGraphicalItems,_=0,N=w.length;_<N;_++){var C=w[_];if(C.item===x||C.props.key===x.key||k===ui(C.item.type)&&S===C.childIndex)return C}return null}},{key:"renderClipPath",value:function(){var x=this.clipPathId,k=this.state.offset,S=k.left,w=k.top,_=k.height,N=k.width;return W.createElement("defs",null,W.createElement("clipPath",{id:x},W.createElement("rect",{x:S,y:w,height:_,width:N})))}},{key:"getXScales",value:function(){var x=this.state.xAxisMap;return x?Object.entries(x).reduce(function(k,S){var w=KE(S,2),_=w[0],N=w[1];return Q(Q({},k),{},Ae({},_,N.scale))},{}):null}},{key:"getYScales",value:function(){var x=this.state.yAxisMap;return x?Object.entries(x).reduce(function(k,S){var w=KE(S,2),_=w[0],N=w[1];return Q(Q({},k),{},Ae({},_,N.scale))},{}):null}},{key:"getXScaleByAxisId",value:function(x){var k;return(k=this.state.xAxisMap)===null||k===void 0||(k=k[x])===null||k===void 0?void 0:k.scale}},{key:"getYScaleByAxisId",value:function(x){var k;return(k=this.state.yAxisMap)===null||k===void 0||(k=k[x])===null||k===void 0?void 0:k.scale}},{key:"getItemByXY",value:function(x){var k=this.state,S=k.formattedGraphicalItems,w=k.activeItem;if(S&&S.length)for(var _=0,N=S.length;_<N;_++){var C=S[_],T=C.props,$=C.item,R=$.type.defaultProps!==void 0?Q(Q({},$.type.defaultProps),$.props):$.props,L=ui($.type);if(L==="Bar"){var I=(T.data||[]).find(function(O){return qQ(x,O)});if(I)return{graphicalItem:C,payload:I}}else if(L==="RadialBar"){var z=(T.data||[]).find(function(O){return $k(x,O)});if(z)return{graphicalItem:C,payload:z}}else if(_p(C,w)||Np(C,w)||nu(C,w)){var D=YJ({graphicalItem:C,activeTooltipItem:w,itemData:R.data}),F=R.activeIndex===void 0?D:R.activeIndex;return{graphicalItem:Q(Q({},C),{},{childIndex:F}),payload:nu(C,w)?R.data[D]:C.props.data[D]}}}return null}},{key:"render",value:function(){var x=this;if(!j1(this))return null;var k=this.props,S=k.children,w=k.className,_=k.width,N=k.height,C=k.style,T=k.compact,$=k.title,R=k.desc,L=VE(k,Gre),I=qe(L,!1);if(T)return W.createElement(PE,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},W.createElement(Ay,Js({},I,{width:_,height:N,title:$,desc:R}),this.renderClipPath(),T1(S,this.renderMap)));if(this.props.accessibilityLayer){var z,D;I.tabIndex=(z=this.props.tabIndex)!==null&&z!==void 0?z:0,I.role=(D=this.props.role)!==null&&D!==void 0?D:"application",I.onKeyDown=function(O){x.accessibilityManager.keyboardEvent(O)},I.onFocus=function(){x.accessibilityManager.focus()}}var F=this.parseEventsOfWrapper();return W.createElement(PE,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},W.createElement("div",Js({className:Ke("recharts-wrapper",w),style:Q({position:"relative",cursor:"default",width:_,height:N},C)},F,{ref:function(P){x.container=P}}),W.createElement(Ay,Js({},I,{width:_,height:N,title:$,desc:R,style:lie}),this.renderClipPath(),T1(S,this.renderMap)),this.renderLegend(),this.renderTooltip()))}}])}(E.Component);Ae(g,"displayName",n),Ae(g,"defaultProps",Q({layout:"horizontal",stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:{top:5,right:5,bottom:5,left:5},reverseStackOrder:!1,syncMethod:"index"},f)),Ae(g,"getDerivedStateFromProps",function(v,y){var b=v.dataKey,x=v.data,k=v.children,S=v.width,w=v.height,_=v.layout,N=v.stackOffset,C=v.margin,T=y.dataStartIndex,$=y.dataEndIndex;if(y.updateId===void 0){var R=ZE(v);return Q(Q(Q({},R),{},{updateId:0},p(Q(Q({props:v},R),{},{updateId:0}),y)),{},{prevDataKey:b,prevData:x,prevWidth:S,prevHeight:w,prevLayout:_,prevStackOffset:N,prevMargin:C,prevChildren:k})}if(b!==y.prevDataKey||x!==y.prevData||S!==y.prevWidth||w!==y.prevHeight||_!==y.prevLayout||N!==y.prevStackOffset||!oo(C,y.prevMargin)){var L=ZE(v),I={chartX:y.chartX,chartY:y.chartY,isTooltipActive:y.isTooltipActive},z=Q(Q({},XE(y,x,_)),{},{updateId:y.updateId+1}),D=Q(Q(Q({},L),I),z);return Q(Q(Q({},D),p(Q({props:v},D),y)),{},{prevDataKey:b,prevData:x,prevWidth:S,prevHeight:w,prevLayout:_,prevStackOffset:N,prevMargin:C,prevChildren:k})}if(!Ny(k,y.prevChildren)){var F,O,P,A,Y=Wn(k,Oo),K=Y&&(F=(O=Y.props)===null||O===void 0?void 0:O.startIndex)!==null&&F!==void 0?F:T,M=Y&&(P=(A=Y.props)===null||A===void 0?void 0:A.endIndex)!==null&&P!==void 0?P:$,le=K!==T||M!==$,be=!Ve(x),me=be&&!le?y.updateId:y.updateId+1;return Q(Q({updateId:me},p(Q(Q({props:v},y),{},{updateId:me,dataStartIndex:K,dataEndIndex:M}),y)),{},{prevChildren:k,dataStartIndex:K,dataEndIndex:M})}return null}),Ae(g,"renderActiveDot",function(v,y,b){var x;return E.isValidElement(v)?x=E.cloneElement(v,y):$e(v)?x=v(y):x=W.createElement(sP,y),W.createElement(Yt,{className:"recharts-active-dot",key:b},x)});var m=E.forwardRef(function(y,b){return W.createElement(g,Js({},y,{ref:b}))});return m.displayName=g.displayName,m},Ma=vie({chartName:"BarChart",GraphicalChild:fn,defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"xAxis",AxisComp:Br},{axisType:"yAxis",AxisComp:zr}],formatAxisMap:xte});function JE(e){return e==null||e<1e-5?"$0.00":e<.01?"$"+e.toFixed(6):"$"+e.toFixed(4)}function Ri(e){return e==null?"0":e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}const bie={local:"#3fb950",groq:"#58a6ff",gemini:"#bc8cff",nim:"#39d2c0",openrouter:"#d29922"};function xie({data:e}){var u,d,f;if(!e)return s.jsxs("div",{className:"loading-state",children:[s.jsx("div",{className:"loading-spinner"}),s.jsx("p",{children:"Connecting to dashboard..."})]});const{cost:t,history:n,benchmarks:r,memory:i,health:a}=e,o=[{icon:"💰",value:JE(t.totalCost),label:"Total Cost"},{icon:"📞",value:Ri(t.totalRequests),label:"API Requests"},{icon:"🧠",value:Ri(i.total),label:"Trajectories"},{icon:"📝",value:Ri(n.total),label:"Chat Sessions"},{icon:"🏆",value:Ri(r.totalRuns),label:"Benchmark Runs"},{icon:"📦",value:Ri(a.vectors),label:"Vector Entries"}],l=Object.entries(t.byProvider||{}).map(([h,p])=>({name:h,value:p})).sort((h,p)=>p.value-h.value),c=Object.entries(i.byFingerprint||{}).map(([h,p])=>({name:h.length>15?h.slice(0,13)+"..":h,value:p})).sort((h,p)=>p.value-h.value).slice(0,8);return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"📊 System Overview"}),s.jsx("div",{className:"stats-grid",children:o.map(h=>s.jsxs("div",{className:"stat-card",children:[s.jsx("div",{className:"stat-icon",children:h.icon}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",children:h.value}),s.jsx("div",{className:"stat-label",children:h.label})]})]},h.label))}),s.jsxs("div",{className:"memory-health-card",children:[s.jsx("h3",{className:"section-subtitle",children:"🧠 Memory Health"}),s.jsxs("div",{className:"memory-health-stats",children:[s.jsxs("div",{className:"memory-health-stat",children:[s.jsx("span",{className:"memory-health-value",children:Ri(i.total)}),s.jsx("span",{className:"memory-health-label",children:"Trajectories"})]}),s.jsxs("div",{className:"memory-health-stat",children:[s.jsx("span",{className:"memory-health-value",children:Ri(((u=i.facts)==null?void 0:u.total)||0)}),s.jsx("span",{className:"memory-health-label",children:"Facts Learned"})]}),s.jsxs("div",{className:"memory-health-stat",children:[s.jsx("span",{className:"memory-health-value",children:Ri(((d=i.recall)==null?void 0:d.last7d)||0)}),s.jsx("span",{className:"memory-health-label",children:"Recalls This Week"})]}),s.jsxs("div",{className:"memory-health-stat",children:[s.jsx("span",{className:"memory-health-value",children:a.patterns||0}),s.jsx("span",{className:"memory-health-label",children:"Coding Patterns"})]})]}),s.jsxs("p",{className:"memory-health-status",children:["Backend: ",s.jsx("code",{children:i.backend||"local"}),(f=i.recall)!=null&&f.last7d?` · ${i.recall.last7d} recall(s) this week`:" · no recalls yet"]})]}),s.jsx("h3",{className:"section-subtitle",children:"💰 Cost by Provider"}),s.jsx("div",{className:"chart-container",children:l.length>0?s.jsx(Pa,{width:"100%",height:260,children:s.jsxs(Ma,{data:l,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(Wi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Br,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(zr,{tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"},tickFormatter:h=>"$"+h.toFixed(4)}),s.jsx(hn,{contentStyle:{background:"#161b22",border:"1px solid #30363d",borderRadius:8},labelStyle:{color:"#e6edf3"},formatter:h=>[JE(h),"Cost"]}),s.jsx(fn,{dataKey:"value",radius:[4,4,0,0],children:l.map(h=>s.jsx(Pc,{fill:bie[h.name]||"#58a6ff",fillOpacity:.8},h.name))})]})}):s.jsx("div",{className:"empty-state",children:"No cost data yet."})}),s.jsx("h3",{className:"section-subtitle",children:"📊 Trajectories by Project Type"}),s.jsx("div",{className:"chart-container",children:c.length>0?s.jsx(Pa,{width:"100%",height:260,children:s.jsxs(Ma,{data:c,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(Wi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Br,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(zr,{tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(hn,{contentStyle:{background:"#161b22",border:"1px solid #30363d",borderRadius:8},labelStyle:{color:"#e6edf3"}}),s.jsx(fn,{dataKey:"value",fill:"#bc8cff",radius:[4,4,0,0],fillOpacity:.8})]})}):s.jsx("div",{className:"empty-state",children:"No trajectory data yet."})})]})}const e_={planner:"📋","context-gatherer":"📂",writer:"✏️",reviewer:"👁️",tester:"🧪",debugger:"🐛",runner:"▶️",git:"🔀",package:"📦","github-release":"🏷️",security:"🔒",orchestrator:"🎯"},t_={planner:"#58a6ff","context-gatherer":"#39d2c0",writer:"#d29922",reviewer:"#bc8cff",tester:"#3fb950",debugger:"#f85149",runner:"#58a6ff",git:"#f0883e",package:"#db6d28","github-release":"#3fb950",security:"#f85149",orchestrator:"#f0883e"},Zm={planner:"Planner","context-gatherer":"Context",writer:"Writer",reviewer:"Reviewer",tester:"Tester",debugger:"Debugger",runner:"Runner",git:"Git",package:"Package","github-release":"Release",security:"Security",orchestrator:"Orchestrator"},n_={pending:{icon:"⏳",label:"Pending"},running:{icon:"▶️",label:"Running"},completed:{icon:"✅",label:"Done"},failed:{icon:"❌",label:"Failed"}},wie={pending:"#6e7681",running:"#58a6ff",completed:"#3fb950",failed:"#f85149"};function Sie(e){if(!e||e.nodes.length===0)return null;const t=e.nodes.map(a=>a.startedAt||0).filter(Boolean),n=e.nodes.map(a=>a.completedAt||0).filter(Boolean),r=t.length>0?Math.min(...t):Date.now(),i=n.length>0?Math.max(...n):Date.now();return{id:`live-${r}`,goal:e.pipeline||"Active execution",startedAt:r,endedAt:n.length>0?i:void 0,success:e.nodes.length>0&&e.nodes.every(a=>a.status==="completed"),totalDurationMs:Math.max(0,i-r),phases:e.nodes.map(a=>({id:a.id,agentType:a.agentType,status:a.status,description:a.description,complexity:a.complexity,summary:a.summary,startedAt:a.startedAt,completedAt:a.completedAt,durationMs:a.startedAt&&a.completedAt?a.completedAt-a.startedAt:void 0}))}}function kie(e,t){const n=[],r=new Set,i=Sie(e);i&&(n.push(i),r.add(i.id));for(const a of(t==null?void 0:t.runs)||[])r.has(a.id)||(n.push(a),r.add(a.id));return n}function Ii(e){return e<1e3?`${Math.round(e)}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}function r_(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit"}):""}function Eie(e,t){if(e.length===0)return{laid:[],total:0};const n=e.length,r=e.map(d=>d.durationMs&&d.durationMs>0?d.durationMs:0),i=r.reduce((d,f)=>d+f,0),a=i>0?e.map((d,f)=>r[f]>0?r[f]:i/n):e.map(()=>1),o=a.reduce((d,f)=>d+f,0)||1;let l=0;const c=e.map((d,f)=>{const h=a[f]/o,p=l;return l+=h,{...d,start:p,width:h,dur:a[f]}}),u=t>0?t:o;return{laid:c,total:u}}function _ie({runs:e,selectedRunId:t,onSelectRun:n,onScrub:r}){const[i,a]=E.useState(null),o=e.find(_=>_.id===(t??i))??e[0]??null,[l,c]=E.useState(0),[u,d]=E.useState(!1),f=E.useRef(null),h=E.useRef(!1),p=E.useRef(r);E.useEffect(()=>{p.current=r},[r]),E.useEffect(()=>{var _;!o&&e.length>0?a(e[0].id):o&&!e.some(N=>N.id===o.id)&&a(((_=e[0])==null?void 0:_.id)??null)},[e,o]);const{laid:g,total:m}=E.useMemo(()=>Eie((o==null?void 0:o.phases)||[],(o==null?void 0:o.totalDurationMs)||0),[o]),v=m>0?Math.min(1,Math.max(0,l/m)):0,y=E.useMemo(()=>{if(m<=0)return null;const _=v*m;return g.find(N=>_>=N.start*m&&_<(N.start+N.width)*m)||null},[g,v,m]);E.useEffect(()=>{var _;(_=p.current)==null||_.call(p,(y==null?void 0:y.id)??null)},[y==null?void 0:y.id]),E.useEffect(()=>{if(!u)return;const _=setInterval(()=>{c(N=>N+m/2e3*50)},50);return()=>clearInterval(_)},[u,m]),E.useEffect(()=>{u&&m>0&&l>=m&&(d(!1),c(0))},[u,m,l]);const b=E.useCallback(_=>{const N=f.current;if(!N||m<=0)return;const C=N.getBoundingClientRect(),T=C.width||1,$=Math.min(1,Math.max(0,(_-C.left)/T));c($*m)},[m]),x=_=>{h.current=!0,d(!1),b(_.clientX)};if(E.useEffect(()=>{const _=C=>{h.current&&b(C.clientX)},N=()=>{h.current=!1};return window.addEventListener("pointermove",_),window.addEventListener("pointerup",N),()=>{window.removeEventListener("pointermove",_),window.removeEventListener("pointerup",N)}},[b]),!o)return s.jsx("div",{className:"phase-timeline phase-timeline-empty",children:s.jsx("p",{children:"No pipeline runs yet. Run an agent task to see its phase timeline here."})});const k=o.id.startsWith("live-"),S=o.phases.filter(_=>_.status==="completed").length,w=o.phases.filter(_=>_.status==="failed").length;return s.jsxs("div",{className:"phase-timeline",children:[s.jsxs("div",{className:"phase-timeline-header",children:[s.jsx("div",{className:"phase-timeline-runs",children:e.map(_=>s.jsxs("button",{className:`phase-run-chip ${_.id===o.id?"active":""} ${_.id.startsWith("live-")?"live":""}`,onClick:()=>{a(_.id),c(0),d(!1),n==null||n(_.id)},title:_.goal,children:[_.id.startsWith("live-")&&s.jsx("span",{className:"dag-live-dot"}),_.engine&&s.jsx("span",{className:`phase-run-chip-engine phase-run-chip-engine-${_.engine}`,children:_.engine==="loop"?"🔁":"⬡"}),_.goal.length>32?_.goal.slice(0,30)+"…":_.goal,s.jsx("span",{className:"phase-run-chip-time",children:r_(_.startedAt)})]},_.id))}),s.jsxs("div",{className:"phase-timeline-meta",children:[k&&s.jsx("span",{className:"dag-live-badge",children:"LIVE"}),o.engine&&s.jsx("span",{className:`dag-engine-badge dag-engine-${o.engine}`,title:o.engine==="loop"?"Loop turn (per-tool telemetry below)":"Orchestrator pipeline",children:o.engine==="loop"?"🔁 loop":"⬡ pipeline"}),s.jsxs("span",{className:"phase-meta-item",children:[o.phases.length," steps"]}),s.jsxs("span",{className:"phase-meta-item phase-meta-ok",children:["✅ ",S]}),w>0&&s.jsxs("span",{className:"phase-meta-item phase-meta-bad",children:["❌ ",w]}),o.turnTelemetry&&s.jsxs("span",{className:"phase-meta-item",title:`tool calls: ${o.turnTelemetry.toolCallCount}, errored: ${o.turnTelemetry.erroredToolCount}${o.turnTelemetry.bounded?", bounded":""}${o.turnTelemetry.provider?`, ${o.turnTelemetry.provider}${o.turnTelemetry.model?`/${o.turnTelemetry.model}`:""}`:""}`,children:["🔧 ",o.turnTelemetry.toolCallCount,o.turnTelemetry.erroredToolCount>0&&s.jsxs("span",{className:"phase-meta-bad",children:[" (",o.turnTelemetry.erroredToolCount," err)"]})]}),s.jsxs("span",{className:"phase-meta-item",children:["⏱ ",Ii(m)]})]})]}),s.jsxs("div",{className:"phase-timeline-controls",children:[s.jsx("button",{className:`phase-play-btn ${u?"paused":""}`,onClick:()=>{u?d(!1):(l>=m&&c(0),d(!0))},"aria-label":u?"Pause scrub":"Play scrub",children:u?"⏸ Pause":"▶ Play"}),s.jsxs("span",{className:"phase-time-label",children:[Ii(l)," / ",Ii(m)]}),s.jsx("input",{className:"phase-range",type:"range",min:0,max:m||1,step:1,value:Math.min(l,m||1),onChange:_=>{d(!1),c(Number(_.target.value))},"aria-label":"Scrub pipeline timeline"})]}),s.jsxs("div",{className:"phase-track-wrap",children:[s.jsxs("div",{ref:f,className:"phase-track",onPointerDown:x,style:{cursor:"grab"},children:[g.map(_=>{const N=t_[_.agentType]||"#58a6ff",C=wie[_.status],T=(y==null?void 0:y.id)===_.id;return s.jsxs("button",{className:`phase-block phase-block-${_.status} ${T?"active":""}`,style:{left:`${_.start*100}%`,width:`${Math.max(_.width*100,2)}%`,background:`linear-gradient(180deg, ${N}cc, ${N}66)`,boxShadow:T?`0 0 0 2px ${C}`:void 0},onClick:$=>{$.stopPropagation(),d(!1),c((_.start+_.width/2)*m)},title:`${Zm[_.agentType]||_.agentType}: ${_.description}`,children:[s.jsx("span",{className:"phase-block-icon",children:e_[_.agentType]||"⚙️"}),s.jsx("span",{className:"phase-block-label",children:Zm[_.agentType]||_.agentType})]},_.id)}),s.jsx("div",{className:"phase-caret",style:{left:`${v*100}%`},onPointerDown:_=>{_.stopPropagation(),x(_)},title:`${Ii(l)} elapsed`})]}),s.jsxs("div",{className:"phase-ticks",children:[s.jsx("span",{children:"0"}),s.jsx("span",{children:Ii(Math.round(m/2))}),s.jsx("span",{children:Ii(m)})]})]}),s.jsx("div",{className:"phase-detail",children:y?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"phase-detail-title",children:[s.jsx("span",{className:"phase-detail-icon",children:e_[y.agentType]||"⚙️"}),s.jsx("span",{className:"phase-detail-agent",style:{color:t_[y.agentType]||"#58a6ff"},children:Zm[y.agentType]||y.agentType}),s.jsxs("span",{className:`phase-status-badge phase-status-${y.status}`,children:[n_[y.status].icon," ",n_[y.status].label]})]}),s.jsx("p",{className:"phase-detail-desc",children:y.description}),s.jsxs("div",{className:"phase-detail-meta",children:[s.jsxs("span",{children:["⏱ ",y.durationMs?Ii(y.dur):`~${Ii(y.dur)}`]}),y.startedAt?s.jsxs("span",{children:["🕐 ",r_(y.startedAt)]}):null,y.complexity?s.jsxs("span",{children:["🎯 ",y.complexity]}):null]}),y.summary&&s.jsx("p",{className:"phase-detail-summary",children:y.summary})]}):s.jsxs("div",{className:"phase-detail-gap",children:[s.jsx("span",{className:"phase-detail-icon",children:"⏳"}),s.jsx("span",{children:"Between steps — waiting for the next agent."})]})})]})}const i_={planner:"📋","context-gatherer":"📂",writer:"✏️",reviewer:"👁️",tester:"🧪",debugger:"🐛",runner:"▶️",git:"🔀",package:"📦","github-release":"🏷️",security:"🔒",orchestrator:"🎯"},Qm={planner:"#58a6ff","context-gatherer":"#39d2c0",writer:"#d29922",reviewer:"#bc8cff",tester:"#3fb950",debugger:"#f85149",runner:"#58a6ff",git:"#f0883e",package:"#db6d28","github-release":"#3fb950",security:"#f85149",orchestrator:"#f0883e"},Nie={pending:{bg:"#1a1f2e",stroke:"#30363d",text:"#6e7681"},running:{bg:"rgba(88, 166, 255, 0.12)",stroke:"#58a6ff",text:"#58a6ff"},completed:{bg:"rgba(63, 185, 80, 0.12)",stroke:"#3fb950",text:"#3fb950"},failed:{bg:"rgba(248, 81, 73, 0.12)",stroke:"#f85149",text:"#f85149"}},a_={pending:"⏳ Pending",running:"▶️ Running",completed:"✅ Done",failed:"❌ Failed"},Ps={trivial:{icon:"🟢",color:"#3fb950"},simple:{icon:"🔵",color:"#58a6ff"},moderate:{icon:"🟡",color:"#d29922"},complex:{icon:"🟠",color:"#f0883e"},critical:{icon:"🔴",color:"#f85149"}},Jm={planner:"Planner","context-gatherer":"Context",writer:"Writer",reviewer:"Reviewer",tester:"Tester",debugger:"Debugger",runner:"Runner",git:"Git",package:"Package","github-release":"Release",security:"Security",orchestrator:"Orchestrator"};function jie(e,t,n=160,r=68,i=40,a=24,o=40){if(e.length===0)return{layoutNodes:[],svgW:400,svgH:200};const l=new Map,c=new Set;function u(v){if(l.has(v))return l.get(v);if(c.has(v))return 0;c.add(v);const y=t.filter(k=>k.to===v);if(y.length===0)return l.set(v,0),0;const x=Math.max(...y.map(k=>u(k.from)))+1;return l.set(v,x),x}for(const v of e)u(v.id);const d=new Map;for(const v of e){const y=l.get(v.id)??0;d.has(y)||d.set(y,[]),d.get(y).push(v)}const f=Math.max(...d.keys()),h=Math.max(...Array.from(d.values()).map(v=>v.length)),p=(f+1)*(n+i)+o*2-i,g=Math.max(h,1)*(r+a)+o*2-a,m=[];for(const v of e){const y=l.get(v.id)??0,b=d.get(y),x=b.indexOf(v),k=b.length,S=k*(r+a)-a,w=g/2-S/2;m.push({...v,x:o+y*(n+i),y:w+x*(r+a),w:n,h:r,step:y,totalInStep:k,indexInStep:x})}return{layoutNodes:m,svgW:p,svgH:g}}function eg(e,t){if(!e)return"--";const n=(t||Date.now())-e;return n<1e3?`${n}ms`:n<6e4?`${(n/1e3).toFixed(1)}s`:`${Math.floor(n/6e4)}m ${Math.floor(n%6e4/1e3)}s`}function s_(e){return e?new Date(e).toLocaleTimeString("en-US",{minute:"2-digit",second:"2-digit"}):""}function Aie({memoryTotal:e}){return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"🔀 Agent Execution DAG"}),s.jsx("p",{className:"section-description",children:"Live visualization of the agent execution pipeline. When an agent task runs, you'll see each step appear here in real time as it moves through planning → context gathering → writing → review → testing."}),s.jsxs("div",{className:"dag-empty",children:[s.jsx("div",{className:"dag-empty-icon",children:"🔀"}),s.jsx("h3",{children:"No Active Pipeline"}),s.jsx("p",{children:"Run an agent task to see the execution pipeline appear here in real time."}),e!==void 0&&e>0&&s.jsxs("p",{className:"dag-empty-hint",children:[s.jsx("code",{children:e})," past executions are stored in memory."]})]})]})}function Tie({data:e}){var O;const t=e==null?void 0:e.dag,n=(O=e==null?void 0:e.memory)==null?void 0:O.total,[r,i]=E.useState(null),[a,o]=E.useState(null),[l,c]=E.useState(void 0),[u,d]=E.useState(void 0),[f,h]=E.useState(void 0);E.useEffect(()=>ee.onDAGEvent(A=>{i(A),c(A.engine),d(A.engineExplanation),h(A.loopTurn)}),[]);const p=t||r,g=r?l:(t==null?void 0:t.engine)??l,m=r?u:(t==null?void 0:t.engineExplanation)??u,v=r?f:(t==null?void 0:t.loopTurn)??f,y=E.useMemo(()=>kie(p,e==null?void 0:e.pipelineRuns),[p,e==null?void 0:e.pipelineRuns]),b=P=>{o(P)},x=!!(p&&(p.nodes.length>0||p.active)),k=y.length>0;if(!x&&!k&&!!!v)return s.jsx(Aie,{memoryTotal:n});const{nodes:w,edges:_,pipeline:N,active:C}=p??{nodes:[],edges:[],pipeline:null,active:!1},{layoutNodes:T,svgW:$,svgH:R}=jie(w,_),L=w.filter(P=>P.status==="running").length,I=w.filter(P=>P.status==="completed").length,z=w.filter(P=>P.status==="failed").length,D=w.filter(P=>P.status==="pending").length,F=w.length;return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"🔀 Agent Execution DAG"}),k&&s.jsxs("div",{className:"dag-timeline-section",children:[s.jsxs("h3",{className:"section-subtitle",children:["⏱ Run Timeline ",s.jsx("span",{className:"timeline-subtitle",children:"— scrub to replay · click a run to switch"})]}),s.jsx(_ie,{runs:y,onScrub:b})]}),v&&s.jsxs("div",{className:"dag-loop-turn-card","data-testid":"dag-loop-turn-card",children:[s.jsxs("div",{className:"dag-loop-turn-header",children:[s.jsx("span",{className:"dag-loop-turn-icon",children:"🔁"}),s.jsxs("span",{className:"dag-loop-turn-title",children:["Loop turn — ",v.title||"chat turn"]}),v.active&&s.jsx("span",{className:"dag-loop-turn-live",children:"● recording"})]}),s.jsxs("div",{className:"dag-loop-turn-meta",children:[s.jsxs("span",{className:"dag-loop-turn-chip",children:["🔧 ",v.toolCallCount," tool call",v.toolCallCount===1?"":"s"]}),v.erroredToolCount>0&&s.jsxs("span",{className:"dag-loop-turn-chip dag-loop-turn-chip-error",children:["❌ ",v.erroredToolCount," errored"]}),v.provider&&s.jsxs("span",{className:"dag-loop-turn-chip dag-loop-turn-chip-dim",children:[v.provider,v.model?` · ${v.model}`:""]}),typeof v.startedAt=="number"&&s.jsxs("span",{className:"dag-loop-turn-chip dag-loop-turn-chip-dim",children:["⏱ ",eg(v.startedAt,v.endedAt)]}),v.bounded&&s.jsx("span",{className:"dag-loop-turn-chip dag-loop-turn-chip-error",children:"⛔ bounded"}),v.generationFailed&&s.jsx("span",{className:"dag-loop-turn-chip dag-loop-turn-chip-error",children:"💀 generation failed"}),v.cancelled&&s.jsx("span",{className:"dag-loop-turn-chip dag-loop-turn-chip-dim",children:"✖ cancelled"})]}),v.toolCalls.length>0&&s.jsx("div",{className:"dag-loop-turn-tools",children:v.toolCalls.slice(-12).map((P,A)=>s.jsxs("span",{className:`dag-loop-tool ${P.ok===!1?"dag-loop-tool-error":""}`,title:P.error||`${P.tool}${P.durationMs!==void 0?` · ${P.durationMs}ms`:""}`,children:[P.ok===!1?"❌":"✓"," ",P.tool]},`${P.tool}-${A}`))})]}),x&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`dag-status-bar ${C?"active":""}`,children:[s.jsxs("div",{className:"dag-pipeline-name",children:[C&&s.jsx("span",{className:"dag-live-dot"}),N||"Execution Pipeline"]}),s.jsxs("div",{className:"dag-pipeline-meta",children:[C&&s.jsx("span",{className:"dag-live-badge",children:"LIVE"}),g&&s.jsx("span",{className:`dag-engine-badge dag-engine-${g}`,title:m||(g==="loop"?"Single agentic loop":"Orchestrator pipeline"),"data-testid":"dag-engine-badge",children:g==="loop"?"🔁 loop engine":"⬡ pipeline engine"}),s.jsxs("span",{className:"dag-step-count",children:[F," steps"]}),L>0&&s.jsxs("span",{className:"dag-running-badge",children:["▶ ",L," running"]}),D>0&&s.jsxs("span",{className:"dag-pending-badge",children:["⏳ ",D," pending"]}),s.jsxs("span",{className:"dag-completed-badge",children:["✅ ",I," done"]}),z>0&&s.jsxs("span",{className:"dag-failed-badge",children:["❌ ",z," failed"]})]})]}),s.jsx("div",{className:"dag-container",children:s.jsxs("svg",{width:$,height:R,viewBox:`0 0 ${$} ${R}`,children:[s.jsxs("defs",{children:[_.map(P=>s.jsx("marker",{id:`arrow-${P.from}-${P.to}`,markerWidth:"8",markerHeight:"6",refX:"8",refY:"3",orient:"auto",children:s.jsx("polygon",{points:"0 0, 8 3, 0 6",fill:"#58a6ff"})},`arrow-${P.from}-${P.to}`)),s.jsxs("filter",{id:"glow",children:[s.jsx("feGaussianBlur",{stdDeviation:"3",result:"coloredBlur"}),s.jsxs("feMerge",{children:[s.jsx("feMergeNode",{in:"coloredBlur"}),s.jsx("feMergeNode",{in:"SourceGraphic"})]})]})]}),_.map(P=>{const A=T.find(X=>X.id===P.from),Y=T.find(X=>X.id===P.to);if(!A||!Y)return null;const K=A.x+A.w,M=A.y+A.h/2,le=Y.x,be=Y.y+Y.h/2,me=(K+le)/2,Pe=Y.status,H=Pe==="failed"?"#f85149":Pe==="running"?"#58a6ff":Pe==="completed"?"#3fb950":"#30363d";return s.jsx("g",{children:s.jsx("path",{d:`M ${K} ${M} C ${me} ${M}, ${me} ${be}, ${le} ${be}`,fill:"none",stroke:H,strokeWidth:Pe==="pending"?1.5:2.5,strokeOpacity:Pe==="pending"?.3:.8,markerEnd:`url(#arrow-${P.from}-${P.to})`,className:"dag-edge"})},`edge-${P.from}-${P.to}`)}),T.map(P=>{const A=Nie[P.status];Qm[P.agentType];const Y=i_[P.agentType]||"⚙️",K=Jm[P.agentType]||P.agentType,M=a===P.id,le=P.status==="running";return s.jsxs("g",{onClick:()=>o(M?null:P.id),style:{cursor:"pointer"},className:"dag-node-group",children:[M&&s.jsx("rect",{x:P.x-4,y:P.y-4,width:P.w+8,height:P.h+8,rx:10,ry:10,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.5}),s.jsx("rect",{x:P.x,y:P.y,width:P.w,height:P.h,rx:8,ry:8,fill:A.bg,stroke:A.stroke,strokeWidth:le?2.5:1.5,strokeOpacity:.9,className:le?"dag-node-running":"",filter:le?"url(#glow)":void 0}),s.jsxs("text",{x:P.x+10,y:P.y+22,fill:"#e6edf3",fontSize:10,fontWeight:600,children:[Y," ",K]}),s.jsx("text",{x:P.x+P.w-10,y:P.y+22,textAnchor:"end",fill:A.text,fontSize:9,fontWeight:500,children:a_[P.status]}),s.jsx("text",{x:P.x+10,y:P.y+40,fill:"#8b949e",fontSize:9,children:P.description.length>28?P.description.slice(0,26)+"..":P.description}),P.complexity&&Ps[P.complexity]&&s.jsxs("text",{x:P.x+10,y:P.y+54,fill:Ps[P.complexity].color,fontSize:8,fontWeight:600,children:[Ps[P.complexity].icon," ",P.complexity]}),s.jsx("text",{x:P.x+10,y:P.y+56,fill:"#6e7681",fontSize:8,children:eg(P.startedAt,P.completedAt)}),s.jsx("text",{x:P.x+P.w-10,y:P.y+56,textAnchor:"end",fill:"#6e7681",fontSize:8,children:s_(P.startedAt||P.completedAt)}),(P.status==="failed"||M)&&P.summary&&s.jsx("foreignObject",{x:Math.max(10,P.x-80),y:P.y+P.h+6,width:P.w+160,height:36,children:s.jsx("div",{className:"dag-node-summary",style:{color:P.status==="failed"?"#f85149":"#8b949e",fontSize:"10px",lineHeight:1.4,background:"rgba(13,17,23,0.9)",padding:"4px 8px",borderRadius:"4px",border:`1px solid ${P.status==="failed"?"rgba(248,81,73,0.3)":"rgba(48,54,61,0.5)"}`,maxHeight:"32px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:P.summary})})]},`node-${P.id}`)})]})}),s.jsx("h3",{className:"section-subtitle",children:"Step Details"}),s.jsx("div",{className:"dag-table-wrapper",children:s.jsxs("table",{className:"dag-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Step"}),s.jsx("th",{children:"Agent"}),s.jsx("th",{children:"Complexity"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Duration"}),s.jsx("th",{children:"Time"}),s.jsx("th",{children:"Summary"})]})}),s.jsx("tbody",{children:T.map(P=>s.jsxs("tr",{className:`dag-row dag-row-${P.status}`,children:[s.jsx("td",{className:"dag-cell-step",children:P.step}),s.jsxs("td",{className:"dag-cell-agent",children:[s.jsx("span",{className:"dag-agent-dot",style:{background:Qm[P.agentType]||"#58a6ff"}}),Jm[P.agentType]||P.agentType]}),s.jsx("td",{className:"dag-cell-complexity",children:P.complexity&&Ps[P.complexity]?s.jsxs("span",{style:{color:Ps[P.complexity].color,fontSize:12},children:[Ps[P.complexity].icon," ",P.complexity]}):s.jsx("span",{style:{color:"#6e7681",fontSize:12},children:"—"})}),s.jsx("td",{className:`dag-cell-status dag-status-${P.status}`,children:a_[P.status]}),s.jsx("td",{className:"dag-cell-duration",children:eg(P.startedAt,P.completedAt)}),s.jsx("td",{className:"dag-cell-time",children:s_(P.startedAt||P.completedAt)}),s.jsx("td",{className:"dag-cell-summary",children:P.summary||P.description||"--"})]},P.id))})]})}),s.jsx("h3",{className:"section-subtitle",children:"Agent Types"}),s.jsxs("div",{className:"dag-legend",children:[Object.entries(i_).map(([P,A])=>s.jsxs("div",{className:"legend-item",children:[s.jsx("span",{className:"legend-dot",style:{background:Qm[P]||"#58a6ff"}}),s.jsx("span",{className:"legend-icon",children:A}),s.jsx("span",{className:"legend-label",children:Jm[P]||P})]},P)),s.jsxs("div",{className:"legend-item",children:[s.jsx("span",{className:"legend-dot",style:{background:"transparent",border:"2px dashed #58a6ff"}}),s.jsx("span",{className:"legend-icon",children:"⚡"}),s.jsx("span",{className:"legend-label",children:"Live node"})]})]})]})]})}function Ms(e){return e==null||e<1e-5?"$0.00":e<.01?"$"+e.toFixed(6):"$"+e.toFixed(4)}function $l(e){return e==null?"0":e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}function Cie(e){return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Oie({data:e}){if(!e)return s.jsx("div",{className:"loading-state",children:s.jsx("p",{children:"Loading cost data..."})});const{cost:t}=e,n=Object.entries(t.byProvider||{}).sort(([,a],[,o])=>o-a),r=Object.entries(t.byModel||{}).sort(([,a],[,o])=>o-a).slice(0,10),i=n.reduce((a,[,o])=>a+o,0);return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"💰 Cost Tracking"}),s.jsxs("div",{className:"cost-summary",children:[s.jsxs("div",{className:"cost-total",children:[s.jsx("span",{className:"cost-label",children:"Total Spent"}),s.jsx("span",{className:"cost-amount",children:Ms(t.totalCost)})]}),s.jsxs("div",{className:"cost-total",children:[s.jsx("span",{className:"cost-label",children:"Total Tokens"}),s.jsx("span",{className:"cost-amount",children:$l(t.totalTokens)})]}),s.jsxs("div",{className:"cost-total",children:[s.jsx("span",{className:"cost-label",children:"Total Requests"}),s.jsx("span",{className:"cost-amount",children:$l(t.totalRequests)})]})]}),s.jsxs("div",{className:"cost-summary cost-summary-sub",children:[s.jsxs("div",{className:"cost-total",children:[s.jsx("span",{className:"cost-label",children:"📏 Measured (exact wire tokens)"}),s.jsx("span",{className:"cost-amount",children:Ms(t.measuredCost)}),s.jsxs("span",{className:"cost-label",children:[$l(t.measuredCalls)," calls"]})]}),s.jsxs("div",{className:"cost-total",children:[s.jsx("span",{className:"cost-label",children:"📐 Estimated (length-based)"}),s.jsx("span",{className:"cost-amount",children:Ms(t.estimatedCost)}),s.jsxs("span",{className:"cost-label",children:[$l(t.estimatedCalls)," calls"]})]})]}),s.jsx("h3",{className:"section-subtitle",children:"By Provider"}),s.jsx("div",{className:"cost-list",children:n.length===0?s.jsx("div",{className:"empty-state",children:"No costs recorded yet."}):n.map(([a,o])=>{const l=i>0?(o/i*100).toFixed(1):"0";return s.jsxs("div",{className:"cost-row",children:[s.jsx("span",{className:"cost-row-name",children:a}),s.jsx("div",{className:"cost-row-bar",children:s.jsx("div",{className:"cost-row-fill",style:{width:`${l}%`}})}),s.jsx("span",{className:"cost-row-value",children:Ms(o)})]},a)})}),s.jsx("h3",{className:"section-subtitle",children:"By Model"}),s.jsx("div",{className:"cost-list",children:r.length===0?s.jsx("div",{className:"empty-state",children:"No model costs recorded yet."}):r.map(([a,o])=>{const l=i>0?(o/i*100).toFixed(1):"0",c=a.length>30?a.slice(0,28)+"..":a;return s.jsxs("div",{className:"cost-row",children:[s.jsx("span",{className:"cost-row-name",children:c}),s.jsx("div",{className:"cost-row-bar",children:s.jsx("div",{className:"cost-row-fill",style:{width:`${l}%`}})}),s.jsx("span",{className:"cost-row-value",children:Ms(o)})]},a)})}),s.jsx("h3",{className:"section-subtitle",children:"Recent Requests"}),s.jsx("div",{className:"request-list",children:!t.recent||t.recent.length===0?s.jsx("div",{className:"empty-state",children:"No requests recorded yet."}):t.recent.slice(0,30).map((a,o)=>s.jsxs("div",{className:"request-row",children:[s.jsx("span",{className:"request-time",children:Cie(a.timestamp)}),s.jsx("span",{className:"request-provider",children:a.provider||"--"}),s.jsx("span",{className:"request-model",children:a.model||"--"}),s.jsx("span",{className:"request-cost",children:Ms(a.costUsd)}),s.jsxs("span",{className:"request-tokens",children:[$l(a.totalTokens)," tok"]})]},o))})]})}function Pie(e){return e==null?"$0.00":"$"+e.toFixed(6)}function pd(e){return e==null?"0%":(e*100).toFixed(1)+"%"}function Mie({data:e}){if(!e)return s.jsx("div",{className:"loading-state",children:s.jsx("p",{children:"Loading benchmark data..."})});const{benchmarks:t,evals:n}=e,r=t.latest,i=t.runs||[],a=(n==null?void 0:n.runs)||[],o=(n==null?void 0:n.latest)||null,l=a.map(u=>({name:u.model.length>12?u.model.slice(0,10)+"..":u.model,score:Math.round(u.summary.avgCompositeScore*100),completion:Math.round(u.summary.completionRate*100),tests:Math.round(u.summary.testPassRate*100),recovery:Math.round(u.summary.recoveryRate*100),efficiency:Math.round(u.summary.avgTokenEfficiency*100),fullModel:u.model,provider:u.provider})).reverse(),c=i.map(u=>({name:u.model.length>12?u.model.slice(0,10)+"..":u.model,passRate:u.summary.totalTasks>0?Math.round(u.summary.tasksPassed/u.summary.totalTasks*100):0,quality:Math.round(u.summary.avgQualityScore*100),latency:u.summary.medianLatencyMs,cost:u.summary.totalCostUsd,fullModel:u.model,provider:u.provider})).reverse();return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"📈 Benchmark Results"}),s.jsx("div",{className:"benchmark-latest",children:r?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"benchmark-header",children:[s.jsx("strong",{children:"Latest Run:"})," ",r.provider,"/",r.model]}),s.jsxs("div",{className:"benchmark-stats",children:[s.jsxs("div",{className:"benchmark-stat pass",children:[s.jsxs("div",{className:"benchmark-stat-value",children:[r.summary.tasksPassed,"/",r.summary.totalTasks]}),s.jsx("div",{className:"benchmark-stat-label",children:"Passed"})]}),s.jsxs("div",{className:"benchmark-stat quality",children:[s.jsx("div",{className:"benchmark-stat-value",children:pd(r.summary.avgQualityScore)}),s.jsx("div",{className:"benchmark-stat-label",children:"Quality"})]}),s.jsxs("div",{className:"benchmark-stat latency",children:[s.jsxs("div",{className:"benchmark-stat-value",children:[r.summary.medianLatencyMs,"ms"]}),s.jsx("div",{className:"benchmark-stat-label",children:"Latency"})]}),s.jsxs("div",{className:"benchmark-stat fail",children:[s.jsx("div",{className:"benchmark-stat-value",children:Pie(r.summary.totalCostUsd)}),s.jsx("div",{className:"benchmark-stat-label",children:"Cost"})]})]})]}):s.jsxs("div",{className:"empty-state",children:["No benchmark runs yet. Run ",s.jsx("code",{children:"buff benchmark"})," to start."]})}),c.length>1&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"section-subtitle",children:"Pass Rate by Model"}),s.jsx("div",{className:"chart-container",children:s.jsx(Pa,{width:"100%",height:260,children:s.jsxs(Ma,{data:c,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(Wi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Br,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(zr,{domain:[0,100],tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"},tickFormatter:u=>u+"%"}),s.jsx(hn,{contentStyle:{background:"#161b22",border:"1px solid #30363d",borderRadius:8},labelStyle:{color:"#e6edf3"},formatter:u=>[u+"%","Pass Rate"]}),s.jsx(fn,{dataKey:"passRate",radius:[4,4,0,0],children:c.map((u,d)=>s.jsx(Pc,{fill:u.passRate>=80?"#3fb950":u.passRate>=50?"#d29922":"#f85149",fillOpacity:.8},d))})]})})}),s.jsx("h3",{className:"section-subtitle",children:"Latency by Model"}),s.jsx("div",{className:"chart-container",children:s.jsx(Pa,{width:"100%",height:260,children:s.jsxs(Ma,{data:c,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(Wi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Br,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(zr,{tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"},tickFormatter:u=>u+"ms"}),s.jsx(hn,{contentStyle:{background:"#161b22",border:"1px solid #30363d",borderRadius:8},labelStyle:{color:"#e6edf3"},formatter:u=>[u+"ms","Latency"]}),s.jsx(fn,{dataKey:"latency",fill:"#d29922",radius:[4,4,0,0],fillOpacity:.8})]})})}),s.jsx("h3",{className:"section-subtitle",children:"Cost by Model"}),s.jsx("div",{className:"chart-container",children:s.jsx(Pa,{width:"100%",height:260,children:s.jsxs(Ma,{data:c,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(Wi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Br,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(zr,{tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"},tickFormatter:u=>"$"+u.toFixed(6)}),s.jsx(hn,{contentStyle:{background:"#161b22",border:"1px solid #30363d",borderRadius:8},labelStyle:{color:"#e6edf3"},formatter:u=>["$"+u.toFixed(6),"Cost"]}),s.jsx(fn,{dataKey:"cost",fill:"#bc8cff",radius:[4,4,0,0],fillOpacity:.8})]})})})]}),s.jsx("h2",{className:"section-title",style:{marginTop:32},children:"🎯 Agent Evaluation"}),s.jsx("p",{className:"section-hint",style:{color:"#8b949e",fontSize:12,marginBottom:16},children:"End-to-end coding tasks run through the full agent pipeline — measures if the agent is actually improving."}),s.jsx("div",{className:"benchmark-latest",children:o?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"benchmark-header",children:[s.jsx("strong",{children:"Latest Eval Run:"})," ",o.provider,"/",o.model]}),s.jsxs("div",{className:"benchmark-stats",children:[s.jsxs("div",{className:"benchmark-stat pass",children:[s.jsxs("div",{className:"benchmark-stat-value",children:[o.summary.tasksPassed,"/",o.summary.totalTasks]}),s.jsx("div",{className:"benchmark-stat-label",children:"Tests Passed"})]}),s.jsxs("div",{className:"benchmark-stat quality",children:[s.jsx("div",{className:"benchmark-stat-value",children:pd(o.summary.avgCompositeScore)}),s.jsx("div",{className:"benchmark-stat-label",children:"Composite Score"})]}),s.jsxs("div",{className:"benchmark-stat latency",children:[s.jsx("div",{className:"benchmark-stat-value",children:pd(o.summary.recoveryRate)}),s.jsx("div",{className:"benchmark-stat-label",children:"Recovery Rate"})]}),s.jsxs("div",{className:"benchmark-stat fail",children:[s.jsx("div",{className:"benchmark-stat-value",children:o.summary.totalRollbacks}),s.jsx("div",{className:"benchmark-stat-label",children:"Rollbacks"})]}),s.jsxs("div",{className:"benchmark-stat deps",children:[s.jsx("div",{className:"benchmark-stat-value",children:pd(o.summary.dependencyInstallRate)}),s.jsx("div",{className:"benchmark-stat-label",children:"Deps Installed"})]})]})]}):s.jsxs("div",{className:"empty-state",children:["No eval runs yet. Run ",s.jsx("code",{children:"buff eval run"})," to measure the agent end-to-end."]})}),l.length>1&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"section-subtitle",children:"Composite Score by Model"}),s.jsx("div",{className:"chart-container",children:s.jsx(Pa,{width:"100%",height:260,children:s.jsxs(Ma,{data:l,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(Wi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Br,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(zr,{domain:[0,100],tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"},tickFormatter:u=>u+"%"}),s.jsx(hn,{contentStyle:{background:"#161b22",border:"1px solid #30363d",borderRadius:8},labelStyle:{color:"#e6edf3"},formatter:u=>[u+"%","Composite Score"]}),s.jsx(fn,{dataKey:"score",radius:[4,4,0,0],children:l.map((u,d)=>s.jsx(Pc,{fill:u.score>=80?"#3fb950":u.score>=50?"#d29922":"#f85149",fillOpacity:.8},d))})]})})}),s.jsx("h3",{className:"section-subtitle",children:"Metric Breakdown (completion / tests / recovery / token efficiency)"}),s.jsx("div",{className:"chart-container",children:s.jsx(Pa,{width:"100%",height:260,children:s.jsxs(Ma,{data:l,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(Wi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Br,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(zr,{domain:[0,100],tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"},tickFormatter:u=>u+"%"}),s.jsx(hn,{contentStyle:{background:"#161b22",border:"1px solid #30363d",borderRadius:8},labelStyle:{color:"#e6edf3"}}),s.jsx(Ga,{wrapperStyle:{color:"#8b949e"}}),s.jsx(fn,{dataKey:"completion",name:"Completion",fill:"#3fb950",radius:[4,4,0,0],fillOpacity:.8}),s.jsx(fn,{dataKey:"tests",name:"Tests",fill:"#58a6ff",radius:[4,4,0,0],fillOpacity:.8}),s.jsx(fn,{dataKey:"recovery",name:"Recovery",fill:"#d29922",radius:[4,4,0,0],fillOpacity:.8}),s.jsx(fn,{dataKey:"efficiency",name:"Token Eff.",fill:"#bc8cff",radius:[4,4,0,0],fillOpacity:.8})]})})})]}),s.jsx("h3",{className:"section-subtitle",children:"Eval Run History"}),s.jsx("div",{className:"benchmark-list",children:a.length===0?s.jsxs("div",{className:"empty-state",children:["No eval runs yet. Run ",s.jsx("code",{children:"buff eval run"})," to start."]}):a.map(u=>{const d=Math.round(u.summary.avgCompositeScore*100),f=d>=80?"high":d>=50?"medium":"low";return s.jsxs("div",{className:"benchmark-item",children:[s.jsx("span",{className:"benchmark-date",children:new Date(u.startedAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("span",{className:"benchmark-model",children:[u.provider,"/",u.model]}),s.jsxs("span",{className:`benchmark-score ${f}`,children:[d,"%"]})]},u.id)})}),s.jsx("h3",{className:"section-subtitle",children:"Run History"}),s.jsx("div",{className:"benchmark-list",children:i.length===0?s.jsxs("div",{className:"empty-state",children:["No benchmark runs yet. Run ",s.jsx("code",{children:"buff benchmark"})," to start."]}):i.map(u=>{const d=u.summary.totalTasks>0?Math.round(u.summary.tasksPassed/u.summary.totalTasks*100):0,f=d>=80?"high":d>=50?"medium":"low";return s.jsxs("div",{className:"benchmark-item",children:[s.jsx("span",{className:"benchmark-date",children:new Date(u.startedAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("span",{className:"benchmark-model",children:[u.provider,"/",u.model]}),s.jsxs("span",{className:`benchmark-score ${f}`,children:[d,"%"]})]},u.id)})})]})}function tg(e){return e==null?"0":e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}function Rie({data:e}){if(!e)return s.jsx("div",{className:"loading-state",children:s.jsx("p",{children:"Loading system data..."})});const{health:t,serverTime:n}=e;return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"⚙️ System Health"}),s.jsxs("div",{className:"health-grid",children:[s.jsxs("div",{className:"health-card",children:[s.jsx("span",{className:"health-icon",children:"💾"}),s.jsxs("div",{className:"health-body",children:[s.jsx("div",{className:"health-title",children:"Memory Directory"}),s.jsx("div",{className:"health-path",children:t.memoryDir||"~/.buff/memory/"})]})]}),s.jsxs("div",{className:"health-card",children:[s.jsx("span",{className:"health-icon",children:"📝"}),s.jsxs("div",{className:"health-body",children:[s.jsx("div",{className:"health-title",children:"Coding Patterns"}),s.jsx("div",{className:"health-value",children:tg(t.patterns)})]})]}),s.jsxs("div",{className:"health-card",children:[s.jsx("span",{className:"health-icon",children:"👍"}),s.jsxs("div",{className:"health-body",children:[s.jsx("div",{className:"health-title",children:"User Feedback"}),s.jsxs("div",{className:"health-value",children:[tg(t.feedback)," ratings"]})]})]}),s.jsxs("div",{className:"health-card",children:[s.jsx("span",{className:"health-icon",children:"🧠"}),s.jsxs("div",{className:"health-body",children:[s.jsx("div",{className:"health-title",children:"Vector Index"}),s.jsxs("div",{className:"health-value",children:[tg(t.vectors)," entries"]})]})]})]}),s.jsx("h3",{className:"section-subtitle",children:"Server Info"}),s.jsxs("div",{className:"server-info",children:[s.jsxs("div",{className:"info-row",children:[s.jsx("span",{className:"info-label",children:"Status"}),s.jsx("span",{className:"info-value",children:"● Connected"})]}),s.jsxs("div",{className:"info-row",children:[s.jsx("span",{className:"info-label",children:"Last Updated"}),s.jsx("span",{className:"info-value",children:n?new Date(n).toLocaleString():"--"})]}),s.jsxs("div",{className:"info-row",children:[s.jsx("span",{className:"info-label",children:"Data Directory"}),s.jsx("span",{className:"info-value",children:t.memoryDir||"~/.buff/memory/"})]})]})]})}const Iie=new Set(["local","lmstudio","vllm"]),$ie=new Set([]),gh={available:{bg:"#0a2e1a",text:"#3fb950",dot:"#3fb950",cardBorder:"#3fb950",cardBg:"#0d2818"},limited:{bg:"#2d1f00",text:"#d29922",dot:"#d29922",cardBorder:"#d29922",cardBg:"#1f1700"},unavailable:{bg:"#2d0f0f",text:"#f85149",dot:"#f85149",cardBorder:"#f85149",cardBg:"#1f0a0a"}},Lie=[3,4,5],XP=12e3,o_=[300,700],Die=6e4,Bie=5e3;function zie(e){return new Promise(t=>setTimeout(t,e))}async function ZP(e,t){const n=new AbortController,r=setTimeout(()=>n.abort(),t);try{return await fetch(e,{signal:n.signal})}finally{clearTimeout(r)}}function QP(e){return e instanceof TypeError||e instanceof Error&&e.name==="AbortError"}async function Fie(e){let t=null,n=!1;for(let r=0;;r++){try{const i=await ZP("/api/models",XP);if(!i.ok)t=i.status;else{const a=await ni(i);if(a&&Array.isArray(a.providers))return a;throw new Error("Model health endpoint returned an unexpected response — is the dashboard server up to date?")}}catch(i){if(!QP(i))throw i;n=!0,e==null||e()}if(r>=o_.length)throw new Error(n?"Dashboard server unreachable — is it still running? Retrying automatically…":`Model health endpoint failed (HTTP ${t})`);await zie(o_[r])}}async function Uie(e){for(let t=0;;t++)try{const n=await ZP("/api/model-registry",XP);return n.ok?await ni(n):null}catch(n){if(!QP(n)||t>=1)return null;e==null||e()}}function Wie(e){return e==="available"?"Available":e==="limited"?"Limited":"Unavailable"}function Hie(e){return e==="available"?"Ready":e==="limited"?"Limited":"Down"}function JP(e){return{local:"💻",groq:"🟢",nim:"🔶",gemini:"🔷",openrouter:"🟣",openai:"🤖",anthropic:"🔮",mistral:"🌀",cohere:"🧠",together:"🟢",deepinfra:"🌐",fireworks:"🎆",perplexity:"❓",azure:"🔵",anyscale:"🔷",lmstudio:"🎨",vllm:"⚡"}[e]||"🔌"}function u0(e){return{local:"Ollama",groq:"Groq",nim:"NVIDIA NIM",gemini:"Gemini",openrouter:"OpenRouter",openai:"OpenAI",anthropic:"Anthropic",mistral:"Mistral",cohere:"Cohere",together:"Together AI",deepinfra:"DeepInfra",fireworks:"Fireworks AI",perplexity:"Perplexity",azure:"Azure OpenAI",anyscale:"Anyscale",lmstudio:"LM Studio",vllm:"vLLM / TGI"}[e]||e}function l_({status:e,label:t}){const n=gh[e];return s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,background:n.bg,color:n.text,padding:"3px 10px",borderRadius:12,fontSize:12,fontWeight:500,border:`1px solid ${n.text}22`},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:n.dot}}),t]})}function Gie({onRefresh:e,loading:t}){return s.jsxs("div",{className:"stats-grid mini",style:{marginBottom:16},children:[s.jsx("button",{onClick:e,disabled:t,className:"stat-card",style:{cursor:t?"not-allowed":"pointer",opacity:t?.6:1,border:"1px solid #30363d",justifyContent:"center",fontSize:13},children:t?"⏳ Testing...":"🔄 Refresh Status"}),s.jsx("div",{className:"stat-card",style:{border:"1px solid #30363d"},children:s.jsx("div",{style:{fontSize:13,color:"#8b949e",textAlign:"center",width:"100%"},children:"Tests all configured providers and their API keys in real time"})})]})}function qie({data:e}){const t=e.totalModels;if(t===0)return null;const n=e.available||0,r=e.limited||0,i=e.unavailable||0;return s.jsxs("div",{style:{marginBottom:16},children:[s.jsxs("div",{style:{background:"#0d1117",borderRadius:8,overflow:"hidden",height:10,display:"flex",border:"1px solid #21262d"},children:[n>0&&s.jsx("div",{style:{width:`${n/t*100}%`,background:"#3fb950",transition:"width 0.5s"},title:`${n} available`}),r>0&&s.jsx("div",{style:{width:`${r/t*100}%`,background:"#d29922",transition:"width 0.5s"},title:`${r} limited`}),i>0&&s.jsx("div",{style:{width:`${i/t*100}%`,background:"#f85149",transition:"width 0.5s"},title:`${i} unavailable`})]}),s.jsxs("div",{style:{display:"flex",gap:16,marginTop:6,fontSize:12,color:"#8b949e"},children:[s.jsxs("span",{children:[s.jsx("span",{style:{color:"#3fb950"},children:"●"})," Ready"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#d29922"},children:"●"})," Limited"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#f85149"},children:"●"})," Unavailable"]})]})]})}function md({provider:e}){const[t,n]=E.useState(!1),r=gh[e.overallStatus].text,i={available:e.models.filter(a=>a.status==="available").length,limited:e.models.filter(a=>a.status==="limited").length,unavailable:e.models.filter(a=>a.status==="unavailable").length};return s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:`1px solid ${r}44`,borderLeft:`4px solid ${r}`,marginBottom:12,overflow:"hidden"},children:[s.jsxs("div",{onClick:()=>n(!t),style:{padding:"14px 18px",cursor:"pointer",display:"flex",alignItems:"center",gap:14,userSelect:"none"},children:[s.jsx("span",{style:{fontSize:24},children:e.icon}),s.jsxs("div",{style:{flex:1},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:2},children:[s.jsx("span",{style:{fontSize:16,fontWeight:600,color:"#e6edf3"},children:e.providerLabel}),s.jsx(l_,{status:e.overallStatus,label:Wie(e.overallStatus)})]}),s.jsxs("div",{style:{fontSize:13,color:"#8b949e"},children:[e.models.length," model",e.models.length!==1?"s":"",i.available>0&&s.jsxs("span",{style:{color:"#3fb950"},children:[" · ",i.available," ready"]}),i.limited>0&&s.jsxs("span",{style:{color:"#d29922"},children:[" · ",i.limited," limited"]}),i.unavailable>0&&s.jsxs("span",{style:{color:"#f85149"},children:[" · ",i.unavailable," unavailable"]})]})]}),s.jsxs("div",{style:{fontSize:12,color:"#8b949e",textAlign:"right"},children:[s.jsx("div",{style:{marginBottom:2,color:e.apiConfigured?"#3fb950":"#f85149"},children:e.apiConfigured?"✅ Key set":"❌ No key"}),s.jsx("div",{style:{color:e.apiAccessible?"#3fb950":"#f85149"},children:e.apiAccessible?"✅ Connected":"❌ Offline"})]}),s.jsx("span",{style:{color:"#8b949e",fontSize:18,transition:"transform 0.2s",transform:t?"rotate(90deg)":"rotate(0deg)"},children:"▶"})]}),t&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{padding:"10px 18px",background:"#0d1117",fontSize:13,color:"#8b949e",display:"flex",justifyContent:"space-between",flexWrap:"wrap",gap:8,borderTop:"1px solid #21262d"},children:[s.jsx("span",{children:e.notes}),e.freeTierInfo&&s.jsxs("span",{style:{color:"#d29922"},children:["🎁 ",e.freeTierInfo]})]}),s.jsx("div",{style:{overflowX:"auto",borderTop:"1px solid #21262d"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid #21262d",color:"#8b949e"},children:[s.jsx("th",{style:{padding:"8px 18px",textAlign:"left",fontWeight:500},children:"Model"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Status"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Quota"}),s.jsx("th",{style:{padding:"8px 18px",textAlign:"left",fontWeight:500},children:"Details"})]})}),s.jsx("tbody",{children:e.models.map((a,o)=>s.jsxs("tr",{style:{borderBottom:o<e.models.length-1?"1px solid #21262d":"none",background:a.status==="unavailable"?"#0d1117":"transparent"},children:[s.jsxs("td",{style:{padding:"8px 18px",color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12},children:[s.jsx("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:gh[a.status].dot,marginRight:8}}),a.name]}),s.jsx("td",{style:{padding:"8px 12px"},children:s.jsx(l_,{status:a.status,label:Hie(a.status)})}),s.jsx("td",{style:{padding:"8px 12px",color:"#8b949e",fontSize:12,fontFamily:"'SFMono-Regular', Consolas, monospace"},children:a.rateLimitRemaining!==void 0?a.rateLimitTotal?`${a.rateLimitRemaining}/${a.rateLimitTotal}`:`${a.rateLimitRemaining} left`:"—"}),s.jsx("td",{style:{padding:"8px 18px",color:"#8b949e",fontSize:12},children:a.statusReason})]},a.id))})]})})]})]})}function eM(e){if(e<=0)return"now";const t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4);return t>0?`${t}h ${n}m`:n>0?`${n}m`:`${Math.ceil(e/1e3)}s`}function Kie(e){return e==="verified"?{text:"#3fb950",bg:"#0a2e1a",dot:"#3fb950"}:e==="unavailable"?{text:"#f85149",bg:"#2d0f0f",dot:"#f85149"}:{text:"#8b949e",bg:"#21262d",dot:"#8b949e"}}function Vie({rate:e}){const t=Math.round(e*100);return s.jsxs("span",{title:`⏸ flaky mid-stream ${t}% — started streaming, died before finish; the router deprioritizes flaky models (P4 M4.4)`,style:{marginLeft:8,fontSize:10,padding:"1px 6px",borderRadius:8,whiteSpace:"nowrap",background:"#21122e",border:"1px solid #bc8cff",color:"#bc8cff"},children:["⏸ flaky ",t,"%"]})}function Yie({tokens:e}){const t=e>=1048576?`${(e/1048576).toFixed(1).replace(/\.0$/,"")}M`:e>=1024?`${(e/1024).toFixed(0)}K`:`${e}`;return s.jsxs("span",{title:`⏳ context window ${e.toLocaleString()} tokens — live from the provider's model list (v1.60.x); feeds the router's context preflight`,style:{marginLeft:8,fontSize:10,padding:"1px 6px",borderRadius:8,whiteSpace:"nowrap",background:"#0a1e2e",border:"1px solid #58a6ff",color:"#58a6ff"},children:["⏳ ",t]})}function Xie({history:e}){if(!e||e.length<2)return null;const t=46,n=14,r=1.5,i=Math.max(.01,...e.map(d=>d.rate)),a=e.map((d,f)=>{const h=r+f/(e.length-1)*(t-r*2),p=n-r-d.rate/i*(n-r*2);return`${h.toFixed(1)},${p.toFixed(1)}`}).join(" "),o=e[0].rate,l=e[e.length-1].rate,c=l<o,u=Math.round(l*100);return s.jsxs("svg",{width:t,height:n,viewBox:`0 0 ${t} ${n}`,style:{marginLeft:8,verticalAlign:"middle",cursor:"default"},"aria-label":"Flakiness trend",children:[s.jsx("title",{children:c?`Flakiness healing — ${u}% now, trending down (clean successes decay the signal)`:`Flakiness climbing — ${u}% now (recent mid-stream interruptions)`}),s.jsx("polyline",{points:a,fill:"none",stroke:"#bc8cff",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",opacity:.9}),s.jsx("circle",{cx:t-r,cy:n-r-l/i*(n-r*2),r:2,fill:c?"#3fb950":"#bc8cff"})]})}function Zie({entry:e}){const t=Kie(e.status),n=e.remainingTokens>=0?`${e.remainingTokens.toLocaleString()} left`:"unlimited";return s.jsxs("tr",{style:{borderBottom:"1px solid #21262d"},children:[s.jsxs("td",{style:{padding:"8px 12px",color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12},children:[s.jsx("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:t.dot,marginRight:8}}),e.model.length>32?e.model.slice(0,29)+"…":e.model,(e.partialRate??0)>0&&s.jsx(Vie,{rate:e.partialRate??0}),e.partialHistory&&e.partialHistory.length>=2&&s.jsx(Xie,{history:e.partialHistory}),e.parked&&s.jsx("span",{style:{marginLeft:8,fontSize:10,padding:"1px 6px",borderRadius:8,background:"#2d1616",border:"1px solid #f85149",color:"#f85149"},children:"⏸ parked"}),e.measuredSamples?s.jsxs("span",{style:{marginLeft:8,fontSize:10,padding:"1px 6px",borderRadius:8,whiteSpace:"nowrap",background:"#0a2e1a",border:"1px solid #3fb950",color:"#3fb950"},children:["📏 ",e.measuredInputTokens,"→",e.measuredOutputTokens," tok"]}):s.jsx("span",{style:{marginLeft:8,fontSize:10,padding:"1px 6px",borderRadius:8,whiteSpace:"nowrap",background:"#21262d",border:"1px solid #8b949e",color:"#8b949e"},children:"📐 est"}),e.contextWindowTokens&&s.jsx(Yie,{tokens:e.contextWindowTokens})]}),s.jsx("td",{style:{padding:"8px 12px"},children:s.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,fontWeight:600,background:t.bg,color:t.text,padding:"2px 8px",borderRadius:6},children:e.status==="verified"?"✓ Verified":e.status==="unavailable"?"✗ Unavailable":"◌ Unverified"})}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12,color:e.remainingTokens>=0&&e.remainingTokens<=100?"#d29922":"#8b949e"},children:n}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",color:"#8b949e",fontSize:12,whiteSpace:"nowrap"},children:e.resetsInMs>0?eM(e.resetsInMs):"—"}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",color:"#8b949e",fontSize:12,fontFamily:"'SFMono-Regular', Consolas, monospace"},children:e.latencyMs!==void 0?`${e.latencyMs}ms`:"—"}),s.jsx("td",{style:{padding:"8px 12px",color:"#6e7681",fontSize:11,maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.lastError||(e.source?`learned via ${e.source}`:"")})]})}function Qie({provider:e}){const[t,n]=E.useState(!1),r=e.verified>0?"#3fb950":e.unavailable>0?"#f85149":"#8b949e";return s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:`1px solid ${r}44`,borderLeft:`4px solid ${r}`,marginBottom:12,overflow:"hidden"},children:[s.jsxs("div",{onClick:()=>n(!t),style:{padding:"14px 18px",cursor:"pointer",display:"flex",alignItems:"center",gap:14,userSelect:"none"},children:[s.jsx("span",{style:{fontSize:24},children:JP(e.provider)}),s.jsxs("div",{style:{flex:1},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:2},children:[s.jsx("span",{style:{fontSize:16,fontWeight:600,color:"#e6edf3"},children:u0(e.provider)}),s.jsx("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:10,background:e.parked>0?"#2d1616":"#12291a",border:`1px solid ${e.parked>0?"#f85149":"#238636"}`,color:e.parked>0?"#f85149":"#3fb950"},children:e.parked>0?`${e.parked} parked`:"routable"}),(e.flaky??0)>0&&s.jsxs("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:10,background:"#21122e",border:"1px solid #bc8cff",color:"#bc8cff"},children:["⏸ ",e.flaky," flaky"]})]}),s.jsxs("div",{style:{fontSize:13,color:"#8b949e"},children:[e.verified," verified · ",e.unverified," unverified · ",e.unavailable," unavailable"]})]}),s.jsx("span",{style:{color:"#8b949e",fontSize:18,transition:"transform 0.2s",transform:t?"rotate(90deg)":"rotate(0deg)"},children:"▶"})]}),t&&s.jsx("div",{style:{overflowX:"auto",borderTop:"1px solid #21262d"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid #21262d",color:"#8b949e"},children:[s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Model"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Availability"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"right",fontWeight:500},children:"Tokens left"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"right",fontWeight:500},children:"Resets in"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"right",fontWeight:500},children:"Latency"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Reason / Source"})]})}),s.jsx("tbody",{children:e.models.map(i=>s.jsx(Zie,{entry:i},i.model))})]})})]})}function Jie(e){if(!e)return null;const t=Object.entries(e.consecutive).filter(([,n])=>n>0);return t.length===0?null:s.jsxs("div",{style:{background:"rgba(210, 153, 34, 0.08)",border:"1px solid #9e6a03",borderRadius:10,padding:"10px 14px",marginBottom:14,fontSize:12,color:"#d29922",display:"flex",gap:10,alignItems:"flex-start"},children:[s.jsx("span",{style:{fontSize:15,lineHeight:"18px"},children:"🧹"}),s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600,color:"#e3b341",marginBottom:2},children:"Key hygiene in progress"}),s.jsx("div",{children:t.map(([n,r])=>s.jsxs("span",{style:{display:"inline-block",marginRight:12},children:[s.jsx("code",{style:{color:"#e6edf3"},children:n})," ",r,"/",e.threshold," consecutive auth failures",r>=e.threshold?" — key auto-cleared 🚫":" — key will be auto-cleared at the threshold"]},n))}),s.jsxs("div",{style:{marginTop:4,color:"#9e6a03"},children:["After ",e.threshold," consecutive 401/403s the invalid key is removed from config; run"," ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff config set providers.<provider>.apiKey <real-key>"})," to re-enable."]})]})]})}function eae({data:e}){return e.enabled?s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",style:{marginTop:36},children:"📦 Model Availability Registry — the store routing reads"}),s.jsxs("p",{className:"section-description",children:["The unified sub-ms FAISS/JSON snapshot the Auto router consults on every pick: verified vs unavailable models plus quota telemetry (tokens remaining, reset windows) mirrored from the ledger. Each row's ",s.jsx("strong",{children:"⏳ chip"})," is the LIVE provider-advertised context window (v1.60.x) — the real spec the router's context preflight uses, recorded by the probe from each provider's model list (Ollama /api/tags + /api/show, OpenRouter, Gemini, NIM). State changes during a session are reported to the watch daemon and recorded here immediately."]}),s.jsxs("div",{className:"stats-grid",style:{marginBottom:16},children:[s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"📦"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",children:e.total}),s.jsx("div",{className:"stat-label",children:"Tracked models"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"✅"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#3fb950"},children:e.verified}),s.jsx("div",{className:"stat-label",children:"Verified"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"◌"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#8b949e"},children:e.unverified}),s.jsx("div",{className:"stat-label",children:"Unverified"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"⛔"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#f85149"},children:e.unavailable}),s.jsx("div",{className:"stat-label",children:"Unavailable"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"⏸"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#d29922"},children:e.parked}),s.jsx("div",{className:"stat-label",children:"Quota-parked"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"⏸"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#bc8cff"},children:e.flaky??0}),s.jsx("div",{className:"stat-label",children:"Flaky mid-stream"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"🗑️"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#8b949e"},children:e.deletedLocal??0}),s.jsx("div",{className:"stat-label",children:"Deleted locally"})]})]})]}),Jie(e.keyHygiene),e.providers.map(t=>s.jsx(Qie,{provider:t},t.provider)),s.jsx("div",{style:{textAlign:"center",fontSize:12,color:"#484f58",marginTop:12},children:"Backend snapshot · auto-refreshes every 60s"})]}):s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:"1px dashed #30363d",padding:"20px 24px",marginTop:24,textAlign:"center"},children:[s.jsx("div",{style:{fontSize:24,marginBottom:8},children:"📦"}),s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#e6edf3",marginBottom:4},children:"Model Availability Registry"}),s.jsxs("div",{style:{fontSize:12,color:"#6e7681"},children:["No registry data yet — run ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff models refresh"})," or use Auto routing; the registry learns from real usage and probes."]})]})}const tae={chat:"💬",execute:"⚙️",plan:"🗺️",edit:"✏️",skill:"🧩",learn:"📚",ci:"🔁",doctor:"🩺",probe:"🔭","spot-check":"🧪",telemetry:"📡",usage:"🧮"};function nae(e){return{chat:"Chat",execute:"Execute",plan:"Plan",edit:"Edit",skill:"Skill",learn:"Learn",ci:"CI Review",doctor:"Doctor Probe",probe:"Probe","spot-check":"Spot-check",telemetry:"Usage mirror"}[e]||e.charAt(0).toUpperCase()+e.slice(1)}function rae(e){return tae[e]||"🎯"}function iae(e){return e?new Date(e).toLocaleDateString()+" "+new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"—"}function Ua({provider:e,model:t,reason:n,killed:r,transient:i,partial:a,streamedChunks:o}){const l=r===!0,c=i===!0,u=a===!0,d=u?"#bc8cff":c?"#d29922":l?"#f85149":"#3fb950",f=u?"#21122e":c?"#2d1f00":l?"#2d0f0f":"#0a2e1a";return s.jsxs("span",{title:u?`Mid-stream interruption — started streaming${typeof o=="number"?` ~${o} chunks in`:""}, died before finish (P4 M4.4); router deprioritizes flaky mid-stream providers${n?` · ${n}`:""}`:c?`Transient failure — health decayed, no flip${n?` · ${n}`:""}`:l?`Killed by this action — predictively skipped by routing${n?` · ${n}`:""}`:"Verified by this action — trusted by routing",style:{display:"inline-flex",alignItems:"center",gap:6,background:f,border:`1px solid ${d}`,color:d,padding:"3px 9px",borderRadius:8,fontSize:11,fontFamily:"'SFMono-Regular', Consolas, monospace",whiteSpace:"nowrap",transition:"transform 0.15s",cursor:"default"},onMouseEnter:h=>{h.currentTarget.style.transform="scale(1.05)"},onMouseLeave:h=>{h.currentTarget.style.transform="scale(1)"},children:[s.jsx("span",{style:{opacity:.85},children:u?"⏸":c?"~":l?"✗":"✓"}),e,"/",t.length>30?t.slice(0,27)+"…":t,(l||u)&&n&&s.jsxs("span",{style:{color:`${d}99`,fontSize:10,fontWeight:400},children:["· ",n]})]})}function aae(e){const t=new Map;for(const r of e)t.set(`${r.provider}|${r.model}|${r.outcome}`,r);const n={unavailable:0,partial:1,verified:2,error:3};return[...t.values()].sort((r,i)=>n[r.outcome]-n[i.outcome]||i.at-r.at)}function sae(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(n.verified+n.killed+n.transient+(n.partial||0)>0)return t}return Math.max(0,e.length-1)}function oae({timeline:e}){const[t,n]=E.useState(()=>sae(e||[])),[r,i]=E.useState(!1),a=E.useRef(null),o=E.useRef(!1),l=(e==null?void 0:e.length)??0,c=Math.max(0,Math.min(t,l-1));E.useEffect(()=>{n(m=>Math.min(m,Math.max(0,l-1)))},[l]);const u=E.useCallback(m=>{const v=a.current;if(!v||l<=0)return;const y=v.getBoundingClientRect(),b=y.width||1,x=Math.min(1,Math.max(0,(m-y.left)/b));n(Math.min(l-1,Math.floor(x*l)))},[l]),d=m=>{o.current=!0,i(!1),u(m.clientX)};if(E.useEffect(()=>{const m=y=>{o.current&&u(y.clientX)},v=()=>{o.current=!1};return window.addEventListener("pointermove",m),window.addEventListener("pointerup",v),()=>{window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",v)}},[u]),E.useEffect(()=>{if(!r||l<=1)return;const m=setInterval(()=>{n(v=>Math.min(l-1,v+1))},300);return()=>clearInterval(m)},[r,l]),E.useEffect(()=>{r&&l>1&&t>=l-1&&(i(!1),n(0))},[r,l,t]),!e||l===0)return null;const f=Math.max(1,...e.map(m=>m.verified+m.killed+m.transient+(m.partial||0))),h=m=>new Date(m).toLocaleDateString([],{month:"short",day:"numeric"}),p=e[c],g=p?aae(p.events||[]):[];return s.jsxs("div",{style:{marginTop:12,paddingTop:10,borderTop:"1px solid #21262d"},children:[s.jsxs("div",{style:{fontSize:11,fontWeight:600,color:"#8b949e",marginBottom:8,textTransform:"uppercase",letterSpacing:.4,display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[s.jsxs("span",{children:["📈 Learned from real usage — last ",l," days"]}),s.jsx("span",{style:{fontWeight:400,color:"#6e7681",letterSpacing:0},children:"— drag across days · click a day · play to sweep"})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:8},children:[s.jsx("button",{onClick:()=>{r?i(!1):(t>=l-1&&n(0),i(!0))},disabled:l<=1,"aria-label":r?"Pause scrub":"Play scrub",style:{background:"#21262d",border:`1px solid ${r?"#f85149":"#30363d"}`,color:"#e6edf3",padding:"3px 10px",borderRadius:6,cursor:l<=1?"not-allowed":"pointer",fontSize:11,fontWeight:600,transition:"all 0.15s",whiteSpace:"nowrap",opacity:l<=1?.5:1},children:r?"⏸ Pause":"▶ Play"}),s.jsxs("span",{style:{fontSize:11,color:"#8b949e",whiteSpace:"nowrap"},children:[h(p.day)," · ✓ ",p.verified," · ✗ ",p.killed,p.transient>0?` · ~ ${p.transient}`:"",p.partial>0?` · ⏸ ${p.partial}`:""]}),s.jsx("input",{type:"range",min:0,max:Math.max(0,l-1),step:1,value:c,onChange:m=>{i(!1),n(Number(m.target.value))},"aria-label":"Scrub action timeline",style:{flex:1,accentColor:"#58a6ff",cursor:"pointer",minWidth:80}})]}),s.jsx("div",{ref:a,onPointerDown:d,style:{position:"relative",display:"flex",alignItems:"flex-end",gap:3,height:64,padding:"0 2px",cursor:"grab",userSelect:"none",touchAction:"none"},children:e.map((m,v)=>{const y=m.verified+m.killed+m.transient+(m.partial||0),b=m.verified/f*56,x=m.killed/f*56,k=m.transient/f*56,S=(m.partial||0)/f*56,w=v===c;return s.jsxs("div",{onClick:()=>{i(!1),n(v)},title:`${h(m.day)} — ✓ ${m.verified} verified · ✗ ${m.killed} killed · ~ ${m.transient} transient${(m.partial||0)>0?` · ⏸ ${m.partial} partial`:""}`,style:{flex:1,display:"flex",flexDirection:"column-reverse",alignItems:"center",gap:0,cursor:"pointer"},children:[s.jsxs("div",{style:{position:"relative",width:"100%",borderRadius:3,overflow:w?"visible":"hidden",background:y===0?"#21262d":"transparent",height:y===0?4:56,display:"flex",flexDirection:"column-reverse",boxShadow:w?"0 0 0 1.5px #58a6ff":void 0,opacity:y===0?.5:1,transition:"box-shadow 0.15s"},children:[w&&s.jsx("div",{style:{position:"absolute",top:-3,bottom:-3,width:2,left:"50%",transform:"translateX(-50%)",background:"#58a6ff",borderRadius:2,pointerEvents:"none",boxShadow:"0 0 8px #58a6ff88",zIndex:1}}),m.verified>0&&s.jsx("div",{style:{height:b,background:"#3fb950",minHeight:3}}),m.killed>0&&s.jsx("div",{style:{height:x,background:"#f85149",minHeight:3}}),m.transient>0&&s.jsx("div",{style:{height:k,background:"#d29922",minHeight:3}}),m.partial>0&&s.jsx("div",{style:{height:S,background:"#bc8cff",minHeight:3}})]}),s.jsx("div",{style:{fontSize:9,color:w?"#58a6ff":"#6e7681",marginTop:4,whiteSpace:"nowrap",fontWeight:w?700:400},children:h(m.day)})]},m.day)})}),s.jsxs("div",{style:{display:"flex",gap:14,marginTop:6,fontSize:11,color:"#8b949e"},children:[s.jsxs("span",{children:[s.jsx("span",{style:{color:"#3fb950"},children:"■"})," verified"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#f85149"},children:"■"})," killed"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#d29922"},children:"■"})," transient"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#bc8cff"},children:"■"})," partial"]})]}),s.jsxs("div",{style:{marginTop:10,background:"#161b22",border:"1px solid #21262d",borderRadius:8,padding:"10px 12px"},children:[s.jsxs("div",{style:{fontSize:12,fontWeight:600,color:"#e6edf3",marginBottom:6},children:[h(p.day)," ",s.jsx("span",{style:{color:"#8b949e",fontWeight:400},children:"— what this action learned that day"})]}),g.length===0?s.jsx("div",{style:{fontSize:12,color:"#6e7681"},children:"No learning recorded that day — nothing verified, killed, or partial."}):s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:g.map(m=>m.outcome==="unavailable"?s.jsx(Ua,{provider:m.provider,model:m.model,reason:m.errorType,killed:!0},`${m.provider}|${m.model}|${m.outcome}`):m.outcome==="verified"?s.jsx(Ua,{provider:m.provider,model:m.model},`${m.provider}|${m.model}|${m.outcome}`):m.outcome==="partial"?s.jsx(Ua,{provider:m.provider,model:m.model,reason:m.errorType,partial:!0,streamedChunks:m.streamedChunks},`${m.provider}|${m.model}|${m.outcome}`):s.jsx(Ua,{provider:m.provider,model:m.model,reason:m.errorType,transient:!0},`${m.provider}|${m.model}|${m.outcome}`))})]})]})}function lae({entry:e}){var i,a;const[t,n]=E.useState(!0),r=(e.partial||0)>0?"#bc8cff":e.killed>0?"#f85149":e.verified>0?"#3fb950":"#d29922";return s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:`1px solid ${r}33`,borderLeft:`4px solid ${r}`,marginBottom:12,overflow:"hidden"},children:[s.jsxs("div",{onClick:()=>n(!t),style:{padding:"12px 16px",cursor:"pointer",display:"flex",alignItems:"center",gap:12,userSelect:"none"},children:[s.jsx("span",{style:{fontSize:20},children:rae(e.action)}),s.jsxs("div",{style:{flex:1},children:[s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#e6edf3",marginBottom:2},children:nae(e.action)}),s.jsxs("div",{style:{fontSize:12,color:"#8b949e",display:"flex",gap:14,flexWrap:"wrap"},children:[s.jsxs("span",{children:[s.jsxs("span",{style:{color:"#3fb950"},children:["✓ ",e.verified]})," verified"]}),s.jsxs("span",{children:[s.jsxs("span",{style:{color:"#f85149"},children:["✗ ",e.killed]})," killed"]}),e.transient>0&&s.jsxs("span",{children:[s.jsxs("span",{style:{color:"#d29922"},children:["~ ",e.transient]})," transient"]}),(e.partial||0)>0&&s.jsxs("span",{children:[s.jsxs("span",{style:{color:"#bc8cff"},children:["⏸ ",e.partial]})," partial"]})]})]}),s.jsx("span",{style:{color:"#8b949e",fontSize:16,transition:"transform 0.2s",transform:t?"rotate(90deg)":"rotate(0deg)"},children:"▶"})]}),t&&s.jsxs("div",{style:{padding:"12px 16px",borderTop:"1px solid #21262d",background:"#0d1117"},children:[e.killedModels.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:11,fontWeight:600,color:"#f85149",marginBottom:6,textTransform:"uppercase",letterSpacing:.4},children:"⛔ Killed — skipped predictively by routing"}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:14},children:e.killedModels.map(o=>s.jsx(Ua,{provider:o.provider,model:o.model,reason:o.reason,killed:!0},`${o.provider}|${o.model}`))})]}),e.verifiedModels.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:11,fontWeight:600,color:"#3fb950",marginBottom:6,textTransform:"uppercase",letterSpacing:.4},children:"✅ Verified — trusted by routing"}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:e.verifiedModels.map(o=>s.jsx(Ua,{provider:o.provider,model:o.model},`${o.provider}|${o.model}`))})]}),(((i=e.partialModels)==null?void 0:i.length)||0)>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:11,fontWeight:600,color:"#bc8cff",marginBottom:6,textTransform:"uppercase",letterSpacing:.4},children:"⏸ Partial — mid-stream interruption (flaky provider, deprioritized)"}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:14},children:e.partialModels.map(o=>s.jsx(Ua,{provider:o.provider,model:o.model,reason:o.reason,partial:!0,streamedChunks:o.streamedChunks},`${o.provider}|${o.model}`))})]}),e.killedModels.length===0&&e.verifiedModels.length===0&&(((a=e.partialModels)==null?void 0:a.length)||0)===0&&s.jsx("div",{style:{fontSize:12,color:"#6e7681"},children:"Only transient failures — health decayed, no model flipped."}),s.jsx(oae,{timeline:e.timeline})]})]})}function cae({registry:e}){const t=e.actionTelemetry;return t?t.enabled?s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",style:{marginTop:36},children:"🎓 Learned from real usage — per action"}),s.jsxs("p",{className:"section-description",children:["Every LLM call writes through to the health store with its action tag. This panel shows which provider × model each action ",s.jsx("span",{style:{color:"#3fb950"},children:"verified"})," (routable) or"," ",s.jsx("span",{style:{color:"#f85149"},children:"killed"})," (predictively skipped) — the exact feed that turns “fail gemini → fail nim → local” into “straight to local”."]}),s.jsxs("div",{className:"stats-grid mini",style:{marginBottom:16},children:[s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"📊"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",children:t.total}),s.jsx("div",{className:"stat-label",children:"Telemetry events"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"🎯"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",children:t.actions.length}),s.jsx("div",{className:"stat-label",children:"Actions learning"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"⏱️"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{fontSize:15},children:iae(t.updatedAt)}),s.jsx("div",{className:"stat-label",children:"Last update"})]})]})]}),t.actions.map(n=>s.jsx(lae,{entry:n},n.action)),s.jsx("div",{style:{textAlign:"center",fontSize:12,color:"#484f58",marginTop:12},children:"All actions share one health store — a provider killed by any action is skipped by all others"})]}):s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:"1px dashed #30363d",padding:"18px 24px",marginTop:24,textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,marginBottom:6},children:"🎓"}),s.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e6edf3",marginBottom:4},children:"Learned from real usage — per action"}),s.jsxs("div",{style:{fontSize:12,color:"#6e7681",lineHeight:1.5},children:["No per-action telemetry yet. As you use ",s.jsx("strong",{style:{color:"#8b949e"},children:"chat"}),","," ",s.jsx("strong",{style:{color:"#8b949e"},children:"execute"}),", ",s.jsx("strong",{style:{color:"#8b949e"},children:"plan"}),", and ",s.jsx("strong",{style:{color:"#8b949e"},children:"edit"}),", each action's verified / killed provider × model combos appear here — showing exactly what routing learned from real usage."]})]}):null}function gd({icon:e,title:t,count:n}){return n===0?null:s.jsxs("h3",{style:{fontSize:15,fontWeight:600,color:"#e6edf3",margin:"24px 0 12px 0",display:"flex",alignItems:"center",gap:8},children:[s.jsx("span",{children:e})," ",t,s.jsx("span",{style:{fontSize:12,color:"#8b949e",fontWeight:400,background:"#161b22",padding:"1px 8px",borderRadius:8},children:n})]})}function uae({value:e,onChange:t,totalCount:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:14},children:[s.jsxs("div",{style:{flex:1,position:"relative",display:"flex",alignItems:"center",background:"#161b22",borderRadius:8,border:"1px solid #30363d",transition:"border-color 0.2s"},children:[s.jsx("span",{style:{position:"absolute",left:12,fontSize:14,color:"#6e7681",pointerEvents:"none"},children:"🔍"}),s.jsx("input",{type:"text",value:e,onChange:r=>t(r.target.value),placeholder:"Search models by name or provider...",style:{width:"100%",padding:"10px 12px 10px 36px",background:"transparent",border:"none",color:"#e6edf3",fontSize:13,outline:"none",fontFamily:"inherit"},onFocus:r=>{r.currentTarget.parentElement.style.borderColor="#58a6ff"},onBlur:r=>{r.currentTarget.parentElement.style.borderColor="#30363d"}}),e&&s.jsx("button",{onClick:()=>t(""),style:{background:"none",border:"none",color:"#6e7681",cursor:"pointer",padding:"8px 12px",fontSize:14,lineHeight:1},children:"✕"})]}),s.jsxs("div",{style:{fontSize:12,color:"#8b949e",whiteSpace:"nowrap"},children:[n," model",n!==1?"s":""]})]})}function dae({value:e,onChange:t}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:"#8b949e",marginBottom:14},children:[s.jsx("span",{children:"Columns:"}),Lie.map(n=>s.jsx("button",{onClick:()=>t(n),style:{padding:"4px 12px",borderRadius:6,background:e===n?"#1f6feb":"#21262d",color:e===n?"#fff":"#8b949e",border:`1px solid ${e===n?"#1f6feb":"#30363d"}`,cursor:"pointer",fontSize:12,fontWeight:e===n?600:400,transition:"all 0.15s"},children:n},n))]})}function fae({model:e,provider:t}){const n=gh[e.status],r=e.rateLimitRemaining!==void 0?e.rateLimitTotal?`${e.rateLimitRemaining} / ${e.rateLimitTotal}`:`${e.rateLimitRemaining} left`:"—";return s.jsx("td",{style:{padding:10,verticalAlign:"top"},children:s.jsxs("div",{style:{background:n.cardBg,border:`1px solid ${n.cardBorder}44`,borderRadius:10,padding:14,display:"flex",flexDirection:"column",gap:8,height:"100%",transition:"all 0.2s ease",position:"relative",overflow:"hidden",cursor:"default"},onMouseEnter:i=>{i.currentTarget.style.borderColor=n.cardBorder,i.currentTarget.style.boxShadow=`0 2px 10px ${n.cardBorder}22`},onMouseLeave:i=>{i.currentTarget.style.borderColor=`${n.cardBorder}44`,i.currentTarget.style.boxShadow="none"},children:[s.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,height:3,background:n.cardBorder,opacity:.6}}),s.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",paddingTop:2},children:e.name.length>28?e.name.slice(0,25)+"…":e.name}),s.jsxs("div",{style:{fontSize:12,color:"#8b949e"},children:[JP(t)," ",u0(t)]}),s.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:5,background:n.bg,color:n.text,padding:"3px 8px",borderRadius:6,fontSize:11,fontWeight:600,alignSelf:"flex-start"},children:[s.jsx("span",{style:{width:7,height:7,borderRadius:"50%",background:n.dot}}),e.status==="available"?"Available":e.status==="limited"?"Limited":"Unavailable"]}),s.jsxs("div",{style:{fontSize:11,color:"#6e7681"},children:[s.jsx("span",{style:{color:"#8b949e"},children:"Tokens:"})," ",s.jsx("span",{style:{color:e.rateLimitRemaining!==void 0&&e.rateLimitRemaining<=10?"#d29922":"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace",fontWeight:500},children:r})]}),e.status!=="available"&&e.statusReason&&s.jsx("div",{style:{fontSize:10,color:"#6e7681",lineHeight:1.3,marginTop:2},children:e.statusReason.length>45?e.statusReason.slice(0,42)+"…":e.statusReason}),e.parked&&e.resetsInMs!==void 0&&e.resetsInMs>0&&s.jsxs("div",{style:{fontSize:10,color:"#d29922",lineHeight:1.3,marginTop:4,padding:"3px 6px",borderRadius:4,background:"#2d2200",border:"1px solid #d2992244"},children:["⏳ Resets in ",eM(e.resetsInMs)]})]})})}function hae({providers:e,colsPerRow:t,searchQuery:n}){const r=[];for(const l of e)for(const c of l.models)r.push({model:c,provider:l.provider});if(r.length===0)return null;let i=r;if(n.trim()){const l=n.toLowerCase().trim();i=r.filter(({model:c,provider:u})=>c.name.toLowerCase().includes(l)||u0(u).toLowerCase().includes(l)||u.toLowerCase().includes(l))}const a={available:0,limited:1,unavailable:2};i.sort((l,c)=>a[l.model.status]-a[c.model.status]);const o=[];for(let l=0;l<i.length;l+=t)o.push(i.slice(l,l+t));return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",style:{marginTop:36},children:"📋 Model Health Overview"}),s.jsx("p",{className:"section-description",children:"All models across all providers, color-coded by health status. Each cell shows: Model · Provider · Health · Token Remaining."}),s.jsx("div",{style:{overflowX:"auto"},children:s.jsx("table",{style:{width:"100%",borderCollapse:"separate",borderSpacing:10,tableLayout:"fixed"},children:s.jsx("tbody",{children:o.length>0?o.map((l,c)=>s.jsxs("tr",{children:[l.map(({model:u,provider:d})=>s.jsx(fae,{model:u,provider:d},`${d}-${u.id}`)),l.length<t&&Array.from({length:t-l.length}).map((u,d)=>s.jsx("td",{style:{padding:10}},`empty-${d}`))]},c)):s.jsx("tr",{children:s.jsxs("td",{colSpan:t,style:{textAlign:"center",padding:40,color:"#6e7681",fontSize:13},children:['No models match your search "',n,'"']})})})})}),n.trim()&&i.length>0&&s.jsxs("div",{style:{textAlign:"right",fontSize:11,color:"#6e7681",marginTop:4},children:["Showing ",i.length," of ",r.length," models"]})]})}function pae(){return s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:"1px dashed #30363d",padding:"20px 24px",marginTop:24,textAlign:"center"},children:[s.jsx("div",{style:{fontSize:24,marginBottom:8},children:"🎙️"}),s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#e6edf3",marginBottom:4},children:"Speech / TTS Provider"}),s.jsxs("div",{style:{fontSize:12,color:"#6e7681"},children:["Speech/TTS provider support coming soon."," ",s.jsx("a",{href:"https://github.com/imdheerajKube/agent-nuvira/issues/new",target:"_blank",rel:"noopener noreferrer",style:{color:"#58a6ff",textDecoration:"none",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.textDecoration="underline"},onMouseLeave:e=>{e.currentTarget.style.textDecoration="none"},children:"Request a provider"})]})]})}function mae(){return s.jsxs("div",{style:{background:"#0d1117",borderRadius:10,padding:14,marginBottom:20,border:"1px solid #21262d",fontSize:13,color:"#8b949e",display:"flex",flexWrap:"wrap",gap:20},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600,color:"#e6edf3",marginBottom:6},children:"Color Coding"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsxs("span",{children:[s.jsx("span",{style:{color:"#3fb950"},children:"●"})," ",s.jsx("strong",{style:{color:"#e6edf3"},children:"Green"})," — Working with rate limit available"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#d29922"},children:"●"})," ",s.jsx("strong",{style:{color:"#e6edf3"},children:"Amber"})," — Slow / low rate limit / needs action"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#f85149"},children:"●"})," ",s.jsx("strong",{style:{color:"#e6edf3"},children:"Red"})," — API key missing / payment needed / unreachable"]})]})]}),s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600,color:"#e6edf3",marginBottom:6},children:"Provider Sections"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3,fontSize:12},children:[s.jsxs("span",{children:["✅ ",s.jsx("strong",{children:"Cloud"})," — Online providers with active API keys"]}),s.jsxs("span",{children:["🏠 ",s.jsx("strong",{children:"Local"})," — Locally running inference servers"]}),s.jsxs("span",{children:["⛔ ",s.jsx("strong",{children:"Unavailable"})," — Missing keys or unreachable endpoints"]}),s.jsxs("span",{children:["🎙️ ",s.jsx("strong",{children:"Speech"})," — Text-to-speech / speech-to-text providers (coming)"]})]})]})]})}function gae(){const[e,t]=E.useState(null),[n,r]=E.useState(null),[i,a]=E.useState(!0),[o,l]=E.useState(null),[c,u]=E.useState(4),[d,f]=E.useState(""),h=E.useRef(!0),p=E.useRef(null),g=E.useRef(!1);function m(){p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{h.current&&v()},Bie)}async function v(){a(!0),l(null),g.current=!1;try{const[b,x]=await Promise.all([Fie(()=>{g.current=!0}),Uie(()=>{g.current=!0})]);if(!h.current)return;t(b),r(x),g.current&&m()}catch(b){if(!h.current)return;l(b instanceof Error&&b.message?b.message:"Failed to fetch model status"),g.current&&m()}finally{h.current&&a(!1)}}E.useEffect(()=>{h.current=!0,v();const b=setInterval(v,Die);return()=>{h.current=!1,clearInterval(b),p.current&&clearTimeout(p.current)}},[]);function y(b){const x=[],k=[],S=[],w=[],_={available:0,limited:1,unavailable:2};for(const N of b.providers)$ie.has(N.provider)?S.push(N):Iie.has(N.provider)?k.push(N):N.overallStatus==="available"?x.push(N):w.push(N);return x.sort((N,C)=>_[N.overallStatus]-_[C.overallStatus]),k.sort((N,C)=>_[N.overallStatus]-_[C.overallStatus]),S.sort((N,C)=>_[N.overallStatus]-_[C.overallStatus]),w.sort((N,C)=>_[N.overallStatus]-_[C.overallStatus]),{available:x,local:k,speech:S,unavailable:w}}return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"🧠 Model Provider Status"}),s.jsx("p",{className:"section-description",children:"Real-time health check of all AI providers and their available models. Providers are grouped into sections: Available cloud → Local → Unavailable."}),s.jsx(Gie,{onRefresh:v,loading:i}),s.jsx(mae,{}),i&&!e&&s.jsxs("div",{className:"loading-state",children:[s.jsx("div",{className:"loading-spinner"}),s.jsx("p",{children:"Testing all 17 provider connections..."})]}),o&&s.jsxs("div",{className:"empty-state",style:{color:"#f85149",border:"1px solid #f8514944",borderRadius:10,padding:16,marginBottom:16},children:["⚠️ ",o]}),e&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"stats-grid",style:{marginBottom:16},children:[s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"🧠"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",children:e.totalModels}),s.jsx("div",{className:"stat-label",children:"Total Models"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"✅"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#3fb950"},children:e.available}),s.jsx("div",{className:"stat-label",children:"Available"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"🟡"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#d29922"},children:e.limited}),s.jsx("div",{className:"stat-label",children:"Limited"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"🔴"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#f85149"},children:e.unavailable}),s.jsx("div",{className:"stat-label",children:"Unavailable"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"🔌"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",children:e.providers.length}),s.jsx("div",{className:"stat-label",children:"Providers"})]})]})]}),s.jsx(qie,{data:e}),(()=>{const{available:b,local:x,speech:k,unavailable:S}=y(e);return s.jsxs(s.Fragment,{children:[s.jsx(gd,{icon:"✅",title:"Available Cloud Providers",count:b.length}),b.map(w=>s.jsx(md,{provider:w},w.provider)),s.jsx(gd,{icon:"🏠",title:"Local Providers",count:x.length}),x.map(w=>s.jsx(md,{provider:w},w.provider)),s.jsx(gd,{icon:"⛔",title:"Unavailable Providers",count:S.length}),S.map(w=>s.jsx(md,{provider:w},w.provider)),s.jsx(gd,{icon:"🎙️",title:"Speech / TTS Providers",count:k.length}),k.map(w=>s.jsx(md,{provider:w},w.provider))]})})(),s.jsx(uae,{value:d,onChange:f,totalCount:e.providers.reduce((b,x)=>b+x.models.length,0)}),s.jsx(dae,{value:c,onChange:u}),s.jsx(hae,{providers:e.providers,colsPerRow:c,searchQuery:d}),n&&s.jsx(eae,{data:n}),n&&s.jsx(cae,{registry:n}),e&&!n&&s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:"1px dashed #30363d",padding:"14px 20px",marginTop:24,fontSize:12,color:"#8b949e",lineHeight:1.6},children:["📦 Registry & telemetry sections are hidden — this dashboard server did not return model-registry data (it may be an"," ",s.jsx("strong",{style:{color:"#e6edf3"},children:"older version"}),"). Restart the dashboard from the latest install to see them."]}),s.jsx(pae,{}),s.jsxs("div",{style:{textAlign:"center",fontSize:12,color:"#484f58",marginTop:16},children:["Last checked: ",new Date(e.lastChecked).toLocaleTimeString()," · ","Auto-refreshes every 60s"]})]})]})}const yae={local:"💻",groq:"🟢",nim:"🔶",gemini:"🔷",openrouter:"🟣"},vae={local:"Ollama (Local)",groq:"Groq",nim:"NVIDIA NIM",gemini:"Gemini",openrouter:"OpenRouter"},bae={trivial:"🟢",simple:"🔵",moderate:"🟡",complex:"🟠",critical:"🔴"},tM={trivial:"🟢 trivial",simple:"🔵 simple",moderate:"🟡 moderate",complex:"🟠 complex",critical:"🔴 critical"},xae={chat:"💬 chat",orchestrator:"🔀 orchestrator",explain:"🔍 explain",benchmark:"📈 benchmark",eval:"🎯 eval"},ka=[{key:"request",icon:"🎯",title:"Request"},{key:"candidates",icon:"⚖️",title:"Candidates"},{key:"exclusions",icon:"🚫",title:"Exclusions"},{key:"pick",icon:"✅",title:"Pick"}],wae=2400;function ng(e){return yae[e]||"🔌"}function c_(e){return vae[e]||e}function d0(e){return e&&xae[e]||e||"unknown"}function Sae(e){const t=Date.now()-e;return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`}function u_(e){const t=Math.ceil(e/6e4);return t>=60?`${Math.floor(t/60)}h ${t%60}m`:`${t}m`}const kae=8;function d_(e,t){const n=t.quota,r=n==null?void 0:n.entries.find(a=>a.provider===e);return r!=null&&r.parked?r.resetsInMs>0?`quota exhausted — auto re-enables in ${u_(r.resetsInMs)}`:"quota exhausted — parked":r&&r.cooldownRemaining>0?`circuit-breaker cooldown — ${u_(r.cooldownRemaining)} remaining`:t.providers.some(a=>a.provider===e)?"ranked below the candidate cutoff for this complexity":"not scored for this complexity (no benchmark quality data)"}function Eae(e){var a,o,l;const t=new Set;for(const c of e.providers)t.add(c.provider);if(e.usage)for(const c of Object.keys(e.usage.byProvider))t.add(c);if(e.bestModels)for(const c of e.bestModels)t.add(c.model.split("/")[0]);if(e.quota)for(const c of e.quota.entries)t.add(c.provider);const n=new Map(e.preference.map(c=>[c.complexity,c])),r=[],i=[...e.history??[]].sort((c,u)=>(u.timestamp??0)-(c.timestamp??0));for(const c of i.slice(0,kae)){const u=n.get(c.complexity),d=(a=u==null?void 0:u.providers)!=null&&a.length?u.providers.map(g=>({provider:g.provider,score:g.score,reason:g.reason})):[{provider:c.provider,score:c.score,reason:"actual pick recorded"}];d.some(g=>g.provider===c.provider)||d.push({provider:c.provider,score:c.score,reason:"actual pick recorded"});const f=new Set(d.map(g=>g.provider)),h=[...t].filter(g=>!f.has(g)).map(g=>({provider:g,reason:d_(g,e)})),p=(o=d.find(g=>g.provider===c.provider))==null?void 0:o.reason;r.push({id:c.id,label:`${d0(c.source)} · ${c.complexity} · ${(c.task||c.agentType).slice(0,26)}`,real:!0,complexity:c.complexity,task:c.task||c.agentType,agentType:c.agentType,source:c.source,timestamp:c.timestamp,winner:`${c.provider}/${c.model}`,winnerScore:c.score,winnerReason:p,candidates:d,exclusions:h})}if(r.length===0)for(const c of e.preference){const u=c.winner.split("/"),d=c.providers.map(g=>({provider:g.provider,score:g.score,reason:g.reason})),f=new Set(d.map(g=>g.provider)),h=[...t].filter(g=>!f.has(g)).map(g=>({provider:g,reason:d_(g,e)})),p=u[0];r.push({id:`profile-${c.complexity}`,label:`${tM[c.complexity]||c.complexity} — what the router would pick`,real:!1,complexity:c.complexity,task:p?`A ${c.complexity} task (auto-routed)`:`A ${c.complexity} task`,agentType:"chat",winner:c.winner,winnerScore:c.score,winnerReason:(l=d.find(g=>g.provider===p))==null?void 0:l.reason,candidates:d,exclusions:h})}return r}function _ae(e,t){switch(e){case"request":return`A ${t.complexity} task arrives${t.source?` from ${d0(t.source)}`:""} and must be routed.`;case"candidates":return`${t.candidates.length} provider${t.candidates.length!==1?"s":""} are scored against the ${t.complexity} weight profile.`;case"exclusions":return t.exclusions.length>0?`${t.exclusions.length} provider${t.exclusions.length!==1?"s":""} known to the system are skipped before scoring.`:"Every known provider was scored — nothing was skipped.";case"pick":return t.winnerReason?`The top score wins: ${t.winner.split("/")[0]} ranked first — ${t.winnerReason}.`:`The top score wins: ${t.winner}.`}}function Nae({value:e,color:t}){const n=Math.min(100,Math.max(0,e*100));return s.jsx("div",{style:{flex:1,background:"#0d1117",borderRadius:4,height:6,overflow:"hidden",border:"1px solid #21262d"},children:s.jsx("div",{style:{width:`${n}%`,background:t,height:"100%",transition:"width 0.4s ease"}})})}function jae({icon:e,title:t,narration:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:10,marginBottom:14},children:[s.jsx("span",{style:{fontSize:20,lineHeight:"24px"},children:e}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#e6edf3"},children:t}),s.jsx("div",{style:{fontSize:12,color:"#8b949e",marginTop:2},children:n})]})]})}function Aae({routing:e}){const t=E.useMemo(()=>Eae(e),[e]),[n,r]=E.useState(""),[i,a]=E.useState(0),[o,l]=E.useState(!1);if(E.useEffect(()=>{t.length!==0&&(t.some(p=>p.id===n)||(r(t[0].id),a(0)))},[t,n]),E.useEffect(()=>{if(!o||t.length===0)return;const p=setInterval(()=>{a(g=>(g+1)%ka.length)},wae);return()=>clearInterval(p)},[o,t.length]),t.length===0)return null;const c=t.find(p=>p.id===n)??t[0],u=ka[i],d=()=>{a(p=>(p+ka.length-1)%ka.length),l(!1)},f=()=>{a(p=>(p+1)%ka.length),l(!1)},h=()=>l(p=>!p);return s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:"1px solid #21262d",padding:"18px 20px",marginBottom:16},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:4},children:[s.jsx("span",{style:{fontSize:20},children:"🎬"}),s.jsx("h3",{style:{fontSize:15,fontWeight:600,color:"#e6edf3",margin:0},children:"Why did the router pick this?"}),c.real&&s.jsx("span",{style:{fontSize:11,padding:"1px 8px",borderRadius:10,background:"#12291a",border:"1px solid #238636",color:"#3fb950"},children:"✓ real decision"})]}),s.jsx("p",{style:{fontSize:12,color:"#8b949e",margin:"2px 0 12px 0"},children:"Narrated step-by-step replay of a routing decision — request, candidates, exclusions, and the pick. Scrubbable, or hit play."}),s.jsx("select",{"aria-label":"Routing decision to replay",value:n,onChange:p=>{r(p.target.value),a(0),l(!1)},style:{width:"100%",marginBottom:16,padding:"8px 10px",background:"#0d1117",color:"#e6edf3",fontSize:12,border:"1px solid #30363d",borderRadius:8,outline:"none"},children:t.map(p=>s.jsxs("option",{value:p.id,style:{background:"#0d1117",color:"#e6edf3"},children:[p.real?"● ":"○ ",p.label]},p.id))}),s.jsx(jae,{icon:u.icon,title:`${i+1}. ${u.title}${i>0?` — ${c.complexity}`:""}`,narration:_ae(u.key,c)}),u.key==="request"&&s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"14px 16px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",marginBottom:8},children:[s.jsxs("span",{style:{fontSize:12,padding:"2px 10px",borderRadius:12,background:"#161b22",border:"1px solid #30363d",color:"#e6edf3"},children:[bae[c.complexity]||"•"," ",tM[c.complexity]||c.complexity]}),s.jsxs("span",{style:{fontSize:12,padding:"2px 10px",borderRadius:12,background:"#161b22",border:"1px solid #30363d",color:"#8b949e"},children:["🤖 ",c.agentType]}),c.source&&s.jsx("span",{style:{fontSize:12,padding:"2px 10px",borderRadius:12,background:"#161b22",border:"1px solid #30363d",color:"#8b949e"},children:d0(c.source)}),c.timestamp&&s.jsx("span",{style:{fontSize:11,color:"#6e7681",marginLeft:"auto"},children:Sae(c.timestamp)})]}),s.jsx("div",{style:{fontSize:13,color:"#e6edf3"},children:c.task})]}),u.key==="candidates"&&s.jsxs("div",{children:[c.candidates.map((p,g)=>{const m=p.provider===c.winner.split("/")[0];return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",background:m?"#12291a":"#0d1117",border:`1px solid ${m?"#238636":"#21262d"}`,borderRadius:8,marginBottom:6},children:[s.jsxs("span",{style:{width:18,fontSize:11,color:"#6e7681",textAlign:"right"},children:[g+1,"."]}),s.jsxs("span",{style:{width:104,color:m?"#3fb950":"#e6edf3",fontWeight:m?600:400,whiteSpace:"nowrap",fontSize:12},children:[ng(p.provider)," ",c_(p.provider).split(" ")[0],m&&" 👑"]}),s.jsx(Nae,{value:p.score,color:m?"#3fb950":"#58a6ff"}),s.jsx("span",{style:{width:44,textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:11,color:"#8b949e"},children:p.score.toFixed(3)})]},p.provider)}),c.candidates.length>0&&s.jsxs("div",{style:{marginTop:10},children:[s.jsx("div",{style:{fontSize:11,color:"#6e7681",marginBottom:4},children:"Why each ranked where it did"}),c.candidates.map(p=>s.jsxs("div",{style:{fontSize:12,color:"#8b949e",marginBottom:3},children:[s.jsx("span",{style:{color:"#e6edf3"},children:p.provider}),": ",p.reason||"scored"]},p.provider))]})]}),u.key==="exclusions"&&(c.exclusions.length>0?s.jsx("div",{children:c.exclusions.map(p=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",background:"#0d1117",border:"1px solid #21262d",borderRadius:8,marginBottom:6},children:[s.jsx("span",{style:{fontSize:13},children:"🚫"}),s.jsxs("span",{style:{width:110,color:"#e6edf3",whiteSpace:"nowrap",fontSize:12},children:[ng(p.provider)," ",c_(p.provider).split(" ")[0]]}),s.jsx("span",{style:{flex:1,fontSize:12,color:"#8b949e"},children:p.reason})]},p.provider))}):s.jsx("div",{style:{background:"#0d1117",border:"1px dashed #30363d",borderRadius:10,padding:"14px 16px",color:"#8b949e",fontSize:13},children:"✅ No exclusions — every provider known to the system was scored for this decision."})),u.key==="pick"&&s.jsxs("div",{style:{background:"#12291a",border:"1px solid #238636",borderRadius:10,padding:"16px 18px"},children:[s.jsx("div",{style:{fontSize:12,color:"#3fb950",fontWeight:600,marginBottom:6},children:"🏆 ROUTER PICK"}),s.jsxs("div",{style:{fontSize:16,fontWeight:700,color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace",marginBottom:4},children:[ng(c.winner.split("/")[0])," ",c.winner]}),s.jsxs("div",{style:{fontSize:12,color:"#8b949e",marginBottom:10},children:["composite score ",s.jsx("span",{style:{fontFamily:"'SFMono-Regular', Consolas, monospace",color:"#3fb950"},children:c.winnerScore.toFixed(3)}),!c.real&&" · profile preview"]}),c.winnerReason&&s.jsxs("div",{style:{fontSize:12,color:"#8b949e",borderTop:"1px solid #23863655",paddingTop:8},children:[s.jsx("span",{style:{color:"#e6edf3"},children:"Why:"})," ",c.winnerReason]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginTop:16},children:[s.jsx("button",{onClick:d,"aria-label":"Previous step",style:rg,children:"◀"}),s.jsx("button",{onClick:h,"aria-label":o?"Pause playback":"Play playback",style:{...rg,minWidth:84,color:o?"#d29922":"#3fb950"},children:o?"⏸ Pause":"▶ Play"}),s.jsx("button",{onClick:f,"aria-label":"Next step",style:rg,children:"▶"}),s.jsx("div",{style:{display:"flex",gap:6,marginLeft:8},children:ka.map((p,g)=>s.jsx("button",{"aria-label":`Go to step ${g+1}: ${p.title}`,onClick:()=>{a(g),l(!1)},style:{width:22,height:22,borderRadius:11,border:"none",cursor:"pointer",fontSize:10,lineHeight:"22px",padding:0,background:g===i?"#58a6ff":"#21262d",color:g===i?"#0d1117":"#8b949e"},title:p.title,children:p.icon},p.key))}),s.jsxs("span",{style:{marginLeft:"auto",fontSize:11,color:"#6e7681"},children:["step ",i+1,"/",ka.length]})]})]})}const rg={background:"#21262d",color:"#e6edf3",border:"1px solid #30363d",borderRadius:8,padding:"6px 12px",fontSize:13,cursor:"pointer",transition:"background 0.15s"},Tae={local:"💻",groq:"🟢",nim:"🔶",gemini:"🔷",openrouter:"🟣"},Cae={local:"Ollama (Local)",groq:"Groq",nim:"NVIDIA NIM",gemini:"Gemini",openrouter:"OpenRouter"},nM={trivial:"🟢",simple:"🔵",moderate:"🟡",complex:"🟠",critical:"🔴"};function Nr(e){return Tae[e]||"🔌"}function sa(e){return Cae[e]||e}function yh(e,t=1){return`${(e*100).toFixed(t)}%`}function Oae(e){return`$${e.toFixed(6)}`}function Yn({icon:e,title:t,subtitle:n,children:r}){return s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:"1px solid #21262d",padding:"18px 20px",marginBottom:16},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:4},children:[s.jsx("span",{style:{fontSize:20},children:e}),s.jsx("h3",{style:{fontSize:15,fontWeight:600,color:"#e6edf3",margin:0},children:t})]}),n&&s.jsx("p",{style:{fontSize:12,color:"#8b949e",margin:"2px 0 12px 0"},children:n}),!n&&s.jsx("div",{style:{height:6}}),r]})}function f0({value:e,color:t}){const n=Math.min(100,Math.max(0,e*100));return s.jsx("div",{style:{flex:1,background:"#0d1117",borderRadius:4,height:6,overflow:"hidden",border:"1px solid #21262d"},children:s.jsx("div",{style:{width:`${n}%`,background:t,height:"100%",transition:"width 0.4s ease"}})})}function eo(e,t,n="#8b949e"){return{fontSize:10,padding:"1px 7px",borderRadius:9,background:e,border:`1px solid ${t}`,color:n,fontFamily:"'SFMono-Regular', Consolas, monospace",whiteSpace:"nowrap"}}function Pae(){return s.jsxs("div",{style:{background:"#0d1117",border:"1px dashed #30363d",borderRadius:10,padding:"18px 20px",color:"#8b949e",fontSize:13,textAlign:"center"},children:["📊 No routing data yet — run ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff benchmark"})," to populate provider quality scores, or use Auto routing (",s.jsx("code",{style:{color:"#58a6ff"},children:"buff model switch auto"}),") to build per-agent best-model stats over time."]})}const Mae={chat:"💬 chat",orchestrator:"🔀 orchestrator",explain:"🔍 explain",benchmark:"📈 benchmark",eval:"🎯 eval"},Rae={trivial:"🟢 trivial",simple:"🔵 simple",moderate:"🟡 moderate",complex:"🟠 complex",critical:"🔴 critical"};function rM(e){return Mae[e]||e}function iM(e){const t=Date.now()-e;return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`}function f_(e){if(e<=0)return"now";const t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4);return t>0?`${t}h ${n}m`:n>0?`${n}m`:`${Math.ceil(e/1e3)}s`}function Iae({label:e,value:t,total:n,color:r}){const i=n>0?t/n*100:0;return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:5},children:[s.jsx("span",{style:{width:110,color:"#e6edf3",whiteSpace:"nowrap",fontSize:12},children:e}),s.jsx("div",{style:{flex:1,background:"#0d1117",borderRadius:4,height:6,overflow:"hidden",border:"1px solid #21262d"},children:s.jsx("div",{style:{width:`${Math.min(100,i)}%`,background:r,height:"100%",transition:"width 0.4s ease"}})}),s.jsx("span",{style:{width:34,textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:11,color:"#8b949e"},children:t})]})}function $ae({usage:e}){if(!e.total)return null;const t=e.total,n=Object.entries(e.byProvider).sort((i,a)=>a[1]-i[1]).slice(0,6),r=Object.entries(e.byModel).sort((i,a)=>a[1]-i[1]).slice(0,5);return s.jsxs(Yn,{icon:"🧮",title:"Routing Usage — actual picks over time",subtitle:"Recorded from live chat, orchestrator runs, explain snapshots, benchmark --routing, and eval --routing",children:[s.jsxs("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginBottom:14},children:[s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:e.total}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"total decisions"})]}),s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:e.last24h>0?"#3fb950":"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:e.last24h}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"last 24h"})]})]}),s.jsx("div",{style:{fontSize:12,color:"#8b949e",marginBottom:6},children:"By provider"}),n.map(([i,a])=>s.jsx(Iae,{label:`${Nr(i)} ${sa(i).split(" ")[0]}`,value:a,total:t,color:"#58a6ff"},i)),Object.keys(e.bySource).length>0&&s.jsx("div",{style:{marginTop:12,display:"flex",gap:6,flexWrap:"wrap"},children:Object.entries(e.bySource).sort((i,a)=>a[1]-i[1]).map(([i,a])=>s.jsxs("span",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:20,padding:"3px 10px",fontSize:11,color:"#e6edf3"},children:[rM(i)," · ",a]},i))}),r.length>0&&s.jsxs("div",{style:{marginTop:14},children:[s.jsx("div",{style:{fontSize:12,color:"#8b949e",marginBottom:6},children:"Most-picked models"}),r.map(([i,a])=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:5},children:[s.jsx("span",{style:{flex:1,color:"#e6edf3",fontSize:12,fontFamily:"'SFMono-Regular', Consolas, monospace",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},title:i,children:i.length>42?i.slice(0,39)+"…":i}),s.jsx("span",{style:{width:34,textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:11,color:"#8b949e"},children:a})]},i))]})]})}function Lae({history:e}){return e.length?s.jsx(Yn,{icon:"🕓",title:"Audit Trail — routing decision timeline",subtitle:"Every explain snapshot (and routing-mode pick) persisted for transparency",children:s.jsx("div",{style:{maxHeight:320,overflowY:"auto",paddingRight:4},children:e.map(t=>s.jsxs("div",{style:{display:"flex",gap:10,padding:"8px 4px",borderBottom:"1px solid #21262d"},children:[s.jsx("div",{style:{width:52,flexShrink:0,fontSize:11,color:"#6e7681",paddingTop:2},children:iM(t.timestamp)}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[s.jsx("span",{style:{fontSize:11,padding:"1px 8px",borderRadius:10,background:"#0d1117",border:"1px solid #30363d",color:"#8b949e"},children:rM(t.source)}),s.jsxs("span",{style:{fontSize:12,fontWeight:600,color:"#3fb950",fontFamily:"'SFMono-Regular', Consolas, monospace",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},title:`${t.provider}/${t.model}`,children:[Nr(t.provider)," ",t.provider,"/",t.model.length>26?t.model.slice(0,23)+"…":t.model]}),t.complexity&&s.jsx("span",{style:{fontSize:11,color:"#6e7681"},children:Rae[t.complexity]||t.complexity})]}),s.jsx("div",{style:{fontSize:12,color:"#8b949e",marginTop:3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:t.task,children:t.task||t.agentType})]})]},t.id))})}):null}function Dae({routing:e}){return e.preference.length?s.jsx(Yn,{icon:"🤖",title:"Auto Router — What the agent would pick",subtitle:"Complexity-weighted scoring across reasoning, speed, cost, privacy, and reliability (real provider pricing)",children:s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid #21262d",color:"#8b949e"},children:[s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Complexity"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Winner"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Score"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"All providers"})]})}),s.jsx("tbody",{children:e.preference.map(t=>s.jsxs("tr",{style:{borderBottom:"1px solid #21262d"},children:[s.jsxs("td",{style:{padding:"10px 12px",color:"#e6edf3",whiteSpace:"nowrap"},children:[nM[t.complexity]||"•"," ",t.complexity]}),s.jsx("td",{style:{padding:"10px 12px",whiteSpace:"nowrap"},children:s.jsxs("span",{style:{color:"#3fb950",fontWeight:600},children:[Nr(t.winner.split("/")[0])," ",t.winner]})}),s.jsx("td",{style:{padding:"10px 12px",fontFamily:"'SFMono-Regular', Consolas, monospace",color:"#8b949e"},children:t.score.toFixed(3)}),s.jsx("td",{style:{padding:"10px 12px",minWidth:300},children:t.providers.map((n,r)=>s.jsxs("div",{style:{marginBottom:5},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsxs("span",{style:{width:16,fontSize:11,color:"#6e7681",textAlign:"right"},children:[r+1,"."]}),s.jsxs("span",{style:{width:90,color:"#e6edf3",whiteSpace:"nowrap",fontSize:12},children:[Nr(n.provider)," ",sa(n.provider).split(" ")[0]]}),s.jsx(f0,{value:n.score,color:r===0?"#3fb950":"#58a6ff"}),s.jsx("span",{style:{width:40,textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:11,color:"#8b949e"},children:n.score.toFixed(2)})]}),(n.capabilityFit!==void 0||n.costSource||n.contextUtilization!==void 0)&&s.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",paddingLeft:16,marginTop:2},children:[n.capabilityFit!==void 0&&s.jsxs("span",{style:eo("#1c2128","#6e7681"),children:["🎯 fit ",n.capabilityFit,"%"]}),n.costSource==="measured"&&n.costBasis?s.jsxs("span",{style:eo("#12291a","#3fb950","#3fb950"),children:["📏 measured ",n.costBasis.inputTokens.toLocaleString(),"→",n.costBasis.outputTokens.toLocaleString()," tok"]}):s.jsx("span",{style:eo("#1c2128","#8b949e"),children:"📐 estimated"}),n.contextUtilization!==void 0&&n.contextWindowTokens!==void 0&&s.jsxs("span",{style:eo("#1c2128","#58a6ff","#58a6ff"),children:["⏳ ctx ",n.contextUtilization,"% (",n.contextWindowTokens.toLocaleString()," tok)"]})]})]},n.provider))})]},t.complexity))})]})})}):null}function Bae({routing:e}){return e.providers.length?s.jsx(Yn,{icon:"📈",title:"Provider Benchmark Quality",subtitle:"Measured from your own `buff benchmark` runs — blended into Auto routing decisions",children:s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid #21262d",color:"#8b949e"},children:[s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Provider"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Runs"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Avg Quality"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Pass Rate"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Total Cost"})]})}),s.jsx("tbody",{children:e.providers.map(t=>s.jsxs("tr",{style:{borderBottom:"1px solid #21262d"},children:[s.jsxs("td",{style:{padding:"10px 12px",color:"#e6edf3",whiteSpace:"nowrap"},children:[Nr(t.provider)," ",sa(t.provider)]}),s.jsx("td",{style:{padding:"10px 12px",color:"#8b949e"},children:t.runs}),s.jsx("td",{style:{padding:"10px 12px"},children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx(f0,{value:t.avgQuality,color:"#58a6ff"}),s.jsx("span",{style:{fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12,color:"#8b949e",width:44,textAlign:"right"},children:yh(t.avgQuality)})]})}),s.jsx("td",{style:{padding:"10px 12px",color:t.passRate>=.8?"#3fb950":"#d29922"},children:yh(t.passRate)}),s.jsx("td",{style:{padding:"10px 12px",fontFamily:"'SFMono-Regular', Consolas, monospace",color:"#8b949e"},children:Oae(t.totalCostUsd)})]},t.provider))})]})})}):null}const h_=["trivial","simple","moderate","complex","critical"];function zae(e){return e>=.7?"#3fb950":e>=.45?"#d29922":"#f85149"}function Fae({bandit:e}){const t=Object.keys(e.priors).sort();if(!e.enabled||t.length===0)return null;const n=e.learningHistory.slice(-15).reverse();return s.jsxs(Yn,{icon:"🎰",title:"Bandit Learning — Thompson-sampling priors",subtitle:"Beta(α, β) per provider × complexity bucket, learned from real task outcomes (routing.bandit = true). Higher expected win rate = more successful history.",children:[s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:12},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid #21262d",color:"#8b949e"},children:[s.jsx("th",{style:{padding:"8px 10px",textAlign:"left",fontWeight:500},children:"Provider"}),h_.map(r=>s.jsxs("th",{style:{padding:"8px 10px",textAlign:"center",fontWeight:500},children:[nM[r]||"•"," ",r]},r))]})}),s.jsx("tbody",{children:t.map(r=>s.jsxs("tr",{style:{borderBottom:"1px solid #21262d"},children:[s.jsxs("td",{style:{padding:"8px 10px",color:"#e6edf3",whiteSpace:"nowrap"},children:[Nr(r)," ",sa(r).split(" ")[0]]}),h_.map(i=>{var o;const a=(o=e.priors[r])==null?void 0:o[i];return!a||a.alpha===0&&a.beta===0?s.jsx("td",{style:{padding:"8px 10px",textAlign:"center",color:"#6e7681"},children:"·"},i):s.jsxs("td",{style:{padding:"8px 10px",textAlign:"center"},children:[s.jsxs("div",{style:{fontSize:13,fontWeight:600,color:zae(a.expectedWinRate),fontFamily:"'SFMono-Regular', Consolas, monospace"},children:[(a.expectedWinRate*100).toFixed(0),"%"]}),s.jsxs("div",{style:{fontSize:10,color:"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:["α",a.alpha," β",a.beta]})]},i)})]},r))})]})}),n.length>0&&s.jsxs("div",{style:{marginTop:16},children:[s.jsx("div",{style:{fontSize:12,color:"#8b949e",marginBottom:8},children:"Recent learning history"}),s.jsx("div",{style:{maxHeight:180,overflowY:"auto",paddingRight:4},children:n.map((r,i)=>{const a=r.outcome==="success"?"✅":r.outcome==="escalated"?"🔄":"❌",o=new Date(r.timestamp).toLocaleTimeString();return s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",padding:"5px 4px",borderBottom:"1px solid #21262d"},children:[s.jsx("span",{children:a}),s.jsx("span",{style:{color:"#e6edf3",fontSize:12,width:110,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},title:r.provider,children:r.provider}),s.jsx("span",{style:{fontSize:11,color:"#6e7681",width:80},children:r.complexity}),s.jsxs("span",{style:{fontSize:11,color:"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:["reward ",r.reward.toFixed(2)]}),s.jsx("span",{style:{fontSize:11,color:"#6e7681",marginLeft:"auto"},children:o})]},i)})})]}),s.jsxs("div",{style:{fontSize:11,color:"#6e7681",marginTop:12},children:["Cold-start Beta(1,1) behaves like the heuristic router until outcomes accumulate. Enable learning with ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff config set routing.bandit true"}),"."]})]})}function Uae(e,t=1){return`${e>0?"+":""}${(e*100).toFixed(t)}%`}function Wae({state:e}){const t={pass:{bg:"#12291a",border:"#238636",color:"#3fb950",label:"✓ pass"},fail:{bg:"#2d1616",border:"#f85149",color:"#f85149",label:"✗ fail"},neutral:{bg:"#1c2128",border:"#6e7681",color:"#8b949e",label:"○ neutral"}}[e];return s.jsx("span",{style:{fontSize:11,padding:"1px 8px",borderRadius:10,background:t.bg,border:`1px solid ${t.border}`,color:t.color},children:t.label})}function Hae({promotion:e}){if(!e.decisionCount)return null;const t=e.promoted?{icon:"🎖️",label:"Promoted — the bandit beats the heuristic",color:"#3fb950"}:e.sufficient?{icon:"⚠️",label:"Not promoted — the bandit is not (yet) better",color:"#d29922"}:{icon:"⏳",label:"Collecting data — need more diverged decisions",color:"#58a6ff"},n=e.minDecisions>0?Math.min(100,Math.round(e.divergedCount/e.minDecisions*100)):0,r=[{key:"quality",label:"Quality ↑",delta:e.qualityDelta,state:e.criteria.quality?"pass":"fail",note:"needs > +2%"},{key:"cost",label:"Cost ↓",delta:e.costDelta,state:e.criteria.cost?"pass":"fail",note:"regression < +1%"},{key:"latency",label:"Latency ↓",delta:e.latencyDelta,state:e.latencyMeasured?e.criteria.latency?"pass":"fail":"neutral",note:e.latencyMeasured?"regression < +5%":"no latency measurements yet"}];return s.jsxs(Yn,{icon:"🎖️",title:"Promotion Gate — is the bandit better than the heuristic?",subtitle:"A/B verdict from real trajectories (router-promotion.jsonl): quality must improve >2% while cost and latency don't regress (ruflo ADR-150)",children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:14},children:[s.jsx("span",{style:{fontSize:22},children:t.icon}),s.jsx("span",{style:{fontSize:14,fontWeight:600,color:t.color},children:t.label})]}),s.jsxs("div",{style:{marginBottom:14},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:11,color:"#8b949e",marginBottom:5},children:[s.jsxs("span",{children:[e.divergedCount," diverged decisions"]}),s.jsxs("span",{children:["need ",e.minDecisions," for a verdict"]})]}),s.jsx("div",{style:{background:"#0d1117",borderRadius:4,height:8,overflow:"hidden",border:"1px solid #21262d"},children:s.jsx("div",{style:{width:`${n}%`,background:e.sufficient?"#3fb950":"#58a6ff",height:"100%",transition:"width 0.4s ease"}})}),s.jsxs("div",{style:{fontSize:11,color:"#6e7681",marginTop:4},children:[e.decisionCount," total decisions logged"]})]}),r.map(i=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"7px 0",borderBottom:"1px solid #21262d"},children:[s.jsx("span",{style:{width:70,fontSize:12,color:"#e6edf3"},children:i.label}),s.jsx("span",{style:{width:92,fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12,color:"#8b949e"},children:Uae(i.delta)}),s.jsx("span",{style:{fontSize:11,color:"#6e7681",flex:1},children:i.note}),s.jsx(Wae,{state:i.state})]},i.key)),s.jsxs("div",{style:{fontSize:11,color:"#6e7681",marginTop:12},children:["Run auto-routed tasks with ",s.jsx("code",{style:{color:"#58a6ff"},children:"routing.bandit true"})," to accumulate A/B decisions. The gate does not disable the bandit — it tells you whether it's actually winning."]})]})}function Gae({ml:e}){if(!e.enabled||e.recordCount===0)return null;const t=e.providers.filter(r=>r.trusted),n=e.providers.filter(r=>!r.trusted);return s.jsxs(Yn,{icon:"🧠",title:"ML Router — learned from similar tasks",subtitle:"Task-feature kNN (ruflo neural-router analog): outcomes of the most similar PAST tasks nudge each provider's score. Win rate is similarity-weighted; factor = 1 + 0.5 × (winRate − 0.5), trusted only after 5 similar-task samples.",children:[s.jsxs("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginBottom:14},children:[s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:e.recordCount.toLocaleString()}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"learned tasks"})]}),s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #238636",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:"#3fb950",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:t.length}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"trusted providers"})]}),s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #d29922",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:"#d29922",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:n.length}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"still learning"})]})]}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:e.providers.map(r=>s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"10px 14px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6},children:[s.jsx("span",{children:Nr(r.provider)}),s.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#e6edf3"},children:sa(r.provider)}),r.trusted?s.jsxs("span",{style:eo("#3fb95026","#238636","#3fb950"),children:["trusted · ",r.samples," samples"]}):s.jsxs("span",{style:eo("#d2992226","#9e6a03","#d29922"),children:[r.samples,"/5 samples"]}),r.model&&s.jsx("span",{style:{fontSize:11,color:"#6e7681",fontFamily:"'SFMono-Regular', Consolas, monospace",marginLeft:"auto"},children:r.model.length>30?r.model.slice(0,27)+"…":r.model})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[s.jsxs("div",{style:{width:70,fontSize:11,color:"#8b949e"},children:["win ",yh(r.winRate,0)]}),s.jsx(f0,{value:r.winRate,color:r.winRate>=.5?"#3fb950":"#f85149"}),s.jsxs("div",{style:{width:74,fontSize:11,color:"#8b949e",textAlign:"right"},children:["factor ",s.jsxs("span",{style:{color:r.trusted&&r.factor!==1?"#58a6ff":"#6e7681",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:[r.factor.toFixed(2),"×"]})]})]})]},r.provider))}),s.jsxs("div",{style:{fontSize:11,color:"#6e7681",marginTop:12},children:["Enabled with ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff config set routing.mlRouter true"})," — the factor only adjusts scores when the provider has ≥ 5 similar-task wins (cold start is neutral)."]})]})}function qae({routing:e}){return e.bestModels.length?s.jsx(Yn,{icon:"🏆",title:"Best Model per Agent (from your runs)",subtitle:"Success-rate-ranked models from agent-stats — the Auto router boosts the proven winner",children:s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:10},children:e.bestModels.map(t=>s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 14px",minWidth:200,flex:"1 1 200px",transition:"border-color 0.2s, box-shadow 0.2s"},onMouseEnter:n=>{n.currentTarget.style.borderColor="#3fb950",n.currentTarget.style.boxShadow="0 2px 10px #3fb95022"},onMouseLeave:n=>{n.currentTarget.style.borderColor="#21262d",n.currentTarget.style.boxShadow="none"},children:[s.jsxs("div",{style:{fontSize:12,color:"#8b949e",marginBottom:4},children:[Nr(t.model.split("/")[0])," ",t.agentType]}),s.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},title:t.model,children:t.model.length>34?t.model.slice(0,31)+"…":t.model}),s.jsxs("div",{style:{fontSize:11,color:"#6e7681",marginTop:6},children:[s.jsxs("span",{style:{color:t.successRate>=.8?"#3fb950":"#d29922"},children:[yh(t.successRate,0)," success"]})," · ",t.runs," run",t.runs!==1?"s":""]})]},`${t.agentType}-${t.model}`))})}):null}function Kae({retrieval:e}){var l,c;if(!e.enabled&&e.repoChunks===0)return null;const t=e.totalSavedTokens??0,n=e.avgPctReduced??0,r=e.lastCall,i=e.totalCalls??0,a=e.totalRetrievals??0,o=e.totalFailovers??0;return s.jsxs(Yn,{icon:"🧠",title:"Vector Retrieval — token savings",subtitle:"Large contexts are chunked, embedded locally (bge-small-en-v1.5), and reduced to the top-k relevant chunks before the LLM — saving tokens so free quotas stretch further. Complements the quota ledger: retrieval saves, the ledger manages.",children:[s.jsxs("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginBottom:14},children:[s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #238636",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:"#3fb950",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:t.toLocaleString()}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"tokens saved"})]}),s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsxs("div",{style:{fontSize:22,fontWeight:700,color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:[n.toFixed(1),"%"]}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"avg context reduction"})]}),s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #d29922",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:"#d29922",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:e.repoChunks.toLocaleString()}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"repo chunks indexed"})]})]}),s.jsxs("div",{style:{display:"flex",gap:20,flexWrap:"wrap",fontSize:12,color:"#8b949e",marginBottom:14},children:[s.jsxs("span",{children:["📞 ",i," context calls · 🧠 ",a," retrievals used · ⚠️ ",o," failovers (full-context fallback)"]}),e.dimensions>0&&s.jsxs("span",{children:["· ",e.dimensions,"-dim embeddings"]})]}),r&&r.used!==!1&&((l=r.hits)==null?void 0:l.length)>0&&s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 16px",marginBottom:12},children:[s.jsxs("div",{style:{fontSize:12,fontWeight:600,color:"#e6edf3",marginBottom:8},children:["Latest retrieval — ",r.originalTokens.toLocaleString()," → ",r.reducedTokens.toLocaleString()," tokens",s.jsxs("span",{style:{color:"#3fb950",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:[" (−",(c=r.pctReduced)==null?void 0:c.toFixed(0),"%)"]})]}),s.jsx("div",{style:{fontSize:11,color:"#8b949e"},children:r.hits.slice(0,5).map(u=>s.jsxs("div",{style:{marginTop:3},children:[s.jsx("span",{style:{color:"#58a6ff"},children:"▸"})," ",u.filePath," ",s.jsxs("span",{style:{fontFamily:"'SFMono-Regular', Consolas, monospace"},children:["(sim ",u.similarity.toFixed(3),")"]})]},u.filePath))})]}),s.jsxs("div",{style:{fontSize:11,color:"#6e7681"},children:["Pre-index your repo with ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff retrieval index <dir>"}),", query it with"," ",s.jsx("code",{style:{color:"#58a6ff"},children:'buff retrieval query "<question>"'}),", and see the same stats with"," ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff retrieval stats"}),"."]})]})}function Vae({quota:e}){var c;if((!e.enabled||e.entries.length===0)&&(((c=e.events)==null?void 0:c.length)??0)===0)return null;const t=e.entries.reduce((u,d)=>u+d.tokensConsumed,0),n=e.entries.reduce((u,d)=>u+d.requests,0),r=e.entries.filter(u=>u.parked).length,i=e.freeTokens??t-(e.paidTokens??0),a=e.paidTokens??0,o=e.estimatedSavedUsd??0,l=t>0?i/t*100:0;return s.jsxs(Yn,{icon:"📒",title:"Quota Ledger — free-tier usage & auto re-enable",subtitle:"Tokens/requests per provider × model with reset windows. Exhausted providers are parked (excluded from Auto routing) and re-enable when the window rolls.",children:[s.jsxs("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginBottom:14},children:[s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:t.toLocaleString()}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"tokens tracked"})]}),s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:n}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"requests"})]}),s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:r>0?"#d29922":"#3fb950",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:r}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"parked"})]})]}),s.jsxs("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginBottom:16},children:[s.jsxs("div",{style:{flex:"1 1 200px",background:"#0d1117",borderRadius:10,padding:"12px 16px",border:"1px solid #238636"},children:[s.jsx("div",{style:{fontSize:20,fontWeight:700,color:"#3fb950",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:i.toLocaleString()}),s.jsxs("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:["tokens on free/local · ",l.toFixed(0),"% of usage"]}),s.jsxs("div",{style:{fontSize:12,color:"#3fb950",marginTop:4,fontFamily:"'SFMono-Regular', Consolas, monospace"},children:["💰 est. $",o.toFixed(4)," saved"]})]}),s.jsxs("div",{style:{flex:"1 1 200px",background:"#0d1117",borderRadius:10,padding:"12px 16px",border:"1px solid #d29922"},children:[s.jsx("div",{style:{fontSize:20,fontWeight:700,color:a>0?"#d29922":"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:a.toLocaleString()}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"tokens on paid providers (spend triggered)"}),s.jsxs("div",{style:{fontSize:12,color:a>0?"#d29922":"#8b949e",marginTop:4},children:[e.paidRequests??0," paid request",e.paidRequests===1?"":"s"]})]})]}),s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:12},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid #21262d",color:"#8b949e"},children:[s.jsx("th",{style:{padding:"8px 10px",textAlign:"left",fontWeight:500},children:"Provider / Model"}),s.jsx("th",{style:{padding:"8px 10px",textAlign:"right",fontWeight:500},children:"Tokens"}),s.jsx("th",{style:{padding:"8px 10px",textAlign:"right",fontWeight:500},children:"Requests"}),s.jsx("th",{style:{padding:"8px 10px",textAlign:"right",fontWeight:500},children:"Resets in"}),s.jsx("th",{style:{padding:"8px 10px",textAlign:"center",fontWeight:500},children:"State"})]})}),s.jsx("tbody",{children:e.entries.map(u=>s.jsxs("tr",{style:{borderBottom:"1px solid #21262d"},children:[s.jsxs("td",{style:{padding:"8px 10px",whiteSpace:"nowrap"},children:[s.jsxs("span",{style:{color:"#e6edf3"},children:[Nr(u.provider)," ",sa(u.provider).split(" ")[0]]}),s.jsxs("span",{style:{color:"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:[" / ",u.model.length>24?u.model.slice(0,21)+"…":u.model]})]}),s.jsx("td",{style:{padding:"8px 10px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",color:"#8b949e"},children:u.tokensConsumed.toLocaleString()}),s.jsx("td",{style:{padding:"8px 10px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",color:"#8b949e"},children:u.requests}),s.jsx("td",{style:{padding:"8px 10px",textAlign:"right",color:"#8b949e",whiteSpace:"nowrap"},children:f_(u.resetsInMs)}),s.jsx("td",{style:{padding:"8px 10px",textAlign:"center"},children:u.parked?s.jsx("span",{style:{fontSize:11,padding:"1px 8px",borderRadius:10,background:"#2d1616",border:"1px solid #f85149",color:"#f85149"},children:"⏸ parked"}):s.jsx("span",{style:{fontSize:11,padding:"1px 8px",borderRadius:10,background:"#12291a",border:"1px solid #238636",color:"#3fb950"},children:"✓ available"})})]},`${u.provider}|${u.model}`))})]})}),s.jsxs("div",{style:{fontSize:11,color:"#6e7681",marginTop:12},children:["Configure limits with ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff config set routing.quota.gemini.requestsPerWindow 1500"}),"; the ledger always tracks usage but only parks when limits are set."]}),e.parkedAccounts&&e.parkedAccounts.length>0&&s.jsxs("div",{style:{marginTop:18},children:[s.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e6edf3",marginBottom:10},children:"🔑 Parked Accounts — multi-account key rotation"}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginBottom:8},children:"Accounts skipped predictively by the failover walk (rate-limit / auth). Fingerprints only — raw keys are never stored."}),s.jsx("div",{style:{maxHeight:180,overflowY:"auto",background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"8px 0"},children:e.parkedAccounts.map((u,d)=>{const f=u.reason==="auth"?"auth":u.reason==="rate-limit"?"rate-limit":u.reason||"cooldown",h=u.reason==="rate-limit"?"#d29922":"#f85149";return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 14px",borderBottom:d<e.parkedAccounts.length-1?"1px solid #161b22":"none"},children:[s.jsx("span",{style:{fontSize:13},children:"🔒"}),s.jsxs("span",{style:{width:90,flexShrink:0,fontSize:12,color:"#e6edf3"},children:[Nr(u.provider)," ",sa(u.provider).split(" ")[0]]}),s.jsxs("span",{style:{fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:11,color:"#8b949e"},title:u.accountId,children:["#",u.accountId.slice(0,8)]}),s.jsx("span",{style:{fontSize:11,padding:"1px 8px",borderRadius:10,background:"#161b22",border:`1px solid ${h}`,color:h,textAlign:"center"},children:f}),s.jsx("span",{style:{flex:1}}),s.jsxs("span",{style:{fontSize:11,color:"#6e7681",whiteSpace:"nowrap"},children:["re-admits in ",f_(u.remainingMs)]})]},`${u.provider}-${u.accountId}-${d}`)})})]}),e.events&&e.events.length>0&&s.jsxs("div",{style:{marginTop:18},children:[s.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e6edf3",marginBottom:10},children:"🛟 Failover Timeline — quota management & mid-session swaps"}),s.jsx("div",{style:{maxHeight:220,overflowY:"auto",background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"8px 0"},children:e.events.map((u,d)=>{const f=u.type==="parked"?"⏸":u.type==="re-enabled"?"🔁":u.type==="released"?"✅":"⚡",h=u.type==="parked"?"#f85149":u.type==="re-enabled"||u.type==="released"?"#3fb950":"#d29922",p=u.type==="parked"?"parked":u.type==="re-enabled"?"re-enabled":u.type==="released"?"released":"failover";return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 14px",borderBottom:d<e.events.length-1?"1px solid #161b22":"none"},children:[s.jsx("span",{style:{fontSize:13},children:f}),s.jsx("span",{style:{width:80,flexShrink:0,fontSize:11,padding:"1px 8px",borderRadius:10,background:"#161b22",border:`1px solid ${h}`,color:h,textAlign:"center"},children:p}),s.jsxs("span",{style:{flex:1,fontSize:12,color:"#e6edf3",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[Nr(u.provider)," ",sa(u.provider)]}),u.reason&&s.jsx("span",{style:{fontSize:11,color:"#8b949e"},children:u.reason}),s.jsx("span",{style:{fontSize:11,color:"#6e7681",whiteSpace:"nowrap"},children:iM(u.timestamp)})]},`${u.timestamp}-${d}`)})})]})]})}function Fd({ok:e,children:t}){return s.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,padding:"3px 9px",borderRadius:8,background:e===!1?"#2d1616":"#12291a",border:`1px solid ${e===!1?"#f85149":"#238636"}`,color:e===!1?"#f85149":"#3fb950",whiteSpace:"nowrap"},children:t})}function Yae({governance:e}){var r,i,a,o,l;if(!e.enabled)return s.jsx(Yn,{icon:"⚖️",title:"Admin Governance Policy",subtitle:"Hard-constraint rules the Auto router enforces on every pick",children:s.jsxs("div",{style:{fontSize:13,color:"#8b949e"},children:[s.jsx("span",{style:{color:"#3fb950"},children:"Fully permissive"})," — no governance rules active; any provider × model is eligible.",s.jsxs("div",{style:{marginTop:6,fontSize:12,color:"#6e7681"},children:["Add rules with ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff admin allow <provider>"})," ·"," ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff admin deny <provider>"})," ·"," ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff admin max-cost <usd>"})]})]})});const t=[];(r=e.allowProviders)!=null&&r.length&&t.push({label:"allow providers",items:e.allowProviders}),(i=e.denyProviders)!=null&&i.length&&t.push({label:"deny providers",items:e.denyProviders,deny:!0}),(a=e.allowModels)!=null&&a.length&&t.push({label:"allow models",items:e.allowModels}),(o=e.denyModels)!=null&&o.length&&t.push({label:"deny models",items:e.denyModels,deny:!0});const n=[];return e.maxCostUsd!==void 0&&n.push(`max cost $${e.maxCostUsd}`),e.minPrivacyForPii!==void 0&&e.minPrivacyForPii<1&&n.push(`PII min privacy ${e.minPrivacyForPii}`),(l=e.piiPatterns)!=null&&l.length&&n.push(`PII guard (${e.piiPatterns.length} patterns)`),e.allowUnblock===!1&&n.push("unblock admin-hard"),s.jsxs(Yn,{icon:"⚖️",title:"Admin Governance Policy",subtitle:"Hard-constraint rules — violating providers are eliminated, never just scored lower",children:[s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:10},children:[t.map(c=>s.jsxs(Fd,{ok:!c.deny,children:[c.deny?"⛔":"✅"," ",c.label,": ",c.items.join(", ")]},c.label)),n.map(c=>s.jsx(Fd,{children:c},c)),t.length===0&&n.length===0&&s.jsx(Fd,{ok:!1,children:"policy configured but no rules active"})]}),s.jsxs("div",{style:{fontSize:12,color:"#6e7681"},children:["Managed via ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff admin"})," — the same policy the CLI’s"," ",s.jsx("code",{children:"model explain"})," surfaces as governance-blocked."]})]})}function Xae({rbac:e}){const t=n=>n==="admin"?"#d29922":n==="operator"?"#3fb950":"#8b949e";return s.jsxs(Yn,{icon:"🔐",title:"RBAC Identity",subtitle:"Who may write policy — role file ~/.buff/rbac.json",children:[s.jsxs("div",{style:{fontSize:13,marginBottom:10},children:[s.jsx("span",{style:{color:"#c9d1d9"},children:"You are "}),s.jsx("code",{style:{color:"#58a6ff"},children:e.identity}),s.jsx("span",{style:{color:"#8b949e"},children:" as "}),e.role?s.jsx("span",{style:{color:t(e.role),fontWeight:600},children:e.role}):s.jsx("span",{style:{color:"#8b949e"},children:"unassigned"})]}),e.legacy?s.jsxs("div",{style:{fontSize:12,color:"#6e7681"},children:[s.jsx("span",{style:{color:"#3fb950"},children:"Legacy single-user mode"})," — no roles assigned; policy writes are open to every user. Assign roles with"," ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff admin role add <you> admin"}),"."]}):s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[e.users.map(n=>s.jsxs(Fd,{ok:n.role!=="viewer",children:[n.user," · ",n.role,n.via==="oidc"?" (oidc)":""]},n.user)),s.jsxs("div",{style:{width:"100%",fontSize:12,color:"#6e7681",marginTop:4},children:["Policy ",s.jsx("em",{children:"writes"})," require ",s.jsx("code",{style:{color:"#58a6ff"},children:"admin"}),"; reads are open to every role."]})]})]})}function Zae({data:e}){var p,g,m,v,y,b,x,k,S,w;const t=e==null?void 0:e.routing,n=t&&(t.preference.length>0||t.providers.length>0||t.bestModels.length>0),r=!!((p=t==null?void 0:t.usage)!=null&&p.total),i=!!((g=t==null?void 0:t.history)!=null&&g.length),a=!!t&&(((m=t.history)==null?void 0:m.length)??0)>0||!!((v=t==null?void 0:t.preference)!=null&&v.length),o=!!((y=t==null?void 0:t.bandit)!=null&&y.enabled),l=!!((b=t==null?void 0:t.promotion)!=null&&b.decisionCount),c=!!((x=t==null?void 0:t.ml)!=null&&x.enabled)&&(t.ml.recordCount??0)>0,u=!!((k=t==null?void 0:t.quota)!=null&&k.enabled),d=!!((S=t==null?void 0:t.retrieval)!=null&&S.enabled)||!!((w=t==null?void 0:t.retrieval)!=null&&w.repoChunks),f=!!(t!=null&&t.governance),h=!!(t!=null&&t.rbac);return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"🤖 Auto Routing Insights"}),s.jsxs("p",{className:"section-description",children:["Which providers and models the Auto router prefers — from real pricing, benchmark quality, per-agent success stats, and the Thompson-sampling bandit. Run"," ",s.jsx("code",{children:"buff benchmark"})," and use Auto routing to build this up over time."]}),!n&&!r&&!i&&!o&&!l&&!c&&!u&&!d&&!f&&!h?s.jsx(Pae,{}):s.jsxs(s.Fragment,{children:[a&&t&&s.jsx(Aae,{routing:t}),f&&t.governance&&s.jsx(Yae,{governance:t.governance}),(t==null?void 0:t.rbac)&&s.jsx(Xae,{rbac:t.rbac}),r&&s.jsx($ae,{usage:t.usage}),i&&s.jsx(Lae,{history:t.history}),o&&s.jsx(Fae,{bandit:t.bandit}),l&&s.jsx(Hae,{promotion:t.promotion}),c&&t.ml&&s.jsx(Gae,{ml:t.ml}),u&&s.jsx(Vae,{quota:t.quota}),d&&s.jsx(Kae,{retrieval:t.retrieval}),s.jsx(Dae,{routing:t}),s.jsx(Bae,{routing:t}),s.jsx(qae,{routing:t})]}),t&&t.providers.length===0&&t.bestModels.length===0&&t.preference.length>0&&s.jsx("div",{style:{fontSize:12,color:"#6e7681",marginTop:4},children:"Auto-router preference is always available (static profiles + real pricing); quality metrics appear once you run benchmarks and agent tasks."})]})}const p_={chat:"💬",execute:"⚙️",plan:"🗺️",edit:"✏️",skill:"🧩",learn:"📚",ci:"🔁",doctor:"🩺",probe:"🔭","spot-check":"🧪",telemetry:"📡",usage:"🧮","ide-chat":"💬","ide-inline":"✍️","ide-execute":"⚙️"};function Qae(e){return new Date(e).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function yd(e){return e!==void 0?`${e}ms`:"—"}function aM(e){return e===0?"#3fb950":e<.2?"#d29922":"#f85149"}function Jae({data:e}){const t=e.rows,n=t.reduce((c,u)=>c+u.requests,0),r=t.reduce((c,u)=>c+Math.round(u.errorRate*u.requests),0),i=t.reduce((c,u)=>c+(u.costUsd??0),0),a=t.flatMap(c=>c.latency?[c.latency.avg]:[]),o=a.length>0?Math.round(a.reduce((c,u)=>c+u,0)/a.length):void 0,l=new Set(t.map(c=>c.action)).size;return s.jsxs("div",{className:"stats-grid",style:{marginBottom:16},children:[s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"📨"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",children:n.toLocaleString()}),s.jsx("div",{className:"stat-label",children:"Requests"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"🎯"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",children:t.length}),s.jsx("div",{className:"stat-label",children:"provider × model × action groups"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"⚡"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:o!==void 0?"#3fb950":"#8b949e"},children:o!==void 0?`${o}ms`:"—"}),s.jsxs("div",{className:"stat-label",children:["Avg latency",o!==void 0?` (${a.length} groups)`:" (no samples)"]})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"📛"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:aM(n>0?r/n:0)},children:n>0?`${(r/n*100).toFixed(1)}%`:"—"}),s.jsxs("div",{className:"stat-label",children:["Overall error rate (",r.toLocaleString()," failures)"]})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"💰"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:i>0?"#d29922":"#8b949e"},children:i>0?`$${i.toFixed(4)}`:"—"}),s.jsxs("div",{className:"stat-label",children:["Measured cost",l>0?` · ${l} actions`:""]})]})]})]})}function ese({data:e}){const[t,n]=E.useState(""),[r,i]=E.useState("all"),a=e==null?void 0:e.requests,o=E.useMemo(()=>{if(!a)return[];const c=t.trim().toLowerCase();return a.rows.filter(u=>r!=="all"&&u.action!==r?!1:c?`${u.provider} ${u.model} ${u.action}`.toLowerCase().includes(c):!0)},[a,t,r]);if(!e)return s.jsx("div",{className:"loading-state",children:s.jsx("p",{children:"Loading requests..."})});if(!a||!a.enabled||a.rows.length===0)return s.jsxs("div",{className:"empty-state",style:{padding:"40px 24px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:28,marginBottom:10},children:"📨"}),s.jsx("h2",{className:"section-title",style:{marginTop:0},children:"Requests — per provider × model × action"}),s.jsxs("p",{className:"section-description",style:{maxWidth:560,margin:"0 auto"},children:["No request telemetry yet. As you use ",s.jsx("strong",{children:"chat"}),", ",s.jsx("strong",{children:"execute"}),","," ",s.jsx("strong",{children:"plan"})," and ",s.jsx("strong",{children:"edit"})," under Auto routing, every call writes to the action-telemetry log and this panel aggregates it: request counts, p50/p95/p99 latency, error rate and measured cost — the same feed that drives the Models panel."]})]});const l=[...new Set(a.rows.map(c=>c.action))].sort();return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"📨 Requests — per provider × model × action"}),s.jsx("p",{className:"section-description",children:"Aggregated from the same action-telemetry log as the Models panel — every Auto-routed call, grouped by action × provider × model. Latency percentiles appear once ≥3 samples exist; cost when the caller reported usage."}),s.jsx(Jae,{data:a}),s.jsxs("div",{style:{display:"flex",gap:12,marginBottom:14,flexWrap:"wrap",alignItems:"center"},children:[s.jsxs("select",{value:r,onChange:c=>i(c.target.value),"aria-label":"Filter by action",style:{background:"#161b22",color:"#e6edf3",border:"1px solid #30363d",borderRadius:8,padding:"8px 10px",fontSize:13,cursor:"pointer"},children:[s.jsx("option",{value:"all",children:"All actions"}),l.map(c=>s.jsxs("option",{value:c,children:[p_[c]||"🎯"," ",c]},c))]}),s.jsxs("div",{style:{flex:1,minWidth:220,position:"relative"},children:[s.jsx("span",{style:{position:"absolute",left:10,top:8,color:"#6e7681",fontSize:13},children:"🔍"}),s.jsx("input",{type:"text",value:t,onChange:c=>n(c.target.value),placeholder:"Search provider, model or action...",style:{width:"100%",padding:"8px 12px 8px 32px",background:"#161b22",border:"1px solid #30363d",borderRadius:8,color:"#e6edf3",fontSize:13,outline:"none"}})]}),s.jsxs("span",{style:{fontSize:12,color:"#8b949e",whiteSpace:"nowrap"},children:[o.length," of ",a.rows.length," groups"]})]}),s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid #21262d",color:"#8b949e",textAlign:"left"},children:[s.jsx("th",{style:{padding:"8px 12px",fontWeight:500},children:"Action"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500},children:"Provider"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500},children:"Model"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500,textAlign:"right"},children:"Requests"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500,textAlign:"right"},children:"Error rate"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500,textAlign:"right"},children:"Latency avg"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500,textAlign:"right"},children:"p50"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500,textAlign:"right"},children:"p95"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500,textAlign:"right"},children:"p99"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500,textAlign:"right"},children:"Measured cost"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500,textAlign:"right"},children:"Last seen"})]})}),s.jsx("tbody",{children:o.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:11,style:{padding:28,textAlign:"center",color:"#6e7681"},children:"No request groups match your filter."})}):o.map(c=>{var u;return s.jsxs("tr",{style:{borderBottom:"1px solid #21262d"},children:[s.jsx("td",{style:{padding:"8px 12px",whiteSpace:"nowrap"},children:s.jsxs("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:8,background:"#21262d",color:"#c9d1d9",border:"1px solid #30363d"},children:[p_[c.action]||"🎯"," ",c.action]})}),s.jsx("td",{style:{padding:"8px 12px",color:"#e6edf3",whiteSpace:"nowrap"},children:c.provider}),s.jsxs("td",{style:{padding:"8px 12px",color:"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12,maxWidth:260,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:c.callIds.length>0?`Correlation ids: ${c.callIds.join(", ")}`:void 0,children:[c.model.length>42?c.model.slice(0,39)+"…":c.model,c.callIds.length>0&&s.jsxs("span",{style:{color:"#6e7681",marginLeft:6},title:c.callIds.join(", "),children:["🔗",c.callIds.length]})]}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12},children:c.requests}),s.jsxs("td",{style:{padding:"8px 12px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12,color:aM(c.errorRate)},children:[(c.errorRate*100).toFixed(1),"%",(c.partials??0)>0&&s.jsxs("span",{title:`⏸ ${c.partials} mid-stream interruption(s) — started streaming, died before finish; the router deprioritizes flaky providers (P4 M4.4)`,style:{display:"inline-flex",alignItems:"center",gap:3,marginLeft:6,fontSize:10,padding:"1px 6px",borderRadius:8,whiteSpace:"nowrap",background:"#21122e",border:"1px solid #bc8cff",color:"#bc8cff"},children:["⏸ ",c.partials]})]}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12},children:yd((u=c.latency)==null?void 0:u.avg)}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12},children:c.latency&&c.latency.samples>=3?yd(c.latency.p50):"—"}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12},children:c.latency&&c.latency.samples>=3?yd(c.latency.p95):"—"}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12},children:c.latency&&c.latency.samples>=3?yd(c.latency.p99):"—"}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12,color:c.costUsd?"#d29922":"#6e7681"},children:c.costUsd!==void 0?`$${c.costUsd.toFixed(4)}`:"—"}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",color:"#6e7681",fontSize:11,whiteSpace:"nowrap"},children:Qae(c.lastAt)})]},`${c.action}|${c.provider}|${c.model}`)})})]})}),s.jsx("div",{style:{textAlign:"center",fontSize:12,color:"#484f58",marginTop:12},children:"Auto-refreshes with the dashboard feed · percentile columns need ≥3 latency samples per group"})]})}const tse={local:"💻",groq:"🟢",nim:"🔶",gemini:"🔷",openrouter:"🟣"},nse={planner:"🗺️",writer:"✍️",reviewer:"🔎",tester:"🧪",debugger:"🐛",runner:"🏃","context-gatherer":"📂",memory:"🧠","self-improver":"📈"};function rse(e){return tse[e]||"🔌"}function ise(e){return nse[e]||"🤖"}function sM(e){const t=Date.now()-e;return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${new Date(e).toLocaleDateString()}`}function h0(e){return e===void 0?"—":e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}function ic(e){return e==null?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}function ase(e){var n;if(!e)return null;const t={bg:"#0d1117",border:"#30363d"};return e.unverifiedClaim?{text:"⚠️ unverified claim — said it acted, but no tool ran",color:"#d29922",bg:"#3d2c00",border:"#d29922"}:e.unfulfilledPromise?{text:"⚠️ unfulfilled promise — announced an action it never performed",color:"#d29922",bg:"#3d2c00",border:"#d29922"}:e.kind==="acted"?{text:e.delivered?"✅ action performed — message sent":`🔧 acted — ${((n=e.tools)==null?void 0:n.length)??0} tool(s)`,color:"#3fb950",bg:"#0d2818",border:"#238636"}:e.kind==="answered"?{text:"💬 answered — no action taken",color:"#8b949e",...t}:e.kind==="cancelled"?{text:"⏹ cancelled",color:"#8b949e",...t}:{text:"❌ generation failed",color:"#f85149",bg:"#2d0f0f",border:"#f85149"}}function qv({icon:e,title:t,subtitle:n,children:r}){return s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:"1px solid #21262d",padding:"18px 20px",marginBottom:16},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:4},children:[s.jsx("span",{style:{fontSize:20},children:e}),s.jsx("h3",{style:{fontSize:15,fontWeight:600,color:"#e6edf3",margin:0},children:t})]}),n&&s.jsx("p",{style:{fontSize:12,color:"#8b949e",margin:"2px 0 12px 0"},children:n}),!n&&s.jsx("div",{style:{height:6}}),r]})}function sse(){return s.jsxs("div",{style:{background:"#0d1117",border:"1px dashed #30363d",borderRadius:10,padding:"18px 20px",color:"#8b949e",fontSize:13,textAlign:"center"},children:["🔍 No reasoning traces yet — every LLM call in a ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff execute"})," pipeline is recorded to ",s.jsx("code",{style:{color:"#58a6ff"},children:"reasoning-traces.json"}),". Run a pipeline, then replay it here or with ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff trace replay <id>"}),"."]})}function ose({step:e}){const[t,n]=E.useState(!1),r=e.success?"#3fb950":"#f85149",i=e.success?"ok":"failed";return s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:8,marginBottom:8,overflow:"hidden"},children:[s.jsxs("button",{onClick:()=>n(!t),style:{width:"100%",background:"none",border:"none",cursor:"pointer",padding:"10px 14px",textAlign:"left",display:"flex",alignItems:"center",gap:10,color:"inherit"},children:[s.jsx("span",{style:{width:26,fontSize:16},children:ise(e.agentType)}),s.jsx("span",{style:{width:130,fontSize:12,fontWeight:600,color:"#e6edf3",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},title:e.agentType,children:e.agentType}),s.jsxs("span",{style:{flex:1,fontSize:12,color:"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},title:`${e.provider}/${e.model}`,children:[rse(e.provider)," ",e.provider,"/",e.model]}),s.jsx("span",{style:{width:70,fontSize:11,color:"#6e7681",textAlign:"right"},children:h0(e.latencyMs)}),s.jsxs("span",{style:{width:86,fontSize:11,color:"#6e7681",fontFamily:"'SFMono-Regular', Consolas, monospace",textAlign:"right"},children:[ic(e.inputTokens),"→",ic(e.outputTokens)," tok"]}),s.jsx("span",{style:{width:46,fontSize:11,color:r,textAlign:"right"},children:i}),s.jsx("span",{style:{width:22,fontSize:11,textAlign:"right"},children:e.escalated?s.jsx("span",{title:"Repair escalated to a stronger routed model (v1.60.4)",children:"🚀"}):""}),s.jsx("span",{style:{fontSize:11,color:"#6e7681"},children:t?"▾":"▸"})]}),t&&s.jsxs("div",{style:{padding:"0 14px 12px 50px",fontSize:12},children:[e.taskId&&s.jsxs("div",{style:{color:"#6e7681",marginBottom:4},children:["Task: ",s.jsx("span",{style:{color:"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:e.taskId})]}),e.description&&s.jsx("div",{style:{color:"#8b949e",marginBottom:6},children:e.description}),e.routing&&s.jsxs("div",{style:{marginBottom:6},children:[s.jsxs("span",{style:{fontSize:10,padding:"1px 8px",borderRadius:10,background:e.escalated?"#3d2c00":"#1c2128",border:e.escalated?"1px solid #d29922":"1px solid #58a6ff",color:e.escalated?"#d29922":"#58a6ff"},children:[e.escalated?"🚀 escalated auto → ":"🤖 auto → ",e.routing.provider,"/",e.routing.model," · score ",e.routing.score.toFixed(3)," · ",e.routing.complexity]}),e.escalated&&s.jsx("div",{style:{color:"#d29922",marginTop:4,fontSize:11},children:"Repair escalated to a stronger routed model (next complexity level)."}),e.routing.explanation&&s.jsx("div",{style:{color:"#6e7681",marginTop:4,fontSize:11},children:e.routing.explanation})]}),e.error&&s.jsxs("div",{style:{color:"#f85149",marginBottom:6},children:["⚠️ ",e.error.slice(0,300)]}),s.jsxs("div",{style:{color:"#6e7681",margin:"6px 0 3px 0"},children:["Prompt ",s.jsxs("span",{style:{fontFamily:"'SFMono-Regular', Consolas, monospace"},children:["#",e.promptDigest]})," · ",e.promptPreview.length,"+ chars:"]}),s.jsx("pre",{style:{background:"#161b22",border:"1px solid #21262d",borderRadius:6,padding:8,margin:0,color:"#8b949e",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:180,overflowY:"auto",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:11},children:e.promptPreview.slice(0,900)}),s.jsxs("div",{style:{color:"#6e7681",margin:"8px 0 3px 0"},children:["Response (",ic(e.responseLength)," chars):"]}),s.jsx("pre",{style:{background:"#161b22",border:"1px solid #21262d",borderRadius:6,padding:8,margin:0,color:"#c9d1d9",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:240,overflowY:"auto",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:11},children:e.responsePreview.slice(0,1200)})]})]})}function lse({trace:e}){const[t,n]=E.useState(e.steps??null),[r,i]=E.useState(!1);E.useEffect(()=>{if(e.steps){n(e.steps);return}let l=!1;return ee.fetchTraceDetail(e.id).then(c=>{l||(c!=null&&c.steps?n(c.steps):i(!0))}),()=>{l=!0}},[e.id,e.steps]);const a=e.success===!0?"✅":e.success===!1?"❌":"⏳",o=e.success===!0?"success":e.success===!1?"failed":"in progress";return s.jsxs(qv,{icon:a,title:`${e.id} — ${o}`,subtitle:e.goal,children:[s.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginBottom:12},children:[s.jsxs("span",{style:{fontSize:11,padding:"2px 10px",borderRadius:12,background:"#0d1117",border:"1px solid #30363d",color:"#8b949e"},children:["🕓 ",sM(e.startedAt)]}),(()=>{const l=ase(e.outcome);return l?s.jsx("span",{style:{fontSize:11,padding:"2px 10px",borderRadius:12,background:l.bg,border:`1px solid ${l.border}`,color:l.color},children:l.text}):null})(),s.jsxs("span",{style:{fontSize:11,padding:"2px 10px",borderRadius:12,background:"#0d1117",border:"1px solid #30363d",color:"#8b949e"},children:["⏱ ",h0(e.durationMs)]}),s.jsxs("span",{style:{fontSize:11,padding:"2px 10px",borderRadius:12,background:"#0d1117",border:"1px solid #30363d",color:"#8b949e"},children:["🔢 ",(t==null?void 0:t.length)??"?"," call(s)"]}),t&&t.some(l=>l.escalated)&&s.jsxs("span",{style:{fontSize:11,padding:"2px 10px",borderRadius:12,background:"#3d2c00",border:"1px solid #d29922",color:"#d29922"},children:["🚀 ",t.filter(l=>l.escalated).length," escalated repair(s)"]}),e.totalTokens!==void 0&&s.jsxs("span",{style:{fontSize:11,padding:"2px 10px",borderRadius:12,background:"#0d1117",border:"1px solid #30363d",color:"#8b949e"},children:["🧮 ",ic(e.totalTokens)," tok"]})]}),r&&s.jsx("div",{style:{color:"#f85149",fontSize:12,marginBottom:10},children:"Could not load trace steps (trace may have been deleted)."}),t===null&&!r&&s.jsx("div",{style:{color:"#8b949e",fontSize:12},children:"Loading steps…"}),t&&t.length===0&&s.jsx("div",{style:{color:"#8b949e",fontSize:12},children:"No LLM calls recorded in this trace."}),t&&t.map(l=>s.jsx(ose,{step:l},l.seq))]})}function cse({traces:e}){const[t,n]=E.useState(null);return t?s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>n(null),style:{background:"#21262d",border:"1px solid #30363d",color:"#e6edf3",borderRadius:8,padding:"6px 14px",fontSize:12,cursor:"pointer",marginBottom:12},children:"← Back to traces"}),s.jsx(lse,{trace:t})]}):s.jsx("div",{children:e.map(r=>{const i=r.success===!0?"✅":r.success===!1?"❌":"⏳",a=r.steps?[...new Set(r.steps.map(o=>o.agentType))].join(", "):"";return s.jsxs("button",{onClick:()=>n(r),style:{width:"100%",background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 16px",marginBottom:8,cursor:"pointer",textAlign:"left",color:"inherit",transition:"border-color 0.2s, box-shadow 0.2s"},onMouseEnter:o=>{o.currentTarget.style.borderColor="#58a6ff",o.currentTarget.style.boxShadow="0 2px 10px #58a6ff22"},onMouseLeave:o=>{o.currentTarget.style.borderColor="#21262d",o.currentTarget.style.boxShadow="none"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[s.jsx("span",{children:i}),s.jsx("span",{style:{fontSize:11,color:"#58a6ff",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:r.id}),s.jsx("span",{style:{fontSize:11,color:"#6e7681",marginLeft:"auto"},children:sM(r.startedAt)})]}),s.jsx("div",{style:{fontSize:13,color:"#e6edf3",marginBottom:6},children:r.goal}),s.jsxs("div",{style:{display:"flex",gap:10,flexWrap:"wrap",fontSize:11,color:"#8b949e"},children:[s.jsxs("span",{children:["🔢 ",r.stepCount??0," call(s)"]}),s.jsxs("span",{children:["⏱ ",h0(r.durationMs)]}),r.failedSteps?s.jsxs("span",{style:{color:"#f85149"},children:["❌ ",r.failedSteps," failed"]}):s.jsx("span",{style:{color:"#3fb950"},children:"✓ all ok"}),r.totalTokens!==void 0&&s.jsxs("span",{children:["🧮 ",ic(r.totalTokens)," tok"]}),a&&s.jsxs("span",{children:["🤖 ",a.slice(0,60)]})]})]},r.id)})})}function use(){const[e,t]=E.useState(null),[n,r]=E.useState(!1),i=E.useCallback(()=>{ee.fetchTraces().then(a=>{a?(t(a),r(!1)):r(!0)})},[]);return E.useEffect(()=>{i();const a=setInterval(i,15e3);return()=>clearInterval(a)},[i]),s.jsxs("div",{className:"panel",children:[s.jsxs("div",{style:{marginBottom:16},children:[s.jsx("h2",{style:{margin:0,fontSize:18,color:"#e6edf3"},children:"🔍 Reasoning Traces"}),s.jsx("p",{style:{margin:"4px 0 0 0",fontSize:12,color:"#8b949e"},children:"Every LLM call in each pipeline — agent × model × prompt digest × response × tokens × latency × routing snapshot (assessment P0)."})]}),e===null&&!n&&s.jsx(qv,{icon:"⏳",title:"Loading…",children:s.jsx("div",{style:{color:"#8b949e",fontSize:13},children:"Fetching reasoning traces…"})}),n&&e===null&&s.jsx(qv,{icon:"⚠️",title:"Could not reach the dashboard server",children:s.jsxs("div",{style:{color:"#8b949e",fontSize:13},children:["The traces endpoint is unavailable right now — retrying automatically. Run"," ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff trace list"})," in the terminal to inspect traces directly."]})}),e!==null&&e.length===0&&s.jsx(sse,{}),e!==null&&e.length>0&&s.jsx(cse,{traces:e})]})}function ig(e){if(e.trim()==="")return null;const t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function dse({authed:e,role:t}){const[n,r]=E.useState(null),[i,a]=E.useState({}),[o,l]=E.useState(""),[c,u]=E.useState(!1),[d,f]=E.useState(null),[h,p]=E.useState(null),g=e&&(t==="admin"||t==="operator"),m=e&&t==="admin",v=E.useCallback(async()=>{var _,N,C;const S=await ee.fetchAdminQuota();if(!S){p("Could not load budget config.");return}p(null),r(S);const w={};for(const T of S.providers){const $=S.quota[T]||{};w[T]={provider:T,tokens:((_=$.tokensPerWindow)==null?void 0:_.toString())??"",requests:((N=$.requestsPerWindow)==null?void 0:N.toString())??"",windowMs:((C=$.windowMs)==null?void 0:C.toString())??""}}a(w),l(S.costUsd===null?"":String(S.costUsd))},[]);E.useEffect(()=>{v()},[v]);const y=(S,w,_)=>{a(N=>({...N,[S]:{...N[S]||{provider:S},[w]:_}}))},b=async()=>{u(!0),f(null);const S={};for(const N of Object.values(i)){const C={},T=ig(N.tokens),$=ig(N.requests),R=ig(N.windowMs);T!==null&&(C.tokensPerWindow=T),$!==null&&(C.requestsPerWindow=$),R!==null&&(C.windowMs=R),S[N.provider]=Object.keys(C).length>0?C:null}const w={quota:S};if(m)if(o.trim()!==""){const N=Number(o);if(!Number.isFinite(N)||N<0){f({ok:!1,text:"Cost cap must be a non-negative number."}),u(!1);return}w.costUsd=N}else w.costUsd=null;const _=await ee.saveAdminQuota(w);u(!1),_.ok?(f({ok:!0,text:"Budget saved — the quota ledger + auto-router will enforce it."}),v()):f({ok:!1,text:_.error||"Save failed."})},x=S=>{const w=n==null?void 0:n.quota[S];return!!w&&(w.tokensPerWindow!==void 0||w.requestsPerWindow!==void 0||w.windowMs!==void 0)},k=S=>"admin-input";return s.jsxs("div",{className:"admin-quota-panel",children:[s.jsx("h3",{className:"section-subtitle",children:"💰 Daily Budget (routing.quota — your plan, your say)"}),s.jsxs("p",{className:"admin-quota-note",children:["Free-tier providers enforce tokens-per-day caps the API doesn't advertise — only you know your plan's allowance. Declare it here and the agent paces around it (parks the provider at the cap, auto-resumes at window rollover) instead of exhausting your budget mid-task. Unset = current behavior. Same config as ",s.jsx("code",{children:"buff model quota set"}),"."]}),h?s.jsx("div",{className:"admin-error",children:h}):null,n?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"admin-quota-table",children:[s.jsxs("div",{className:"admin-quota-row admin-quota-head",children:[s.jsx("span",{children:"Provider"}),s.jsx("span",{children:"Tokens / window"}),s.jsx("span",{children:"Requests / window"}),s.jsx("span",{children:"Window (ms)"}),s.jsx("span",{children:"Status"})]}),n.providers.map(S=>{var w,_,N;return s.jsxs("div",{className:"admin-quota-row",children:[s.jsx("span",{className:"admin-provider-type",children:S}),s.jsx("input",{className:k(!g),type:"number",min:0,placeholder:"unset",disabled:!g,value:((w=i[S])==null?void 0:w.tokens)??"",onChange:C=>y(S,"tokens",C.target.value)}),s.jsx("input",{className:k(!g),type:"number",min:0,placeholder:"unset",disabled:!g,value:((_=i[S])==null?void 0:_.requests)??"",onChange:C=>y(S,"requests",C.target.value)}),s.jsx("input",{className:k(!g),type:"number",min:0,placeholder:"86400000 (24h)",disabled:!g,value:((N=i[S])==null?void 0:N.windowMs)??"",onChange:C=>y(S,"windowMs",C.target.value)}),s.jsx("span",{className:`admin-role-badge ${x(S)?"admin-role-admin":"admin-role-viewer"}`,children:x(S)?"declared":"unset"})]},S)})]}),s.jsxs("div",{className:"admin-quota-row admin-quota-cost",children:[s.jsx("span",{className:"admin-provider-type",children:"Max cost / call (USD, admin)"}),s.jsx("input",{className:k(!m),type:"number",min:0,step:.01,placeholder:"unset",disabled:!m,value:o,onChange:S=>l(S.target.value)}),s.jsx("span",{className:"admin-quota-cost-hint",children:"governance.maxCostUsd — hard admin cap"})]}),g||m?s.jsxs("div",{className:"admin-quota-actions",children:[s.jsx("button",{className:"admin-mini-btn",onClick:()=>void b(),disabled:c,children:c?"⏳ Saving…":"💾 Save budget"}),d?s.jsx("span",{className:d.ok?"admin-quota-ok":"admin-quota-err",children:d.text}):null]}):s.jsxs("div",{className:"admin-readonly-note",children:["🔒 Read-only for ",s.jsx("code",{children:t})," — budget limits need ",s.jsx("code",{children:"admin"})," or"," ",s.jsx("code",{children:"operator"}),"; the cost cap needs ",s.jsx("code",{children:"admin"}),"."]})]}):s.jsx("div",{className:"empty-state",children:"Loading budget…"})]})}const fse={pass:"✅",warn:"⚠️",fail:"❌"},hse={pass:"PASS",warn:"WARN",fail:"FAIL"},pse={env:"Environment",config:"Config",vault:"Vault",local:"Local (no key)",none:"Not configured"};function m_({check:e}){return s.jsxs("div",{className:"admin-check-row","data-status":e.status,children:[s.jsxs("span",{className:`admin-check-badge admin-check-${e.status}`,children:[fse[e.status]," ",hse[e.status]]}),s.jsxs("div",{className:"admin-check-body",children:[s.jsx("div",{className:"admin-check-name",children:e.name}),s.jsx("div",{className:"admin-check-message",children:e.message}),e.detail?s.jsx("div",{className:"admin-check-detail",children:e.detail}):null,e.fix?s.jsxs("div",{className:"admin-check-fix",children:["💡 ",e.fix]}):null]})]})}function mse(){const[e,t]=E.useState(null),[n,r]=E.useState(!0),[i,a]=E.useState(null),[o,l]=E.useState(null),[c,u]=E.useState(!1),[d,f]=E.useState(null),[h,p]=E.useState(null),[g,m]=E.useState(""),[v,y]=E.useState(""),[b,x]=E.useState(""),[k,S]=E.useState(null),[w,_]=E.useState(!1),[N,C]=E.useState([]),[T,$]=E.useState(null),[R,L]=E.useState(""),[I,z]=E.useState(""),[D,F]=E.useState("viewer"),[O,P]=E.useState([]),[A,Y]=E.useState({}),[K,M]=E.useState(null),[le,be]=E.useState({}),[me,Pe]=E.useState(""),[H,X]=E.useState(null),[oe,ce]=E.useState(null),Z=E.useCallback(async()=>{r(!0),a(null);const G=await ee.fetchAdminChecks();t(G),G||a("Could not reach the dashboard server, or the server is older than this panel. Run `buff dashboard` to start it."),r(!1)},[]),_e=E.useCallback(async()=>{const G=await ee.fetchAdminCatalog();G&&G.length>0&&P(G)},[]),we=E.useCallback(async()=>{const G=await ee.fetchAdminUsers();G.ok&&G.users&&C(G.users)},[]);E.useEffect(()=>{let G=!0;return ee.fetchAdminAuthStatus().then(he=>{if(G){if(!he){a("Could not reach the dashboard server, or the server is older than this panel. Run `buff dashboard` to start it."),r(!1);return}l({configured:he.configured,authenticated:he.authenticated}),u(he.authenticated),f(he.role??null),p(he.user??null),he.authenticated?(Z(),_e(),we()):r(!1)}}),()=>{G=!1}},[Z,_e,we]);const Ne=d==="admin",ge=()=>{u(!1),l(G=>G&&{...G,authenticated:!1}),S("Session expired — log in again.")},Be=async G=>{G.preventDefault(),_(!0),S(null);const he=await ee.adminLogin(g,v);he.ok?(u(!0),l({configured:!0,authenticated:!0}),f(he.role??"admin"),p(he.user??null),m(""),y(""),Z(),_e(),we()):S(he.error||"Login failed."),_(!1)},pe=async G=>{if(G.preventDefault(),_(!0),S(null),v.length<8){S("Password must be at least 8 characters."),_(!1);return}if(v!==b){S("Passwords do not match."),_(!1);return}const he=await ee.adminSetup(g,v);he.ok?(u(!0),l({configured:!0,authenticated:!0}),f(he.role??"admin"),p(he.user??null),m(""),y(""),x(""),Z(),_e(),we()):S(he.error||"Setup failed."),_(!1)},Ct=async()=>{await ee.adminLogout(),u(!1),l(G=>G&&{...G,authenticated:!1}),f(null),p(null),t(null),Y({}),be({}),C([])},We=async()=>{if(!window.confirm("Stop the running gateway? Channels will stop responding until you restart it with `buff gateway start`."))return;ce("gateway"),X(null);const G=await ee.shutdown("gateway");ce(null),G.ok?X(G.stopped?"✅ Gateway stopped.":`ℹ️ ${G.reason||"No running gateway found — nothing to stop."}`):(X(`❌ ${G.error||"Stop failed."}`),G.unauthorized&&ge())},Oe=async()=>{window.confirm("Shut down the dashboard? This page will disconnect and the server will exit. Restart with `buff dashboard`.")&&(ce("dashboard"),X("🛑 Shutting down the dashboard — this page will disconnect…"),await ee.shutdown("dashboard"),ce(null),X("ℹ️ The dashboard server did not stop (see the server terminal). You can also stop it with `buff dashboard stop`."))},Ze=async G=>{if(G.preventDefault(),$(null),I.length<8){$("Password must be at least 8 characters.");return}const he=await ee.addAdminUser(R,I,D);he.ok?(L(""),z(""),$("✅ User added"),we()):($(`❌ ${he.error||"Failed to add user"}`),he.unauthorized&&ge())},Me=async G=>{if(!window.confirm(`Remove dashboard user '${G}'?`))return;$(null);const he=await ee.removeAdminUser(G);he.ok?($(`✅ Removed ${G}`),we()):($(`❌ ${he.error||"Failed to remove user"}`),he.unauthorized&&ge())},Qt=(G,he,Ie)=>{Y(Re=>({...Re,[G]:{...Re[G]||{},[he]:Ie}}))},$t=async G=>{M(G),be({});const he=A[G]||{},Ie=await ee.saveProvider(G,he);Ie.ok?(t(Re=>{if(!Re)return Re;const Jt=Re.providers.some(An=>An.type===G)?Re.providers.map(An=>An.type===G&&Ie.provider?Ie.provider:An):Ie.provider?[...Re.providers,Ie.provider]:Re.providers;return{...Re,providers:Jt}}),Y(Re=>{const Cr={...Re};return delete Cr[G],Cr}),be(Re=>({...Re,[G]:"✅ Saved"}))):(be(Re=>({...Re,[G]:`❌ ${Ie.error||"Save failed"}`})),Ie.unauthorized&&ge()),M(null)},U=async G=>{if(!window.confirm(`Remove ${G}'s API key and configuration? This cannot be undone.`))return;M(G),be({});const he=await ee.deleteProvider(G);he.ok?he.envSourced?(t(Ie=>Ie&&{...Ie,providers:Ie.providers.map(Re=>Re.type===G&&he.provider||Re)}),be(Ie=>({...Ie,[G]:`⚠️ Key comes from ${he.envVar?`$${he.envVar}`:"an env var"} — unset it there to remove it (config can't override the env).`}))):(t(Ie=>Ie&&{...Ie,providers:Ie.providers.filter(Re=>Re.type!==G)}),Y(Ie=>{const Re={...Ie};return delete Re[G],Re})):(be(Ie=>({...Ie,[G]:`❌ ${he.error||"Remove failed"}`})),he.unauthorized&&ge()),M(null)},V=async G=>{M(G);const he=await ee.testProvider(G);be(Ie=>{var Re;return{...Ie,[G]:he.ok?`✅ Connected — ${((Re=he.models)==null?void 0:Re.length)??0} model(s) reachable`:`❌ ${he.error||"Connection failed"}`}}),M(null)},se=()=>{me&&(Y(G=>({...G,[me]:{}})),Pe(""))};if(i&&!o)return s.jsxs("div",{className:"admin-header",children:[s.jsx("h2",{className:"section-title",children:"🛠️ Admin"}),s.jsx("div",{className:"admin-error",children:i})]});if(!o||!c&&n)return s.jsxs("div",{className:"admin-header",children:[s.jsx("h2",{className:"section-title",children:"🛠️ Admin"}),s.jsxs("div",{className:"loading-state",children:[s.jsx("div",{className:"loading-spinner"}),s.jsx("p",{children:"Loading…"})]})]});if(!c){const G=!o.configured;return s.jsxs("div",{className:"admin-header",children:[s.jsxs("h2",{className:"section-title",children:["🛠️ Admin — ",G?"Set up access":"Log in"]}),s.jsx("p",{className:"admin-subtitle",children:G?"Create the admin user-id and password that gate the dashboard write surface (API-key/provider configuration). The CLI keeps working exactly as before — this only guards the GUI.":"The write surface (API-key/provider configuration) is gated by the admin credentials. Read-only checks stay open."}),s.jsxs("form",{className:"admin-gate-form",onSubmit:G?pe:Be,children:[s.jsxs("label",{children:[s.jsx("span",{children:"Username"}),s.jsx("input",{type:"text",value:g,onChange:he=>m(he.target.value),autoComplete:"username",placeholder:"admin"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Password"}),s.jsx("input",{type:"password",value:v,onChange:he=>y(he.target.value),autoComplete:G?"new-password":"current-password",placeholder:"••••••••"})]}),G?s.jsxs("label",{children:[s.jsx("span",{children:"Confirm password"}),s.jsx("input",{type:"password",value:b,onChange:he=>x(he.target.value),autoComplete:"new-password",placeholder:"••••••••"})]}):null,k?s.jsx("div",{className:"admin-error",children:k}):null,s.jsx("button",{className:"admin-refresh-btn",type:"submit",disabled:w||!g||!v,children:w?"⏳ …":G?"🔐 Create admin":"🔐 Log in"}),G?s.jsxs("p",{className:"admin-hint",children:["Automation alternative: set ",s.jsx("code",{children:"BUFF_DASHBOARD_ADMIN_USER"})," and"," ",s.jsx("code",{children:"BUFF_DASHBOARD_ADMIN_PASSWORD"})," in the dashboard's environment."]}):null]})]})}const fe=(e==null?void 0:e.system.filter(G=>G.status==="pass").length)??0,Se=(e==null?void 0:e.system.filter(G=>G.status==="warn").length)??0,Qe=(e==null?void 0:e.system.filter(G=>G.status==="fail").length)??0,Lt=(e==null?void 0:e.enterprise.filter(G=>G.status==="pass").length)??0,Ot=(e==null?void 0:e.enterprise.filter(G=>G.status==="warn").length)??0,jn=(e==null?void 0:e.enterprise.filter(G=>G.status==="fail").length)??0,xt=(e==null?void 0:e.providers)??[],dt=G=>{const he=O.find(Ie=>Ie.id===G);return he||{label:G}};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"admin-header",children:[s.jsxs("h2",{className:"section-title",children:["🛠️ Admin — Command Runner & Configuration",h?s.jsxs("span",{className:`admin-role-badge admin-role-${d||"viewer"}`,children:[h," · ",d||"viewer"]}):null]}),s.jsxs("div",{className:"admin-header-actions",children:[s.jsx("button",{className:"admin-refresh-btn",onClick:()=>void Z(),disabled:n,children:n?"⏳ Running checks…":"🔄 Refresh (run all commands)"}),Ne||d==="operator"?s.jsx("button",{className:"admin-logout-btn",onClick:()=>void We(),disabled:oe!==null,title:"Stop the running gateway (buff gateway stop)",children:oe==="gateway"?"⏳ Stopping…":"⏻ Stop gateway"}):null,Ne?s.jsx("button",{className:"admin-logout-btn",onClick:()=>void Oe(),disabled:oe!==null,title:"Shut down this dashboard server (buff dashboard stop)",children:oe==="dashboard"?"⏳ Stopping…":"🛑 Stop dashboard"}):null,s.jsx("button",{className:"admin-logout-btn",onClick:()=>void Ct(),children:"🚪 Log out"})]})]}),H?s.jsx("div",{className:"admin-error",children:H}):null,Ne?null:s.jsxs("div",{className:"admin-readonly-note",children:["🔒 Your role (",s.jsx("code",{children:d||"viewer"}),") is read-only here — provider configuration and user management require the ",s.jsx("code",{children:"admin"})," role. The CLI enforces the same governance policy (rbac.json)."]}),s.jsx("p",{className:"admin-subtitle",children:"The dashboard executes the same state commands as the CLI — no command needed. Provider keys are masked here and every write goes through the same config the CLI uses."}),i?s.jsx("div",{className:"admin-error",children:i}):null,e?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"admin-summary-grid",children:[s.jsxs("div",{className:"admin-summary-card admin-summary-pass",children:[s.jsx("div",{className:"admin-summary-value",children:fe+Lt}),s.jsx("div",{className:"admin-summary-label",children:"✅ Passing"})]}),s.jsxs("div",{className:"admin-summary-card admin-summary-warn",children:[s.jsx("div",{className:"admin-summary-value",children:Se+Ot}),s.jsx("div",{className:"admin-summary-label",children:"⚠️ Warnings"})]}),s.jsxs("div",{className:"admin-summary-card admin-summary-fail",children:[s.jsx("div",{className:"admin-summary-value",children:Qe+jn}),s.jsx("div",{className:"admin-summary-label",children:"❌ Failing"})]}),s.jsxs("div",{className:"admin-summary-card",children:[s.jsx("div",{className:"admin-summary-value",children:xt.length}),s.jsx("div",{className:"admin-summary-label",children:"Providers"})]})]}),s.jsx("h3",{className:"section-subtitle",children:"⚙️ System Checks (buff doctor)"}),s.jsx("div",{className:"admin-check-list",children:e.system.map(G=>s.jsx(m_,{check:G},G.name))}),s.jsx("h3",{className:"section-subtitle",children:"🏥 Enterprise Self-Check (doctor --enterprise)"}),s.jsx("div",{className:"admin-check-list",children:e.enterprise.length>0?e.enterprise.map(G=>s.jsx(m_,{check:G},G.name)):s.jsx("div",{className:"empty-state",children:"No enterprise checks returned."})}),s.jsx("h3",{className:"section-subtitle",children:"🔑 Provider Configuration (keys masked)"}),s.jsx("div",{className:"admin-table-wrapper",children:s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Provider"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Key"}),s.jsx("th",{children:"Base URL"}),s.jsx("th",{children:"Model"}),s.jsx("th",{children:"Actions"})]})}),s.jsxs("tbody",{children:[xt.map(G=>{const he=dt(G.type),Ie=A[G.type]||{};return s.jsxs("tr",{children:[s.jsxs("td",{className:"admin-provider-type",children:[he.icon?`${he.icon} `:"",he.label,s.jsxs("div",{className:"admin-provider-sub",children:[G.type," · ",pse[G.keySource]||G.keySource]}),G.keySource==="env"?s.jsxs("div",{className:"admin-hint",children:["comes from ",he.envVar||"env var"," — change it there, config can't override it"]}):G.keySource==="vault"?s.jsx("div",{className:"admin-hint",children:"stored in the OS keyring (vault)"}):null]}),s.jsx("td",{children:s.jsx("span",{className:`admin-check-badge ${G.configured?"admin-check-pass":"admin-check-warn"}`,children:G.configured?"✅ Configured":"⚠️ Not configured"})}),s.jsx("td",{children:he.keyless?s.jsx("div",{className:"admin-hint",children:"No key needed (probed)"}):Ne?s.jsx("input",{className:"admin-input admin-key-input",type:"password","aria-label":`${G.type} API key`,placeholder:G.keyMasked||"set a new key…",value:Ie.apiKey??"",onChange:Re=>Qt(G.type,"apiKey",Re.target.value),autoComplete:"new-password"}):s.jsx("div",{className:"admin-hint",children:G.keyMasked||"—"})}),s.jsx("td",{children:Ne?s.jsx("input",{className:"admin-input",type:"text","aria-label":`${G.type} base URL`,placeholder:G.baseUrl||"default endpoint",value:Ie.baseUrl??"",onChange:Re=>Qt(G.type,"baseUrl",Re.target.value)}):s.jsx("div",{className:"admin-hint",children:G.baseUrl?G.baseUrl.replace(/^https?:\/\/(?:[^@/]*@)?/,""):"default endpoint"})}),s.jsx("td",{children:Ne?s.jsx("input",{className:"admin-input",type:"text","aria-label":`${G.type} model`,placeholder:G.model||"default model",value:Ie.model??"",onChange:Re=>Qt(G.type,"model",Re.target.value)}):s.jsx("div",{className:"admin-hint",children:G.model||"default model"})}),s.jsx("td",{children:Ne?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"admin-row-actions",children:[s.jsx("button",{className:"admin-mini-btn",disabled:K===G.type,onClick:()=>void $t(G.type),children:"💾 Save"}),s.jsx("button",{className:"admin-mini-btn",disabled:K===G.type,title:"Tests the SAVED configuration — save first to test a new key",onClick:()=>void V(G.type),children:"🔌 Test"}),s.jsx("button",{className:"admin-mini-btn admin-mini-danger",disabled:K===G.type,onClick:()=>void U(G.type),children:"🗑 Remove"})]}),le[G.type]?s.jsx("div",{className:"admin-row-msg",children:le[G.type]}):null]}):s.jsx("div",{className:"admin-hint",children:"read-only"})})]},G.type)}),xt.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:6,className:"admin-empty-cell",children:"No providers configured yet."})}):null]})]})}),Ne&&O.length>0?s.jsxs("div",{className:"admin-add-provider",children:[s.jsxs("select",{className:"admin-input",value:me,onChange:G=>Pe(G.target.value),children:[s.jsx("option",{value:"",children:"Add a provider…"}),O.filter(G=>!xt.some(he=>he.type===G.id)).map(G=>s.jsxs("option",{value:G.id,children:[G.icon?`${G.icon} `:"",G.label," (",G.id,")"]},G.id))]}),s.jsx("button",{className:"admin-mini-btn",disabled:!me,onClick:se,children:"➕ Add"})]}):null,s.jsx(dse,{authed:c,role:d||"viewer"}),Ne?s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"section-subtitle",children:"👥 Dashboard Users (role.manage)"}),s.jsxs("div",{className:"admin-users-list",children:[N.map(G=>s.jsxs("div",{className:"admin-user-row",children:[s.jsx("span",{className:"admin-user-name",children:G.user}),s.jsx("span",{className:`admin-role-badge admin-role-${G.role}`,children:G.role}),s.jsxs("span",{className:"admin-user-since",children:["since ",new Date(G.createdAt).toLocaleDateString()]}),G.user!==h?s.jsx("button",{className:"admin-mini-btn admin-mini-danger",onClick:()=>void Me(G.user),children:"🗑 Remove user"}):s.jsx("span",{className:"admin-hint",children:"you"})]},G.user)),N.length===0?s.jsx("div",{className:"empty-state",children:"No dashboard users yet."}):null]}),s.jsxs("form",{className:"admin-gate-form admin-user-form",onSubmit:Ze,children:[s.jsxs("label",{children:[s.jsx("span",{children:"Username"}),s.jsx("input",{type:"text",value:R,onChange:G=>L(G.target.value),autoComplete:"off"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Password (min 8 chars)"}),s.jsx("input",{type:"password",value:I,onChange:G=>z(G.target.value),autoComplete:"new-password"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Role"}),s.jsxs("select",{value:D,onChange:G=>F(G.target.value),children:[s.jsx("option",{value:"viewer",children:"viewer — read-only"}),s.jsx("option",{value:"operator",children:"operator — read-only in the dashboard today"}),s.jsx("option",{value:"admin",children:"admin — full control"})]})]}),T?s.jsx("div",{className:"admin-row-msg",children:T}):null,s.jsx("button",{className:"admin-refresh-btn",type:"submit",disabled:!R||!I,children:"➕ Add user"})]})]}):null]}):n?s.jsxs("div",{className:"loading-state",children:[s.jsx("div",{className:"loading-spinner"}),s.jsx("p",{children:"Running all state checks…"})]}):null]})}function oM(e){return String(e??"").replace(/\d{3,}/g,t=>t.slice(0,2)+"***")}const gse={idle:"Not paired",pairing:"⏳ Pairing…",paired:"✅ Paired",failed:"❌ Pairing failed",cancelled:"⏹ Cancelled",error:"💥 Pairing error"};function yse({authed:e,canWrite:t,sessionExpired:n,reveal:r=!1}){const[i,a]=E.useState(null),[o,l]=E.useState({}),[c,u]=E.useState(""),[d,f]=E.useState(!1),[h,p]=E.useState(null),g=E.useRef(null),m=E.useCallback(async()=>{const w=await ee.getWhatsAppStatus();w&&(a(w.status),l(w.contacts??{}))},[]);E.useEffect(()=>{if(m(),!e||typeof EventSource>"u")return;const w=ee.subscribeWhatsApp({onQr:_=>a(N=>N&&{...N,qr:_,state:"pairing"}),onCode:_=>a(N=>N&&{...N,pairingCode:_}),onStatus:_=>{a(_),(_.state==="paired"||_.state==="failed"||_.state==="error"||_.state==="cancelled")&&f(!1)}});return g.current=w,()=>{w(),g.current=null}},[e,m]);const v=async w=>{f(!0),p(null);const _=await w();if(!_.ok&&_.error&&/Not authenticated|Session expired/i.test(_.error)){n(),f(!1);return}_.ok?(p({kind:"ok",text:"Done."}),await m()):p({kind:"err",text:_.error||"Action failed."}),f(!1)},y=w=>{p(null),v(()=>ee.startWhatsAppPair(w?c.trim():void 0)).then(()=>u(""))},b=()=>{p(null),v(()=>ee.cancelWhatsAppPair())},x=()=>{window.confirm("Remove the paired WhatsApp session from this machine? You will need to scan a QR to pair again.")&&(p(null),v(()=>ee.unpairWhatsApp()))},k=(i==null?void 0:i.state)??"idle",S=k==="pairing";return s.jsxs("div",{className:"wa-panel",children:[s.jsxs("div",{className:"wa-panel-head",children:[s.jsx("span",{className:"wa-panel-title",children:"🟢 WhatsApp bridge"}),i?s.jsx("span",{className:`wa-badge ${i.paired?"wa-badge-paired":S?"wa-badge-pairing":""}`,children:gse[k]}):s.jsx("span",{className:"admin-hint",children:"loading…"})]}),s.jsxs("p",{className:"admin-hint",children:["The personal Baileys bridge (no Meta Business account) — pair once, and the gateway can send & receive WhatsApp. Session: ",s.jsx("code",{children:(i==null?void 0:i.sessionDir)??"~/.buff/whatsapp/session"}),". Same engine as"," ",s.jsx("code",{children:"buff whatsapp pair"}),"."]}),S?s.jsxs("div",{className:"wa-pairing",children:[i!=null&&i.qr?s.jsxs("div",{className:"wa-qr-box",children:[s.jsx("img",{className:"wa-qr-img",src:i.qr,alt:"WhatsApp pairing QR code"}),s.jsxs("p",{className:"admin-hint",children:["Open WhatsApp on the phone → ",s.jsx("strong",{children:"Linked devices → Link a device → scan"}),". The QR refreshes automatically while this window is open."]})]}):i!=null&&i.phone?s.jsxs("div",{className:"wa-code-box",children:[s.jsxs("p",{className:"admin-hint",children:["On the phone with ",s.jsx("strong",{children:i.phone}),": WhatsApp → Linked devices → Link a device →"," ",s.jsx("strong",{children:"“Link with phone number instead”"})," → enter:"]}),s.jsx("div",{className:"wa-code",children:i.pairingCode??"… waiting for code"})]}):s.jsx("div",{className:"wa-code-box",children:s.jsx("p",{className:"admin-hint",children:"Waiting for WhatsApp to hand over a QR… (it usually appears within a few seconds)"})}),i!=null&&i.phone?null:s.jsxs("div",{className:"admin-hint",children:["Tip: on a phone, “Link with phone number instead” needs the number format"," ",s.jsx("code",{children:"918844433322"})," (country code included) — enter it below instead of scanning."]}),i!=null&&i.error?s.jsx("div",{className:"admin-row-msg admin-row-msg-err",children:i.error}):null,t&&e?s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:b,disabled:d,children:d?"⏳…":"⏹ Cancel pairing"}):null]}):s.jsxs("div",{className:"wa-actions",children:[t&&e?i!=null&&i.paired?s.jsxs("div",{className:"wa-action-row",children:[s.jsx("button",{className:"admin-refresh-btn wa-unpair-btn",type:"button",onClick:x,disabled:d,children:d?"⏳…":"🗑 Unpair (remove session)"}),s.jsx("span",{className:"admin-hint",children:"Removes creds.json — you will need to scan a QR again."})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"wa-action-row",children:[s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>y(!1),disabled:d,children:d?"⏳…":"🔳 Pair with a QR"}),s.jsx("span",{className:"admin-hint",children:"Scans from the phone you want to link."})]}),s.jsxs("div",{className:"wa-action-row wa-phone-row",children:[s.jsx("input",{type:"text",className:"wa-phone-input",value:c,onChange:w=>u(w.target.value),placeholder:"or pair with a number — e.g. 918844433322",disabled:d,maxLength:16}),s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>y(!0),disabled:d||!c.trim(),children:"Pair by number"})]})]}):null,k==="failed"||k==="error"||k==="cancelled"?s.jsx("div",{className:"admin-row-msg admin-row-msg-err",children:(i==null?void 0:i.error)||(k==="cancelled"?"Pairing cancelled.":"Pairing failed — try again.")}):null,e?t?null:s.jsx("div",{className:"admin-row-msg",children:"Your role can view pairing status but not change it (requires admin or operator)."}):s.jsx("div",{className:"admin-row-msg",children:"Log in (admin or operator) to pair, cancel, or unpair."}),h?s.jsx("div",{className:`admin-row-msg${h.kind==="ok"?"":" admin-row-msg-err"}`,children:h.text}):null]}),s.jsxs("div",{className:"wa-contacts",children:[s.jsxs("div",{className:"wa-contacts-head",children:[s.jsx("span",{className:"wa-panel-title",children:"📇 Send-by-name contacts"}),s.jsxs("span",{className:"admin-hint",children:[Object.keys(o).length," mapped"]})]}),s.jsxs("p",{className:"admin-hint",children:["These names are for ",s.jsx("strong",{children:"sending messages by name"})," (e.g."," ",s.jsx("code",{children:'buff gateway send whatsapp:Name "…"'}),") — they do"," ",s.jsx("strong",{children:"NOT"})," let these numbers trigger the agent."]}),s.jsx("div",{className:"hub-alias-list",children:Object.keys(o).length===0?s.jsxs("span",{className:"admin-hint",children:["(none — add one with ",s.jsx("code",{children:"buff whatsapp contact add <Name> <number>"}),")"]}):Object.entries(o).map(([w,_])=>s.jsxs("div",{className:"hub-alias-row",children:[s.jsx("span",{className:"hub-chip",children:w}),s.jsxs("span",{className:"admin-hint",children:["→ ",r?_:oM(_)]})]},w))}),s.jsxs("p",{className:"admin-hint",style:{marginTop:8},children:["To let a number ",s.jsx("strong",{children:"trigger the agent"})," (respond to its messages), add it to the"," ",s.jsx("strong",{children:"verified list"})," in the ",s.jsx("strong",{children:"Permissions tab above"}),", or run"," ",s.jsx("code",{children:"buff config gateway allow whatsapp user <number>"}),"."]})]})]})}function vse({canWrite:e,sessionExpired:t,mode:n="grid"}){const[r,i]=E.useState(null),[a,o]=E.useState(null),[l,c]=E.useState(null),[u,d]=E.useState(null),[f,h]=E.useState(null),[p,g]=E.useState(0),[m,v]=E.useState({}),[y,b]=E.useState(!1),[x,k]=E.useState(null),S=E.useRef(!0),w=E.useCallback(async()=>{const L=await ee.getPlatformConfigs();S.current&&i(L)},[t]);E.useEffect(()=>(w(),()=>{S.current=!1}),[w]);const _=async(L,I)=>{c(L),d(null);const z=await ee.setPlatformConfig(L,I);if(S.current){if(c(null),z.unauthorized||z.forbidden){t(z.error);return}d({kind:z.ok?"ok":"err",text:z.ok?"Saved — transport active.":z.error||"Save failed."}),z.ok&&(o(null),w())}},N=async L=>{if(!window.confirm(`Remove ${L} transport config? Tokens will be deleted from ~/.buff/.env.`))return;c(L),d(null);const I=await ee.removePlatformConfig(L);if(S.current){if(c(null),I.unauthorized||I.forbidden){t(I.error);return}d({kind:I.ok?"ok":"err",text:I.ok?"Removed.":I.error||"Remove failed."}),I.ok&&w()}},C={telegram:{steps:["Open Telegram and search for @BotFather","Send /newbot to BotFather and follow the prompts",'Give your bot a name (e.g. "My Agent Bot")','Give your bot a username (must end with "bot", e.g. "my_agent_bot")',"BotFather will give you a token — paste it in the field below","Open your bot in Telegram and send it a message (e.g. /start)"],postSetup:["Start the gateway: buff gateway start (or from the Gateway tab)","Open your bot in Telegram and send a message — the agent replies!"]},discord:{steps:["Go to https://discord.com/developers/applications",'Click "New Application" → give it a name → Create','Go to "Bot" in the left sidebar → click "Add Bot"','Under "Token", click "Copy" to copy the bot token','Enable "Message Content Intent" under Privileged Gateway Intents',"Invite the bot to your server with the OAuth2 URL generator"],postSetup:["Start the gateway: buff gateway start","Mention the bot in a Discord channel or send it a DM","The agent will reply automatically!"]},slack:{steps:["Go to https://api.slack.com/apps",'Click "Create New App" → "From scratch"',"Add Bot Token Scopes: chat:write, im:read, im:write","Install the app to your workspace","Copy the Bot User OAuth Token (starts with xoxb-)"],postSetup:["Start the gateway: buff gateway start","DM the bot or mention it in a channel","The agent will reply automatically!"]},email:{steps:["You need an SMTP relay (Gmail, SendGrid, Mailgun, etc.)","For Gmail: use smtp.gmail.com:587 with an App Password","For SendGrid/Mailgun: get SMTP credentials from their dashboard"],postSetup:["Start the gateway: buff gateway start","Send an email to the configured address","The agent will reply via email!"]}},T=L=>{e&&(h(L),g(0),v(Object.fromEntries(L.envVars.map(I=>[I.varName,I.value]))),k(null))},$=async()=>{if(!f||!e)return;b(!0),k(null);const L=await ee.setPlatformConfig(f.platform,m);if(b(!1),L.unauthorized||L.forbidden){t(L.error);return}L.ok?(k({kind:"ok",text:"✅ Token saved! The transport is now active."}),w()):k({kind:"err",text:L.error||"Save failed."})};if(r===null)return s.jsx("div",{className:"empty-state",children:"Loading platform transports…"});const R=f?C[f.platform]:null;return n==="table"?s.jsxs(s.Fragment,{children:[f&&R?s.jsx("div",{className:"wizard-overlay",onClick:()=>h(null),children:s.jsxs("div",{className:"wizard-modal",onClick:L=>L.stopPropagation(),children:[s.jsxs("div",{className:"wizard-header",children:[s.jsx("span",{className:"wizard-icon",children:"🚀"}),s.jsxs("span",{className:"wizard-title",children:["Getting Started: ",f.label]}),s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>h(null),children:"✕"})]}),s.jsx("div",{className:"wizard-body",children:p===0?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"wizard-section-title",children:"📋 Steps to create your bot:"}),s.jsx("ol",{className:"wizard-steps",children:R.steps.map((L,I)=>s.jsx("li",{children:L},I))}),s.jsxs("div",{className:"wizard-nav",children:[s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>g(1),children:"I have my token →"}),f.setupUrl?s.jsx("a",{href:f.setupUrl,target:"_blank",rel:"noopener noreferrer",className:"admin-mini-btn platform-docs-link",children:"📖 Docs"}):null]})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"wizard-section-title",children:"🔑 Paste your token:"}),f.envVars.map(L=>s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:L.prompt}),s.jsx("input",{type:L.secret?"password":"text",value:m[L.varName]??"",onChange:I=>v(z=>({...z,[L.varName]:I.target.value})),placeholder:L.secret?"••••••••":"value",autoComplete:"off",spellCheck:!1,autoFocus:!0})]},L.varName)),x?s.jsx("div",{className:`admin-row-msg${x.kind==="ok"?"":" admin-row-msg-err"}`,children:x.text}):null,s.jsxs("div",{className:"wizard-nav",children:[s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>g(0),children:"← Back"}),s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void $(),disabled:y||!e,children:y?"⏳ Saving…":"💾 Save token"})]}),(x==null?void 0:x.kind)==="ok"?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"wizard-section-title",children:"📋 Next steps:"}),s.jsx("ol",{className:"wizard-steps",children:R.postSetup.map((L,I)=>s.jsx("li",{children:L},I))})]}):null]})})]})}):null,u?s.jsx("div",{className:`admin-row-msg${u.kind==="ok"?"":" admin-row-msg-err"}`,children:u.text}):null,s.jsx("div",{className:"platform-config-table-wrapper",children:s.jsxs("table",{className:"platform-config-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Platform"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Configuration"}),s.jsx("th",{children:"CLI Command"})]})}),s.jsx("tbody",{children:r.map(L=>s.jsxs(W.Fragment,{children:[s.jsxs("tr",{className:`platform-config-row ${L.configured?"configured":""}`,children:[s.jsxs("td",{className:"platform-config-name",children:[s.jsx("span",{className:"hub-platform-label",children:L.label}),s.jsx("span",{className:"hub-card-id",children:L.platform})]}),s.jsxs("td",{children:[s.jsx("span",{className:`status-dot ${L.configured?"connected":"reconnecting"}`}),s.jsx("span",{className:"platform-config-status-text",children:L.configured?"Active":"Not configured"})]}),s.jsxs("td",{className:"platform-config-actions",children:[L.configured?null:s.jsx("button",{type:"button",className:"wizard-start-btn",onClick:()=>T(L),disabled:!e,children:"🚀 Getting Started"}),L.setupUrl?s.jsx("a",{href:L.setupUrl,target:"_blank",rel:"noopener noreferrer",className:"admin-mini-btn platform-docs-link",children:"📖 Docs"}):null,s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>o(a===L.platform?null:L.platform),disabled:!e,children:a===L.platform?"▴ Close":L.configured?"✎ Edit":"⚙ Configure"}),L.configured?s.jsx("button",{type:"button",className:"admin-mini-btn contact-delete-btn",onClick:()=>void N(L.platform),disabled:!e,children:"🗑️"}):null]}),s.jsx("td",{className:"platform-config-cli",children:s.jsxs("code",{children:["buff gateway setup ",L.platform]})})]}),a===L.platform?s.jsx("tr",{className:"platform-config-expanded",children:s.jsx("td",{colSpan:4,children:s.jsxs("div",{className:"platform-config-form",children:[L.envVars.map(I=>s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:I.prompt}),s.jsx("input",{type:I.secret?"password":"text",value:I.value,readOnly:!0,className:"platform-config-readonly",placeholder:I.secret?"••••••••":"value"})]},I.varName)),s.jsxs("p",{className:"admin-hint",children:["Tokens are in ",s.jsx("code",{children:"~/.buff/.env"})," — edit there or use the wizard above."]})]})})}):null]},L.platform))})]})})]}):s.jsxs(s.Fragment,{children:[f&&R?s.jsx("div",{className:"wizard-overlay",onClick:()=>h(null),children:s.jsxs("div",{className:"wizard-modal",onClick:L=>L.stopPropagation(),children:[s.jsxs("div",{className:"wizard-header",children:[s.jsx("span",{className:"wizard-icon",children:"🚀"}),s.jsxs("span",{className:"wizard-title",children:["Getting Started: ",f.label]}),s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>h(null),children:"✕"})]}),s.jsx("div",{className:"wizard-body",children:p===0?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"wizard-section-title",children:"📋 Steps to create your bot:"}),s.jsx("ol",{className:"wizard-steps",children:R.steps.map((L,I)=>s.jsx("li",{children:L},I))}),s.jsxs("div",{className:"wizard-nav",children:[s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>g(1),children:"I have my token →"}),f.setupUrl?s.jsx("a",{href:f.setupUrl,target:"_blank",rel:"noopener noreferrer",className:"admin-mini-btn platform-docs-link",children:"📖 Open docs in new tab"}):null]})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"wizard-section-title",children:"🔑 Paste your token:"}),f.envVars.map(L=>s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:L.prompt}),s.jsx("input",{type:L.secret?"password":"text",value:m[L.varName]??"",onChange:I=>v(z=>({...z,[L.varName]:I.target.value})),placeholder:L.secret?"••••••••":"value",autoComplete:"off",spellCheck:!1,autoFocus:!0})]},L.varName)),x?s.jsx("div",{className:`admin-row-msg${x.kind==="ok"?"":" admin-row-msg-err"}`,children:x.text}):null,s.jsxs("div",{className:"wizard-nav",children:[s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>g(0),children:"← Back"}),s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void $(),disabled:y||!e,children:y?"⏳ Saving…":"💾 Save token"})]}),(x==null?void 0:x.kind)==="ok"?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"wizard-section-title",children:"📋 Next steps:"}),s.jsx("ol",{className:"wizard-steps",children:R.postSetup.map((L,I)=>s.jsx("li",{children:L},I))})]}):null]})})]})}):null,s.jsxs("div",{className:"platform-config",children:[s.jsx("h3",{className:"section-subtitle",children:"⚙️ Platform transports (buff config gateway)"}),u?s.jsx("div",{className:`admin-row-msg${u.kind==="ok"?"":" admin-row-msg-err"}`,children:u.text}):null,s.jsx("div",{className:"hub-platform-grid",children:r.map(L=>s.jsx(bse,{entry:L,canWrite:e,busy:l===L.platform,expanded:a===L.platform,onToggle:()=>o(a===L.platform?null:L.platform),onSave:I=>void _(L.platform,I),onRemove:()=>void N(L.platform),onStartWizard:()=>T(L)},L.platform))}),s.jsxs("p",{className:"admin-hint",children:["Tokens are written to ",s.jsx("code",{children:"~/.buff/.env"})," (loaded by both the CLI and this dashboard at startup) — no env vars to hand-export. The WhatsApp personal bridge is configured separately above via QR/code pairing."]})]})]})}function bse(e){const{entry:t,canWrite:n,busy:r,expanded:i,onToggle:a,onSave:o,onRemove:l,onStartWizard:c}=e,[u,d]=E.useState(()=>Object.fromEntries(t.envVars.map(h=>[h.varName,h.value]))),f=(h,p)=>{d(g=>({...g,[h]:p}))};return s.jsxs("div",{className:`hub-platform${t.configured?" configured":""}`,children:[s.jsxs("div",{className:"hub-platform-head",children:[s.jsx("span",{className:`status-dot ${t.configured?"connected":"reconnecting"}`}),s.jsx("span",{className:"hub-platform-label",children:t.label}),s.jsx("span",{className:"hub-card-id",children:t.platform}),t.configured?null:s.jsx("button",{type:"button",className:"wizard-start-btn",onClick:c,disabled:!n,title:"Step-by-step setup wizard",children:"🚀 Getting Started"}),t.setupUrl?s.jsx("a",{href:t.setupUrl,target:"_blank",rel:"noopener noreferrer",className:"admin-mini-btn platform-docs-link",title:"Setup documentation",children:"📖 Docs"}):null,s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:a,disabled:!n,children:i?"▴ Collapse":t.configured?"✎ Edit":"⚙ Configure"})]}),!i&&t.setupHint&&!t.configured?s.jsx("div",{className:"platform-setup-hint",children:t.setupHint}):null,i?s.jsxs("div",{className:"platform-config-form",children:[t.setupHint?s.jsx("div",{className:"platform-setup-hint",children:t.setupHint}):null,t.envVars.map(h=>s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:h.prompt}),s.jsx("input",{type:h.secret?"password":"text",value:u[h.varName]??"",onChange:p=>f(h.varName,p.target.value),placeholder:h.secret?"••••••••":"value",autoComplete:"off",spellCheck:!1,maxLength:512})]},h.varName)),s.jsxs("div",{className:"platform-config-actions",children:[s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>o(u),disabled:r||!n,children:r?"⏳ Saving…":"💾 Save"}),t.configured?s.jsx("button",{type:"button",className:"hub-remove-btn",onClick:l,disabled:r||!n,children:"🗑 Remove"}):null]})]}):s.jsx("div",{className:"hub-platform-env",children:t.envVars.map(h=>s.jsxs("div",{children:[s.jsx("code",{children:h.varName})," ",h.set?"✓ set":"— unset"]},h.varName))})]})}const xse=[{id:"tools",label:"Tools",icon:"🧰"},{id:"channels",label:"Channels",icon:"📡"},{id:"conversations",label:"Conversations",icon:"💬"},{id:"artifacts",label:"Artifacts",icon:"📦"},{id:"skills",label:"Skills",icon:"🧠"}],wse={pending:"⏳ pending",sent:"✅ sent",failed:"❌ failed"};function Sse(){var F0,U0,W0,H0,G0,q0,K0,V0,Y0;const[e,t]=E.useState("tools"),[n,r]=E.useState(null),[i,a]=E.useState(!0),[o,l]=E.useState(null),[c,u]=E.useState(!1),[d,f]=E.useState(null),[h,p]=E.useState(!1),[g,m]=E.useState(null),[v,y]=E.useState(null),[b,x]=E.useState(""),[k,S]=E.useState(""),[w,_]=E.useState(null),[N,C]=E.useState(!1),[T,$]=E.useState(null),[R,L]=E.useState(null),[I,z]=E.useState({}),[D,F]=E.useState(""),[O,P]=E.useState(""),[A,Y]=E.useState(!1),[K,M]=E.useState(null),[le,be]=E.useState(!1),[me,Pe]=E.useState({}),[H,X]=E.useState(!1),[oe,ce]=E.useState(null),[Z,_e]=E.useState({}),[we,Ne]=E.useState({}),[ge,Be]=E.useState({}),[pe,Ct]=E.useState(!1),[We,Oe]=E.useState(null),[Ze,Me]=E.useState(""),[Qt,$t]=E.useState(null),[U,V]=E.useState(!1),[se,fe]=E.useState(new Map),[Se,Qe]=E.useState(new Set),[Lt,Ot]=E.useState(!1),[jn,xt]=E.useState([]),[dt,G]=E.useState(""),[he,Ie]=E.useState(null),[Re,Cr]=E.useState(""),[Jt,An]=E.useState([]),[ys,zp]=E.useState(0),[vs,bs]=E.useState(0),[Ni,xs]=E.useState(!0),[ze,ws]=E.useState(!1),[Xr,Ht]=E.useState(!1),ji=20,Ai=E.useRef(null),Ti=E.useCallback(async(j=!1)=>{if(ze)return;const q=j?0:vs;ws(!0);try{const ne=await ee.fetchGatewayConversations({offset:q,limit:ji,q:Ze||void 0});ne.ok&&ne.conversations&&(An(re=>j?ne.conversations:[...re,...ne.conversations]),zp(ne.total??0),bs(q+ne.conversations.length),xs(ne.hasMore??!1))}catch{}ws(!1)},[ze,vs,Ze]);E.useEffect(()=>{e==="conversations"&&!Xr&&!ze&&(Ht(!0),Ti(!0))},[e,Xr,ze,Ti]),E.useEffect(()=>{const j=Ai.current;if(!j)return;const q=new IntersectionObserver(ne=>{var re;(re=ne[0])!=null&&re.isIntersecting&&Ni&&!ze&&Ti(!1)},{threshold:.1});return q.observe(j),()=>q.disconnect()},[Ni,ze,Ti]),E.useEffect(()=>{const j=setTimeout(()=>{e==="conversations"&&Xr&&(An([]),bs(0),xs(!0),Ti(!0))},300);return()=>clearTimeout(j)},[Ze]),E.useEffect(()=>ee.onTypingEvent(q=>{fe(ne=>{const re=new Map(ne),de=`${q.platform}:${q.channelId}`;return q.typing?re.set(de,{platform:q.platform,channelId:q.channelId,startedAt:Date.now()}):re.delete(de),re})}),[]);const Fp=E.useCallback((j,q)=>{q.stopPropagation(),Qe(ne=>{const re=new Set(ne);return re.has(j)?re.delete(j):re.add(j),re})},[]),cl=E.useCallback(()=>{Qe(j=>j.size===Jt.length?new Set:new Set(Jt.map(q=>q.key)))},[Jt]),Ss=E.useCallback(async()=>{if(Se.size!==0){Ot(!0);try{await ee.exportGatewayConversations([...Se])}catch{}Ot(!1)}},[Se]);E.useEffect(()=>{e==="conversations"&&ee.getAllConversationTags().then(j=>{j.ok&&j.tags&&xt(j.tags)})},[e]);const Up=E.useCallback(async(j,q)=>{if(!q.trim())return;(await ee.addConversationTag(j,q.trim())).ok&&(An(re=>re.map(de=>de.key===j?{...de,tags:[...de.tags??[],q.trim().toLowerCase()]}:de)),xt(re=>re.includes(q.trim().toLowerCase())?re:[...re,q.trim().toLowerCase()].sort())),Ie(null),Cr("")},[]),Cu=E.useCallback(async(j,q)=>{(await ee.removeConversationTag(j,q)).ok&&An(re=>re.map(de=>de.key===j?{...de,tags:(de.tags??[]).filter(Te=>Te!==q)}:de))},[]),Wp=E.useCallback((j,q)=>{q.stopPropagation();const ne=j.contactName||j.channelId,re=[`Conversation with ${ne} (${j.platform})`,`Exported: ${new Date().toLocaleString()}`,`Messages: ${j.messageCount}`,"─".repeat(50),""];if(j.messages)for(const ht of j.messages){const xe=ht.role==="user"?ne:"Agent",Nt=new Date(ht.ts).toLocaleString();re.push(`[${Nt}] ${xe}:`),re.push(ht.content),re.push("")}const de=new Blob([re.join(`
|
|
134
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function qP(e,t){if(e){if(typeof e=="string")return Hv(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Hv(e,t)}}function iie(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function aie(e){if(Array.isArray(e))return Hv(e)}function Hv(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function YE(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function Q(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?YE(Object(n),!0).forEach(function(r){Ae(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):YE(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Ae(e,t,n){return t=KP(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function KP(e){var t=sie(e,"string");return Bo(t)=="symbol"?t:t+""}function sie(e,t){if(Bo(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Bo(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var oie={xAxis:["bottom","top"],yAxis:["left","right"]},lie={width:"100%",height:"100%"},VP={x:0,y:0};function hd(e){return e}var cie=function(t,n){return n==="horizontal"?t.x:n==="vertical"?t.y:n==="centric"?t.angle:t.radius},uie=function(t,n,r,i){var a=n.find(function(d){return d&&d.index===r});if(a){if(t==="horizontal")return{x:a.coordinate,y:i.y};if(t==="vertical")return{x:i.x,y:a.coordinate};if(t==="centric"){var o=a.coordinate,l=i.radius;return Q(Q(Q({},i),rn(i.cx,i.cy,l,o)),{},{angle:o,radius:l})}var c=a.coordinate,u=i.angle;return Q(Q(Q({},i),rn(i.cx,i.cy,c,u)),{},{angle:u,radius:c})}return VP},Pp=function(t,n){var r=n.graphicalItems,i=n.dataStartIndex,a=n.dataEndIndex,o=(r??[]).reduce(function(l,c){var u=c.props.data;return u&&u.length?[].concat(zo(l),zo(u)):l},[]);return o.length>0?o:t&&t.length&&ue(i)&&ue(a)?t.slice(i,a+1):[]};function YP(e){return e==="number"?[0,"auto"]:void 0}var Gv=function(t,n,r,i){var a=t.graphicalItems,o=t.tooltipAxis,l=Pp(n,t);return r<0||!a||!a.length||r>=l.length?null:a.reduce(function(c,u){var d,f=(d=u.props.data)!==null&&d!==void 0?d:n;f&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=r&&(f=f.slice(t.dataStartIndex,t.dataEndIndex+1));var h;if(o.dataKey&&!o.allowDuplicatedCategory){var p=f===void 0?l:f;h=Ey(p,o.dataKey,i)}else h=f&&f[r]||l[r];return h?[].concat(zo(c),[qO(u,h)]):c},[])},XE=function(t,n,r,i){var a=i||{x:t.chartX,y:t.chartY},o=cie(a,r),l=t.orderedTooltipTicks,c=t.tooltipAxis,u=t.tooltipTicks,d=RY(o,l,u,c);if(d>=0&&u){var f=u[d]&&u[d].value,h=Gv(t,n,d,f),p=uie(r,l,d,a);return{activeTooltipIndex:d,activeLabel:f,activePayload:h,activeCoordinate:p}}return null},die=function(t,n){var r=n.axes,i=n.graphicalItems,a=n.axisType,o=n.axisIdKey,l=n.stackGroups,c=n.dataStartIndex,u=n.dataEndIndex,d=t.layout,f=t.children,h=t.stackOffset,p=WO(d,a);return r.reduce(function(g,m){var v,y=m.type.defaultProps!==void 0?Q(Q({},m.type.defaultProps),m.props):m.props,b=y.type,x=y.dataKey,k=y.allowDataOverflow,S=y.allowDuplicatedCategory,w=y.scale,_=y.ticks,N=y.includeHidden,C=y[o];if(g[C])return g;var T=Pp(t.data,{graphicalItems:i.filter(function(K){var M,le=o in K.props?K.props[o]:(M=K.type.defaultProps)===null||M===void 0?void 0:M[o];return le===C}),dataStartIndex:c,dataEndIndex:u}),$=T.length,R,L,I;Lre(y.domain,k,b)&&(R=dv(y.domain,null,k),p&&(b==="number"||w!=="auto")&&(I=nc(T,x,"category")));var z=YP(b);if(!R||R.length===0){var D,F=(D=y.domain)!==null&&D!==void 0?D:z;if(x){if(R=nc(T,x,b),b==="category"&&p){var O=S3(R);S&&O?(L=R,R=rh(0,$)):S||(R=Mk(F,R,m).reduce(function(K,M){return K.indexOf(M)>=0?K:[].concat(zo(K),[M])},[]))}else if(b==="category")S?R=R.filter(function(K){return K!==""&&!Ve(K)}):R=Mk(F,R,m).reduce(function(K,M){return K.indexOf(M)>=0||M===""||Ve(M)?K:[].concat(zo(K),[M])},[]);else if(b==="number"){var P=BY(T,i.filter(function(K){var M,le,be=o in K.props?K.props[o]:(M=K.type.defaultProps)===null||M===void 0?void 0:M[o],me="hide"in K.props?K.props.hide:(le=K.type.defaultProps)===null||le===void 0?void 0:le.hide;return be===C&&(N||!me)}),x,a,d);P&&(R=P)}p&&(b==="number"||w!=="auto")&&(I=nc(T,x,"category"))}else p?R=rh(0,$):l&&l[C]&&l[C].hasStack&&b==="number"?R=h==="expand"?[0,1]:GO(l[C].stackGroups,c,u):R=UO(T,i.filter(function(K){var M=o in K.props?K.props[o]:K.type.defaultProps[o],le="hide"in K.props?K.props.hide:K.type.defaultProps.hide;return M===C&&(N||!le)}),b,d,!0);if(b==="number")R=Uv(f,R,C,a,_),F&&(R=dv(F,R,k));else if(b==="category"&&F){var A=F,Y=R.every(function(K){return A.indexOf(K)>=0});Y&&(R=A)}}return Q(Q({},g),{},Ae({},C,Q(Q({},y),{},{axisType:a,domain:R,categoricalDomain:I,duplicateDomain:L,originalDomain:(v=y.domain)!==null&&v!==void 0?v:z,isCategorical:p,layout:d})))},{})},fie=function(t,n){var r=n.graphicalItems,i=n.Axis,a=n.axisType,o=n.axisIdKey,l=n.stackGroups,c=n.dataStartIndex,u=n.dataEndIndex,d=t.layout,f=t.children,h=Pp(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:u}),p=h.length,g=WO(d,a),m=-1;return r.reduce(function(v,y){var b=y.type.defaultProps!==void 0?Q(Q({},y.type.defaultProps),y.props):y.props,x=b[o],k=YP("number");if(!v[x]){m++;var S;return g?S=rh(0,p):l&&l[x]&&l[x].hasStack?(S=GO(l[x].stackGroups,c,u),S=Uv(f,S,x,a)):(S=dv(k,UO(h,r.filter(function(w){var _,N,C=o in w.props?w.props[o]:(_=w.type.defaultProps)===null||_===void 0?void 0:_[o],T="hide"in w.props?w.props.hide:(N=w.type.defaultProps)===null||N===void 0?void 0:N.hide;return C===x&&!T}),"number",d),i.defaultProps.allowDataOverflow),S=Uv(f,S,x,a)),Q(Q({},v),{},Ae({},x,Q(Q({axisType:a},i.defaultProps),{},{hide:!0,orientation:or(oie,"".concat(a,".").concat(m%2),null),domain:S,originalDomain:k,isCategorical:g,layout:d})))}return v},{})},hie=function(t,n){var r=n.axisType,i=r===void 0?"xAxis":r,a=n.AxisComp,o=n.graphicalItems,l=n.stackGroups,c=n.dataStartIndex,u=n.dataEndIndex,d=t.children,f="".concat(i,"Id"),h=_r(d,a),p={};return h&&h.length?p=die(t,{axes:h,graphicalItems:o,axisType:i,axisIdKey:f,stackGroups:l,dataStartIndex:c,dataEndIndex:u}):o&&o.length&&(p=fie(t,{Axis:a,graphicalItems:o,axisType:i,axisIdKey:f,stackGroups:l,dataStartIndex:c,dataEndIndex:u})),p},pie=function(t){var n=Ui(t),r=li(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:Nx(r,function(i){return i.coordinate}),tooltipAxis:n,tooltipAxisBandSize:Kf(n,r)}},ZE=function(t){var n=t.children,r=t.defaultShowTooltip,i=Wn(n,Oo),a=0,o=0;return t.data&&t.data.length!==0&&(o=t.data.length-1),i&&i.props&&(i.props.startIndex>=0&&(a=i.props.startIndex),i.props.endIndex>=0&&(o=i.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:a,dataEndIndex:o,activeTooltipIndex:-1,isTooltipActive:!!r}},mie=function(t){return!t||!t.length?!1:t.some(function(n){var r=ui(n&&n.type);return r&&r.indexOf("Bar")>=0})},QE=function(t){return t==="horizontal"?{numericAxisName:"yAxis",cateAxisName:"xAxis"}:t==="vertical"?{numericAxisName:"xAxis",cateAxisName:"yAxis"}:t==="centric"?{numericAxisName:"radiusAxis",cateAxisName:"angleAxis"}:{numericAxisName:"angleAxis",cateAxisName:"radiusAxis"}},gie=function(t,n){var r=t.props,i=t.graphicalItems,a=t.xAxisMap,o=a===void 0?{}:a,l=t.yAxisMap,c=l===void 0?{}:l,u=r.width,d=r.height,f=r.children,h=r.margin||{},p=Wn(f,Oo),g=Wn(f,Ga),m=Object.keys(c).reduce(function(S,w){var _=c[w],N=_.orientation;return!_.mirror&&!_.hide?Q(Q({},S),{},Ae({},N,S[N]+_.width)):S},{left:h.left||0,right:h.right||0}),v=Object.keys(o).reduce(function(S,w){var _=o[w],N=_.orientation;return!_.mirror&&!_.hide?Q(Q({},S),{},Ae({},N,or(S,"".concat(N))+_.height)):S},{top:h.top||0,bottom:h.bottom||0}),y=Q(Q({},v),m),b=y.bottom;p&&(y.bottom+=p.props.height||Oo.defaultProps.height),g&&n&&(y=LY(y,i,r,n));var x=u-y.left-y.right,k=d-y.top-y.bottom;return Q(Q({brushBottom:b},y),{},{width:Math.max(x,0),height:Math.max(k,0)})},yie=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},vie=function(t){var n=t.chartName,r=t.GraphicalChild,i=t.defaultTooltipEventType,a=i===void 0?"axis":i,o=t.validateTooltipEventTypes,l=o===void 0?["axis"]:o,c=t.axisComponents,u=t.legendContent,d=t.formatAxisMap,f=t.defaultProps,h=function(y,b){var x=b.graphicalItems,k=b.stackGroups,S=b.offset,w=b.updateId,_=b.dataStartIndex,N=b.dataEndIndex,C=y.barSize,T=y.layout,$=y.barGap,R=y.barCategoryGap,L=y.maxBarSize,I=QE(T),z=I.numericAxisName,D=I.cateAxisName,F=mie(x),O=[];return x.forEach(function(P,A){var Y=Pp(y.data,{graphicalItems:[P],dataStartIndex:_,dataEndIndex:N}),K=P.type.defaultProps!==void 0?Q(Q({},P.type.defaultProps),P.props):P.props,M=K.dataKey,le=K.maxBarSize,be=K["".concat(z,"Id")],me=K["".concat(D,"Id")],Pe={},H=c.reduce(function(Oe,Ze){var Me=b["".concat(Ze.axisType,"Map")],Qt=K["".concat(Ze.axisType,"Id")];Me&&Me[Qt]||Ze.axisType==="zAxis"||as();var $t=Me[Qt];return Q(Q({},Oe),{},Ae(Ae({},Ze.axisType,$t),"".concat(Ze.axisType,"Ticks"),li($t)))},Pe),X=H[D],oe=H["".concat(D,"Ticks")],ce=k&&k[be]&&k[be].hasStack&&ZY(P,k[be].stackGroups),Z=ui(P.type).indexOf("Bar")>=0,_e=Kf(X,oe),we=[],Ne=F&&IY({barSize:C,stackGroups:k,totalSize:yie(H,D)});if(Z){var ge,Be,pe=Ve(le)?L:le,Ct=(ge=(Be=Kf(X,oe,!0))!==null&&Be!==void 0?Be:pe)!==null&&ge!==void 0?ge:0;we=$Y({barGap:$,barCategoryGap:R,bandSize:Ct!==_e?Ct:_e,sizeList:Ne[me],maxBarSize:pe}),Ct!==_e&&(we=we.map(function(Oe){return Q(Q({},Oe),{},{position:Q(Q({},Oe.position),{},{offset:Oe.position.offset-Ct/2})})}))}var We=P&&P.type&&P.type.getComposedData;We&&O.push({props:Q(Q({},We(Q(Q({},H),{},{displayedData:Y,props:y,dataKey:M,item:P,bandSize:_e,barPosition:we,offset:S,stackedData:ce,layout:T,dataStartIndex:_,dataEndIndex:N}))),{},Ae(Ae(Ae({key:P.key||"item-".concat(A)},z,H[z]),D,H[D]),"animationId",w)),childIndex:R3(P,y.children),item:P})}),O},p=function(y,b){var x=y.props,k=y.dataStartIndex,S=y.dataEndIndex,w=y.updateId;if(!j1({props:x}))return null;var _=x.children,N=x.layout,C=x.stackOffset,T=x.data,$=x.reverseStackOrder,R=QE(N),L=R.numericAxisName,I=R.cateAxisName,z=_r(_,r),D=VY(T,z,"".concat(L,"Id"),"".concat(I,"Id"),C,$),F=c.reduce(function(K,M){var le="".concat(M.axisType,"Map");return Q(Q({},K),{},Ae({},le,hie(x,Q(Q({},M),{},{graphicalItems:z,stackGroups:M.axisType===L&&D,dataStartIndex:k,dataEndIndex:S}))))},{}),O=gie(Q(Q({},F),{},{props:x,graphicalItems:z}),b==null?void 0:b.legendBBox);Object.keys(F).forEach(function(K){F[K]=d(x,F[K],O,K.replace("Map",""),n)});var P=F["".concat(I,"Map")],A=pie(P),Y=h(x,Q(Q({},F),{},{dataStartIndex:k,dataEndIndex:S,updateId:w,graphicalItems:z,stackGroups:D,offset:O}));return Q(Q({formattedGraphicalItems:Y,graphicalItems:z,offset:O,stackGroups:D},A),F)},g=function(v){function y(b){var x,k,S;return Xre(this,y),S=Jre(this,y,[b]),Ae(S,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),Ae(S,"accessibilityManager",new $re),Ae(S,"handleLegendBBoxUpdate",function(w){if(w){var _=S.state,N=_.dataStartIndex,C=_.dataEndIndex,T=_.updateId;S.setState(Q({legendBBox:w},p({props:S.props,dataStartIndex:N,dataEndIndex:C,updateId:T},Q(Q({},S.state),{},{legendBBox:w}))))}}),Ae(S,"handleReceiveSyncEvent",function(w,_,N){if(S.props.syncId===w){if(N===S.eventEmitterSymbol&&typeof S.props.syncMethod!="function")return;S.applySyncEvent(_)}}),Ae(S,"handleBrushChange",function(w){var _=w.startIndex,N=w.endIndex;if(_!==S.state.dataStartIndex||N!==S.state.dataEndIndex){var C=S.state.updateId;S.setState(function(){return Q({dataStartIndex:_,dataEndIndex:N},p({props:S.props,dataStartIndex:_,dataEndIndex:N,updateId:C},S.state))}),S.triggerSyncEvent({dataStartIndex:_,dataEndIndex:N})}}),Ae(S,"handleMouseEnter",function(w){var _=S.getMouseInfo(w);if(_){var N=Q(Q({},_),{},{isTooltipActive:!0});S.setState(N),S.triggerSyncEvent(N);var C=S.props.onMouseEnter;$e(C)&&C(N,w)}}),Ae(S,"triggeredAfterMouseMove",function(w){var _=S.getMouseInfo(w),N=_?Q(Q({},_),{},{isTooltipActive:!0}):{isTooltipActive:!1};S.setState(N),S.triggerSyncEvent(N);var C=S.props.onMouseMove;$e(C)&&C(N,w)}),Ae(S,"handleItemMouseEnter",function(w){S.setState(function(){return{isTooltipActive:!0,activeItem:w,activePayload:w.tooltipPayload,activeCoordinate:w.tooltipPosition||{x:w.cx,y:w.cy}}})}),Ae(S,"handleItemMouseLeave",function(){S.setState(function(){return{isTooltipActive:!1}})}),Ae(S,"handleMouseMove",function(w){w.persist(),S.throttleTriggeredAfterMouseMove(w)}),Ae(S,"handleMouseLeave",function(w){S.throttleTriggeredAfterMouseMove.cancel();var _={isTooltipActive:!1};S.setState(_),S.triggerSyncEvent(_);var N=S.props.onMouseLeave;$e(N)&&N(_,w)}),Ae(S,"handleOuterEvent",function(w){var _=M3(w),N=or(S.props,"".concat(_));if(_&&$e(N)){var C,T;/.*touch.*/i.test(_)?T=S.getMouseInfo(w.changedTouches[0]):T=S.getMouseInfo(w),N((C=T)!==null&&C!==void 0?C:{},w)}}),Ae(S,"handleClick",function(w){var _=S.getMouseInfo(w);if(_){var N=Q(Q({},_),{},{isTooltipActive:!0});S.setState(N),S.triggerSyncEvent(N);var C=S.props.onClick;$e(C)&&C(N,w)}}),Ae(S,"handleMouseDown",function(w){var _=S.props.onMouseDown;if($e(_)){var N=S.getMouseInfo(w);_(N,w)}}),Ae(S,"handleMouseUp",function(w){var _=S.props.onMouseUp;if($e(_)){var N=S.getMouseInfo(w);_(N,w)}}),Ae(S,"handleTouchMove",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&S.throttleTriggeredAfterMouseMove(w.changedTouches[0])}),Ae(S,"handleTouchStart",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&S.handleMouseDown(w.changedTouches[0])}),Ae(S,"handleTouchEnd",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&S.handleMouseUp(w.changedTouches[0])}),Ae(S,"handleDoubleClick",function(w){var _=S.props.onDoubleClick;if($e(_)){var N=S.getMouseInfo(w);_(N,w)}}),Ae(S,"handleContextMenu",function(w){var _=S.props.onContextMenu;if($e(_)){var N=S.getMouseInfo(w);_(N,w)}}),Ae(S,"triggerSyncEvent",function(w){S.props.syncId!==void 0&&Vm.emit(Ym,S.props.syncId,w,S.eventEmitterSymbol)}),Ae(S,"applySyncEvent",function(w){var _=S.props,N=_.layout,C=_.syncMethod,T=S.state.updateId,$=w.dataStartIndex,R=w.dataEndIndex;if(w.dataStartIndex!==void 0||w.dataEndIndex!==void 0)S.setState(Q({dataStartIndex:$,dataEndIndex:R},p({props:S.props,dataStartIndex:$,dataEndIndex:R,updateId:T},S.state)));else if(w.activeTooltipIndex!==void 0){var L=w.chartX,I=w.chartY,z=w.activeTooltipIndex,D=S.state,F=D.offset,O=D.tooltipTicks;if(!F)return;if(typeof C=="function")z=C(O,w);else if(C==="value"){z=-1;for(var P=0;P<O.length;P++)if(O[P].value===w.activeLabel){z=P;break}}var A=Q(Q({},F),{},{x:F.left,y:F.top}),Y=Math.min(L,A.x+A.width),K=Math.min(I,A.y+A.height),M=O[z]&&O[z].value,le=Gv(S.state,S.props.data,z),be=O[z]?{x:N==="horizontal"?O[z].coordinate:Y,y:N==="horizontal"?K:O[z].coordinate}:VP;S.setState(Q(Q({},w),{},{activeLabel:M,activeCoordinate:be,activePayload:le,activeTooltipIndex:z}))}else S.setState(w)}),Ae(S,"renderCursor",function(w){var _,N=S.state,C=N.isTooltipActive,T=N.activeCoordinate,$=N.activePayload,R=N.offset,L=N.activeTooltipIndex,I=N.tooltipAxisBandSize,z=S.getTooltipEventType(),D=(_=w.props.active)!==null&&_!==void 0?_:C,F=S.props.layout,O=w.key||"_recharts-cursor";return W.createElement(Wre,{key:O,activeCoordinate:T,activePayload:$,activeTooltipIndex:L,chartName:n,element:w,isActive:D,layout:F,offset:R,tooltipAxisBandSize:I,tooltipEventType:z})}),Ae(S,"renderPolarAxis",function(w,_,N){var C=or(w,"type.axisType"),T=or(S.state,"".concat(C,"Map")),$=w.type.defaultProps,R=$!==void 0?Q(Q({},$),w.props):w.props,L=T&&T[R["".concat(C,"Id")]];return E.cloneElement(w,Q(Q({},L),{},{className:Ke(C,L.className),key:w.key||"".concat(_,"-").concat(N),ticks:li(L,!0)}))}),Ae(S,"renderPolarGrid",function(w){var _=w.props,N=_.radialLines,C=_.polarAngles,T=_.polarRadius,$=S.state,R=$.radiusAxisMap,L=$.angleAxisMap,I=Ui(R),z=Ui(L),D=z.cx,F=z.cy,O=z.innerRadius,P=z.outerRadius;return E.cloneElement(w,{polarAngles:Array.isArray(C)?C:li(z,!0).map(function(A){return A.coordinate}),polarRadius:Array.isArray(T)?T:li(I,!0).map(function(A){return A.coordinate}),cx:D,cy:F,innerRadius:O,outerRadius:P,key:w.key||"polar-grid",radialLines:N})}),Ae(S,"renderLegend",function(){var w=S.state.formattedGraphicalItems,_=S.props,N=_.children,C=_.width,T=_.height,$=S.props.margin||{},R=C-($.left||0)-($.right||0),L=zO({children:N,formattedGraphicalItems:w,legendWidth:R,legendContent:u});if(!L)return null;var I=L.item,z=VE(L,Hre);return E.cloneElement(I,Q(Q({},z),{},{chartWidth:C,chartHeight:T,margin:$,onBBoxUpdate:S.handleLegendBBoxUpdate}))}),Ae(S,"renderTooltip",function(){var w,_=S.props,N=_.children,C=_.accessibilityLayer,T=Wn(N,hn);if(!T)return null;var $=S.state,R=$.isTooltipActive,L=$.activeCoordinate,I=$.activePayload,z=$.activeLabel,D=$.offset,F=(w=T.props.active)!==null&&w!==void 0?w:R;return E.cloneElement(T,{viewBox:Q(Q({},D),{},{x:D.left,y:D.top}),active:F,label:z,payload:F?I:[],coordinate:L,accessibilityLayer:C})}),Ae(S,"renderBrush",function(w){var _=S.props,N=_.margin,C=_.data,T=S.state,$=T.offset,R=T.dataStartIndex,L=T.dataEndIndex,I=T.updateId;return E.cloneElement(w,{key:w.key||"_recharts-brush",onChange:ld(S.handleBrushChange,w.props.onChange),data:C,x:ue(w.props.x)?w.props.x:$.left,y:ue(w.props.y)?w.props.y:$.top+$.height+$.brushBottom-(N.bottom||0),width:ue(w.props.width)?w.props.width:$.width,startIndex:R,endIndex:L,updateId:"brush-".concat(I)})}),Ae(S,"renderReferenceElement",function(w,_,N){if(!w)return null;var C=S,T=C.clipPathId,$=S.state,R=$.xAxisMap,L=$.yAxisMap,I=$.offset,z=w.type.defaultProps||{},D=w.props,F=D.xAxisId,O=F===void 0?z.xAxisId:F,P=D.yAxisId,A=P===void 0?z.yAxisId:P;return E.cloneElement(w,{key:w.key||"".concat(_,"-").concat(N),xAxis:R[O],yAxis:L[A],viewBox:{x:I.left,y:I.top,width:I.width,height:I.height},clipPathId:T})}),Ae(S,"renderActivePoints",function(w){var _=w.item,N=w.activePoint,C=w.basePoint,T=w.childIndex,$=w.isRange,R=[],L=_.props.key,I=_.item.type.defaultProps!==void 0?Q(Q({},_.item.type.defaultProps),_.item.props):_.item.props,z=I.activeDot,D=I.dataKey,F=Q(Q({index:T,dataKey:D,cx:N.x,cy:N.y,r:4,fill:Jx(_.item),strokeWidth:2,stroke:"#fff",payload:N.payload,value:N.value},qe(z,!1)),yf(z));return R.push(y.renderActiveDot(z,F,"".concat(L,"-activePoint-").concat(T))),C?R.push(y.renderActiveDot(z,Q(Q({},F),{},{cx:C.x,cy:C.y}),"".concat(L,"-basePoint-").concat(T))):$&&R.push(null),R}),Ae(S,"renderGraphicChild",function(w,_,N){var C=S.filterFormatItem(w,_,N);if(!C)return null;var T=S.getTooltipEventType(),$=S.state,R=$.isTooltipActive,L=$.tooltipAxis,I=$.activeTooltipIndex,z=$.activeLabel,D=S.props.children,F=Wn(D,hn),O=C.props,P=O.points,A=O.isRange,Y=O.baseLine,K=C.item.type.defaultProps!==void 0?Q(Q({},C.item.type.defaultProps),C.item.props):C.item.props,M=K.activeDot,le=K.hide,be=K.activeBar,me=K.activeShape,Pe=!!(!le&&R&&F&&(M||be||me)),H={};T!=="axis"&&F&&F.props.trigger==="click"?H={onClick:ld(S.handleItemMouseEnter,w.props.onClick)}:T!=="axis"&&(H={onMouseLeave:ld(S.handleItemMouseLeave,w.props.onMouseLeave),onMouseEnter:ld(S.handleItemMouseEnter,w.props.onMouseEnter)});var X=E.cloneElement(w,Q(Q({},C.props),H));function oe(Ze){return typeof L.dataKey=="function"?L.dataKey(Ze.payload):null}if(Pe)if(I>=0){var ce,Z;if(L.dataKey&&!L.allowDuplicatedCategory){var _e=typeof L.dataKey=="function"?oe:"payload.".concat(L.dataKey.toString());ce=Ey(P,_e,z),Z=A&&Y&&Ey(Y,_e,z)}else ce=P==null?void 0:P[I],Z=A&&Y&&Y[I];if(me||be){var we=w.props.activeIndex!==void 0?w.props.activeIndex:I;return[E.cloneElement(w,Q(Q(Q({},C.props),H),{},{activeIndex:we})),null,null]}if(!Ve(ce))return[X].concat(zo(S.renderActivePoints({item:C,activePoint:ce,basePoint:Z,childIndex:I,isRange:A})))}else{var Ne,ge=(Ne=S.getItemByXY(S.state.activeCoordinate))!==null&&Ne!==void 0?Ne:{graphicalItem:X},Be=ge.graphicalItem,pe=Be.item,Ct=pe===void 0?w:pe,We=Be.childIndex,Oe=Q(Q(Q({},C.props),H),{},{activeIndex:We});return[E.cloneElement(Ct,Oe),null,null]}return A?[X,null,null]:[X,null]}),Ae(S,"renderCustomized",function(w,_,N){return E.cloneElement(w,Q(Q({key:"recharts-customized-".concat(N)},S.props),S.state))}),Ae(S,"renderMap",{CartesianGrid:{handler:hd,once:!0},ReferenceArea:{handler:S.renderReferenceElement},ReferenceLine:{handler:hd},ReferenceDot:{handler:S.renderReferenceElement},XAxis:{handler:hd},YAxis:{handler:hd},Brush:{handler:S.renderBrush,once:!0},Bar:{handler:S.renderGraphicChild},Line:{handler:S.renderGraphicChild},Area:{handler:S.renderGraphicChild},Radar:{handler:S.renderGraphicChild},RadialBar:{handler:S.renderGraphicChild},Scatter:{handler:S.renderGraphicChild},Pie:{handler:S.renderGraphicChild},Funnel:{handler:S.renderGraphicChild},Tooltip:{handler:S.renderCursor,once:!0},PolarGrid:{handler:S.renderPolarGrid,once:!0},PolarAngleAxis:{handler:S.renderPolarAxis},PolarRadiusAxis:{handler:S.renderPolarAxis},Customized:{handler:S.renderCustomized}}),S.clipPathId="".concat((x=b.id)!==null&&x!==void 0?x:sp("recharts"),"-clip"),S.throttleTriggeredAfterMouseMove=FC(S.triggeredAfterMouseMove,(k=b.throttleDelay)!==null&&k!==void 0?k:1e3/60),S.state={},S}return nie(y,v),Qre(y,[{key:"componentDidMount",value:function(){var x,k;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(x=this.props.margin.left)!==null&&x!==void 0?x:0,top:(k=this.props.margin.top)!==null&&k!==void 0?k:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var x=this.props,k=x.children,S=x.data,w=x.height,_=x.layout,N=Wn(k,hn);if(N){var C=N.props.defaultIndex;if(!(typeof C!="number"||C<0||C>this.state.tooltipTicks.length-1)){var T=this.state.tooltipTicks[C]&&this.state.tooltipTicks[C].value,$=Gv(this.state,S,C,T),R=this.state.tooltipTicks[C].coordinate,L=(this.state.offset.top+w)/2,I=_==="horizontal",z=I?{x:R,y:L}:{y:R,x:L},D=this.state.formattedGraphicalItems.find(function(O){var P=O.item;return P.type.name==="Scatter"});D&&(z=Q(Q({},z),D.props.points[C].tooltipPosition),$=D.props.points[C].tooltipPayload);var F={activeTooltipIndex:C,isTooltipActive:!0,activeLabel:T,activePayload:$,activeCoordinate:z};this.setState(F),this.renderCursor(N),this.accessibilityManager.setIndex(C)}}}},{key:"getSnapshotBeforeUpdate",value:function(x,k){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==k.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==x.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==x.margin){var S,w;this.accessibilityManager.setDetails({offset:{left:(S=this.props.margin.left)!==null&&S!==void 0?S:0,top:(w=this.props.margin.top)!==null&&w!==void 0?w:0}})}return null}},{key:"componentDidUpdate",value:function(x){Ny([Wn(x.children,hn)],[Wn(this.props.children,hn)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var x=Wn(this.props.children,hn);if(x&&typeof x.props.shared=="boolean"){var k=x.props.shared?"axis":"item";return l.indexOf(k)>=0?k:a}return a}},{key:"getMouseInfo",value:function(x){if(!this.container)return null;var k=this.container,S=k.getBoundingClientRect(),w=sq(S),_={chartX:Math.round(x.pageX-w.left),chartY:Math.round(x.pageY-w.top)},N=S.width/k.offsetWidth||1,C=this.inRange(_.chartX,_.chartY,N);if(!C)return null;var T=this.state,$=T.xAxisMap,R=T.yAxisMap,L=this.getTooltipEventType(),I=XE(this.state,this.props.data,this.props.layout,C);if(L!=="axis"&&$&&R){var z=Ui($).scale,D=Ui(R).scale,F=z&&z.invert?z.invert(_.chartX):null,O=D&&D.invert?D.invert(_.chartY):null;return Q(Q({},_),{},{xValue:F,yValue:O},I)}return I?Q(Q({},_),I):null}},{key:"inRange",value:function(x,k){var S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,w=this.props.layout,_=x/S,N=k/S;if(w==="horizontal"||w==="vertical"){var C=this.state.offset,T=_>=C.left&&_<=C.left+C.width&&N>=C.top&&N<=C.top+C.height;return T?{x:_,y:N}:null}var $=this.state,R=$.angleAxisMap,L=$.radiusAxisMap;if(R&&L){var I=Ui(R);return $k({x:_,y:N},I)}return null}},{key:"parseEventsOfWrapper",value:function(){var x=this.props.children,k=this.getTooltipEventType(),S=Wn(x,hn),w={};S&&k==="axis"&&(S.props.trigger==="click"?w={onClick:this.handleClick}:w={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var _=yf(this.props,this.handleOuterEvent);return Q(Q({},_),w)}},{key:"addListener",value:function(){Vm.on(Ym,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){Vm.removeListener(Ym,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(x,k,S){for(var w=this.state.formattedGraphicalItems,_=0,N=w.length;_<N;_++){var C=w[_];if(C.item===x||C.props.key===x.key||k===ui(C.item.type)&&S===C.childIndex)return C}return null}},{key:"renderClipPath",value:function(){var x=this.clipPathId,k=this.state.offset,S=k.left,w=k.top,_=k.height,N=k.width;return W.createElement("defs",null,W.createElement("clipPath",{id:x},W.createElement("rect",{x:S,y:w,height:_,width:N})))}},{key:"getXScales",value:function(){var x=this.state.xAxisMap;return x?Object.entries(x).reduce(function(k,S){var w=KE(S,2),_=w[0],N=w[1];return Q(Q({},k),{},Ae({},_,N.scale))},{}):null}},{key:"getYScales",value:function(){var x=this.state.yAxisMap;return x?Object.entries(x).reduce(function(k,S){var w=KE(S,2),_=w[0],N=w[1];return Q(Q({},k),{},Ae({},_,N.scale))},{}):null}},{key:"getXScaleByAxisId",value:function(x){var k;return(k=this.state.xAxisMap)===null||k===void 0||(k=k[x])===null||k===void 0?void 0:k.scale}},{key:"getYScaleByAxisId",value:function(x){var k;return(k=this.state.yAxisMap)===null||k===void 0||(k=k[x])===null||k===void 0?void 0:k.scale}},{key:"getItemByXY",value:function(x){var k=this.state,S=k.formattedGraphicalItems,w=k.activeItem;if(S&&S.length)for(var _=0,N=S.length;_<N;_++){var C=S[_],T=C.props,$=C.item,R=$.type.defaultProps!==void 0?Q(Q({},$.type.defaultProps),$.props):$.props,L=ui($.type);if(L==="Bar"){var I=(T.data||[]).find(function(O){return qQ(x,O)});if(I)return{graphicalItem:C,payload:I}}else if(L==="RadialBar"){var z=(T.data||[]).find(function(O){return $k(x,O)});if(z)return{graphicalItem:C,payload:z}}else if(_p(C,w)||Np(C,w)||nu(C,w)){var D=YJ({graphicalItem:C,activeTooltipItem:w,itemData:R.data}),F=R.activeIndex===void 0?D:R.activeIndex;return{graphicalItem:Q(Q({},C),{},{childIndex:F}),payload:nu(C,w)?R.data[D]:C.props.data[D]}}}return null}},{key:"render",value:function(){var x=this;if(!j1(this))return null;var k=this.props,S=k.children,w=k.className,_=k.width,N=k.height,C=k.style,T=k.compact,$=k.title,R=k.desc,L=VE(k,Gre),I=qe(L,!1);if(T)return W.createElement(PE,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},W.createElement(Ay,Js({},I,{width:_,height:N,title:$,desc:R}),this.renderClipPath(),T1(S,this.renderMap)));if(this.props.accessibilityLayer){var z,D;I.tabIndex=(z=this.props.tabIndex)!==null&&z!==void 0?z:0,I.role=(D=this.props.role)!==null&&D!==void 0?D:"application",I.onKeyDown=function(O){x.accessibilityManager.keyboardEvent(O)},I.onFocus=function(){x.accessibilityManager.focus()}}var F=this.parseEventsOfWrapper();return W.createElement(PE,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},W.createElement("div",Js({className:Ke("recharts-wrapper",w),style:Q({position:"relative",cursor:"default",width:_,height:N},C)},F,{ref:function(P){x.container=P}}),W.createElement(Ay,Js({},I,{width:_,height:N,title:$,desc:R,style:lie}),this.renderClipPath(),T1(S,this.renderMap)),this.renderLegend(),this.renderTooltip()))}}])}(E.Component);Ae(g,"displayName",n),Ae(g,"defaultProps",Q({layout:"horizontal",stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:{top:5,right:5,bottom:5,left:5},reverseStackOrder:!1,syncMethod:"index"},f)),Ae(g,"getDerivedStateFromProps",function(v,y){var b=v.dataKey,x=v.data,k=v.children,S=v.width,w=v.height,_=v.layout,N=v.stackOffset,C=v.margin,T=y.dataStartIndex,$=y.dataEndIndex;if(y.updateId===void 0){var R=ZE(v);return Q(Q(Q({},R),{},{updateId:0},p(Q(Q({props:v},R),{},{updateId:0}),y)),{},{prevDataKey:b,prevData:x,prevWidth:S,prevHeight:w,prevLayout:_,prevStackOffset:N,prevMargin:C,prevChildren:k})}if(b!==y.prevDataKey||x!==y.prevData||S!==y.prevWidth||w!==y.prevHeight||_!==y.prevLayout||N!==y.prevStackOffset||!oo(C,y.prevMargin)){var L=ZE(v),I={chartX:y.chartX,chartY:y.chartY,isTooltipActive:y.isTooltipActive},z=Q(Q({},XE(y,x,_)),{},{updateId:y.updateId+1}),D=Q(Q(Q({},L),I),z);return Q(Q(Q({},D),p(Q({props:v},D),y)),{},{prevDataKey:b,prevData:x,prevWidth:S,prevHeight:w,prevLayout:_,prevStackOffset:N,prevMargin:C,prevChildren:k})}if(!Ny(k,y.prevChildren)){var F,O,P,A,Y=Wn(k,Oo),K=Y&&(F=(O=Y.props)===null||O===void 0?void 0:O.startIndex)!==null&&F!==void 0?F:T,M=Y&&(P=(A=Y.props)===null||A===void 0?void 0:A.endIndex)!==null&&P!==void 0?P:$,le=K!==T||M!==$,be=!Ve(x),me=be&&!le?y.updateId:y.updateId+1;return Q(Q({updateId:me},p(Q(Q({props:v},y),{},{updateId:me,dataStartIndex:K,dataEndIndex:M}),y)),{},{prevChildren:k,dataStartIndex:K,dataEndIndex:M})}return null}),Ae(g,"renderActiveDot",function(v,y,b){var x;return E.isValidElement(v)?x=E.cloneElement(v,y):$e(v)?x=v(y):x=W.createElement(sP,y),W.createElement(Yt,{className:"recharts-active-dot",key:b},x)});var m=E.forwardRef(function(y,b){return W.createElement(g,Js({},y,{ref:b}))});return m.displayName=g.displayName,m},Ma=vie({chartName:"BarChart",GraphicalChild:fn,defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"xAxis",AxisComp:Br},{axisType:"yAxis",AxisComp:zr}],formatAxisMap:xte});function JE(e){return e==null||e<1e-5?"$0.00":e<.01?"$"+e.toFixed(6):"$"+e.toFixed(4)}function Ri(e){return e==null?"0":e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}const bie={local:"#3fb950",groq:"#58a6ff",gemini:"#bc8cff",nim:"#39d2c0",openrouter:"#d29922"};function xie({data:e}){var u,d,f;if(!e)return s.jsxs("div",{className:"loading-state",children:[s.jsx("div",{className:"loading-spinner"}),s.jsx("p",{children:"Connecting to dashboard..."})]});const{cost:t,history:n,benchmarks:r,memory:i,health:a}=e,o=[{icon:"💰",value:JE(t.totalCost),label:"Total Cost"},{icon:"📞",value:Ri(t.totalRequests),label:"API Requests"},{icon:"🧠",value:Ri(i.total),label:"Trajectories"},{icon:"📝",value:Ri(n.total),label:"Chat Sessions"},{icon:"🏆",value:Ri(r.totalRuns),label:"Benchmark Runs"},{icon:"📦",value:Ri(a.vectors),label:"Vector Entries"}],l=Object.entries(t.byProvider||{}).map(([h,p])=>({name:h,value:p})).sort((h,p)=>p.value-h.value),c=Object.entries(i.byFingerprint||{}).map(([h,p])=>({name:h.length>15?h.slice(0,13)+"..":h,value:p})).sort((h,p)=>p.value-h.value).slice(0,8);return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"📊 System Overview"}),s.jsx("div",{className:"stats-grid",children:o.map(h=>s.jsxs("div",{className:"stat-card",children:[s.jsx("div",{className:"stat-icon",children:h.icon}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",children:h.value}),s.jsx("div",{className:"stat-label",children:h.label})]})]},h.label))}),s.jsxs("div",{className:"memory-health-card",children:[s.jsx("h3",{className:"section-subtitle",children:"🧠 Memory Health"}),s.jsxs("div",{className:"memory-health-stats",children:[s.jsxs("div",{className:"memory-health-stat",children:[s.jsx("span",{className:"memory-health-value",children:Ri(i.total)}),s.jsx("span",{className:"memory-health-label",children:"Trajectories"})]}),s.jsxs("div",{className:"memory-health-stat",children:[s.jsx("span",{className:"memory-health-value",children:Ri(((u=i.facts)==null?void 0:u.total)||0)}),s.jsx("span",{className:"memory-health-label",children:"Facts Learned"})]}),s.jsxs("div",{className:"memory-health-stat",children:[s.jsx("span",{className:"memory-health-value",children:Ri(((d=i.recall)==null?void 0:d.last7d)||0)}),s.jsx("span",{className:"memory-health-label",children:"Recalls This Week"})]}),s.jsxs("div",{className:"memory-health-stat",children:[s.jsx("span",{className:"memory-health-value",children:a.patterns||0}),s.jsx("span",{className:"memory-health-label",children:"Coding Patterns"})]})]}),s.jsxs("p",{className:"memory-health-status",children:["Backend: ",s.jsx("code",{children:i.backend||"local"}),(f=i.recall)!=null&&f.last7d?` · ${i.recall.last7d} recall(s) this week`:" · no recalls yet"]})]}),s.jsx("h3",{className:"section-subtitle",children:"💰 Cost by Provider"}),s.jsx("div",{className:"chart-container",children:l.length>0?s.jsx(Pa,{width:"100%",height:260,children:s.jsxs(Ma,{data:l,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(Wi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Br,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(zr,{tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"},tickFormatter:h=>"$"+h.toFixed(4)}),s.jsx(hn,{contentStyle:{background:"#161b22",border:"1px solid #30363d",borderRadius:8},labelStyle:{color:"#e6edf3"},formatter:h=>[JE(h),"Cost"]}),s.jsx(fn,{dataKey:"value",radius:[4,4,0,0],children:l.map(h=>s.jsx(Pc,{fill:bie[h.name]||"#58a6ff",fillOpacity:.8},h.name))})]})}):s.jsx("div",{className:"empty-state",children:"No cost data yet."})}),s.jsx("h3",{className:"section-subtitle",children:"📊 Trajectories by Project Type"}),s.jsx("div",{className:"chart-container",children:c.length>0?s.jsx(Pa,{width:"100%",height:260,children:s.jsxs(Ma,{data:c,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(Wi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Br,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(zr,{tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(hn,{contentStyle:{background:"#161b22",border:"1px solid #30363d",borderRadius:8},labelStyle:{color:"#e6edf3"}}),s.jsx(fn,{dataKey:"value",fill:"#bc8cff",radius:[4,4,0,0],fillOpacity:.8})]})}):s.jsx("div",{className:"empty-state",children:"No trajectory data yet."})})]})}const e_={planner:"📋","context-gatherer":"📂",writer:"✏️",reviewer:"👁️",tester:"🧪",debugger:"🐛",runner:"▶️",git:"🔀",package:"📦","github-release":"🏷️",security:"🔒",orchestrator:"🎯"},t_={planner:"#58a6ff","context-gatherer":"#39d2c0",writer:"#d29922",reviewer:"#bc8cff",tester:"#3fb950",debugger:"#f85149",runner:"#58a6ff",git:"#f0883e",package:"#db6d28","github-release":"#3fb950",security:"#f85149",orchestrator:"#f0883e"},Zm={planner:"Planner","context-gatherer":"Context",writer:"Writer",reviewer:"Reviewer",tester:"Tester",debugger:"Debugger",runner:"Runner",git:"Git",package:"Package","github-release":"Release",security:"Security",orchestrator:"Orchestrator"},n_={pending:{icon:"⏳",label:"Pending"},running:{icon:"▶️",label:"Running"},completed:{icon:"✅",label:"Done"},failed:{icon:"❌",label:"Failed"}},wie={pending:"#6e7681",running:"#58a6ff",completed:"#3fb950",failed:"#f85149"};function Sie(e){if(!e||e.nodes.length===0)return null;const t=e.nodes.map(a=>a.startedAt||0).filter(Boolean),n=e.nodes.map(a=>a.completedAt||0).filter(Boolean),r=t.length>0?Math.min(...t):Date.now(),i=n.length>0?Math.max(...n):Date.now();return{id:`live-${r}`,goal:e.pipeline||"Active execution",startedAt:r,endedAt:n.length>0?i:void 0,success:e.nodes.length>0&&e.nodes.every(a=>a.status==="completed"),totalDurationMs:Math.max(0,i-r),phases:e.nodes.map(a=>({id:a.id,agentType:a.agentType,status:a.status,description:a.description,complexity:a.complexity,summary:a.summary,startedAt:a.startedAt,completedAt:a.completedAt,durationMs:a.startedAt&&a.completedAt?a.completedAt-a.startedAt:void 0}))}}function kie(e,t){const n=[],r=new Set,i=Sie(e);i&&(n.push(i),r.add(i.id));for(const a of(t==null?void 0:t.runs)||[])r.has(a.id)||(n.push(a),r.add(a.id));return n}function Ii(e){return e<1e3?`${Math.round(e)}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}function r_(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit"}):""}function Eie(e,t){if(e.length===0)return{laid:[],total:0};const n=e.length,r=e.map(d=>d.durationMs&&d.durationMs>0?d.durationMs:0),i=r.reduce((d,f)=>d+f,0),a=i>0?e.map((d,f)=>r[f]>0?r[f]:i/n):e.map(()=>1),o=a.reduce((d,f)=>d+f,0)||1;let l=0;const c=e.map((d,f)=>{const h=a[f]/o,p=l;return l+=h,{...d,start:p,width:h,dur:a[f]}}),u=t>0?t:o;return{laid:c,total:u}}function _ie({runs:e,selectedRunId:t,onSelectRun:n,onScrub:r}){const[i,a]=E.useState(null),o=e.find(_=>_.id===(t??i))??e[0]??null,[l,c]=E.useState(0),[u,d]=E.useState(!1),f=E.useRef(null),h=E.useRef(!1),p=E.useRef(r);E.useEffect(()=>{p.current=r},[r]),E.useEffect(()=>{var _;!o&&e.length>0?a(e[0].id):o&&!e.some(N=>N.id===o.id)&&a(((_=e[0])==null?void 0:_.id)??null)},[e,o]);const{laid:g,total:m}=E.useMemo(()=>Eie((o==null?void 0:o.phases)||[],(o==null?void 0:o.totalDurationMs)||0),[o]),v=m>0?Math.min(1,Math.max(0,l/m)):0,y=E.useMemo(()=>{if(m<=0)return null;const _=v*m;return g.find(N=>_>=N.start*m&&_<(N.start+N.width)*m)||null},[g,v,m]);E.useEffect(()=>{var _;(_=p.current)==null||_.call(p,(y==null?void 0:y.id)??null)},[y==null?void 0:y.id]),E.useEffect(()=>{if(!u)return;const _=setInterval(()=>{c(N=>N+m/2e3*50)},50);return()=>clearInterval(_)},[u,m]),E.useEffect(()=>{u&&m>0&&l>=m&&(d(!1),c(0))},[u,m,l]);const b=E.useCallback(_=>{const N=f.current;if(!N||m<=0)return;const C=N.getBoundingClientRect(),T=C.width||1,$=Math.min(1,Math.max(0,(_-C.left)/T));c($*m)},[m]),x=_=>{h.current=!0,d(!1),b(_.clientX)};if(E.useEffect(()=>{const _=C=>{h.current&&b(C.clientX)},N=()=>{h.current=!1};return window.addEventListener("pointermove",_),window.addEventListener("pointerup",N),()=>{window.removeEventListener("pointermove",_),window.removeEventListener("pointerup",N)}},[b]),!o)return s.jsx("div",{className:"phase-timeline phase-timeline-empty",children:s.jsx("p",{children:"No pipeline runs yet. Run an agent task to see its phase timeline here."})});const k=o.id.startsWith("live-"),S=o.phases.filter(_=>_.status==="completed").length,w=o.phases.filter(_=>_.status==="failed").length;return s.jsxs("div",{className:"phase-timeline",children:[s.jsxs("div",{className:"phase-timeline-header",children:[s.jsx("div",{className:"phase-timeline-runs",children:e.map(_=>s.jsxs("button",{className:`phase-run-chip ${_.id===o.id?"active":""} ${_.id.startsWith("live-")?"live":""}`,onClick:()=>{a(_.id),c(0),d(!1),n==null||n(_.id)},title:_.goal,children:[_.id.startsWith("live-")&&s.jsx("span",{className:"dag-live-dot"}),_.engine&&s.jsx("span",{className:`phase-run-chip-engine phase-run-chip-engine-${_.engine}`,children:_.engine==="loop"?"🔁":"⬡"}),_.goal.length>32?_.goal.slice(0,30)+"…":_.goal,s.jsx("span",{className:"phase-run-chip-time",children:r_(_.startedAt)})]},_.id))}),s.jsxs("div",{className:"phase-timeline-meta",children:[k&&s.jsx("span",{className:"dag-live-badge",children:"LIVE"}),o.engine&&s.jsx("span",{className:`dag-engine-badge dag-engine-${o.engine}`,title:o.engine==="loop"?"Loop turn (per-tool telemetry below)":"Orchestrator pipeline",children:o.engine==="loop"?"🔁 loop":"⬡ pipeline"}),s.jsxs("span",{className:"phase-meta-item",children:[o.phases.length," steps"]}),s.jsxs("span",{className:"phase-meta-item phase-meta-ok",children:["✅ ",S]}),w>0&&s.jsxs("span",{className:"phase-meta-item phase-meta-bad",children:["❌ ",w]}),o.turnTelemetry&&s.jsxs("span",{className:"phase-meta-item",title:`tool calls: ${o.turnTelemetry.toolCallCount}, errored: ${o.turnTelemetry.erroredToolCount}${o.turnTelemetry.bounded?", bounded":""}${o.turnTelemetry.provider?`, ${o.turnTelemetry.provider}${o.turnTelemetry.model?`/${o.turnTelemetry.model}`:""}`:""}`,children:["🔧 ",o.turnTelemetry.toolCallCount,o.turnTelemetry.erroredToolCount>0&&s.jsxs("span",{className:"phase-meta-bad",children:[" (",o.turnTelemetry.erroredToolCount," err)"]})]}),s.jsxs("span",{className:"phase-meta-item",children:["⏱ ",Ii(m)]})]})]}),s.jsxs("div",{className:"phase-timeline-controls",children:[s.jsx("button",{className:`phase-play-btn ${u?"paused":""}`,onClick:()=>{u?d(!1):(l>=m&&c(0),d(!0))},"aria-label":u?"Pause scrub":"Play scrub",children:u?"⏸ Pause":"▶ Play"}),s.jsxs("span",{className:"phase-time-label",children:[Ii(l)," / ",Ii(m)]}),s.jsx("input",{className:"phase-range",type:"range",min:0,max:m||1,step:1,value:Math.min(l,m||1),onChange:_=>{d(!1),c(Number(_.target.value))},"aria-label":"Scrub pipeline timeline"})]}),s.jsxs("div",{className:"phase-track-wrap",children:[s.jsxs("div",{ref:f,className:"phase-track",onPointerDown:x,style:{cursor:"grab"},children:[g.map(_=>{const N=t_[_.agentType]||"#58a6ff",C=wie[_.status],T=(y==null?void 0:y.id)===_.id;return s.jsxs("button",{className:`phase-block phase-block-${_.status} ${T?"active":""}`,style:{left:`${_.start*100}%`,width:`${Math.max(_.width*100,2)}%`,background:`linear-gradient(180deg, ${N}cc, ${N}66)`,boxShadow:T?`0 0 0 2px ${C}`:void 0},onClick:$=>{$.stopPropagation(),d(!1),c((_.start+_.width/2)*m)},title:`${Zm[_.agentType]||_.agentType}: ${_.description}`,children:[s.jsx("span",{className:"phase-block-icon",children:e_[_.agentType]||"⚙️"}),s.jsx("span",{className:"phase-block-label",children:Zm[_.agentType]||_.agentType})]},_.id)}),s.jsx("div",{className:"phase-caret",style:{left:`${v*100}%`},onPointerDown:_=>{_.stopPropagation(),x(_)},title:`${Ii(l)} elapsed`})]}),s.jsxs("div",{className:"phase-ticks",children:[s.jsx("span",{children:"0"}),s.jsx("span",{children:Ii(Math.round(m/2))}),s.jsx("span",{children:Ii(m)})]})]}),s.jsx("div",{className:"phase-detail",children:y?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"phase-detail-title",children:[s.jsx("span",{className:"phase-detail-icon",children:e_[y.agentType]||"⚙️"}),s.jsx("span",{className:"phase-detail-agent",style:{color:t_[y.agentType]||"#58a6ff"},children:Zm[y.agentType]||y.agentType}),s.jsxs("span",{className:`phase-status-badge phase-status-${y.status}`,children:[n_[y.status].icon," ",n_[y.status].label]})]}),s.jsx("p",{className:"phase-detail-desc",children:y.description}),s.jsxs("div",{className:"phase-detail-meta",children:[s.jsxs("span",{children:["⏱ ",y.durationMs?Ii(y.dur):`~${Ii(y.dur)}`]}),y.startedAt?s.jsxs("span",{children:["🕐 ",r_(y.startedAt)]}):null,y.complexity?s.jsxs("span",{children:["🎯 ",y.complexity]}):null]}),y.summary&&s.jsx("p",{className:"phase-detail-summary",children:y.summary})]}):s.jsxs("div",{className:"phase-detail-gap",children:[s.jsx("span",{className:"phase-detail-icon",children:"⏳"}),s.jsx("span",{children:"Between steps — waiting for the next agent."})]})})]})}const i_={planner:"📋","context-gatherer":"📂",writer:"✏️",reviewer:"👁️",tester:"🧪",debugger:"🐛",runner:"▶️",git:"🔀",package:"📦","github-release":"🏷️",security:"🔒",orchestrator:"🎯"},Qm={planner:"#58a6ff","context-gatherer":"#39d2c0",writer:"#d29922",reviewer:"#bc8cff",tester:"#3fb950",debugger:"#f85149",runner:"#58a6ff",git:"#f0883e",package:"#db6d28","github-release":"#3fb950",security:"#f85149",orchestrator:"#f0883e"},Nie={pending:{bg:"#1a1f2e",stroke:"#30363d",text:"#6e7681"},running:{bg:"rgba(88, 166, 255, 0.12)",stroke:"#58a6ff",text:"#58a6ff"},completed:{bg:"rgba(63, 185, 80, 0.12)",stroke:"#3fb950",text:"#3fb950"},failed:{bg:"rgba(248, 81, 73, 0.12)",stroke:"#f85149",text:"#f85149"}},a_={pending:"⏳ Pending",running:"▶️ Running",completed:"✅ Done",failed:"❌ Failed"},Ps={trivial:{icon:"🟢",color:"#3fb950"},simple:{icon:"🔵",color:"#58a6ff"},moderate:{icon:"🟡",color:"#d29922"},complex:{icon:"🟠",color:"#f0883e"},critical:{icon:"🔴",color:"#f85149"}},Jm={planner:"Planner","context-gatherer":"Context",writer:"Writer",reviewer:"Reviewer",tester:"Tester",debugger:"Debugger",runner:"Runner",git:"Git",package:"Package","github-release":"Release",security:"Security",orchestrator:"Orchestrator"};function jie(e,t,n=160,r=68,i=40,a=24,o=40){if(e.length===0)return{layoutNodes:[],svgW:400,svgH:200};const l=new Map,c=new Set;function u(v){if(l.has(v))return l.get(v);if(c.has(v))return 0;c.add(v);const y=t.filter(k=>k.to===v);if(y.length===0)return l.set(v,0),0;const x=Math.max(...y.map(k=>u(k.from)))+1;return l.set(v,x),x}for(const v of e)u(v.id);const d=new Map;for(const v of e){const y=l.get(v.id)??0;d.has(y)||d.set(y,[]),d.get(y).push(v)}const f=Math.max(...d.keys()),h=Math.max(...Array.from(d.values()).map(v=>v.length)),p=(f+1)*(n+i)+o*2-i,g=Math.max(h,1)*(r+a)+o*2-a,m=[];for(const v of e){const y=l.get(v.id)??0,b=d.get(y),x=b.indexOf(v),k=b.length,S=k*(r+a)-a,w=g/2-S/2;m.push({...v,x:o+y*(n+i),y:w+x*(r+a),w:n,h:r,step:y,totalInStep:k,indexInStep:x})}return{layoutNodes:m,svgW:p,svgH:g}}function eg(e,t){if(!e)return"--";const n=(t||Date.now())-e;return n<1e3?`${n}ms`:n<6e4?`${(n/1e3).toFixed(1)}s`:`${Math.floor(n/6e4)}m ${Math.floor(n%6e4/1e3)}s`}function s_(e){return e?new Date(e).toLocaleTimeString("en-US",{minute:"2-digit",second:"2-digit"}):""}function Aie({memoryTotal:e}){return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"🔀 Agent Execution DAG"}),s.jsx("p",{className:"section-description",children:"Live visualization of the agent execution pipeline. When an agent task runs, you'll see each step appear here in real time as it moves through planning → context gathering → writing → review → testing."}),s.jsxs("div",{className:"dag-empty",children:[s.jsx("div",{className:"dag-empty-icon",children:"🔀"}),s.jsx("h3",{children:"No Active Pipeline"}),s.jsx("p",{children:"Run an agent task to see the execution pipeline appear here in real time."}),e!==void 0&&e>0&&s.jsxs("p",{className:"dag-empty-hint",children:[s.jsx("code",{children:e})," past executions are stored in memory."]})]})]})}function Tie({data:e}){var O;const t=e==null?void 0:e.dag,n=(O=e==null?void 0:e.memory)==null?void 0:O.total,[r,i]=E.useState(null),[a,o]=E.useState(null),[l,c]=E.useState(void 0),[u,d]=E.useState(void 0),[f,h]=E.useState(void 0);E.useEffect(()=>ee.onDAGEvent(A=>{i(A),c(A.engine),d(A.engineExplanation),h(A.loopTurn)}),[]);const p=t||r,g=r?l:(t==null?void 0:t.engine)??l,m=r?u:(t==null?void 0:t.engineExplanation)??u,v=r?f:(t==null?void 0:t.loopTurn)??f,y=E.useMemo(()=>kie(p,e==null?void 0:e.pipelineRuns),[p,e==null?void 0:e.pipelineRuns]),b=P=>{o(P)},x=!!(p&&(p.nodes.length>0||p.active)),k=y.length>0;if(!x&&!k&&!!!v)return s.jsx(Aie,{memoryTotal:n});const{nodes:w,edges:_,pipeline:N,active:C}=p??{nodes:[],edges:[],pipeline:null,active:!1},{layoutNodes:T,svgW:$,svgH:R}=jie(w,_),L=w.filter(P=>P.status==="running").length,I=w.filter(P=>P.status==="completed").length,z=w.filter(P=>P.status==="failed").length,D=w.filter(P=>P.status==="pending").length,F=w.length;return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"🔀 Agent Execution DAG"}),k&&s.jsxs("div",{className:"dag-timeline-section",children:[s.jsxs("h3",{className:"section-subtitle",children:["⏱ Run Timeline ",s.jsx("span",{className:"timeline-subtitle",children:"— scrub to replay · click a run to switch"})]}),s.jsx(_ie,{runs:y,onScrub:b})]}),v&&s.jsxs("div",{className:"dag-loop-turn-card","data-testid":"dag-loop-turn-card",children:[s.jsxs("div",{className:"dag-loop-turn-header",children:[s.jsx("span",{className:"dag-loop-turn-icon",children:"🔁"}),s.jsxs("span",{className:"dag-loop-turn-title",children:["Loop turn — ",v.title||"chat turn"]}),v.active&&s.jsx("span",{className:"dag-loop-turn-live",children:"● recording"})]}),s.jsxs("div",{className:"dag-loop-turn-meta",children:[s.jsxs("span",{className:"dag-loop-turn-chip",children:["🔧 ",v.toolCallCount," tool call",v.toolCallCount===1?"":"s"]}),v.erroredToolCount>0&&s.jsxs("span",{className:"dag-loop-turn-chip dag-loop-turn-chip-error",children:["❌ ",v.erroredToolCount," errored"]}),v.provider&&s.jsxs("span",{className:"dag-loop-turn-chip dag-loop-turn-chip-dim",children:[v.provider,v.model?` · ${v.model}`:""]}),typeof v.startedAt=="number"&&s.jsxs("span",{className:"dag-loop-turn-chip dag-loop-turn-chip-dim",children:["⏱ ",eg(v.startedAt,v.endedAt)]}),v.bounded&&s.jsx("span",{className:"dag-loop-turn-chip dag-loop-turn-chip-error",children:"⛔ bounded"}),v.generationFailed&&s.jsx("span",{className:"dag-loop-turn-chip dag-loop-turn-chip-error",children:"💀 generation failed"}),v.cancelled&&s.jsx("span",{className:"dag-loop-turn-chip dag-loop-turn-chip-dim",children:"✖ cancelled"})]}),v.toolCalls.length>0&&s.jsx("div",{className:"dag-loop-turn-tools",children:v.toolCalls.slice(-12).map((P,A)=>s.jsxs("span",{className:`dag-loop-tool ${P.ok===!1?"dag-loop-tool-error":""}`,title:P.error||`${P.tool}${P.durationMs!==void 0?` · ${P.durationMs}ms`:""}`,children:[P.ok===!1?"❌":"✓"," ",P.tool]},`${P.tool}-${A}`))})]}),x&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`dag-status-bar ${C?"active":""}`,children:[s.jsxs("div",{className:"dag-pipeline-name",children:[C&&s.jsx("span",{className:"dag-live-dot"}),N||"Execution Pipeline"]}),s.jsxs("div",{className:"dag-pipeline-meta",children:[C&&s.jsx("span",{className:"dag-live-badge",children:"LIVE"}),g&&s.jsx("span",{className:`dag-engine-badge dag-engine-${g}`,title:m||(g==="loop"?"Single agentic loop":"Orchestrator pipeline"),"data-testid":"dag-engine-badge",children:g==="loop"?"🔁 loop engine":"⬡ pipeline engine"}),s.jsxs("span",{className:"dag-step-count",children:[F," steps"]}),L>0&&s.jsxs("span",{className:"dag-running-badge",children:["▶ ",L," running"]}),D>0&&s.jsxs("span",{className:"dag-pending-badge",children:["⏳ ",D," pending"]}),s.jsxs("span",{className:"dag-completed-badge",children:["✅ ",I," done"]}),z>0&&s.jsxs("span",{className:"dag-failed-badge",children:["❌ ",z," failed"]})]})]}),s.jsx("div",{className:"dag-container",children:s.jsxs("svg",{width:$,height:R,viewBox:`0 0 ${$} ${R}`,children:[s.jsxs("defs",{children:[_.map(P=>s.jsx("marker",{id:`arrow-${P.from}-${P.to}`,markerWidth:"8",markerHeight:"6",refX:"8",refY:"3",orient:"auto",children:s.jsx("polygon",{points:"0 0, 8 3, 0 6",fill:"#58a6ff"})},`arrow-${P.from}-${P.to}`)),s.jsxs("filter",{id:"glow",children:[s.jsx("feGaussianBlur",{stdDeviation:"3",result:"coloredBlur"}),s.jsxs("feMerge",{children:[s.jsx("feMergeNode",{in:"coloredBlur"}),s.jsx("feMergeNode",{in:"SourceGraphic"})]})]})]}),_.map(P=>{const A=T.find(X=>X.id===P.from),Y=T.find(X=>X.id===P.to);if(!A||!Y)return null;const K=A.x+A.w,M=A.y+A.h/2,le=Y.x,be=Y.y+Y.h/2,me=(K+le)/2,Pe=Y.status,H=Pe==="failed"?"#f85149":Pe==="running"?"#58a6ff":Pe==="completed"?"#3fb950":"#30363d";return s.jsx("g",{children:s.jsx("path",{d:`M ${K} ${M} C ${me} ${M}, ${me} ${be}, ${le} ${be}`,fill:"none",stroke:H,strokeWidth:Pe==="pending"?1.5:2.5,strokeOpacity:Pe==="pending"?.3:.8,markerEnd:`url(#arrow-${P.from}-${P.to})`,className:"dag-edge"})},`edge-${P.from}-${P.to}`)}),T.map(P=>{const A=Nie[P.status];Qm[P.agentType];const Y=i_[P.agentType]||"⚙️",K=Jm[P.agentType]||P.agentType,M=a===P.id,le=P.status==="running";return s.jsxs("g",{onClick:()=>o(M?null:P.id),style:{cursor:"pointer"},className:"dag-node-group",children:[M&&s.jsx("rect",{x:P.x-4,y:P.y-4,width:P.w+8,height:P.h+8,rx:10,ry:10,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.5}),s.jsx("rect",{x:P.x,y:P.y,width:P.w,height:P.h,rx:8,ry:8,fill:A.bg,stroke:A.stroke,strokeWidth:le?2.5:1.5,strokeOpacity:.9,className:le?"dag-node-running":"",filter:le?"url(#glow)":void 0}),s.jsxs("text",{x:P.x+10,y:P.y+22,fill:"#e6edf3",fontSize:10,fontWeight:600,children:[Y," ",K]}),s.jsx("text",{x:P.x+P.w-10,y:P.y+22,textAnchor:"end",fill:A.text,fontSize:9,fontWeight:500,children:a_[P.status]}),s.jsx("text",{x:P.x+10,y:P.y+40,fill:"#8b949e",fontSize:9,children:P.description.length>28?P.description.slice(0,26)+"..":P.description}),P.complexity&&Ps[P.complexity]&&s.jsxs("text",{x:P.x+10,y:P.y+54,fill:Ps[P.complexity].color,fontSize:8,fontWeight:600,children:[Ps[P.complexity].icon," ",P.complexity]}),s.jsx("text",{x:P.x+10,y:P.y+56,fill:"#6e7681",fontSize:8,children:eg(P.startedAt,P.completedAt)}),s.jsx("text",{x:P.x+P.w-10,y:P.y+56,textAnchor:"end",fill:"#6e7681",fontSize:8,children:s_(P.startedAt||P.completedAt)}),(P.status==="failed"||M)&&P.summary&&s.jsx("foreignObject",{x:Math.max(10,P.x-80),y:P.y+P.h+6,width:P.w+160,height:36,children:s.jsx("div",{className:"dag-node-summary",style:{color:P.status==="failed"?"#f85149":"#8b949e",fontSize:"10px",lineHeight:1.4,background:"rgba(13,17,23,0.9)",padding:"4px 8px",borderRadius:"4px",border:`1px solid ${P.status==="failed"?"rgba(248,81,73,0.3)":"rgba(48,54,61,0.5)"}`,maxHeight:"32px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:P.summary})})]},`node-${P.id}`)})]})}),s.jsx("h3",{className:"section-subtitle",children:"Step Details"}),s.jsx("div",{className:"dag-table-wrapper",children:s.jsxs("table",{className:"dag-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Step"}),s.jsx("th",{children:"Agent"}),s.jsx("th",{children:"Complexity"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Duration"}),s.jsx("th",{children:"Time"}),s.jsx("th",{children:"Summary"})]})}),s.jsx("tbody",{children:T.map(P=>s.jsxs("tr",{className:`dag-row dag-row-${P.status}`,children:[s.jsx("td",{className:"dag-cell-step",children:P.step}),s.jsxs("td",{className:"dag-cell-agent",children:[s.jsx("span",{className:"dag-agent-dot",style:{background:Qm[P.agentType]||"#58a6ff"}}),Jm[P.agentType]||P.agentType]}),s.jsx("td",{className:"dag-cell-complexity",children:P.complexity&&Ps[P.complexity]?s.jsxs("span",{style:{color:Ps[P.complexity].color,fontSize:12},children:[Ps[P.complexity].icon," ",P.complexity]}):s.jsx("span",{style:{color:"#6e7681",fontSize:12},children:"—"})}),s.jsx("td",{className:`dag-cell-status dag-status-${P.status}`,children:a_[P.status]}),s.jsx("td",{className:"dag-cell-duration",children:eg(P.startedAt,P.completedAt)}),s.jsx("td",{className:"dag-cell-time",children:s_(P.startedAt||P.completedAt)}),s.jsx("td",{className:"dag-cell-summary",children:P.summary||P.description||"--"})]},P.id))})]})}),s.jsx("h3",{className:"section-subtitle",children:"Agent Types"}),s.jsxs("div",{className:"dag-legend",children:[Object.entries(i_).map(([P,A])=>s.jsxs("div",{className:"legend-item",children:[s.jsx("span",{className:"legend-dot",style:{background:Qm[P]||"#58a6ff"}}),s.jsx("span",{className:"legend-icon",children:A}),s.jsx("span",{className:"legend-label",children:Jm[P]||P})]},P)),s.jsxs("div",{className:"legend-item",children:[s.jsx("span",{className:"legend-dot",style:{background:"transparent",border:"2px dashed #58a6ff"}}),s.jsx("span",{className:"legend-icon",children:"⚡"}),s.jsx("span",{className:"legend-label",children:"Live node"})]})]})]})]})}function Ms(e){return e==null||e<1e-5?"$0.00":e<.01?"$"+e.toFixed(6):"$"+e.toFixed(4)}function $l(e){return e==null?"0":e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}function Cie(e){return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Oie({data:e}){if(!e)return s.jsx("div",{className:"loading-state",children:s.jsx("p",{children:"Loading cost data..."})});const{cost:t}=e,n=Object.entries(t.byProvider||{}).sort(([,a],[,o])=>o-a),r=Object.entries(t.byModel||{}).sort(([,a],[,o])=>o-a).slice(0,10),i=n.reduce((a,[,o])=>a+o,0);return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"💰 Cost Tracking"}),s.jsxs("div",{className:"cost-summary",children:[s.jsxs("div",{className:"cost-total",children:[s.jsx("span",{className:"cost-label",children:"Total Spent"}),s.jsx("span",{className:"cost-amount",children:Ms(t.totalCost)})]}),s.jsxs("div",{className:"cost-total",children:[s.jsx("span",{className:"cost-label",children:"Total Tokens"}),s.jsx("span",{className:"cost-amount",children:$l(t.totalTokens)})]}),s.jsxs("div",{className:"cost-total",children:[s.jsx("span",{className:"cost-label",children:"Total Requests"}),s.jsx("span",{className:"cost-amount",children:$l(t.totalRequests)})]})]}),s.jsxs("div",{className:"cost-summary cost-summary-sub",children:[s.jsxs("div",{className:"cost-total",children:[s.jsx("span",{className:"cost-label",children:"📏 Measured (exact wire tokens)"}),s.jsx("span",{className:"cost-amount",children:Ms(t.measuredCost)}),s.jsxs("span",{className:"cost-label",children:[$l(t.measuredCalls)," calls"]})]}),s.jsxs("div",{className:"cost-total",children:[s.jsx("span",{className:"cost-label",children:"📐 Estimated (length-based)"}),s.jsx("span",{className:"cost-amount",children:Ms(t.estimatedCost)}),s.jsxs("span",{className:"cost-label",children:[$l(t.estimatedCalls)," calls"]})]})]}),s.jsx("h3",{className:"section-subtitle",children:"By Provider"}),s.jsx("div",{className:"cost-list",children:n.length===0?s.jsx("div",{className:"empty-state",children:"No costs recorded yet."}):n.map(([a,o])=>{const l=i>0?(o/i*100).toFixed(1):"0";return s.jsxs("div",{className:"cost-row",children:[s.jsx("span",{className:"cost-row-name",children:a}),s.jsx("div",{className:"cost-row-bar",children:s.jsx("div",{className:"cost-row-fill",style:{width:`${l}%`}})}),s.jsx("span",{className:"cost-row-value",children:Ms(o)})]},a)})}),s.jsx("h3",{className:"section-subtitle",children:"By Model"}),s.jsx("div",{className:"cost-list",children:r.length===0?s.jsx("div",{className:"empty-state",children:"No model costs recorded yet."}):r.map(([a,o])=>{const l=i>0?(o/i*100).toFixed(1):"0",c=a.length>30?a.slice(0,28)+"..":a;return s.jsxs("div",{className:"cost-row",children:[s.jsx("span",{className:"cost-row-name",children:c}),s.jsx("div",{className:"cost-row-bar",children:s.jsx("div",{className:"cost-row-fill",style:{width:`${l}%`}})}),s.jsx("span",{className:"cost-row-value",children:Ms(o)})]},a)})}),s.jsx("h3",{className:"section-subtitle",children:"Recent Requests"}),s.jsx("div",{className:"request-list",children:!t.recent||t.recent.length===0?s.jsx("div",{className:"empty-state",children:"No requests recorded yet."}):t.recent.slice(0,30).map((a,o)=>s.jsxs("div",{className:"request-row",children:[s.jsx("span",{className:"request-time",children:Cie(a.timestamp)}),s.jsx("span",{className:"request-provider",children:a.provider||"--"}),s.jsx("span",{className:"request-model",children:a.model||"--"}),s.jsx("span",{className:"request-cost",children:Ms(a.costUsd)}),s.jsxs("span",{className:"request-tokens",children:[$l(a.totalTokens)," tok"]})]},o))})]})}function Pie(e){return e==null?"$0.00":"$"+e.toFixed(6)}function pd(e){return e==null?"0%":(e*100).toFixed(1)+"%"}function Mie({data:e}){if(!e)return s.jsx("div",{className:"loading-state",children:s.jsx("p",{children:"Loading benchmark data..."})});const{benchmarks:t,evals:n}=e,r=t.latest,i=t.runs||[],a=(n==null?void 0:n.runs)||[],o=(n==null?void 0:n.latest)||null,l=a.map(u=>({name:u.model.length>12?u.model.slice(0,10)+"..":u.model,score:Math.round(u.summary.avgCompositeScore*100),completion:Math.round(u.summary.completionRate*100),tests:Math.round(u.summary.testPassRate*100),recovery:Math.round(u.summary.recoveryRate*100),efficiency:Math.round(u.summary.avgTokenEfficiency*100),fullModel:u.model,provider:u.provider})).reverse(),c=i.map(u=>({name:u.model.length>12?u.model.slice(0,10)+"..":u.model,passRate:u.summary.totalTasks>0?Math.round(u.summary.tasksPassed/u.summary.totalTasks*100):0,quality:Math.round(u.summary.avgQualityScore*100),latency:u.summary.medianLatencyMs,cost:u.summary.totalCostUsd,fullModel:u.model,provider:u.provider})).reverse();return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"📈 Benchmark Results"}),s.jsx("div",{className:"benchmark-latest",children:r?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"benchmark-header",children:[s.jsx("strong",{children:"Latest Run:"})," ",r.provider,"/",r.model]}),s.jsxs("div",{className:"benchmark-stats",children:[s.jsxs("div",{className:"benchmark-stat pass",children:[s.jsxs("div",{className:"benchmark-stat-value",children:[r.summary.tasksPassed,"/",r.summary.totalTasks]}),s.jsx("div",{className:"benchmark-stat-label",children:"Passed"})]}),s.jsxs("div",{className:"benchmark-stat quality",children:[s.jsx("div",{className:"benchmark-stat-value",children:pd(r.summary.avgQualityScore)}),s.jsx("div",{className:"benchmark-stat-label",children:"Quality"})]}),s.jsxs("div",{className:"benchmark-stat latency",children:[s.jsxs("div",{className:"benchmark-stat-value",children:[r.summary.medianLatencyMs,"ms"]}),s.jsx("div",{className:"benchmark-stat-label",children:"Latency"})]}),s.jsxs("div",{className:"benchmark-stat fail",children:[s.jsx("div",{className:"benchmark-stat-value",children:Pie(r.summary.totalCostUsd)}),s.jsx("div",{className:"benchmark-stat-label",children:"Cost"})]})]})]}):s.jsxs("div",{className:"empty-state",children:["No benchmark runs yet. Run ",s.jsx("code",{children:"buff benchmark"})," to start."]})}),c.length>1&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"section-subtitle",children:"Pass Rate by Model"}),s.jsx("div",{className:"chart-container",children:s.jsx(Pa,{width:"100%",height:260,children:s.jsxs(Ma,{data:c,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(Wi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Br,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(zr,{domain:[0,100],tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"},tickFormatter:u=>u+"%"}),s.jsx(hn,{contentStyle:{background:"#161b22",border:"1px solid #30363d",borderRadius:8},labelStyle:{color:"#e6edf3"},formatter:u=>[u+"%","Pass Rate"]}),s.jsx(fn,{dataKey:"passRate",radius:[4,4,0,0],children:c.map((u,d)=>s.jsx(Pc,{fill:u.passRate>=80?"#3fb950":u.passRate>=50?"#d29922":"#f85149",fillOpacity:.8},d))})]})})}),s.jsx("h3",{className:"section-subtitle",children:"Latency by Model"}),s.jsx("div",{className:"chart-container",children:s.jsx(Pa,{width:"100%",height:260,children:s.jsxs(Ma,{data:c,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(Wi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Br,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(zr,{tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"},tickFormatter:u=>u+"ms"}),s.jsx(hn,{contentStyle:{background:"#161b22",border:"1px solid #30363d",borderRadius:8},labelStyle:{color:"#e6edf3"},formatter:u=>[u+"ms","Latency"]}),s.jsx(fn,{dataKey:"latency",fill:"#d29922",radius:[4,4,0,0],fillOpacity:.8})]})})}),s.jsx("h3",{className:"section-subtitle",children:"Cost by Model"}),s.jsx("div",{className:"chart-container",children:s.jsx(Pa,{width:"100%",height:260,children:s.jsxs(Ma,{data:c,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(Wi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Br,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(zr,{tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"},tickFormatter:u=>"$"+u.toFixed(6)}),s.jsx(hn,{contentStyle:{background:"#161b22",border:"1px solid #30363d",borderRadius:8},labelStyle:{color:"#e6edf3"},formatter:u=>["$"+u.toFixed(6),"Cost"]}),s.jsx(fn,{dataKey:"cost",fill:"#bc8cff",radius:[4,4,0,0],fillOpacity:.8})]})})})]}),s.jsx("h2",{className:"section-title",style:{marginTop:32},children:"🎯 Agent Evaluation"}),s.jsx("p",{className:"section-hint",style:{color:"#8b949e",fontSize:12,marginBottom:16},children:"End-to-end coding tasks run through the full agent pipeline — measures if the agent is actually improving."}),s.jsx("div",{className:"benchmark-latest",children:o?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"benchmark-header",children:[s.jsx("strong",{children:"Latest Eval Run:"})," ",o.provider,"/",o.model]}),s.jsxs("div",{className:"benchmark-stats",children:[s.jsxs("div",{className:"benchmark-stat pass",children:[s.jsxs("div",{className:"benchmark-stat-value",children:[o.summary.tasksPassed,"/",o.summary.totalTasks]}),s.jsx("div",{className:"benchmark-stat-label",children:"Tests Passed"})]}),s.jsxs("div",{className:"benchmark-stat quality",children:[s.jsx("div",{className:"benchmark-stat-value",children:pd(o.summary.avgCompositeScore)}),s.jsx("div",{className:"benchmark-stat-label",children:"Composite Score"})]}),s.jsxs("div",{className:"benchmark-stat latency",children:[s.jsx("div",{className:"benchmark-stat-value",children:pd(o.summary.recoveryRate)}),s.jsx("div",{className:"benchmark-stat-label",children:"Recovery Rate"})]}),s.jsxs("div",{className:"benchmark-stat fail",children:[s.jsx("div",{className:"benchmark-stat-value",children:o.summary.totalRollbacks}),s.jsx("div",{className:"benchmark-stat-label",children:"Rollbacks"})]}),s.jsxs("div",{className:"benchmark-stat deps",children:[s.jsx("div",{className:"benchmark-stat-value",children:pd(o.summary.dependencyInstallRate)}),s.jsx("div",{className:"benchmark-stat-label",children:"Deps Installed"})]})]})]}):s.jsxs("div",{className:"empty-state",children:["No eval runs yet. Run ",s.jsx("code",{children:"buff eval run"})," to measure the agent end-to-end."]})}),l.length>1&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"section-subtitle",children:"Composite Score by Model"}),s.jsx("div",{className:"chart-container",children:s.jsx(Pa,{width:"100%",height:260,children:s.jsxs(Ma,{data:l,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(Wi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Br,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(zr,{domain:[0,100],tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"},tickFormatter:u=>u+"%"}),s.jsx(hn,{contentStyle:{background:"#161b22",border:"1px solid #30363d",borderRadius:8},labelStyle:{color:"#e6edf3"},formatter:u=>[u+"%","Composite Score"]}),s.jsx(fn,{dataKey:"score",radius:[4,4,0,0],children:l.map((u,d)=>s.jsx(Pc,{fill:u.score>=80?"#3fb950":u.score>=50?"#d29922":"#f85149",fillOpacity:.8},d))})]})})}),s.jsx("h3",{className:"section-subtitle",children:"Metric Breakdown (completion / tests / recovery / token efficiency)"}),s.jsx("div",{className:"chart-container",children:s.jsx(Pa,{width:"100%",height:260,children:s.jsxs(Ma,{data:l,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(Wi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Br,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(zr,{domain:[0,100],tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"},tickFormatter:u=>u+"%"}),s.jsx(hn,{contentStyle:{background:"#161b22",border:"1px solid #30363d",borderRadius:8},labelStyle:{color:"#e6edf3"}}),s.jsx(Ga,{wrapperStyle:{color:"#8b949e"}}),s.jsx(fn,{dataKey:"completion",name:"Completion",fill:"#3fb950",radius:[4,4,0,0],fillOpacity:.8}),s.jsx(fn,{dataKey:"tests",name:"Tests",fill:"#58a6ff",radius:[4,4,0,0],fillOpacity:.8}),s.jsx(fn,{dataKey:"recovery",name:"Recovery",fill:"#d29922",radius:[4,4,0,0],fillOpacity:.8}),s.jsx(fn,{dataKey:"efficiency",name:"Token Eff.",fill:"#bc8cff",radius:[4,4,0,0],fillOpacity:.8})]})})})]}),s.jsx("h3",{className:"section-subtitle",children:"Eval Run History"}),s.jsx("div",{className:"benchmark-list",children:a.length===0?s.jsxs("div",{className:"empty-state",children:["No eval runs yet. Run ",s.jsx("code",{children:"buff eval run"})," to start."]}):a.map(u=>{const d=Math.round(u.summary.avgCompositeScore*100),f=d>=80?"high":d>=50?"medium":"low";return s.jsxs("div",{className:"benchmark-item",children:[s.jsx("span",{className:"benchmark-date",children:new Date(u.startedAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("span",{className:"benchmark-model",children:[u.provider,"/",u.model]}),s.jsxs("span",{className:`benchmark-score ${f}`,children:[d,"%"]})]},u.id)})}),s.jsx("h3",{className:"section-subtitle",children:"Run History"}),s.jsx("div",{className:"benchmark-list",children:i.length===0?s.jsxs("div",{className:"empty-state",children:["No benchmark runs yet. Run ",s.jsx("code",{children:"buff benchmark"})," to start."]}):i.map(u=>{const d=u.summary.totalTasks>0?Math.round(u.summary.tasksPassed/u.summary.totalTasks*100):0,f=d>=80?"high":d>=50?"medium":"low";return s.jsxs("div",{className:"benchmark-item",children:[s.jsx("span",{className:"benchmark-date",children:new Date(u.startedAt).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("span",{className:"benchmark-model",children:[u.provider,"/",u.model]}),s.jsxs("span",{className:`benchmark-score ${f}`,children:[d,"%"]})]},u.id)})})]})}function tg(e){return e==null?"0":e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}function Rie({data:e}){if(!e)return s.jsx("div",{className:"loading-state",children:s.jsx("p",{children:"Loading system data..."})});const{health:t,serverTime:n}=e;return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"⚙️ System Health"}),s.jsxs("div",{className:"health-grid",children:[s.jsxs("div",{className:"health-card",children:[s.jsx("span",{className:"health-icon",children:"💾"}),s.jsxs("div",{className:"health-body",children:[s.jsx("div",{className:"health-title",children:"Memory Directory"}),s.jsx("div",{className:"health-path",children:t.memoryDir||"~/.buff/memory/"})]})]}),s.jsxs("div",{className:"health-card",children:[s.jsx("span",{className:"health-icon",children:"📝"}),s.jsxs("div",{className:"health-body",children:[s.jsx("div",{className:"health-title",children:"Coding Patterns"}),s.jsx("div",{className:"health-value",children:tg(t.patterns)})]})]}),s.jsxs("div",{className:"health-card",children:[s.jsx("span",{className:"health-icon",children:"👍"}),s.jsxs("div",{className:"health-body",children:[s.jsx("div",{className:"health-title",children:"User Feedback"}),s.jsxs("div",{className:"health-value",children:[tg(t.feedback)," ratings"]})]})]}),s.jsxs("div",{className:"health-card",children:[s.jsx("span",{className:"health-icon",children:"🧠"}),s.jsxs("div",{className:"health-body",children:[s.jsx("div",{className:"health-title",children:"Vector Index"}),s.jsxs("div",{className:"health-value",children:[tg(t.vectors)," entries"]})]})]})]}),s.jsx("h3",{className:"section-subtitle",children:"Server Info"}),s.jsxs("div",{className:"server-info",children:[s.jsxs("div",{className:"info-row",children:[s.jsx("span",{className:"info-label",children:"Status"}),s.jsx("span",{className:"info-value",children:"● Connected"})]}),s.jsxs("div",{className:"info-row",children:[s.jsx("span",{className:"info-label",children:"Last Updated"}),s.jsx("span",{className:"info-value",children:n?new Date(n).toLocaleString():"--"})]}),s.jsxs("div",{className:"info-row",children:[s.jsx("span",{className:"info-label",children:"Data Directory"}),s.jsx("span",{className:"info-value",children:t.memoryDir||"~/.buff/memory/"})]})]})]})}const Iie=new Set(["local","lmstudio","vllm"]),$ie=new Set([]),gh={available:{bg:"#0a2e1a",text:"#3fb950",dot:"#3fb950",cardBorder:"#3fb950",cardBg:"#0d2818"},limited:{bg:"#2d1f00",text:"#d29922",dot:"#d29922",cardBorder:"#d29922",cardBg:"#1f1700"},unavailable:{bg:"#2d0f0f",text:"#f85149",dot:"#f85149",cardBorder:"#f85149",cardBg:"#1f0a0a"}},Lie=[3,4,5],XP=12e3,o_=[300,700],Die=6e4,Bie=5e3;function zie(e){return new Promise(t=>setTimeout(t,e))}async function ZP(e,t){const n=new AbortController,r=setTimeout(()=>n.abort(),t);try{return await fetch(e,{signal:n.signal})}finally{clearTimeout(r)}}function QP(e){return e instanceof TypeError||e instanceof Error&&e.name==="AbortError"}async function Fie(e){let t=null,n=!1;for(let r=0;;r++){try{const i=await ZP("/api/models",XP);if(!i.ok)t=i.status;else{const a=await ni(i);if(a&&Array.isArray(a.providers))return a;throw new Error("Model health endpoint returned an unexpected response — is the dashboard server up to date?")}}catch(i){if(!QP(i))throw i;n=!0,e==null||e()}if(r>=o_.length)throw new Error(n?"Dashboard server unreachable — is it still running? Retrying automatically…":`Model health endpoint failed (HTTP ${t})`);await zie(o_[r])}}async function Uie(e){for(let t=0;;t++)try{const n=await ZP("/api/model-registry",XP);return n.ok?await ni(n):null}catch(n){if(!QP(n)||t>=1)return null;e==null||e()}}function Wie(e){return e==="available"?"Available":e==="limited"?"Limited":"Unavailable"}function Hie(e){return e==="available"?"Ready":e==="limited"?"Limited":"Down"}function JP(e){return{local:"💻",groq:"🟢",nim:"🔶",gemini:"🔷",openrouter:"🟣",openai:"🤖",anthropic:"🔮",mistral:"🌀",cohere:"🧠",together:"🟢",deepinfra:"🌐",fireworks:"🎆",perplexity:"❓",azure:"🔵",anyscale:"🔷",lmstudio:"🎨",vllm:"⚡"}[e]||"🔌"}function u0(e){return{local:"Ollama",groq:"Groq",nim:"NVIDIA NIM",gemini:"Gemini",openrouter:"OpenRouter",openai:"OpenAI",anthropic:"Anthropic",mistral:"Mistral",cohere:"Cohere",together:"Together AI",deepinfra:"DeepInfra",fireworks:"Fireworks AI",perplexity:"Perplexity",azure:"Azure OpenAI",anyscale:"Anyscale",lmstudio:"LM Studio",vllm:"vLLM / TGI"}[e]||e}function l_({status:e,label:t}){const n=gh[e];return s.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,background:n.bg,color:n.text,padding:"3px 10px",borderRadius:12,fontSize:12,fontWeight:500,border:`1px solid ${n.text}22`},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:n.dot}}),t]})}function Gie({onRefresh:e,loading:t}){return s.jsxs("div",{className:"stats-grid mini",style:{marginBottom:16},children:[s.jsx("button",{onClick:e,disabled:t,className:"stat-card",style:{cursor:t?"not-allowed":"pointer",opacity:t?.6:1,border:"1px solid #30363d",justifyContent:"center",fontSize:13},children:t?"⏳ Testing...":"🔄 Refresh Status"}),s.jsx("div",{className:"stat-card",style:{border:"1px solid #30363d"},children:s.jsx("div",{style:{fontSize:13,color:"#8b949e",textAlign:"center",width:"100%"},children:"Tests all configured providers and their API keys in real time"})})]})}function qie({data:e}){const t=e.totalModels;if(t===0)return null;const n=e.available||0,r=e.limited||0,i=e.unavailable||0;return s.jsxs("div",{style:{marginBottom:16},children:[s.jsxs("div",{style:{background:"#0d1117",borderRadius:8,overflow:"hidden",height:10,display:"flex",border:"1px solid #21262d"},children:[n>0&&s.jsx("div",{style:{width:`${n/t*100}%`,background:"#3fb950",transition:"width 0.5s"},title:`${n} available`}),r>0&&s.jsx("div",{style:{width:`${r/t*100}%`,background:"#d29922",transition:"width 0.5s"},title:`${r} limited`}),i>0&&s.jsx("div",{style:{width:`${i/t*100}%`,background:"#f85149",transition:"width 0.5s"},title:`${i} unavailable`})]}),s.jsxs("div",{style:{display:"flex",gap:16,marginTop:6,fontSize:12,color:"#8b949e"},children:[s.jsxs("span",{children:[s.jsx("span",{style:{color:"#3fb950"},children:"●"})," Ready"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#d29922"},children:"●"})," Limited"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#f85149"},children:"●"})," Unavailable"]})]}),typeof e.routable=="number"&&s.jsxs("div",{style:{marginTop:6,fontSize:12,color:"#8b949e",lineHeight:1.5},children:[s.jsx("strong",{style:{color:"#e6edf3"},children:t})," listed by providers ·"," ",s.jsx("strong",{style:{color:e.routable>0?"#3fb950":"#d29922"},children:e.routable})," ","routable right now (verified, un-parked, not stale)",typeof e.registryTotal=="number"&&e.registryTotal>0&&s.jsxs(s.Fragment,{children:[" ","· registry tracks"," ",s.jsx("strong",{style:{color:"#e6edf3"},children:e.registryVerified??0})," of"," ",s.jsx("strong",{style:{color:"#e6edf3"},children:e.registryTotal})," verified"]})]})]})}function md({provider:e}){const[t,n]=E.useState(!1),r=gh[e.overallStatus].text,i={available:e.models.filter(a=>a.status==="available").length,limited:e.models.filter(a=>a.status==="limited").length,unavailable:e.models.filter(a=>a.status==="unavailable").length};return s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:`1px solid ${r}44`,borderLeft:`4px solid ${r}`,marginBottom:12,overflow:"hidden"},children:[s.jsxs("div",{onClick:()=>n(!t),style:{padding:"14px 18px",cursor:"pointer",display:"flex",alignItems:"center",gap:14,userSelect:"none"},children:[s.jsx("span",{style:{fontSize:24},children:e.icon}),s.jsxs("div",{style:{flex:1},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:2},children:[s.jsx("span",{style:{fontSize:16,fontWeight:600,color:"#e6edf3"},children:e.providerLabel}),s.jsx(l_,{status:e.overallStatus,label:Wie(e.overallStatus)})]}),s.jsxs("div",{style:{fontSize:13,color:"#8b949e"},children:[e.models.length," model",e.models.length!==1?"s":"",i.available>0&&s.jsxs("span",{style:{color:"#3fb950"},children:[" · ",i.available," ready"]}),i.limited>0&&s.jsxs("span",{style:{color:"#d29922"},children:[" · ",i.limited," limited"]}),i.unavailable>0&&s.jsxs("span",{style:{color:"#f85149"},children:[" · ",i.unavailable," unavailable"]})]})]}),s.jsxs("div",{style:{fontSize:12,color:"#8b949e",textAlign:"right"},children:[s.jsx("div",{style:{marginBottom:2,color:e.apiConfigured?"#3fb950":"#f85149"},children:e.apiConfigured?"✅ Key set":"❌ No key"}),s.jsx("div",{style:{color:e.apiAccessible?"#3fb950":"#f85149"},children:e.apiAccessible?"✅ Connected":"❌ Offline"})]}),s.jsx("span",{style:{color:"#8b949e",fontSize:18,transition:"transform 0.2s",transform:t?"rotate(90deg)":"rotate(0deg)"},children:"▶"})]}),t&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{padding:"10px 18px",background:"#0d1117",fontSize:13,color:"#8b949e",display:"flex",justifyContent:"space-between",flexWrap:"wrap",gap:8,borderTop:"1px solid #21262d"},children:[s.jsx("span",{children:e.notes}),e.freeTierInfo&&s.jsxs("span",{style:{color:"#d29922"},children:["🎁 ",e.freeTierInfo]})]}),s.jsx("div",{style:{overflowX:"auto",borderTop:"1px solid #21262d"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid #21262d",color:"#8b949e"},children:[s.jsx("th",{style:{padding:"8px 18px",textAlign:"left",fontWeight:500},children:"Model"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Status"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Quota"}),s.jsx("th",{style:{padding:"8px 18px",textAlign:"left",fontWeight:500},children:"Details"})]})}),s.jsx("tbody",{children:e.models.map((a,o)=>s.jsxs("tr",{style:{borderBottom:o<e.models.length-1?"1px solid #21262d":"none",background:a.status==="unavailable"?"#0d1117":"transparent"},children:[s.jsxs("td",{style:{padding:"8px 18px",color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12},children:[s.jsx("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:gh[a.status].dot,marginRight:8}}),a.name]}),s.jsx("td",{style:{padding:"8px 12px"},children:s.jsx(l_,{status:a.status,label:Hie(a.status)})}),s.jsx("td",{style:{padding:"8px 12px",color:"#8b949e",fontSize:12,fontFamily:"'SFMono-Regular', Consolas, monospace"},children:a.rateLimitRemaining!==void 0?a.rateLimitTotal?`${a.rateLimitRemaining}/${a.rateLimitTotal}`:`${a.rateLimitRemaining} left`:"—"}),s.jsx("td",{style:{padding:"8px 18px",color:"#8b949e",fontSize:12},children:a.statusReason})]},a.id))})]})})]})]})}function eM(e){if(e<=0)return"now";const t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4);return t>0?`${t}h ${n}m`:n>0?`${n}m`:`${Math.ceil(e/1e3)}s`}function Kie(e){return e==="verified"?{text:"#3fb950",bg:"#0a2e1a",dot:"#3fb950"}:e==="unavailable"?{text:"#f85149",bg:"#2d0f0f",dot:"#f85149"}:{text:"#8b949e",bg:"#21262d",dot:"#8b949e"}}function Vie({rate:e}){const t=Math.round(e*100);return s.jsxs("span",{title:`⏸ flaky mid-stream ${t}% — started streaming, died before finish; the router deprioritizes flaky models (P4 M4.4)`,style:{marginLeft:8,fontSize:10,padding:"1px 6px",borderRadius:8,whiteSpace:"nowrap",background:"#21122e",border:"1px solid #bc8cff",color:"#bc8cff"},children:["⏸ flaky ",t,"%"]})}function Yie({tokens:e}){const t=e>=1048576?`${(e/1048576).toFixed(1).replace(/\.0$/,"")}M`:e>=1024?`${(e/1024).toFixed(0)}K`:`${e}`;return s.jsxs("span",{title:`⏳ context window ${e.toLocaleString()} tokens — live from the provider's model list (v1.60.x); feeds the router's context preflight`,style:{marginLeft:8,fontSize:10,padding:"1px 6px",borderRadius:8,whiteSpace:"nowrap",background:"#0a1e2e",border:"1px solid #58a6ff",color:"#58a6ff"},children:["⏳ ",t]})}function Xie({history:e}){if(!e||e.length<2)return null;const t=46,n=14,r=1.5,i=Math.max(.01,...e.map(d=>d.rate)),a=e.map((d,f)=>{const h=r+f/(e.length-1)*(t-r*2),p=n-r-d.rate/i*(n-r*2);return`${h.toFixed(1)},${p.toFixed(1)}`}).join(" "),o=e[0].rate,l=e[e.length-1].rate,c=l<o,u=Math.round(l*100);return s.jsxs("svg",{width:t,height:n,viewBox:`0 0 ${t} ${n}`,style:{marginLeft:8,verticalAlign:"middle",cursor:"default"},"aria-label":"Flakiness trend",children:[s.jsx("title",{children:c?`Flakiness healing — ${u}% now, trending down (clean successes decay the signal)`:`Flakiness climbing — ${u}% now (recent mid-stream interruptions)`}),s.jsx("polyline",{points:a,fill:"none",stroke:"#bc8cff",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",opacity:.9}),s.jsx("circle",{cx:t-r,cy:n-r-l/i*(n-r*2),r:2,fill:c?"#3fb950":"#bc8cff"})]})}function Zie({entry:e}){const t=Kie(e.status),n=e.remainingTokens>=0?`${e.remainingTokens.toLocaleString()} left`:"unlimited";return s.jsxs("tr",{style:{borderBottom:"1px solid #21262d"},children:[s.jsxs("td",{style:{padding:"8px 12px",color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12},children:[s.jsx("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",background:t.dot,marginRight:8}}),e.model.length>32?e.model.slice(0,29)+"…":e.model,(e.partialRate??0)>0&&s.jsx(Vie,{rate:e.partialRate??0}),e.partialHistory&&e.partialHistory.length>=2&&s.jsx(Xie,{history:e.partialHistory}),e.parked&&s.jsx("span",{style:{marginLeft:8,fontSize:10,padding:"1px 6px",borderRadius:8,background:"#2d1616",border:"1px solid #f85149",color:"#f85149"},children:"⏸ parked"}),e.measuredSamples?s.jsxs("span",{style:{marginLeft:8,fontSize:10,padding:"1px 6px",borderRadius:8,whiteSpace:"nowrap",background:"#0a2e1a",border:"1px solid #3fb950",color:"#3fb950"},children:["📏 ",e.measuredInputTokens,"→",e.measuredOutputTokens," tok"]}):s.jsx("span",{style:{marginLeft:8,fontSize:10,padding:"1px 6px",borderRadius:8,whiteSpace:"nowrap",background:"#21262d",border:"1px solid #8b949e",color:"#8b949e"},children:"📐 est"}),e.contextWindowTokens&&s.jsx(Yie,{tokens:e.contextWindowTokens})]}),s.jsx("td",{style:{padding:"8px 12px"},children:s.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,fontWeight:600,background:t.bg,color:t.text,padding:"2px 8px",borderRadius:6},children:e.status==="verified"?"✓ Verified":e.status==="unavailable"?"✗ Unavailable":"◌ Unverified"})}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12,color:e.remainingTokens>=0&&e.remainingTokens<=100?"#d29922":"#8b949e"},children:n}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",color:"#8b949e",fontSize:12,whiteSpace:"nowrap"},children:e.resetsInMs>0?eM(e.resetsInMs):"—"}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",color:"#8b949e",fontSize:12,fontFamily:"'SFMono-Regular', Consolas, monospace"},children:e.latencyMs!==void 0?`${e.latencyMs}ms`:"—"}),s.jsx("td",{style:{padding:"8px 12px",color:"#6e7681",fontSize:11,maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.lastError||(e.source?`learned via ${e.source}`:"")})]})}function Qie({provider:e}){const[t,n]=E.useState(!1),r=e.verified>0?"#3fb950":e.unavailable>0?"#f85149":"#8b949e";return s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:`1px solid ${r}44`,borderLeft:`4px solid ${r}`,marginBottom:12,overflow:"hidden"},children:[s.jsxs("div",{onClick:()=>n(!t),style:{padding:"14px 18px",cursor:"pointer",display:"flex",alignItems:"center",gap:14,userSelect:"none"},children:[s.jsx("span",{style:{fontSize:24},children:JP(e.provider)}),s.jsxs("div",{style:{flex:1},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:2},children:[s.jsx("span",{style:{fontSize:16,fontWeight:600,color:"#e6edf3"},children:u0(e.provider)}),s.jsx("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:10,background:e.parked>0?"#2d1616":"#12291a",border:`1px solid ${e.parked>0?"#f85149":"#238636"}`,color:e.parked>0?"#f85149":"#3fb950"},children:e.parked>0?`${e.parked} parked`:"routable"}),(e.flaky??0)>0&&s.jsxs("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:10,background:"#21122e",border:"1px solid #bc8cff",color:"#bc8cff"},children:["⏸ ",e.flaky," flaky"]})]}),s.jsxs("div",{style:{fontSize:13,color:"#8b949e"},children:[e.verified," verified · ",e.unverified," unverified · ",e.unavailable," unavailable"]})]}),s.jsx("span",{style:{color:"#8b949e",fontSize:18,transition:"transform 0.2s",transform:t?"rotate(90deg)":"rotate(0deg)"},children:"▶"})]}),t&&s.jsx("div",{style:{overflowX:"auto",borderTop:"1px solid #21262d"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid #21262d",color:"#8b949e"},children:[s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Model"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Availability"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"right",fontWeight:500},children:"Tokens left"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"right",fontWeight:500},children:"Resets in"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"right",fontWeight:500},children:"Latency"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Reason / Source"})]})}),s.jsx("tbody",{children:e.models.map(i=>s.jsx(Zie,{entry:i},i.model))})]})})]})}function Jie(e){if(!e)return null;const t=Object.entries(e.consecutive).filter(([,n])=>n>0);return t.length===0?null:s.jsxs("div",{style:{background:"rgba(210, 153, 34, 0.08)",border:"1px solid #9e6a03",borderRadius:10,padding:"10px 14px",marginBottom:14,fontSize:12,color:"#d29922",display:"flex",gap:10,alignItems:"flex-start"},children:[s.jsx("span",{style:{fontSize:15,lineHeight:"18px"},children:"🧹"}),s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600,color:"#e3b341",marginBottom:2},children:"Key hygiene in progress"}),s.jsx("div",{children:t.map(([n,r])=>s.jsxs("span",{style:{display:"inline-block",marginRight:12},children:[s.jsx("code",{style:{color:"#e6edf3"},children:n})," ",r,"/",e.threshold," consecutive auth failures",r>=e.threshold?" — key auto-cleared 🚫":" — key will be auto-cleared at the threshold"]},n))}),s.jsxs("div",{style:{marginTop:4,color:"#9e6a03"},children:["After ",e.threshold," consecutive 401/403s the invalid key is removed from config; run"," ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff config set providers.<provider>.apiKey <real-key>"})," to re-enable."]})]})]})}function eae({data:e}){return e.enabled?s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",style:{marginTop:36},children:"📦 Model Availability Registry — the store routing reads"}),s.jsxs("p",{className:"section-description",children:["The unified sub-ms FAISS/JSON snapshot the Auto router consults on every pick: verified vs unavailable models plus quota telemetry (tokens remaining, reset windows) mirrored from the ledger. Each row's ",s.jsx("strong",{children:"⏳ chip"})," is the LIVE provider-advertised context window (v1.60.x) — the real spec the router's context preflight uses, recorded by the probe from each provider's model list (Ollama /api/tags + /api/show, OpenRouter, Gemini, NIM). State changes during a session are reported to the watch daemon and recorded here immediately."]}),s.jsxs("div",{className:"stats-grid",style:{marginBottom:16},children:[s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"📦"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",children:e.total}),s.jsx("div",{className:"stat-label",children:"Tracked models"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"✅"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#3fb950"},children:e.verified}),s.jsx("div",{className:"stat-label",children:"Verified"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"◌"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#8b949e"},children:e.unverified}),s.jsx("div",{className:"stat-label",children:"Unverified"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"⛔"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#f85149"},children:e.unavailable}),s.jsx("div",{className:"stat-label",children:"Unavailable"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"⏸"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#d29922"},children:e.parked}),s.jsx("div",{className:"stat-label",children:"Quota-parked"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"⏸"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#bc8cff"},children:e.flaky??0}),s.jsx("div",{className:"stat-label",children:"Flaky mid-stream"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"🗑️"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#8b949e"},children:e.deletedLocal??0}),s.jsx("div",{className:"stat-label",children:"Deleted locally"})]})]})]}),Jie(e.keyHygiene),e.providers.map(t=>s.jsx(Qie,{provider:t},t.provider)),s.jsx("div",{style:{textAlign:"center",fontSize:12,color:"#484f58",marginTop:12},children:"Backend snapshot · auto-refreshes every 60s"})]}):s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:"1px dashed #30363d",padding:"20px 24px",marginTop:24,textAlign:"center"},children:[s.jsx("div",{style:{fontSize:24,marginBottom:8},children:"📦"}),s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#e6edf3",marginBottom:4},children:"Model Availability Registry"}),s.jsxs("div",{style:{fontSize:12,color:"#6e7681"},children:["No registry data yet — run ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff models refresh"})," or use Auto routing; the registry learns from real usage and probes."]})]})}const tae={chat:"💬",execute:"⚙️",plan:"🗺️",edit:"✏️",skill:"🧩",learn:"📚",ci:"🔁",doctor:"🩺",probe:"🔭","spot-check":"🧪",telemetry:"📡",usage:"🧮"};function nae(e){return{chat:"Chat",execute:"Execute",plan:"Plan",edit:"Edit",skill:"Skill",learn:"Learn",ci:"CI Review",doctor:"Doctor Probe",probe:"Probe","spot-check":"Spot-check",telemetry:"Usage mirror"}[e]||e.charAt(0).toUpperCase()+e.slice(1)}function rae(e){return tae[e]||"🎯"}function iae(e){return e?new Date(e).toLocaleDateString()+" "+new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"—"}function Ua({provider:e,model:t,reason:n,killed:r,transient:i,partial:a,streamedChunks:o}){const l=r===!0,c=i===!0,u=a===!0,d=u?"#bc8cff":c?"#d29922":l?"#f85149":"#3fb950",f=u?"#21122e":c?"#2d1f00":l?"#2d0f0f":"#0a2e1a";return s.jsxs("span",{title:u?`Mid-stream interruption — started streaming${typeof o=="number"?` ~${o} chunks in`:""}, died before finish (P4 M4.4); router deprioritizes flaky mid-stream providers${n?` · ${n}`:""}`:c?`Transient failure — health decayed, no flip${n?` · ${n}`:""}`:l?`Killed by this action — predictively skipped by routing${n?` · ${n}`:""}`:"Verified by this action — trusted by routing",style:{display:"inline-flex",alignItems:"center",gap:6,background:f,border:`1px solid ${d}`,color:d,padding:"3px 9px",borderRadius:8,fontSize:11,fontFamily:"'SFMono-Regular', Consolas, monospace",whiteSpace:"nowrap",transition:"transform 0.15s",cursor:"default"},onMouseEnter:h=>{h.currentTarget.style.transform="scale(1.05)"},onMouseLeave:h=>{h.currentTarget.style.transform="scale(1)"},children:[s.jsx("span",{style:{opacity:.85},children:u?"⏸":c?"~":l?"✗":"✓"}),e,"/",t.length>30?t.slice(0,27)+"…":t,(l||u)&&n&&s.jsxs("span",{style:{color:`${d}99`,fontSize:10,fontWeight:400},children:["· ",n]})]})}function aae(e){const t=new Map;for(const r of e)t.set(`${r.provider}|${r.model}|${r.outcome}`,r);const n={unavailable:0,partial:1,verified:2,error:3};return[...t.values()].sort((r,i)=>n[r.outcome]-n[i.outcome]||i.at-r.at)}function sae(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(n.verified+n.killed+n.transient+(n.partial||0)>0)return t}return Math.max(0,e.length-1)}function oae({timeline:e}){const[t,n]=E.useState(()=>sae(e||[])),[r,i]=E.useState(!1),a=E.useRef(null),o=E.useRef(!1),l=(e==null?void 0:e.length)??0,c=Math.max(0,Math.min(t,l-1));E.useEffect(()=>{n(m=>Math.min(m,Math.max(0,l-1)))},[l]);const u=E.useCallback(m=>{const v=a.current;if(!v||l<=0)return;const y=v.getBoundingClientRect(),b=y.width||1,x=Math.min(1,Math.max(0,(m-y.left)/b));n(Math.min(l-1,Math.floor(x*l)))},[l]),d=m=>{o.current=!0,i(!1),u(m.clientX)};if(E.useEffect(()=>{const m=y=>{o.current&&u(y.clientX)},v=()=>{o.current=!1};return window.addEventListener("pointermove",m),window.addEventListener("pointerup",v),()=>{window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",v)}},[u]),E.useEffect(()=>{if(!r||l<=1)return;const m=setInterval(()=>{n(v=>Math.min(l-1,v+1))},300);return()=>clearInterval(m)},[r,l]),E.useEffect(()=>{r&&l>1&&t>=l-1&&(i(!1),n(0))},[r,l,t]),!e||l===0)return null;const f=Math.max(1,...e.map(m=>m.verified+m.killed+m.transient+(m.partial||0))),h=m=>new Date(m).toLocaleDateString([],{month:"short",day:"numeric"}),p=e[c],g=p?aae(p.events||[]):[];return s.jsxs("div",{style:{marginTop:12,paddingTop:10,borderTop:"1px solid #21262d"},children:[s.jsxs("div",{style:{fontSize:11,fontWeight:600,color:"#8b949e",marginBottom:8,textTransform:"uppercase",letterSpacing:.4,display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[s.jsxs("span",{children:["📈 Learned from real usage — last ",l," days"]}),s.jsx("span",{style:{fontWeight:400,color:"#6e7681",letterSpacing:0},children:"— drag across days · click a day · play to sweep"})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:8},children:[s.jsx("button",{onClick:()=>{r?i(!1):(t>=l-1&&n(0),i(!0))},disabled:l<=1,"aria-label":r?"Pause scrub":"Play scrub",style:{background:"#21262d",border:`1px solid ${r?"#f85149":"#30363d"}`,color:"#e6edf3",padding:"3px 10px",borderRadius:6,cursor:l<=1?"not-allowed":"pointer",fontSize:11,fontWeight:600,transition:"all 0.15s",whiteSpace:"nowrap",opacity:l<=1?.5:1},children:r?"⏸ Pause":"▶ Play"}),s.jsxs("span",{style:{fontSize:11,color:"#8b949e",whiteSpace:"nowrap"},children:[h(p.day)," · ✓ ",p.verified," · ✗ ",p.killed,p.transient>0?` · ~ ${p.transient}`:"",p.partial>0?` · ⏸ ${p.partial}`:""]}),s.jsx("input",{type:"range",min:0,max:Math.max(0,l-1),step:1,value:c,onChange:m=>{i(!1),n(Number(m.target.value))},"aria-label":"Scrub action timeline",style:{flex:1,accentColor:"#58a6ff",cursor:"pointer",minWidth:80}})]}),s.jsx("div",{ref:a,onPointerDown:d,style:{position:"relative",display:"flex",alignItems:"flex-end",gap:3,height:64,padding:"0 2px",cursor:"grab",userSelect:"none",touchAction:"none"},children:e.map((m,v)=>{const y=m.verified+m.killed+m.transient+(m.partial||0),b=m.verified/f*56,x=m.killed/f*56,k=m.transient/f*56,S=(m.partial||0)/f*56,w=v===c;return s.jsxs("div",{onClick:()=>{i(!1),n(v)},title:`${h(m.day)} — ✓ ${m.verified} verified · ✗ ${m.killed} killed · ~ ${m.transient} transient${(m.partial||0)>0?` · ⏸ ${m.partial} partial`:""}`,style:{flex:1,display:"flex",flexDirection:"column-reverse",alignItems:"center",gap:0,cursor:"pointer"},children:[s.jsxs("div",{style:{position:"relative",width:"100%",borderRadius:3,overflow:w?"visible":"hidden",background:y===0?"#21262d":"transparent",height:y===0?4:56,display:"flex",flexDirection:"column-reverse",boxShadow:w?"0 0 0 1.5px #58a6ff":void 0,opacity:y===0?.5:1,transition:"box-shadow 0.15s"},children:[w&&s.jsx("div",{style:{position:"absolute",top:-3,bottom:-3,width:2,left:"50%",transform:"translateX(-50%)",background:"#58a6ff",borderRadius:2,pointerEvents:"none",boxShadow:"0 0 8px #58a6ff88",zIndex:1}}),m.verified>0&&s.jsx("div",{style:{height:b,background:"#3fb950",minHeight:3}}),m.killed>0&&s.jsx("div",{style:{height:x,background:"#f85149",minHeight:3}}),m.transient>0&&s.jsx("div",{style:{height:k,background:"#d29922",minHeight:3}}),m.partial>0&&s.jsx("div",{style:{height:S,background:"#bc8cff",minHeight:3}})]}),s.jsx("div",{style:{fontSize:9,color:w?"#58a6ff":"#6e7681",marginTop:4,whiteSpace:"nowrap",fontWeight:w?700:400},children:h(m.day)})]},m.day)})}),s.jsxs("div",{style:{display:"flex",gap:14,marginTop:6,fontSize:11,color:"#8b949e"},children:[s.jsxs("span",{children:[s.jsx("span",{style:{color:"#3fb950"},children:"■"})," verified"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#f85149"},children:"■"})," killed"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#d29922"},children:"■"})," transient"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#bc8cff"},children:"■"})," partial"]})]}),s.jsxs("div",{style:{marginTop:10,background:"#161b22",border:"1px solid #21262d",borderRadius:8,padding:"10px 12px"},children:[s.jsxs("div",{style:{fontSize:12,fontWeight:600,color:"#e6edf3",marginBottom:6},children:[h(p.day)," ",s.jsx("span",{style:{color:"#8b949e",fontWeight:400},children:"— what this action learned that day"})]}),g.length===0?s.jsx("div",{style:{fontSize:12,color:"#6e7681"},children:"No learning recorded that day — nothing verified, killed, or partial."}):s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:g.map(m=>m.outcome==="unavailable"?s.jsx(Ua,{provider:m.provider,model:m.model,reason:m.errorType,killed:!0},`${m.provider}|${m.model}|${m.outcome}`):m.outcome==="verified"?s.jsx(Ua,{provider:m.provider,model:m.model},`${m.provider}|${m.model}|${m.outcome}`):m.outcome==="partial"?s.jsx(Ua,{provider:m.provider,model:m.model,reason:m.errorType,partial:!0,streamedChunks:m.streamedChunks},`${m.provider}|${m.model}|${m.outcome}`):s.jsx(Ua,{provider:m.provider,model:m.model,reason:m.errorType,transient:!0},`${m.provider}|${m.model}|${m.outcome}`))})]})]})}function lae({entry:e}){var i,a;const[t,n]=E.useState(!0),r=(e.partial||0)>0?"#bc8cff":e.killed>0?"#f85149":e.verified>0?"#3fb950":"#d29922";return s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:`1px solid ${r}33`,borderLeft:`4px solid ${r}`,marginBottom:12,overflow:"hidden"},children:[s.jsxs("div",{onClick:()=>n(!t),style:{padding:"12px 16px",cursor:"pointer",display:"flex",alignItems:"center",gap:12,userSelect:"none"},children:[s.jsx("span",{style:{fontSize:20},children:rae(e.action)}),s.jsxs("div",{style:{flex:1},children:[s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#e6edf3",marginBottom:2},children:nae(e.action)}),s.jsxs("div",{style:{fontSize:12,color:"#8b949e",display:"flex",gap:14,flexWrap:"wrap"},children:[s.jsxs("span",{children:[s.jsxs("span",{style:{color:"#3fb950"},children:["✓ ",e.verified]})," verified"]}),s.jsxs("span",{children:[s.jsxs("span",{style:{color:"#f85149"},children:["✗ ",e.killed]})," killed"]}),e.transient>0&&s.jsxs("span",{children:[s.jsxs("span",{style:{color:"#d29922"},children:["~ ",e.transient]})," transient"]}),(e.partial||0)>0&&s.jsxs("span",{children:[s.jsxs("span",{style:{color:"#bc8cff"},children:["⏸ ",e.partial]})," partial"]})]})]}),s.jsx("span",{style:{color:"#8b949e",fontSize:16,transition:"transform 0.2s",transform:t?"rotate(90deg)":"rotate(0deg)"},children:"▶"})]}),t&&s.jsxs("div",{style:{padding:"12px 16px",borderTop:"1px solid #21262d",background:"#0d1117"},children:[e.killedModels.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:11,fontWeight:600,color:"#f85149",marginBottom:6,textTransform:"uppercase",letterSpacing:.4},children:"⛔ Killed — skipped predictively by routing"}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:14},children:e.killedModels.map(o=>s.jsx(Ua,{provider:o.provider,model:o.model,reason:o.reason,killed:!0},`${o.provider}|${o.model}`))})]}),e.verifiedModels.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:11,fontWeight:600,color:"#3fb950",marginBottom:6,textTransform:"uppercase",letterSpacing:.4},children:"✅ Verified — trusted by routing"}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:e.verifiedModels.map(o=>s.jsx(Ua,{provider:o.provider,model:o.model},`${o.provider}|${o.model}`))})]}),(((i=e.partialModels)==null?void 0:i.length)||0)>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{style:{fontSize:11,fontWeight:600,color:"#bc8cff",marginBottom:6,textTransform:"uppercase",letterSpacing:.4},children:"⏸ Partial — mid-stream interruption (flaky provider, deprioritized)"}),s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:14},children:e.partialModels.map(o=>s.jsx(Ua,{provider:o.provider,model:o.model,reason:o.reason,partial:!0,streamedChunks:o.streamedChunks},`${o.provider}|${o.model}`))})]}),e.killedModels.length===0&&e.verifiedModels.length===0&&(((a=e.partialModels)==null?void 0:a.length)||0)===0&&s.jsx("div",{style:{fontSize:12,color:"#6e7681"},children:"Only transient failures — health decayed, no model flipped."}),s.jsx(oae,{timeline:e.timeline})]})]})}function cae({registry:e}){const t=e.actionTelemetry;return t?t.enabled?s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",style:{marginTop:36},children:"🎓 Learned from real usage — per action"}),s.jsxs("p",{className:"section-description",children:["Every LLM call writes through to the health store with its action tag. This panel shows which provider × model each action ",s.jsx("span",{style:{color:"#3fb950"},children:"verified"})," (routable) or"," ",s.jsx("span",{style:{color:"#f85149"},children:"killed"})," (predictively skipped) — the exact feed that turns “fail gemini → fail nim → local” into “straight to local”."]}),s.jsxs("div",{className:"stats-grid mini",style:{marginBottom:16},children:[s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"📊"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",children:t.total}),s.jsx("div",{className:"stat-label",children:"Telemetry events"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"🎯"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",children:t.actions.length}),s.jsx("div",{className:"stat-label",children:"Actions learning"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"⏱️"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{fontSize:15},children:iae(t.updatedAt)}),s.jsx("div",{className:"stat-label",children:"Last update"})]})]}),t.synthetic>0&&s.jsxs("div",{className:"stat-card",title:"Written by a test process — excluded from every number on this panel. The records remain in the hash-chained log.",children:[s.jsx("span",{className:"stat-icon",children:"🧪"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#d29922"},children:t.synthetic}),s.jsx("div",{className:"stat-label",children:"Test-origin, excluded"})]})]})]}),t.actions.map(n=>s.jsx(lae,{entry:n},n.action)),s.jsx("div",{style:{textAlign:"center",fontSize:12,color:"#484f58",marginTop:12},children:"All actions share one health store — a provider killed by any action is skipped by all others"})]}):s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:"1px dashed #30363d",padding:"18px 24px",marginTop:24,textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,marginBottom:6},children:"🎓"}),s.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e6edf3",marginBottom:4},children:"Learned from real usage — per action"}),s.jsxs("div",{style:{fontSize:12,color:"#6e7681",lineHeight:1.5},children:["No per-action telemetry yet. As you use ",s.jsx("strong",{style:{color:"#8b949e"},children:"chat"}),","," ",s.jsx("strong",{style:{color:"#8b949e"},children:"execute"}),", ",s.jsx("strong",{style:{color:"#8b949e"},children:"plan"}),", and ",s.jsx("strong",{style:{color:"#8b949e"},children:"edit"}),", each action's verified / killed provider × model combos appear here — showing exactly what routing learned from real usage."]})]}):null}function gd({icon:e,title:t,count:n}){return n===0?null:s.jsxs("h3",{style:{fontSize:15,fontWeight:600,color:"#e6edf3",margin:"24px 0 12px 0",display:"flex",alignItems:"center",gap:8},children:[s.jsx("span",{children:e})," ",t,s.jsx("span",{style:{fontSize:12,color:"#8b949e",fontWeight:400,background:"#161b22",padding:"1px 8px",borderRadius:8},children:n})]})}function uae({value:e,onChange:t,totalCount:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:14},children:[s.jsxs("div",{style:{flex:1,position:"relative",display:"flex",alignItems:"center",background:"#161b22",borderRadius:8,border:"1px solid #30363d",transition:"border-color 0.2s"},children:[s.jsx("span",{style:{position:"absolute",left:12,fontSize:14,color:"#6e7681",pointerEvents:"none"},children:"🔍"}),s.jsx("input",{type:"text",value:e,onChange:r=>t(r.target.value),placeholder:"Search models by name or provider...",style:{width:"100%",padding:"10px 12px 10px 36px",background:"transparent",border:"none",color:"#e6edf3",fontSize:13,outline:"none",fontFamily:"inherit"},onFocus:r=>{r.currentTarget.parentElement.style.borderColor="#58a6ff"},onBlur:r=>{r.currentTarget.parentElement.style.borderColor="#30363d"}}),e&&s.jsx("button",{onClick:()=>t(""),style:{background:"none",border:"none",color:"#6e7681",cursor:"pointer",padding:"8px 12px",fontSize:14,lineHeight:1},children:"✕"})]}),s.jsxs("div",{style:{fontSize:12,color:"#8b949e",whiteSpace:"nowrap"},children:[n," model",n!==1?"s":""]})]})}function dae({value:e,onChange:t}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:"#8b949e",marginBottom:14},children:[s.jsx("span",{children:"Columns:"}),Lie.map(n=>s.jsx("button",{onClick:()=>t(n),style:{padding:"4px 12px",borderRadius:6,background:e===n?"#1f6feb":"#21262d",color:e===n?"#fff":"#8b949e",border:`1px solid ${e===n?"#1f6feb":"#30363d"}`,cursor:"pointer",fontSize:12,fontWeight:e===n?600:400,transition:"all 0.15s"},children:n},n))]})}function fae({model:e,provider:t}){const n=gh[e.status],r=e.rateLimitRemaining!==void 0?e.rateLimitTotal?`${e.rateLimitRemaining} / ${e.rateLimitTotal}`:`${e.rateLimitRemaining} left`:"—";return s.jsx("td",{style:{padding:10,verticalAlign:"top"},children:s.jsxs("div",{style:{background:n.cardBg,border:`1px solid ${n.cardBorder}44`,borderRadius:10,padding:14,display:"flex",flexDirection:"column",gap:8,height:"100%",transition:"all 0.2s ease",position:"relative",overflow:"hidden",cursor:"default"},onMouseEnter:i=>{i.currentTarget.style.borderColor=n.cardBorder,i.currentTarget.style.boxShadow=`0 2px 10px ${n.cardBorder}22`},onMouseLeave:i=>{i.currentTarget.style.borderColor=`${n.cardBorder}44`,i.currentTarget.style.boxShadow="none"},children:[s.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,height:3,background:n.cardBorder,opacity:.6}}),s.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",paddingTop:2},children:e.name.length>28?e.name.slice(0,25)+"…":e.name}),s.jsxs("div",{style:{fontSize:12,color:"#8b949e"},children:[JP(t)," ",u0(t)]}),s.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:5,background:n.bg,color:n.text,padding:"3px 8px",borderRadius:6,fontSize:11,fontWeight:600,alignSelf:"flex-start"},children:[s.jsx("span",{style:{width:7,height:7,borderRadius:"50%",background:n.dot}}),e.status==="available"?"Available":e.status==="limited"?"Limited":"Unavailable"]}),s.jsxs("div",{style:{fontSize:11,color:"#6e7681"},children:[s.jsx("span",{style:{color:"#8b949e"},children:"Tokens:"})," ",s.jsx("span",{style:{color:e.rateLimitRemaining!==void 0&&e.rateLimitRemaining<=10?"#d29922":"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace",fontWeight:500},children:r})]}),e.routable===!1&&s.jsx("div",{style:{fontSize:10,color:"#d29922",lineHeight:1.3,marginTop:2},children:e.registryStatus==="unavailable"?e.registryDead?"✗ Not served here — this id does not exist on the endpoint":"✗ Your key cannot use this model (auth / entitlement / access)":e.registryStatus==="verified"?"◌ Parked or gone stale — not routable now":e.registryStatus==="unverified"?"◌ Listed but never verified — the router cannot pick it":"◌ Not in the registry — never probed"}),e.routable===!1&&e.registryError&&s.jsx("div",{style:{fontSize:10,color:"#6e7681",lineHeight:1.3,marginTop:1},children:e.registryError.length>60?e.registryError.slice(0,57)+"…":e.registryError}),e.entitlement&&e.entitlement.tier!=="unknown"&&s.jsx("div",{title:e.entitlement.basis,style:{fontSize:10,lineHeight:1.3,marginTop:2,color:e.entitlement.tier==="free"?"#3fb950":"#8b949e"},children:e.entitlement.tier==="free"?"🎁 free":"💸 metered"}),e.status!=="available"&&e.statusReason&&s.jsx("div",{style:{fontSize:10,color:"#6e7681",lineHeight:1.3,marginTop:2},children:e.statusReason.length>45?e.statusReason.slice(0,42)+"…":e.statusReason}),e.parked&&e.resetsInMs!==void 0&&e.resetsInMs>0&&s.jsxs("div",{style:{fontSize:10,color:"#d29922",lineHeight:1.3,marginTop:4,padding:"3px 6px",borderRadius:4,background:"#2d2200",border:"1px solid #d2992244"},children:["⏳ Resets in ",eM(e.resetsInMs)]})]})})}function hae({providers:e,colsPerRow:t,searchQuery:n}){const r=[];for(const l of e)for(const c of l.models)r.push({model:c,provider:l.provider});if(r.length===0)return null;let i=r;if(n.trim()){const l=n.toLowerCase().trim();i=r.filter(({model:c,provider:u})=>c.name.toLowerCase().includes(l)||u0(u).toLowerCase().includes(l)||u.toLowerCase().includes(l))}const a={available:0,limited:1,unavailable:2};i.sort((l,c)=>a[l.model.status]-a[c.model.status]);const o=[];for(let l=0;l<i.length;l+=t)o.push(i.slice(l,l+t));return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",style:{marginTop:36},children:"📋 Model Health Overview"}),s.jsx("p",{className:"section-description",children:"All models across all providers, color-coded by health status. Each cell shows: Model · Provider · Health · Token Remaining."}),s.jsx("div",{style:{overflowX:"auto"},children:s.jsx("table",{style:{width:"100%",borderCollapse:"separate",borderSpacing:10,tableLayout:"fixed"},children:s.jsx("tbody",{children:o.length>0?o.map((l,c)=>s.jsxs("tr",{children:[l.map(({model:u,provider:d})=>s.jsx(fae,{model:u,provider:d},`${d}-${u.id}`)),l.length<t&&Array.from({length:t-l.length}).map((u,d)=>s.jsx("td",{style:{padding:10}},`empty-${d}`))]},c)):s.jsx("tr",{children:s.jsxs("td",{colSpan:t,style:{textAlign:"center",padding:40,color:"#6e7681",fontSize:13},children:['No models match your search "',n,'"']})})})})}),n.trim()&&i.length>0&&s.jsxs("div",{style:{textAlign:"right",fontSize:11,color:"#6e7681",marginTop:4},children:["Showing ",i.length," of ",r.length," models"]})]})}function pae(){return s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:"1px dashed #30363d",padding:"20px 24px",marginTop:24,textAlign:"center"},children:[s.jsx("div",{style:{fontSize:24,marginBottom:8},children:"🎙️"}),s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#e6edf3",marginBottom:4},children:"Speech / TTS Provider"}),s.jsxs("div",{style:{fontSize:12,color:"#6e7681"},children:["Speech/TTS provider support coming soon."," ",s.jsx("a",{href:"https://github.com/imdheerajKube/agent-nuvira/issues/new",target:"_blank",rel:"noopener noreferrer",style:{color:"#58a6ff",textDecoration:"none",cursor:"pointer"},onMouseEnter:e=>{e.currentTarget.style.textDecoration="underline"},onMouseLeave:e=>{e.currentTarget.style.textDecoration="none"},children:"Request a provider"})]})]})}function mae(){return s.jsxs("div",{style:{background:"#0d1117",borderRadius:10,padding:14,marginBottom:20,border:"1px solid #21262d",fontSize:13,color:"#8b949e",display:"flex",flexWrap:"wrap",gap:20},children:[s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600,color:"#e6edf3",marginBottom:6},children:"Color Coding"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[s.jsxs("span",{children:[s.jsx("span",{style:{color:"#3fb950"},children:"●"})," ",s.jsx("strong",{style:{color:"#e6edf3"},children:"Green"})," — Working with rate limit available"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#d29922"},children:"●"})," ",s.jsx("strong",{style:{color:"#e6edf3"},children:"Amber"})," — Slow / low rate limit / needs action"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#f85149"},children:"●"})," ",s.jsx("strong",{style:{color:"#e6edf3"},children:"Red"})," — API key missing / payment needed / unreachable"]})]})]}),s.jsxs("div",{children:[s.jsx("div",{style:{fontWeight:600,color:"#e6edf3",marginBottom:6},children:"Provider Sections"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3,fontSize:12},children:[s.jsxs("span",{children:["✅ ",s.jsx("strong",{children:"Cloud"})," — Online providers with active API keys"]}),s.jsxs("span",{children:["🏠 ",s.jsx("strong",{children:"Local"})," — Locally running inference servers"]}),s.jsxs("span",{children:["⛔ ",s.jsx("strong",{children:"Unavailable"})," — Missing keys or unreachable endpoints"]}),s.jsxs("span",{children:["🎙️ ",s.jsx("strong",{children:"Speech"})," — Text-to-speech / speech-to-text providers (coming)"]})]})]})]})}function gae(){const[e,t]=E.useState(null),[n,r]=E.useState(null),[i,a]=E.useState(!0),[o,l]=E.useState(null),[c,u]=E.useState(4),[d,f]=E.useState(""),h=E.useRef(!0),p=E.useRef(null),g=E.useRef(!1);function m(){p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{h.current&&v()},Bie)}async function v(){a(!0),l(null),g.current=!1;try{const[b,x]=await Promise.all([Fie(()=>{g.current=!0}),Uie(()=>{g.current=!0})]);if(!h.current)return;t(b),r(x),g.current&&m()}catch(b){if(!h.current)return;l(b instanceof Error&&b.message?b.message:"Failed to fetch model status"),g.current&&m()}finally{h.current&&a(!1)}}E.useEffect(()=>{h.current=!0,v();const b=setInterval(v,Die);return()=>{h.current=!1,clearInterval(b),p.current&&clearTimeout(p.current)}},[]);function y(b){const x=[],k=[],S=[],w=[],_={available:0,limited:1,unavailable:2};for(const N of b.providers)$ie.has(N.provider)?S.push(N):Iie.has(N.provider)?k.push(N):N.overallStatus==="available"?x.push(N):w.push(N);return x.sort((N,C)=>_[N.overallStatus]-_[C.overallStatus]),k.sort((N,C)=>_[N.overallStatus]-_[C.overallStatus]),S.sort((N,C)=>_[N.overallStatus]-_[C.overallStatus]),w.sort((N,C)=>_[N.overallStatus]-_[C.overallStatus]),{available:x,local:k,speech:S,unavailable:w}}return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"🧠 Model Provider Status"}),s.jsx("p",{className:"section-description",children:"Real-time health check of all AI providers and their available models. Providers are grouped into sections: Available cloud → Local → Unavailable."}),s.jsx(Gie,{onRefresh:v,loading:i}),s.jsx(mae,{}),i&&!e&&s.jsxs("div",{className:"loading-state",children:[s.jsx("div",{className:"loading-spinner"}),s.jsx("p",{children:"Testing all 17 provider connections..."})]}),o&&s.jsxs("div",{className:"empty-state",style:{color:"#f85149",border:"1px solid #f8514944",borderRadius:10,padding:16,marginBottom:16},children:["⚠️ ",o]}),e&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"stats-grid",style:{marginBottom:16},children:[s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"🧠"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",children:e.totalModels}),s.jsx("div",{className:"stat-label",children:"Total Models"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"✅"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#3fb950"},children:e.available}),s.jsx("div",{className:"stat-label",children:"Available"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"🟡"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#d29922"},children:e.limited}),s.jsx("div",{className:"stat-label",children:"Limited"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"🔴"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:"#f85149"},children:e.unavailable}),s.jsx("div",{className:"stat-label",children:"Unavailable"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"🔌"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",children:e.providers.length}),s.jsx("div",{className:"stat-label",children:"Providers"})]})]})]}),s.jsx(qie,{data:e}),(()=>{const{available:b,local:x,speech:k,unavailable:S}=y(e);return s.jsxs(s.Fragment,{children:[s.jsx(gd,{icon:"✅",title:"Available Cloud Providers",count:b.length}),b.map(w=>s.jsx(md,{provider:w},w.provider)),s.jsx(gd,{icon:"🏠",title:"Local Providers",count:x.length}),x.map(w=>s.jsx(md,{provider:w},w.provider)),s.jsx(gd,{icon:"⛔",title:"Unavailable Providers",count:S.length}),S.map(w=>s.jsx(md,{provider:w},w.provider)),s.jsx(gd,{icon:"🎙️",title:"Speech / TTS Providers",count:k.length}),k.map(w=>s.jsx(md,{provider:w},w.provider))]})})(),s.jsx(uae,{value:d,onChange:f,totalCount:e.providers.reduce((b,x)=>b+x.models.length,0)}),s.jsx(dae,{value:c,onChange:u}),s.jsx(hae,{providers:e.providers,colsPerRow:c,searchQuery:d}),n&&s.jsx(eae,{data:n}),n&&s.jsx(cae,{registry:n}),e&&!n&&s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:"1px dashed #30363d",padding:"14px 20px",marginTop:24,fontSize:12,color:"#8b949e",lineHeight:1.6},children:["📦 Registry & telemetry sections are hidden — this dashboard server did not return model-registry data (it may be an"," ",s.jsx("strong",{style:{color:"#e6edf3"},children:"older version"}),"). Restart the dashboard from the latest install to see them."]}),s.jsx(pae,{}),s.jsxs("div",{style:{textAlign:"center",fontSize:12,color:"#484f58",marginTop:16},children:["Last checked: ",new Date(e.lastChecked).toLocaleTimeString()," · ","Auto-refreshes every 60s"]})]})]})}const yae={local:"💻",groq:"🟢",nim:"🔶",gemini:"🔷",openrouter:"🟣"},vae={local:"Ollama (Local)",groq:"Groq",nim:"NVIDIA NIM",gemini:"Gemini",openrouter:"OpenRouter"},bae={trivial:"🟢",simple:"🔵",moderate:"🟡",complex:"🟠",critical:"🔴"},tM={trivial:"🟢 trivial",simple:"🔵 simple",moderate:"🟡 moderate",complex:"🟠 complex",critical:"🔴 critical"},xae={chat:"💬 chat",orchestrator:"🔀 orchestrator",explain:"🔍 explain",benchmark:"📈 benchmark",eval:"🎯 eval"},ka=[{key:"request",icon:"🎯",title:"Request"},{key:"candidates",icon:"⚖️",title:"Candidates"},{key:"exclusions",icon:"🚫",title:"Exclusions"},{key:"pick",icon:"✅",title:"Pick"}],wae=2400;function ng(e){return yae[e]||"🔌"}function c_(e){return vae[e]||e}function d0(e){return e&&xae[e]||e||"unknown"}function Sae(e){const t=Date.now()-e;return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`}function u_(e){const t=Math.ceil(e/6e4);return t>=60?`${Math.floor(t/60)}h ${t%60}m`:`${t}m`}const kae=8;function d_(e,t){const n=t.quota,r=n==null?void 0:n.entries.find(a=>a.provider===e);return r!=null&&r.parked?r.resetsInMs>0?`quota exhausted — auto re-enables in ${u_(r.resetsInMs)}`:"quota exhausted — parked":r&&r.cooldownRemaining>0?`circuit-breaker cooldown — ${u_(r.cooldownRemaining)} remaining`:t.providers.some(a=>a.provider===e)?"ranked below the candidate cutoff for this complexity":"not scored for this complexity (no benchmark quality data)"}function Eae(e){var a,o,l;const t=new Set;for(const c of e.providers)t.add(c.provider);if(e.usage)for(const c of Object.keys(e.usage.byProvider))t.add(c);if(e.bestModels)for(const c of e.bestModels)t.add(c.model.split("/")[0]);if(e.quota)for(const c of e.quota.entries)t.add(c.provider);const n=new Map(e.preference.map(c=>[c.complexity,c])),r=[],i=[...e.history??[]].sort((c,u)=>(u.timestamp??0)-(c.timestamp??0));for(const c of i.slice(0,kae)){const u=n.get(c.complexity),d=(a=u==null?void 0:u.providers)!=null&&a.length?u.providers.map(g=>({provider:g.provider,score:g.score,reason:g.reason})):[{provider:c.provider,score:c.score,reason:"actual pick recorded"}];d.some(g=>g.provider===c.provider)||d.push({provider:c.provider,score:c.score,reason:"actual pick recorded"});const f=new Set(d.map(g=>g.provider)),h=[...t].filter(g=>!f.has(g)).map(g=>({provider:g,reason:d_(g,e)})),p=(o=d.find(g=>g.provider===c.provider))==null?void 0:o.reason;r.push({id:c.id,label:`${d0(c.source)} · ${c.complexity} · ${(c.task||c.agentType).slice(0,26)}`,real:!0,complexity:c.complexity,task:c.task||c.agentType,agentType:c.agentType,source:c.source,timestamp:c.timestamp,winner:`${c.provider}/${c.model}`,winnerScore:c.score,winnerReason:p,candidates:d,exclusions:h})}if(r.length===0)for(const c of e.preference){const u=c.winner.split("/"),d=c.providers.map(g=>({provider:g.provider,score:g.score,reason:g.reason})),f=new Set(d.map(g=>g.provider)),h=[...t].filter(g=>!f.has(g)).map(g=>({provider:g,reason:d_(g,e)})),p=u[0];r.push({id:`profile-${c.complexity}`,label:`${tM[c.complexity]||c.complexity} — what the router would pick`,real:!1,complexity:c.complexity,task:p?`A ${c.complexity} task (auto-routed)`:`A ${c.complexity} task`,agentType:"chat",winner:c.winner,winnerScore:c.score,winnerReason:(l=d.find(g=>g.provider===p))==null?void 0:l.reason,candidates:d,exclusions:h})}return r}function _ae(e,t){switch(e){case"request":return`A ${t.complexity} task arrives${t.source?` from ${d0(t.source)}`:""} and must be routed.`;case"candidates":return`${t.candidates.length} provider${t.candidates.length!==1?"s":""} are scored against the ${t.complexity} weight profile.`;case"exclusions":return t.exclusions.length>0?`${t.exclusions.length} provider${t.exclusions.length!==1?"s":""} known to the system are skipped before scoring.`:"Every known provider was scored — nothing was skipped.";case"pick":return t.winnerReason?`The top score wins: ${t.winner.split("/")[0]} ranked first — ${t.winnerReason}.`:`The top score wins: ${t.winner}.`}}function Nae({value:e,color:t}){const n=Math.min(100,Math.max(0,e*100));return s.jsx("div",{style:{flex:1,background:"#0d1117",borderRadius:4,height:6,overflow:"hidden",border:"1px solid #21262d"},children:s.jsx("div",{style:{width:`${n}%`,background:t,height:"100%",transition:"width 0.4s ease"}})})}function jae({icon:e,title:t,narration:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:10,marginBottom:14},children:[s.jsx("span",{style:{fontSize:20,lineHeight:"24px"},children:e}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#e6edf3"},children:t}),s.jsx("div",{style:{fontSize:12,color:"#8b949e",marginTop:2},children:n})]})]})}function Aae({routing:e}){const t=E.useMemo(()=>Eae(e),[e]),[n,r]=E.useState(""),[i,a]=E.useState(0),[o,l]=E.useState(!1);if(E.useEffect(()=>{t.length!==0&&(t.some(p=>p.id===n)||(r(t[0].id),a(0)))},[t,n]),E.useEffect(()=>{if(!o||t.length===0)return;const p=setInterval(()=>{a(g=>(g+1)%ka.length)},wae);return()=>clearInterval(p)},[o,t.length]),t.length===0)return null;const c=t.find(p=>p.id===n)??t[0],u=ka[i],d=()=>{a(p=>(p+ka.length-1)%ka.length),l(!1)},f=()=>{a(p=>(p+1)%ka.length),l(!1)},h=()=>l(p=>!p);return s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:"1px solid #21262d",padding:"18px 20px",marginBottom:16},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:4},children:[s.jsx("span",{style:{fontSize:20},children:"🎬"}),s.jsx("h3",{style:{fontSize:15,fontWeight:600,color:"#e6edf3",margin:0},children:"Why did the router pick this?"}),c.real&&s.jsx("span",{style:{fontSize:11,padding:"1px 8px",borderRadius:10,background:"#12291a",border:"1px solid #238636",color:"#3fb950"},children:"✓ real decision"})]}),s.jsx("p",{style:{fontSize:12,color:"#8b949e",margin:"2px 0 12px 0"},children:"Narrated step-by-step replay of a routing decision — request, candidates, exclusions, and the pick. Scrubbable, or hit play."}),s.jsx("select",{"aria-label":"Routing decision to replay",value:n,onChange:p=>{r(p.target.value),a(0),l(!1)},style:{width:"100%",marginBottom:16,padding:"8px 10px",background:"#0d1117",color:"#e6edf3",fontSize:12,border:"1px solid #30363d",borderRadius:8,outline:"none"},children:t.map(p=>s.jsxs("option",{value:p.id,style:{background:"#0d1117",color:"#e6edf3"},children:[p.real?"● ":"○ ",p.label]},p.id))}),s.jsx(jae,{icon:u.icon,title:`${i+1}. ${u.title}${i>0?` — ${c.complexity}`:""}`,narration:_ae(u.key,c)}),u.key==="request"&&s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"14px 16px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",marginBottom:8},children:[s.jsxs("span",{style:{fontSize:12,padding:"2px 10px",borderRadius:12,background:"#161b22",border:"1px solid #30363d",color:"#e6edf3"},children:[bae[c.complexity]||"•"," ",tM[c.complexity]||c.complexity]}),s.jsxs("span",{style:{fontSize:12,padding:"2px 10px",borderRadius:12,background:"#161b22",border:"1px solid #30363d",color:"#8b949e"},children:["🤖 ",c.agentType]}),c.source&&s.jsx("span",{style:{fontSize:12,padding:"2px 10px",borderRadius:12,background:"#161b22",border:"1px solid #30363d",color:"#8b949e"},children:d0(c.source)}),c.timestamp&&s.jsx("span",{style:{fontSize:11,color:"#6e7681",marginLeft:"auto"},children:Sae(c.timestamp)})]}),s.jsx("div",{style:{fontSize:13,color:"#e6edf3"},children:c.task})]}),u.key==="candidates"&&s.jsxs("div",{children:[c.candidates.map((p,g)=>{const m=p.provider===c.winner.split("/")[0];return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",background:m?"#12291a":"#0d1117",border:`1px solid ${m?"#238636":"#21262d"}`,borderRadius:8,marginBottom:6},children:[s.jsxs("span",{style:{width:18,fontSize:11,color:"#6e7681",textAlign:"right"},children:[g+1,"."]}),s.jsxs("span",{style:{width:104,color:m?"#3fb950":"#e6edf3",fontWeight:m?600:400,whiteSpace:"nowrap",fontSize:12},children:[ng(p.provider)," ",c_(p.provider).split(" ")[0],m&&" 👑"]}),s.jsx(Nae,{value:p.score,color:m?"#3fb950":"#58a6ff"}),s.jsx("span",{style:{width:44,textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:11,color:"#8b949e"},children:p.score.toFixed(3)})]},p.provider)}),c.candidates.length>0&&s.jsxs("div",{style:{marginTop:10},children:[s.jsx("div",{style:{fontSize:11,color:"#6e7681",marginBottom:4},children:"Why each ranked where it did"}),c.candidates.map(p=>s.jsxs("div",{style:{fontSize:12,color:"#8b949e",marginBottom:3},children:[s.jsx("span",{style:{color:"#e6edf3"},children:p.provider}),": ",p.reason||"scored"]},p.provider))]})]}),u.key==="exclusions"&&(c.exclusions.length>0?s.jsx("div",{children:c.exclusions.map(p=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"8px 12px",background:"#0d1117",border:"1px solid #21262d",borderRadius:8,marginBottom:6},children:[s.jsx("span",{style:{fontSize:13},children:"🚫"}),s.jsxs("span",{style:{width:110,color:"#e6edf3",whiteSpace:"nowrap",fontSize:12},children:[ng(p.provider)," ",c_(p.provider).split(" ")[0]]}),s.jsx("span",{style:{flex:1,fontSize:12,color:"#8b949e"},children:p.reason})]},p.provider))}):s.jsx("div",{style:{background:"#0d1117",border:"1px dashed #30363d",borderRadius:10,padding:"14px 16px",color:"#8b949e",fontSize:13},children:"✅ No exclusions — every provider known to the system was scored for this decision."})),u.key==="pick"&&s.jsxs("div",{style:{background:"#12291a",border:"1px solid #238636",borderRadius:10,padding:"16px 18px"},children:[s.jsx("div",{style:{fontSize:12,color:"#3fb950",fontWeight:600,marginBottom:6},children:"🏆 ROUTER PICK"}),s.jsxs("div",{style:{fontSize:16,fontWeight:700,color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace",marginBottom:4},children:[ng(c.winner.split("/")[0])," ",c.winner]}),s.jsxs("div",{style:{fontSize:12,color:"#8b949e",marginBottom:10},children:["composite score ",s.jsx("span",{style:{fontFamily:"'SFMono-Regular', Consolas, monospace",color:"#3fb950"},children:c.winnerScore.toFixed(3)}),!c.real&&" · profile preview"]}),c.winnerReason&&s.jsxs("div",{style:{fontSize:12,color:"#8b949e",borderTop:"1px solid #23863655",paddingTop:8},children:[s.jsx("span",{style:{color:"#e6edf3"},children:"Why:"})," ",c.winnerReason]})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginTop:16},children:[s.jsx("button",{onClick:d,"aria-label":"Previous step",style:rg,children:"◀"}),s.jsx("button",{onClick:h,"aria-label":o?"Pause playback":"Play playback",style:{...rg,minWidth:84,color:o?"#d29922":"#3fb950"},children:o?"⏸ Pause":"▶ Play"}),s.jsx("button",{onClick:f,"aria-label":"Next step",style:rg,children:"▶"}),s.jsx("div",{style:{display:"flex",gap:6,marginLeft:8},children:ka.map((p,g)=>s.jsx("button",{"aria-label":`Go to step ${g+1}: ${p.title}`,onClick:()=>{a(g),l(!1)},style:{width:22,height:22,borderRadius:11,border:"none",cursor:"pointer",fontSize:10,lineHeight:"22px",padding:0,background:g===i?"#58a6ff":"#21262d",color:g===i?"#0d1117":"#8b949e"},title:p.title,children:p.icon},p.key))}),s.jsxs("span",{style:{marginLeft:"auto",fontSize:11,color:"#6e7681"},children:["step ",i+1,"/",ka.length]})]})]})}const rg={background:"#21262d",color:"#e6edf3",border:"1px solid #30363d",borderRadius:8,padding:"6px 12px",fontSize:13,cursor:"pointer",transition:"background 0.15s"},Tae={local:"💻",groq:"🟢",nim:"🔶",gemini:"🔷",openrouter:"🟣"},Cae={local:"Ollama (Local)",groq:"Groq",nim:"NVIDIA NIM",gemini:"Gemini",openrouter:"OpenRouter"},nM={trivial:"🟢",simple:"🔵",moderate:"🟡",complex:"🟠",critical:"🔴"};function Nr(e){return Tae[e]||"🔌"}function sa(e){return Cae[e]||e}function yh(e,t=1){return`${(e*100).toFixed(t)}%`}function Oae(e){return`$${e.toFixed(6)}`}function Yn({icon:e,title:t,subtitle:n,children:r}){return s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:"1px solid #21262d",padding:"18px 20px",marginBottom:16},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:4},children:[s.jsx("span",{style:{fontSize:20},children:e}),s.jsx("h3",{style:{fontSize:15,fontWeight:600,color:"#e6edf3",margin:0},children:t})]}),n&&s.jsx("p",{style:{fontSize:12,color:"#8b949e",margin:"2px 0 12px 0"},children:n}),!n&&s.jsx("div",{style:{height:6}}),r]})}function f0({value:e,color:t}){const n=Math.min(100,Math.max(0,e*100));return s.jsx("div",{style:{flex:1,background:"#0d1117",borderRadius:4,height:6,overflow:"hidden",border:"1px solid #21262d"},children:s.jsx("div",{style:{width:`${n}%`,background:t,height:"100%",transition:"width 0.4s ease"}})})}function eo(e,t,n="#8b949e"){return{fontSize:10,padding:"1px 7px",borderRadius:9,background:e,border:`1px solid ${t}`,color:n,fontFamily:"'SFMono-Regular', Consolas, monospace",whiteSpace:"nowrap"}}function Pae(){return s.jsxs("div",{style:{background:"#0d1117",border:"1px dashed #30363d",borderRadius:10,padding:"18px 20px",color:"#8b949e",fontSize:13,textAlign:"center"},children:["📊 No routing data yet — run ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff benchmark"})," to populate provider quality scores, or use Auto routing (",s.jsx("code",{style:{color:"#58a6ff"},children:"buff model switch auto"}),") to build per-agent best-model stats over time."]})}const Mae={chat:"💬 chat",orchestrator:"🔀 orchestrator",explain:"🔍 explain",benchmark:"📈 benchmark",eval:"🎯 eval"},Rae={trivial:"🟢 trivial",simple:"🔵 simple",moderate:"🟡 moderate",complex:"🟠 complex",critical:"🔴 critical"};function rM(e){return Mae[e]||e}function iM(e){const t=Date.now()-e;return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`}function f_(e){if(e<=0)return"now";const t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4);return t>0?`${t}h ${n}m`:n>0?`${n}m`:`${Math.ceil(e/1e3)}s`}function Iae({label:e,value:t,total:n,color:r}){const i=n>0?t/n*100:0;return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:5},children:[s.jsx("span",{style:{width:110,color:"#e6edf3",whiteSpace:"nowrap",fontSize:12},children:e}),s.jsx("div",{style:{flex:1,background:"#0d1117",borderRadius:4,height:6,overflow:"hidden",border:"1px solid #21262d"},children:s.jsx("div",{style:{width:`${Math.min(100,i)}%`,background:r,height:"100%",transition:"width 0.4s ease"}})}),s.jsx("span",{style:{width:34,textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:11,color:"#8b949e"},children:t})]})}function $ae({usage:e}){if(!e.total)return null;const t=e.total,n=Object.entries(e.byProvider).sort((i,a)=>a[1]-i[1]).slice(0,6),r=Object.entries(e.byModel).sort((i,a)=>a[1]-i[1]).slice(0,5);return s.jsxs(Yn,{icon:"🧮",title:"Routing Usage — actual picks over time",subtitle:"Recorded from live chat, orchestrator runs, explain snapshots, benchmark --routing, and eval --routing",children:[s.jsxs("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginBottom:14},children:[s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:e.total}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"total decisions"})]}),s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:e.last24h>0?"#3fb950":"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:e.last24h}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"last 24h"})]})]}),s.jsx("div",{style:{fontSize:12,color:"#8b949e",marginBottom:6},children:"By provider"}),n.map(([i,a])=>s.jsx(Iae,{label:`${Nr(i)} ${sa(i).split(" ")[0]}`,value:a,total:t,color:"#58a6ff"},i)),Object.keys(e.bySource).length>0&&s.jsx("div",{style:{marginTop:12,display:"flex",gap:6,flexWrap:"wrap"},children:Object.entries(e.bySource).sort((i,a)=>a[1]-i[1]).map(([i,a])=>s.jsxs("span",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:20,padding:"3px 10px",fontSize:11,color:"#e6edf3"},children:[rM(i)," · ",a]},i))}),r.length>0&&s.jsxs("div",{style:{marginTop:14},children:[s.jsx("div",{style:{fontSize:12,color:"#8b949e",marginBottom:6},children:"Most-picked models"}),r.map(([i,a])=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:5},children:[s.jsx("span",{style:{flex:1,color:"#e6edf3",fontSize:12,fontFamily:"'SFMono-Regular', Consolas, monospace",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},title:i,children:i.length>42?i.slice(0,39)+"…":i}),s.jsx("span",{style:{width:34,textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:11,color:"#8b949e"},children:a})]},i))]})]})}function Lae({history:e}){return e.length?s.jsx(Yn,{icon:"🕓",title:"Audit Trail — routing decision timeline",subtitle:"Every explain snapshot (and routing-mode pick) persisted for transparency",children:s.jsx("div",{style:{maxHeight:320,overflowY:"auto",paddingRight:4},children:e.map(t=>s.jsxs("div",{style:{display:"flex",gap:10,padding:"8px 4px",borderBottom:"1px solid #21262d"},children:[s.jsx("div",{style:{width:52,flexShrink:0,fontSize:11,color:"#6e7681",paddingTop:2},children:iM(t.timestamp)}),s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[s.jsx("span",{style:{fontSize:11,padding:"1px 8px",borderRadius:10,background:"#0d1117",border:"1px solid #30363d",color:"#8b949e"},children:rM(t.source)}),s.jsxs("span",{style:{fontSize:12,fontWeight:600,color:"#3fb950",fontFamily:"'SFMono-Regular', Consolas, monospace",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},title:`${t.provider}/${t.model}`,children:[Nr(t.provider)," ",t.provider,"/",t.model.length>26?t.model.slice(0,23)+"…":t.model]}),t.complexity&&s.jsx("span",{style:{fontSize:11,color:"#6e7681"},children:Rae[t.complexity]||t.complexity})]}),s.jsx("div",{style:{fontSize:12,color:"#8b949e",marginTop:3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:t.task,children:t.task||t.agentType})]})]},t.id))})}):null}function Dae({routing:e}){return e.preference.length?s.jsx(Yn,{icon:"🤖",title:"Auto Router — What the agent would pick",subtitle:"Complexity-weighted scoring across reasoning, speed, cost, privacy, and reliability (real provider pricing)",children:s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid #21262d",color:"#8b949e"},children:[s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Complexity"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Winner"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Score"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"All providers"})]})}),s.jsx("tbody",{children:e.preference.map(t=>s.jsxs("tr",{style:{borderBottom:"1px solid #21262d"},children:[s.jsxs("td",{style:{padding:"10px 12px",color:"#e6edf3",whiteSpace:"nowrap"},children:[nM[t.complexity]||"•"," ",t.complexity]}),s.jsx("td",{style:{padding:"10px 12px",whiteSpace:"nowrap"},children:s.jsxs("span",{style:{color:"#3fb950",fontWeight:600},children:[Nr(t.winner.split("/")[0])," ",t.winner]})}),s.jsx("td",{style:{padding:"10px 12px",fontFamily:"'SFMono-Regular', Consolas, monospace",color:"#8b949e"},children:t.score.toFixed(3)}),s.jsx("td",{style:{padding:"10px 12px",minWidth:300},children:t.providers.map((n,r)=>s.jsxs("div",{style:{marginBottom:5},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsxs("span",{style:{width:16,fontSize:11,color:"#6e7681",textAlign:"right"},children:[r+1,"."]}),s.jsxs("span",{style:{width:90,color:"#e6edf3",whiteSpace:"nowrap",fontSize:12},children:[Nr(n.provider)," ",sa(n.provider).split(" ")[0]]}),s.jsx(f0,{value:n.score,color:r===0?"#3fb950":"#58a6ff"}),s.jsx("span",{style:{width:40,textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:11,color:"#8b949e"},children:n.score.toFixed(2)})]}),(n.capabilityFit!==void 0||n.costSource||n.contextUtilization!==void 0)&&s.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",paddingLeft:16,marginTop:2},children:[n.capabilityFit!==void 0&&s.jsxs("span",{style:eo("#1c2128","#6e7681"),children:["🎯 fit ",n.capabilityFit,"%"]}),n.costSource==="measured"&&n.costBasis?s.jsxs("span",{style:eo("#12291a","#3fb950","#3fb950"),children:["📏 measured ",n.costBasis.inputTokens.toLocaleString(),"→",n.costBasis.outputTokens.toLocaleString()," tok"]}):s.jsx("span",{style:eo("#1c2128","#8b949e"),children:"📐 estimated"}),n.contextUtilization!==void 0&&n.contextWindowTokens!==void 0&&s.jsxs("span",{style:eo("#1c2128","#58a6ff","#58a6ff"),children:["⏳ ctx ",n.contextUtilization,"% (",n.contextWindowTokens.toLocaleString()," tok)"]})]})]},n.provider))})]},t.complexity))})]})})}):null}function Bae({routing:e}){return e.providers.length?s.jsx(Yn,{icon:"📈",title:"Provider Benchmark Quality",subtitle:"Measured from your own `buff benchmark` runs — blended into Auto routing decisions",children:s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid #21262d",color:"#8b949e"},children:[s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Provider"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Runs"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Avg Quality"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Pass Rate"}),s.jsx("th",{style:{padding:"8px 12px",textAlign:"left",fontWeight:500},children:"Total Cost"})]})}),s.jsx("tbody",{children:e.providers.map(t=>s.jsxs("tr",{style:{borderBottom:"1px solid #21262d"},children:[s.jsxs("td",{style:{padding:"10px 12px",color:"#e6edf3",whiteSpace:"nowrap"},children:[Nr(t.provider)," ",sa(t.provider)]}),s.jsx("td",{style:{padding:"10px 12px",color:"#8b949e"},children:t.runs}),s.jsx("td",{style:{padding:"10px 12px"},children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx(f0,{value:t.avgQuality,color:"#58a6ff"}),s.jsx("span",{style:{fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12,color:"#8b949e",width:44,textAlign:"right"},children:yh(t.avgQuality)})]})}),s.jsx("td",{style:{padding:"10px 12px",color:t.passRate>=.8?"#3fb950":"#d29922"},children:yh(t.passRate)}),s.jsx("td",{style:{padding:"10px 12px",fontFamily:"'SFMono-Regular', Consolas, monospace",color:"#8b949e"},children:Oae(t.totalCostUsd)})]},t.provider))})]})})}):null}const h_=["trivial","simple","moderate","complex","critical"];function zae(e){return e>=.7?"#3fb950":e>=.45?"#d29922":"#f85149"}function Fae({bandit:e}){const t=Object.keys(e.priors).sort();if(!e.enabled||t.length===0)return null;const n=e.learningHistory.slice(-15).reverse();return s.jsxs(Yn,{icon:"🎰",title:"Bandit Learning — Thompson-sampling priors",subtitle:"Beta(α, β) per provider × complexity bucket, learned from real task outcomes (routing.bandit = true). Higher expected win rate = more successful history.",children:[s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:12},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid #21262d",color:"#8b949e"},children:[s.jsx("th",{style:{padding:"8px 10px",textAlign:"left",fontWeight:500},children:"Provider"}),h_.map(r=>s.jsxs("th",{style:{padding:"8px 10px",textAlign:"center",fontWeight:500},children:[nM[r]||"•"," ",r]},r))]})}),s.jsx("tbody",{children:t.map(r=>s.jsxs("tr",{style:{borderBottom:"1px solid #21262d"},children:[s.jsxs("td",{style:{padding:"8px 10px",color:"#e6edf3",whiteSpace:"nowrap"},children:[Nr(r)," ",sa(r).split(" ")[0]]}),h_.map(i=>{var o;const a=(o=e.priors[r])==null?void 0:o[i];return!a||a.alpha===0&&a.beta===0?s.jsx("td",{style:{padding:"8px 10px",textAlign:"center",color:"#6e7681"},children:"·"},i):s.jsxs("td",{style:{padding:"8px 10px",textAlign:"center"},children:[s.jsxs("div",{style:{fontSize:13,fontWeight:600,color:zae(a.expectedWinRate),fontFamily:"'SFMono-Regular', Consolas, monospace"},children:[(a.expectedWinRate*100).toFixed(0),"%"]}),s.jsxs("div",{style:{fontSize:10,color:"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:["α",a.alpha," β",a.beta]})]},i)})]},r))})]})}),n.length>0&&s.jsxs("div",{style:{marginTop:16},children:[s.jsx("div",{style:{fontSize:12,color:"#8b949e",marginBottom:8},children:"Recent learning history"}),s.jsx("div",{style:{maxHeight:180,overflowY:"auto",paddingRight:4},children:n.map((r,i)=>{const a=r.outcome==="success"?"✅":r.outcome==="escalated"?"🔄":"❌",o=new Date(r.timestamp).toLocaleTimeString();return s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",padding:"5px 4px",borderBottom:"1px solid #21262d"},children:[s.jsx("span",{children:a}),s.jsx("span",{style:{color:"#e6edf3",fontSize:12,width:110,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},title:r.provider,children:r.provider}),s.jsx("span",{style:{fontSize:11,color:"#6e7681",width:80},children:r.complexity}),s.jsxs("span",{style:{fontSize:11,color:"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:["reward ",r.reward.toFixed(2)]}),s.jsx("span",{style:{fontSize:11,color:"#6e7681",marginLeft:"auto"},children:o})]},i)})})]}),s.jsxs("div",{style:{fontSize:11,color:"#6e7681",marginTop:12},children:["Cold-start Beta(1,1) behaves like the heuristic router until outcomes accumulate. Enable learning with ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff config set routing.bandit true"}),"."]})]})}function Uae(e,t=1){return`${e>0?"+":""}${(e*100).toFixed(t)}%`}function Wae({state:e}){const t={pass:{bg:"#12291a",border:"#238636",color:"#3fb950",label:"✓ pass"},fail:{bg:"#2d1616",border:"#f85149",color:"#f85149",label:"✗ fail"},neutral:{bg:"#1c2128",border:"#6e7681",color:"#8b949e",label:"○ neutral"}}[e];return s.jsx("span",{style:{fontSize:11,padding:"1px 8px",borderRadius:10,background:t.bg,border:`1px solid ${t.border}`,color:t.color},children:t.label})}function Hae({promotion:e}){if(!e.decisionCount)return null;const t=e.promoted?{icon:"🎖️",label:"Promoted — the bandit beats the heuristic",color:"#3fb950"}:e.sufficient?{icon:"⚠️",label:"Not promoted — the bandit is not (yet) better",color:"#d29922"}:{icon:"⏳",label:"Collecting data — need more diverged decisions",color:"#58a6ff"},n=e.minDecisions>0?Math.min(100,Math.round(e.divergedCount/e.minDecisions*100)):0,r=[{key:"quality",label:"Quality ↑",delta:e.qualityDelta,state:e.criteria.quality?"pass":"fail",note:"needs > +2%"},{key:"cost",label:"Cost ↓",delta:e.costDelta,state:e.criteria.cost?"pass":"fail",note:"regression < +1%"},{key:"latency",label:"Latency ↓",delta:e.latencyDelta,state:e.latencyMeasured?e.criteria.latency?"pass":"fail":"neutral",note:e.latencyMeasured?"regression < +5%":"no latency measurements yet"}];return s.jsxs(Yn,{icon:"🎖️",title:"Promotion Gate — is the bandit better than the heuristic?",subtitle:"A/B verdict from real trajectories (router-promotion.jsonl): quality must improve >2% while cost and latency don't regress (ruflo ADR-150)",children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:14},children:[s.jsx("span",{style:{fontSize:22},children:t.icon}),s.jsx("span",{style:{fontSize:14,fontWeight:600,color:t.color},children:t.label})]}),s.jsxs("div",{style:{marginBottom:14},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:11,color:"#8b949e",marginBottom:5},children:[s.jsxs("span",{children:[e.divergedCount," diverged decisions"]}),s.jsxs("span",{children:["need ",e.minDecisions," for a verdict"]})]}),s.jsx("div",{style:{background:"#0d1117",borderRadius:4,height:8,overflow:"hidden",border:"1px solid #21262d"},children:s.jsx("div",{style:{width:`${n}%`,background:e.sufficient?"#3fb950":"#58a6ff",height:"100%",transition:"width 0.4s ease"}})}),s.jsxs("div",{style:{fontSize:11,color:"#6e7681",marginTop:4},children:[e.decisionCount," total decisions logged"]})]}),r.map(i=>s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"7px 0",borderBottom:"1px solid #21262d"},children:[s.jsx("span",{style:{width:70,fontSize:12,color:"#e6edf3"},children:i.label}),s.jsx("span",{style:{width:92,fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12,color:"#8b949e"},children:Uae(i.delta)}),s.jsx("span",{style:{fontSize:11,color:"#6e7681",flex:1},children:i.note}),s.jsx(Wae,{state:i.state})]},i.key)),s.jsxs("div",{style:{fontSize:11,color:"#6e7681",marginTop:12},children:["Run auto-routed tasks with ",s.jsx("code",{style:{color:"#58a6ff"},children:"routing.bandit true"})," to accumulate A/B decisions. The gate does not disable the bandit — it tells you whether it's actually winning."]})]})}function Gae({ml:e}){if(!e.enabled||e.recordCount===0)return null;const t=e.providers.filter(r=>r.trusted),n=e.providers.filter(r=>!r.trusted);return s.jsxs(Yn,{icon:"🧠",title:"ML Router — learned from similar tasks",subtitle:"Task-feature kNN (ruflo neural-router analog): outcomes of the most similar PAST tasks nudge each provider's score. Win rate is similarity-weighted; factor = 1 + 0.5 × (winRate − 0.5), trusted only after 5 similar-task samples.",children:[s.jsxs("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginBottom:14},children:[s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:e.recordCount.toLocaleString()}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"learned tasks"})]}),s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #238636",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:"#3fb950",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:t.length}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"trusted providers"})]}),s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #d29922",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:"#d29922",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:n.length}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"still learning"})]})]}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:e.providers.map(r=>s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"10px 14px"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:6},children:[s.jsx("span",{children:Nr(r.provider)}),s.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#e6edf3"},children:sa(r.provider)}),r.trusted?s.jsxs("span",{style:eo("#3fb95026","#238636","#3fb950"),children:["trusted · ",r.samples," samples"]}):s.jsxs("span",{style:eo("#d2992226","#9e6a03","#d29922"),children:[r.samples,"/5 samples"]}),r.model&&s.jsx("span",{style:{fontSize:11,color:"#6e7681",fontFamily:"'SFMono-Regular', Consolas, monospace",marginLeft:"auto"},children:r.model.length>30?r.model.slice(0,27)+"…":r.model})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[s.jsxs("div",{style:{width:70,fontSize:11,color:"#8b949e"},children:["win ",yh(r.winRate,0)]}),s.jsx(f0,{value:r.winRate,color:r.winRate>=.5?"#3fb950":"#f85149"}),s.jsxs("div",{style:{width:74,fontSize:11,color:"#8b949e",textAlign:"right"},children:["factor ",s.jsxs("span",{style:{color:r.trusted&&r.factor!==1?"#58a6ff":"#6e7681",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:[r.factor.toFixed(2),"×"]})]})]})]},r.provider))}),s.jsxs("div",{style:{fontSize:11,color:"#6e7681",marginTop:12},children:["Enabled with ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff config set routing.mlRouter true"})," — the factor only adjusts scores when the provider has ≥ 5 similar-task wins (cold start is neutral)."]})]})}function qae({routing:e}){return e.bestModels.length?s.jsx(Yn,{icon:"🏆",title:"Best Model per Agent (from your runs)",subtitle:"Success-rate-ranked models from agent-stats — the Auto router boosts the proven winner",children:s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:10},children:e.bestModels.map(t=>s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 14px",minWidth:200,flex:"1 1 200px",transition:"border-color 0.2s, box-shadow 0.2s"},onMouseEnter:n=>{n.currentTarget.style.borderColor="#3fb950",n.currentTarget.style.boxShadow="0 2px 10px #3fb95022"},onMouseLeave:n=>{n.currentTarget.style.borderColor="#21262d",n.currentTarget.style.boxShadow="none"},children:[s.jsxs("div",{style:{fontSize:12,color:"#8b949e",marginBottom:4},children:[Nr(t.model.split("/")[0])," ",t.agentType]}),s.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},title:t.model,children:t.model.length>34?t.model.slice(0,31)+"…":t.model}),s.jsxs("div",{style:{fontSize:11,color:"#6e7681",marginTop:6},children:[s.jsxs("span",{style:{color:t.successRate>=.8?"#3fb950":"#d29922"},children:[yh(t.successRate,0)," success"]})," · ",t.runs," run",t.runs!==1?"s":""]})]},`${t.agentType}-${t.model}`))})}):null}function Kae({retrieval:e}){var l,c;if(!e.enabled&&e.repoChunks===0)return null;const t=e.totalSavedTokens??0,n=e.avgPctReduced??0,r=e.lastCall,i=e.totalCalls??0,a=e.totalRetrievals??0,o=e.totalFailovers??0;return s.jsxs(Yn,{icon:"🧠",title:"Vector Retrieval — token savings",subtitle:"Large contexts are chunked, embedded locally (bge-small-en-v1.5), and reduced to the top-k relevant chunks before the LLM — saving tokens so free quotas stretch further. Complements the quota ledger: retrieval saves, the ledger manages.",children:[s.jsxs("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginBottom:14},children:[s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #238636",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:"#3fb950",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:t.toLocaleString()}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"tokens saved"})]}),s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsxs("div",{style:{fontSize:22,fontWeight:700,color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:[n.toFixed(1),"%"]}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"avg context reduction"})]}),s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #d29922",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:"#d29922",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:e.repoChunks.toLocaleString()}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"repo chunks indexed"})]})]}),s.jsxs("div",{style:{display:"flex",gap:20,flexWrap:"wrap",fontSize:12,color:"#8b949e",marginBottom:14},children:[s.jsxs("span",{children:["📞 ",i," context calls · 🧠 ",a," retrievals used · ⚠️ ",o," failovers (full-context fallback)"]}),e.dimensions>0&&s.jsxs("span",{children:["· ",e.dimensions,"-dim embeddings"]})]}),r&&r.used!==!1&&((l=r.hits)==null?void 0:l.length)>0&&s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 16px",marginBottom:12},children:[s.jsxs("div",{style:{fontSize:12,fontWeight:600,color:"#e6edf3",marginBottom:8},children:["Latest retrieval — ",r.originalTokens.toLocaleString()," → ",r.reducedTokens.toLocaleString()," tokens",s.jsxs("span",{style:{color:"#3fb950",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:[" (−",(c=r.pctReduced)==null?void 0:c.toFixed(0),"%)"]})]}),s.jsx("div",{style:{fontSize:11,color:"#8b949e"},children:r.hits.slice(0,5).map(u=>s.jsxs("div",{style:{marginTop:3},children:[s.jsx("span",{style:{color:"#58a6ff"},children:"▸"})," ",u.filePath," ",s.jsxs("span",{style:{fontFamily:"'SFMono-Regular', Consolas, monospace"},children:["(sim ",u.similarity.toFixed(3),")"]})]},u.filePath))})]}),s.jsxs("div",{style:{fontSize:11,color:"#6e7681"},children:["Pre-index your repo with ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff retrieval index <dir>"}),", query it with"," ",s.jsx("code",{style:{color:"#58a6ff"},children:'buff retrieval query "<question>"'}),", and see the same stats with"," ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff retrieval stats"}),"."]})]})}function Vae({quota:e}){var c;if((!e.enabled||e.entries.length===0)&&(((c=e.events)==null?void 0:c.length)??0)===0)return null;const t=e.entries.reduce((u,d)=>u+d.tokensConsumed,0),n=e.entries.reduce((u,d)=>u+d.requests,0),r=e.entries.filter(u=>u.parked).length,i=e.freeTokens??t-(e.paidTokens??0),a=e.paidTokens??0,o=e.estimatedSavedUsd??0,l=t>0?i/t*100:0;return s.jsxs(Yn,{icon:"📒",title:"Quota Ledger — free-tier usage & auto re-enable",subtitle:"Tokens/requests per provider × model with reset windows. Exhausted providers are parked (excluded from Auto routing) and re-enable when the window rolls.",children:[s.jsxs("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginBottom:14},children:[s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:t.toLocaleString()}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"tokens tracked"})]}),s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:"#e6edf3",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:n}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"requests"})]}),s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 18px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700,color:r>0?"#d29922":"#3fb950",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:r}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"parked"})]})]}),s.jsxs("div",{style:{display:"flex",gap:20,flexWrap:"wrap",marginBottom:16},children:[s.jsxs("div",{style:{flex:"1 1 200px",background:"#0d1117",borderRadius:10,padding:"12px 16px",border:"1px solid #238636"},children:[s.jsx("div",{style:{fontSize:20,fontWeight:700,color:"#3fb950",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:i.toLocaleString()}),s.jsxs("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:["tokens on free/local · ",l.toFixed(0),"% of usage"]}),s.jsxs("div",{style:{fontSize:12,color:"#3fb950",marginTop:4,fontFamily:"'SFMono-Regular', Consolas, monospace"},children:["💰 est. $",o.toFixed(4)," saved"]})]}),s.jsxs("div",{style:{flex:"1 1 200px",background:"#0d1117",borderRadius:10,padding:"12px 16px",border:"1px solid #d29922"},children:[s.jsx("div",{style:{fontSize:20,fontWeight:700,color:a>0?"#d29922":"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:a.toLocaleString()}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginTop:2},children:"tokens on paid providers (spend triggered)"}),s.jsxs("div",{style:{fontSize:12,color:a>0?"#d29922":"#8b949e",marginTop:4},children:[e.paidRequests??0," paid request",e.paidRequests===1?"":"s"]})]})]}),s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:12},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid #21262d",color:"#8b949e"},children:[s.jsx("th",{style:{padding:"8px 10px",textAlign:"left",fontWeight:500},children:"Provider / Model"}),s.jsx("th",{style:{padding:"8px 10px",textAlign:"right",fontWeight:500},children:"Tokens"}),s.jsx("th",{style:{padding:"8px 10px",textAlign:"right",fontWeight:500},children:"Requests"}),s.jsx("th",{style:{padding:"8px 10px",textAlign:"right",fontWeight:500},children:"Resets in"}),s.jsx("th",{style:{padding:"8px 10px",textAlign:"center",fontWeight:500},children:"State"})]})}),s.jsx("tbody",{children:e.entries.map(u=>s.jsxs("tr",{style:{borderBottom:"1px solid #21262d"},children:[s.jsxs("td",{style:{padding:"8px 10px",whiteSpace:"nowrap"},children:[s.jsxs("span",{style:{color:"#e6edf3"},children:[Nr(u.provider)," ",sa(u.provider).split(" ")[0]]}),s.jsxs("span",{style:{color:"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:[" / ",u.model.length>24?u.model.slice(0,21)+"…":u.model]})]}),s.jsx("td",{style:{padding:"8px 10px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",color:"#8b949e"},children:u.tokensConsumed.toLocaleString()}),s.jsx("td",{style:{padding:"8px 10px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",color:"#8b949e"},children:u.requests}),s.jsx("td",{style:{padding:"8px 10px",textAlign:"right",color:"#8b949e",whiteSpace:"nowrap"},children:f_(u.resetsInMs)}),s.jsx("td",{style:{padding:"8px 10px",textAlign:"center"},children:u.parked?s.jsx("span",{style:{fontSize:11,padding:"1px 8px",borderRadius:10,background:"#2d1616",border:"1px solid #f85149",color:"#f85149"},children:"⏸ parked"}):s.jsx("span",{style:{fontSize:11,padding:"1px 8px",borderRadius:10,background:"#12291a",border:"1px solid #238636",color:"#3fb950"},children:"✓ available"})})]},`${u.provider}|${u.model}`))})]})}),s.jsxs("div",{style:{fontSize:11,color:"#6e7681",marginTop:12},children:["Configure limits with ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff config set routing.quota.gemini.requestsPerWindow 1500"}),"; the ledger always tracks usage but only parks when limits are set."]}),e.parkedAccounts&&e.parkedAccounts.length>0&&s.jsxs("div",{style:{marginTop:18},children:[s.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e6edf3",marginBottom:10},children:"🔑 Parked Accounts — multi-account key rotation"}),s.jsx("div",{style:{fontSize:11,color:"#8b949e",marginBottom:8},children:"Accounts skipped predictively by the failover walk (rate-limit / auth). Fingerprints only — raw keys are never stored."}),s.jsx("div",{style:{maxHeight:180,overflowY:"auto",background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"8px 0"},children:e.parkedAccounts.map((u,d)=>{const f=u.reason==="auth"?"auth":u.reason==="rate-limit"?"rate-limit":u.reason||"cooldown",h=u.reason==="rate-limit"?"#d29922":"#f85149";return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 14px",borderBottom:d<e.parkedAccounts.length-1?"1px solid #161b22":"none"},children:[s.jsx("span",{style:{fontSize:13},children:"🔒"}),s.jsxs("span",{style:{width:90,flexShrink:0,fontSize:12,color:"#e6edf3"},children:[Nr(u.provider)," ",sa(u.provider).split(" ")[0]]}),s.jsxs("span",{style:{fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:11,color:"#8b949e"},title:u.accountId,children:["#",u.accountId.slice(0,8)]}),s.jsx("span",{style:{fontSize:11,padding:"1px 8px",borderRadius:10,background:"#161b22",border:`1px solid ${h}`,color:h,textAlign:"center"},children:f}),s.jsx("span",{style:{flex:1}}),s.jsxs("span",{style:{fontSize:11,color:"#6e7681",whiteSpace:"nowrap"},children:["re-admits in ",f_(u.remainingMs)]})]},`${u.provider}-${u.accountId}-${d}`)})})]}),e.events&&e.events.length>0&&s.jsxs("div",{style:{marginTop:18},children:[s.jsx("div",{style:{fontSize:13,fontWeight:600,color:"#e6edf3",marginBottom:10},children:"🛟 Failover Timeline — quota management & mid-session swaps"}),s.jsx("div",{style:{maxHeight:220,overflowY:"auto",background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"8px 0"},children:e.events.map((u,d)=>{const f=u.type==="parked"?"⏸":u.type==="re-enabled"?"🔁":u.type==="released"?"✅":"⚡",h=u.type==="parked"?"#f85149":u.type==="re-enabled"||u.type==="released"?"#3fb950":"#d29922",p=u.type==="parked"?"parked":u.type==="re-enabled"?"re-enabled":u.type==="released"?"released":"failover";return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"6px 14px",borderBottom:d<e.events.length-1?"1px solid #161b22":"none"},children:[s.jsx("span",{style:{fontSize:13},children:f}),s.jsx("span",{style:{width:80,flexShrink:0,fontSize:11,padding:"1px 8px",borderRadius:10,background:"#161b22",border:`1px solid ${h}`,color:h,textAlign:"center"},children:p}),s.jsxs("span",{style:{flex:1,fontSize:12,color:"#e6edf3",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[Nr(u.provider)," ",sa(u.provider)]}),u.reason&&s.jsx("span",{style:{fontSize:11,color:"#8b949e"},children:u.reason}),s.jsx("span",{style:{fontSize:11,color:"#6e7681",whiteSpace:"nowrap"},children:iM(u.timestamp)})]},`${u.timestamp}-${d}`)})})]})]})}function Fd({ok:e,children:t}){return s.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11,padding:"3px 9px",borderRadius:8,background:e===!1?"#2d1616":"#12291a",border:`1px solid ${e===!1?"#f85149":"#238636"}`,color:e===!1?"#f85149":"#3fb950",whiteSpace:"nowrap"},children:t})}function Yae({governance:e}){var r,i,a,o,l;if(!e.enabled)return s.jsx(Yn,{icon:"⚖️",title:"Admin Governance Policy",subtitle:"Hard-constraint rules the Auto router enforces on every pick",children:s.jsxs("div",{style:{fontSize:13,color:"#8b949e"},children:[s.jsx("span",{style:{color:"#3fb950"},children:"Fully permissive"})," — no governance rules active; any provider × model is eligible.",s.jsxs("div",{style:{marginTop:6,fontSize:12,color:"#6e7681"},children:["Add rules with ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff admin allow <provider>"})," ·"," ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff admin deny <provider>"})," ·"," ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff admin max-cost <usd>"})]})]})});const t=[];(r=e.allowProviders)!=null&&r.length&&t.push({label:"allow providers",items:e.allowProviders}),(i=e.denyProviders)!=null&&i.length&&t.push({label:"deny providers",items:e.denyProviders,deny:!0}),(a=e.allowModels)!=null&&a.length&&t.push({label:"allow models",items:e.allowModels}),(o=e.denyModels)!=null&&o.length&&t.push({label:"deny models",items:e.denyModels,deny:!0});const n=[];return e.maxCostUsd!==void 0&&n.push(`max cost $${e.maxCostUsd}`),e.minPrivacyForPii!==void 0&&e.minPrivacyForPii<1&&n.push(`PII min privacy ${e.minPrivacyForPii}`),(l=e.piiPatterns)!=null&&l.length&&n.push(`PII guard (${e.piiPatterns.length} patterns)`),e.allowUnblock===!1&&n.push("unblock admin-hard"),s.jsxs(Yn,{icon:"⚖️",title:"Admin Governance Policy",subtitle:"Hard-constraint rules — violating providers are eliminated, never just scored lower",children:[s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:10},children:[t.map(c=>s.jsxs(Fd,{ok:!c.deny,children:[c.deny?"⛔":"✅"," ",c.label,": ",c.items.join(", ")]},c.label)),n.map(c=>s.jsx(Fd,{children:c},c)),t.length===0&&n.length===0&&s.jsx(Fd,{ok:!1,children:"policy configured but no rules active"})]}),s.jsxs("div",{style:{fontSize:12,color:"#6e7681"},children:["Managed via ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff admin"})," — the same policy the CLI’s"," ",s.jsx("code",{children:"model explain"})," surfaces as governance-blocked."]})]})}function Xae({rbac:e}){const t=n=>n==="admin"?"#d29922":n==="operator"?"#3fb950":"#8b949e";return s.jsxs(Yn,{icon:"🔐",title:"RBAC Identity",subtitle:"Who may write policy — role file ~/.buff/rbac.json",children:[s.jsxs("div",{style:{fontSize:13,marginBottom:10},children:[s.jsx("span",{style:{color:"#c9d1d9"},children:"You are "}),s.jsx("code",{style:{color:"#58a6ff"},children:e.identity}),s.jsx("span",{style:{color:"#8b949e"},children:" as "}),e.role?s.jsx("span",{style:{color:t(e.role),fontWeight:600},children:e.role}):s.jsx("span",{style:{color:"#8b949e"},children:"unassigned"})]}),e.legacy?s.jsxs("div",{style:{fontSize:12,color:"#6e7681"},children:[s.jsx("span",{style:{color:"#3fb950"},children:"Legacy single-user mode"})," — no roles assigned; policy writes are open to every user. Assign roles with"," ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff admin role add <you> admin"}),"."]}):s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[e.users.map(n=>s.jsxs(Fd,{ok:n.role!=="viewer",children:[n.user," · ",n.role,n.via==="oidc"?" (oidc)":""]},n.user)),s.jsxs("div",{style:{width:"100%",fontSize:12,color:"#6e7681",marginTop:4},children:["Policy ",s.jsx("em",{children:"writes"})," require ",s.jsx("code",{style:{color:"#58a6ff"},children:"admin"}),"; reads are open to every role."]})]})]})}function Zae({data:e}){var p,g,m,v,y,b,x,k,S,w;const t=e==null?void 0:e.routing,n=t&&(t.preference.length>0||t.providers.length>0||t.bestModels.length>0),r=!!((p=t==null?void 0:t.usage)!=null&&p.total),i=!!((g=t==null?void 0:t.history)!=null&&g.length),a=!!t&&(((m=t.history)==null?void 0:m.length)??0)>0||!!((v=t==null?void 0:t.preference)!=null&&v.length),o=!!((y=t==null?void 0:t.bandit)!=null&&y.enabled),l=!!((b=t==null?void 0:t.promotion)!=null&&b.decisionCount),c=!!((x=t==null?void 0:t.ml)!=null&&x.enabled)&&(t.ml.recordCount??0)>0,u=!!((k=t==null?void 0:t.quota)!=null&&k.enabled),d=!!((S=t==null?void 0:t.retrieval)!=null&&S.enabled)||!!((w=t==null?void 0:t.retrieval)!=null&&w.repoChunks),f=!!(t!=null&&t.governance),h=!!(t!=null&&t.rbac);return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"🤖 Auto Routing Insights"}),s.jsxs("p",{className:"section-description",children:["Which providers and models the Auto router prefers — from real pricing, benchmark quality, per-agent success stats, and the Thompson-sampling bandit. Run"," ",s.jsx("code",{children:"buff benchmark"})," and use Auto routing to build this up over time."]}),!n&&!r&&!i&&!o&&!l&&!c&&!u&&!d&&!f&&!h?s.jsx(Pae,{}):s.jsxs(s.Fragment,{children:[a&&t&&s.jsx(Aae,{routing:t}),f&&t.governance&&s.jsx(Yae,{governance:t.governance}),(t==null?void 0:t.rbac)&&s.jsx(Xae,{rbac:t.rbac}),r&&s.jsx($ae,{usage:t.usage}),i&&s.jsx(Lae,{history:t.history}),o&&s.jsx(Fae,{bandit:t.bandit}),l&&s.jsx(Hae,{promotion:t.promotion}),c&&t.ml&&s.jsx(Gae,{ml:t.ml}),u&&s.jsx(Vae,{quota:t.quota}),d&&s.jsx(Kae,{retrieval:t.retrieval}),s.jsx(Dae,{routing:t}),s.jsx(Bae,{routing:t}),s.jsx(qae,{routing:t})]}),t&&t.providers.length===0&&t.bestModels.length===0&&t.preference.length>0&&s.jsx("div",{style:{fontSize:12,color:"#6e7681",marginTop:4},children:"Auto-router preference is always available (static profiles + real pricing); quality metrics appear once you run benchmarks and agent tasks."})]})}const p_={chat:"💬",execute:"⚙️",plan:"🗺️",edit:"✏️",skill:"🧩",learn:"📚",ci:"🔁",doctor:"🩺",probe:"🔭","spot-check":"🧪",telemetry:"📡",usage:"🧮","ide-chat":"💬","ide-inline":"✍️","ide-execute":"⚙️"};function Qae(e){return new Date(e).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function yd(e){return e!==void 0?`${e}ms`:"—"}function aM(e){return e===0?"#3fb950":e<.2?"#d29922":"#f85149"}function Jae({data:e}){const t=e.rows,n=t.reduce((c,u)=>c+u.requests,0),r=t.reduce((c,u)=>c+Math.round(u.errorRate*u.requests),0),i=t.reduce((c,u)=>c+(u.costUsd??0),0),a=t.flatMap(c=>c.latency?[c.latency.avg]:[]),o=a.length>0?Math.round(a.reduce((c,u)=>c+u,0)/a.length):void 0,l=new Set(t.map(c=>c.action)).size;return s.jsxs("div",{className:"stats-grid",style:{marginBottom:16},children:[s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"📨"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",children:n.toLocaleString()}),s.jsx("div",{className:"stat-label",children:"Requests"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"🎯"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",children:t.length}),s.jsx("div",{className:"stat-label",children:"provider × model × action groups"})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"⚡"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:o!==void 0?"#3fb950":"#8b949e"},children:o!==void 0?`${o}ms`:"—"}),s.jsxs("div",{className:"stat-label",children:["Avg latency",o!==void 0?` (${a.length} groups)`:" (no samples)"]})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"📛"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:aM(n>0?r/n:0)},children:n>0?`${(r/n*100).toFixed(1)}%`:"—"}),s.jsxs("div",{className:"stat-label",children:["Overall error rate (",r.toLocaleString()," failures)"]})]})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("span",{className:"stat-icon",children:"💰"}),s.jsxs("div",{className:"stat-body",children:[s.jsx("div",{className:"stat-value",style:{color:i>0?"#d29922":"#8b949e"},children:i>0?`$${i.toFixed(4)}`:"—"}),s.jsxs("div",{className:"stat-label",children:["Measured cost",l>0?` · ${l} actions`:""]})]})]})]})}function ese({data:e}){const[t,n]=E.useState(""),[r,i]=E.useState("all"),a=e==null?void 0:e.requests,o=E.useMemo(()=>{if(!a)return[];const c=t.trim().toLowerCase();return a.rows.filter(u=>r!=="all"&&u.action!==r?!1:c?`${u.provider} ${u.model} ${u.action}`.toLowerCase().includes(c):!0)},[a,t,r]);if(!e)return s.jsx("div",{className:"loading-state",children:s.jsx("p",{children:"Loading requests..."})});if(!a||!a.enabled||a.rows.length===0)return s.jsxs("div",{className:"empty-state",style:{padding:"40px 24px",textAlign:"center"},children:[s.jsx("div",{style:{fontSize:28,marginBottom:10},children:"📨"}),s.jsx("h2",{className:"section-title",style:{marginTop:0},children:"Requests — per provider × model × action"}),s.jsxs("p",{className:"section-description",style:{maxWidth:560,margin:"0 auto"},children:["No request telemetry yet. As you use ",s.jsx("strong",{children:"chat"}),", ",s.jsx("strong",{children:"execute"}),","," ",s.jsx("strong",{children:"plan"})," and ",s.jsx("strong",{children:"edit"})," under Auto routing, every call writes to the action-telemetry log and this panel aggregates it: request counts, p50/p95/p99 latency, error rate and measured cost — the same feed that drives the Models panel."]})]});const l=[...new Set(a.rows.map(c=>c.action))].sort();return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"📨 Requests — per provider × model × action"}),s.jsx("p",{className:"section-description",children:"Aggregated from the same action-telemetry log as the Models panel — every Auto-routed call, grouped by action × provider × model. Latency percentiles appear once ≥3 samples exist; cost when the caller reported usage."}),s.jsx(Jae,{data:a}),s.jsxs("div",{style:{display:"flex",gap:12,marginBottom:14,flexWrap:"wrap",alignItems:"center"},children:[s.jsxs("select",{value:r,onChange:c=>i(c.target.value),"aria-label":"Filter by action",style:{background:"#161b22",color:"#e6edf3",border:"1px solid #30363d",borderRadius:8,padding:"8px 10px",fontSize:13,cursor:"pointer"},children:[s.jsx("option",{value:"all",children:"All actions"}),l.map(c=>s.jsxs("option",{value:c,children:[p_[c]||"🎯"," ",c]},c))]}),s.jsxs("div",{style:{flex:1,minWidth:220,position:"relative"},children:[s.jsx("span",{style:{position:"absolute",left:10,top:8,color:"#6e7681",fontSize:13},children:"🔍"}),s.jsx("input",{type:"text",value:t,onChange:c=>n(c.target.value),placeholder:"Search provider, model or action...",style:{width:"100%",padding:"8px 12px 8px 32px",background:"#161b22",border:"1px solid #30363d",borderRadius:8,color:"#e6edf3",fontSize:13,outline:"none"}})]}),s.jsxs("span",{style:{fontSize:12,color:"#8b949e",whiteSpace:"nowrap"},children:[o.length," of ",a.rows.length," groups"]})]}),s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{borderBottom:"1px solid #21262d",color:"#8b949e",textAlign:"left"},children:[s.jsx("th",{style:{padding:"8px 12px",fontWeight:500},children:"Action"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500},children:"Provider"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500},children:"Model"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500,textAlign:"right"},children:"Requests"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500,textAlign:"right"},children:"Error rate"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500,textAlign:"right"},children:"Latency avg"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500,textAlign:"right"},children:"p50"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500,textAlign:"right"},children:"p95"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500,textAlign:"right"},children:"p99"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500,textAlign:"right"},children:"Measured cost"}),s.jsx("th",{style:{padding:"8px 12px",fontWeight:500,textAlign:"right"},children:"Last seen"})]})}),s.jsx("tbody",{children:o.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:11,style:{padding:28,textAlign:"center",color:"#6e7681"},children:"No request groups match your filter."})}):o.map(c=>{var u;return s.jsxs("tr",{style:{borderBottom:"1px solid #21262d"},children:[s.jsx("td",{style:{padding:"8px 12px",whiteSpace:"nowrap"},children:s.jsxs("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:8,background:"#21262d",color:"#c9d1d9",border:"1px solid #30363d"},children:[p_[c.action]||"🎯"," ",c.action]})}),s.jsx("td",{style:{padding:"8px 12px",color:"#e6edf3",whiteSpace:"nowrap"},children:c.provider}),s.jsxs("td",{style:{padding:"8px 12px",color:"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12,maxWidth:260,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:c.callIds.length>0?`Correlation ids: ${c.callIds.join(", ")}`:void 0,children:[c.model.length>42?c.model.slice(0,39)+"…":c.model,c.callIds.length>0&&s.jsxs("span",{style:{color:"#6e7681",marginLeft:6},title:c.callIds.join(", "),children:["🔗",c.callIds.length]})]}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12},children:c.requests}),s.jsxs("td",{style:{padding:"8px 12px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12,color:aM(c.errorRate)},children:[(c.errorRate*100).toFixed(1),"%",(c.partials??0)>0&&s.jsxs("span",{title:`⏸ ${c.partials} mid-stream interruption(s) — started streaming, died before finish; the router deprioritizes flaky providers (P4 M4.4)`,style:{display:"inline-flex",alignItems:"center",gap:3,marginLeft:6,fontSize:10,padding:"1px 6px",borderRadius:8,whiteSpace:"nowrap",background:"#21122e",border:"1px solid #bc8cff",color:"#bc8cff"},children:["⏸ ",c.partials]})]}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12},children:yd((u=c.latency)==null?void 0:u.avg)}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12},children:c.latency&&c.latency.samples>=3?yd(c.latency.p50):"—"}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12},children:c.latency&&c.latency.samples>=3?yd(c.latency.p95):"—"}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12},children:c.latency&&c.latency.samples>=3?yd(c.latency.p99):"—"}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12,color:c.costUsd?"#d29922":"#6e7681"},children:c.costUsd!==void 0?`$${c.costUsd.toFixed(4)}`:"—"}),s.jsx("td",{style:{padding:"8px 12px",textAlign:"right",color:"#6e7681",fontSize:11,whiteSpace:"nowrap"},children:Qae(c.lastAt)})]},`${c.action}|${c.provider}|${c.model}`)})})]})}),s.jsx("div",{style:{textAlign:"center",fontSize:12,color:"#484f58",marginTop:12},children:"Auto-refreshes with the dashboard feed · percentile columns need ≥3 latency samples per group"})]})}const tse={local:"💻",groq:"🟢",nim:"🔶",gemini:"🔷",openrouter:"🟣"},nse={planner:"🗺️",writer:"✍️",reviewer:"🔎",tester:"🧪",debugger:"🐛",runner:"🏃","context-gatherer":"📂",memory:"🧠","self-improver":"📈"};function rse(e){return tse[e]||"🔌"}function ise(e){return nse[e]||"🤖"}function sM(e){const t=Date.now()-e;return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${new Date(e).toLocaleDateString()}`}function h0(e){return e===void 0?"—":e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m ${Math.floor(e%6e4/1e3)}s`}function ic(e){return e==null?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}function ase(e){var n,r;if(!e)return null;const t={bg:"#0d1117",border:"#30363d"};return e.unverifiedClaim?{text:"⚠️ unverified claim — said it acted, but no tool ran",color:"#d29922",bg:"#3d2c00",border:"#d29922"}:e.unfulfilledPromise?{text:"⚠️ unfulfilled promise — announced an action it never performed",color:"#d29922",bg:"#3d2c00",border:"#d29922"}:e.unverifiedEditClaim?{text:"⚠️ unverified edit claim — asserted a fix, but nothing verified it",color:"#d29922",bg:"#3d2c00",border:"#d29922"}:e.unverifiedEdit?{text:`⚠️ unverified edit — ${((n=e.tools)==null?void 0:n.length)??0} tool(s), no test/typecheck/browser run`,color:"#d29922",bg:"#3d2c00",border:"#d29922"}:e.kind==="acted"?{text:e.delivered?"✅ action performed — message sent":`🔧 acted — ${((r=e.tools)==null?void 0:r.length)??0} tool(s)`,color:"#3fb950",bg:"#0d2818",border:"#238636"}:e.kind==="answered"?{text:"💬 answered — no action taken",color:"#8b949e",...t}:e.kind==="cancelled"?{text:"⏹ cancelled",color:"#8b949e",...t}:{text:"❌ generation failed",color:"#f85149",bg:"#2d0f0f",border:"#f85149"}}function qv({icon:e,title:t,subtitle:n,children:r}){return s.jsxs("div",{style:{background:"#161b22",borderRadius:12,border:"1px solid #21262d",padding:"18px 20px",marginBottom:16},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:4},children:[s.jsx("span",{style:{fontSize:20},children:e}),s.jsx("h3",{style:{fontSize:15,fontWeight:600,color:"#e6edf3",margin:0},children:t})]}),n&&s.jsx("p",{style:{fontSize:12,color:"#8b949e",margin:"2px 0 12px 0"},children:n}),!n&&s.jsx("div",{style:{height:6}}),r]})}function sse(){return s.jsxs("div",{style:{background:"#0d1117",border:"1px dashed #30363d",borderRadius:10,padding:"18px 20px",color:"#8b949e",fontSize:13,textAlign:"center"},children:["🔍 No reasoning traces yet — every LLM call in a ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff execute"})," pipeline is recorded to ",s.jsx("code",{style:{color:"#58a6ff"},children:"reasoning-traces.json"}),". Run a pipeline, then replay it here or with ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff trace replay <id>"}),"."]})}function ose({step:e}){const[t,n]=E.useState(!1),r=e.success?"#3fb950":"#f85149",i=e.success?"ok":"failed";return s.jsxs("div",{style:{background:"#0d1117",border:"1px solid #21262d",borderRadius:8,marginBottom:8,overflow:"hidden"},children:[s.jsxs("button",{onClick:()=>n(!t),style:{width:"100%",background:"none",border:"none",cursor:"pointer",padding:"10px 14px",textAlign:"left",display:"flex",alignItems:"center",gap:10,color:"inherit"},children:[s.jsx("span",{style:{width:26,fontSize:16},children:ise(e.agentType)}),s.jsx("span",{style:{width:130,fontSize:12,fontWeight:600,color:"#e6edf3",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},title:e.agentType,children:e.agentType}),s.jsxs("span",{style:{flex:1,fontSize:12,color:"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},title:`${e.provider}/${e.model}`,children:[rse(e.provider)," ",e.provider,"/",e.model]}),s.jsx("span",{style:{width:70,fontSize:11,color:"#6e7681",textAlign:"right"},children:h0(e.latencyMs)}),s.jsxs("span",{style:{width:86,fontSize:11,color:"#6e7681",fontFamily:"'SFMono-Regular', Consolas, monospace",textAlign:"right"},children:[ic(e.inputTokens),"→",ic(e.outputTokens)," tok"]}),s.jsx("span",{style:{width:46,fontSize:11,color:r,textAlign:"right"},children:i}),s.jsx("span",{style:{width:22,fontSize:11,textAlign:"right"},children:e.escalated?s.jsx("span",{title:"Repair escalated to a stronger routed model (v1.60.4)",children:"🚀"}):""}),s.jsx("span",{style:{fontSize:11,color:"#6e7681"},children:t?"▾":"▸"})]}),t&&s.jsxs("div",{style:{padding:"0 14px 12px 50px",fontSize:12},children:[e.taskId&&s.jsxs("div",{style:{color:"#6e7681",marginBottom:4},children:["Task: ",s.jsx("span",{style:{color:"#8b949e",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:e.taskId})]}),e.description&&s.jsx("div",{style:{color:"#8b949e",marginBottom:6},children:e.description}),e.routing&&s.jsxs("div",{style:{marginBottom:6},children:[s.jsxs("span",{style:{fontSize:10,padding:"1px 8px",borderRadius:10,background:e.escalated?"#3d2c00":"#1c2128",border:e.escalated?"1px solid #d29922":"1px solid #58a6ff",color:e.escalated?"#d29922":"#58a6ff"},children:[e.escalated?"🚀 escalated auto → ":"🤖 auto → ",e.routing.provider,"/",e.routing.model," · score ",e.routing.score.toFixed(3)," · ",e.routing.complexity]}),e.escalated&&s.jsx("div",{style:{color:"#d29922",marginTop:4,fontSize:11},children:"Repair escalated to a stronger routed model (next complexity level)."}),e.routing.explanation&&s.jsx("div",{style:{color:"#6e7681",marginTop:4,fontSize:11},children:e.routing.explanation})]}),e.layers&&s.jsxs("div",{style:{marginBottom:6,fontSize:11,color:"#6e7681",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:[s.jsx("span",{style:{color:"#58a6ff"},children:"sys"})," ",e.layers.systemChars,"c/#",e.layers.systemDigest," ·"," ",s.jsx("span",{style:{color:"#7ee787"},children:"ctx"})," ",e.layers.contextChars,"c/#",e.layers.contextDigest," ·"," ",s.jsx("span",{style:{color:"#d29922"},children:"vol"})," ",e.layers.volatileChars,"c/#",e.layers.volatileDigest,s.jsxs("div",{style:{color:"#484f58",marginTop:2},children:["a constant ",s.jsx("span",{style:{color:"#58a6ff"},children:"sys"})," digest across steps ⇒ the stable layer is prompt-cacheable"]})]}),e.error&&s.jsxs("div",{style:{color:"#f85149",marginBottom:6},children:["⚠️ ",e.error.slice(0,300)]}),s.jsxs("div",{style:{color:"#6e7681",margin:"6px 0 3px 0"},children:["Prompt ",s.jsxs("span",{style:{fontFamily:"'SFMono-Regular', Consolas, monospace"},children:["#",e.promptDigest]})," · ",e.promptPreview.length,"+ chars:"]}),s.jsx("pre",{style:{background:"#161b22",border:"1px solid #21262d",borderRadius:6,padding:8,margin:0,color:"#8b949e",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:180,overflowY:"auto",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:11},children:e.promptPreview.slice(0,900)}),s.jsxs("div",{style:{color:"#6e7681",margin:"8px 0 3px 0"},children:["Response (",ic(e.responseLength)," chars):"]}),s.jsx("pre",{style:{background:"#161b22",border:"1px solid #21262d",borderRadius:6,padding:8,margin:0,color:"#c9d1d9",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:240,overflowY:"auto",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:11},children:e.responsePreview.slice(0,1200)})]})]})}function lse({trace:e}){const[t,n]=E.useState(e.steps??null),[r,i]=E.useState(!1);E.useEffect(()=>{if(e.steps){n(e.steps);return}let l=!1;return ee.fetchTraceDetail(e.id).then(c=>{l||(c!=null&&c.steps?n(c.steps):i(!0))}),()=>{l=!0}},[e.id,e.steps]);const a=e.success===!0?"✅":e.success===!1?"❌":"⏳",o=e.success===!0?"success":e.success===!1?"failed":"in progress";return s.jsxs(qv,{icon:a,title:`${e.id} — ${o}`,subtitle:e.goal,children:[s.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginBottom:12},children:[s.jsxs("span",{style:{fontSize:11,padding:"2px 10px",borderRadius:12,background:"#0d1117",border:"1px solid #30363d",color:"#8b949e"},children:["🕓 ",sM(e.startedAt)]}),(()=>{const l=ase(e.outcome);return l?s.jsx("span",{style:{fontSize:11,padding:"2px 10px",borderRadius:12,background:l.bg,border:`1px solid ${l.border}`,color:l.color},children:l.text}):null})(),s.jsxs("span",{style:{fontSize:11,padding:"2px 10px",borderRadius:12,background:"#0d1117",border:"1px solid #30363d",color:"#8b949e"},children:["⏱ ",h0(e.durationMs)]}),s.jsxs("span",{style:{fontSize:11,padding:"2px 10px",borderRadius:12,background:"#0d1117",border:"1px solid #30363d",color:"#8b949e"},children:["🔢 ",(t==null?void 0:t.length)??"?"," call(s)"]}),t&&t.some(l=>l.escalated)&&s.jsxs("span",{style:{fontSize:11,padding:"2px 10px",borderRadius:12,background:"#3d2c00",border:"1px solid #d29922",color:"#d29922"},children:["🚀 ",t.filter(l=>l.escalated).length," escalated repair(s)"]}),e.totalTokens!==void 0&&s.jsxs("span",{style:{fontSize:11,padding:"2px 10px",borderRadius:12,background:"#0d1117",border:"1px solid #30363d",color:"#8b949e"},children:["🧮 ",ic(e.totalTokens)," tok"]})]}),e.systemPrompt&&s.jsxs("details",{style:{marginBottom:12},children:[s.jsxs("summary",{style:{cursor:"pointer",fontSize:12,color:"#58a6ff"},children:["🧬 System prompt — stable layer (",e.systemPromptChars??e.systemPrompt.length," chars)"]}),s.jsx("pre",{style:{background:"#161b22",border:"1px solid #21262d",borderRadius:6,padding:10,margin:"8px 0 0 0",color:"#8b949e",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:320,overflowY:"auto",fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:11},children:e.systemPrompt})]}),r&&s.jsx("div",{style:{color:"#f85149",fontSize:12,marginBottom:10},children:"Could not load trace steps (trace may have been deleted)."}),t===null&&!r&&s.jsx("div",{style:{color:"#8b949e",fontSize:12},children:"Loading steps…"}),t&&t.length===0&&s.jsx("div",{style:{color:"#8b949e",fontSize:12},children:"No LLM calls recorded in this trace."}),t&&t.map(l=>s.jsx(ose,{step:l},l.seq))]})}function cse({traces:e}){const[t,n]=E.useState(null);return t?s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>n(null),style:{background:"#21262d",border:"1px solid #30363d",color:"#e6edf3",borderRadius:8,padding:"6px 14px",fontSize:12,cursor:"pointer",marginBottom:12},children:"← Back to traces"}),s.jsx(lse,{trace:t})]}):s.jsx("div",{children:e.map(r=>{const i=r.success===!0?"✅":r.success===!1?"❌":"⏳",a=r.steps?[...new Set(r.steps.map(o=>o.agentType))].join(", "):"";return s.jsxs("button",{onClick:()=>n(r),style:{width:"100%",background:"#0d1117",border:"1px solid #21262d",borderRadius:10,padding:"12px 16px",marginBottom:8,cursor:"pointer",textAlign:"left",color:"inherit",transition:"border-color 0.2s, box-shadow 0.2s"},onMouseEnter:o=>{o.currentTarget.style.borderColor="#58a6ff",o.currentTarget.style.boxShadow="0 2px 10px #58a6ff22"},onMouseLeave:o=>{o.currentTarget.style.borderColor="#21262d",o.currentTarget.style.boxShadow="none"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:4},children:[s.jsx("span",{children:i}),s.jsx("span",{style:{fontSize:11,color:"#58a6ff",fontFamily:"'SFMono-Regular', Consolas, monospace"},children:r.id}),s.jsx("span",{style:{fontSize:11,color:"#6e7681",marginLeft:"auto"},children:sM(r.startedAt)})]}),s.jsx("div",{style:{fontSize:13,color:"#e6edf3",marginBottom:6},children:r.goal}),s.jsxs("div",{style:{display:"flex",gap:10,flexWrap:"wrap",fontSize:11,color:"#8b949e"},children:[s.jsxs("span",{children:["🔢 ",r.stepCount??0," call(s)"]}),s.jsxs("span",{children:["⏱ ",h0(r.durationMs)]}),r.failedSteps?s.jsxs("span",{style:{color:"#f85149"},children:["❌ ",r.failedSteps," failed"]}):s.jsx("span",{style:{color:"#3fb950"},children:"✓ all ok"}),r.totalTokens!==void 0&&s.jsxs("span",{children:["🧮 ",ic(r.totalTokens)," tok"]}),a&&s.jsxs("span",{children:["🤖 ",a.slice(0,60)]})]})]},r.id)})})}function use(){const[e,t]=E.useState(null),[n,r]=E.useState(!1),i=E.useCallback(()=>{ee.fetchTraces().then(a=>{a?(t(a),r(!1)):r(!0)})},[]);return E.useEffect(()=>{i();const a=setInterval(i,15e3);return()=>clearInterval(a)},[i]),s.jsxs("div",{className:"panel",children:[s.jsxs("div",{style:{marginBottom:16},children:[s.jsx("h2",{style:{margin:0,fontSize:18,color:"#e6edf3"},children:"🔍 Reasoning Traces"}),s.jsx("p",{style:{margin:"4px 0 0 0",fontSize:12,color:"#8b949e"},children:"Every LLM call in each pipeline — agent × model × prompt digest × response × tokens × latency × routing snapshot (assessment P0)."})]}),e===null&&!n&&s.jsx(qv,{icon:"⏳",title:"Loading…",children:s.jsx("div",{style:{color:"#8b949e",fontSize:13},children:"Fetching reasoning traces…"})}),n&&e===null&&s.jsx(qv,{icon:"⚠️",title:"Could not reach the dashboard server",children:s.jsxs("div",{style:{color:"#8b949e",fontSize:13},children:["The traces endpoint is unavailable right now — retrying automatically. Run"," ",s.jsx("code",{style:{color:"#58a6ff"},children:"buff trace list"})," in the terminal to inspect traces directly."]})}),e!==null&&e.length===0&&s.jsx(sse,{}),e!==null&&e.length>0&&s.jsx(cse,{traces:e})]})}function ig(e){if(e.trim()==="")return null;const t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function dse({authed:e,role:t}){const[n,r]=E.useState(null),[i,a]=E.useState({}),[o,l]=E.useState(""),[c,u]=E.useState(!1),[d,f]=E.useState(null),[h,p]=E.useState(null),g=e&&(t==="admin"||t==="operator"),m=e&&t==="admin",v=E.useCallback(async()=>{var _,N,C;const S=await ee.fetchAdminQuota();if(!S){p("Could not load budget config.");return}p(null),r(S);const w={};for(const T of S.providers){const $=S.quota[T]||{};w[T]={provider:T,tokens:((_=$.tokensPerWindow)==null?void 0:_.toString())??"",requests:((N=$.requestsPerWindow)==null?void 0:N.toString())??"",windowMs:((C=$.windowMs)==null?void 0:C.toString())??""}}a(w),l(S.costUsd===null?"":String(S.costUsd))},[]);E.useEffect(()=>{v()},[v]);const y=(S,w,_)=>{a(N=>({...N,[S]:{...N[S]||{provider:S},[w]:_}}))},b=async()=>{u(!0),f(null);const S={};for(const N of Object.values(i)){const C={},T=ig(N.tokens),$=ig(N.requests),R=ig(N.windowMs);T!==null&&(C.tokensPerWindow=T),$!==null&&(C.requestsPerWindow=$),R!==null&&(C.windowMs=R),S[N.provider]=Object.keys(C).length>0?C:null}const w={quota:S};if(m)if(o.trim()!==""){const N=Number(o);if(!Number.isFinite(N)||N<0){f({ok:!1,text:"Cost cap must be a non-negative number."}),u(!1);return}w.costUsd=N}else w.costUsd=null;const _=await ee.saveAdminQuota(w);u(!1),_.ok?(f({ok:!0,text:"Budget saved — the quota ledger + auto-router will enforce it."}),v()):f({ok:!1,text:_.error||"Save failed."})},x=S=>{const w=n==null?void 0:n.quota[S];return!!w&&(w.tokensPerWindow!==void 0||w.requestsPerWindow!==void 0||w.windowMs!==void 0)},k=S=>"admin-input";return s.jsxs("div",{className:"admin-quota-panel",children:[s.jsx("h3",{className:"section-subtitle",children:"💰 Daily Budget (routing.quota — your plan, your say)"}),s.jsxs("p",{className:"admin-quota-note",children:["Free-tier providers enforce tokens-per-day caps the API doesn't advertise — only you know your plan's allowance. Declare it here and the agent paces around it (parks the provider at the cap, auto-resumes at window rollover) instead of exhausting your budget mid-task. Unset = current behavior. Same config as ",s.jsx("code",{children:"buff model quota set"}),"."]}),h?s.jsx("div",{className:"admin-error",children:h}):null,n?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"admin-quota-table",children:[s.jsxs("div",{className:"admin-quota-row admin-quota-head",children:[s.jsx("span",{children:"Provider"}),s.jsx("span",{children:"Tokens / window"}),s.jsx("span",{children:"Requests / window"}),s.jsx("span",{children:"Window (ms)"}),s.jsx("span",{children:"Status"})]}),n.providers.map(S=>{var w,_,N;return s.jsxs("div",{className:"admin-quota-row",children:[s.jsx("span",{className:"admin-provider-type",children:S}),s.jsx("input",{className:k(!g),type:"number",min:0,placeholder:"unset",disabled:!g,value:((w=i[S])==null?void 0:w.tokens)??"",onChange:C=>y(S,"tokens",C.target.value)}),s.jsx("input",{className:k(!g),type:"number",min:0,placeholder:"unset",disabled:!g,value:((_=i[S])==null?void 0:_.requests)??"",onChange:C=>y(S,"requests",C.target.value)}),s.jsx("input",{className:k(!g),type:"number",min:0,placeholder:"86400000 (24h)",disabled:!g,value:((N=i[S])==null?void 0:N.windowMs)??"",onChange:C=>y(S,"windowMs",C.target.value)}),s.jsx("span",{className:`admin-role-badge ${x(S)?"admin-role-admin":"admin-role-viewer"}`,children:x(S)?"declared":"unset"})]},S)})]}),s.jsxs("div",{className:"admin-quota-row admin-quota-cost",children:[s.jsx("span",{className:"admin-provider-type",children:"Max cost / call (USD, admin)"}),s.jsx("input",{className:k(!m),type:"number",min:0,step:.01,placeholder:"unset",disabled:!m,value:o,onChange:S=>l(S.target.value)}),s.jsx("span",{className:"admin-quota-cost-hint",children:"governance.maxCostUsd — hard admin cap"})]}),g||m?s.jsxs("div",{className:"admin-quota-actions",children:[s.jsx("button",{className:"admin-mini-btn",onClick:()=>void b(),disabled:c,children:c?"⏳ Saving…":"💾 Save budget"}),d?s.jsx("span",{className:d.ok?"admin-quota-ok":"admin-quota-err",children:d.text}):null]}):s.jsxs("div",{className:"admin-readonly-note",children:["🔒 Read-only for ",s.jsx("code",{children:t})," — budget limits need ",s.jsx("code",{children:"admin"})," or"," ",s.jsx("code",{children:"operator"}),"; the cost cap needs ",s.jsx("code",{children:"admin"}),"."]})]}):s.jsx("div",{className:"empty-state",children:"Loading budget…"})]})}const fse={pass:"✅",warn:"⚠️",fail:"❌"},hse={pass:"PASS",warn:"WARN",fail:"FAIL"},pse={env:"Environment",config:"Config",vault:"Vault",local:"Local (no key)",none:"Not configured"};function m_({check:e}){return s.jsxs("div",{className:"admin-check-row","data-status":e.status,children:[s.jsxs("span",{className:`admin-check-badge admin-check-${e.status}`,children:[fse[e.status]," ",hse[e.status]]}),s.jsxs("div",{className:"admin-check-body",children:[s.jsx("div",{className:"admin-check-name",children:e.name}),s.jsx("div",{className:"admin-check-message",children:e.message}),e.detail?s.jsx("div",{className:"admin-check-detail",children:e.detail}):null,e.fix?s.jsxs("div",{className:"admin-check-fix",children:["💡 ",e.fix]}):null]})]})}function mse(){const[e,t]=E.useState(null),[n,r]=E.useState(!0),[i,a]=E.useState(null),[o,l]=E.useState(null),[c,u]=E.useState(!1),[d,f]=E.useState(null),[h,p]=E.useState(null),[g,m]=E.useState(""),[v,y]=E.useState(""),[b,x]=E.useState(""),[k,S]=E.useState(null),[w,_]=E.useState(!1),[N,C]=E.useState([]),[T,$]=E.useState(null),[R,L]=E.useState(""),[I,z]=E.useState(""),[D,F]=E.useState("viewer"),[O,P]=E.useState([]),[A,Y]=E.useState({}),[K,M]=E.useState(null),[le,be]=E.useState({}),[me,Pe]=E.useState(""),[H,X]=E.useState(null),[oe,ce]=E.useState(null),Z=E.useCallback(async()=>{r(!0),a(null);const G=await ee.fetchAdminChecks();t(G),G||a("Could not reach the dashboard server, or the server is older than this panel. Run `buff dashboard` to start it."),r(!1)},[]),_e=E.useCallback(async()=>{const G=await ee.fetchAdminCatalog();G&&G.length>0&&P(G)},[]),we=E.useCallback(async()=>{const G=await ee.fetchAdminUsers();G.ok&&G.users&&C(G.users)},[]);E.useEffect(()=>{let G=!0;return ee.fetchAdminAuthStatus().then(he=>{if(G){if(!he){a("Could not reach the dashboard server, or the server is older than this panel. Run `buff dashboard` to start it."),r(!1);return}l({configured:he.configured,authenticated:he.authenticated}),u(he.authenticated),f(he.role??null),p(he.user??null),he.authenticated?(Z(),_e(),we()):r(!1)}}),()=>{G=!1}},[Z,_e,we]);const Ne=d==="admin",ge=()=>{u(!1),l(G=>G&&{...G,authenticated:!1}),S("Session expired — log in again.")},Be=async G=>{G.preventDefault(),_(!0),S(null);const he=await ee.adminLogin(g,v);he.ok?(u(!0),l({configured:!0,authenticated:!0}),f(he.role??"admin"),p(he.user??null),m(""),y(""),Z(),_e(),we()):S(he.error||"Login failed."),_(!1)},pe=async G=>{if(G.preventDefault(),_(!0),S(null),v.length<8){S("Password must be at least 8 characters."),_(!1);return}if(v!==b){S("Passwords do not match."),_(!1);return}const he=await ee.adminSetup(g,v);he.ok?(u(!0),l({configured:!0,authenticated:!0}),f(he.role??"admin"),p(he.user??null),m(""),y(""),x(""),Z(),_e(),we()):S(he.error||"Setup failed."),_(!1)},Ct=async()=>{await ee.adminLogout(),u(!1),l(G=>G&&{...G,authenticated:!1}),f(null),p(null),t(null),Y({}),be({}),C([])},We=async()=>{if(!window.confirm("Stop the running gateway? Channels will stop responding until you restart it with `buff gateway start`."))return;ce("gateway"),X(null);const G=await ee.shutdown("gateway");ce(null),G.ok?X(G.stopped?"✅ Gateway stopped.":`ℹ️ ${G.reason||"No running gateway found — nothing to stop."}`):(X(`❌ ${G.error||"Stop failed."}`),G.unauthorized&&ge())},Oe=async()=>{window.confirm("Shut down the dashboard? This page will disconnect and the server will exit. Restart with `buff dashboard`.")&&(ce("dashboard"),X("🛑 Shutting down the dashboard — this page will disconnect…"),await ee.shutdown("dashboard"),ce(null),X("ℹ️ The dashboard server did not stop (see the server terminal). You can also stop it with `buff dashboard stop`."))},Ze=async G=>{if(G.preventDefault(),$(null),I.length<8){$("Password must be at least 8 characters.");return}const he=await ee.addAdminUser(R,I,D);he.ok?(L(""),z(""),$("✅ User added"),we()):($(`❌ ${he.error||"Failed to add user"}`),he.unauthorized&&ge())},Me=async G=>{if(!window.confirm(`Remove dashboard user '${G}'?`))return;$(null);const he=await ee.removeAdminUser(G);he.ok?($(`✅ Removed ${G}`),we()):($(`❌ ${he.error||"Failed to remove user"}`),he.unauthorized&&ge())},Qt=(G,he,Ie)=>{Y(Re=>({...Re,[G]:{...Re[G]||{},[he]:Ie}}))},$t=async G=>{M(G),be({});const he=A[G]||{},Ie=await ee.saveProvider(G,he);Ie.ok?(t(Re=>{if(!Re)return Re;const Jt=Re.providers.some(An=>An.type===G)?Re.providers.map(An=>An.type===G&&Ie.provider?Ie.provider:An):Ie.provider?[...Re.providers,Ie.provider]:Re.providers;return{...Re,providers:Jt}}),Y(Re=>{const Cr={...Re};return delete Cr[G],Cr}),be(Re=>({...Re,[G]:"✅ Saved"}))):(be(Re=>({...Re,[G]:`❌ ${Ie.error||"Save failed"}`})),Ie.unauthorized&&ge()),M(null)},U=async G=>{if(!window.confirm(`Remove ${G}'s API key and configuration? This cannot be undone.`))return;M(G),be({});const he=await ee.deleteProvider(G);he.ok?he.envSourced?(t(Ie=>Ie&&{...Ie,providers:Ie.providers.map(Re=>Re.type===G&&he.provider||Re)}),be(Ie=>({...Ie,[G]:`⚠️ Key comes from ${he.envVar?`$${he.envVar}`:"an env var"} — unset it there to remove it (config can't override the env).`}))):(t(Ie=>Ie&&{...Ie,providers:Ie.providers.filter(Re=>Re.type!==G)}),Y(Ie=>{const Re={...Ie};return delete Re[G],Re})):(be(Ie=>({...Ie,[G]:`❌ ${he.error||"Remove failed"}`})),he.unauthorized&&ge()),M(null)},V=async G=>{M(G);const he=await ee.testProvider(G);be(Ie=>{var Re;return{...Ie,[G]:he.ok?`✅ Connected — ${((Re=he.models)==null?void 0:Re.length)??0} model(s) reachable`:`❌ ${he.error||"Connection failed"}`}}),M(null)},se=()=>{me&&(Y(G=>({...G,[me]:{}})),Pe(""))};if(i&&!o)return s.jsxs("div",{className:"admin-header",children:[s.jsx("h2",{className:"section-title",children:"🛠️ Admin"}),s.jsx("div",{className:"admin-error",children:i})]});if(!o||!c&&n)return s.jsxs("div",{className:"admin-header",children:[s.jsx("h2",{className:"section-title",children:"🛠️ Admin"}),s.jsxs("div",{className:"loading-state",children:[s.jsx("div",{className:"loading-spinner"}),s.jsx("p",{children:"Loading…"})]})]});if(!c){const G=!o.configured;return s.jsxs("div",{className:"admin-header",children:[s.jsxs("h2",{className:"section-title",children:["🛠️ Admin — ",G?"Set up access":"Log in"]}),s.jsx("p",{className:"admin-subtitle",children:G?"Create the admin user-id and password that gate the dashboard write surface (API-key/provider configuration). The CLI keeps working exactly as before — this only guards the GUI.":"The write surface (API-key/provider configuration) is gated by the admin credentials. Read-only checks stay open."}),s.jsxs("form",{className:"admin-gate-form",onSubmit:G?pe:Be,children:[s.jsxs("label",{children:[s.jsx("span",{children:"Username"}),s.jsx("input",{type:"text",value:g,onChange:he=>m(he.target.value),autoComplete:"username",placeholder:"admin"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Password"}),s.jsx("input",{type:"password",value:v,onChange:he=>y(he.target.value),autoComplete:G?"new-password":"current-password",placeholder:"••••••••"})]}),G?s.jsxs("label",{children:[s.jsx("span",{children:"Confirm password"}),s.jsx("input",{type:"password",value:b,onChange:he=>x(he.target.value),autoComplete:"new-password",placeholder:"••••••••"})]}):null,k?s.jsx("div",{className:"admin-error",children:k}):null,s.jsx("button",{className:"admin-refresh-btn",type:"submit",disabled:w||!g||!v,children:w?"⏳ …":G?"🔐 Create admin":"🔐 Log in"}),G?s.jsxs("p",{className:"admin-hint",children:["Automation alternative: set ",s.jsx("code",{children:"BUFF_DASHBOARD_ADMIN_USER"})," and"," ",s.jsx("code",{children:"BUFF_DASHBOARD_ADMIN_PASSWORD"})," in the dashboard's environment."]}):null]})]})}const fe=(e==null?void 0:e.system.filter(G=>G.status==="pass").length)??0,Se=(e==null?void 0:e.system.filter(G=>G.status==="warn").length)??0,Qe=(e==null?void 0:e.system.filter(G=>G.status==="fail").length)??0,Lt=(e==null?void 0:e.enterprise.filter(G=>G.status==="pass").length)??0,Ot=(e==null?void 0:e.enterprise.filter(G=>G.status==="warn").length)??0,jn=(e==null?void 0:e.enterprise.filter(G=>G.status==="fail").length)??0,xt=(e==null?void 0:e.providers)??[],dt=G=>{const he=O.find(Ie=>Ie.id===G);return he||{label:G}};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"admin-header",children:[s.jsxs("h2",{className:"section-title",children:["🛠️ Admin — Command Runner & Configuration",h?s.jsxs("span",{className:`admin-role-badge admin-role-${d||"viewer"}`,children:[h," · ",d||"viewer"]}):null]}),s.jsxs("div",{className:"admin-header-actions",children:[s.jsx("button",{className:"admin-refresh-btn",onClick:()=>void Z(),disabled:n,children:n?"⏳ Running checks…":"🔄 Refresh (run all commands)"}),Ne||d==="operator"?s.jsx("button",{className:"admin-logout-btn",onClick:()=>void We(),disabled:oe!==null,title:"Stop the running gateway (buff gateway stop)",children:oe==="gateway"?"⏳ Stopping…":"⏻ Stop gateway"}):null,Ne?s.jsx("button",{className:"admin-logout-btn",onClick:()=>void Oe(),disabled:oe!==null,title:"Shut down this dashboard server (buff dashboard stop)",children:oe==="dashboard"?"⏳ Stopping…":"🛑 Stop dashboard"}):null,s.jsx("button",{className:"admin-logout-btn",onClick:()=>void Ct(),children:"🚪 Log out"})]})]}),H?s.jsx("div",{className:"admin-error",children:H}):null,Ne?null:s.jsxs("div",{className:"admin-readonly-note",children:["🔒 Your role (",s.jsx("code",{children:d||"viewer"}),") is read-only here — provider configuration and user management require the ",s.jsx("code",{children:"admin"})," role. The CLI enforces the same governance policy (rbac.json)."]}),s.jsx("p",{className:"admin-subtitle",children:"The dashboard executes the same state commands as the CLI — no command needed. Provider keys are masked here and every write goes through the same config the CLI uses."}),i?s.jsx("div",{className:"admin-error",children:i}):null,e?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"admin-summary-grid",children:[s.jsxs("div",{className:"admin-summary-card admin-summary-pass",children:[s.jsx("div",{className:"admin-summary-value",children:fe+Lt}),s.jsx("div",{className:"admin-summary-label",children:"✅ Passing"})]}),s.jsxs("div",{className:"admin-summary-card admin-summary-warn",children:[s.jsx("div",{className:"admin-summary-value",children:Se+Ot}),s.jsx("div",{className:"admin-summary-label",children:"⚠️ Warnings"})]}),s.jsxs("div",{className:"admin-summary-card admin-summary-fail",children:[s.jsx("div",{className:"admin-summary-value",children:Qe+jn}),s.jsx("div",{className:"admin-summary-label",children:"❌ Failing"})]}),s.jsxs("div",{className:"admin-summary-card",children:[s.jsx("div",{className:"admin-summary-value",children:xt.length}),s.jsx("div",{className:"admin-summary-label",children:"Providers"})]})]}),s.jsx("h3",{className:"section-subtitle",children:"⚙️ System Checks (buff doctor)"}),s.jsx("div",{className:"admin-check-list",children:e.system.map(G=>s.jsx(m_,{check:G},G.name))}),s.jsx("h3",{className:"section-subtitle",children:"🏥 Enterprise Self-Check (doctor --enterprise)"}),s.jsx("div",{className:"admin-check-list",children:e.enterprise.length>0?e.enterprise.map(G=>s.jsx(m_,{check:G},G.name)):s.jsx("div",{className:"empty-state",children:"No enterprise checks returned."})}),s.jsx("h3",{className:"section-subtitle",children:"🔑 Provider Configuration (keys masked)"}),s.jsx("div",{className:"admin-table-wrapper",children:s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Provider"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Key"}),s.jsx("th",{children:"Base URL"}),s.jsx("th",{children:"Model"}),s.jsx("th",{children:"Actions"})]})}),s.jsxs("tbody",{children:[xt.map(G=>{const he=dt(G.type),Ie=A[G.type]||{};return s.jsxs("tr",{children:[s.jsxs("td",{className:"admin-provider-type",children:[he.icon?`${he.icon} `:"",he.label,s.jsxs("div",{className:"admin-provider-sub",children:[G.type," · ",pse[G.keySource]||G.keySource]}),G.keySource==="env"?s.jsxs("div",{className:"admin-hint",children:["comes from ",he.envVar||"env var"," — change it there, config can't override it"]}):G.keySource==="vault"?s.jsx("div",{className:"admin-hint",children:"stored in the OS keyring (vault)"}):null]}),s.jsx("td",{children:s.jsx("span",{className:`admin-check-badge ${G.configured?"admin-check-pass":"admin-check-warn"}`,children:G.configured?"✅ Configured":"⚠️ Not configured"})}),s.jsx("td",{children:he.keyless?s.jsx("div",{className:"admin-hint",children:"No key needed (probed)"}):Ne?s.jsx("input",{className:"admin-input admin-key-input",type:"password","aria-label":`${G.type} API key`,placeholder:G.keyMasked||"set a new key…",value:Ie.apiKey??"",onChange:Re=>Qt(G.type,"apiKey",Re.target.value),autoComplete:"new-password"}):s.jsx("div",{className:"admin-hint",children:G.keyMasked||"—"})}),s.jsx("td",{children:Ne?s.jsx("input",{className:"admin-input",type:"text","aria-label":`${G.type} base URL`,placeholder:G.baseUrl||"default endpoint",value:Ie.baseUrl??"",onChange:Re=>Qt(G.type,"baseUrl",Re.target.value)}):s.jsx("div",{className:"admin-hint",children:G.baseUrl?G.baseUrl.replace(/^https?:\/\/(?:[^@/]*@)?/,""):"default endpoint"})}),s.jsx("td",{children:Ne?s.jsx("input",{className:"admin-input",type:"text","aria-label":`${G.type} model`,placeholder:G.model||"default model",value:Ie.model??"",onChange:Re=>Qt(G.type,"model",Re.target.value)}):s.jsx("div",{className:"admin-hint",children:G.model||"default model"})}),s.jsx("td",{children:Ne?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"admin-row-actions",children:[s.jsx("button",{className:"admin-mini-btn",disabled:K===G.type,onClick:()=>void $t(G.type),children:"💾 Save"}),s.jsx("button",{className:"admin-mini-btn",disabled:K===G.type,title:"Tests the SAVED configuration — save first to test a new key",onClick:()=>void V(G.type),children:"🔌 Test"}),s.jsx("button",{className:"admin-mini-btn admin-mini-danger",disabled:K===G.type,onClick:()=>void U(G.type),children:"🗑 Remove"})]}),le[G.type]?s.jsx("div",{className:"admin-row-msg",children:le[G.type]}):null]}):s.jsx("div",{className:"admin-hint",children:"read-only"})})]},G.type)}),xt.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:6,className:"admin-empty-cell",children:"No providers configured yet."})}):null]})]})}),Ne&&O.length>0?s.jsxs("div",{className:"admin-add-provider",children:[s.jsxs("select",{className:"admin-input",value:me,onChange:G=>Pe(G.target.value),children:[s.jsx("option",{value:"",children:"Add a provider…"}),O.filter(G=>!xt.some(he=>he.type===G.id)).map(G=>s.jsxs("option",{value:G.id,children:[G.icon?`${G.icon} `:"",G.label," (",G.id,")"]},G.id))]}),s.jsx("button",{className:"admin-mini-btn",disabled:!me,onClick:se,children:"➕ Add"})]}):null,s.jsx(dse,{authed:c,role:d||"viewer"}),Ne?s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"section-subtitle",children:"👥 Dashboard Users (role.manage)"}),s.jsxs("div",{className:"admin-users-list",children:[N.map(G=>s.jsxs("div",{className:"admin-user-row",children:[s.jsx("span",{className:"admin-user-name",children:G.user}),s.jsx("span",{className:`admin-role-badge admin-role-${G.role}`,children:G.role}),s.jsxs("span",{className:"admin-user-since",children:["since ",new Date(G.createdAt).toLocaleDateString()]}),G.user!==h?s.jsx("button",{className:"admin-mini-btn admin-mini-danger",onClick:()=>void Me(G.user),children:"🗑 Remove user"}):s.jsx("span",{className:"admin-hint",children:"you"})]},G.user)),N.length===0?s.jsx("div",{className:"empty-state",children:"No dashboard users yet."}):null]}),s.jsxs("form",{className:"admin-gate-form admin-user-form",onSubmit:Ze,children:[s.jsxs("label",{children:[s.jsx("span",{children:"Username"}),s.jsx("input",{type:"text",value:R,onChange:G=>L(G.target.value),autoComplete:"off"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Password (min 8 chars)"}),s.jsx("input",{type:"password",value:I,onChange:G=>z(G.target.value),autoComplete:"new-password"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Role"}),s.jsxs("select",{value:D,onChange:G=>F(G.target.value),children:[s.jsx("option",{value:"viewer",children:"viewer — read-only"}),s.jsx("option",{value:"operator",children:"operator — read-only in the dashboard today"}),s.jsx("option",{value:"admin",children:"admin — full control"})]})]}),T?s.jsx("div",{className:"admin-row-msg",children:T}):null,s.jsx("button",{className:"admin-refresh-btn",type:"submit",disabled:!R||!I,children:"➕ Add user"})]})]}):null]}):n?s.jsxs("div",{className:"loading-state",children:[s.jsx("div",{className:"loading-spinner"}),s.jsx("p",{children:"Running all state checks…"})]}):null]})}function oM(e){return String(e??"").replace(/\d{3,}/g,t=>t.slice(0,2)+"***")}const gse={idle:"Not paired",pairing:"⏳ Pairing…",paired:"✅ Paired",failed:"❌ Pairing failed",cancelled:"⏹ Cancelled",error:"💥 Pairing error"};function yse({authed:e,canWrite:t,sessionExpired:n,reveal:r=!1}){const[i,a]=E.useState(null),[o,l]=E.useState({}),[c,u]=E.useState(""),[d,f]=E.useState(!1),[h,p]=E.useState(null),g=E.useRef(null),m=E.useCallback(async()=>{const w=await ee.getWhatsAppStatus();w&&(a(w.status),l(w.contacts??{}))},[]);E.useEffect(()=>{if(m(),!e||typeof EventSource>"u")return;const w=ee.subscribeWhatsApp({onQr:_=>a(N=>N&&{...N,qr:_,state:"pairing"}),onCode:_=>a(N=>N&&{...N,pairingCode:_}),onStatus:_=>{a(_),(_.state==="paired"||_.state==="failed"||_.state==="error"||_.state==="cancelled")&&f(!1)}});return g.current=w,()=>{w(),g.current=null}},[e,m]);const v=async w=>{f(!0),p(null);const _=await w();if(!_.ok&&_.error&&/Not authenticated|Session expired/i.test(_.error)){n(),f(!1);return}_.ok?(p({kind:"ok",text:"Done."}),await m()):p({kind:"err",text:_.error||"Action failed."}),f(!1)},y=w=>{p(null),v(()=>ee.startWhatsAppPair(w?c.trim():void 0)).then(()=>u(""))},b=()=>{p(null),v(()=>ee.cancelWhatsAppPair())},x=()=>{window.confirm("Remove the paired WhatsApp session from this machine? You will need to scan a QR to pair again.")&&(p(null),v(()=>ee.unpairWhatsApp()))},k=(i==null?void 0:i.state)??"idle",S=k==="pairing";return s.jsxs("div",{className:"wa-panel",children:[s.jsxs("div",{className:"wa-panel-head",children:[s.jsx("span",{className:"wa-panel-title",children:"🟢 WhatsApp bridge"}),i?s.jsx("span",{className:`wa-badge ${i.paired?"wa-badge-paired":S?"wa-badge-pairing":""}`,children:gse[k]}):s.jsx("span",{className:"admin-hint",children:"loading…"})]}),s.jsxs("p",{className:"admin-hint",children:["The personal Baileys bridge (no Meta Business account) — pair once, and the gateway can send & receive WhatsApp. Session: ",s.jsx("code",{children:(i==null?void 0:i.sessionDir)??"~/.buff/whatsapp/session"}),". Same engine as"," ",s.jsx("code",{children:"buff whatsapp pair"}),"."]}),S?s.jsxs("div",{className:"wa-pairing",children:[i!=null&&i.qr?s.jsxs("div",{className:"wa-qr-box",children:[s.jsx("img",{className:"wa-qr-img",src:i.qr,alt:"WhatsApp pairing QR code"}),s.jsxs("p",{className:"admin-hint",children:["Open WhatsApp on the phone → ",s.jsx("strong",{children:"Linked devices → Link a device → scan"}),". The QR refreshes automatically while this window is open."]})]}):i!=null&&i.phone?s.jsxs("div",{className:"wa-code-box",children:[s.jsxs("p",{className:"admin-hint",children:["On the phone with ",s.jsx("strong",{children:i.phone}),": WhatsApp → Linked devices → Link a device →"," ",s.jsx("strong",{children:"“Link with phone number instead”"})," → enter:"]}),s.jsx("div",{className:"wa-code",children:i.pairingCode??"… waiting for code"})]}):s.jsx("div",{className:"wa-code-box",children:s.jsx("p",{className:"admin-hint",children:"Waiting for WhatsApp to hand over a QR… (it usually appears within a few seconds)"})}),i!=null&&i.phone?null:s.jsxs("div",{className:"admin-hint",children:["Tip: on a phone, “Link with phone number instead” needs the number format"," ",s.jsx("code",{children:"918844433322"})," (country code included) — enter it below instead of scanning."]}),i!=null&&i.error?s.jsx("div",{className:"admin-row-msg admin-row-msg-err",children:i.error}):null,t&&e?s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:b,disabled:d,children:d?"⏳…":"⏹ Cancel pairing"}):null]}):s.jsxs("div",{className:"wa-actions",children:[t&&e?i!=null&&i.paired?s.jsxs("div",{className:"wa-action-row",children:[s.jsx("button",{className:"admin-refresh-btn wa-unpair-btn",type:"button",onClick:x,disabled:d,children:d?"⏳…":"🗑 Unpair (remove session)"}),s.jsx("span",{className:"admin-hint",children:"Removes creds.json — you will need to scan a QR again."})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"wa-action-row",children:[s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>y(!1),disabled:d,children:d?"⏳…":"🔳 Pair with a QR"}),s.jsx("span",{className:"admin-hint",children:"Scans from the phone you want to link."})]}),s.jsxs("div",{className:"wa-action-row wa-phone-row",children:[s.jsx("input",{type:"text",className:"wa-phone-input",value:c,onChange:w=>u(w.target.value),placeholder:"or pair with a number — e.g. 918844433322",disabled:d,maxLength:16}),s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>y(!0),disabled:d||!c.trim(),children:"Pair by number"})]})]}):null,k==="failed"||k==="error"||k==="cancelled"?s.jsx("div",{className:"admin-row-msg admin-row-msg-err",children:(i==null?void 0:i.error)||(k==="cancelled"?"Pairing cancelled.":"Pairing failed — try again.")}):null,e?t?null:s.jsx("div",{className:"admin-row-msg",children:"Your role can view pairing status but not change it (requires admin or operator)."}):s.jsx("div",{className:"admin-row-msg",children:"Log in (admin or operator) to pair, cancel, or unpair."}),h?s.jsx("div",{className:`admin-row-msg${h.kind==="ok"?"":" admin-row-msg-err"}`,children:h.text}):null]}),s.jsxs("div",{className:"wa-contacts",children:[s.jsxs("div",{className:"wa-contacts-head",children:[s.jsx("span",{className:"wa-panel-title",children:"📇 Send-by-name contacts"}),s.jsxs("span",{className:"admin-hint",children:[Object.keys(o).length," mapped"]})]}),s.jsxs("p",{className:"admin-hint",children:["These names are for ",s.jsx("strong",{children:"sending messages by name"})," (e.g."," ",s.jsx("code",{children:'buff gateway send whatsapp:Name "…"'}),") — they do"," ",s.jsx("strong",{children:"NOT"})," let these numbers trigger the agent."]}),s.jsx("div",{className:"hub-alias-list",children:Object.keys(o).length===0?s.jsxs("span",{className:"admin-hint",children:["(none — add one with ",s.jsx("code",{children:"buff whatsapp contact add <Name> <number>"}),")"]}):Object.entries(o).map(([w,_])=>s.jsxs("div",{className:"hub-alias-row",children:[s.jsx("span",{className:"hub-chip",children:w}),s.jsxs("span",{className:"admin-hint",children:["→ ",r?_:oM(_)]})]},w))}),s.jsxs("p",{className:"admin-hint",style:{marginTop:8},children:["To let a number ",s.jsx("strong",{children:"trigger the agent"})," (respond to its messages), add it to the"," ",s.jsx("strong",{children:"verified list"})," in the ",s.jsx("strong",{children:"Permissions tab above"}),", or run"," ",s.jsx("code",{children:"buff config gateway allow whatsapp user <number>"}),"."]})]})]})}function vse({canWrite:e,sessionExpired:t,mode:n="grid"}){const[r,i]=E.useState(null),[a,o]=E.useState(null),[l,c]=E.useState(null),[u,d]=E.useState(null),[f,h]=E.useState(null),[p,g]=E.useState(0),[m,v]=E.useState({}),[y,b]=E.useState(!1),[x,k]=E.useState(null),S=E.useRef(!0),w=E.useCallback(async()=>{const L=await ee.getPlatformConfigs();S.current&&i(L)},[t]);E.useEffect(()=>(w(),()=>{S.current=!1}),[w]);const _=async(L,I)=>{c(L),d(null);const z=await ee.setPlatformConfig(L,I);if(S.current){if(c(null),z.unauthorized||z.forbidden){t(z.error);return}d({kind:z.ok?"ok":"err",text:z.ok?"Saved — transport active.":z.error||"Save failed."}),z.ok&&(o(null),w())}},N=async L=>{if(!window.confirm(`Remove ${L} transport config? Tokens will be deleted from ~/.buff/.env.`))return;c(L),d(null);const I=await ee.removePlatformConfig(L);if(S.current){if(c(null),I.unauthorized||I.forbidden){t(I.error);return}d({kind:I.ok?"ok":"err",text:I.ok?"Removed.":I.error||"Remove failed."}),I.ok&&w()}},C={telegram:{steps:["Open Telegram and search for @BotFather","Send /newbot to BotFather and follow the prompts",'Give your bot a name (e.g. "My Agent Bot")','Give your bot a username (must end with "bot", e.g. "my_agent_bot")',"BotFather will give you a token — paste it in the field below","Open your bot in Telegram and send it a message (e.g. /start)"],postSetup:["Start the gateway: buff gateway start (or from the Gateway tab)","Open your bot in Telegram and send a message — the agent replies!"]},discord:{steps:["Go to https://discord.com/developers/applications",'Click "New Application" → give it a name → Create','Go to "Bot" in the left sidebar → click "Add Bot"','Under "Token", click "Copy" to copy the bot token','Enable "Message Content Intent" under Privileged Gateway Intents',"Invite the bot to your server with the OAuth2 URL generator"],postSetup:["Start the gateway: buff gateway start","Mention the bot in a Discord channel or send it a DM","The agent will reply automatically!"]},slack:{steps:["Go to https://api.slack.com/apps",'Click "Create New App" → "From scratch"',"Add Bot Token Scopes: chat:write, im:read, im:write","Install the app to your workspace","Copy the Bot User OAuth Token (starts with xoxb-)"],postSetup:["Start the gateway: buff gateway start","DM the bot or mention it in a channel","The agent will reply automatically!"]},email:{steps:["You need an SMTP relay (Gmail, SendGrid, Mailgun, etc.)","For Gmail: use smtp.gmail.com:587 with an App Password","For SendGrid/Mailgun: get SMTP credentials from their dashboard"],postSetup:["Start the gateway: buff gateway start","Send an email to the configured address","The agent will reply via email!"]}},T=L=>{e&&(h(L),g(0),v(Object.fromEntries(L.envVars.map(I=>[I.varName,I.value]))),k(null))},$=async()=>{if(!f||!e)return;b(!0),k(null);const L=await ee.setPlatformConfig(f.platform,m);if(b(!1),L.unauthorized||L.forbidden){t(L.error);return}L.ok?(k({kind:"ok",text:"✅ Token saved! The transport is now active."}),w()):k({kind:"err",text:L.error||"Save failed."})};if(r===null)return s.jsx("div",{className:"empty-state",children:"Loading platform transports…"});const R=f?C[f.platform]:null;return n==="table"?s.jsxs(s.Fragment,{children:[f&&R?s.jsx("div",{className:"wizard-overlay",onClick:()=>h(null),children:s.jsxs("div",{className:"wizard-modal",onClick:L=>L.stopPropagation(),children:[s.jsxs("div",{className:"wizard-header",children:[s.jsx("span",{className:"wizard-icon",children:"🚀"}),s.jsxs("span",{className:"wizard-title",children:["Getting Started: ",f.label]}),s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>h(null),children:"✕"})]}),s.jsx("div",{className:"wizard-body",children:p===0?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"wizard-section-title",children:"📋 Steps to create your bot:"}),s.jsx("ol",{className:"wizard-steps",children:R.steps.map((L,I)=>s.jsx("li",{children:L},I))}),s.jsxs("div",{className:"wizard-nav",children:[s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>g(1),children:"I have my token →"}),f.setupUrl?s.jsx("a",{href:f.setupUrl,target:"_blank",rel:"noopener noreferrer",className:"admin-mini-btn platform-docs-link",children:"📖 Docs"}):null]})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"wizard-section-title",children:"🔑 Paste your token:"}),f.envVars.map(L=>s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:L.prompt}),s.jsx("input",{type:L.secret?"password":"text",value:m[L.varName]??"",onChange:I=>v(z=>({...z,[L.varName]:I.target.value})),placeholder:L.secret?"••••••••":"value",autoComplete:"off",spellCheck:!1,autoFocus:!0})]},L.varName)),x?s.jsx("div",{className:`admin-row-msg${x.kind==="ok"?"":" admin-row-msg-err"}`,children:x.text}):null,s.jsxs("div",{className:"wizard-nav",children:[s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>g(0),children:"← Back"}),s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void $(),disabled:y||!e,children:y?"⏳ Saving…":"💾 Save token"})]}),(x==null?void 0:x.kind)==="ok"?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"wizard-section-title",children:"📋 Next steps:"}),s.jsx("ol",{className:"wizard-steps",children:R.postSetup.map((L,I)=>s.jsx("li",{children:L},I))})]}):null]})})]})}):null,u?s.jsx("div",{className:`admin-row-msg${u.kind==="ok"?"":" admin-row-msg-err"}`,children:u.text}):null,s.jsx("div",{className:"platform-config-table-wrapper",children:s.jsxs("table",{className:"platform-config-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Platform"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Configuration"}),s.jsx("th",{children:"CLI Command"})]})}),s.jsx("tbody",{children:r.map(L=>s.jsxs(W.Fragment,{children:[s.jsxs("tr",{className:`platform-config-row ${L.configured?"configured":""}`,children:[s.jsxs("td",{className:"platform-config-name",children:[s.jsx("span",{className:"hub-platform-label",children:L.label}),s.jsx("span",{className:"hub-card-id",children:L.platform})]}),s.jsxs("td",{children:[s.jsx("span",{className:`status-dot ${L.configured?"connected":"reconnecting"}`}),s.jsx("span",{className:"platform-config-status-text",children:L.configured?"Active":"Not configured"})]}),s.jsxs("td",{className:"platform-config-actions",children:[L.configured?null:s.jsx("button",{type:"button",className:"wizard-start-btn",onClick:()=>T(L),disabled:!e,children:"🚀 Getting Started"}),L.setupUrl?s.jsx("a",{href:L.setupUrl,target:"_blank",rel:"noopener noreferrer",className:"admin-mini-btn platform-docs-link",children:"📖 Docs"}):null,s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>o(a===L.platform?null:L.platform),disabled:!e,children:a===L.platform?"▴ Close":L.configured?"✎ Edit":"⚙ Configure"}),L.configured?s.jsx("button",{type:"button",className:"admin-mini-btn contact-delete-btn",onClick:()=>void N(L.platform),disabled:!e,children:"🗑️"}):null]}),s.jsx("td",{className:"platform-config-cli",children:s.jsxs("code",{children:["buff gateway setup ",L.platform]})})]}),a===L.platform?s.jsx("tr",{className:"platform-config-expanded",children:s.jsx("td",{colSpan:4,children:s.jsxs("div",{className:"platform-config-form",children:[L.envVars.map(I=>s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:I.prompt}),s.jsx("input",{type:I.secret?"password":"text",value:I.value,readOnly:!0,className:"platform-config-readonly",placeholder:I.secret?"••••••••":"value"})]},I.varName)),s.jsxs("p",{className:"admin-hint",children:["Tokens are in ",s.jsx("code",{children:"~/.buff/.env"})," — edit there or use the wizard above."]})]})})}):null]},L.platform))})]})})]}):s.jsxs(s.Fragment,{children:[f&&R?s.jsx("div",{className:"wizard-overlay",onClick:()=>h(null),children:s.jsxs("div",{className:"wizard-modal",onClick:L=>L.stopPropagation(),children:[s.jsxs("div",{className:"wizard-header",children:[s.jsx("span",{className:"wizard-icon",children:"🚀"}),s.jsxs("span",{className:"wizard-title",children:["Getting Started: ",f.label]}),s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>h(null),children:"✕"})]}),s.jsx("div",{className:"wizard-body",children:p===0?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"wizard-section-title",children:"📋 Steps to create your bot:"}),s.jsx("ol",{className:"wizard-steps",children:R.steps.map((L,I)=>s.jsx("li",{children:L},I))}),s.jsxs("div",{className:"wizard-nav",children:[s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>g(1),children:"I have my token →"}),f.setupUrl?s.jsx("a",{href:f.setupUrl,target:"_blank",rel:"noopener noreferrer",className:"admin-mini-btn platform-docs-link",children:"📖 Open docs in new tab"}):null]})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"wizard-section-title",children:"🔑 Paste your token:"}),f.envVars.map(L=>s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:L.prompt}),s.jsx("input",{type:L.secret?"password":"text",value:m[L.varName]??"",onChange:I=>v(z=>({...z,[L.varName]:I.target.value})),placeholder:L.secret?"••••••••":"value",autoComplete:"off",spellCheck:!1,autoFocus:!0})]},L.varName)),x?s.jsx("div",{className:`admin-row-msg${x.kind==="ok"?"":" admin-row-msg-err"}`,children:x.text}):null,s.jsxs("div",{className:"wizard-nav",children:[s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>g(0),children:"← Back"}),s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void $(),disabled:y||!e,children:y?"⏳ Saving…":"💾 Save token"})]}),(x==null?void 0:x.kind)==="ok"?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"wizard-section-title",children:"📋 Next steps:"}),s.jsx("ol",{className:"wizard-steps",children:R.postSetup.map((L,I)=>s.jsx("li",{children:L},I))})]}):null]})})]})}):null,s.jsxs("div",{className:"platform-config",children:[s.jsx("h3",{className:"section-subtitle",children:"⚙️ Platform transports (buff config gateway)"}),u?s.jsx("div",{className:`admin-row-msg${u.kind==="ok"?"":" admin-row-msg-err"}`,children:u.text}):null,s.jsx("div",{className:"hub-platform-grid",children:r.map(L=>s.jsx(bse,{entry:L,canWrite:e,busy:l===L.platform,expanded:a===L.platform,onToggle:()=>o(a===L.platform?null:L.platform),onSave:I=>void _(L.platform,I),onRemove:()=>void N(L.platform),onStartWizard:()=>T(L)},L.platform))}),s.jsxs("p",{className:"admin-hint",children:["Tokens are written to ",s.jsx("code",{children:"~/.buff/.env"})," (loaded by both the CLI and this dashboard at startup) — no env vars to hand-export. The WhatsApp personal bridge is configured separately above via QR/code pairing."]})]})]})}function bse(e){const{entry:t,canWrite:n,busy:r,expanded:i,onToggle:a,onSave:o,onRemove:l,onStartWizard:c}=e,[u,d]=E.useState(()=>Object.fromEntries(t.envVars.map(h=>[h.varName,h.value]))),f=(h,p)=>{d(g=>({...g,[h]:p}))};return s.jsxs("div",{className:`hub-platform${t.configured?" configured":""}`,children:[s.jsxs("div",{className:"hub-platform-head",children:[s.jsx("span",{className:`status-dot ${t.configured?"connected":"reconnecting"}`}),s.jsx("span",{className:"hub-platform-label",children:t.label}),s.jsx("span",{className:"hub-card-id",children:t.platform}),t.configured?null:s.jsx("button",{type:"button",className:"wizard-start-btn",onClick:c,disabled:!n,title:"Step-by-step setup wizard",children:"🚀 Getting Started"}),t.setupUrl?s.jsx("a",{href:t.setupUrl,target:"_blank",rel:"noopener noreferrer",className:"admin-mini-btn platform-docs-link",title:"Setup documentation",children:"📖 Docs"}):null,s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:a,disabled:!n,children:i?"▴ Collapse":t.configured?"✎ Edit":"⚙ Configure"})]}),!i&&t.setupHint&&!t.configured?s.jsx("div",{className:"platform-setup-hint",children:t.setupHint}):null,i?s.jsxs("div",{className:"platform-config-form",children:[t.setupHint?s.jsx("div",{className:"platform-setup-hint",children:t.setupHint}):null,t.envVars.map(h=>s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:h.prompt}),s.jsx("input",{type:h.secret?"password":"text",value:u[h.varName]??"",onChange:p=>f(h.varName,p.target.value),placeholder:h.secret?"••••••••":"value",autoComplete:"off",spellCheck:!1,maxLength:512})]},h.varName)),s.jsxs("div",{className:"platform-config-actions",children:[s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>o(u),disabled:r||!n,children:r?"⏳ Saving…":"💾 Save"}),t.configured?s.jsx("button",{type:"button",className:"hub-remove-btn",onClick:l,disabled:r||!n,children:"🗑 Remove"}):null]})]}):s.jsx("div",{className:"hub-platform-env",children:t.envVars.map(h=>s.jsxs("div",{children:[s.jsx("code",{children:h.varName})," ",h.set?"✓ set":"— unset"]},h.varName))})]})}const xse=[{id:"tools",label:"Tools",icon:"🧰"},{id:"channels",label:"Channels",icon:"📡"},{id:"conversations",label:"Conversations",icon:"💬"},{id:"artifacts",label:"Artifacts",icon:"📦"},{id:"skills",label:"Skills",icon:"🧠"}],wse={pending:"⏳ pending",sent:"✅ sent",failed:"❌ failed"};function Sse(){var F0,U0,W0,H0,G0,q0,K0,V0,Y0;const[e,t]=E.useState("tools"),[n,r]=E.useState(null),[i,a]=E.useState(!0),[o,l]=E.useState(null),[c,u]=E.useState(!1),[d,f]=E.useState(null),[h,p]=E.useState(!1),[g,m]=E.useState(null),[v,y]=E.useState(null),[b,x]=E.useState(""),[k,S]=E.useState(""),[w,_]=E.useState(null),[N,C]=E.useState(!1),[T,$]=E.useState(null),[R,L]=E.useState(null),[I,z]=E.useState({}),[D,F]=E.useState(""),[O,P]=E.useState(""),[A,Y]=E.useState(!1),[K,M]=E.useState(null),[le,be]=E.useState(!1),[me,Pe]=E.useState({}),[H,X]=E.useState(!1),[oe,ce]=E.useState(null),[Z,_e]=E.useState({}),[we,Ne]=E.useState({}),[ge,Be]=E.useState({}),[pe,Ct]=E.useState(!1),[We,Oe]=E.useState(null),[Ze,Me]=E.useState(""),[Qt,$t]=E.useState(null),[U,V]=E.useState(!1),[se,fe]=E.useState(new Map),[Se,Qe]=E.useState(new Set),[Lt,Ot]=E.useState(!1),[jn,xt]=E.useState([]),[dt,G]=E.useState(""),[he,Ie]=E.useState(null),[Re,Cr]=E.useState(""),[Jt,An]=E.useState([]),[ys,zp]=E.useState(0),[vs,bs]=E.useState(0),[Ni,xs]=E.useState(!0),[ze,ws]=E.useState(!1),[Xr,Ht]=E.useState(!1),ji=20,Ai=E.useRef(null),Ti=E.useCallback(async(j=!1)=>{if(ze)return;const q=j?0:vs;ws(!0);try{const ne=await ee.fetchGatewayConversations({offset:q,limit:ji,q:Ze||void 0});ne.ok&&ne.conversations&&(An(re=>j?ne.conversations:[...re,...ne.conversations]),zp(ne.total??0),bs(q+ne.conversations.length),xs(ne.hasMore??!1))}catch{}ws(!1)},[ze,vs,Ze]);E.useEffect(()=>{e==="conversations"&&!Xr&&!ze&&(Ht(!0),Ti(!0))},[e,Xr,ze,Ti]),E.useEffect(()=>{const j=Ai.current;if(!j)return;const q=new IntersectionObserver(ne=>{var re;(re=ne[0])!=null&&re.isIntersecting&&Ni&&!ze&&Ti(!1)},{threshold:.1});return q.observe(j),()=>q.disconnect()},[Ni,ze,Ti]),E.useEffect(()=>{const j=setTimeout(()=>{e==="conversations"&&Xr&&(An([]),bs(0),xs(!0),Ti(!0))},300);return()=>clearTimeout(j)},[Ze]),E.useEffect(()=>ee.onTypingEvent(q=>{fe(ne=>{const re=new Map(ne),de=`${q.platform}:${q.channelId}`;return q.typing?re.set(de,{platform:q.platform,channelId:q.channelId,startedAt:Date.now()}):re.delete(de),re})}),[]);const Fp=E.useCallback((j,q)=>{q.stopPropagation(),Qe(ne=>{const re=new Set(ne);return re.has(j)?re.delete(j):re.add(j),re})},[]),cl=E.useCallback(()=>{Qe(j=>j.size===Jt.length?new Set:new Set(Jt.map(q=>q.key)))},[Jt]),Ss=E.useCallback(async()=>{if(Se.size!==0){Ot(!0);try{await ee.exportGatewayConversations([...Se])}catch{}Ot(!1)}},[Se]);E.useEffect(()=>{e==="conversations"&&ee.getAllConversationTags().then(j=>{j.ok&&j.tags&&xt(j.tags)})},[e]);const Up=E.useCallback(async(j,q)=>{if(!q.trim())return;(await ee.addConversationTag(j,q.trim())).ok&&(An(re=>re.map(de=>de.key===j?{...de,tags:[...de.tags??[],q.trim().toLowerCase()]}:de)),xt(re=>re.includes(q.trim().toLowerCase())?re:[...re,q.trim().toLowerCase()].sort())),Ie(null),Cr("")},[]),Cu=E.useCallback(async(j,q)=>{(await ee.removeConversationTag(j,q)).ok&&An(re=>re.map(de=>de.key===j?{...de,tags:(de.tags??[]).filter(Te=>Te!==q)}:de))},[]),Wp=E.useCallback((j,q)=>{q.stopPropagation();const ne=j.contactName||j.channelId,re=[`Conversation with ${ne} (${j.platform})`,`Exported: ${new Date().toLocaleString()}`,`Messages: ${j.messageCount}`,"─".repeat(50),""];if(j.messages)for(const ht of j.messages){const xe=ht.role==="user"?ne:"Agent",Nt=new Date(ht.ts).toLocaleString();re.push(`[${Nt}] ${xe}:`),re.push(ht.content),re.push("")}const de=new Blob([re.join(`
|
|
135
135
|
`)],{type:"text/plain;charset=utf-8"}),Te=URL.createObjectURL(de),it=document.createElement("a");it.href=Te,it.download=`conversation-${j.platform}-${j.channelId.replace(/[^\w]/g,"_")}-${new Date().toISOString().slice(0,10)}.txt`,document.body.appendChild(it),it.click(),document.body.removeChild(it),URL.revokeObjectURL(Te)},[]),Hp=E.useCallback((j,q)=>{q.stopPropagation();const ne=j.contactName||j.channelId,re=j.messages??[],de=`<!DOCTYPE html>
|
|
136
136
|
<html>
|
|
137
137
|
<head>
|
|
@@ -204,4 +204,4 @@ ${r}`);return n&&t.push(n),t}function kge(e){return/(^|\n)\s*(PASS|FAIL|✅|❌|
|
|
|
204
204
|
`);return s.jsxs("div",{className:`chat-task-card${n?" chat-task-running":e.status==="done"?" chat-task-ok":" chat-task-err"}`,children:[s.jsxs("div",{className:"chat-task-head",children:[s.jsx("span",{className:"chat-task-icon",children:"⚙️"}),s.jsx("code",{className:"chat-task-cmd",children:e.command}),s.jsx("span",{className:"chat-task-status",title:e.status,children:Oge[e.status]}),!n&&e.exitCode!==null?s.jsxs("span",{className:"chat-task-exit",children:["exit ",e.exitCode]}):null,!n&&e.durationMs!==null?s.jsxs("span",{className:"chat-task-dur",children:[e.durationMs,"ms"]}):null,r?s.jsx(D0,{text:r,label:"task output"}):null,n&&t?s.jsx("button",{className:"admin-mini-btn",type:"button",onClick:t,children:"⏹ Cancel"}):null]}),s.jsx("pre",{className:"chat-task-logs",role:"log",children:e.logs.length>0?e.logs.map((i,a)=>{const o=e.logs[a-1],l=o&&o.stream!==i.stream,c=qN(i.text)||" ";return s.jsxs("div",{children:[l?s.jsx("div",{className:`chat-task-log-sep chat-task-log-sep-${i.stream}`,"aria-hidden":"true",children:i.stream}):null,s.jsx("div",{className:`chat-task-log chat-task-log-${i.stream}`,children:c})]},a)}):s.jsx("div",{className:"admin-hint",children:n?"Waiting for output…":"(no output)"})})]})}function VN({draft:e,onAccept:t,onReject:n,onEdit:r}){const i=e.status??"pending",a=e.markdown.split(`
|
|
205
205
|
`),o=a.findIndex(c=>c.startsWith("# "))>=0?a.findIndex(c=>c.startsWith("# ")):0,l=a.slice(o,o+14).join(`
|
|
206
206
|
`);return s.jsxs("div",{className:`chat-draft-card${i==="saved"?" chat-draft-saved":""}${i==="rejected"?" chat-draft-rejected":""}`,children:[s.jsxs("div",{className:"chat-draft-head",children:[s.jsx("span",{className:"chat-draft-icon",children:"🧠"}),s.jsxs("span",{className:"chat-draft-title",children:["New skill draft: ",e.name]}),s.jsx("span",{className:"chat-draft-meta",children:"pending your review"})]}),s.jsx("p",{className:"chat-draft-desc",children:e.description}),s.jsx("pre",{className:"chat-draft-body",children:l}),i==="saving"?s.jsx("div",{className:"admin-hint",children:"Saving…"}):i==="saved"?s.jsx("div",{className:"admin-hint",children:"✅ Saved — the skill is live: load it in chat or see it in the Agent Hub Skills tab."}):i==="rejected"?s.jsx("div",{className:"admin-hint",children:"🗑️ Rejected — the draft was discarded, nothing was saved."}):s.jsxs("div",{className:"chat-draft-actions",children:[s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>t(e.name),children:"✅ Accept"}),s.jsx("button",{className:"admin-mini-btn",type:"button",onClick:()=>r(e.name),children:"✏️ Edit"}),s.jsx("button",{className:"admin-mini-btn",type:"button",onClick:()=>n(e.name),children:"↩ Reject"})]})]})}function $ge({request:e,onSave:t}){const[n,r]=E.useState({}),[i,a]=E.useState(!1),o=e.missing.every(u=>{var d;return(d=n[u])==null?void 0:d.trim()}),l=e.missing.filter(u=>e.persisted[u]),c=e.missing.filter(u=>!e.persisted[u]);return s.jsxs("div",{className:"chat-secret-card",children:[s.jsxs("div",{className:"chat-secret-head",children:[s.jsx("span",{className:"chat-secret-icon",children:"🔐"}),s.jsxs("span",{className:"chat-secret-title",children:[e.skillName," needs environment variables"]})]}),l.length>0?s.jsxs("div",{className:"chat-secret-persisted",children:["Already configured: ",l.map(u=>s.jsx("code",{children:u},u)).join(", ")]}):null,c.length>0&&!i?s.jsxs("div",{className:"chat-secret-fields",children:[c.map(u=>s.jsxs("div",{className:"chat-secret-row",children:[s.jsxs("label",{className:"chat-secret-label",htmlFor:`secret-${u}`,children:[u,":"]}),s.jsx("input",{id:`secret-${u}`,className:"chat-secret-input",type:"password",placeholder:`Enter ${u} value…`,value:n[u]??"",onChange:d=>r(f=>({...f,[u]:d.target.value}))})]},u)),s.jsx("button",{className:"admin-refresh-btn",type:"button",disabled:!o,onClick:()=>{t(n),a(!0)},children:"💾 Save to ~/.buff/.env"})]}):i?s.jsx("div",{className:"admin-hint",children:"✅ Saved — the skill will pick up these values on next load."}):s.jsx("div",{className:"admin-hint",children:"All required env vars are already configured."})]})}function Lge({result:e}){const[t,n]=E.useState(!1),r=e.success?"✅":"❌",i=e.success?"Success":`Failed (exit ${e.exitCode})`,a=e.success?"chat-exec-success":"chat-exec-failure",o=new Date(e.timestamp).toLocaleTimeString();return s.jsxs("div",{className:`chat-exec-card ${a}`,children:[s.jsxs("div",{className:"chat-exec-head",onClick:()=>n(!t),style:{cursor:"pointer"},children:[s.jsx("span",{className:"chat-exec-icon",children:"📜"}),s.jsx("span",{className:"chat-exec-title",children:e.skillName}),s.jsxs("span",{className:"chat-exec-status",children:[r," ",i]}),s.jsxs("span",{className:"chat-exec-meta",children:[e.runtime," · ",e.durationMs,"ms · ",o]}),s.jsx("span",{className:"chat-exec-expand",children:t?"▼":"▶"})]}),t&&s.jsxs("div",{className:"chat-exec-body",children:[e.stdout&&s.jsxs("div",{className:"chat-exec-section",children:[s.jsx("div",{className:"chat-exec-section-title",children:"stdout"}),s.jsx("pre",{className:"chat-exec-output",children:e.stdout})]}),e.stderr&&s.jsxs("div",{className:"chat-exec-section chat-exec-stderr",children:[s.jsx("div",{className:"chat-exec-section-title",children:"stderr"}),s.jsx("pre",{className:"chat-exec-output",children:e.stderr})]}),s.jsxs("div",{className:"chat-exec-details",children:[s.jsxs("span",{children:["Runtime: ",e.runtime]}),s.jsxs("span",{children:["Exit code: ",e.exitCode]}),s.jsxs("span",{children:["Duration: ",e.durationMs,"ms"]})]})]})]})}function Dge(e){return e==="done"?"✅":e==="running"?"🔄":e==="blocked"?"⛔":"⬜"}function YN({plan:e}){const t=e.steps.filter(n=>n.status==="done").length;return s.jsxs("div",{className:"chat-plan-card",children:[s.jsxs("div",{className:"chat-plan-head",children:[s.jsx("span",{className:"chat-plan-icon",children:"🗂️"}),s.jsx("span",{className:"chat-plan-goal",children:e.goal}),s.jsxs("span",{className:"chat-plan-count",children:[t,"/",e.steps.length," done"]})]}),s.jsx("div",{className:"chat-plan-steps",children:e.steps.map(n=>s.jsxs("div",{className:`chat-plan-step chat-plan-step-${n.status}`,children:[s.jsx("span",{className:"chat-plan-step-icon",children:Dge(n.status)}),s.jsx("span",{className:"chat-plan-step-text",children:n.description}),s.jsx("span",{className:"chat-plan-step-status",children:n.status})]},n.id))})]})}function XN({tools:e,live:t}){return!e||e.length===0?null:s.jsx("div",{className:`chat-tool-cards${t?" chat-tool-cards-live":""}`,children:e.map(n=>{const r=n.phase==="started"||n.ok===void 0,i=n.ok===!1;return s.jsxs("div",{className:`chat-tool-card${r?" chat-tool-running":i?" chat-tool-err":" chat-tool-ok"}`,children:[s.jsxs("div",{className:"chat-tool-head",children:[s.jsx("span",{className:"chat-tool-icon",children:Cge(n.tool)}),s.jsx("span",{className:"chat-tool-name",children:n.tool}),n.args?s.jsx("code",{className:"chat-tool-args",children:n.args}):null,s.jsx("span",{className:"chat-tool-status",title:r?"running":i?"failed":"done",children:r?"⏳":i?"✗":"✓"}),n.durationMs!==void 0&&!r?s.jsxs("span",{className:"chat-tool-dur",children:[n.durationMs,"ms"]}):null]}),n.error||n.result?s.jsxs("details",{className:"chat-tool-detail",children:[s.jsx("summary",{children:i?"Error":"Result"}),s.jsx("pre",{className:"chat-tool-body",children:n.error||n.result})]}):null]},n.id)})})}function kg(){try{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch{}return`chat-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Bge(e,t){const n=t.trim().toLowerCase(),r=n?e.filter(u=>`${u.title} ${u.preview} ${u.firstUser}`.toLowerCase().includes(n)):e,i=[],a=new Date,o=new Date(a.getFullYear(),a.getMonth(),a.getDate()).getTime(),l=864e5,c=[{label:"Today",match:u=>u>=o},{label:"Yesterday",match:u=>u>=o-l&&u<o},{label:"This week",match:u=>u>=o-7*l&&u<o-l},{label:"Older",match:()=>!0}];for(const u of c){const d=r.filter(f=>u.match(f.updatedAt));d.length>0&&i.push({label:u.label,items:d})}return i}function ZN(){var Mu,Ru,Iu,Pi,$u;const[e,t]=E.useState(null),[n,r]=E.useState([]),[i,a]=E.useState(""),[o,l]=E.useState(!1),[c,u]=E.useState(""),[d,f]=E.useState(null),[h,p]=E.useState([]),[g,m]=E.useState([]),[v,y]=E.useState(null),[b,x]=E.useState(null),[k,S]=E.useState(null),[w,_]=E.useState([]),[N,C]=E.useState([]),[T,$]=E.useState(null),R=E.useRef([]),L=E.useRef([]),I=E.useRef(null),z=E.useRef(null),D=E.useRef(null),[F,O]=E.useState(""),P=E.useRef(""),A=E.useRef(null),[Y,K]=E.useState(null),M=E.useRef(kg()),le=E.useRef(""),[be,me]=E.useState([]),[Pe,H]=E.useState(!0),[X,oe]=E.useState(""),[ce,Z]=E.useState(null),[_e,we]=E.useState(""),[Ne,ge]=E.useState([]),[Be,pe]=E.useState(null),[Ct,We]=E.useState(!1),Oe=E.useRef(null),Ze=E.useRef(null),[Me,Qt]=E.useState(null),[$t,U]=E.useState(null),[V,se]=E.useState([]),[fe,Se]=E.useState(""),[Qe,Lt]=E.useState(""),[Ot,jn]=E.useState(!1),[xt,dt]=E.useState(""),[G,he]=E.useState([]),[Ie,Re]=E.useState(null),[Cr,Jt]=E.useState(!1),[An,ys]=E.useState([]),[zp,vs]=E.useState([]),[bs,Ni]=E.useState(""),xs=E.useRef(null),ze=E.useRef(null),ws=E.useRef(null),Xr=E.useRef(null),[Ht,ji]=E.useState(null),[Ai,Ti]=E.useState(new Set);E.useEffect(()=>{ee.fetchAdminAuthStatus().then(B=>{t(B?{configured:B.configured,authenticated:B.authenticated,role:B.role}:{configured:!1,authenticated:!1,role:null})})},[]),E.useEffect(()=>{var B,te;try{(te=(B=ws.current)==null?void 0:B.scrollTo)==null||te.call(B,{top:ws.current.scrollHeight})}catch{}},[n,o,h]),E.useEffect(()=>()=>{var B;(B=ze.current)==null||B.call(ze),ze.current=null},[]);const Fp=E.useCallback(async B=>{var Ee,Jr;(Ee=ze.current)==null||Ee.call(ze),ze.current=null;const te=await ee.getChatSession(B);if(!te)return;M.current=B,r(te.turns.map(qt=>({role:qt.role,content:qt.content,...qt.role==="assistant"?{followups:[],artifacts:GN(qt.content)}:{}}))),p([]),R.current=[],m([]),L.current=[],y(null),I.current=null,x(null),z.current=null,S(null),D.current=null,P.current="",O(""),K(null),u(""),f(null),$(null),ji(null),H(!0);const J=te.projectPath;if(J){if(U(J),(Me==null?void 0:Me.path)===J)return;(Jr=Xr.current)==null||Jr.call(Xr,J)}else U(null)},[Me]),cl=E.useCallback(()=>{var B;(B=ze.current)==null||B.call(ze),ze.current=null,M.current=kg(),U(null),r([]),p([]),R.current=[],m([]),L.current=[],y(null),I.current=null,x(null),z.current=null,S(null),D.current=null,P.current="",O(""),K(null),u(""),f(null),$(null),ji(null),ge([]),pe(null),a(""),H(!0)},[]),Ss=E.useCallback(B=>{ge(te=>[...te,B].slice(-10))},[]),Up=E.useCallback(B=>{ge(te=>te.filter((J,Ee)=>Ee!==B))},[]),Cu=E.useCallback(async B=>{if(!B)return;if(B.size>KN){u(`Attachment "${B.name}" is too large (max ${Math.round(KN/1024)} KB).`);return}const te=await B.text();Ss({name:B.name,content:te,kind:"file"})},[Ss]),Wp=E.useCallback(B=>{const te=B.currentTarget,J=B.clipboardData.getData("text")||"";J.length>=Tge&&(Ze.current={start:te.selectionStart,end:te.selectionEnd},pe({text:J}))},[]),Hp=E.useCallback(()=>{const B=Be;if(!B)return;const te=Ze.current;a(J=>te?J.slice(0,te.start)+J.slice(te.end):J),Ss({name:"pasted-text.txt",content:B.text,kind:"paste"}),pe(null),Ze.current=null},[Be,Ss]),ul=E.useCallback(B=>{Z(B.id),we(B.title==="(untitled conversation)"?"":B.title)},[]),Ou=E.useCallback(async B=>{const te=await ee.renameChatSession(B,_e);te.ok?me(J=>J.map(Ee=>Ee.id===B?{...Ee,title:_e.trim()||Ee.title}:Ee)):u(te.error||"Could not rename the session."),Z(null),we("")},[_e]),Pu=E.useCallback(async B=>{const te=await ee.deleteChatSession(B);te.ok?(me(J=>J.filter(Ee=>Ee.id!==B)),M.current===B&&cl()):u(te.error||"Could not delete the session.")},[cl]),dl=(e==null?void 0:e.authenticated)===!0&&(e.role==="admin"||e.role==="operator");E.useEffect(()=>{dl&&(ee.listChatSessions().then(B=>{Array.isArray(B)&&me(B)}),ee.listProjects().then(B=>{Array.isArray(B)&&se(B)}))},[dl]);const hr=E.useCallback(async B=>{const te=B.trim();if(!te)return;Lt("");const J=await ee.attachProject(te);if(J.ok&&J.project){Qt(J.project),Se("");const Ee=await ee.listProjects();Array.isArray(Ee)&&se(Ee)}else Lt(J.error||"Could not attach that directory.")},[]);Xr.current=hr;const ks=E.useCallback(async B=>{jn(!0),Jt(!0),Ni("");const te=await ee.browseDirectories(B,{showDrives:!B});te.ok&&(dt(te.path),he(te.entries),Re(te.parent),te.drives&&ys(te.drives),te.breadcrumbs&&vs(te.breadcrumbs)),Jt(!1)},[]),xa=E.useCallback(async B=>{Jt(!0),Ni("");const te=await ee.browseDirectories(B);te.ok&&(dt(te.path),he(te.entries),Re(te.parent),te.breadcrumbs&&vs(te.breadcrumbs)),Jt(!1)},[]),Es=E.useCallback(async()=>{if(!xt)return;const B=await ee.browseDirectories(xt);B.ok&&he(B.entries)},[xt]);E.useEffect(()=>ee.onChatRetryEvent(te=>{if(te.sessionId!==M.current){ee.listChatSessions().then(J=>{Array.isArray(J)&&me(J)});return}r(J=>[...J,{role:"assistant",content:te.content}]),te.kind==="answer"&&K(null)}),[]),E.useEffect(()=>(Ot&&xt&&(xs.current=setInterval(()=>{Es()},5e3)),()=>{xs.current&&clearInterval(xs.current)}),[Ot,xt,Es]);const fl=E.useCallback(async()=>{if(typeof window<"u"&&"showDirectoryPicker"in window)try{const J=(await window.showDirectoryPicker({mode:"read"})).name;if(!J){ks();return}Lt(""),l(!0);const Ee=await ee.resolveFolder(J);l(!1),Ee.ok&&Ee.path?(Se(Ee.path),hr(Ee.path)):Lt('Folder "'+J+'" found — selecting it now. If this is wrong, type the full path below.');return}catch(te){if((te==null?void 0:te.name)==="AbortError")return}ks()},[ks,hr]),Je=E.useCallback(async(B,te)=>{var pr,Cn;const J=B.trim(),Ee=Array.isArray(te)?te:Ne,Jr=!Array.isArray(te)&&(te==null?void 0:te.skipResolve)===!0;if(!J&&Ee.length===0||o)return;if(u(""),f(null),p([]),R.current=[],m([]),L.current=[],y(null),I.current=null,x(null),z.current=null,S(null),D.current=null,r(ke=>[...ke,{role:"user",content:J,attachments:Ee.length>0?Ee:void 0}]),a(""),ge([]),pe(null),le.current=J||`[${Ee.length} attachment(s)]`,l(!0),H(!1),!Jr){const ft=((await ee.chatResolve(J)).matches??[])[0]??null;if(ft&&ft.command&&!ft.ambiguous&&ft.score>=.6){$({ask:J,top:ft}),l(!1);return}if(ft&&ft.ambiguous&&!T){$({ask:J,top:ft}),l(!1);return}}const qt=M.current,Tn=new AbortController;A.current=Tn,K(null),(pr=ze.current)==null||pr.call(ze),ze.current=ee.subscribeChat(qt,{onToken:ke=>{P.current+=ke,O(P.current)},onProgress:ke=>{R.current=[...R.current,ke],p(R.current)},onQuestion:ke=>{ji(ke),Ti(new Set)},onTool:ke=>{const Fe=[...L.current],ft=Fe.findIndex(on=>on.id===ke.id),wt={id:ke.id,tool:ke.tool,phase:ke.phase,args:ke.args,ok:ke.ok,result:ke.result,error:ke.error,durationMs:ke.durationMs};ft>=0?Fe[ft]=wt:Fe.push(wt),L.current=Fe,m(Fe)},onPlan:ke=>{const Fe={goal:ke.goal,steps:ke.steps,revision:ke.revision};I.current=Fe,y(Fe)},onDiff:ke=>{const Fe={files:ke.files,summary:ke.summary};z.current=Fe,x(Fe)},onSkillDraft:ke=>{const Fe={name:ke.name,description:ke.description,markdown:ke.markdown,updatedAt:ke.updatedAt,status:"pending"};D.current=Fe,S(Fe)},onSecretRequest:ke=>{_(Fe=>{const ft=Fe.findIndex(wt=>wt.skillName===ke.skillName);if(ft>=0){const wt=[...Fe];return wt[ft]=ke,wt}return[...Fe,ke]})},onExecutionResult:ke=>{C(Fe=>[...Fe,ke])}});const en=await ee.chatSend(qt,J||`(see ${Ee.length} attachment${Ee.length===1?"":"s"})`,{projectPath:Me==null?void 0:Me.path,attachments:Ee.map(ke=>({name:ke.name,content:ke.content,kind:ke.kind}))},Tn.signal);if(A.current=null,(Cn=ze.current)==null||Cn.call(ze),ze.current=null,P.current="",O(""),en.ok){f(en.generationFailed?null:`${en.provider??"provider"}${en.model?` / ${en.model}`:" (auto-routed)"}`),K(en.generationFailed&&!en.retryQueued?J:null);const ke=en.content||"(the agent produced no text — try rephrasing)";r(Fe=>[...Fe,{role:"assistant",content:ke,error:en.generationFailed,followups:en.followups,steps:R.current,tools:L.current,plan:I.current,diff:z.current,draft:D.current,artifacts:GN(ke)}])}else Tn.signal.aborted?(u(""),K(null)):en.unauthorized?(t(ke=>ke&&{...ke,authenticated:!1}),u("Session expired — log in again to chat.")):(u(en.error||"The agent could not answer — check that a provider API key is set for the dashboard process."),K(J));l(!1),H(!0)},[o,Me,Ne]),hl=E.useCallback(()=>{var B;(B=A.current)==null||B.abort()},[]),wa=E.useCallback(async B=>{S(J=>J&&{...J,status:"saving"});const te=await ee.skillDraftAccept(B);S(J=>J&&{...J,status:te.ok?"saved":"error"}),te.ok||u(te.error||"Could not accept the draft.")},[]),pl=E.useCallback(async B=>{const te=await ee.skillDraftReject(B);te.ok?S(J=>J&&{...J,status:"rejected"}):u(te.error||"Could not reject the draft.")},[]),ml=E.useCallback(B=>{Je(`Revise the skill draft "${B}" — improve it per your best judgment and present it again.`)},[Je]),Ci=E.useCallback(async B=>{const te=await ee.saveSecrets(B);if(!te.ok){u(te.error||"Could not save secrets.");return}const J=te.refused??[];J.length>0&&u(J.map(Ee=>Ee.reason==="provider-credential"?`${Ee.name} is a provider credential — set it up as a provider, skills never receive it.`:`${Ee.name} was not saved (${Ee.reason}).`).join(" "))},[]),gl=E.useCallback(async B=>{const Ee=((await ee.chatResolve(B)).matches??[])[0]??null;if(!(Ee!=null&&Ee.command)){$(null);return}$(null),l(!0);const Jr=Ee.command.split(/\s+/),qt=await ee.startTask(Jr,6e4);if(!qt.ok||!qt.task){u(qt.error||"The command could not be started."),l(!1);return}const Tn=qt.task.id,en={id:Tn,command:Ee.command,status:qt.task.status,exitCode:qt.task.exitCode,durationMs:qt.task.durationMs,logs:qt.task.logs??[]};r(ft=>[...ft,{role:"assistant",content:"",task:en}]);const pr=ft=>r(wt=>wt.map(on=>on.task&&on.task.id===Tn?{...on,task:{...on.task,...ft}}:on));let Cn=null;Cn=ee.subscribeTask(Tn,{onLog:ft=>r(wt=>wt.map(on=>on.task&&on.task.id===Tn?{...on,task:{...on.task,logs:[...on.task.logs,ft]}}:on)),onStatus:ft=>{pr({status:ft}),ft!=="running"&&(ee.getTask(Tn).then(wt=>{wt!=null&&wt.task&&pr({exitCode:wt.task.exitCode,durationMs:wt.task.durationMs,logs:wt.task.logs??[]})}),Cn==null||Cn(),l(!1))}});const ke=await ee.getTask(Tn);ke!=null&&ke.task&&pr({status:ke.task.status,exitCode:ke.task.exitCode,durationMs:ke.task.durationMs,logs:ke.task.logs??[]});const Fe=await ee.getTask(Tn);Fe!=null&&Fe.task&&Fe.task.status!=="running"&&(Cn==null||Cn(),pr({status:Fe.task.status,exitCode:Fe.task.exitCode,durationMs:Fe.task.durationMs,logs:Fe.task.logs??[]}),l(!1))},[]),Oi=E.useCallback(B=>{$(null),Je(B,{skipResolve:!0})},[Je]),_s=E.useCallback(B=>{if(B.length===0)return;const te=Me?` in the attached project ${Me.path}`:"";Je(`Commit exactly these files that I accepted on the diff card (and nothing else)${te}: ${B.join(", ")}. Show me a short confirmation before finishing.`)},[Je,Me]),Ns=E.useCallback(async B=>{await ee.cancelTask(B)},[]),Zr=E.useCallback(async B=>{const te=Ht;if(!te)return;ji(null);const J=await ee.chatRespond(M.current,te.questionId,B);J.ok||u(J.error||"The question could not be answered — try sending your message again.")},[Ht]),Qr=E.useCallback(()=>{if(!Ht)return;const B=Ht.multiSelect?[...Ai]:[...Ai][0];Ht.multiSelect?Zr({index:[...Ai]}):Zr(B!==void 0?{index:B}:{index:-1})},[Ht,Ai,Zr]),Gp=E.useCallback(()=>{Ht&&Zr({index:-1})},[Ht,Zr]),qp=E.useCallback(B=>{Ti(te=>{const J=new Set(te);return Ht!=null&&Ht.multiSelect?J.has(B)?J.delete(B):J.add(B):(J.clear(),J.add(B)),J})},[Ht]),Or=E.useCallback(async()=>{var te;(te=ze.current)==null||te.call(ze),ze.current=null,M.current=kg(),r([]),p([]),R.current=[],m([]),L.current=[],y(null),I.current=null,x(null),z.current=null,S(null),D.current=null,P.current="",O(""),K(null),u(""),f(null),$(null),ji(null);const B=await ee.listChatSessions();Array.isArray(B)&&me(B)},[]),Gt=((Mu=[...n].reverse().find(B=>{var te;return B.role==="assistant"&&!B.error&&(((te=B.followups)==null?void 0:te.length)??0)>0}))==null?void 0:Mu.followups)??[];return s.jsxs("div",{className:"panel",children:[s.jsxs("div",{className:"panel-header",children:[s.jsx("h2",{children:"💬 Chat with the agent"}),s.jsxs("div",{className:"chat-head-actions",children:[d?s.jsx("span",{className:"admin-hint",children:d}):null,s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>void Or(),disabled:o||n.length===0,children:"🗑 New conversation"})]})]}),e!=null&&e.authenticated?dl?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"chat-project-bar",children:Me?s.jsxs("div",{className:"chat-project-attached",children:[s.jsx("span",{className:"chat-project-icon",children:"📁"}),s.jsx("span",{className:"chat-project-name",children:Me.name}),s.jsxs("span",{className:"chat-project-meta",children:[Me.fileCount," files · ",Me.symbolCount," symbols",Me.truncated?" · truncated map":""]}),s.jsx("span",{className:"chat-project-path",title:Me.path,children:Me.path}),s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>Qt(null),children:"✕ detach"})]}):s.jsxs("div",{className:"chat-project-pick",children:[s.jsx("span",{className:"chat-project-icon",children:"📁"}),s.jsx("span",{className:"chat-project-hint",children:"Select Project Folder"}),V.length>0?s.jsx("span",{className:"chat-project-chips",children:V.filter(B=>B.kind!=="cwd").slice(0,3).map(B=>s.jsx("button",{type:"button",className:"chat-chip",onClick:()=>void hr(B.path),children:B.name},B.path))}):null,s.jsx("input",{className:"chat-project-input",value:fe,onChange:B=>Se(B.target.value),onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),hr(fe))},placeholder:"or type a path, e.g. ~/code/my-app",disabled:o}),s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void hr(fe),disabled:o||!fe.trim(),children:"Attach"}),s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>void fl(),title:"Pick a project folder using your system's folder picker (Finder / Explorer)",children:"🗂️ Browse"}),Qe?s.jsx("span",{className:"chat-project-error",children:Qe}):null,Ot?s.jsxs("div",{className:"chat-browse-popover",children:[s.jsxs("div",{className:"chat-browse-head",children:[s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>jn(!1),title:"Close",children:"✕"}),s.jsx("div",{className:"chat-browse-breadcrumbs",children:An.length>0&&!xt?s.jsx("span",{className:"admin-hint",children:"Select a drive or home folder:"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"chat-breadcrumb",onClick:()=>void ks(),children:"🏠"}),zp.map((B,te)=>s.jsxs("span",{children:[s.jsx("span",{className:"chat-breadcrumb-sep",children:"/"}),s.jsx("button",{type:"button",className:"chat-breadcrumb",onClick:()=>void xa(B.path),children:B.name})]},B.path))]})})]}),An.length>0&&!xt?s.jsx("div",{className:"chat-browse-drives",children:An.map(B=>s.jsx("button",{type:"button",className:"chat-browse-drive",onClick:()=>void xa(B.path),children:B.name},B.path))}):null,G.length>5?s.jsx("div",{className:"chat-browse-search",children:s.jsx("input",{type:"text",className:"chat-browse-filter",placeholder:"🔍 Filter folders…",value:bs,onChange:B=>Ni(B.target.value),autoFocus:!0})}):null,s.jsx("div",{className:"chat-browse-list",children:Cr?s.jsx("span",{className:"admin-hint",children:"Loading…"}):G.length===0?s.jsx("span",{className:"admin-hint",children:"No subdirectories found"}):G.filter(B=>!bs||B.name.toLowerCase().includes(bs.toLowerCase())).map(B=>s.jsxs("button",{type:"button",className:"chat-browse-entry",onClick:()=>void xa(B.path),children:[s.jsx("span",{className:"chat-browse-entry-icon",children:"📁"}),s.jsx("span",{className:"chat-browse-entry-name",children:B.name}),B.modified?s.jsx("span",{className:"chat-browse-entry-date",children:new Date(B.modified).toLocaleDateString()}):null]},B.path))}),s.jsxs("div",{className:"chat-browse-foot",children:[s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>void Es(),title:"Refresh folder list",children:"🔄"}),s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>{jn(!1),hr(xt)},disabled:!xt,children:"📁 Select this folder"})]})]}):null]})}),$t&&(!Me||Me.path!==$t)?s.jsxs("div",{className:"chat-session-project-banner",children:[s.jsxs("span",{children:["⚠️ This conversation was working in ",s.jsx("code",{children:$t})]}),Me?s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void hr($t),children:"📁 Switch to it"}):s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void hr($t),children:"📁 Attach it"})]}):null,s.jsxs("div",{className:"chat-layout",children:[Pe?s.jsxs("div",{className:"chat-sidebar",children:[s.jsxs("div",{className:"chat-sidebar-head",children:[s.jsx("span",{children:"📁 Sessions"}),s.jsxs("div",{className:"chat-sidebar-head-actions",children:[s.jsx("button",{type:"button",className:"chat-mini-action",title:"New chat",onClick:cl,children:"+ New"}),s.jsx("button",{type:"button",className:"chat-mini-action",title:"Collapse history",onClick:()=>H(!1),children:"▸"})]})]}),s.jsx("input",{className:"chat-session-search",placeholder:"Search conversations…",value:X,onChange:B=>oe(B.target.value)}),be.length===0?s.jsx("div",{className:"chat-sidebar-empty",children:"No past conversations yet."}):s.jsx("div",{className:"chat-sidebar-list",children:Bge(be,X).map(({label:B,items:te})=>s.jsxs("div",{className:"chat-session-group",children:[s.jsx("div",{className:"chat-session-group-label",children:B}),te.map(J=>s.jsx("div",{className:`chat-session-item${J.id===M.current?" chat-session-active":""}`,children:ce===J.id?s.jsxs("div",{className:"chat-session-rename",children:[s.jsx("input",{autoFocus:!0,value:_e,onChange:Ee=>we(Ee.target.value),onKeyDown:Ee=>{Ee.key==="Enter"&&Ou(J.id),Ee.key==="Escape"&&Z(null)},placeholder:"Session title"}),s.jsx("button",{type:"button",className:"chat-mini-action",onClick:()=>void Ou(J.id),children:"✓"})]}):s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"chat-session-main",onClick:()=>void Fp(J.id),title:J.preview||J.title,children:[s.jsx("span",{className:"chat-session-title",children:J.title}),s.jsx("span",{className:"chat-session-preview",children:J.firstUser||J.preview}),s.jsxs("span",{className:"chat-session-meta",children:[J.projectPath?`📁 ${J.projectPath.split("/").pop()} · `:"",J.turnCount," msg",J.turnCount===1?"":"s"," · ",new Date(J.updatedAt).toLocaleString()]})]}),s.jsxs("span",{className:"chat-session-actions",children:[s.jsx("button",{type:"button",className:"chat-mini-action",title:"Rename",onClick:()=>ul(J),children:"✏️"}),s.jsx("button",{type:"button",className:"chat-mini-action",title:"Delete",onClick:()=>void Pu(J.id),children:"🗑"})]})]})},J.id))]},B))})]}):s.jsx("div",{className:"chat-rail",children:s.jsx("button",{type:"button",className:"chat-rail-btn",onClick:()=>H(!0),title:"Show history",children:"📁"})}),s.jsxs("div",{className:"chat-main",children:[s.jsxs("div",{className:"chat-thread",ref:ws,role:"log","aria-live":"polite",children:[n.length===0?s.jsxs("div",{className:"empty-state",children:[s.jsx("p",{className:"empty-state-title",children:"Say anything — the agent decides what to do (answer, fix code, plan, run the pipeline)."}),s.jsxs("div",{className:"empty-state-chips",children:[s.jsx("button",{type:"button",className:"chat-chip",onClick:()=>void Je("what's the state of this project?"),children:"📋 assess this project"}),s.jsx("button",{type:"button",className:"chat-chip",onClick:()=>void Je("run the test suite"),children:"🧪 run the tests"}),s.jsx("button",{type:"button",className:"chat-chip",onClick:()=>void Je("stop the gateway"),children:"⏹ stop the gateway"}),s.jsx("button",{type:"button",className:"chat-chip",onClick:()=>void Je("load the code-assessment skill and assess this project"),children:"🧠 load the code-assessment skill"}),s.jsx("button",{type:"button",className:"chat-chip",onClick:()=>void Je("learn the workflow I just did as a skill"),children:"📚 learn a workflow as a skill"}),s.jsx("button",{type:"button",className:"chat-chip",onClick:()=>void Je("publish the current version"),children:"🚀 publish the release"})]})]}):n.map((B,te)=>s.jsxs("div",{className:`chat-bubble chat-${B.role}${B.error?" chat-error":""}`,children:[s.jsx("div",{className:"chat-bubble-role",children:B.role==="user"?"You":"🤖 Agent"}),B.role==="assistant"?s.jsx("div",{className:"chat-bubble-text",children:s.jsx(FN,{text:B.content})}):s.jsx("div",{className:"chat-bubble-text",children:B.content}),B.role==="user"&&B.attachments&&B.attachments.length>0?s.jsxs("details",{className:"chat-steps",open:B.attachments.length===1,children:[s.jsxs("summary",{children:["📎 ",B.attachments.length," attachment",B.attachments.length===1?"":"s",":"," ",B.attachments.map(J=>J.name).join(", ")]}),B.attachments.map((J,Ee)=>s.jsxs("div",{className:"chat-attach-content",children:[s.jsxs("div",{className:"admin-hint",children:[J.name," — ",J.content.length.toLocaleString()," chars"]}),s.jsx("pre",{children:J.content})]},Ee))]}):null,B.role==="assistant"&&B.diff?s.jsxs("details",{className:"chat-steps",open:!0,children:[s.jsxs("summary",{children:["Changes: ",B.diff.summary]}),s.jsx(Ad,{diff:B.diff,selectable:!0,onCommitAccepted:_s})]}):null,B.role==="assistant"&&B.artifacts&&(B.artifacts.diffs.length>0||B.artifacts.results.length>0||B.artifacts.deploys.length>0)?s.jsxs(Rge,{children:[B.artifacts.diffs.map((J,Ee)=>s.jsx("div",{"data-artifact-card":!0,tabIndex:0,role:"group","aria-label":`Diff: ${J.summary}`,className:"chat-artifact-item",children:Me?s.jsx(Ad,{diff:J,selectable:!0,onCommitAccepted:_s}):s.jsx(Ad,{diff:J,lockedHint:"Attach a project to review and commit these changes."})},`diff-${Ee}`)),B.artifacts.results.map((J,Ee)=>s.jsx("div",{"data-artifact-card":!0,tabIndex:0,role:"group","aria-label":`Result: ${J.title}`,className:"chat-artifact-item",children:s.jsx(Pge,{result:J})},`result-${Ee}`)),B.artifacts.deploys.map((J,Ee)=>s.jsx("div",{"data-artifact-card":!0,tabIndex:0,role:"group","aria-label":`Deployment: ${J.url}`,className:"chat-artifact-item",children:s.jsx(Mge,{deploy:J})},`deploy-${Ee}`))]}):null,B.role==="assistant"&&B.task?s.jsx(Ige,{task:B.task,onCancel:B.task.status==="running"?()=>void Ns(B.task.id):void 0}):null,B.role==="assistant"&&B.draft?s.jsxs("details",{className:"chat-steps",open:!0,children:[s.jsxs("summary",{children:["Skill draft: ",B.draft.name]}),s.jsx(VN,{draft:B.draft,onAccept:wa,onReject:pl,onEdit:ml})]}):null,B.role==="assistant"&&B.plan?s.jsxs("details",{className:"chat-steps",open:!0,children:[s.jsxs("summary",{children:["Plan: ",B.plan.goal]}),s.jsx(YN,{plan:B.plan})]}):null,B.role==="assistant"&&B.tools&&B.tools.length>0?s.jsxs("details",{className:"chat-steps",open:!0,children:[s.jsxs("summary",{children:[B.tools.length," tool call",B.tools.length===1?"":"s"]}),s.jsx(XN,{tools:B.tools})]}):null,B.role==="assistant"&&B.steps&&B.steps.length>0?s.jsxs("details",{className:"chat-steps",children:[s.jsxs("summary",{children:[B.steps.length," step",B.steps.length===1?"":"s"]}),s.jsx("div",{className:"chat-step-line",children:B.steps.map((J,Ee)=>s.jsx("div",{children:J.trim()},Ee))})]}):null]},te)),o?s.jsxs("div",{className:"chat-bubble chat-assistant",children:[s.jsx("div",{className:"chat-bubble-role",children:"🤖 Agent"}),v?s.jsx(YN,{plan:v}):null,b?s.jsx(Ad,{diff:b}):null,k?s.jsx(VN,{draft:k,onAccept:wa,onReject:pl,onEdit:ml}):null,w.map(B=>s.jsx($ge,{request:B,onSave:Ci},B.skillName)),N.map((B,te)=>s.jsx(Lge,{result:B},`${B.skillName}-${te}`)),s.jsx(XN,{tools:g,live:!0}),F?s.jsx("div",{className:"chat-bubble-text chat-streaming",children:s.jsx(FN,{text:F})}):null,s.jsx("div",{className:"chat-working",children:h.length>0?s.jsx("span",{className:"chat-working-lines",children:h.map((B,te)=>s.jsx("div",{className:"chat-step-line",children:B.trim()},te))}):s.jsxs(s.Fragment,{children:["💭 thinking… ",s.jsx("span",{className:"chat-dots"})]})})]}):null]}),c?s.jsx("div",{className:"admin-row-msg admin-row-msg-err",children:c}):null,Y&&!o?s.jsxs("div",{className:"chat-retry-row",children:[s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>void Je(Y),children:"↻ Retry"}),s.jsx("span",{className:"admin-hint",children:"Re-send the last message — the turn failed."})]}):null,T&&!o?s.jsx("div",{className:"chat-resolve-card",children:(Ru=T.top)!=null&&Ru.ambiguous&&((Iu=T.top.options)!=null&&Iu.length)?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"chat-resolve-head",children:[s.jsx("strong",{children:"🤔 Which do you mean?"}),' — "',T.ask,'" maps to more than one action.']}),s.jsx("div",{className:"chat-resolve-options",children:T.top.options.map(B=>s.jsxs("button",{className:"chat-chip",type:"button",onClick:()=>void Je(B.command),children:[B.summary," — ",s.jsx("code",{children:B.command})]},B.command))}),s.jsx("div",{className:"chat-resolve-foot",children:s.jsx("button",{className:"admin-mini-btn",type:"button",onClick:()=>{$(null)},children:"✕ Not that — ask the agent"})})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"chat-resolve-head",children:[s.jsx("strong",{children:"⚡ Run this command?"}),' — "',T.ask,'"']}),s.jsx("div",{className:"chat-resolve-cmd",children:s.jsx("code",{children:(Pi=T.top)==null?void 0:Pi.command})}),($u=T.top)!=null&&$u.confirmation?s.jsx("div",{className:"admin-hint",children:"⚠ This changes running services/state."}):null,s.jsxs("div",{className:"chat-resolve-foot",children:[s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>void gl(T.ask),children:"▶ Run"}),s.jsx("button",{className:"admin-mini-btn",type:"button",onClick:()=>Oi(T.ask),children:"✕ No — ask the agent"})]})]})}):null,Ht?s.jsxs("div",{className:"chat-resolve-card chat-question-card",children:[s.jsx("div",{className:"chat-resolve-head",children:s.jsxs("strong",{children:["🤔 ",Ht.question]})}),s.jsx("div",{className:"chat-resolve-options",children:Ht.choices.map((B,te)=>s.jsxs("button",{type:"button",className:`chat-chip${Ai.has(te)?" chat-chip-selected":""}`,onClick:()=>qp(te),children:[B.label,B.description?s.jsxs("span",{className:"admin-hint",children:[" — ",B.description]}):null]},`${B.label}-${te}`))}),s.jsxs("div",{className:"chat-resolve-foot",children:[s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:Qr,children:Ht.multiSelect?"Submit":"Choose"}),s.jsx("button",{className:"admin-mini-btn",type:"button",onClick:Gp,children:"Skip — best judgment"})]})]}):null,Gt.length>0&&!o?s.jsxs("div",{className:"chat-followups",children:[s.jsx("span",{className:"admin-hint",children:"Next steps:"}),Gt.map((B,te)=>s.jsx("button",{className:"chat-chip",type:"button",onClick:()=>void Je(B.prompt),children:B.label||B.prompt},te))]}):null,s.jsxs("form",{className:`chat-composer${Ct?" chat-composer-drag":""}`,onSubmit:B=>{B.preventDefault(),Je(i)},onDragOver:B=>{B.preventDefault(),We(!0)},onDragLeave:()=>We(!1),onDrop:B=>{var J;B.preventDefault(),We(!1);const te=Array.from(((J=B.dataTransfer)==null?void 0:J.files)??[]);for(const Ee of te.slice(0,10))Cu(Ee)},children:[Be?s.jsxs("div",{className:"chat-paste-offer",children:[s.jsxs("span",{className:"admin-hint",children:["📄 You pasted ",Be.text.length.toLocaleString()," characters. Attach it as a file instead?"]}),s.jsx("button",{type:"button",className:"chat-chip",onClick:Hp,children:"Attach as text"}),s.jsx("button",{type:"button",className:"chat-mini-action",onClick:()=>{pe(null),Ze.current=null},children:"Keep inline"})]}):null,Ne.length>0?s.jsx("div",{className:"chat-attach-row",children:Ne.map((B,te)=>s.jsxs("span",{className:"chat-attach-chip",title:`${B.name} (${B.content.length.toLocaleString()} chars)`,children:["📎 ",B.name,s.jsxs("span",{className:"admin-hint",children:[" ",B.content.length.toLocaleString(),"c"]}),s.jsx("button",{type:"button",className:"chat-mini-action",onClick:()=>Up(te),children:"✕"})]},`${B.name}-${te}`))}):null,s.jsxs("div",{className:"chat-input-row",children:[s.jsx("input",{ref:Oe,type:"file",style:{display:"none"},onChange:B=>{var J;const te=(J=B.target.files)==null?void 0:J[0];te&&Cu(te),B.target.value=""}}),s.jsx("button",{type:"button",className:"chat-attach-btn",title:"Attach a file (up to 300 KB, text only)",disabled:o||Ne.length>=10,onClick:()=>{var B;return(B=Oe.current)==null?void 0:B.click()},children:"📎"}),s.jsx("textarea",{className:"chat-input-box",value:i,onChange:B=>a(B.target.value),onPaste:Wp,onKeyDown:B=>{B.key==="Enter"&&!B.shiftKey?(B.preventDefault(),Je(i)):B.key==="ArrowUp"&&i===""&&le.current&&(B.preventDefault(),a(le.current))},placeholder:"Message the agent… (Enter to send · Shift+Enter for a new line · ↑ recalls last · 📎 attach a file or paste a large document)",disabled:o,maxLength:8e3,rows:1,autoFocus:!0}),o?s.jsx("button",{className:"admin-mini-btn chat-cancel-btn",type:"button",onClick:hl,children:"⏹ Cancel"}):null,s.jsx("button",{className:"admin-refresh-btn",type:"submit",disabled:o||!i.trim()&&Ne.length===0,children:o?"⏳ Working…":"➤ Send"})]})]}),s.jsxs("p",{className:"admin-hint",children:["Each message runs the full agent loop in the dashboard process (same engine as"," ",s.jsx("code",{children:'buff chat "<prompt>"'}),") — the provider API keys must be configured in the dashboard process. Clarifications (",s.jsx("code",{children:"ask_user"}),") appear as a question card here — choose an answer or skip (best judgment)."]})]})]})]}):s.jsx("div",{className:"admin-login-hint",children:s.jsx("p",{children:"Your role can view the dashboard but not chat (requires admin or operator)."})}):s.jsxs("div",{className:"admin-login-hint",children:[s.jsx("p",{children:"Log in (admin or operator) to chat with the agent. Configure the dashboard admin credential first if this is a fresh setup."}),(e==null?void 0:e.configured)===!1?s.jsxs("p",{className:"admin-hint",children:["Run ",s.jsx("code",{children:"buff dashboard"})," once, or set ",s.jsx("code",{children:"BUFF_DASHBOARD_ADMIN_USER"})," / ",s.jsx("code",{children:"BUFF_DASHBOARD_ADMIN_PASSWORD"}),"."]}):null]})]})}const zge={running:"⏳ running",done:"✅ done",failed:"❌ failed",cancelled:"⏹ cancelled",timeout:"⏰ timed out",error:"💥 error"};function i2({presets:e,customPlaceholder:t,timeoutMs:n=3e5,hint:r}){const[i,a]=E.useState(null),[o,l]=E.useState(!1),[c,u]=E.useState(""),[d,f]=E.useState(""),[h,p]=E.useState(null),[g,m]=E.useState([]),v=E.useRef(null),y=E.useRef(null);E.useEffect(()=>{ee.fetchAdminAuthStatus().then(S=>{a(S?{authenticated:S.authenticated,role:S.role}:{authenticated:!1,role:null})})},[]),E.useEffect(()=>{var S,w;try{(w=(S=v.current)==null?void 0:S.scrollIntoView)==null||w.call(S,{block:"end"})}catch{}},[g]),E.useEffect(()=>()=>{var S;(S=y.current)==null||S.call(y)},[]);const b=(i==null?void 0:i.authenticated)===!0&&(i.role==="admin"||i.role==="operator"),x=E.useCallback(async(S,w)=>{var T;if(o)return;l(!0),u(""),m([]);const _=await ee.startTask(S,w??n);if(!_.ok||!_.task){u(_.error||"Could not start the command."),l(!1);return}const N=_.task;p(N);const C=await ee.getTask(N.id);C!=null&&C.task&&m(C.task.logs.map($=>({stream:$.stream,text:$.text}))),(T=y.current)==null||T.call(y),y.current=ee.subscribeTask(N.id,{onLog:$=>m(R=>[...R,{stream:$.stream,text:$.text}]),onStatus:$=>{p(R=>R&&{...R,status:$}),$!=="running"&&l(!1)}})},[o,n]),k=E.useCallback(async()=>{h&&await ee.cancelTask(h.id)},[h]);return s.jsxs("div",{className:"ops-console",children:[i!=null&&i.authenticated?b?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"ops-presets",children:e.map(S=>s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>void x(S.args,S.timeoutMs),disabled:o,children:S.label},S.label))}),s.jsxs("div",{className:"ops-custom-row",children:[s.jsx("input",{type:"text",value:d,onChange:S=>f(S.target.value),placeholder:t,disabled:o,maxLength:160}),s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>void x(d.trim().split(/\s+/)),disabled:o||!d.trim(),children:"Run"})]}),r?s.jsx("p",{className:"admin-hint",children:r}):null]}):s.jsx("div",{className:"admin-login-hint",children:"Your role can view but not run commands (requires admin or operator)."}):s.jsx("div",{className:"admin-login-hint",children:"Log in (admin or operator) to run commands."}),c?s.jsx("div",{className:"admin-row-msg admin-row-msg-err",children:c}):null,h?s.jsxs("div",{className:"ops-console-box",children:[s.jsxs("div",{className:"ops-console-head",children:[s.jsxs("span",{children:[h.command," · ",s.jsx("span",{className:h.status==="running"?"task-status-running":"",children:zge[h.status]})]}),h.status==="running"?s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>void k(),children:"⏹ Cancel"}):null]}),s.jsxs("pre",{className:"ops-console",role:"log",children:[g.length>0?g.map((S,w)=>s.jsx("div",{children:S.text},w)):s.jsx("div",{className:"admin-hint",children:"Waiting for output…"}),s.jsx("div",{ref:v})]})]}):null]})}const Fge=[{label:"⚡ Quick smoke",args:["eval","run","--tasks","quick","--format","text"]},{label:"⏱ Medium suite",args:["eval","run","--tasks","medium","--format","text"]},{label:"🐢 Slow suite",args:["eval","run","--tasks","slow","--format","text"]},{label:"🏆 M2B parity",args:["eval","run","--suite","m2b","--format","text"]},{label:"📦 Full suite",args:["eval","run","--suite","full","--format","text"]}];function QN(e){return typeof e!="number"?"—":`${Math.round(e*100)}%`}function Uge(e){return new Date(e).toLocaleString()}function Wge({data:e}){var n;const t=((n=e==null?void 0:e.evals)==null?void 0:n.runs)??[];return s.jsxs("div",{className:"panel",children:[s.jsx("div",{className:"panel-header",children:s.jsx("h2",{children:"🏆 Evals — run buff eval from the GUI"})}),s.jsx(i2,{presets:Fge,customPlaceholder:"e.g. eval run --tasks my-task --provider groq --model llama",timeoutMs:9e5,hint:s.jsxs(s.Fragment,{children:["Runs the real ",s.jsx("code",{children:"buff eval run"})," as an isolated process — same engine, same ledger, same results as the CLI. Long suites can take minutes; you can cancel mid-run."]})}),s.jsx("h3",{className:"section-subtitle",children:"📜 Past runs (auto-refreshes)"}),t.length>0?s.jsx("div",{className:"admin-table-wrapper",children:s.jsxs("table",{className:"admin-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Started"}),s.jsx("th",{children:"Provider"}),s.jsx("th",{children:"Model"}),s.jsx("th",{children:"Tasks"}),s.jsx("th",{children:"Pass"}),s.jsx("th",{children:"Completion"}),s.jsx("th",{children:"Composite"}),s.jsx("th",{children:"Cost"})]})}),s.jsx("tbody",{children:t.map(r=>s.jsxs("tr",{children:[s.jsx("td",{children:Uge(r.startedAt)}),s.jsx("td",{className:"admin-provider-type",children:r.provider}),s.jsx("td",{children:r.model}),s.jsx("td",{children:r.summary.totalTasks}),s.jsxs("td",{children:[r.summary.tasksPassed,"/",r.summary.totalTasks]}),s.jsx("td",{children:QN(r.summary.completionRate)}),s.jsx("td",{children:QN(r.summary.avgCompositeScore)}),s.jsxs("td",{children:["$",(r.summary.totalCostUsd??0).toFixed(4)]})]},r.id))})]})}):s.jsx("div",{className:"empty-state",children:"No eval runs yet — start one above (or `buff eval run` from the CLI)."})]})}const Hge=[{label:"🌐 Gateway status",args:["gateway","status"]},{label:"📮 Delivery ledger",args:["gateway","delivery"]},{label:"▶️ Start gateway (foreground)",args:["gateway","start","--no-events"],timeoutMs:0},{label:"⏰ Cron jobs",args:["admin","cron","list"]}];function Gge(){return s.jsxs("div",{className:"panel",children:[s.jsx("div",{className:"panel-header",children:s.jsx("h2",{children:"🌐 Gateway ops — run buff gateway from the GUI"})}),s.jsx(i2,{presets:Hge,customPlaceholder:"e.g. admin cron run nightly or gateway alias add ops email:team@example.com",timeoutMs:3e5,hint:s.jsxs(s.Fragment,{children:["Each command runs as the real CLI in an isolated process (the P1 task runner) — the same engine as your terminal. ",s.jsx("code",{children:"gateway start"})," runs in the foreground ",s.jsx("strong",{children:"with no timeout"}),": it keeps running even after you switch tabs (the process lives on the dashboard server, not the page) and streams platform events until you press ",s.jsx("strong",{children:"Cancel"}),". The delivery ledger also has its own view in"," ",s.jsx("strong",{children:"Agent Hub → Channels"}),"."]})})]})}const Eg={telegram:{icon:"✈️",category:"Chat",steps:["Open Telegram and search for @BotFather","Send /newbot and follow the prompts",'Give your bot a name (e.g. "My Agent Bot")','Give your bot a username ending in "bot"',"BotFather gives you a token — paste it in Step 2","Open your bot in Telegram and send /start"],testTarget:"telegram:"},discord:{icon:"🎮",category:"Chat",steps:["Go to discord.com/developers/applications",'Click "New Application" and give it a name','Go to Bot tab and click "Add Bot"',"Copy the bot token",'Enable "Message Content Intent"',"Invite bot to your server (OAuth2 URL generator)"],testTarget:"discord:"},slack:{icon:"💬",category:"Chat",steps:["Go to api.slack.com/apps","Create New App from scratch","Add Bot Token Scopes: chat:write, im:read, im:write","Install to workspace","Copy the Bot User OAuth Token (xoxb-...)"],testTarget:"slack:"},whatsapp:{icon:"📱",category:"Chat",steps:["Run: buff whatsapp pair (or from Gateway tab)","Scan the QR code with WhatsApp","Pairing completes automatically"],testTarget:""},whatsapp_cloud:{icon:"☁️",category:"Chat",steps:["Go to developers.facebook.com","Set up WhatsApp Cloud API","Copy token + Phone ID"],testTarget:"whatsapp_cloud:"},email:{icon:"📧",category:"Chat",steps:["Get SMTP credentials (Gmail, SendGrid, etc.)","For Gmail: use App Password at smtp.gmail.com:587","Paste SMTP host + user below"],testTarget:""},signal:{icon:"🔒",category:"Chat",steps:["Run signal-cli-rest-api Docker container","Register a Signal account","Paste account number below"],testTarget:""},dingtalk:{icon:"🔔",category:"Webhooks",steps:["Open DingTalk and create a group","Add custom robot and copy webhook URL","Paste URL below"],testTarget:""},feishu:{icon:"🐦",category:"Webhooks",steps:["Open Feishu and create a bot","Copy webhook URL and paste below"],testTarget:""},wecom:{icon:"🏢",category:"Webhooks",steps:["Open WeCom and create a group bot","Copy webhook URL and paste below"],testTarget:""},mattermost:{icon:"📋",category:"Webhooks",steps:["Open Mattermost, go to Integrations","Create incoming webhook and copy URL"],testTarget:""},matrix:{icon:"🔗",category:"Chat",steps:["Get your Matrix homeserver URL","Create a bot user and get access token","Paste URL + token below"],testTarget:""},webhook:{icon:"🪝",category:"Webhooks",steps:["Enter your webhook URL","The agent sends outbound webhooks to this URL"],testTarget:""},bluebubbles:{icon:"💙",category:"Chat",steps:["Set up BlueBubbles server","Copy server URL + password"],testTarget:""},ntfy:{icon:"📢",category:"Notifications",steps:["Choose an ntfy topic (or use ntfy.sh)","Paste the topic below"],testTarget:""},teams:{icon:"👥",category:"Webhooks",steps:["Open Microsoft Teams, go to channel","Connectors, Incoming Webhook, create","Copy webhook URL"],testTarget:""},google_chat:{icon:"💬",category:"Webhooks",steps:["Open Google Chat, space settings","Create webhook and copy URL"],testTarget:""},weixin:{icon:"🔴",category:"Chat",steps:["Get Weixin iLink bot token","Paste token below"],testTarget:""},sms:{icon:"📲",category:"Chat",steps:["Get Twilio account SID + auth token","Register a phone number","Paste credentials below"],testTarget:""},irc:{icon:"💻",category:"Chat",steps:["Choose an IRC server (e.g. irc.libera.chat)","Set nickname + channel and paste below"],testTarget:""},simplex:{icon:"📨",category:"Chat",steps:["Run local simplex-chat daemon","Paste WebSocket URL (ws://127.0.0.1:5225)"],testTarget:""},homeassistant:{icon:"🏠",category:"IoT",steps:["Open Home Assistant Profile","Create long-lived access token and paste below"],testTarget:""}};function qge(){const[e,t]=E.useState(null),[n,r]=E.useState("all"),[i,a]=E.useState(null),[o,l]=E.useState(0),[c,u]=E.useState({}),[d,f]=E.useState(!1),[h,p]=E.useState(null),[g,m]=E.useState({status:"idle"}),[v,y]=E.useState(""),[b,x]=E.useState("Hello from agent-nuvira!"),[k,S]=E.useState(!1),[w,_]=E.useState(null),N=E.useRef(!0),C=E.useCallback(async()=>{const O=await ee.getPlatformConfigs();N.current&&t(O)},[]);E.useEffect(()=>(C(),()=>{N.current=!1}),[C]);const T=O=>{a(O),l(0),u(Object.fromEntries(O.envVars.map(A=>[A.varName,A.value]))),p(null),m({status:"idle"});const P=Eg[O.platform];y((P==null?void 0:P.testTarget)??""),x("Hello from agent-nuvira!"),_(null)},$=async()=>{if(!i)return;m({status:"checking"});const O=await ee.verifyPlatformConfig(i.platform,c);O.ok?(m({status:"ok",info:O.info}),p({kind:"ok",text:"Verified! "+(O.info?"Connected as "+O.info+".":"Token is valid.")})):(m({status:"err",error:O.error}),p({kind:"err",text:O.error||"Verification failed."}))},R=async()=>{if(!i)return;f(!0),p(null);const O=await ee.setPlatformConfig(i.platform,c);f(!1),O.ok?(p({kind:"ok",text:"Token saved! Verifying..."}),C(),l(2),$()):p({kind:"err",text:O.error||"Save failed."})},L=async()=>{if(!i||!v)return;S(!0),_(null);const O=await ee.sendChannelMessage(v,b);S(!1),O.ok?_({kind:"ok",text:"Message sent via "+O.platform+"! Check your "+i.label+" app."}):_({kind:"err",text:O.error||"Send failed. Make sure the gateway is running (Gateway tab)."})};if(e===null)return s.jsx("div",{className:"empty-state",children:"Loading platforms..."});const I=e.filter(O=>O.configured).length,z=e.filter(O=>n==="configured"?O.configured:n==="unconfigured"?!O.configured:!0),D=i?Eg[i.platform]:null;function F(O){return o===O?"wizard-step-dot active":"wizard-step-dot"}return s.jsxs("div",{className:"panel",children:[s.jsx("div",{className:"panel-header",children:s.jsx("h2",{children:"Platforms — Messaging Gateway Onboarding"})}),s.jsxs("div",{className:"platforms-summary",children:[s.jsxs("div",{className:"platforms-summary-stat",children:[s.jsx("span",{className:"platforms-summary-number",children:I}),s.jsx("span",{className:"platforms-summary-label",children:"configured"})]}),s.jsxs("div",{className:"platforms-summary-stat",children:[s.jsx("span",{className:"platforms-summary-number",children:e.length-I}),s.jsx("span",{className:"platforms-summary-label",children:"available"})]}),s.jsx("div",{className:"platforms-summary-filters",children:["all","configured","unconfigured"].map(O=>s.jsx("button",{type:"button",className:n===O?"platforms-filter-btn active":"platforms-filter-btn",onClick:()=>r(O),children:O==="all"?"All":O==="configured"?"Configured":"Not set up"},O))})]}),s.jsx("div",{className:"platforms-grid",children:z.map(O=>{const P=Eg[O.platform];return s.jsxs("div",{className:O.configured?"platform-card configured":"platform-card",children:[s.jsxs("div",{className:"platform-card-head",children:[s.jsx("span",{className:"platform-card-icon",children:(P==null?void 0:P.icon)??"🔌"}),s.jsxs("div",{className:"platform-card-info",children:[s.jsx("span",{className:"platform-card-name",children:O.label}),s.jsx("span",{className:"platform-card-category",children:(P==null?void 0:P.category)??"Platform"})]}),s.jsx("span",{className:O.configured?"status-dot connected":"status-dot reconnecting"})]}),s.jsx("div",{className:"platform-card-vars",children:O.envVars.map(A=>s.jsxs("span",{className:A.set?"platform-var-chip set":"platform-var-chip",children:[A.varName," ",A.set?"done":"--"]},A.varName))}),s.jsxs("div",{className:"platform-card-actions",children:[O.configured?s.jsx("span",{className:"platform-card-badge",children:"Active"}):s.jsx("button",{type:"button",className:"wizard-start-btn",onClick:()=>T(O),children:"Setup"}),O.setupUrl?s.jsx("a",{href:O.setupUrl,target:"_blank",rel:"noopener noreferrer",className:"admin-mini-btn platform-docs-link",children:"Docs"}):null]}),!O.configured&&O.setupHint?s.jsx("div",{className:"platform-card-hint",children:O.setupHint}):null]},O.platform)})}),s.jsxs("div",{className:"platforms-cli-hint",children:[s.jsx("span",{className:"admin-hint",children:"Prefer the terminal? "}),s.jsx("code",{children:"buff gateway setup telegram"}),s.jsx("span",{className:"admin-hint",children:" — same wizard from your CLI"})]}),i&&D?s.jsx("div",{className:"wizard-overlay",onClick:()=>a(null),children:s.jsxs("div",{className:"wizard-modal",onClick:O=>O.stopPropagation(),children:[s.jsxs("div",{className:"wizard-header",children:[s.jsx("span",{className:"wizard-icon",children:D.icon}),s.jsxs("span",{className:"wizard-title",children:["Getting Started: ",i.label]}),s.jsxs("div",{className:"wizard-steps-indicator",children:[s.jsx("span",{className:F(0),children:"1"}),s.jsx("span",{className:F(1),children:"2"}),s.jsx("span",{className:F(2),children:"3"})]}),s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>a(null),children:"X"})]}),s.jsxs("div",{className:"wizard-body",children:[o===0&&s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"wizard-section-title",children:["Step 1: Create your bot on ",i.label]}),s.jsx("ol",{className:"wizard-steps",children:D.steps.map((O,P)=>s.jsx("li",{children:O},P))}),s.jsxs("div",{className:"wizard-nav",children:[s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>l(1),children:"I have my token — Step 2"}),i.setupUrl?s.jsx("a",{href:i.setupUrl,target:"_blank",rel:"noopener noreferrer",className:"admin-mini-btn platform-docs-link",children:"Open docs"}):null]})]}),o===1&&s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"wizard-section-title",children:"Step 2: Paste your token"}),i.envVars.map(O=>s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:O.prompt}),s.jsx("input",{type:O.secret?"password":"text",value:c[O.varName]??"",onChange:P=>u(A=>({...A,[O.varName]:P.target.value})),placeholder:O.secret?"paste your token here":"value",autoComplete:"off",spellCheck:!1,autoFocus:!0})]},O.varName)),h?s.jsx("div",{className:h.kind==="ok"?"admin-row-msg":"admin-row-msg admin-row-msg-err",children:h.text}):null,s.jsxs("div",{className:"wizard-nav",children:[s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>l(0),children:"Back"}),s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void R(),disabled:d,children:d?"Saving...":"Save & Verify"})]})]}),o===2&&s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"wizard-section-title",children:"Step 3: Verify and test"}),g.status==="checking"&&s.jsx("div",{className:"wizard-verify-status",children:"Verifying token..."}),g.status==="ok"&&s.jsxs("div",{className:"wizard-verify-status ok",children:["Connected as ",g.info]}),g.status==="err"&&s.jsx("div",{className:"wizard-verify-status err",children:g.error}),g.status==="idle"&&(h==null?void 0:h.kind)==="ok"&&s.jsx("div",{className:"wizard-verify-status ok",children:h.text}),v&&s.jsxs("div",{className:"wizard-test-section",children:[s.jsx("p",{className:"wizard-section-title",children:"Send a test message:"}),s.jsx("div",{className:"wizard-test-row",children:s.jsx("input",{className:"wizard-test-input",value:v,onChange:O=>y(O.target.value),placeholder:"telegram:YOUR_CHAT_ID"})}),s.jsxs("div",{className:"wizard-test-row",children:[s.jsx("input",{className:"wizard-test-input",value:b,onChange:O=>x(O.target.value),placeholder:"Hello from agent-nuvira!"}),s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void L(),disabled:k||!v,children:k?"Sending...":"Send test"})]}),w?s.jsx("div",{className:w.kind==="ok"?"admin-row-msg":"admin-row-msg admin-row-msg-err",children:w.text}):null]}),s.jsxs("div",{className:"wizard-nav",children:[s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>l(1),children:"Edit token"}),s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>a(null),children:"Done"})]}),!v&&s.jsxs("p",{className:"wizard-hint",children:["Token saved! Start the gateway from the Gateway tab, then send a message from your ",i.label," app."]})]})]})]})}):null]})}const Kge=[{value:"us-east-1",label:"us-east-1 (N. Virginia) — most models"},{value:"us-west-2",label:"us-west-2 (Oregon) — most models"},{value:"eu-west-1",label:"eu-west-1 (Ireland) — EU coverage"},{value:"ap-southeast-1",label:"ap-southeast-1 (Singapore)"},{value:"ap-northeast-1",label:"ap-northeast-1 (Tokyo)"}],JN=[{name:"Anthropic Claude",models:["claude-haiku-4.5","claude-sonnet-4.6","claude-fable-5","claude-opus-4.6"],checked:!0},{name:"Meta Llama",models:["llama3-1-8b","llama3-1-70b","llama3-3-70b","llama4-scout","llama4-maverick"],checked:!0},{name:"Mistral AI",models:["mistral-large-3","devstral-2","ministral-3"],checked:!1},{name:"DeepSeek",models:["deepseek-v3.2","deepseek-r1"],checked:!1},{name:"Amazon Nova",models:["nova-pro","nova-lite"],checked:!1},{name:"OpenAI on Bedrock",models:["gpt-5.6-terra","gpt-oss-120b"],checked:!1},{name:"Qwen",models:["qwen3-coder-next","qwen3-32b"],checked:!1},{name:"Google Gemma",models:["gemma-3-12b"],checked:!1},{name:"xAI",models:["grok-4.6"],checked:!1}];function Vge({canWrite:e,sessionExpired:t}){const[n,r]=E.useState(null),[i,a]=E.useState(null),[o,l]=E.useState(!1),[c,u]=E.useState("overview"),d=E.useRef(!0),[f,h]=E.useState("bearer"),[p,g]=E.useState(""),[m,v]=E.useState(""),[y,b]=E.useState(""),[x,k]=E.useState("us-east-1"),[S,w]=E.useState(JN.filter(I=>I.checked).map(I=>I.name)),[_,N]=E.useState(!1),[C,T]=E.useState(null),$=E.useCallback(async()=>{const I=await ee.getBedrockStatus();d.current&&r(I)},[]);E.useEffect(()=>($(),()=>{d.current=!1}),[$]);const R=async()=>{l(!0),a(null);try{const I=await ee.probeBedrock((n==null?void 0:n.region)||"us-east-1");if(!d.current)return;I.ok&&I.models&&(a(I.models),u("test"))}catch{}finally{d.current&&l(!1)}},L=async()=>{N(!0),T(null);try{const I={BEDROCK_REGION:x};f==="bearer"&&p?I.AWS_BEARER_TOKEN=p:f==="iam"&&(m&&(I.AWS_ACCESS_KEY_ID=m),y&&(I.AWS_SECRET_ACCESS_KEY=y));const z=await ee.setupBedrock(I);if(!d.current)return;z.ok?(T({kind:"ok",text:"✅ Configuration saved! Running connectivity test…"}),u("overview"),await $(),setTimeout(()=>void R(),500)):T({kind:"err",text:z.error||"Save failed"})}catch{d.current&&T({kind:"err",text:"Could not reach the dashboard server."})}finally{d.current&&N(!1)}};return n===null?s.jsx("div",{className:"empty-state",children:"Loading Bedrock status…"}):s.jsxs("div",{className:"bedrock-onboarding",children:[s.jsx("h2",{className:"section-title",children:"🟠 AWS Bedrock"}),s.jsxs("p",{className:"admin-subtitle",children:["Bedrock gives you access to Claude, Llama, Mistral, DeepSeek, and more — all through a single AWS account. Unlike other providers, Bedrock requires a ",s.jsx("strong",{children:"region"}),", ",s.jsx("strong",{children:"AWS credentials"}),", and explicit ",s.jsx("strong",{children:"model access approval"}),"."]}),C?s.jsx("div",{className:`admin-row-msg${C.kind==="ok"?"":" admin-row-msg-err"}`,children:C.text}):null,s.jsxs("div",{className:"bedrock-status-bar",children:[s.jsxs("div",{className:"bedrock-status-item",children:[s.jsx("span",{className:`status-dot ${n.configured?"connected":"reconnecting"}`}),s.jsx("span",{children:n.configured?"Configured":"Not configured"})]}),s.jsxs("div",{className:"bedrock-status-item",children:[s.jsx("span",{className:"bedrock-status-label",children:"Region:"}),s.jsx("code",{children:n.region})]}),s.jsxs("div",{className:"bedrock-status-item",children:[s.jsx("span",{className:"bedrock-status-label",children:"Auth:"}),s.jsx("code",{children:n.authMethod==="bearer"?"API Key":n.authMethod==="iam"?"IAM":"None"})]}),s.jsxs("div",{className:"bedrock-status-actions",children:[e?s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>u(c==="setup"?"overview":"setup"),children:c==="setup"?"✕ Cancel":"⚙ Setup Wizard"}):null,n.configured?s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void R(),disabled:o,children:o?"⏳ Probing…":"🔍 Test Models"}):null]})]}),c==="setup"&&s.jsxs("div",{className:"bedrock-setup-wizard",children:[s.jsx("h3",{className:"section-subtitle",children:"🚀 Bedrock Setup Wizard"}),s.jsxs("div",{className:"bedrock-wizard-step",children:[s.jsx("h4",{children:"Step 1: Authentication"}),s.jsxs("div",{className:"bedrock-auth-options",children:[s.jsxs("label",{className:`bedrock-auth-option ${f==="bearer"?"selected":""}`,children:[s.jsx("input",{type:"radio",name:"authMethod",checked:f==="bearer",onChange:()=>h("bearer")}),s.jsxs("div",{children:[s.jsx("strong",{children:"Bedrock API Key"}),s.jsx("span",{children:"Simpler — get from Bedrock → Settings → API keys"})]})]}),s.jsxs("label",{className:`bedrock-auth-option ${f==="iam"?"selected":""}`,children:[s.jsx("input",{type:"radio",name:"authMethod",checked:f==="iam",onChange:()=>h("iam")}),s.jsxs("div",{children:[s.jsx("strong",{children:"IAM Credentials"}),s.jsx("span",{children:"Full AWS SDK auth — AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY"})]})]})]}),f==="bearer"?s.jsxs("div",{className:"bedrock-wizard-fields",children:[s.jsxs("div",{className:"bedrock-setup-hint",children:[s.jsx("strong",{children:"How to get a Bedrock API key:"}),s.jsxs("ol",{children:[s.jsxs("li",{children:["Open ",s.jsx("a",{href:"https://console.aws.amazon.com/bedrock/",target:"_blank",rel:"noopener noreferrer",children:"AWS Bedrock Console"})]}),s.jsxs("li",{children:["Go to ",s.jsx("strong",{children:"Settings"})," → ",s.jsx("strong",{children:"API keys"})]}),s.jsx("li",{children:"Create a new key and paste it below"})]})]}),s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:"Bedrock API Key (Bearer token)"}),s.jsx("input",{type:"password",value:p,onChange:I=>g(I.target.value),placeholder:"••••••••••••",autoComplete:"off",spellCheck:!1})]})]}):s.jsxs("div",{className:"bedrock-wizard-fields",children:[s.jsxs("div",{className:"bedrock-setup-hint",children:[s.jsx("strong",{children:"IAM credentials"})," give full AWS SDK access. Create an IAM user with Bedrock permissions."]}),s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:"AWS_ACCESS_KEY_ID"}),s.jsx("input",{type:"text",value:m,onChange:I=>v(I.target.value),placeholder:"AKIA...",autoComplete:"off",spellCheck:!1})]}),s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:"AWS_SECRET_ACCESS_KEY"}),s.jsx("input",{type:"password",value:y,onChange:I=>b(I.target.value),placeholder:"••••••••••••",autoComplete:"off",spellCheck:!1})]})]})]}),s.jsxs("div",{className:"bedrock-wizard-step",children:[s.jsx("h4",{children:"Step 2: AWS Region"}),s.jsxs("p",{className:"admin-hint",children:["Models vary by region. ",s.jsx("strong",{children:"us-east-1"})," and ",s.jsx("strong",{children:"us-west-2"})," have the most models. ⚠️ Do NOT use eu-north-1 unless models are explicitly enabled there."]}),s.jsx("select",{className:"bedrock-region-select",value:x,onChange:I=>k(I.target.value),children:Kge.map(I=>s.jsx("option",{value:I.value,children:I.label},I.value))})]}),s.jsxs("div",{className:"bedrock-wizard-step",children:[s.jsx("h4",{children:"Step 3: Model Access"}),s.jsx("p",{className:"admin-hint",children:"Bedrock requires you to request access for each model family."}),s.jsx("div",{className:"bedrock-model-access-hint",children:s.jsx("a",{href:`https://console.aws.amazon.com/bedrock/home?region=${x}#/modelaccess`,target:"_blank",rel:"noopener noreferrer",className:"admin-mini-btn",children:"📖 Open Model Access in AWS Console"})}),s.jsx("div",{className:"bedrock-family-grid",children:JN.map(I=>s.jsxs("label",{className:`bedrock-family-card ${S.includes(I.name)?"selected":""}`,children:[s.jsx("input",{type:"checkbox",checked:S.includes(I.name),onChange:z=>{z.target.checked?w(D=>[...D,I.name]):w(D=>D.filter(F=>F!==I.name))}}),s.jsxs("div",{children:[s.jsx("strong",{children:I.name}),s.jsxs("span",{children:[I.models.length," model(s)"]})]})]},I.name))}),s.jsx("p",{className:"admin-hint",style:{marginTop:8},children:"In the AWS Console, select the families above and submit. Approval is usually instant for Anthropic and Meta models."})]}),s.jsxs("div",{className:"bedrock-wizard-actions",children:[s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void L(),disabled:_||f==="bearer"&&!p||f==="iam"&&(!m||!y),children:_?"⏳ Saving…":"💾 Save & Test"}),s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>u("overview"),children:"Cancel"})]})]}),c==="test"&&i&&s.jsxs("div",{className:"bedrock-probe-results",children:[s.jsxs("h3",{className:"section-subtitle",children:["🔍 Model Probe Results (",n.region,")"]}),s.jsx("div",{className:"bedrock-probe-grid",children:i.map(I=>s.jsxs("div",{className:`bedrock-probe-card bedrock-probe-${I.status}`,children:[s.jsx("span",{className:"bedrock-probe-icon",children:I.status==="accessible"?"✅":I.status==="permission-denied"?"🔒":I.status==="not-found"?"⚫":"❌"}),s.jsx("span",{className:"bedrock-probe-id",children:I.modelId}),s.jsx("span",{className:"bedrock-probe-status",children:I.status==="accessible"?"Ready":I.status==="permission-denied"?`Need access (HTTP ${I.httpStatus})`:I.status==="not-found"?"Not in this region":"Error"})]},I.modelId))}),i.some(I=>I.status==="permission-denied")&&s.jsxs("div",{className:"bedrock-probe-action",children:[s.jsxs("p",{children:["Some models exist in ",n.region," but access is not approved."]}),s.jsx("a",{href:`https://console.aws.amazon.com/bedrock/home?region=${n.region}#/modelaccess`,target:"_blank",rel:"noopener noreferrer",className:"admin-mini-btn",children:"🔓 Request Model Access in AWS Console →"})]}),s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>u("overview"),style:{marginTop:12},children:"← Back"})]}),!n.configured&&c==="overview"&&s.jsxs("div",{className:"bedrock-getting-started",children:[s.jsx("h3",{className:"section-subtitle",children:"📋 Getting Started with Bedrock"}),s.jsxs("div",{className:"bedrock-steps",children:[s.jsxs("div",{className:"bedrock-step",children:[s.jsx("span",{className:"bedrock-step-num",children:"1"}),s.jsxs("div",{children:[s.jsx("strong",{children:"Create an AWS account"})," (or use existing)",s.jsxs("span",{children:["New to AWS? Sign up at ",s.jsx("a",{href:"https://aws.amazon.com/",target:"_blank",rel:"noopener noreferrer",children:"aws.amazon.com"})]})]})]}),s.jsxs("div",{className:"bedrock-step",children:[s.jsx("span",{className:"bedrock-step-num",children:"2"}),s.jsxs("div",{children:[s.jsx("strong",{children:"Get Bedrock API key"}),s.jsx("span",{children:"Bedrock → Settings → API keys → Create key"})]})]}),s.jsxs("div",{className:"bedrock-step",children:[s.jsx("span",{className:"bedrock-step-num",children:"3"}),s.jsxs("div",{children:[s.jsx("strong",{children:"Request model access"}),s.jsx("span",{children:"Bedrock → Model access → Select Claude, Llama, etc. → Submit"})]})]}),s.jsxs("div",{className:"bedrock-step",children:[s.jsx("span",{className:"bedrock-step-num",children:"4"}),s.jsxs("div",{children:[s.jsx("strong",{children:"Configure in this wizard"}),s.jsx("span",{children:'Click "Setup Wizard" above to enter your credentials'})]})]})]})]}),n.configured&&c==="overview"&&!i&&s.jsx("div",{className:"bedrock-quick-status",children:s.jsxs("p",{className:"admin-hint",children:["Bedrock is configured. Click ",s.jsx("strong",{children:"🔍 Test Models"})," to verify connectivity and discover which models are accessible in ",n.region,"."]})})]})}const _g=["whatsapp","whatsapp_cloud","telegram","signal","slack","discord","email"];function Yge(){const[e,t]=E.useState([]),[n,r]=E.useState(!0),[i,a]=E.useState("all"),[o,l]=E.useState(null),[c,u]=E.useState(""),[d,f]=E.useState(""),[h,p]=E.useState(null),[g,m]=E.useState({}),[v,y]=E.useState({}),[b,x]=E.useState({}),[k,S]=E.useState(null),[w,_]=E.useState(!1),[N,C]=E.useState(!1),[T,$]=E.useState(!1),[R,L]=E.useState(12e4),I=E.useCallback(async()=>{r(!0);const H=await ee.getContacts();H.ok&&H.contacts&&t(H.contacts);const X=await ee.gatewayPolicies();if(X.ok&&X.policies){const oe={};for(const ce of _g){const Z=X.policies[ce];Z&&(oe[ce]={...Z.outboundSenders!==void 0?{outboundSenders:Z.outboundSenders}:{},...Z.requireApprovedTarget!==void 0?{requireApprovedTarget:Z.requireApprovedTarget}:{}})}m(oe),y(oe)}C(X.askUserWait===!0),$(X.askUserWait===!0),typeof X.askUserTimeoutMs=="number"&&L(X.askUserTimeoutMs),r(!1)},[]);E.useEffect(()=>{I()},[I]);const z=e.filter(H=>i==="all"||H.status===i),D=async H=>{p(null);const X=await ee.approveContact(H.platform,H.name);p(X.ok?{kind:"ok",text:`✅ ${H.name} approved.`}:{kind:"err",text:X.error||"Failed."}),I()},F=async H=>{p(null);const X=await ee.rejectContact(H.platform,H.name);p(X.ok?{kind:"ok",text:`🚫 ${H.name} rejected.`}:{kind:"err",text:X.error||"Failed."}),I()},O=async H=>{p(null);const X=await ee.deleteContact(H.platform,H.name);p(X.ok?{kind:"ok",text:`🗑️ ${H.name} deleted.`}:{kind:"err",text:X.error||"Failed."}),I()},P=async()=>{if(!o)return;p(null);const H=await ee.updateContact(o.platform,o.id,{name:c,phone:d});p(H.ok?{kind:"ok",text:`✅ ${c} updated.`}:{kind:"err",text:H.error||"Failed."}),l(null),I()},A=H=>H==="approved"?s.jsx("span",{className:"contact-status-badge approved",children:"✅ Approved"}):H==="pending"?s.jsx("span",{className:"contact-status-badge pending",children:"⏳ Pending"}):s.jsx("span",{className:"contact-status-badge rejected",children:"🚫 Rejected"}),Y=H=>({telegram:"✈️",whatsapp:"📱",whatsapp_cloud:"📱",email:"📧",slack:"💬",discord:"🎮"})[H]||"🔌",K=H=>H?new Date(H).toLocaleString():"—",M=H=>{const X=(b[H]??"").trim();X&&(m(oe=>{var _e;const ce={...oe[H]??{}},Z=ce.outboundSenders??((_e=v[H])==null?void 0:_e.outboundSenders)??[];return Z.some(we=>we.toLowerCase()===X.toLowerCase())||(ce.outboundSenders=[...Z,X]),{...oe,[H]:ce}}),x(oe=>({...oe,[H]:""})))},le=(H,X)=>{m(oe=>{var _e;const ce={...oe[H]??{}},Z=ce.outboundSenders??((_e=v[H])==null?void 0:_e.outboundSenders)??[];return ce.outboundSenders=Z.filter(we=>we.toLowerCase()!==X.toLowerCase()),{...oe,[H]:ce}})},be=H=>{m(X=>{const oe={...X[H]??{}};return oe.requireApprovedTarget=oe.requireApprovedTarget!==!0,{...X,[H]:oe}})},me=H=>{m(X=>{const oe={...X[H]??{}};return delete oe.outboundSenders,{...X,[H]:oe}})},Pe=async()=>{_(!0),S(null);const H={};for(const ce of _g){const Z=g[ce]??{},_e=v[ce]??{};(JSON.stringify(Z.outboundSenders??null)!==JSON.stringify(_e.outboundSenders??null)||!!Z.requireApprovedTarget!=!!_e.requireApprovedTarget)&&(H[ce]={...Z.outboundSenders!==void 0?{outboundSenders:Z.outboundSenders}:{outboundSenders:null},requireApprovedTarget:!!Z.requireApprovedTarget})}const X=N!==T;if(Object.keys(H).length===0&&!X){_(!1),S({kind:"ok",text:"No changes to save."});return}const oe=await ee.saveGatewayPolicies(H,void 0,void 0,{wait:N,timeoutMs:R});oe.ok?(S({kind:"ok",text:"✅ Send authority saved."}),I()):S({kind:"err",text:oe.error||"Failed to save send authority."}),_(!1)};return s.jsxs("div",{className:"panel contacts-page",children:[s.jsxs("div",{className:"panel-header",children:[s.jsx("h2",{children:"📇 Contacts — Outbound Messaging Directory"}),s.jsx("p",{className:"admin-hint",children:"Manage who the bot can send messages to. Users auto-register on first Telegram message."})]}),h&&s.jsxs("div",{className:`admin-row-msg ${h.kind==="err"?"admin-row-msg-err":""}`,children:[h.text,s.jsx("button",{className:"admin-mini-btn",onClick:()=>p(null),children:"✕"})]}),s.jsxs("div",{className:"contacts-filters",children:[["all","approved","pending","rejected"].map(H=>s.jsx("button",{type:"button",className:i===H?"platforms-filter-btn active":"platforms-filter-btn",onClick:()=>a(H),children:H==="all"?`All (${e.length})`:H==="approved"?`✅ Approved (${e.filter(X=>X.status==="approved").length})`:H==="pending"?`⏳ Pending (${e.filter(X=>X.status==="pending").length})`:`🚫 Rejected (${e.filter(X=>X.status==="rejected").length})`},H)),s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void I(),children:"🔄 Refresh"})]}),n?s.jsx("div",{className:"empty-state",children:"Loading contacts..."}):z.length===0?s.jsxs("div",{className:"empty-state",children:[s.jsxs("p",{children:["No contacts",i!=="all"?` with status "${i}"`:"","."]}),s.jsx("p",{className:"admin-hint",children:'Contacts auto-register when users message the bot on Telegram. They appear here as "Pending" until you approve them.'})]}):s.jsx("div",{className:"contacts-table-wrapper",children:s.jsxs("table",{className:"contacts-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Platform"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"ID"}),s.jsx("th",{children:"Phone"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Registered"}),s.jsx("th",{children:"Actions"})]})}),s.jsx("tbody",{children:z.map(H=>s.jsxs("tr",{className:`contact-row status-${H.status}`,children:[s.jsxs("td",{children:[Y(H.platform)," ",H.platform]}),s.jsx("td",{className:"contact-name",children:H.name}),s.jsx("td",{className:"contact-id",children:s.jsx("code",{children:H.id})}),s.jsx("td",{className:"contact-phone",children:H.phone||"—"}),s.jsx("td",{children:A(H.status)}),s.jsx("td",{className:"contact-date",children:K(H.registeredAt||H.addedAt)}),s.jsxs("td",{className:"contact-actions",children:[H.status!=="approved"&&s.jsx("button",{className:"admin-mini-btn contact-approve-btn",onClick:()=>void D(H),children:"✅ Approve"}),H.status!=="rejected"&&s.jsx("button",{className:"admin-mini-btn contact-reject-btn",onClick:()=>void F(H),children:"🚫 Reject"}),s.jsx("button",{className:"admin-mini-btn",onClick:()=>{l(H),u(H.name),f(H.phone||"")},children:"✏️ Edit"}),s.jsx("button",{className:"admin-mini-btn contact-delete-btn",onClick:()=>void O(H),children:"🗑️"})]})]},`${H.platform}:${H.id}`))})]})}),s.jsxs("div",{className:"panel-header",style:{marginTop:28},children:[s.jsx("h2",{children:"🔐 Send authority — who may message others"}),s.jsxs("p",{className:"admin-hint",children:["Controls who can ask the agent to send a message to ",s.jsx("strong",{children:"someone else"})," through the gateway (e.g. “send this poem to my brother on WhatsApp”). This is separate from a contact’s approval status above, which only gates sending ",s.jsx("em",{children:"to"})," that person. Left empty, a platform ",s.jsx("strong",{children:"inherits"})," its allowed-users list (open). Add ",s.jsx("code",{children:"Allow-All"})," to allow everyone, or list specific senders to restrict it."]})]}),k&&s.jsxs("div",{className:`admin-row-msg ${k.kind==="err"?"admin-row-msg-err":""}`,children:[k.text,s.jsx("button",{className:"admin-mini-btn",onClick:()=>S(null),children:"✕"})]}),s.jsx("div",{className:"hub-permissions",children:_g.map(H=>{const X=g[H]??{},oe=X.outboundSenders??[],ce=X.outboundSenders===void 0;return s.jsxs("div",{className:"hub-card",children:[s.jsxs("div",{className:"hub-card-top",children:[s.jsxs("span",{className:"hub-chip",children:[Y(H)," ",H]}),ce?s.jsx("span",{className:"hub-chip",children:"open"}):s.jsx("span",{className:"hub-chip",children:"restricted"})]}),s.jsx("div",{className:"hub-alias-list",children:ce?s.jsx("span",{className:"admin-hint",children:"Open — anyone who can trigger the agent may send to others."}):oe.length===0?s.jsx("span",{className:"admin-hint",children:"(empty — nobody may send to others)"}):oe.map(Z=>s.jsxs("div",{className:"hub-alias-row",children:[s.jsx("span",{className:"hub-chip",children:Z}),s.jsx("button",{className:"admin-refresh-btn",disabled:w,onClick:()=>le(H,Z),children:"✕"})]},`sa-${H}-${Z}`))}),s.jsxs("div",{className:"hub-send-form",children:[s.jsx("input",{type:"text",value:b[H]??"",onChange:Z=>x(_e=>({..._e,[H]:Z.target.value})),placeholder:"sender id, or Allow-All",disabled:w}),s.jsx("button",{className:"admin-refresh-btn",disabled:w||!(b[H]??"").trim(),onClick:()=>M(H),children:"+ Sender"}),ce?null:s.jsx("button",{className:"admin-refresh-btn",disabled:w,onClick:()=>me(H),children:"↺ Reset to open"})]}),s.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:6,marginTop:6},children:[s.jsx("input",{type:"checkbox",checked:!!X.requireApprovedTarget,disabled:w,onChange:()=>be(H)}),s.jsx("span",{className:"admin-hint",children:"Require approved recipients"})]})]},`sa-${H}`)})}),s.jsxs("div",{className:"hub-card",style:{marginTop:16},children:[s.jsxs("div",{className:"hub-card-top",children:[s.jsx("span",{className:"hub-chip",children:"🧠 Clarifying questions"}),N?s.jsx("span",{className:"hub-chip",children:"wait for reply"}):s.jsx("span",{className:"hub-chip",children:"assume option 1"}),N!==T?s.jsx("span",{className:"hub-chip",children:"· unsaved"}):null]}),s.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:6,marginTop:6},children:[s.jsx("input",{type:"checkbox",checked:N,disabled:w,onChange:()=>C(H=>!H)}),s.jsxs("span",{className:"admin-hint",children:["When the agent asks a question on a channel, ",s.jsx("strong",{children:"wait for the sender's reply"})," before acting. Off (default): the question is sent and the ",s.jsx("em",{children:"first"})," option is assumed immediately — so a reply typed afterwards arrives too late to change anything."]})]}),N?s.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:6,marginTop:6},children:[s.jsx("span",{className:"admin-hint",children:"Reply window (seconds)"}),s.jsx("input",{type:"number",min:5,max:600,value:Math.round(R/1e3),disabled:w,onChange:H=>L(Math.max(5,Math.min(600,Number(H.target.value)||120))*1e3),style:{width:90}}),s.jsx("span",{className:"admin-hint",children:"then the first option is used, and the timeout is logged."})]}):null]}),s.jsx("div",{style:{marginTop:12},children:s.jsx("button",{className:"admin-refresh-btn",disabled:w,onClick:()=>void Pe(),children:"💾 Save send authority"})}),o&&s.jsx("div",{className:"wizard-overlay",onClick:()=>l(null),children:s.jsxs("div",{className:"wizard-modal",onClick:H=>H.stopPropagation(),children:[s.jsxs("div",{className:"wizard-header",children:[s.jsx("span",{className:"wizard-icon",children:"✏️"}),s.jsxs("span",{className:"wizard-title",children:["Edit Contact: ",o.name]}),s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>l(null),children:"✕"})]}),s.jsxs("div",{className:"wizard-body",children:[s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:"Name"}),s.jsx("input",{type:"text",value:c,onChange:H=>u(H.target.value)})]}),s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:"Phone (optional, for flexible lookup)"}),s.jsx("input",{type:"text",value:d,onChange:H=>f(H.target.value),placeholder:"+918800123456"})]}),s.jsxs("p",{className:"admin-hint",children:["Platform: ",s.jsx("strong",{children:o.platform})," | ID: ",s.jsx("code",{children:o.id})]}),s.jsxs("div",{className:"wizard-nav",children:[s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>l(null),children:"Cancel"}),s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void P(),children:"Save"})]})]})]})})]})}function uo(e){if(e<=0)return"never";const t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60),i=Math.floor(r/24);return i>30?`${i}d ago`:i>0?`${i}d ${r%24}h ago`:r>0?`${r}h ${n%60}m ago`:n>0?`${n}m ago`:`${t}s ago`}function Xge(e,t,n){if(e==="unavailable")return"#f85149";if(e==="unverified")return"#d29922";const i=(Date.now()-t)/(24*60*60*1e3);return i>30&&n>.5?"#f85149":i>7?"#d29922":"#3fb950"}function Zge(e,t,n){if(e==="unavailable")return"Unavailable";if(e==="unverified")return"Unverified";const i=(Date.now()-t)/(24*60*60*1e3);return i>30&&n>.5?"Likely Removed":i>7?"Stale":"Fresh"}function Qge({entry:e}){const t=Date.now(),n=t-e.lastProbedAt,r=t-e.lastVerifiedAt,i=t-e.lastUsedAt,a=Math.min(100,n/(30*24*60*60*1e3)*100),o=e.lastVerifiedAt>0?Math.min(100,r/(30*24*60*60*1e3)*100):-1,l=e.lastUsedAt>0?Math.min(100,i/(30*24*60*60*1e3)*100):-1;return s.jsxs("div",{className:"timeline-bar-container",children:[s.jsx("div",{className:"timeline-bar",title:`Last probed: ${uo(n)}`,children:s.jsx("div",{className:"timeline-bar-fill probe",style:{width:`${a}%`}})}),o>=0&&s.jsx("div",{className:"timeline-bar small",title:`Last verified: ${uo(r)}`,children:s.jsx("div",{className:"timeline-bar-fill verify",style:{width:`${o}%`}})}),l>=0&&s.jsx("div",{className:"timeline-bar small",title:`Last used: ${uo(i)}`,children:s.jsx("div",{className:"timeline-bar-fill use",style:{width:`${l}%`}})})]})}function Jge(){const[e,t]=E.useState(null),[n,r]=E.useState(!0),[i,a]=E.useState(null),[o,l]=E.useState("all"),[c,u]=E.useState("provider"),d=E.useRef(!0),f=E.useCallback(async()=>{try{const v=await fetch("/api/model-timeline");if(!v.ok)throw new Error("Failed to fetch timeline data");const y=await v.json();d.current&&(t(y),a(null))}catch(v){d.current&&a(v instanceof Error?v.message:"Failed to load timeline")}finally{d.current&&r(!1)}},[]);if(E.useEffect(()=>{d.current=!0,f();const v=setInterval(f,3e4);return()=>{d.current=!1,clearInterval(v)}},[f]),n)return s.jsxs("div",{className:"admin-header",children:[s.jsx("h2",{className:"section-title",children:"📅 Model Discovery Timeline"}),s.jsxs("div",{className:"loading-state",children:[s.jsx("div",{className:"loading-spinner"}),s.jsx("p",{children:"Loading timeline..."})]})]});if(i)return s.jsxs("div",{className:"admin-header",children:[s.jsx("h2",{className:"section-title",children:"📅 Model Discovery Timeline"}),s.jsx("div",{className:"admin-row-msg admin-row-msg-err",children:i})]});const p=((e==null?void 0:e.entries)??[]).filter(v=>{const b=(Date.now()-v.lastProbedAt)/(24*60*60*1e3),x=b>7,k=b>30&&v.errorRate>.5,S=!x&&!k;return o==="fresh"?S:o==="stale"?x&&!k:o==="removed"?k:!0}),g=[...p].sort((v,y)=>{if(c==="provider")return v.provider.localeCompare(y.provider)||v.model.localeCompare(y.model);if(c==="lastProbed")return y.lastProbedAt-v.lastProbedAt;if(c==="status"){const b={unavailable:0,unverified:1,verified:2};return(b[y.status]??0)-(b[v.status]??0)}return 0}),m=new Map;for(const v of g)m.has(v.provider)||m.set(v.provider,[]),m.get(v.provider).push(v);return s.jsxs("div",{className:"admin-header",children:[s.jsx("h2",{className:"section-title",children:"📅 Model Discovery Timeline"}),s.jsxs("div",{className:"stats-grid",style:{marginBottom:16},children:[s.jsxs("div",{className:"stat-card",children:[s.jsx("div",{className:"stat-value",children:(e==null?void 0:e.totalModels)??0}),s.jsx("div",{className:"stat-label",children:"Total Models"})]}),s.jsxs("div",{className:"stat-card",style:{borderColor:"#3fb950"},children:[s.jsx("div",{className:"stat-value",style:{color:"#3fb950"},children:(e==null?void 0:e.freshCount)??0}),s.jsx("div",{className:"stat-label",children:"Fresh (<7d)"})]}),s.jsxs("div",{className:"stat-card",style:{borderColor:"#d29922"},children:[s.jsx("div",{className:"stat-value",style:{color:"#d29922"},children:(e==null?void 0:e.staleCount)??0}),s.jsx("div",{className:"stat-label",children:"Stale (7-30d)"})]}),s.jsxs("div",{className:"stat-card",style:{borderColor:"#f85149"},children:[s.jsx("div",{className:"stat-value",style:{color:"#f85149"},children:(e==null?void 0:e.removedCount)??0}),s.jsx("div",{className:"stat-label",children:"Likely Removed (>30d)"})]})]}),s.jsxs("div",{style:{display:"flex",gap:8,marginBottom:16,flexWrap:"wrap"},children:[s.jsx("div",{style:{display:"flex",gap:4},children:["all","fresh","stale","removed"].map(v=>s.jsx("button",{className:`admin-refresh-btn ${o===v?"active":""}`,onClick:()=>l(v),style:{background:o===v?"#238636":"#21262d",border:`1px solid ${o===v?"#3fb950":"#30363d"}`,padding:"4px 12px",fontSize:12,cursor:"pointer"},children:v.charAt(0).toUpperCase()+v.slice(1)},v))}),s.jsx("div",{style:{display:"flex",gap:4},children:["provider","lastProbed","status"].map(v=>s.jsxs("button",{className:`admin-refresh-btn ${c===v?"active":""}`,onClick:()=>u(v),style:{background:c===v?"#238636":"#21262d",border:`1px solid ${c===v?"#3fb950":"#30363d"}`,padding:"4px 12px",fontSize:12,cursor:"pointer"},children:["Sort: ",v==="lastProbed"?"Last Seen":v.charAt(0).toUpperCase()+v.slice(1)]},v))}),s.jsx("button",{className:"admin-refresh-btn",onClick:f,style:{background:"#21262d",border:"1px solid #30363d",padding:"4px 12px",fontSize:12,cursor:"pointer"},children:"🔄 Refresh"})]}),s.jsxs("div",{style:{display:"flex",gap:16,marginBottom:12,fontSize:11,color:"#8b949e"},children:[s.jsxs("span",{children:[s.jsx("span",{style:{color:"#58a6ff"},children:"■"})," Probe (last seen)"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#3fb950"},children:"■"})," Verified (last success)"]}),s.jsxs("span",{children:[s.jsx("span",{style:{color:"#d29922"},children:"■"})," Used (last invocation)"]})]}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:Array.from(m.entries()).map(([v,y])=>s.jsxs("div",{style:{background:"#161b22",borderRadius:8,border:"1px solid #30363d",overflow:"hidden"},children:[s.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid #30363d",display:"flex",alignItems:"center",gap:8},children:[s.jsx("span",{style:{fontSize:16},children:v==="groq"?"⚡":v==="gemini"?"🌀":v==="local"?"💻":"🤖"}),s.jsx("span",{style:{fontWeight:600,color:"#e6edf3"},children:v}),s.jsxs("span",{style:{fontSize:12,color:"#8b949e"},children:["(",y.length," models)"]})]}),s.jsx("div",{style:{padding:"8px 14px"},children:y.map(b=>{const x=Date.now();(x-b.lastProbedAt)/(24*60*60*1e3);const k=Xge(b.status,b.lastProbedAt,b.errorRate),S=Zge(b.status,b.lastProbedAt,b.errorRate);return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"6px 0",borderBottom:"1px solid #21262d"},children:[s.jsxs("div",{style:{flex:1,minWidth:0},children:[s.jsx("div",{style:{fontSize:13,color:"#e6edf3",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b.model}),s.jsxs("div",{style:{fontSize:11,color:"#8b949e",display:"flex",gap:12},children:[s.jsxs("span",{children:["Probed: ",uo(x-b.lastProbedAt)]}),b.lastVerifiedAt>0&&s.jsxs("span",{children:["Verified: ",uo(x-b.lastVerifiedAt)]}),b.lastUsedAt>0&&s.jsxs("span",{children:["Used: ",uo(x-b.lastUsedAt)]}),b.latencyMs!==void 0&&s.jsxs("span",{children:[b.latencyMs,"ms"]})]})]}),s.jsx(Qge,{entry:b}),s.jsx("div",{style:{fontSize:11,padding:"2px 8px",borderRadius:4,background:`${k}20`,color:k,border:`1px solid ${k}40`,whiteSpace:"nowrap"},children:S})]},b.model)})})]},v))}),p.length===0&&s.jsx("div",{style:{textAlign:"center",padding:"40px 20px",color:"#8b949e"},children:"No models match the current filter"})]})}function _a(e){return e==null?"0":e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}function eye(e){return e==null?"0%":(e*100).toFixed(1)+"%"}function tye({data:e}){var o,l;if(!e)return s.jsx("div",{className:"loading-state",children:s.jsx("p",{children:"Loading memory data..."})});const{memory:t,health:n}=e,r=Object.entries(t.byFingerprint||{}).sort(([,c],[,u])=>u-c),i=Object.entries(((o=t.facts)==null?void 0:o.byProject)||{}).sort(([,c],[,u])=>u-c),a=t.recall||{total:0,today:0,last7d:0};return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"💾 Memory Store"}),s.jsxs("div",{className:"stats-grid mini",children:[s.jsxs("div",{className:"stat-card",children:[s.jsx("div",{className:"stat-value",children:_a(t.total)}),s.jsx("div",{className:"stat-label",children:"Trajectories"})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("div",{className:"stat-value",children:eye(t.avgScore)}),s.jsx("div",{className:"stat-label",children:"Avg Score"})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("div",{className:"stat-value",children:_a((l=t.facts)==null?void 0:l.total)}),s.jsx("div",{className:"stat-label",children:"Facts"})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("div",{className:"stat-value",children:_a(a.total)}),s.jsx("div",{className:"stat-label",children:"Recall Hits"})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("div",{className:"stat-value",children:_a(n==null?void 0:n.patterns)}),s.jsx("div",{className:"stat-label",children:"Coding Patterns"})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("div",{className:"stat-value",children:_a(n==null?void 0:n.feedback)}),s.jsx("div",{className:"stat-label",children:"Feedback Ratings"})]})]}),s.jsxs("p",{className:"memory-backend",children:["Backend: ",s.jsx("code",{children:t.backend||"local"}),a.last7d>0?` · ${_a(a.last7d)} recall(s) this week, ${_a(a.today)} today`:" · no recalls yet"]}),r.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"section-subtitle",children:"By Project Type"}),s.jsx("div",{className:"memory-list",children:r.map(([c,u])=>s.jsxs("div",{className:"memory-item",children:[s.jsx("span",{className:"memory-project",children:c}),s.jsxs("span",{className:"memory-count",children:[u," trajectory(ies)"]})]},c))})]}),i.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"section-subtitle",children:"Facts by Project"}),s.jsx("div",{className:"memory-list",children:i.map(([c,u])=>s.jsxs("div",{className:"memory-item",children:[s.jsx("span",{className:"memory-project",children:c}),s.jsxs("span",{className:"memory-count",children:[u," fact(s)"]})]},c))})]})]})}function nye(e){return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function rye({data:e}){if(!e)return s.jsx("div",{className:"loading-state",children:s.jsx("p",{children:"Loading history..."})});const{history:t}=e,n=t.recent||[];return s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"section-title",children:"📝 Conversation History"}),s.jsx("div",{className:"history-stats",children:s.jsxs("span",{className:"history-count",children:["Total: ",s.jsx("strong",{children:t.total})," sessions"]})}),s.jsx("div",{className:"history-list",children:n.length===0?s.jsx("div",{className:"empty-state",children:"No conversations recorded yet."}):n.map(r=>s.jsxs("div",{className:"history-item",children:[s.jsx("div",{className:"history-summary",children:r.summary||"Untitled"}),s.jsxs("div",{className:"history-meta",children:[s.jsxs("span",{children:["📅 ",nye(r.startedAt)]}),s.jsxs("span",{children:["🤖 ",r.provider||"--"]}),s.jsxs("span",{children:["💬 ",r.messageCount||0," msgs"]}),r.tags&&r.tags.length>0&&s.jsxs("span",{children:["🏷️ ",r.tags.map(i=>s.jsx("span",{className:"history-tag",children:i},i))]})]})]},r.id))})]})}function iye({onFetch:e,onClear:t,onExport:n}){const[r,i]=E.useState([]),[a,o]=E.useState(!1),[l,c]=E.useState(""),[u,d]=E.useState(""),[f,h]=E.useState(null),[p,g]=E.useState(null);E.useEffect(()=>{m()},[l,u]);const m=async()=>{o(!0);try{const k=await e({skillName:l||void 0,status:u||void 0,limit:100});i(k);const S=k.length,w=k.filter(C=>C.status==="success").length,_=k.filter(C=>C.status==="failure").length,N=S>0?Math.round(k.reduce((C,T)=>C+T.durationMs,0)/S):0;g({total:S,success:w,failure:_,avgDuration:N})}catch(k){console.error("Failed to fetch execution history:",k)}finally{o(!1)}},v=async k=>{if(n)try{const S=await n(k),w=new Blob([S],{type:k==="json"?"application/json":"text/csv"}),_=URL.createObjectURL(w),N=document.createElement("a");N.href=_,N.download=`execution-history.${k}`,N.click(),URL.revokeObjectURL(_)}catch(S){console.error("Failed to export history:",S)}},y=async()=>{if(t&&confirm("Are you sure you want to clear all execution history?"))try{await t(),i([]),g(null)}catch(k){console.error("Failed to clear history:",k)}},b=k=>{switch(k){case"success":return"✅";case"failure":return"❌";case"timeout":return"⏰";case"rejected":return"🚫";case"error":return"💥";default:return"❓"}},x=k=>{switch(k){case"python":return"🐍";case"node":return"🟢";case"shell":return"🖥️";case"ruby":return"💎";case"go":return"🔵";case"rust":return"🦀";default:return"📜"}};return s.jsxs("div",{className:"execution-history",children:[s.jsxs("div",{className:"execution-history-header",children:[s.jsx("h3",{className:"execution-history-title",children:"📜 Execution History"}),s.jsxs("div",{className:"execution-history-actions",children:[s.jsx("button",{className:"admin-mini-btn",type:"button",onClick:()=>v("json"),children:"📥 Export JSON"}),s.jsx("button",{className:"admin-mini-btn",type:"button",onClick:()=>v("csv"),children:"📥 Export CSV"}),t&&s.jsx("button",{className:"admin-mini-btn admin-mini-btn-danger",type:"button",onClick:y,children:"🗑️ Clear"})]})]}),p&&s.jsxs("div",{className:"execution-history-stats",children:[s.jsxs("div",{className:"stat-item",children:[s.jsx("span",{className:"stat-value",children:p.total}),s.jsx("span",{className:"stat-label",children:"Total"})]}),s.jsxs("div",{className:"stat-item stat-success",children:[s.jsx("span",{className:"stat-value",children:p.success}),s.jsx("span",{className:"stat-label",children:"Success"})]}),s.jsxs("div",{className:"stat-item stat-failure",children:[s.jsx("span",{className:"stat-value",children:p.failure}),s.jsx("span",{className:"stat-label",children:"Failed"})]}),s.jsxs("div",{className:"stat-item",children:[s.jsxs("span",{className:"stat-value",children:[p.avgDuration,"ms"]}),s.jsx("span",{className:"stat-label",children:"Avg Duration"})]})]}),s.jsxs("div",{className:"execution-history-filters",children:[s.jsx("input",{className:"env-var-input",type:"text",placeholder:"Filter by skill name...",value:l,onChange:k=>c(k.target.value)}),s.jsxs("select",{className:"env-var-input",value:u,onChange:k=>d(k.target.value),children:[s.jsx("option",{value:"",children:"All statuses"}),s.jsx("option",{value:"success",children:"Success"}),s.jsx("option",{value:"failure",children:"Failure"}),s.jsx("option",{value:"timeout",children:"Timeout"}),s.jsx("option",{value:"rejected",children:"Rejected"}),s.jsx("option",{value:"error",children:"Error"})]})]}),s.jsx("div",{className:"execution-history-list",children:a?s.jsx("div",{className:"execution-history-empty",children:"Loading..."}):r.length===0?s.jsx("div",{className:"execution-history-empty",children:"No execution history found. Execute a skill to see results here."}):r.map(k=>s.jsxs("div",{className:`execution-history-entry ${k.status}`,onClick:()=>h((f==null?void 0:f.id)===k.id?null:k),children:[s.jsxs("div",{className:"entry-header",children:[s.jsx("span",{className:"entry-icon",children:b(k.status)}),s.jsx("span",{className:"entry-skill",children:k.skillName}),s.jsxs("span",{className:"entry-runtime",children:[x(k.runtime)," ",k.runtime]}),s.jsxs("span",{className:"entry-duration",children:[k.durationMs,"ms"]}),s.jsx("span",{className:"entry-time",children:new Date(k.timestamp).toLocaleString()}),s.jsx("span",{className:"entry-expand",children:(f==null?void 0:f.id)===k.id?"▼":"▶"})]}),(f==null?void 0:f.id)===k.id&&s.jsxs("div",{className:"entry-details",children:[s.jsxs("div",{className:"entry-detail-row",children:[s.jsx("span",{className:"detail-label",children:"Status:"}),s.jsx("span",{className:"detail-value",children:k.status})]}),s.jsxs("div",{className:"entry-detail-row",children:[s.jsx("span",{className:"detail-label",children:"Runtime:"}),s.jsx("span",{className:"detail-value",children:k.runtime})]}),s.jsxs("div",{className:"entry-detail-row",children:[s.jsx("span",{className:"detail-label",children:"Duration:"}),s.jsxs("span",{className:"detail-value",children:[k.durationMs,"ms"]})]}),k.exitCode!==void 0&&s.jsxs("div",{className:"entry-detail-row",children:[s.jsx("span",{className:"detail-label",children:"Exit Code:"}),s.jsx("span",{className:"detail-value",children:k.exitCode})]}),k.error&&s.jsxs("div",{className:"entry-detail-row",children:[s.jsx("span",{className:"detail-label",children:"Error:"}),s.jsx("span",{className:"detail-value entry-error",children:k.error})]}),k.command&&s.jsxs("div",{className:"entry-detail-row",children:[s.jsx("span",{className:"detail-label",children:"Command:"}),s.jsx("code",{className:"detail-value",children:k.command})]})]})]},k.id))})]})}function aye({envVars:e,onSave:t,onDelete:n,onTest:r,readOnly:i=!1}){const[a,o]=E.useState(null),[l,c]=E.useState(""),[u,d]=E.useState(!1),[f,h]=E.useState(""),[p,g]=E.useState(""),[m,v]=E.useState(null),[y,b]=E.useState({}),x=[...e].sort((_,N)=>_.requiredBy&&!N.requiredBy?-1:!_.requiredBy&&N.requiredBy?1:_.name.localeCompare(N.name)),k=_=>{t(_,l),o(null),c("")},S=()=>{f&&p&&(t(f,p),h(""),g(""),d(!1))},w=async _=>{if(r){v(_);try{const N=await r(_);b(C=>({...C,[_]:N}))}catch{b(N=>({...N,[_]:!1}))}finally{v(null)}}};return s.jsxs("div",{className:"env-var-editor",children:[s.jsxs("div",{className:"env-var-header",children:[s.jsx("h3",{className:"env-var-title",children:"🔐 Environment Variables"}),!i&&s.jsx("button",{className:"admin-mini-btn",type:"button",onClick:()=>d(!u),children:u?"✕ Cancel":"+ Add Variable"})]}),u&&!i&&s.jsxs("div",{className:"env-var-add-form",children:[s.jsx("input",{className:"env-var-input",type:"text",placeholder:"Variable name (e.g., MY_API_KEY)",value:f,onChange:_=>h(_.target.value)}),s.jsx("input",{className:"env-var-input",type:"password",placeholder:"Value",value:p,onChange:_=>g(_.target.value)}),s.jsx("button",{className:"admin-refresh-btn",type:"button",disabled:!f||!p,onClick:S,children:"💾 Save"})]}),s.jsx("div",{className:"env-var-list",children:x.length===0?s.jsx("div",{className:"env-var-empty",children:"No environment variables configured. Add one to get started."}):x.map(_=>s.jsxs("div",{className:`env-var-row ${_.isSet?"env-var-set":"env-var-missing"} ${_.isProviderCredential?"env-var-blocked":""}`,children:[s.jsxs("div",{className:"env-var-row-header",children:[s.jsxs("span",{className:"env-var-name",children:[_.name,_.requiredBy&&s.jsxs("span",{className:"env-var-required-badge",children:["required by ",_.requiredBy]}),_.isProviderCredential&&s.jsx("span",{className:"env-var-blocked-badge",children:"🔒 provider credential (blocked)"})]}),s.jsx("span",{className:"env-var-status",children:_.isSet?"✅ Set":"❌ Not set"})]}),_.description&&s.jsx("div",{className:"env-var-description",children:_.description}),a===_.name?s.jsxs("div",{className:"env-var-edit",children:[s.jsx("input",{className:"env-var-input",type:"password",value:l,onChange:N=>c(N.target.value),placeholder:"Enter new value..."}),s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>k(_.name),children:"💾 Save"}),s.jsx("button",{className:"admin-mini-btn",type:"button",onClick:()=>o(null),children:"Cancel"})]}):s.jsxs("div",{className:"env-var-actions",children:[!i&&!_.isProviderCredential&&s.jsx("button",{className:"admin-mini-btn",type:"button",onClick:()=>{o(_.name),c("")},children:"✏️ Edit"}),r&&s.jsx("button",{className:"admin-mini-btn",type:"button",disabled:m===_.name,onClick:()=>w(_.name),children:m===_.name?"⏳ Testing...":"🧪 Test"}),!i&&s.jsx("button",{className:"admin-mini-btn admin-mini-btn-danger",type:"button",onClick:()=>n(_.name),children:"🗑️ Delete"}),y[_.name]!==void 0&&s.jsx("span",{className:`env-var-test-result ${y[_.name]?"env-var-test-pass":"env-var-test-fail"}`,children:y[_.name]?"✅ Valid":"❌ Invalid"})]})]},_.name))}),s.jsx("div",{className:"env-var-help",children:s.jsxs("p",{children:[s.jsx("strong",{children:"Tip:"})," Environment variables are stored in ",s.jsx("code",{children:"~/.nuvira/.env"})," and injected into skill executions. Provider credentials (ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.) are automatically blocked from skill execution for security."]})})]})}function sye(){const[e,t]=E.useState({configured:!1,authenticated:!1,role:null}),[n,r]=E.useState([]),[i,a]=E.useState(!0),[o,l]=E.useState(null),[c,u]=E.useState(null),d=e.authenticated&&(e.role==="admin"||e.role==="operator"),f=E.useCallback(async()=>{a(!0);const m=await ee.fetchSkillEnv();r(m),a(!1)},[]);E.useEffect(()=>{ee.fetchAdminAuthStatus().then(m=>{t(m?{configured:m.configured,authenticated:m.authenticated,role:m.role??null}:{configured:!1,authenticated:!1,role:null})}),f()},[f]);const h=E.useCallback(async(m,v)=>{var x;l(null),u(null);const y=await ee.saveSecrets({[m]:v}),b=(x=y.refused)==null?void 0:x.find(k=>k.name===m);!y.ok||b?l(b?oye(m,b.reason):y.error||`Could not save ${m}.`):u(`Saved ${m}.`),await f()},[f]),p=E.useCallback(async m=>{l(null),u(null);const v=await ee.deleteSkillEnvVar(m);v.ok?u(v.removed?`Deleted ${m}.`:`${m} was not stored in the env file.`):l(v.error||`Could not delete ${m}.`),await f()},[f]),g=E.useCallback(async m=>{const v=await ee.testSkillEnvVar(m);return v.ok?(l(null),u(v.detail||`${m}: ${v.usable?"usable by skills":"not usable by skills"}`),v.usable===!0):(l(v.error||`Could not test ${m}.`),!1)},[]);return s.jsxs("div",{children:[s.jsx("h2",{className:"section-title",children:"🔐 Skill Environment Variables"}),s.jsxs("div",{className:"env-var-header",children:[s.jsx("span",{className:"env-var-title",children:"Values are masked; only names and set/unset state are shown."}),s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>void f(),children:"↻ Refresh"})]}),s.jsxs("div",{className:"admin-hint",children:["Secrets here are injected into skill executions that declare them (",s.jsx("code",{children:"required_environment_variables"}),"). Provider credentials are listed but locked — they belong to provider setup, and skills never receive them."]}),e.authenticated?null:s.jsx("div",{className:"admin-hint",children:e.configured?"Log in to view or edit skill secrets.":"Set up an admin account to manage skill secrets."}),e.authenticated&&!d?s.jsx("div",{className:"admin-hint",children:"Read-only — admins and operators can change these values."}):null,o?s.jsx("div",{className:"env-var-notice env-var-notice-error",children:o}):null,c?s.jsx("div",{className:"env-var-notice",children:c}):null,i?s.jsx("div",{className:"loading-state",children:"Loading…"}):s.jsx(aye,{envVars:n,onSave:(m,v)=>void h(m,v),onDelete:m=>void p(m),onTest:g,readOnly:!d})]})}function oye(e,t){switch(t){case"provider-credential":return`${e} is a provider credential — configure it in provider setup instead. Skills never receive it.`;case"invalid-name":return`${e} is not a valid environment variable name.`;case"write-failed":return`${e} could not be written to the env file.`;default:return`${e} was not saved (${t}).`}}function lye(){const[e,t]=E.useState(null),[n,r]=E.useState(!1),[i,a]=E.useState("--"),o=E.useCallback(c=>{t(c),a(new Date().toLocaleTimeString())},[]),l=E.useCallback(c=>{r(c)},[]);return E.useEffect(()=>{ee.fetchAll().then(d=>{d&&o(d)});const c=ee.subscribe(o),u=ee.onConnectionChange(l);return ee.connect(),()=>{c(),u(),ee.disconnect()}},[o,l]),s.jsx(WL,{connected:n,lastUpdated:i,children:s.jsxs(EL,{children:[s.jsx(at,{path:"/",element:s.jsx(ZN,{})}),s.jsx(at,{path:"/overview",element:s.jsx(xie,{data:e})}),s.jsx(at,{path:"/chat",element:s.jsx(d1,{to:"/",replace:!0})}),s.jsx(at,{path:"/dag",element:s.jsx(Tie,{data:e})}),s.jsx(at,{path:"/costs",element:s.jsx(Oie,{data:e})}),s.jsx(at,{path:"/benchmarks",element:s.jsx(Mie,{data:e})}),s.jsx(at,{path:"/models",element:s.jsx(gae,{})}),s.jsx(at,{path:"/models/timeline",element:s.jsx(Jge,{})}),s.jsx(at,{path:"/routing",element:s.jsx(Zae,{data:e})}),s.jsx(at,{path:"/requests",element:s.jsx(ese,{data:e})}),s.jsx(at,{path:"/traces",element:s.jsx(use,{})}),s.jsx(at,{path:"/hub",element:s.jsx(Sse,{})}),s.jsx(at,{path:"/tasks",element:s.jsx(_se,{})}),s.jsx(at,{path:"/chat",element:s.jsx(ZN,{})}),s.jsx(at,{path:"/evals",element:s.jsx(Wge,{data:e})}),s.jsx(at,{path:"/platforms",element:s.jsx(qge,{})}),s.jsx(at,{path:"/bedrock",element:s.jsx(Vge,{canWrite:!0,sessionExpired:c=>console.error(c)})}),s.jsx(at,{path:"/contacts",element:s.jsx(Yge,{})}),s.jsx(at,{path:"/gateway",element:s.jsx(Gge,{})}),s.jsx(at,{path:"/env",element:s.jsx(sye,{})}),s.jsx(at,{path:"/memory",element:s.jsx(tye,{data:e})}),s.jsx(at,{path:"/history",element:s.jsx(rye,{data:e})}),s.jsx(at,{path:"/executions",element:s.jsx(iye,{onFetch:c=>ee.fetchExecutionAudit(c)})}),s.jsx(at,{path:"/system",element:s.jsx(Rie,{data:e})}),s.jsx(at,{path:"/admin",element:s.jsx(mse,{})}),s.jsx(at,{path:"*",element:s.jsx(d1,{to:"/",replace:!0})})]})})}fT(document.getElementById("root")).render(s.jsx(E.StrictMode,{children:s.jsx(PL,{children:s.jsx(lye,{})})}));
|
|
207
|
-
//# sourceMappingURL=index-
|
|
207
|
+
//# sourceMappingURL=index-kCUkORm7.js.map
|