agent-nuvira 3.3.1 → 3.3.3
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/README.md +5 -8
- package/dist/agents/agents/runner.d.ts +9 -0
- package/dist/agents/agents/runner.d.ts.map +1 -1
- package/dist/agents/agents/runner.js +34 -12
- package/dist/agents/agents/runner.js.map +1 -1
- package/dist/agents/agents/writer-tool-calling.d.ts.map +1 -1
- package/dist/agents/agents/writer-tool-calling.js +7 -2
- package/dist/agents/agents/writer-tool-calling.js.map +1 -1
- package/dist/agents/agents/writer.d.ts.map +1 -1
- package/dist/agents/agents/writer.js +7 -1
- package/dist/agents/agents/writer.js.map +1 -1
- package/dist/agents/artifact-verification.d.ts +102 -0
- package/dist/agents/artifact-verification.d.ts.map +1 -0
- package/dist/agents/artifact-verification.js +216 -0
- package/dist/agents/artifact-verification.js.map +1 -0
- package/dist/agents/checkpoint-store.d.ts +73 -0
- package/dist/agents/checkpoint-store.d.ts.map +1 -1
- package/dist/agents/checkpoint-store.js +161 -0
- package/dist/agents/checkpoint-store.js.map +1 -1
- package/dist/agents/credential-store.d.ts +120 -0
- package/dist/agents/credential-store.d.ts.map +1 -1
- package/dist/agents/credential-store.js +358 -19
- package/dist/agents/credential-store.js.map +1 -1
- package/dist/agents/orchestrator.d.ts +10 -1
- package/dist/agents/orchestrator.d.ts.map +1 -1
- package/dist/agents/orchestrator.js +234 -75
- package/dist/agents/orchestrator.js.map +1 -1
- package/dist/agents/phase-engine.d.ts +61 -0
- package/dist/agents/phase-engine.d.ts.map +1 -1
- package/dist/agents/phase-engine.js +68 -2
- package/dist/agents/phase-engine.js.map +1 -1
- package/dist/agents/prompt-assembly.d.ts +11 -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/agents/release-preflight.d.ts +121 -0
- package/dist/agents/release-preflight.d.ts.map +1 -0
- package/dist/agents/release-preflight.js +259 -0
- package/dist/agents/release-preflight.js.map +1 -0
- package/dist/agents/release-runner.d.ts +157 -0
- package/dist/agents/release-runner.d.ts.map +1 -0
- package/dist/agents/release-runner.js +719 -0
- package/dist/agents/release-runner.js.map +1 -0
- package/dist/agents/step-handoff.d.ts +190 -0
- package/dist/agents/step-handoff.d.ts.map +1 -0
- package/dist/agents/step-handoff.js +443 -0
- package/dist/agents/step-handoff.js.map +1 -0
- package/dist/cli/benchmark.d.ts.map +1 -1
- package/dist/cli/benchmark.js +11 -4
- package/dist/cli/benchmark.js.map +1 -1
- package/dist/cli/chat.d.ts.map +1 -1
- package/dist/cli/chat.js +25 -4
- package/dist/cli/chat.js.map +1 -1
- package/dist/cli/cli-program.d.ts.map +1 -1
- package/dist/cli/cli-program.js +3 -0
- package/dist/cli/cli-program.js.map +1 -1
- package/dist/cli/credentials.d.ts +28 -0
- package/dist/cli/credentials.d.ts.map +1 -0
- package/dist/cli/credentials.js +213 -0
- package/dist/cli/credentials.js.map +1 -0
- package/dist/cli/failover-runner.d.ts.map +1 -1
- package/dist/cli/failover-runner.js +9 -3
- package/dist/cli/failover-runner.js.map +1 -1
- package/dist/cli/loop-executor.d.ts.map +1 -1
- package/dist/cli/loop-executor.js +74 -7
- package/dist/cli/loop-executor.js.map +1 -1
- package/dist/cli/nlu.d.ts.map +1 -1
- package/dist/cli/nlu.js +8 -2
- package/dist/cli/nlu.js.map +1 -1
- package/dist/cli/publish.d.ts +22 -0
- package/dist/cli/publish.d.ts.map +1 -1
- package/dist/cli/publish.js +109 -13
- package/dist/cli/publish.js.map +1 -1
- package/dist/config/live-credentials.d.ts +57 -0
- package/dist/config/live-credentials.d.ts.map +1 -0
- package/dist/config/live-credentials.js +126 -0
- package/dist/config/live-credentials.js.map +1 -0
- package/dist/config/paths.d.ts +18 -0
- package/dist/config/paths.d.ts.map +1 -1
- package/dist/config/paths.js +25 -0
- package/dist/config/paths.js.map +1 -1
- package/dist/federation/a2a-types.js +1 -1
- package/dist/federation/a2a-types.js.map +1 -1
- package/dist/inference/model-validator.d.ts +6 -1
- package/dist/inference/model-validator.d.ts.map +1 -1
- package/dist/inference/model-validator.js +7 -2
- package/dist/inference/model-validator.js.map +1 -1
- package/dist/inference/route-resolver.d.ts +116 -0
- package/dist/inference/route-resolver.d.ts.map +1 -0
- package/dist/inference/route-resolver.js +159 -0
- package/dist/inference/route-resolver.js.map +1 -0
- package/dist/learning/autonomy-policy.d.ts +18 -0
- package/dist/learning/autonomy-policy.d.ts.map +1 -1
- package/dist/learning/autonomy-policy.js +35 -0
- package/dist/learning/autonomy-policy.js.map +1 -1
- package/dist/learning/reasoning-trace.d.ts +1 -1
- package/dist/learning/reasoning-trace.d.ts.map +1 -1
- package/dist/learning/reasoning-trace.js +25 -1
- package/dist/learning/reasoning-trace.js.map +1 -1
- package/dist/learning/resilient-call.d.ts.map +1 -1
- package/dist/learning/resilient-call.js +29 -17
- package/dist/learning/resilient-call.js.map +1 -1
- package/dist/learning/skill-store.d.ts.map +1 -1
- package/dist/learning/skill-store.js +30 -9
- package/dist/learning/skill-store.js.map +1 -1
- package/dist/mcp/catalog.js +2 -3
- package/dist/mcp/catalog.js.map +1 -1
- package/dist/mcp/manager.d.ts.map +1 -1
- package/dist/mcp/manager.js +5 -3
- package/dist/mcp/manager.js.map +1 -1
- package/dist/skills/secret-capture.d.ts.map +1 -1
- package/dist/skills/secret-capture.js +9 -4
- package/dist/skills/secret-capture.js.map +1 -1
- package/dist/tools/credentials-tool.d.ts +24 -0
- package/dist/tools/credentials-tool.d.ts.map +1 -0
- package/dist/tools/credentials-tool.js +125 -0
- package/dist/tools/credentials-tool.js.map +1 -0
- package/dist/tools/git-tool.d.ts +25 -7
- package/dist/tools/git-tool.d.ts.map +1 -1
- package/dist/tools/git-tool.js +155 -15
- package/dist/tools/git-tool.js.map +1 -1
- package/dist/tools/loop-project-context.d.ts.map +1 -1
- package/dist/tools/loop-project-context.js +16 -0
- package/dist/tools/loop-project-context.js.map +1 -1
- package/dist/tools/loop-route-feed.d.ts +57 -0
- package/dist/tools/loop-route-feed.d.ts.map +1 -0
- package/dist/tools/loop-route-feed.js +101 -0
- package/dist/tools/loop-route-feed.js.map +1 -0
- package/dist/tools/pipeline-tool.d.ts.map +1 -1
- package/dist/tools/pipeline-tool.js +8 -2
- package/dist/tools/pipeline-tool.js.map +1 -1
- package/dist/tools/publish-tool.d.ts.map +1 -1
- package/dist/tools/publish-tool.js +76 -10
- package/dist/tools/publish-tool.js.map +1 -1
- package/dist/tools/registry.d.ts +21 -1
- package/dist/tools/registry.d.ts.map +1 -1
- package/dist/tools/registry.js +44 -6
- package/dist/tools/registry.js.map +1 -1
- package/dist/tools/run-terminal.d.ts +9 -0
- package/dist/tools/run-terminal.d.ts.map +1 -1
- package/dist/tools/run-terminal.js +80 -2
- package/dist/tools/run-terminal.js.map +1 -1
- package/dist/tools/tool-loop.d.ts +12 -5
- package/dist/tools/tool-loop.d.ts.map +1 -1
- package/dist/tools/tool-loop.js +148 -0
- package/dist/tools/tool-loop.js.map +1 -1
- package/dist/tools/toolsets.js +2 -2
- package/dist/tools/toolsets.js.map +1 -1
- package/dist/workflow/registry.js +1 -1
- package/dist/workflow/registry.js.map +1 -1
- package/package.json +5 -4
- package/src/web-dashboard/public/assets/{index-CjvoBhlz.js → index-CxDj7p6i.js} +2 -2
- package/src/web-dashboard/public/assets/{index-CjvoBhlz.js.map → index-CxDj7p6i.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 lne(e,t){if(e){if(typeof e=="string")return LE(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 LE(e,t)}}function LE(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 cne(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 une(e){if(Array.isArray(e))return e}function Mv(){return Mv=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},Mv.apply(this,arguments)}var dne=function(t,n){var r;return H.isValidElement(t)?r=H.cloneElement(t,n):De(t)?r=t(n):r=H.createElement("line",Mv({},n,{className:"recharts-reference-line-line"})),r},fne=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(Yr(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(Yr(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 Yr(u,"discard")&&Iee(S,function(w){return!t.isInRange(w)})?null:S}return null};function hne(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=Kte(),d=jP(i),f=AP(a),h=Xte();if(!u||!h)return null;mi(c===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.');var p=r0({x:d.scale,y:f.scale}),g=Ut(t),m=Ut(n),v=r&&r.length===2,y=fne(p,g,m,v,h,e.position,d.orientation,f.orientation,e);if(!y)return null;var b=sne(y,2),x=b[0],k=x.x,S=x.y,w=b[1],_=w.x,N=w.y,C=Yr(e,"hidden")?"url(#".concat(u,")"):void 0,T=$E($E({clipPath:C},Ke(e,!0)),{},{x1:k,y1:S,x2:_,y2:N});return H.createElement(Yt,{className:Ve("recharts-reference-line",l)},dne(o,T),mn.renderCallByParent(e,Ete({x1:k,y1:S,x2:_,y2:N})))}var c0=function(e){function t(){return Qte(this,t),tne(this,t,arguments)}return ine(t,e),ene(t,[{key:"render",value:function(){return H.createElement(hne,this.props)}}])}(H.Component);l0(c0,"displayName","ReferenceLine");l0(c0,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,fill:"none",stroke:"#ccc",fillOpacity:1,strokeWidth:1,position:"middle"});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){Tp(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 pne(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function mne(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,PP(r.key),r)}}function gne(e,t,n){return t&&mne(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function yne(e,t,n){return t=uh(t),vne(e,OP()?Reflect.construct(t,n||[],uh(e).constructor):t.apply(e,n))}function vne(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 bne(e)}function bne(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function OP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(OP=function(){return!!e})()}function uh(e){return uh=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},uh(e)}function xne(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 Tp(e,t,n){return t=PP(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function PP(e){var t=wne(e,"string");return Io(t)=="symbol"?t:t+""}function wne(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 Sne=function(t){var n=t.x,r=t.y,i=t.xAxis,a=t.yAxis,o=r0({x:i.scale,y:a.scale}),l=o.apply({x:n,y:r},{bandAware:!0});return Yr(t,"discard")&&!o.isInRange(l)?null:l},Cp=function(e){function t(){return pne(this,t),yne(this,t,arguments)}return xne(t,e),gne(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(mi(l===void 0,'The alwaysShow prop is deprecated. Please use ifOverflow="extendDomain" instead.'),!u||!d)return null;var f=Sne(this.props);if(!f)return null;var h=f.x,p=f.y,g=this.props,m=g.shape,v=g.className,y=Yr(this.props,"hidden")?"url(#".concat(c,")"):void 0,b=BE(BE({clipPath:y},Ke(this.props,!0)),{},{cx:h,cy:p});return H.createElement(Yt,{className:Ve("recharts-reference-dot",v)},t.renderDot(m,b),mn.renderCallByParent(this.props,{x:h-o,y:p-o,width:2*o,height:2*o}))}}])}(H.Component);Tp(Cp,"displayName","ReferenceDot");Tp(Cp,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,r:10,fill:"#fff",stroke:"#ccc",fillOpacity:1,strokeWidth:1});Tp(Cp,"renderDot",function(e,t){var n;return H.isValidElement(e)?n=H.cloneElement(e,t):De(e)?n=e(t):n=H.createElement(cP,Rv({},t,{cx:t.cx,cy:t.cy,className:"recharts-reference-dot-dot"})),n});function $v(){return $v=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},$v.apply(this,arguments)}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 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 FE(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){Op(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 kne(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Ene(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 _ne(e,t,n){return t&&Ene(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Nne(e,t,n){return t=dh(t),jne(e,MP()?Reflect.construct(t,n||[],dh(e).constructor):t.apply(e,n))}function jne(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 Ane(e)}function Ane(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 dh(e){return dh=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},dh(e)}function Tne(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 Op(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=Cne(e,"string");return $o(t)=="symbol"?t:t+""}function Cne(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 One=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=r0({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 Yr(a,"discard")&&(!h.isInRange(p)||!h.isInRange(g))?null:xP(p,g)},Pp=function(e){function t(){return kne(this,t),Nne(this,t,arguments)}return Tne(t,e),_ne(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;mi(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=One(f,h,p,g,this.props);if(!v&&!m)return null;var y=Yr(this.props,"hidden")?"url(#".concat(d,")"):void 0;return H.createElement(Yt,{className:Ve("recharts-reference-area",c)},t.renderRect(m,FE(FE({clipPath:y},Ke(this.props,!0)),v)),mn.renderCallByParent(this.props,v))}}])}(H.Component);Op(Pp,"displayName","ReferenceArea");Op(Pp,"defaultProps",{isFront:!1,ifOverflow:"discard",xAxisId:0,yAxisId:0,r:10,fill:"#ccc",fillOpacity:.5,stroke:"none",strokeWidth:1});Op(Pp,"renderRect",function(e,t){var n;return H.isValidElement(e)?n=H.cloneElement(e,t):De(e)?n=e(t):n=H.createElement(n0,$v({},t,{className:"recharts-reference-area-rect"})),n});function IP(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 Pne(e,t,n){var r={width:e.width+t.width,height:e.height+t.height};return Nte(r,n)}function Mne(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 fh(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 Rne(e,t){return IP(e,t+1)}function Ine(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:IP(r,u)};var m=c,v,y=function(){return v===void 0&&(v=n(g,m)),v},b=g.coordinate,x=c===0||fh(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 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 UE(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?UE(Object(n),!0).forEach(function(r){$ne(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):UE(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function $ne(e,t,n){return t=Lne(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Lne(e){var t=Dne(e,"string");return ou(t)=="symbol"?t:t+""}function Dne(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(t==="string"?String:Number)(e)}function Bne(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=fh(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 zne(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=fh(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 _=fh(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 u0(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)||Su.isSsr)return Rne(i,typeof c=="number"&&ue(c)?c:0);var h=[],p=l==="top"||l==="bottom"?"width":"height",g=d&&p==="width"?tc(d,{fontSize:t,letterSpacing:n}):{width:0,height:0},m=function(x,k){var S=De(u)?u(x.value,k):x.value;return p==="width"?Pne(tc(S,{fontSize:t,letterSpacing:n}),g,f):tc(S,{fontSize:t,letterSpacing:n})[p]},v=i.length>=2?Nr(i[1].coordinate-i[0].coordinate):1,y=Mne(a,v,p);return c==="equidistantPreserveStart"?Ine(v,y,m,i,o):(c==="preserveStart"||c==="preserveStartEnd"?h=zne(v,y,m,i,o,c==="preserveStartEnd"):h=Bne(v,y,m,i,o),h.filter(function(b){return b.isShow}))}var Fne=["viewBox"],Une=["viewBox"],Wne=["ticks"];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 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 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 Dt(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){d0(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 Km(e,t){if(e==null)return{};var n=Hne(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 Hne(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 Gne(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function HE(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,LP(r.key),r)}}function qne(e,t,n){return t&&HE(e.prototype,t),n&&HE(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function Kne(e,t,n){return t=hh(t),Vne(e,$P()?Reflect.construct(t,n||[],hh(e).constructor):t.apply(e,n))}function Vne(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 Yne(e)}function Yne(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 Xne(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&&Dv(e,t)}function Dv(e,t){return Dv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,i){return r.__proto__=i,r},Dv(e,t)}function d0(e,t,n){return t=LP(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function LP(e){var t=Zne(e,"string");return Lo(t)=="symbol"?t:t+""}function Zne(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)}var ol=function(e){function t(n){var r;return Gne(this,t),r=Kne(this,t,[n]),r.state={fontSize:"",letterSpacing:""},r}return Xne(t,e),qne(t,[{key:"shouldComponentUpdate",value:function(r,i){var a=r.viewBox,o=Km(r,Fne),l=this.props,c=l.viewBox,u=Km(l,Une);return!lo(a,c)||!lo(o,u)||!lo(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({},Ke(this.props,!1)),Ke(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 H.createElement("line",Js({},f,{className:Ve("recharts-cartesian-axis-line",cr(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=u0(Dt(Dt({},this.props),{},{ticks:r}),i,a),g=this.getTickTextAnchor(),m=this.getTickVerticalAnchor(),v=Ke(this.props,!1),y=Ke(d,!1),b=Dt(Dt({},v),{},{fill:"none"},Ke(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 H.createElement(Yt,Js({className:"recharts-cartesian-axis-tick",key:"tick-".concat(k.value,"-").concat(k.coordinate,"-").concat(k.tickCoord)},bf(o.props,k,S)),c&&H.createElement("line",Js({},b,_,{className:Ve("recharts-cartesian-axis-tick-line",cr(c,"className"))})),d&&t.renderTickItem(d,C,"".concat(De(f)?f(k.value,S):k.value).concat(h||"")))});return H.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,Wne),g=h;return De(c)&&(g=h&&h.length>0?c(this.props):c(p)),o<=0||l<=0||!g||!g.length?null:H.createElement(Yt,{className:Ve("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=Ve(i.className,"recharts-cartesian-axis-tick-value");return H.isValidElement(r)?o=H.cloneElement(r,Dt(Dt({},i),{},{className:l})):De(r)?o=r(Dt(Dt({},i),{},{className:l})):o=H.createElement(Mf,Js({},i,{className:"recharts-cartesian-axis-tick-value"}),a),o}}])}(E.Component);d0(ol,"displayName","CartesianAxis");d0(ol,"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 Qne=["x1","y1","x2","y2","key"],Jne=["offset"];function us(e){"@babel/helpers - typeof";return us=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},us(e)}function GE(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?GE(Object(n),!0).forEach(function(r){ere(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):GE(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function ere(e,t,n){return t=tre(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function tre(e){var t=nre(e,"string");return us(t)=="symbol"?t:t+""}function nre(e,t){if(us(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(us(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Ga(){return Ga=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},Ga.apply(this,arguments)}function qE(e,t){if(e==null)return{};var n=rre(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 rre(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 ire=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 H.createElement("rect",{x:i,y:a,ry:c,width:o,height:l,stroke:"none",fill:n,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function DP(e,t){var n;if(H.isValidElement(e))n=H.cloneElement(e,t);else if(De(e))n=e(t);else{var r=t.x1,i=t.y1,a=t.x2,o=t.y2,l=t.key,c=qE(t,Qne),u=Ke(c,!1);u.offset;var d=qE(u,Jne);n=H.createElement("line",Ga({},d,{x1:r,y1:i,x2:a,y2:o,fill:"none",key:l}))}return n}function are(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 DP(i,u)});return H.createElement("g",{className:"recharts-cartesian-grid-horizontal"},o)}function sre(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 DP(i,u)});return H.createElement("g",{className:"recharts-cartesian-grid-vertical"},o)}function ore(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 H.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 H.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},f)}function lre(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 H.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 H.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},f)}var cre=function(t,n){var r=t.xAxis,i=t.width,a=t.height,o=t.offset;return KO(u0(gn(gn(gn({},ol.defaultProps),r),{},{ticks:fi(r,!0),viewBox:{x:0,y:0,width:i,height:a}})),o.left,o.left+o.width,n)},ure=function(t,n){var r=t.yAxis,i=t.width,a=t.height,o=t.offset;return KO(u0(gn(gn(gn({},ol.defaultProps),r),{},{ticks:fi(r,!0),viewBox:{x:0,y:0,width:i,height:a}})),o.top,o.top+o.height,n)},Ps={horizontal:!0,vertical:!0,stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function qi(e){var t,n,r,i,a,o,l=s0(),c=o0(),u=Zte(),d=gn(gn({},e),{},{stroke:(t=e.stroke)!==null&&t!==void 0?t:Ps.stroke,fill:(n=e.fill)!==null&&n!==void 0?n:Ps.fill,horizontal:(r=e.horizontal)!==null&&r!==void 0?r:Ps.horizontal,horizontalFill:(i=e.horizontalFill)!==null&&i!==void 0?i:Ps.horizontalFill,vertical:(a=e.vertical)!==null&&a!==void 0?a:Ps.vertical,verticalFill:(o=e.verticalFill)!==null&&o!==void 0?o:Ps.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=Vte(),x=Yte();if(!ue(p)||p<=0||!ue(g)||g<=0||!ue(f)||f!==+f||!ue(h)||h!==+h)return null;var k=d.verticalCoordinatesGenerator||cre,S=d.horizontalCoordinatesGenerator||ure,w=d.horizontalPoints,_=d.verticalPoints;if((!w||!w.length)&&De(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);mi(Array.isArray(C),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(us(C),"]")),Array.isArray(C)&&(w=C)}if((!_||!_.length)&&De(k)){var T=y&&y.length,I=k({xAxis:b?gn(gn({},b),{},{ticks:T?y:b.ticks}):void 0,width:l,height:c,offset:u},T?!0:m);mi(Array.isArray(I),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(us(I),"]")),Array.isArray(I)&&(_=I)}return H.createElement("g",{className:"recharts-cartesian-grid"},H.createElement(ire,{fill:d.fill,fillOpacity:d.fillOpacity,x:d.x,y:d.y,width:d.width,height:d.height,ry:d.ry}),H.createElement(are,Ga({},d,{offset:u,horizontalPoints:w,xAxis:b,yAxis:x})),H.createElement(sre,Ga({},d,{offset:u,verticalPoints:_,xAxis:b,yAxis:x})),H.createElement(ore,Ga({},d,{horizontalPoints:w})),H.createElement(lre,Ga({},d,{verticalPoints:_})))}qi.displayName="CartesianGrid";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 dre(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function fre(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 hre(e,t,n){return t&&fre(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function pre(e,t,n){return t=ph(t),mre(e,BP()?Reflect.construct(t,n||[],ph(e).constructor):t.apply(e,n))}function mre(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 gre(e)}function gre(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 yre(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=vre(e,"string");return Do(t)=="symbol"?t:t+""}function vre(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)}function bre(e){var t=e.xAxisId,n=s0(),r=o0(),i=jP(t);return i==null?null:E.createElement(ol,zv({},i,{className:Ve("recharts-".concat(i.axisType," ").concat(i.axisType),i.className),viewBox:{x:0,y:0,width:n,height:r},ticksGenerator:function(o){return fi(o,!0)}}))}var Wr=function(e){function t(){return dre(this,t),pre(this,t,arguments)}return yre(t,e),hre(t,[{key:"render",value:function(){return E.createElement(bre,this.props)}}])}(E.Component);zP(Wr,"displayName","XAxis");zP(Wr,"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 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 xre(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function wre(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,HP(r.key),r)}}function Sre(e,t,n){return t&&wre(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function kre(e,t,n){return t=mh(t),Ere(e,UP()?Reflect.construct(t,n||[],mh(e).constructor):t.apply(e,n))}function Ere(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 _re(e)}function _re(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function UP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(UP=function(){return!!e})()}function mh(e){return mh=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},mh(e)}function Nre(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&&Fv(e,t)}function Fv(e,t){return Fv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,i){return r.__proto__=i,r},Fv(e,t)}function WP(e,t,n){return t=HP(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function HP(e){var t=jre(e,"string");return Bo(t)=="symbol"?t:t+""}function jre(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 String(e)}function Uv(){return Uv=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},Uv.apply(this,arguments)}var Are=function(t){var n=t.yAxisId,r=s0(),i=o0(),a=AP(n);return a==null?null:E.createElement(ol,Uv({},a,{className:Ve("recharts-".concat(a.axisType," ").concat(a.axisType),a.className),viewBox:{x:0,y:0,width:r,height:i},ticksGenerator:function(l){return fi(l,!0)}}))},Hr=function(e){function t(){return xre(this,t),kre(this,t,arguments)}return Nre(t,e),Sre(t,[{key:"render",value:function(){return E.createElement(Are,this.props)}}])}(E.Component);WP(Hr,"displayName","YAxis");WP(Hr,"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 KE(e){return Pre(e)||Ore(e)||Cre(e)||Tre()}function Tre(){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 Cre(e,t){if(e){if(typeof e=="string")return Wv(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 Wv(e,t)}}function Ore(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Pre(e){if(Array.isArray(e))return Wv(e)}function Wv(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 Hv=function(t,n,r,i,a){var o=Tr(t,c0),l=Tr(t,Cp),c=[].concat(KE(o),KE(l)),u=Tr(t,Pp),d="".concat(i,"Id"),f=i[0],h=n;if(c.length&&(h=c.reduce(function(m,v){if(v.props[d]===r&&Yr(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&&Yr(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},GP={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})(GP);var Mre=GP.exports;const Rre=Ze(Mre);var Vm=new Rre,Ym="recharts.syncMouseEvents";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 Ire(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function $re(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,qP(r.key),r)}}function Lre(e,t,n){return t&&$re(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function Xm(e,t,n){return t=qP(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function qP(e){var t=Dre(e,"string");return lu(t)=="symbol"?t:t+""}function Dre(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 String(e)}var Bre=function(){function e(){Ire(this,e),Xm(this,"activeIndex",0),Xm(this,"coordinateList",[]),Xm(this,"layout","horizontal")}return Lre(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 zre(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 Fre(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 KP(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 Ure(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 KP(t);return[{x:r,y:i},{x:a,y:o}]}function cu(e){"@babel/helpers - typeof";return cu=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},cu(e)}function VE(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 hd(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?VE(Object(n),!0).forEach(function(r){Wre(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):VE(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Wre(e,t,n){return t=Hre(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Hre(e){var t=Gre(e,"string");return cu(t)=="symbol"?t:t+""}function Gre(e,t){if(cu(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(cu(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function qre(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=Vk;if(h==="ScatterChart")g=o,m=aJ;else if(h==="BarChart")g=Fre(f,o,c,d),m=n0;else if(f==="radial"){var v=KP(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=QO}else g={points:Ure(f,o,c)},m=Vk;var w=hd(hd(hd(hd({stroke:"#ccc",pointerEvents:"none"},c),g),Ke(p,!1)),{},{payload:l,payloadIndex:u,className:Ve("recharts-tooltip-cursor",p.className)});return E.isValidElement(p)?E.cloneElement(p,w):E.createElement(m,w)}var Kre=["item"],Vre=["children","className","width","height","style","compact","title","desc"];function zo(e){"@babel/helpers - typeof";return zo=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},zo(e)}function eo(){return eo=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},eo.apply(this,arguments)}function YE(e,t){return Zre(e)||Xre(e,t)||YP(e,t)||Yre()}function Yre(){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 Xre(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 Zre(e){if(Array.isArray(e))return e}function XE(e,t){if(e==null)return{};var n=Qre(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 Qre(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 Jre(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function eie(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,XP(r.key),r)}}function tie(e,t,n){return t&&eie(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function nie(e,t,n){return t=gh(t),rie(e,VP()?Reflect.construct(t,n||[],gh(e).constructor):t.apply(e,n))}function rie(e,t){if(t&&(zo(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return iie(e)}function iie(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function VP(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(VP=function(){return!!e})()}function gh(e){return gh=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},gh(e)}function aie(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&&Gv(e,t)}function Gv(e,t){return Gv=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,i){return r.__proto__=i,r},Gv(e,t)}function Fo(e){return lie(e)||oie(e)||YP(e)||sie()}function sie(){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 YP(e,t){if(e){if(typeof e=="string")return qv(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 qv(e,t)}}function oie(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function lie(e){if(Array.isArray(e))return qv(e)}function qv(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 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 Q(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){Te(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 Te(e,t,n){return t=XP(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function XP(e){var t=cie(e,"string");return zo(t)=="symbol"?t:t+""}function cie(e,t){if(zo(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(zo(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var uie={xAxis:["bottom","top"],yAxis:["left","right"]},die={width:"100%",height:"100%"},ZP={x:0,y:0};function pd(e){return e}var fie=function(t,n){return n==="horizontal"?t.x:n==="vertical"?t.y:n==="centric"?t.angle:t.radius},hie=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 ZP},Mp=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(Fo(l),Fo(u)):l},[]);return o.length>0?o:t&&t.length&&ue(i)&&ue(a)?t.slice(i,a+1):[]};function QP(e){return e==="number"?[0,"auto"]:void 0}var Kv=function(t,n,r,i){var a=t.graphicalItems,o=t.tooltipAxis,l=Mp(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=Ny(p,o.dataKey,i)}else h=f&&f[r]||l[r];return h?[].concat(Fo(c),[YO(u,h)]):c},[])},QE=function(t,n,r,i){var a=i||{x:t.chartX,y:t.chartY},o=fie(a,r),l=t.orderedTooltipTicks,c=t.tooltipAxis,u=t.tooltipTicks,d=LY(o,l,u,c);if(d>=0&&u){var f=u[d]&&u[d].value,h=Kv(t,n,d,f),p=hie(r,l,d,a);return{activeTooltipIndex:d,activeLabel:f,activePayload:h,activeCoordinate:p}}return null},pie=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=qO(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=Mp(t.data,{graphicalItems:i.filter(function(L){var P,ce=o in L.props?L.props[o]:(P=L.type.defaultProps)===null||P===void 0?void 0:P[o];return ce===C}),dataStartIndex:c,dataEndIndex:u}),I=T.length,M,$,R;zre(y.domain,k,b)&&(M=hv(y.domain,null,k),p&&(b==="number"||w!=="auto")&&(R=rc(T,x,"category")));var z=QP(b);if(!M||M.length===0){var D,U=(D=y.domain)!==null&&D!==void 0?D:z;if(x){if(M=rc(T,x,b),b==="category"&&p){var O=_3(M);S&&O?($=M,M=ih(0,I)):S||(M=Ik(U,M,m).reduce(function(L,P){return L.indexOf(P)>=0?L:[].concat(Fo(L),[P])},[]))}else if(b==="category")S?M=M.filter(function(L){return L!==""&&!Ye(L)}):M=Ik(U,M,m).reduce(function(L,P){return L.indexOf(P)>=0||P===""||Ye(P)?L:[].concat(Fo(L),[P])},[]);else if(b==="number"){var F=UY(T,i.filter(function(L){var P,ce,we=o in L.props?L.props[o]:(P=L.type.defaultProps)===null||P===void 0?void 0:P[o],pe="hide"in L.props?L.props.hide:(ce=L.type.defaultProps)===null||ce===void 0?void 0:ce.hide;return we===C&&(N||!pe)}),x,a,d);F&&(M=F)}p&&(b==="number"||w!=="auto")&&(R=rc(T,x,"category"))}else p?M=ih(0,I):l&&l[C]&&l[C].hasStack&&b==="number"?M=h==="expand"?[0,1]:VO(l[C].stackGroups,c,u):M=GO(T,i.filter(function(L){var P=o in L.props?L.props[o]:L.type.defaultProps[o],ce="hide"in L.props?L.props.hide:L.type.defaultProps.hide;return P===C&&(N||!ce)}),b,d,!0);if(b==="number")M=Hv(f,M,C,a,_),U&&(M=hv(U,M,k));else if(b==="category"&&U){var A=U,Z=M.every(function(L){return A.indexOf(L)>=0});Z&&(M=A)}}return Q(Q({},g),{},Te({},C,Q(Q({},y),{},{axisType:a,domain:M,categoricalDomain:R,duplicateDomain:$,originalDomain:(v=y.domain)!==null&&v!==void 0?v:z,isCategorical:p,layout:d})))},{})},mie=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=Mp(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:u}),p=h.length,g=qO(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=QP("number");if(!v[x]){m++;var S;return g?S=ih(0,p):l&&l[x]&&l[x].hasStack?(S=VO(l[x].stackGroups,c,u),S=Hv(f,S,x,a)):(S=hv(k,GO(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=Hv(f,S,x,a)),Q(Q({},v),{},Te({},x,Q(Q({axisType:a},i.defaultProps),{},{hide:!0,orientation:cr(uie,"".concat(a,".").concat(m%2),null),domain:S,originalDomain:k,isCategorical:g,layout:d})))}return v},{})},gie=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=Tr(d,a),p={};return h&&h.length?p=pie(t,{axes:h,graphicalItems:o,axisType:i,axisIdKey:f,stackGroups:l,dataStartIndex:c,dataEndIndex:u}):o&&o.length&&(p=mie(t,{Axis:a,graphicalItems:o,axisType:i,axisIdKey:f,stackGroups:l,dataStartIndex:c,dataEndIndex:u})),p},yie=function(t){var n=Gi(t),r=fi(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:Ax(r,function(i){return i.coordinate}),tooltipAxis:n,tooltipAxisBandSize:Vf(n,r)}},JE=function(t){var n=t.children,r=t.defaultShowTooltip,i=Gn(n,Po),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}},vie=function(t){return!t||!t.length?!1:t.some(function(n){var r=pi(n&&n.type);return r&&r.indexOf("Bar")>=0})},e_=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"}},bie=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=Gn(f,Po),g=Gn(f,Ya),m=Object.keys(c).reduce(function(S,w){var _=c[w],N=_.orientation;return!_.mirror&&!_.hide?Q(Q({},S),{},Te({},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),{},Te({},N,cr(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||Po.defaultProps.height),g&&n&&(y=zY(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)})},xie=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},wie=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,I=y.barGap,M=y.barCategoryGap,$=y.maxBarSize,R=e_(T),z=R.numericAxisName,D=R.cateAxisName,U=vie(x),O=[];return x.forEach(function(F,A){var Z=Mp(y.data,{graphicalItems:[F],dataStartIndex:_,dataEndIndex:N}),L=F.type.defaultProps!==void 0?Q(Q({},F.type.defaultProps),F.props):F.props,P=L.dataKey,ce=L.maxBarSize,we=L["".concat(z,"Id")],pe=L["".concat(D,"Id")],Pe={},G=c.reduce(function(Ae,He){var Ie=b["".concat(He.axisType,"Map")],xn=L["".concat(He.axisType,"Id")];Ie&&Ie[xn]||He.axisType==="zAxis"||cs();var $t=Ie[xn];return Q(Q({},Ae),{},Te(Te({},He.axisType,$t),"".concat(He.axisType,"Ticks"),fi($t)))},Pe),X=G[D],ae=G["".concat(D,"Ticks")],le=k&&k[we]&&k[we].hasStack&&eX(F,k[we].stackGroups),Y=pi(F.type).indexOf("Bar")>=0,_e=Vf(X,ae),Ee=[],je=U&&DY({barSize:C,stackGroups:k,totalSize:xie(G,D)});if(Y){var ve,$e,fe=Ye(ce)?$:ce,vt=(ve=($e=Vf(X,ae,!0))!==null&&$e!==void 0?$e:fe)!==null&&ve!==void 0?ve:0;Ee=BY({barGap:I,barCategoryGap:M,bandSize:vt!==_e?vt:_e,sizeList:je[pe],maxBarSize:fe}),vt!==_e&&(Ee=Ee.map(function(Ae){return Q(Q({},Ae),{},{position:Q(Q({},Ae.position),{},{offset:Ae.position.offset-vt/2})})}))}var Le=F&&F.type&&F.type.getComposedData;Le&&O.push({props:Q(Q({},Le(Q(Q({},G),{},{displayedData:Z,props:y,dataKey:P,item:F,bandSize:_e,barPosition:Ee,offset:S,stackedData:le,layout:T,dataStartIndex:_,dataEndIndex:N}))),{},Te(Te(Te({key:F.key||"item-".concat(A)},z,G[z]),D,G[D]),"animationId",w)),childIndex:L3(F,y.children),item:F})}),O},p=function(y,b){var x=y.props,k=y.dataStartIndex,S=y.dataEndIndex,w=y.updateId;if(!T1({props:x}))return null;var _=x.children,N=x.layout,C=x.stackOffset,T=x.data,I=x.reverseStackOrder,M=e_(N),$=M.numericAxisName,R=M.cateAxisName,z=Tr(_,r),D=ZY(T,z,"".concat($,"Id"),"".concat(R,"Id"),C,I),U=c.reduce(function(L,P){var ce="".concat(P.axisType,"Map");return Q(Q({},L),{},Te({},ce,gie(x,Q(Q({},P),{},{graphicalItems:z,stackGroups:P.axisType===$&&D,dataStartIndex:k,dataEndIndex:S}))))},{}),O=bie(Q(Q({},U),{},{props:x,graphicalItems:z}),b==null?void 0:b.legendBBox);Object.keys(U).forEach(function(L){U[L]=d(x,U[L],O,L.replace("Map",""),n)});var F=U["".concat(R,"Map")],A=yie(F),Z=h(x,Q(Q({},U),{},{dataStartIndex:k,dataEndIndex:S,updateId:w,graphicalItems:z,stackGroups:D,offset:O}));return Q(Q({formattedGraphicalItems:Z,graphicalItems:z,offset:O,stackGroups:D},A),U)},g=function(v){function y(b){var x,k,S;return Jre(this,y),S=nie(this,y,[b]),Te(S,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),Te(S,"accessibilityManager",new Bre),Te(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}))))}}),Te(S,"handleReceiveSyncEvent",function(w,_,N){if(S.props.syncId===w){if(N===S.eventEmitterSymbol&&typeof S.props.syncMethod!="function")return;S.applySyncEvent(_)}}),Te(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})}}),Te(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;De(C)&&C(N,w)}}),Te(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;De(C)&&C(N,w)}),Te(S,"handleItemMouseEnter",function(w){S.setState(function(){return{isTooltipActive:!0,activeItem:w,activePayload:w.tooltipPayload,activeCoordinate:w.tooltipPosition||{x:w.cx,y:w.cy}}})}),Te(S,"handleItemMouseLeave",function(){S.setState(function(){return{isTooltipActive:!1}})}),Te(S,"handleMouseMove",function(w){w.persist(),S.throttleTriggeredAfterMouseMove(w)}),Te(S,"handleMouseLeave",function(w){S.throttleTriggeredAfterMouseMove.cancel();var _={isTooltipActive:!1};S.setState(_),S.triggerSyncEvent(_);var N=S.props.onMouseLeave;De(N)&&N(_,w)}),Te(S,"handleOuterEvent",function(w){var _=$3(w),N=cr(S.props,"".concat(_));if(_&&De(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)}}),Te(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;De(C)&&C(N,w)}}),Te(S,"handleMouseDown",function(w){var _=S.props.onMouseDown;if(De(_)){var N=S.getMouseInfo(w);_(N,w)}}),Te(S,"handleMouseUp",function(w){var _=S.props.onMouseUp;if(De(_)){var N=S.getMouseInfo(w);_(N,w)}}),Te(S,"handleTouchMove",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&S.throttleTriggeredAfterMouseMove(w.changedTouches[0])}),Te(S,"handleTouchStart",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&S.handleMouseDown(w.changedTouches[0])}),Te(S,"handleTouchEnd",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&S.handleMouseUp(w.changedTouches[0])}),Te(S,"handleDoubleClick",function(w){var _=S.props.onDoubleClick;if(De(_)){var N=S.getMouseInfo(w);_(N,w)}}),Te(S,"handleContextMenu",function(w){var _=S.props.onContextMenu;if(De(_)){var N=S.getMouseInfo(w);_(N,w)}}),Te(S,"triggerSyncEvent",function(w){S.props.syncId!==void 0&&Vm.emit(Ym,S.props.syncId,w,S.eventEmitterSymbol)}),Te(S,"applySyncEvent",function(w){var _=S.props,N=_.layout,C=_.syncMethod,T=S.state.updateId,I=w.dataStartIndex,M=w.dataEndIndex;if(w.dataStartIndex!==void 0||w.dataEndIndex!==void 0)S.setState(Q({dataStartIndex:I,dataEndIndex:M},p({props:S.props,dataStartIndex:I,dataEndIndex:M,updateId:T},S.state)));else if(w.activeTooltipIndex!==void 0){var $=w.chartX,R=w.chartY,z=w.activeTooltipIndex,D=S.state,U=D.offset,O=D.tooltipTicks;if(!U)return;if(typeof C=="function")z=C(O,w);else if(C==="value"){z=-1;for(var F=0;F<O.length;F++)if(O[F].value===w.activeLabel){z=F;break}}var A=Q(Q({},U),{},{x:U.left,y:U.top}),Z=Math.min($,A.x+A.width),L=Math.min(R,A.y+A.height),P=O[z]&&O[z].value,ce=Kv(S.state,S.props.data,z),we=O[z]?{x:N==="horizontal"?O[z].coordinate:Z,y:N==="horizontal"?L:O[z].coordinate}:ZP;S.setState(Q(Q({},w),{},{activeLabel:P,activeCoordinate:we,activePayload:ce,activeTooltipIndex:z}))}else S.setState(w)}),Te(S,"renderCursor",function(w){var _,N=S.state,C=N.isTooltipActive,T=N.activeCoordinate,I=N.activePayload,M=N.offset,$=N.activeTooltipIndex,R=N.tooltipAxisBandSize,z=S.getTooltipEventType(),D=(_=w.props.active)!==null&&_!==void 0?_:C,U=S.props.layout,O=w.key||"_recharts-cursor";return H.createElement(qre,{key:O,activeCoordinate:T,activePayload:I,activeTooltipIndex:$,chartName:n,element:w,isActive:D,layout:U,offset:M,tooltipAxisBandSize:R,tooltipEventType:z})}),Te(S,"renderPolarAxis",function(w,_,N){var C=cr(w,"type.axisType"),T=cr(S.state,"".concat(C,"Map")),I=w.type.defaultProps,M=I!==void 0?Q(Q({},I),w.props):w.props,$=T&&T[M["".concat(C,"Id")]];return E.cloneElement(w,Q(Q({},$),{},{className:Ve(C,$.className),key:w.key||"".concat(_,"-").concat(N),ticks:fi($,!0)}))}),Te(S,"renderPolarGrid",function(w){var _=w.props,N=_.radialLines,C=_.polarAngles,T=_.polarRadius,I=S.state,M=I.radiusAxisMap,$=I.angleAxisMap,R=Gi(M),z=Gi($),D=z.cx,U=z.cy,O=z.innerRadius,F=z.outerRadius;return E.cloneElement(w,{polarAngles:Array.isArray(C)?C:fi(z,!0).map(function(A){return A.coordinate}),polarRadius:Array.isArray(T)?T:fi(R,!0).map(function(A){return A.coordinate}),cx:D,cy:U,innerRadius:O,outerRadius:F,key:w.key||"polar-grid",radialLines:N})}),Te(S,"renderLegend",function(){var w=S.state.formattedGraphicalItems,_=S.props,N=_.children,C=_.width,T=_.height,I=S.props.margin||{},M=C-(I.left||0)-(I.right||0),$=WO({children:N,formattedGraphicalItems:w,legendWidth:M,legendContent:u});if(!$)return null;var R=$.item,z=XE($,Kre);return E.cloneElement(R,Q(Q({},z),{},{chartWidth:C,chartHeight:T,margin:I,onBBoxUpdate:S.handleLegendBBoxUpdate}))}),Te(S,"renderTooltip",function(){var w,_=S.props,N=_.children,C=_.accessibilityLayer,T=Gn(N,hn);if(!T)return null;var I=S.state,M=I.isTooltipActive,$=I.activeCoordinate,R=I.activePayload,z=I.activeLabel,D=I.offset,U=(w=T.props.active)!==null&&w!==void 0?w:M;return E.cloneElement(T,{viewBox:Q(Q({},D),{},{x:D.left,y:D.top}),active:U,label:z,payload:U?R:[],coordinate:$,accessibilityLayer:C})}),Te(S,"renderBrush",function(w){var _=S.props,N=_.margin,C=_.data,T=S.state,I=T.offset,M=T.dataStartIndex,$=T.dataEndIndex,R=T.updateId;return E.cloneElement(w,{key:w.key||"_recharts-brush",onChange:cd(S.handleBrushChange,w.props.onChange),data:C,x:ue(w.props.x)?w.props.x:I.left,y:ue(w.props.y)?w.props.y:I.top+I.height+I.brushBottom-(N.bottom||0),width:ue(w.props.width)?w.props.width:I.width,startIndex:M,endIndex:$,updateId:"brush-".concat(R)})}),Te(S,"renderReferenceElement",function(w,_,N){if(!w)return null;var C=S,T=C.clipPathId,I=S.state,M=I.xAxisMap,$=I.yAxisMap,R=I.offset,z=w.type.defaultProps||{},D=w.props,U=D.xAxisId,O=U===void 0?z.xAxisId:U,F=D.yAxisId,A=F===void 0?z.yAxisId:F;return E.cloneElement(w,{key:w.key||"".concat(_,"-").concat(N),xAxis:M[O],yAxis:$[A],viewBox:{x:R.left,y:R.top,width:R.width,height:R.height},clipPathId:T})}),Te(S,"renderActivePoints",function(w){var _=w.item,N=w.activePoint,C=w.basePoint,T=w.childIndex,I=w.isRange,M=[],$=_.props.key,R=_.item.type.defaultProps!==void 0?Q(Q({},_.item.type.defaultProps),_.item.props):_.item.props,z=R.activeDot,D=R.dataKey,U=Q(Q({index:T,dataKey:D,cx:N.x,cy:N.y,r:4,fill:t0(_.item),strokeWidth:2,stroke:"#fff",payload:N.payload,value:N.value},Ke(z,!1)),vf(z));return M.push(y.renderActiveDot(z,U,"".concat($,"-activePoint-").concat(T))),C?M.push(y.renderActiveDot(z,Q(Q({},U),{},{cx:C.x,cy:C.y}),"".concat($,"-basePoint-").concat(T))):I&&M.push(null),M}),Te(S,"renderGraphicChild",function(w,_,N){var C=S.filterFormatItem(w,_,N);if(!C)return null;var T=S.getTooltipEventType(),I=S.state,M=I.isTooltipActive,$=I.tooltipAxis,R=I.activeTooltipIndex,z=I.activeLabel,D=S.props.children,U=Gn(D,hn),O=C.props,F=O.points,A=O.isRange,Z=O.baseLine,L=C.item.type.defaultProps!==void 0?Q(Q({},C.item.type.defaultProps),C.item.props):C.item.props,P=L.activeDot,ce=L.hide,we=L.activeBar,pe=L.activeShape,Pe=!!(!ce&&M&&U&&(P||we||pe)),G={};T!=="axis"&&U&&U.props.trigger==="click"?G={onClick:cd(S.handleItemMouseEnter,w.props.onClick)}:T!=="axis"&&(G={onMouseLeave:cd(S.handleItemMouseLeave,w.props.onMouseLeave),onMouseEnter:cd(S.handleItemMouseEnter,w.props.onMouseEnter)});var X=E.cloneElement(w,Q(Q({},C.props),G));function ae(He){return typeof $.dataKey=="function"?$.dataKey(He.payload):null}if(Pe)if(R>=0){var le,Y;if($.dataKey&&!$.allowDuplicatedCategory){var _e=typeof $.dataKey=="function"?ae:"payload.".concat($.dataKey.toString());le=Ny(F,_e,z),Y=A&&Z&&Ny(Z,_e,z)}else le=F==null?void 0:F[R],Y=A&&Z&&Z[R];if(pe||we){var Ee=w.props.activeIndex!==void 0?w.props.activeIndex:R;return[E.cloneElement(w,Q(Q(Q({},C.props),G),{},{activeIndex:Ee})),null,null]}if(!Ye(le))return[X].concat(Fo(S.renderActivePoints({item:C,activePoint:le,basePoint:Y,childIndex:R,isRange:A})))}else{var je,ve=(je=S.getItemByXY(S.state.activeCoordinate))!==null&&je!==void 0?je:{graphicalItem:X},$e=ve.graphicalItem,fe=$e.item,vt=fe===void 0?w:fe,Le=$e.childIndex,Ae=Q(Q(Q({},C.props),G),{},{activeIndex:Le});return[E.cloneElement(vt,Ae),null,null]}return A?[X,null,null]:[X,null]}),Te(S,"renderCustomized",function(w,_,N){return E.cloneElement(w,Q(Q({key:"recharts-customized-".concat(N)},S.props),S.state))}),Te(S,"renderMap",{CartesianGrid:{handler:pd,once:!0},ReferenceArea:{handler:S.renderReferenceElement},ReferenceLine:{handler:pd},ReferenceDot:{handler:S.renderReferenceElement},XAxis:{handler:pd},YAxis:{handler:pd},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:op("recharts"),"-clip"),S.throttleTriggeredAfterMouseMove=HC(S.triggeredAfterMouseMove,(k=b.throttleDelay)!==null&&k!==void 0?k:1e3/60),S.state={},S}return aie(y,v),tie(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=Gn(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,I=Kv(this.state,S,C,T),M=this.state.tooltipTicks[C].coordinate,$=(this.state.offset.top+w)/2,R=_==="horizontal",z=R?{x:M,y:$}:{y:M,x:$},D=this.state.formattedGraphicalItems.find(function(O){var F=O.item;return F.type.name==="Scatter"});D&&(z=Q(Q({},z),D.props.points[C].tooltipPosition),I=D.props.points[C].tooltipPayload);var U={activeTooltipIndex:C,isTooltipActive:!0,activeLabel:T,activePayload:I,activeCoordinate:z};this.setState(U),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){Ay([Gn(x.children,hn)],[Gn(this.props.children,hn)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var x=Gn(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=cq(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,I=T.xAxisMap,M=T.yAxisMap,$=this.getTooltipEventType(),R=QE(this.state,this.props.data,this.props.layout,C);if($!=="axis"&&I&&M){var z=Gi(I).scale,D=Gi(M).scale,U=z&&z.invert?z.invert(_.chartX):null,O=D&&D.invert?D.invert(_.chartY):null;return Q(Q({},_),{},{xValue:U,yValue:O},R)}return R?Q(Q({},_),R):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 I=this.state,M=I.angleAxisMap,$=I.radiusAxisMap;if(M&&$){var R=Gi(M);return Dk({x:_,y:N},R)}return null}},{key:"parseEventsOfWrapper",value:function(){var x=this.props.children,k=this.getTooltipEventType(),S=Gn(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 _=vf(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===pi(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 H.createElement("defs",null,H.createElement("clipPath",{id:x},H.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=YE(S,2),_=w[0],N=w[1];return Q(Q({},k),{},Te({},_,N.scale))},{}):null}},{key:"getYScales",value:function(){var x=this.state.yAxisMap;return x?Object.entries(x).reduce(function(k,S){var w=YE(S,2),_=w[0],N=w[1];return Q(Q({},k),{},Te({},_,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,I=C.item,M=I.type.defaultProps!==void 0?Q(Q({},I.type.defaultProps),I.props):I.props,$=pi(I.type);if($==="Bar"){var R=(T.data||[]).find(function(O){return YQ(x,O)});if(R)return{graphicalItem:C,payload:R}}else if($==="RadialBar"){var z=(T.data||[]).find(function(O){return Dk(x,O)});if(z)return{graphicalItem:C,payload:z}}else if(Np(C,w)||jp(C,w)||ru(C,w)){var D=QJ({graphicalItem:C,activeTooltipItem:w,itemData:M.data}),U=M.activeIndex===void 0?D:M.activeIndex;return{graphicalItem:Q(Q({},C),{},{childIndex:U}),payload:ru(C,w)?M.data[D]:C.props.data[D]}}}return null}},{key:"render",value:function(){var x=this;if(!T1(this))return null;var k=this.props,S=k.children,w=k.className,_=k.width,N=k.height,C=k.style,T=k.compact,I=k.title,M=k.desc,$=XE(k,Vre),R=Ke($,!1);if(T)return H.createElement(RE,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},H.createElement(Cy,eo({},R,{width:_,height:N,title:I,desc:M}),this.renderClipPath(),O1(S,this.renderMap)));if(this.props.accessibilityLayer){var z,D;R.tabIndex=(z=this.props.tabIndex)!==null&&z!==void 0?z:0,R.role=(D=this.props.role)!==null&&D!==void 0?D:"application",R.onKeyDown=function(O){x.accessibilityManager.keyboardEvent(O)},R.onFocus=function(){x.accessibilityManager.focus()}}var U=this.parseEventsOfWrapper();return H.createElement(RE,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},H.createElement("div",eo({className:Ve("recharts-wrapper",w),style:Q({position:"relative",cursor:"default",width:_,height:N},C)},U,{ref:function(F){x.container=F}}),H.createElement(Cy,eo({},R,{width:_,height:N,title:I,desc:M,style:die}),this.renderClipPath(),O1(S,this.renderMap)),this.renderLegend(),this.renderTooltip()))}}])}(E.Component);Te(g,"displayName",n),Te(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)),Te(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,I=y.dataEndIndex;if(y.updateId===void 0){var M=JE(v);return Q(Q(Q({},M),{},{updateId:0},p(Q(Q({props:v},M),{},{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||!lo(C,y.prevMargin)){var $=JE(v),R={chartX:y.chartX,chartY:y.chartY,isTooltipActive:y.isTooltipActive},z=Q(Q({},QE(y,x,_)),{},{updateId:y.updateId+1}),D=Q(Q(Q({},$),R),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(!Ay(k,y.prevChildren)){var U,O,F,A,Z=Gn(k,Po),L=Z&&(U=(O=Z.props)===null||O===void 0?void 0:O.startIndex)!==null&&U!==void 0?U:T,P=Z&&(F=(A=Z.props)===null||A===void 0?void 0:A.endIndex)!==null&&F!==void 0?F:I,ce=L!==T||P!==I,we=!Ye(x),pe=we&&!ce?y.updateId:y.updateId+1;return Q(Q({updateId:pe},p(Q(Q({props:v},y),{},{updateId:pe,dataStartIndex:L,dataEndIndex:P}),y)),{},{prevChildren:k,dataStartIndex:L,dataEndIndex:P})}return null}),Te(g,"renderActiveDot",function(v,y,b){var x;return E.isValidElement(v)?x=E.cloneElement(v,y):De(v)?x=v(y):x=H.createElement(cP,y),H.createElement(Yt,{className:"recharts-active-dot",key:b},x)});var m=E.forwardRef(function(y,b){return H.createElement(g,eo({},y,{ref:b}))});return m.displayName=g.displayName,m},La=wie({chartName:"BarChart",GraphicalChild:fn,defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"xAxis",AxisComp:Wr},{axisType:"yAxis",AxisComp:Hr}],formatAxisMap:kte});function t_(e){return e==null||e<1e-5?"$0.00":e<.01?"$"+e.toFixed(6):"$"+e.toFixed(4)}function Li(e){return e==null?"0":e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}const Sie={local:"#3fb950",groq:"#58a6ff",gemini:"#bc8cff",nim:"#39d2c0",openrouter:"#d29922"};function kie({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:t_(t.totalCost),label:"Total Cost"},{icon:"📞",value:Li(t.totalRequests),label:"API Requests"},{icon:"🧠",value:Li(i.total),label:"Trajectories"},{icon:"📝",value:Li(n.total),label:"Chat Sessions"},{icon:"🏆",value:Li(r.totalRuns),label:"Benchmark Runs"},{icon:"📦",value:Li(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:Li(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:Li(((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:Li(((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($a,{width:"100%",height:260,children:s.jsxs(La,{data:l,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(qi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Wr,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(Hr,{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=>[t_(h),"Cost"]}),s.jsx(fn,{dataKey:"value",radius:[4,4,0,0],children:l.map(h=>s.jsx(Mc,{fill:Sie[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($a,{width:"100%",height:260,children:s.jsxs(La,{data:c,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(qi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Wr,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(Hr,{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 n_={planner:"📋","context-gatherer":"📂",writer:"✏️",reviewer:"👁️",tester:"🧪",debugger:"🐛",runner:"▶️",git:"🔀",package:"📦","github-release":"🏷️",security:"🔒",orchestrator:"🎯"},r_={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"},i_={pending:{icon:"⏳",label:"Pending"},running:{icon:"▶️",label:"Running"},completed:{icon:"✅",label:"Done"},failed:{icon:"❌",label:"Failed"}},Eie={pending:"#6e7681",running:"#58a6ff",completed:"#3fb950",failed:"#f85149"};function _ie(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 Nie(e,t){const n=[],r=new Set,i=_ie(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 Di(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 a_(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit"}):""}function jie(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 Aie({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(()=>jie((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,I=Math.min(1,Math.max(0,(_-C.left)/T));c(I*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:a_(_.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:["⏱ ",Di(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:[Di(l)," / ",Di(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=r_[_.agentType]||"#58a6ff",C=Eie[_.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:I=>{I.stopPropagation(),d(!1),c((_.start+_.width/2)*m)},title:`${Zm[_.agentType]||_.agentType}: ${_.description}`,children:[s.jsx("span",{className:"phase-block-icon",children:n_[_.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:`${Di(l)} elapsed`})]}),s.jsxs("div",{className:"phase-ticks",children:[s.jsx("span",{children:"0"}),s.jsx("span",{children:Di(Math.round(m/2))}),s.jsx("span",{children:Di(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:n_[y.agentType]||"⚙️"}),s.jsx("span",{className:"phase-detail-agent",style:{color:r_[y.agentType]||"#58a6ff"},children:Zm[y.agentType]||y.agentType}),s.jsxs("span",{className:`phase-status-badge phase-status-${y.status}`,children:[i_[y.status].icon," ",i_[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?Di(y.dur):`~${Di(y.dur)}`]}),y.startedAt?s.jsxs("span",{children:["🕐 ",a_(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."})]})})]})}function Qm(e){return e===void 0?"—":`$${e.toFixed(5)}`}function s_(e){if(e===void 0||!Number.isFinite(e)||e<0)return"—";if(e<1e3)return`${Math.round(e)}ms`;const t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;const n=Math.floor(t/60);return n<60?`${n}m ${String(Math.round(t%60)).padStart(2,"0")}s`:`${Math.floor(n/60)}h ${String(n%60).padStart(2,"0")}m`}function Jm(e){return e===void 0?"—":e.toLocaleString("en-US")}function Tie({jobs:e}){const t=E.useMemo(()=>e.filter(u=>u.batchStats.length>0),[e]),[n,r]=E.useState(null);if(t.length===0)return null;const i=t.find(u=>u.id===n)??t[0],a=i.batchStats,o=a.filter(u=>u.durationMs!==void 0),l=o.reduce((u,d)=>u+(d.durationMs??0),0),c=o.length>0?l/o.length:void 0;return s.jsxs("div",{className:"dag-timeline-section","data-testid":"batch-economy",children:[s.jsxs("h3",{className:"section-subtitle",children:["📊 Per-batch cost & latency"," ",s.jsx("span",{className:"timeline-subtitle",children:"— measured, not estimated"})]}),t.length>1&&s.jsx("div",{className:"dag-loop-turn-meta",style:{marginBottom:8},children:t.slice(0,5).map(u=>s.jsx("button",{type:"button",className:"dag-loop-turn-chip",onClick:()=>r(u.id),style:{cursor:"pointer",opacity:u.id===i.id?1:.55,fontWeight:u.id===i.id?600:400},children:u.progressLine??u.goal.slice(0,40)},u.id))}),s.jsxs("div",{className:"dag-loop-turn-meta",style:{marginBottom:8},children:[s.jsxs("span",{className:"dag-loop-turn-chip",children:[i.kind==="long-form"?"📖":"🛠️"," ",i.status]}),s.jsxs("span",{className:"dag-loop-turn-chip",children:[i.progress,"% done"]}),s.jsxs("span",{className:"dag-loop-turn-chip",children:[i.batches," batch",i.batches===1?"":"es"]}),s.jsxs("span",{className:"dag-loop-turn-chip dag-loop-turn-chip-dim",children:[Jm(i.tokens)," tokens · ",Qm(i.costUsd)]}),i.stopReason&&s.jsxs("span",{className:"dag-loop-turn-chip dag-loop-turn-chip-dim",children:["stopped: ",i.stopReason]})]}),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:"Batch"}),s.jsx("th",{children:"Done"}),s.jsx("th",{children:"Tokens"}),s.jsx("th",{children:"Cost"}),s.jsx("th",{children:"Time"})]})}),s.jsxs("tbody",{children:[a.map(u=>s.jsxs("tr",{children:[s.jsx("td",{children:u.index}),s.jsx("td",{children:`${Math.round(u.progress)}%`}),s.jsx("td",{children:Jm(u.tokens)}),s.jsx("td",{children:Qm(u.costUsd)}),s.jsx("td",{children:s_(u.durationMs)})]},u.index)),a.some(u=>u.error)&&s.jsx("tr",{children:s.jsxs("td",{colSpan:5,style:{opacity:.75},children:["✗ failures:"," ",a.filter(u=>u.error).map(u=>`#${u.index} ${u.error}`).join(" · ")]})}),s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("strong",{children:"total"})}),s.jsx("td",{children:s.jsx("strong",{children:`${i.progress}%`})}),s.jsx("td",{children:s.jsx("strong",{children:Jm(i.tokens)})}),s.jsx("td",{children:s.jsx("strong",{children:Qm(i.costUsd)})}),s.jsx("td",{children:s.jsx("strong",{children:c===void 0?"—":`~${s_(c)} avg`})})]})]})]})})]})}const o_={planner:"📋","context-gatherer":"📂",writer:"✏️",reviewer:"👁️",tester:"🧪",debugger:"🐛",runner:"▶️",git:"🔀",package:"📦","github-release":"🏷️",security:"🔒",orchestrator:"🎯"},eg={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"},Cie={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"}},l_={pending:"⏳ Pending",running:"▶️ Running",completed:"✅ Done",failed:"❌ Failed"},Ms={trivial:{icon:"🟢",color:"#3fb950"},simple:{icon:"🔵",color:"#58a6ff"},moderate:{icon:"🟡",color:"#d29922"},complex:{icon:"🟠",color:"#f0883e"},critical:{icon:"🔴",color:"#f85149"}},tg={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 Oie(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 ng(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 c_(e){return e?new Date(e).toLocaleTimeString("en-US",{minute:"2-digit",second:"2-digit"}):""}function Pie({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 Mie({data:e}){var A,Z;const t=e==null?void 0:e.dag,n=(A=e==null?void 0:e.memory)==null?void 0:A.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(P=>{i(P),c(P.engine),d(P.engineExplanation),h(P.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(()=>Nie(p,e==null?void 0:e.pipelineRuns),[p,e==null?void 0:e.pipelineRuns]),b=L=>{o(L)},x=!!(p&&(p.nodes.length>0||p.active)),k=y.length>0,S=!!v,w=((Z=e==null?void 0:e.unattendedJobs)==null?void 0:Z.jobs)??[],_=w.some(L=>L.batchStats.length>0);if(!x&&!k&&!S&&!_)return s.jsx(Pie,{memoryTotal:n});const{nodes:N,edges:C,pipeline:T,active:I}=p??{nodes:[],edges:[],pipeline:null,active:!1},{layoutNodes:M,svgW:$,svgH:R}=Oie(N,C),z=N.filter(L=>L.status==="running").length,D=N.filter(L=>L.status==="completed").length,U=N.filter(L=>L.status==="failed").length,O=N.filter(L=>L.status==="pending").length,F=N.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(Aie,{runs:y,onScrub:b})]}),s.jsx(Tie,{jobs:w}),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:["⏱ ",ng(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((L,P)=>s.jsxs("span",{className:`dag-loop-tool ${L.ok===!1?"dag-loop-tool-error":""}`,title:L.error||`${L.tool}${L.durationMs!==void 0?` · ${L.durationMs}ms`:""}`,children:[L.ok===!1?"❌":"✓"," ",L.tool]},`${L.tool}-${P}`))})]}),x&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`dag-status-bar ${I?"active":""}`,children:[s.jsxs("div",{className:"dag-pipeline-name",children:[I&&s.jsx("span",{className:"dag-live-dot"}),T||"Execution Pipeline"]}),s.jsxs("div",{className:"dag-pipeline-meta",children:[I&&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"]}),z>0&&s.jsxs("span",{className:"dag-running-badge",children:["▶ ",z," running"]}),O>0&&s.jsxs("span",{className:"dag-pending-badge",children:["⏳ ",O," pending"]}),s.jsxs("span",{className:"dag-completed-badge",children:["✅ ",D," done"]}),U>0&&s.jsxs("span",{className:"dag-failed-badge",children:["❌ ",U," failed"]})]})]}),s.jsx("div",{className:"dag-container",children:s.jsxs("svg",{width:$,height:R,viewBox:`0 0 ${$} ${R}`,children:[s.jsxs("defs",{children:[C.map(L=>s.jsx("marker",{id:`arrow-${L.from}-${L.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-${L.from}-${L.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"})]})]})]}),C.map(L=>{const P=M.find(Y=>Y.id===L.from),ce=M.find(Y=>Y.id===L.to);if(!P||!ce)return null;const we=P.x+P.w,pe=P.y+P.h/2,Pe=ce.x,G=ce.y+ce.h/2,X=(we+Pe)/2,ae=ce.status,le=ae==="failed"?"#f85149":ae==="running"?"#58a6ff":ae==="completed"?"#3fb950":"#30363d";return s.jsx("g",{children:s.jsx("path",{d:`M ${we} ${pe} C ${X} ${pe}, ${X} ${G}, ${Pe} ${G}`,fill:"none",stroke:le,strokeWidth:ae==="pending"?1.5:2.5,strokeOpacity:ae==="pending"?.3:.8,markerEnd:`url(#arrow-${L.from}-${L.to})`,className:"dag-edge"})},`edge-${L.from}-${L.to}`)}),M.map(L=>{const P=Cie[L.status];eg[L.agentType];const ce=o_[L.agentType]||"⚙️",we=tg[L.agentType]||L.agentType,pe=a===L.id,Pe=L.status==="running";return s.jsxs("g",{onClick:()=>o(pe?null:L.id),style:{cursor:"pointer"},className:"dag-node-group",children:[pe&&s.jsx("rect",{x:L.x-4,y:L.y-4,width:L.w+8,height:L.h+8,rx:10,ry:10,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.5}),s.jsx("rect",{x:L.x,y:L.y,width:L.w,height:L.h,rx:8,ry:8,fill:P.bg,stroke:P.stroke,strokeWidth:Pe?2.5:1.5,strokeOpacity:.9,className:Pe?"dag-node-running":"",filter:Pe?"url(#glow)":void 0}),s.jsxs("text",{x:L.x+10,y:L.y+22,fill:"#e6edf3",fontSize:10,fontWeight:600,children:[ce," ",we]}),s.jsx("text",{x:L.x+L.w-10,y:L.y+22,textAnchor:"end",fill:P.text,fontSize:9,fontWeight:500,children:l_[L.status]}),s.jsx("text",{x:L.x+10,y:L.y+40,fill:"#8b949e",fontSize:9,children:L.description.length>28?L.description.slice(0,26)+"..":L.description}),L.complexity&&Ms[L.complexity]&&s.jsxs("text",{x:L.x+10,y:L.y+54,fill:Ms[L.complexity].color,fontSize:8,fontWeight:600,children:[Ms[L.complexity].icon," ",L.complexity]}),s.jsx("text",{x:L.x+10,y:L.y+56,fill:"#6e7681",fontSize:8,children:ng(L.startedAt,L.completedAt)}),s.jsx("text",{x:L.x+L.w-10,y:L.y+56,textAnchor:"end",fill:"#6e7681",fontSize:8,children:c_(L.startedAt||L.completedAt)}),(L.status==="failed"||pe)&&L.summary&&s.jsx("foreignObject",{x:Math.max(10,L.x-80),y:L.y+L.h+6,width:L.w+160,height:36,children:s.jsx("div",{className:"dag-node-summary",style:{color:L.status==="failed"?"#f85149":"#8b949e",fontSize:"10px",lineHeight:1.4,background:"rgba(13,17,23,0.9)",padding:"4px 8px",borderRadius:"4px",border:`1px solid ${L.status==="failed"?"rgba(248,81,73,0.3)":"rgba(48,54,61,0.5)"}`,maxHeight:"32px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:L.summary})})]},`node-${L.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:M.map(L=>s.jsxs("tr",{className:`dag-row dag-row-${L.status}`,children:[s.jsx("td",{className:"dag-cell-step",children:L.step}),s.jsxs("td",{className:"dag-cell-agent",children:[s.jsx("span",{className:"dag-agent-dot",style:{background:eg[L.agentType]||"#58a6ff"}}),tg[L.agentType]||L.agentType]}),s.jsx("td",{className:"dag-cell-complexity",children:L.complexity&&Ms[L.complexity]?s.jsxs("span",{style:{color:Ms[L.complexity].color,fontSize:12},children:[Ms[L.complexity].icon," ",L.complexity]}):s.jsx("span",{style:{color:"#6e7681",fontSize:12},children:"—"})}),s.jsx("td",{className:`dag-cell-status dag-status-${L.status}`,children:l_[L.status]}),s.jsx("td",{className:"dag-cell-duration",children:ng(L.startedAt,L.completedAt)}),s.jsx("td",{className:"dag-cell-time",children:c_(L.startedAt||L.completedAt)}),s.jsx("td",{className:"dag-cell-summary",children:L.summary||L.description||"--"})]},L.id))})]})}),s.jsx("h3",{className:"section-subtitle",children:"Agent Types"}),s.jsxs("div",{className:"dag-legend",children:[Object.entries(o_).map(([L,P])=>s.jsxs("div",{className:"legend-item",children:[s.jsx("span",{className:"legend-dot",style:{background:eg[L]||"#58a6ff"}}),s.jsx("span",{className:"legend-icon",children:P}),s.jsx("span",{className:"legend-label",children:tg[L]||L})]},L)),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 Rs(e){return e==null||e<1e-5?"$0.00":e<.01?"$"+e.toFixed(6):"$"+e.toFixed(4)}function Ll(e){return e==null?"0":e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}function Rie(e){return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Iie({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:Rs(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:Ll(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:Ll(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:Rs(t.measuredCost)}),s.jsxs("span",{className:"cost-label",children:[Ll(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:Rs(t.estimatedCost)}),s.jsxs("span",{className:"cost-label",children:[Ll(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:Rs(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:Rs(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:Rie(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:Rs(a.costUsd)}),s.jsxs("span",{className:"request-tokens",children:[Ll(a.totalTokens)," tok"]})]},o))})]})}function $ie(e){return e==null?"$0.00":"$"+e.toFixed(6)}function md(e){return e==null?"0%":(e*100).toFixed(1)+"%"}function Lie({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:md(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:$ie(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($a,{width:"100%",height:260,children:s.jsxs(La,{data:c,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(qi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Wr,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(Hr,{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(Mc,{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($a,{width:"100%",height:260,children:s.jsxs(La,{data:c,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(qi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Wr,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(Hr,{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($a,{width:"100%",height:260,children:s.jsxs(La,{data:c,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(qi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Wr,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(Hr,{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:md(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:md(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:md(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($a,{width:"100%",height:260,children:s.jsxs(La,{data:l,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(qi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Wr,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(Hr,{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(Mc,{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($a,{width:"100%",height:260,children:s.jsxs(La,{data:l,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(qi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Wr,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(Hr,{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(Ya,{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 rg(e){return e==null?"0":e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}function Die({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:rg(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:[rg(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:[rg(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 Bie=new Set(["local","lmstudio","vllm"]),zie=new Set([]),yh={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"}},Fie=[3,4,5],JP=12e3,u_=[300,700],Uie=6e4,Wie=5e3;function Hie(e){return new Promise(t=>setTimeout(t,e))}async function eM(e,t){const n=new AbortController,r=setTimeout(()=>n.abort(),t);try{return await fetch(e,{signal:n.signal})}finally{clearTimeout(r)}}function tM(e){return e instanceof TypeError||e instanceof Error&&e.name==="AbortError"}async function Gie(e){let t=null,n=!1;for(let r=0;;r++){try{const i=await eM("/api/models",JP);if(!i.ok)t=i.status;else{const a=await si(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(!tM(i))throw i;n=!0,e==null||e()}if(r>=u_.length)throw new Error(n?"Dashboard server unreachable — is it still running? Retrying automatically…":`Model health endpoint failed (HTTP ${t})`);await Hie(u_[r])}}async function qie(e){for(let t=0;;t++)try{const n=await eM("/api/model-registry",JP);return n.ok?await si(n):null}catch(n){if(!tM(n)||t>=1)return null;e==null||e()}}function Kie(e){return e==="available"?"Available":e==="limited"?"Limited":"Unavailable"}function Vie(e){return e==="available"?"Ready":e==="limited"?"Limited":"Down"}function nM(e){return{local:"💻",groq:"🟢",nim:"🔶",gemini:"🔷",openrouter:"🟣",openai:"🤖",anthropic:"🔮",mistral:"🌀",cohere:"🧠",together:"🟢",deepinfra:"🌐",fireworks:"🎆",perplexity:"❓",azure:"🔵",anyscale:"🔷",lmstudio:"🎨",vllm:"⚡"}[e]||"🔌"}function f0(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 d_({status:e,label:t}){const n=yh[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 Yie({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 Xie({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 gd({provider:e}){const[t,n]=E.useState(!1),r=yh[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(d_,{status:e.overallStatus,label:Kie(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:yh[a.status].dot,marginRight:8}}),a.name]}),s.jsx("td",{style:{padding:"8px 12px"},children:s.jsx(d_,{status:a.status,label:Vie(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 rM(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 Zie(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 Qie({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 Jie({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 eae({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 tae({entry:e}){const t=Zie(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(Qie,{rate:e.partialRate??0}),e.partialHistory&&e.partialHistory.length>=2&&s.jsx(eae,{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(Jie,{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?rM(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 nae({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:nM(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:f0(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(tae,{entry:i},i.model))})]})})]})}function rae(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 iae({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"})]})]})]}),rae(e.keyHygiene),e.providers.map(t=>s.jsx(nae,{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 aae={chat:"💬",execute:"⚙️",plan:"🗺️",edit:"✏️",skill:"🧩",learn:"📚",ci:"🔁",doctor:"🩺",probe:"🔭","spot-check":"🧪",telemetry:"📡",usage:"🧮"};function sae(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 oae(e){return aae[e]||"🎯"}function lae(e){return e?new Date(e).toLocaleDateString()+" "+new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"—"}function qa({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 cae(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 uae(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 dae({timeline:e}){const[t,n]=E.useState(()=>uae(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?cae(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(qa,{provider:m.provider,model:m.model,reason:m.errorType,killed:!0},`${m.provider}|${m.model}|${m.outcome}`):m.outcome==="verified"?s.jsx(qa,{provider:m.provider,model:m.model},`${m.provider}|${m.model}|${m.outcome}`):m.outcome==="partial"?s.jsx(qa,{provider:m.provider,model:m.model,reason:m.errorType,partial:!0,streamedChunks:m.streamedChunks},`${m.provider}|${m.model}|${m.outcome}`):s.jsx(qa,{provider:m.provider,model:m.model,reason:m.errorType,transient:!0},`${m.provider}|${m.model}|${m.outcome}`))})]})]})}function fae({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:oae(e.action)}),s.jsxs("div",{style:{flex:1},children:[s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#e6edf3",marginBottom:2},children:sae(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(qa,{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(qa,{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(qa,{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(dae,{timeline:e.timeline})]})]})}function hae({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:lae(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(fae,{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 yd({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 pae({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 mae({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:"}),Fie.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 gae({model:e,provider:t}){const n=yh[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:[nM(t)," ",f0(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 ",rM(e.resetsInMs)]})]})})}function yae({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)||f0(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(gae,{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 vae(){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 bae(){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 xae(){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()},Wie)}async function v(){a(!0),l(null),g.current=!1;try{const[b,x]=await Promise.all([Gie(()=>{g.current=!0}),qie(()=>{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,Uie);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)zie.has(N.provider)?S.push(N):Bie.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(Yie,{onRefresh:v,loading:i}),s.jsx(bae,{}),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(Xie,{data:e}),(()=>{const{available:b,local:x,speech:k,unavailable:S}=y(e);return s.jsxs(s.Fragment,{children:[s.jsx(yd,{icon:"✅",title:"Available Cloud Providers",count:b.length}),b.map(w=>s.jsx(gd,{provider:w},w.provider)),s.jsx(yd,{icon:"🏠",title:"Local Providers",count:x.length}),x.map(w=>s.jsx(gd,{provider:w},w.provider)),s.jsx(yd,{icon:"⛔",title:"Unavailable Providers",count:S.length}),S.map(w=>s.jsx(gd,{provider:w},w.provider)),s.jsx(yd,{icon:"🎙️",title:"Speech / TTS Providers",count:k.length}),k.map(w=>s.jsx(gd,{provider:w},w.provider))]})})(),s.jsx(pae,{value:d,onChange:f,totalCount:e.providers.reduce((b,x)=>b+x.models.length,0)}),s.jsx(mae,{value:c,onChange:u}),s.jsx(yae,{providers:e.providers,colsPerRow:c,searchQuery:d}),n&&s.jsx(iae,{data:n}),n&&s.jsx(hae,{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(vae,{}),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 wae={local:"💻",groq:"🟢",nim:"🔶",gemini:"🔷",openrouter:"🟣"},Sae={local:"Ollama (Local)",groq:"Groq",nim:"NVIDIA NIM",gemini:"Gemini",openrouter:"OpenRouter"},kae={trivial:"🟢",simple:"🔵",moderate:"🟡",complex:"🟠",critical:"🔴"},iM={trivial:"🟢 trivial",simple:"🔵 simple",moderate:"🟡 moderate",complex:"🟠 complex",critical:"🔴 critical"},Eae={chat:"💬 chat",orchestrator:"🔀 orchestrator",explain:"🔍 explain",benchmark:"📈 benchmark",eval:"🎯 eval"},ja=[{key:"request",icon:"🎯",title:"Request"},{key:"candidates",icon:"⚖️",title:"Candidates"},{key:"exclusions",icon:"🚫",title:"Exclusions"},{key:"pick",icon:"✅",title:"Pick"}],_ae=2400;function ig(e){return wae[e]||"🔌"}function f_(e){return Sae[e]||e}function h0(e){return e&&Eae[e]||e||"unknown"}function Nae(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 h_(e){const t=Math.ceil(e/6e4);return t>=60?`${Math.floor(t/60)}h ${t%60}m`:`${t}m`}const jae=8;function p_(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 ${h_(r.resetsInMs)}`:"quota exhausted — parked":r&&r.cooldownRemaining>0?`circuit-breaker cooldown — ${h_(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 Aae(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,jae)){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:p_(g,e)})),p=(o=d.find(g=>g.provider===c.provider))==null?void 0:o.reason;r.push({id:c.id,label:`${h0(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:p_(g,e)})),p=u[0];r.push({id:`profile-${c.complexity}`,label:`${iM[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 Tae(e,t){switch(e){case"request":return`A ${t.complexity} task arrives${t.source?` from ${h0(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 Cae({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 Oae({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 Pae({routing:e}){const t=E.useMemo(()=>Aae(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)%ja.length)},_ae);return()=>clearInterval(p)},[o,t.length]),t.length===0)return null;const c=t.find(p=>p.id===n)??t[0],u=ja[i],d=()=>{a(p=>(p+ja.length-1)%ja.length),l(!1)},f=()=>{a(p=>(p+1)%ja.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(Oae,{icon:u.icon,title:`${i+1}. ${u.title}${i>0?` — ${c.complexity}`:""}`,narration:Tae(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:[kae[c.complexity]||"•"," ",iM[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:h0(c.source)}),c.timestamp&&s.jsx("span",{style:{fontSize:11,color:"#6e7681",marginLeft:"auto"},children:Nae(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:[ig(p.provider)," ",f_(p.provider).split(" ")[0],m&&" 👑"]}),s.jsx(Cae,{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:[ig(p.provider)," ",f_(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:[ig(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:ag,children:"◀"}),s.jsx("button",{onClick:h,"aria-label":o?"Pause playback":"Play playback",style:{...ag,minWidth:84,color:o?"#d29922":"#3fb950"},children:o?"⏸ Pause":"▶ Play"}),s.jsx("button",{onClick:f,"aria-label":"Next step",style:ag,children:"▶"}),s.jsx("div",{style:{display:"flex",gap:6,marginLeft:8},children:ja.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,"/",ja.length]})]})]})}const ag={background:"#21262d",color:"#e6edf3",border:"1px solid #30363d",borderRadius:8,padding:"6px 12px",fontSize:13,cursor:"pointer",transition:"background 0.15s"},Mae={local:"💻",groq:"🟢",nim:"🔶",gemini:"🔷",openrouter:"🟣"},Rae={local:"Ollama (Local)",groq:"Groq",nim:"NVIDIA NIM",gemini:"Gemini",openrouter:"OpenRouter"},aM={trivial:"🟢",simple:"🔵",moderate:"🟡",complex:"🟠",critical:"🔴"};function Cr(e){return Mae[e]||"🔌"}function ca(e){return Rae[e]||e}function vh(e,t=1){return`${(e*100).toFixed(t)}%`}function Iae(e){return`$${e.toFixed(6)}`}function Zn({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 p0({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 to(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 $ae(){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 Lae={chat:"💬 chat",orchestrator:"🔀 orchestrator",explain:"🔍 explain",benchmark:"📈 benchmark",eval:"🎯 eval"},Dae={trivial:"🟢 trivial",simple:"🔵 simple",moderate:"🟡 moderate",complex:"🟠 complex",critical:"🔴 critical"};function sM(e){return Lae[e]||e}function oM(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 m_(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 Bae({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 zae({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(Zn,{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(Bae,{label:`${Cr(i)} ${ca(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:[sM(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 Fae({history:e}){return e.length?s.jsx(Zn,{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:oM(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:sM(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:[Cr(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:Dae[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 Uae({routing:e}){return e.preference.length?s.jsx(Zn,{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:[aM[t.complexity]||"•"," ",t.complexity]}),s.jsx("td",{style:{padding:"10px 12px",whiteSpace:"nowrap"},children:s.jsxs("span",{style:{color:"#3fb950",fontWeight:600},children:[Cr(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:[Cr(n.provider)," ",ca(n.provider).split(" ")[0]]}),s.jsx(p0,{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:to("#1c2128","#6e7681"),children:["🎯 fit ",n.capabilityFit,"%"]}),n.costSource==="measured"&&n.costBasis?s.jsxs("span",{style:to("#12291a","#3fb950","#3fb950"),children:["📏 measured ",n.costBasis.inputTokens.toLocaleString(),"→",n.costBasis.outputTokens.toLocaleString()," tok"]}):s.jsx("span",{style:to("#1c2128","#8b949e"),children:"📐 estimated"}),n.contextUtilization!==void 0&&n.contextWindowTokens!==void 0&&s.jsxs("span",{style:to("#1c2128","#58a6ff","#58a6ff"),children:["⏳ ctx ",n.contextUtilization,"% (",n.contextWindowTokens.toLocaleString()," tok)"]})]})]},n.provider))})]},t.complexity))})]})})}):null}function Wae({routing:e}){return e.providers.length?s.jsx(Zn,{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:[Cr(t.provider)," ",ca(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(p0,{value:t.avgQuality,color:"#58a6ff"}),s.jsx("span",{style:{fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12,color:"#8b949e",width:44,textAlign:"right"},children:vh(t.avgQuality)})]})}),s.jsx("td",{style:{padding:"10px 12px",color:t.passRate>=.8?"#3fb950":"#d29922"},children:vh(t.passRate)}),s.jsx("td",{style:{padding:"10px 12px",fontFamily:"'SFMono-Regular', Consolas, monospace",color:"#8b949e"},children:Iae(t.totalCostUsd)})]},t.provider))})]})})}):null}const g_=["trivial","simple","moderate","complex","critical"];function Hae(e){return e>=.7?"#3fb950":e>=.45?"#d29922":"#f85149"}function Gae({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(Zn,{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"}),g_.map(r=>s.jsxs("th",{style:{padding:"8px 10px",textAlign:"center",fontWeight:500},children:[aM[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:[Cr(r)," ",ca(r).split(" ")[0]]}),g_.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:Hae(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 qae(e,t=1){return`${e>0?"+":""}${(e*100).toFixed(t)}%`}function Kae({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 Vae({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(Zn,{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:qae(i.delta)}),s.jsx("span",{style:{fontSize:11,color:"#6e7681",flex:1},children:i.note}),s.jsx(Kae,{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 Yae({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(Zn,{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:Cr(r.provider)}),s.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#e6edf3"},children:ca(r.provider)}),r.trusted?s.jsxs("span",{style:to("#3fb95026","#238636","#3fb950"),children:["trusted · ",r.samples," samples"]}):s.jsxs("span",{style:to("#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 ",vh(r.winRate,0)]}),s.jsx(p0,{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 Xae({routing:e}){return e.bestModels.length?s.jsx(Zn,{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:[Cr(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:[vh(t.successRate,0)," success"]})," · ",t.runs," run",t.runs!==1?"s":""]})]},`${t.agentType}-${t.model}`))})}):null}function Zae({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(Zn,{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 Qae({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(Zn,{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:[Cr(u.provider)," ",ca(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:m_(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:[Cr(u.provider)," ",ca(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 ",m_(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:[Cr(u.provider)," ",ca(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:oM(u.timestamp)})]},`${u.timestamp}-${d}`)})})]})]})}function Ud({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 Jae({governance:e}){var r,i,a,o,l;if(!e.enabled)return s.jsx(Zn,{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(Zn,{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(Ud,{ok:!c.deny,children:[c.deny?"⛔":"✅"," ",c.label,": ",c.items.join(", ")]},c.label)),n.map(c=>s.jsx(Ud,{children:c},c)),t.length===0&&n.length===0&&s.jsx(Ud,{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 ese({rbac:e}){const t=n=>n==="admin"?"#d29922":n==="operator"?"#3fb950":"#8b949e";return s.jsxs(Zn,{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(Ud,{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 tse({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($ae,{}):s.jsxs(s.Fragment,{children:[a&&t&&s.jsx(Pae,{routing:t}),f&&t.governance&&s.jsx(Jae,{governance:t.governance}),(t==null?void 0:t.rbac)&&s.jsx(ese,{rbac:t.rbac}),r&&s.jsx(zae,{usage:t.usage}),i&&s.jsx(Fae,{history:t.history}),o&&s.jsx(Gae,{bandit:t.bandit}),l&&s.jsx(Vae,{promotion:t.promotion}),c&&t.ml&&s.jsx(Yae,{ml:t.ml}),u&&s.jsx(Qae,{quota:t.quota}),d&&s.jsx(Zae,{retrieval:t.retrieval}),s.jsx(Uae,{routing:t}),s.jsx(Wae,{routing:t}),s.jsx(Xae,{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 y_={chat:"💬",execute:"⚙️",plan:"🗺️",edit:"✏️",skill:"🧩",learn:"📚",ci:"🔁",doctor:"🩺",probe:"🔭","spot-check":"🧪",telemetry:"📡",usage:"🧮","ide-chat":"💬","ide-inline":"✍️","ide-execute":"⚙️"};function nse(e){return new Date(e).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function vd(e){return e!==void 0?`${e}ms`:"—"}function lM(e){return e===0?"#3fb950":e<.2?"#d29922":"#f85149"}function rse({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:lM(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 ise({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(rse,{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:[y_[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:[y_[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:lM(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:vd((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?vd(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?vd(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?vd(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:nse(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 ase={local:"💻",groq:"🟢",nim:"🔶",gemini:"🔷",openrouter:"🟣"},sse={planner:"🗺️",writer:"✍️",reviewer:"🔎",tester:"🧪",debugger:"🐛",runner:"🏃","context-gatherer":"📂",memory:"🧠","self-improver":"📈"};function ose(e){return ase[e]||"🔌"}function lse(e){return sse[e]||"🤖"}function cM(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 m0(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 ac(e){return e==null?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}function cse(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 Vv({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 use(){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 dse({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:lse(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:[ose(e.provider)," ",e.provider,"/",e.model]}),s.jsx("span",{style:{width:70,fontSize:11,color:"#6e7681",textAlign:"right"},children:m0(e.latencyMs)}),s.jsxs("span",{style:{width:86,fontSize:11,color:"#6e7681",fontFamily:"'SFMono-Regular', Consolas, monospace",textAlign:"right"},children:[ac(e.inputTokens),"→",ac(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 (",ac(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 fse({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(Vv,{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:["🕓 ",cM(e.startedAt)]}),(()=>{const l=cse(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:["⏱ ",m0(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:["🧮 ",ac(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(dse,{step:l},l.seq))]})}function hse({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(fse,{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:cM(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:["⏱ ",m0(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:["🧮 ",ac(r.totalTokens)," tok"]}),a&&s.jsxs("span",{children:["🤖 ",a.slice(0,60)]})]})]},r.id)})})}function pse(){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(Vv,{icon:"⏳",title:"Loading…",children:s.jsx("div",{style:{color:"#8b949e",fontSize:13},children:"Fetching reasoning traces…"})}),n&&e===null&&s.jsx(Vv,{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(use,{}),e!==null&&e.length>0&&s.jsx(hse,{traces:e})]})}function sg(e){if(e.trim()==="")return null;const t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function mse({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 I=S.quota[T]||{};w[T]={provider:T,tokens:((_=I.tokensPerWindow)==null?void 0:_.toString())??"",requests:((N=I.requestsPerWindow)==null?void 0:N.toString())??"",windowMs:((C=I.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=sg(N.tokens),I=sg(N.requests),M=sg(N.windowMs);T!==null&&(C.tokensPerWindow=T),I!==null&&(C.requestsPerWindow=I),M!==null&&(C.windowMs=M),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 gse={pass:"✅",warn:"⚠️",fail:"❌"},yse={pass:"PASS",warn:"WARN",fail:"FAIL"},vse={env:"Environment",config:"Config",vault:"Vault",local:"Local (no key)",none:"Not configured"};function v_({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:[gse[e.status]," ",yse[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 bse(){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(!1),[h,p]=E.useState(""),[g,m]=E.useState(""),[v,y]=E.useState(null),[b,x]=E.useState(null),[k,S]=E.useState(""),[w,_]=E.useState(""),[N,C]=E.useState(""),[T,I]=E.useState(null),[M,$]=E.useState(!1),[R,z]=E.useState([]),[D,U]=E.useState(null),[O,F]=E.useState(""),[A,Z]=E.useState(""),[L,P]=E.useState("viewer"),[ce,we]=E.useState([]),[pe,Pe]=E.useState({}),[G,X]=E.useState(null),[ae,le]=E.useState({}),[Y,_e]=E.useState(""),[Ee,je]=E.useState(null),[ve,$e]=E.useState(null),fe=E.useCallback(async()=>{r(!0),a(null);const q=await ee.fetchAdminChecks();t(q),q||a("Could not reach the dashboard server, or the server is older than this panel. Run `buff dashboard` to start it."),r(!1)},[]),vt=E.useCallback(async()=>{const q=await ee.fetchAdminCatalog();q&&q.length>0&&we(q)},[]),Le=E.useCallback(async()=>{const q=await ee.fetchAdminUsers();q.ok&&q.users&&z(q.users)},[]);E.useEffect(()=>{let q=!0;return ee.fetchAdminAuthStatus().then(me=>{if(q){if(!me){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:me.configured,authenticated:me.authenticated}),u(me.authenticated),y(me.role??null),x(me.user??null),f(me.mustChangePassword===!0),me.authenticated?(fe(),vt(),Le()):r(!1)}}),()=>{q=!1}},[fe,vt,Le]);const Ae=v==="admin",He=()=>{u(!1),l(q=>q&&{...q,authenticated:!1}),I("Session expired — log in again.")},Ie=async q=>{q.preventDefault(),$(!0),I(null);const me=await ee.adminLogin(k,w);me.ok?(u(!0),l({configured:!0,authenticated:!0}),y(me.role??"admin"),x(me.user??null),S(""),_(""),ee.fetchAdminAuthStatus().then(Re=>{Re&&f(Re.mustChangePassword===!0)}),fe(),vt(),Le()):I(me.error||"Login failed."),$(!1)},xn=async q=>{if(q.preventDefault(),$(!0),I(null),w.length<8){I("Password must be at least 8 characters."),$(!1);return}if(w!==N){I("Passwords do not match."),$(!1);return}const me=await ee.adminSetup(k,w);me.ok?(u(!0),l({configured:!0,authenticated:!0}),y(me.role??"admin"),x(me.user??null),S(""),_(""),C(""),fe(),vt(),Le()):I(me.error||"Setup failed."),$(!1)},$t=async()=>{await ee.adminLogout(),u(!1),l(q=>q&&{...q,authenticated:!1}),y(null),x(null),t(null),Pe({}),le({}),z([])},W=async()=>{if(!window.confirm("Stop the running gateway? Channels will stop responding until you restart it with `buff gateway start`."))return;$e("gateway"),je(null);const q=await ee.shutdown("gateway");$e(null),q.ok?je(q.stopped?"✅ Gateway stopped.":`ℹ️ ${q.reason||"No running gateway found — nothing to stop."}`):(je(`❌ ${q.error||"Stop failed."}`),q.unauthorized&&He())},V=async()=>{window.confirm("Shut down the dashboard? This page will disconnect and the server will exit. Restart with `buff dashboard`.")&&($e("dashboard"),je("🛑 Shutting down the dashboard — this page will disconnect…"),await ee.shutdown("dashboard"),$e(null),je("ℹ️ The dashboard server did not stop (see the server terminal). You can also stop it with `buff dashboard stop`."))},oe=async q=>{if(q.preventDefault(),U(null),A.length<8){U("Password must be at least 8 characters.");return}const me=await ee.addAdminUser(O,A,L);me.ok?(F(""),Z(""),U("✅ User added"),Le()):(U(`❌ ${me.error||"Failed to add user"}`),me.unauthorized&&He())},he=async q=>{if(!window.confirm(`Remove dashboard user '${q}'?`))return;U(null);const me=await ee.removeAdminUser(q);me.ok?(U(`✅ Removed ${q}`),Le()):(U(`❌ ${me.error||"Failed to remove user"}`),me.unauthorized&&He())},xe=(q,me,Re)=>{Pe(Ce=>({...Ce,[q]:{...Ce[q]||{},[me]:Re}}))},Qe=async q=>{X(q),le({});const me=pe[q]||{},Re=await ee.saveProvider(q,me);Re.ok?(t(Ce=>{if(!Ce)return Ce;const Rr=Ce.providers.some(gr=>gr.type===q)?Ce.providers.map(gr=>gr.type===q&&Re.provider?Re.provider:gr):Re.provider?[...Ce.providers,Re.provider]:Ce.providers;return{...Ce,providers:Rr}}),Pe(Ce=>{const Fn={...Ce};return delete Fn[q],Fn}),le(Ce=>({...Ce,[q]:"✅ Saved"}))):(le(Ce=>({...Ce,[q]:`❌ ${Re.error||"Save failed"}`})),Re.unauthorized&&He()),X(null)},Lt=async q=>{if(!window.confirm(`Remove ${q}'s API key and configuration? This cannot be undone.`))return;X(q),le({});const me=await ee.deleteProvider(q);me.ok?me.envSourced?(t(Re=>Re&&{...Re,providers:Re.providers.map(Ce=>Ce.type===q&&me.provider||Ce)}),le(Re=>({...Re,[q]:`⚠️ Key comes from ${me.envVar?`$${me.envVar}`:"an env var"} — unset it there to remove it (config can't override the env).`}))):(t(Re=>Re&&{...Re,providers:Re.providers.filter(Ce=>Ce.type!==q)}),Pe(Re=>{const Ce={...Re};return delete Ce[q],Ce})):(le(Re=>({...Re,[q]:`❌ ${me.error||"Remove failed"}`})),me.unauthorized&&He()),X(null)},Ct=async q=>{X(q);const me=await ee.testProvider(q);le(Re=>{var Ce;return{...Re,[q]:me.ok?`✅ Connected — ${((Ce=me.models)==null?void 0:Ce.length)??0} model(s) reachable`:`❌ ${me.error||"Connection failed"}`}}),X(null)},An=()=>{Y&&(Pe(q=>({...q,[Y]:{}})),_e(""))};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 q=!o.configured;return s.jsxs("div",{className:"admin-header",children:[s.jsxs("h2",{className:"section-title",children:["🛠️ Admin — ",q?"Set up access":"Log in"]}),s.jsx("p",{className:"admin-subtitle",children:q?"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:q?xn:Ie,children:[s.jsxs("label",{children:[s.jsx("span",{children:"Username"}),s.jsx("input",{type:"text",value:k,onChange:me=>S(me.target.value),autoComplete:"username",placeholder:"admin"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Password"}),s.jsx("input",{type:"password",value:w,onChange:me=>_(me.target.value),autoComplete:q?"new-password":"current-password",placeholder:"••••••••"})]}),q?s.jsxs("label",{children:[s.jsx("span",{children:"Confirm password"}),s.jsx("input",{type:"password",value:N,onChange:me=>C(me.target.value),autoComplete:"new-password",placeholder:"••••••••"})]}):null,T?s.jsx("div",{className:"admin-error",children:T}):null,s.jsx("button",{className:"admin-refresh-btn",type:"submit",disabled:M||!k||!w,children:M?"⏳ …":q?"🔐 Create admin":"🔐 Log in"}),q?s.jsxs("p",{className:"admin-hint",children:["Automation alternative: set ",s.jsx("code",{children:"NUVIRA_DASHBOARD_ADMIN_USER"})," and"," ",s.jsx("code",{children:"NUVIRA_DASHBOARD_ADMIN_PASSWORD"})," in the dashboard's environment."]}):null]})]})}if(d){const q=h.length>0&&h.length<8,me=g.length>0&&g!==h,Re=async Ce=>{if(Ce.preventDefault(),q||me||!h)return;$(!0),I(null);const Fn=await ee.changeAdminPassword(w,h);Fn.ok?(f(!1),_(""),p(""),m(""),fe(),vt(),Le()):I(Fn.error||"Could not change the password."),$(!1)};return s.jsxs("div",{className:"admin-header",children:[s.jsx("h2",{className:"section-title",children:"🔐 Set your own password"}),s.jsxs("p",{className:"admin-subtitle",children:["This dashboard is running on its ",s.jsx("strong",{children:"published default password"}),", so anyone who can reach this port can sign in. Until you replace it, the agent will refuse to save anything — API keys, provider settings, users."]}),s.jsxs("form",{className:"admin-gate-form",onSubmit:Re,children:[s.jsxs("label",{children:[s.jsx("span",{children:"Current password"}),s.jsx("input",{type:"password",value:w,onChange:Ce=>_(Ce.target.value),autoComplete:"current-password",placeholder:"admin"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"New password"}),s.jsx("input",{type:"password",value:h,onChange:Ce=>p(Ce.target.value),autoComplete:"new-password",placeholder:"at least 8 characters"})]}),q?s.jsx("div",{className:"admin-error",children:"Use at least 8 characters."}):null,s.jsxs("label",{children:[s.jsx("span",{children:"Confirm new password"}),s.jsx("input",{type:"password",value:g,onChange:Ce=>m(Ce.target.value),autoComplete:"new-password",placeholder:"repeat it"})]}),me?s.jsx("div",{className:"admin-error",children:"The two passwords do not match."}):null,T?s.jsx("div",{className:"admin-error",children:T}):null,s.jsx("button",{className:"admin-refresh-btn",type:"submit",disabled:M||!w||!h||q||me,children:M?"⏳ …":"🔐 Save new password"})]})]})}const Ot=(e==null?void 0:e.system.filter(q=>q.status==="pass").length)??0,dt=(e==null?void 0:e.system.filter(q=>q.status==="warn").length)??0,Tn=(e==null?void 0:e.system.filter(q=>q.status==="fail").length)??0,Qt=(e==null?void 0:e.enterprise.filter(q=>q.status==="pass").length)??0,ws=(e==null?void 0:e.enterprise.filter(q=>q.status==="warn").length)??0,ka=(e==null?void 0:e.enterprise.filter(q=>q.status==="fail").length)??0,mr=(e==null?void 0:e.providers)??[],Jt=q=>{const me=ce.find(Re=>Re.id===q);return me||{label:q}};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"admin-header",children:[s.jsxs("h2",{className:"section-title",children:["🛠️ Admin — Command Runner & Configuration",b?s.jsxs("span",{className:`admin-role-badge admin-role-${v||"viewer"}`,children:[b," · ",v||"viewer"]}):null]}),s.jsxs("div",{className:"admin-header-actions",children:[s.jsx("button",{className:"admin-refresh-btn",onClick:()=>void fe(),disabled:n,children:n?"⏳ Running checks…":"🔄 Refresh (run all commands)"}),Ae||v==="operator"?s.jsx("button",{className:"admin-logout-btn",onClick:()=>void W(),disabled:ve!==null,title:"Stop the running gateway (buff gateway stop)",children:ve==="gateway"?"⏳ Stopping…":"⏻ Stop gateway"}):null,Ae?s.jsx("button",{className:"admin-logout-btn",onClick:()=>void V(),disabled:ve!==null,title:"Shut down this dashboard server (buff dashboard stop)",children:ve==="dashboard"?"⏳ Stopping…":"🛑 Stop dashboard"}):null,s.jsx("button",{className:"admin-logout-btn",onClick:()=>void $t(),children:"🚪 Log out"})]})]}),Ee?s.jsx("div",{className:"admin-error",children:Ee}):null,Ae?null:s.jsxs("div",{className:"admin-readonly-note",children:["🔒 Your role (",s.jsx("code",{children:v||"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:Ot+Qt}),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:dt+ws}),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:Tn+ka}),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:mr.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(q=>s.jsx(v_,{check:q},q.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(q=>s.jsx(v_,{check:q},q.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:[mr.map(q=>{const me=Jt(q.type),Re=pe[q.type]||{};return s.jsxs("tr",{children:[s.jsxs("td",{className:"admin-provider-type",children:[me.icon?`${me.icon} `:"",me.label,s.jsxs("div",{className:"admin-provider-sub",children:[q.type," · ",vse[q.keySource]||q.keySource]}),q.keySource==="env"?s.jsxs("div",{className:"admin-hint",children:["comes from ",me.envVar||"env var"," — change it there, config can't override it"]}):q.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 ${q.configured?"admin-check-pass":"admin-check-warn"}`,children:q.configured?"✅ Configured":"⚠️ Not configured"})}),s.jsx("td",{children:me.keyless?s.jsx("div",{className:"admin-hint",children:"No key needed (probed)"}):Ae?s.jsx("input",{className:"admin-input admin-key-input",type:"password","aria-label":`${q.type} API key`,placeholder:q.keyMasked||"set a new key…",value:Re.apiKey??"",onChange:Ce=>xe(q.type,"apiKey",Ce.target.value),autoComplete:"new-password"}):s.jsx("div",{className:"admin-hint",children:q.keyMasked||"—"})}),s.jsx("td",{children:Ae?s.jsx("input",{className:"admin-input",type:"text","aria-label":`${q.type} base URL`,placeholder:q.baseUrl||"default endpoint",value:Re.baseUrl??"",onChange:Ce=>xe(q.type,"baseUrl",Ce.target.value)}):s.jsx("div",{className:"admin-hint",children:q.baseUrl?q.baseUrl.replace(/^https?:\/\/(?:[^@/]*@)?/,""):"default endpoint"})}),s.jsx("td",{children:Ae?s.jsx("input",{className:"admin-input",type:"text","aria-label":`${q.type} model`,placeholder:q.model||"default model",value:Re.model??"",onChange:Ce=>xe(q.type,"model",Ce.target.value)}):s.jsx("div",{className:"admin-hint",children:q.model||"default model"})}),s.jsx("td",{children:Ae?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"admin-row-actions",children:[s.jsx("button",{className:"admin-mini-btn",disabled:G===q.type,onClick:()=>void Qe(q.type),children:"💾 Save"}),s.jsx("button",{className:"admin-mini-btn",disabled:G===q.type,title:"Tests the SAVED configuration — save first to test a new key",onClick:()=>void Ct(q.type),children:"🔌 Test"}),s.jsx("button",{className:"admin-mini-btn admin-mini-danger",disabled:G===q.type,onClick:()=>void Lt(q.type),children:"🗑 Remove"})]}),ae[q.type]?s.jsx("div",{className:"admin-row-msg",children:ae[q.type]}):null]}):s.jsx("div",{className:"admin-hint",children:"read-only"})})]},q.type)}),mr.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:6,className:"admin-empty-cell",children:"No providers configured yet."})}):null]})]})}),Ae&&ce.length>0?s.jsxs("div",{className:"admin-add-provider",children:[s.jsxs("select",{className:"admin-input",value:Y,onChange:q=>_e(q.target.value),children:[s.jsx("option",{value:"",children:"Add a provider…"}),ce.filter(q=>!mr.some(me=>me.type===q.id)).map(q=>s.jsxs("option",{value:q.id,children:[q.icon?`${q.icon} `:"",q.label," (",q.id,")"]},q.id))]}),s.jsx("button",{className:"admin-mini-btn",disabled:!Y,onClick:An,children:"➕ Add"})]}):null,s.jsx(mse,{authed:c,role:v||"viewer"}),Ae?s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"section-subtitle",children:"👥 Dashboard Users (role.manage)"}),s.jsxs("div",{className:"admin-users-list",children:[R.map(q=>s.jsxs("div",{className:"admin-user-row",children:[s.jsx("span",{className:"admin-user-name",children:q.user}),s.jsx("span",{className:`admin-role-badge admin-role-${q.role}`,children:q.role}),s.jsxs("span",{className:"admin-user-since",children:["since ",new Date(q.createdAt).toLocaleDateString()]}),q.user!==b?s.jsx("button",{className:"admin-mini-btn admin-mini-danger",onClick:()=>void he(q.user),children:"🗑 Remove user"}):s.jsx("span",{className:"admin-hint",children:"you"})]},q.user)),R.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:oe,children:[s.jsxs("label",{children:[s.jsx("span",{children:"Username"}),s.jsx("input",{type:"text",value:O,onChange:q=>F(q.target.value),autoComplete:"off"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Password (min 8 chars)"}),s.jsx("input",{type:"password",value:A,onChange:q=>Z(q.target.value),autoComplete:"new-password"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Role"}),s.jsxs("select",{value:L,onChange:q=>P(q.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"})]})]}),D?s.jsx("div",{className:"admin-row-msg",children:D}):null,s.jsx("button",{className:"admin-refresh-btn",type:"submit",disabled:!O||!A,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 uM(e){return String(e??"").replace(/\d{3,}/g,t=>t.slice(0,2)+"***")}const xse={idle:"Not paired",pairing:"⏳ Pairing…",paired:"✅ Paired",failed:"❌ Pairing failed",cancelled:"⏹ Cancelled",error:"💥 Pairing error"};function wse({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:xse[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?_:uM(_)]})]},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 Sse({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 $=await ee.getPlatformConfigs();S.current&&i($)},[t]);E.useEffect(()=>(w(),()=>{S.current=!1}),[w]);const _=async($,R)=>{c($),d(null);const z=await ee.setPlatformConfig($,R);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 $=>{if(!window.confirm(`Remove ${$} transport config? Tokens will be deleted from ~/.buff/.env.`))return;c($),d(null);const R=await ee.removePlatformConfig($);if(S.current){if(c(null),R.unauthorized||R.forbidden){t(R.error);return}d({kind:R.ok?"ok":"err",text:R.ok?"Removed.":R.error||"Remove failed."}),R.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=$=>{e&&(h($),g(0),v(Object.fromEntries($.envVars.map(R=>[R.varName,R.value]))),k(null))},I=async()=>{if(!f||!e)return;b(!0),k(null);const $=await ee.setPlatformConfig(f.platform,m);if(b(!1),$.unauthorized||$.forbidden){t($.error);return}$.ok?(k({kind:"ok",text:"✅ Token saved! The transport is now active."}),w()):k({kind:"err",text:$.error||"Save failed."})};if(r===null)return s.jsx("div",{className:"empty-state",children:"Loading platform transports…"});const M=f?C[f.platform]:null;return n==="table"?s.jsxs(s.Fragment,{children:[f&&M?s.jsx("div",{className:"wizard-overlay",onClick:()=>h(null),children:s.jsxs("div",{className:"wizard-modal",onClick:$=>$.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:M.steps.map(($,R)=>s.jsx("li",{children:$},R))}),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($=>s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:$.prompt}),s.jsx("input",{type:$.secret?"password":"text",value:m[$.varName]??"",onChange:R=>v(z=>({...z,[$.varName]:R.target.value})),placeholder:$.secret?"••••••••":"value",autoComplete:"off",spellCheck:!1,autoFocus:!0})]},$.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 I(),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:M.postSetup.map(($,R)=>s.jsx("li",{children:$},R))})]}):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($=>s.jsxs(H.Fragment,{children:[s.jsxs("tr",{className:`platform-config-row ${$.configured?"configured":""}`,children:[s.jsxs("td",{className:"platform-config-name",children:[s.jsx("span",{className:"hub-platform-label",children:$.label}),s.jsx("span",{className:"hub-card-id",children:$.platform})]}),s.jsxs("td",{children:[s.jsx("span",{className:`status-dot ${$.configured?"connected":"reconnecting"}`}),s.jsx("span",{className:"platform-config-status-text",children:$.configured?"Active":"Not configured"})]}),s.jsxs("td",{className:"platform-config-actions",children:[$.configured?null:s.jsx("button",{type:"button",className:"wizard-start-btn",onClick:()=>T($),disabled:!e,children:"🚀 Getting Started"}),$.setupUrl?s.jsx("a",{href:$.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===$.platform?null:$.platform),disabled:!e,children:a===$.platform?"▴ Close":$.configured?"✎ Edit":"⚙ Configure"}),$.configured?s.jsx("button",{type:"button",className:"admin-mini-btn contact-delete-btn",onClick:()=>void N($.platform),disabled:!e,children:"🗑️"}):null]}),s.jsx("td",{className:"platform-config-cli",children:s.jsxs("code",{children:["buff gateway setup ",$.platform]})})]}),a===$.platform?s.jsx("tr",{className:"platform-config-expanded",children:s.jsx("td",{colSpan:4,children:s.jsxs("div",{className:"platform-config-form",children:[$.envVars.map(R=>s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:R.prompt}),s.jsx("input",{type:R.secret?"password":"text",value:R.value,readOnly:!0,className:"platform-config-readonly",placeholder:R.secret?"••••••••":"value"})]},R.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]},$.platform))})]})})]}):s.jsxs(s.Fragment,{children:[f&&M?s.jsx("div",{className:"wizard-overlay",onClick:()=>h(null),children:s.jsxs("div",{className:"wizard-modal",onClick:$=>$.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:M.steps.map(($,R)=>s.jsx("li",{children:$},R))}),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($=>s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:$.prompt}),s.jsx("input",{type:$.secret?"password":"text",value:m[$.varName]??"",onChange:R=>v(z=>({...z,[$.varName]:R.target.value})),placeholder:$.secret?"••••••••":"value",autoComplete:"off",spellCheck:!1,autoFocus:!0})]},$.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 I(),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:M.postSetup.map(($,R)=>s.jsx("li",{children:$},R))})]}):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($=>s.jsx(kse,{entry:$,canWrite:e,busy:l===$.platform,expanded:a===$.platform,onToggle:()=>o(a===$.platform?null:$.platform),onSave:R=>void _($.platform,R),onRemove:()=>void N($.platform),onStartWizard:()=>T($)},$.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 kse(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 Ese=[{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:"🧠"}],_se={pending:"⏳ pending",sent:"✅ sent",failed:"❌ failed"};function Nse(){var W0,H0,G0,q0,K0,V0,Y0,X0,Z0;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,I]=E.useState(null),[M,$]=E.useState(null),[R,z]=E.useState({}),[D,U]=E.useState(""),[O,F]=E.useState(""),[A,Z]=E.useState(!1),[L,P]=E.useState(null),[ce,we]=E.useState(!1),[pe,Pe]=E.useState({}),[G,X]=E.useState(!1),[ae,le]=E.useState(null),[Y,_e]=E.useState({}),[Ee,je]=E.useState({}),[ve,$e]=E.useState({}),[fe,vt]=E.useState(!1),[Le,Ae]=E.useState(null),[He,Ie]=E.useState(""),[xn,$t]=E.useState(null),[W,V]=E.useState(!1),[oe,he]=E.useState(new Map),[xe,Qe]=E.useState(new Set),[Lt,Ct]=E.useState(!1),[An,Ot]=E.useState([]),[dt,Tn]=E.useState(""),[Qt,ws]=E.useState(null),[ka,mr]=E.useState(""),[Jt,q]=E.useState([]),[me,Re]=E.useState(0),[Ce,Fn]=E.useState(0),[Rr,gr]=E.useState(!0),[Fe,Ss]=E.useState(!1),[ei,Ht]=E.useState(!1),Ci=20,Oi=E.useRef(null),Pi=E.useCallback(async(j=!1)=>{if(Fe)return;const K=j?0:Ce;Ss(!0);try{const ne=await ee.fetchGatewayConversations({offset:K,limit:Ci,q:He||void 0});ne.ok&&ne.conversations&&(q(re=>j?ne.conversations:[...re,...ne.conversations]),Re(ne.total??0),Fn(K+ne.conversations.length),gr(ne.hasMore??!1))}catch{}Ss(!1)},[Fe,Ce,He]);E.useEffect(()=>{e==="conversations"&&!ei&&!Fe&&(Ht(!0),Pi(!0))},[e,ei,Fe,Pi]),E.useEffect(()=>{const j=Oi.current;if(!j)return;const K=new IntersectionObserver(ne=>{var re;(re=ne[0])!=null&&re.isIntersecting&&Rr&&!Fe&&Pi(!1)},{threshold:.1});return K.observe(j),()=>K.disconnect()},[Rr,Fe,Pi]),E.useEffect(()=>{const j=setTimeout(()=>{e==="conversations"&&ei&&(q([]),Fn(0),gr(!0),Pi(!0))},300);return()=>clearTimeout(j)},[He]),E.useEffect(()=>ee.onTypingEvent(K=>{he(ne=>{const re=new Map(ne),de=`${K.platform}:${K.channelId}`;return K.typing?re.set(de,{platform:K.platform,channelId:K.channelId,startedAt:Date.now()}):re.delete(de),re})}),[]);const Fp=E.useCallback((j,K)=>{K.stopPropagation(),Qe(ne=>{const re=new Set(ne);return re.has(j)?re.delete(j):re.add(j),re})},[]),ul=E.useCallback(()=>{Qe(j=>j.size===Jt.length?new Set:new Set(Jt.map(K=>K.key)))},[Jt]),ks=E.useCallback(async()=>{if(xe.size!==0){Ct(!0);try{await ee.exportGatewayConversations([...xe])}catch{}Ct(!1)}},[xe]);E.useEffect(()=>{e==="conversations"&&ee.getAllConversationTags().then(j=>{j.ok&&j.tags&&Ot(j.tags)})},[e]);const Up=E.useCallback(async(j,K)=>{if(!K.trim())return;(await ee.addConversationTag(j,K.trim())).ok&&(q(re=>re.map(de=>de.key===j?{...de,tags:[...de.tags??[],K.trim().toLowerCase()]}:de)),Ot(re=>re.includes(K.trim().toLowerCase())?re:[...re,K.trim().toLowerCase()].sort())),ws(null),mr("")},[]),Ou=E.useCallback(async(j,K)=>{(await ee.removeConversationTag(j,K)).ok&&q(re=>re.map(de=>de.key===j?{...de,tags:(de.tags??[]).filter(Oe=>Oe!==K)}:de))},[]),Wp=E.useCallback((j,K)=>{K.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 be=ht.role==="user"?ne:"Agent",Nt=new Date(ht.ts).toLocaleString();re.push(`[${Nt}] ${be}:`),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 YP(e,t){if(e){if(typeof e=="string")return qv(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 qv(e,t)}}function oie(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function lie(e){if(Array.isArray(e))return qv(e)}function qv(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 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 Q(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){Te(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 Te(e,t,n){return t=XP(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function XP(e){var t=cie(e,"string");return zo(t)=="symbol"?t:t+""}function cie(e,t){if(zo(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(zo(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var uie={xAxis:["bottom","top"],yAxis:["left","right"]},die={width:"100%",height:"100%"},ZP={x:0,y:0};function pd(e){return e}var fie=function(t,n){return n==="horizontal"?t.x:n==="vertical"?t.y:n==="centric"?t.angle:t.radius},hie=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 ZP},Mp=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(Fo(l),Fo(u)):l},[]);return o.length>0?o:t&&t.length&&ue(i)&&ue(a)?t.slice(i,a+1):[]};function QP(e){return e==="number"?[0,"auto"]:void 0}var Kv=function(t,n,r,i){var a=t.graphicalItems,o=t.tooltipAxis,l=Mp(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=Ny(p,o.dataKey,i)}else h=f&&f[r]||l[r];return h?[].concat(Fo(c),[YO(u,h)]):c},[])},QE=function(t,n,r,i){var a=i||{x:t.chartX,y:t.chartY},o=fie(a,r),l=t.orderedTooltipTicks,c=t.tooltipAxis,u=t.tooltipTicks,d=LY(o,l,u,c);if(d>=0&&u){var f=u[d]&&u[d].value,h=Kv(t,n,d,f),p=hie(r,l,d,a);return{activeTooltipIndex:d,activeLabel:f,activePayload:h,activeCoordinate:p}}return null},pie=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=qO(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=Mp(t.data,{graphicalItems:i.filter(function(L){var P,ce=o in L.props?L.props[o]:(P=L.type.defaultProps)===null||P===void 0?void 0:P[o];return ce===C}),dataStartIndex:c,dataEndIndex:u}),I=T.length,M,$,R;zre(y.domain,k,b)&&(M=hv(y.domain,null,k),p&&(b==="number"||w!=="auto")&&(R=rc(T,x,"category")));var z=QP(b);if(!M||M.length===0){var D,U=(D=y.domain)!==null&&D!==void 0?D:z;if(x){if(M=rc(T,x,b),b==="category"&&p){var O=_3(M);S&&O?($=M,M=ih(0,I)):S||(M=Ik(U,M,m).reduce(function(L,P){return L.indexOf(P)>=0?L:[].concat(Fo(L),[P])},[]))}else if(b==="category")S?M=M.filter(function(L){return L!==""&&!Ye(L)}):M=Ik(U,M,m).reduce(function(L,P){return L.indexOf(P)>=0||P===""||Ye(P)?L:[].concat(Fo(L),[P])},[]);else if(b==="number"){var F=UY(T,i.filter(function(L){var P,ce,we=o in L.props?L.props[o]:(P=L.type.defaultProps)===null||P===void 0?void 0:P[o],pe="hide"in L.props?L.props.hide:(ce=L.type.defaultProps)===null||ce===void 0?void 0:ce.hide;return we===C&&(N||!pe)}),x,a,d);F&&(M=F)}p&&(b==="number"||w!=="auto")&&(R=rc(T,x,"category"))}else p?M=ih(0,I):l&&l[C]&&l[C].hasStack&&b==="number"?M=h==="expand"?[0,1]:VO(l[C].stackGroups,c,u):M=GO(T,i.filter(function(L){var P=o in L.props?L.props[o]:L.type.defaultProps[o],ce="hide"in L.props?L.props.hide:L.type.defaultProps.hide;return P===C&&(N||!ce)}),b,d,!0);if(b==="number")M=Hv(f,M,C,a,_),U&&(M=hv(U,M,k));else if(b==="category"&&U){var A=U,Z=M.every(function(L){return A.indexOf(L)>=0});Z&&(M=A)}}return Q(Q({},g),{},Te({},C,Q(Q({},y),{},{axisType:a,domain:M,categoricalDomain:R,duplicateDomain:$,originalDomain:(v=y.domain)!==null&&v!==void 0?v:z,isCategorical:p,layout:d})))},{})},mie=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=Mp(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:u}),p=h.length,g=qO(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=QP("number");if(!v[x]){m++;var S;return g?S=ih(0,p):l&&l[x]&&l[x].hasStack?(S=VO(l[x].stackGroups,c,u),S=Hv(f,S,x,a)):(S=hv(k,GO(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=Hv(f,S,x,a)),Q(Q({},v),{},Te({},x,Q(Q({axisType:a},i.defaultProps),{},{hide:!0,orientation:cr(uie,"".concat(a,".").concat(m%2),null),domain:S,originalDomain:k,isCategorical:g,layout:d})))}return v},{})},gie=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=Tr(d,a),p={};return h&&h.length?p=pie(t,{axes:h,graphicalItems:o,axisType:i,axisIdKey:f,stackGroups:l,dataStartIndex:c,dataEndIndex:u}):o&&o.length&&(p=mie(t,{Axis:a,graphicalItems:o,axisType:i,axisIdKey:f,stackGroups:l,dataStartIndex:c,dataEndIndex:u})),p},yie=function(t){var n=Gi(t),r=fi(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:Ax(r,function(i){return i.coordinate}),tooltipAxis:n,tooltipAxisBandSize:Vf(n,r)}},JE=function(t){var n=t.children,r=t.defaultShowTooltip,i=Gn(n,Po),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}},vie=function(t){return!t||!t.length?!1:t.some(function(n){var r=pi(n&&n.type);return r&&r.indexOf("Bar")>=0})},e_=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"}},bie=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=Gn(f,Po),g=Gn(f,Ya),m=Object.keys(c).reduce(function(S,w){var _=c[w],N=_.orientation;return!_.mirror&&!_.hide?Q(Q({},S),{},Te({},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),{},Te({},N,cr(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||Po.defaultProps.height),g&&n&&(y=zY(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)})},xie=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},wie=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,I=y.barGap,M=y.barCategoryGap,$=y.maxBarSize,R=e_(T),z=R.numericAxisName,D=R.cateAxisName,U=vie(x),O=[];return x.forEach(function(F,A){var Z=Mp(y.data,{graphicalItems:[F],dataStartIndex:_,dataEndIndex:N}),L=F.type.defaultProps!==void 0?Q(Q({},F.type.defaultProps),F.props):F.props,P=L.dataKey,ce=L.maxBarSize,we=L["".concat(z,"Id")],pe=L["".concat(D,"Id")],Pe={},G=c.reduce(function(Ae,He){var Ie=b["".concat(He.axisType,"Map")],xn=L["".concat(He.axisType,"Id")];Ie&&Ie[xn]||He.axisType==="zAxis"||cs();var $t=Ie[xn];return Q(Q({},Ae),{},Te(Te({},He.axisType,$t),"".concat(He.axisType,"Ticks"),fi($t)))},Pe),X=G[D],ae=G["".concat(D,"Ticks")],le=k&&k[we]&&k[we].hasStack&&eX(F,k[we].stackGroups),Y=pi(F.type).indexOf("Bar")>=0,_e=Vf(X,ae),Ee=[],je=U&&DY({barSize:C,stackGroups:k,totalSize:xie(G,D)});if(Y){var ve,$e,fe=Ye(ce)?$:ce,vt=(ve=($e=Vf(X,ae,!0))!==null&&$e!==void 0?$e:fe)!==null&&ve!==void 0?ve:0;Ee=BY({barGap:I,barCategoryGap:M,bandSize:vt!==_e?vt:_e,sizeList:je[pe],maxBarSize:fe}),vt!==_e&&(Ee=Ee.map(function(Ae){return Q(Q({},Ae),{},{position:Q(Q({},Ae.position),{},{offset:Ae.position.offset-vt/2})})}))}var Le=F&&F.type&&F.type.getComposedData;Le&&O.push({props:Q(Q({},Le(Q(Q({},G),{},{displayedData:Z,props:y,dataKey:P,item:F,bandSize:_e,barPosition:Ee,offset:S,stackedData:le,layout:T,dataStartIndex:_,dataEndIndex:N}))),{},Te(Te(Te({key:F.key||"item-".concat(A)},z,G[z]),D,G[D]),"animationId",w)),childIndex:L3(F,y.children),item:F})}),O},p=function(y,b){var x=y.props,k=y.dataStartIndex,S=y.dataEndIndex,w=y.updateId;if(!T1({props:x}))return null;var _=x.children,N=x.layout,C=x.stackOffset,T=x.data,I=x.reverseStackOrder,M=e_(N),$=M.numericAxisName,R=M.cateAxisName,z=Tr(_,r),D=ZY(T,z,"".concat($,"Id"),"".concat(R,"Id"),C,I),U=c.reduce(function(L,P){var ce="".concat(P.axisType,"Map");return Q(Q({},L),{},Te({},ce,gie(x,Q(Q({},P),{},{graphicalItems:z,stackGroups:P.axisType===$&&D,dataStartIndex:k,dataEndIndex:S}))))},{}),O=bie(Q(Q({},U),{},{props:x,graphicalItems:z}),b==null?void 0:b.legendBBox);Object.keys(U).forEach(function(L){U[L]=d(x,U[L],O,L.replace("Map",""),n)});var F=U["".concat(R,"Map")],A=yie(F),Z=h(x,Q(Q({},U),{},{dataStartIndex:k,dataEndIndex:S,updateId:w,graphicalItems:z,stackGroups:D,offset:O}));return Q(Q({formattedGraphicalItems:Z,graphicalItems:z,offset:O,stackGroups:D},A),U)},g=function(v){function y(b){var x,k,S;return Jre(this,y),S=nie(this,y,[b]),Te(S,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),Te(S,"accessibilityManager",new Bre),Te(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}))))}}),Te(S,"handleReceiveSyncEvent",function(w,_,N){if(S.props.syncId===w){if(N===S.eventEmitterSymbol&&typeof S.props.syncMethod!="function")return;S.applySyncEvent(_)}}),Te(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})}}),Te(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;De(C)&&C(N,w)}}),Te(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;De(C)&&C(N,w)}),Te(S,"handleItemMouseEnter",function(w){S.setState(function(){return{isTooltipActive:!0,activeItem:w,activePayload:w.tooltipPayload,activeCoordinate:w.tooltipPosition||{x:w.cx,y:w.cy}}})}),Te(S,"handleItemMouseLeave",function(){S.setState(function(){return{isTooltipActive:!1}})}),Te(S,"handleMouseMove",function(w){w.persist(),S.throttleTriggeredAfterMouseMove(w)}),Te(S,"handleMouseLeave",function(w){S.throttleTriggeredAfterMouseMove.cancel();var _={isTooltipActive:!1};S.setState(_),S.triggerSyncEvent(_);var N=S.props.onMouseLeave;De(N)&&N(_,w)}),Te(S,"handleOuterEvent",function(w){var _=$3(w),N=cr(S.props,"".concat(_));if(_&&De(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)}}),Te(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;De(C)&&C(N,w)}}),Te(S,"handleMouseDown",function(w){var _=S.props.onMouseDown;if(De(_)){var N=S.getMouseInfo(w);_(N,w)}}),Te(S,"handleMouseUp",function(w){var _=S.props.onMouseUp;if(De(_)){var N=S.getMouseInfo(w);_(N,w)}}),Te(S,"handleTouchMove",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&S.throttleTriggeredAfterMouseMove(w.changedTouches[0])}),Te(S,"handleTouchStart",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&S.handleMouseDown(w.changedTouches[0])}),Te(S,"handleTouchEnd",function(w){w.changedTouches!=null&&w.changedTouches.length>0&&S.handleMouseUp(w.changedTouches[0])}),Te(S,"handleDoubleClick",function(w){var _=S.props.onDoubleClick;if(De(_)){var N=S.getMouseInfo(w);_(N,w)}}),Te(S,"handleContextMenu",function(w){var _=S.props.onContextMenu;if(De(_)){var N=S.getMouseInfo(w);_(N,w)}}),Te(S,"triggerSyncEvent",function(w){S.props.syncId!==void 0&&Vm.emit(Ym,S.props.syncId,w,S.eventEmitterSymbol)}),Te(S,"applySyncEvent",function(w){var _=S.props,N=_.layout,C=_.syncMethod,T=S.state.updateId,I=w.dataStartIndex,M=w.dataEndIndex;if(w.dataStartIndex!==void 0||w.dataEndIndex!==void 0)S.setState(Q({dataStartIndex:I,dataEndIndex:M},p({props:S.props,dataStartIndex:I,dataEndIndex:M,updateId:T},S.state)));else if(w.activeTooltipIndex!==void 0){var $=w.chartX,R=w.chartY,z=w.activeTooltipIndex,D=S.state,U=D.offset,O=D.tooltipTicks;if(!U)return;if(typeof C=="function")z=C(O,w);else if(C==="value"){z=-1;for(var F=0;F<O.length;F++)if(O[F].value===w.activeLabel){z=F;break}}var A=Q(Q({},U),{},{x:U.left,y:U.top}),Z=Math.min($,A.x+A.width),L=Math.min(R,A.y+A.height),P=O[z]&&O[z].value,ce=Kv(S.state,S.props.data,z),we=O[z]?{x:N==="horizontal"?O[z].coordinate:Z,y:N==="horizontal"?L:O[z].coordinate}:ZP;S.setState(Q(Q({},w),{},{activeLabel:P,activeCoordinate:we,activePayload:ce,activeTooltipIndex:z}))}else S.setState(w)}),Te(S,"renderCursor",function(w){var _,N=S.state,C=N.isTooltipActive,T=N.activeCoordinate,I=N.activePayload,M=N.offset,$=N.activeTooltipIndex,R=N.tooltipAxisBandSize,z=S.getTooltipEventType(),D=(_=w.props.active)!==null&&_!==void 0?_:C,U=S.props.layout,O=w.key||"_recharts-cursor";return H.createElement(qre,{key:O,activeCoordinate:T,activePayload:I,activeTooltipIndex:$,chartName:n,element:w,isActive:D,layout:U,offset:M,tooltipAxisBandSize:R,tooltipEventType:z})}),Te(S,"renderPolarAxis",function(w,_,N){var C=cr(w,"type.axisType"),T=cr(S.state,"".concat(C,"Map")),I=w.type.defaultProps,M=I!==void 0?Q(Q({},I),w.props):w.props,$=T&&T[M["".concat(C,"Id")]];return E.cloneElement(w,Q(Q({},$),{},{className:Ve(C,$.className),key:w.key||"".concat(_,"-").concat(N),ticks:fi($,!0)}))}),Te(S,"renderPolarGrid",function(w){var _=w.props,N=_.radialLines,C=_.polarAngles,T=_.polarRadius,I=S.state,M=I.radiusAxisMap,$=I.angleAxisMap,R=Gi(M),z=Gi($),D=z.cx,U=z.cy,O=z.innerRadius,F=z.outerRadius;return E.cloneElement(w,{polarAngles:Array.isArray(C)?C:fi(z,!0).map(function(A){return A.coordinate}),polarRadius:Array.isArray(T)?T:fi(R,!0).map(function(A){return A.coordinate}),cx:D,cy:U,innerRadius:O,outerRadius:F,key:w.key||"polar-grid",radialLines:N})}),Te(S,"renderLegend",function(){var w=S.state.formattedGraphicalItems,_=S.props,N=_.children,C=_.width,T=_.height,I=S.props.margin||{},M=C-(I.left||0)-(I.right||0),$=WO({children:N,formattedGraphicalItems:w,legendWidth:M,legendContent:u});if(!$)return null;var R=$.item,z=XE($,Kre);return E.cloneElement(R,Q(Q({},z),{},{chartWidth:C,chartHeight:T,margin:I,onBBoxUpdate:S.handleLegendBBoxUpdate}))}),Te(S,"renderTooltip",function(){var w,_=S.props,N=_.children,C=_.accessibilityLayer,T=Gn(N,hn);if(!T)return null;var I=S.state,M=I.isTooltipActive,$=I.activeCoordinate,R=I.activePayload,z=I.activeLabel,D=I.offset,U=(w=T.props.active)!==null&&w!==void 0?w:M;return E.cloneElement(T,{viewBox:Q(Q({},D),{},{x:D.left,y:D.top}),active:U,label:z,payload:U?R:[],coordinate:$,accessibilityLayer:C})}),Te(S,"renderBrush",function(w){var _=S.props,N=_.margin,C=_.data,T=S.state,I=T.offset,M=T.dataStartIndex,$=T.dataEndIndex,R=T.updateId;return E.cloneElement(w,{key:w.key||"_recharts-brush",onChange:cd(S.handleBrushChange,w.props.onChange),data:C,x:ue(w.props.x)?w.props.x:I.left,y:ue(w.props.y)?w.props.y:I.top+I.height+I.brushBottom-(N.bottom||0),width:ue(w.props.width)?w.props.width:I.width,startIndex:M,endIndex:$,updateId:"brush-".concat(R)})}),Te(S,"renderReferenceElement",function(w,_,N){if(!w)return null;var C=S,T=C.clipPathId,I=S.state,M=I.xAxisMap,$=I.yAxisMap,R=I.offset,z=w.type.defaultProps||{},D=w.props,U=D.xAxisId,O=U===void 0?z.xAxisId:U,F=D.yAxisId,A=F===void 0?z.yAxisId:F;return E.cloneElement(w,{key:w.key||"".concat(_,"-").concat(N),xAxis:M[O],yAxis:$[A],viewBox:{x:R.left,y:R.top,width:R.width,height:R.height},clipPathId:T})}),Te(S,"renderActivePoints",function(w){var _=w.item,N=w.activePoint,C=w.basePoint,T=w.childIndex,I=w.isRange,M=[],$=_.props.key,R=_.item.type.defaultProps!==void 0?Q(Q({},_.item.type.defaultProps),_.item.props):_.item.props,z=R.activeDot,D=R.dataKey,U=Q(Q({index:T,dataKey:D,cx:N.x,cy:N.y,r:4,fill:t0(_.item),strokeWidth:2,stroke:"#fff",payload:N.payload,value:N.value},Ke(z,!1)),vf(z));return M.push(y.renderActiveDot(z,U,"".concat($,"-activePoint-").concat(T))),C?M.push(y.renderActiveDot(z,Q(Q({},U),{},{cx:C.x,cy:C.y}),"".concat($,"-basePoint-").concat(T))):I&&M.push(null),M}),Te(S,"renderGraphicChild",function(w,_,N){var C=S.filterFormatItem(w,_,N);if(!C)return null;var T=S.getTooltipEventType(),I=S.state,M=I.isTooltipActive,$=I.tooltipAxis,R=I.activeTooltipIndex,z=I.activeLabel,D=S.props.children,U=Gn(D,hn),O=C.props,F=O.points,A=O.isRange,Z=O.baseLine,L=C.item.type.defaultProps!==void 0?Q(Q({},C.item.type.defaultProps),C.item.props):C.item.props,P=L.activeDot,ce=L.hide,we=L.activeBar,pe=L.activeShape,Pe=!!(!ce&&M&&U&&(P||we||pe)),G={};T!=="axis"&&U&&U.props.trigger==="click"?G={onClick:cd(S.handleItemMouseEnter,w.props.onClick)}:T!=="axis"&&(G={onMouseLeave:cd(S.handleItemMouseLeave,w.props.onMouseLeave),onMouseEnter:cd(S.handleItemMouseEnter,w.props.onMouseEnter)});var X=E.cloneElement(w,Q(Q({},C.props),G));function ae(He){return typeof $.dataKey=="function"?$.dataKey(He.payload):null}if(Pe)if(R>=0){var le,Y;if($.dataKey&&!$.allowDuplicatedCategory){var _e=typeof $.dataKey=="function"?ae:"payload.".concat($.dataKey.toString());le=Ny(F,_e,z),Y=A&&Z&&Ny(Z,_e,z)}else le=F==null?void 0:F[R],Y=A&&Z&&Z[R];if(pe||we){var Ee=w.props.activeIndex!==void 0?w.props.activeIndex:R;return[E.cloneElement(w,Q(Q(Q({},C.props),G),{},{activeIndex:Ee})),null,null]}if(!Ye(le))return[X].concat(Fo(S.renderActivePoints({item:C,activePoint:le,basePoint:Y,childIndex:R,isRange:A})))}else{var je,ve=(je=S.getItemByXY(S.state.activeCoordinate))!==null&&je!==void 0?je:{graphicalItem:X},$e=ve.graphicalItem,fe=$e.item,vt=fe===void 0?w:fe,Le=$e.childIndex,Ae=Q(Q(Q({},C.props),G),{},{activeIndex:Le});return[E.cloneElement(vt,Ae),null,null]}return A?[X,null,null]:[X,null]}),Te(S,"renderCustomized",function(w,_,N){return E.cloneElement(w,Q(Q({key:"recharts-customized-".concat(N)},S.props),S.state))}),Te(S,"renderMap",{CartesianGrid:{handler:pd,once:!0},ReferenceArea:{handler:S.renderReferenceElement},ReferenceLine:{handler:pd},ReferenceDot:{handler:S.renderReferenceElement},XAxis:{handler:pd},YAxis:{handler:pd},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:op("recharts"),"-clip"),S.throttleTriggeredAfterMouseMove=HC(S.triggeredAfterMouseMove,(k=b.throttleDelay)!==null&&k!==void 0?k:1e3/60),S.state={},S}return aie(y,v),tie(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=Gn(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,I=Kv(this.state,S,C,T),M=this.state.tooltipTicks[C].coordinate,$=(this.state.offset.top+w)/2,R=_==="horizontal",z=R?{x:M,y:$}:{y:M,x:$},D=this.state.formattedGraphicalItems.find(function(O){var F=O.item;return F.type.name==="Scatter"});D&&(z=Q(Q({},z),D.props.points[C].tooltipPosition),I=D.props.points[C].tooltipPayload);var U={activeTooltipIndex:C,isTooltipActive:!0,activeLabel:T,activePayload:I,activeCoordinate:z};this.setState(U),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){Ay([Gn(x.children,hn)],[Gn(this.props.children,hn)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var x=Gn(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=cq(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,I=T.xAxisMap,M=T.yAxisMap,$=this.getTooltipEventType(),R=QE(this.state,this.props.data,this.props.layout,C);if($!=="axis"&&I&&M){var z=Gi(I).scale,D=Gi(M).scale,U=z&&z.invert?z.invert(_.chartX):null,O=D&&D.invert?D.invert(_.chartY):null;return Q(Q({},_),{},{xValue:U,yValue:O},R)}return R?Q(Q({},_),R):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 I=this.state,M=I.angleAxisMap,$=I.radiusAxisMap;if(M&&$){var R=Gi(M);return Dk({x:_,y:N},R)}return null}},{key:"parseEventsOfWrapper",value:function(){var x=this.props.children,k=this.getTooltipEventType(),S=Gn(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 _=vf(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===pi(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 H.createElement("defs",null,H.createElement("clipPath",{id:x},H.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=YE(S,2),_=w[0],N=w[1];return Q(Q({},k),{},Te({},_,N.scale))},{}):null}},{key:"getYScales",value:function(){var x=this.state.yAxisMap;return x?Object.entries(x).reduce(function(k,S){var w=YE(S,2),_=w[0],N=w[1];return Q(Q({},k),{},Te({},_,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,I=C.item,M=I.type.defaultProps!==void 0?Q(Q({},I.type.defaultProps),I.props):I.props,$=pi(I.type);if($==="Bar"){var R=(T.data||[]).find(function(O){return YQ(x,O)});if(R)return{graphicalItem:C,payload:R}}else if($==="RadialBar"){var z=(T.data||[]).find(function(O){return Dk(x,O)});if(z)return{graphicalItem:C,payload:z}}else if(Np(C,w)||jp(C,w)||ru(C,w)){var D=QJ({graphicalItem:C,activeTooltipItem:w,itemData:M.data}),U=M.activeIndex===void 0?D:M.activeIndex;return{graphicalItem:Q(Q({},C),{},{childIndex:U}),payload:ru(C,w)?M.data[D]:C.props.data[D]}}}return null}},{key:"render",value:function(){var x=this;if(!T1(this))return null;var k=this.props,S=k.children,w=k.className,_=k.width,N=k.height,C=k.style,T=k.compact,I=k.title,M=k.desc,$=XE(k,Vre),R=Ke($,!1);if(T)return H.createElement(RE,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},H.createElement(Cy,eo({},R,{width:_,height:N,title:I,desc:M}),this.renderClipPath(),O1(S,this.renderMap)));if(this.props.accessibilityLayer){var z,D;R.tabIndex=(z=this.props.tabIndex)!==null&&z!==void 0?z:0,R.role=(D=this.props.role)!==null&&D!==void 0?D:"application",R.onKeyDown=function(O){x.accessibilityManager.keyboardEvent(O)},R.onFocus=function(){x.accessibilityManager.focus()}}var U=this.parseEventsOfWrapper();return H.createElement(RE,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},H.createElement("div",eo({className:Ve("recharts-wrapper",w),style:Q({position:"relative",cursor:"default",width:_,height:N},C)},U,{ref:function(F){x.container=F}}),H.createElement(Cy,eo({},R,{width:_,height:N,title:I,desc:M,style:die}),this.renderClipPath(),O1(S,this.renderMap)),this.renderLegend(),this.renderTooltip()))}}])}(E.Component);Te(g,"displayName",n),Te(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)),Te(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,I=y.dataEndIndex;if(y.updateId===void 0){var M=JE(v);return Q(Q(Q({},M),{},{updateId:0},p(Q(Q({props:v},M),{},{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||!lo(C,y.prevMargin)){var $=JE(v),R={chartX:y.chartX,chartY:y.chartY,isTooltipActive:y.isTooltipActive},z=Q(Q({},QE(y,x,_)),{},{updateId:y.updateId+1}),D=Q(Q(Q({},$),R),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(!Ay(k,y.prevChildren)){var U,O,F,A,Z=Gn(k,Po),L=Z&&(U=(O=Z.props)===null||O===void 0?void 0:O.startIndex)!==null&&U!==void 0?U:T,P=Z&&(F=(A=Z.props)===null||A===void 0?void 0:A.endIndex)!==null&&F!==void 0?F:I,ce=L!==T||P!==I,we=!Ye(x),pe=we&&!ce?y.updateId:y.updateId+1;return Q(Q({updateId:pe},p(Q(Q({props:v},y),{},{updateId:pe,dataStartIndex:L,dataEndIndex:P}),y)),{},{prevChildren:k,dataStartIndex:L,dataEndIndex:P})}return null}),Te(g,"renderActiveDot",function(v,y,b){var x;return E.isValidElement(v)?x=E.cloneElement(v,y):De(v)?x=v(y):x=H.createElement(cP,y),H.createElement(Yt,{className:"recharts-active-dot",key:b},x)});var m=E.forwardRef(function(y,b){return H.createElement(g,eo({},y,{ref:b}))});return m.displayName=g.displayName,m},La=wie({chartName:"BarChart",GraphicalChild:fn,defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"xAxis",AxisComp:Wr},{axisType:"yAxis",AxisComp:Hr}],formatAxisMap:kte});function t_(e){return e==null||e<1e-5?"$0.00":e<.01?"$"+e.toFixed(6):"$"+e.toFixed(4)}function Li(e){return e==null?"0":e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}const Sie={local:"#3fb950",groq:"#58a6ff",gemini:"#bc8cff",nim:"#39d2c0",openrouter:"#d29922"};function kie({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:t_(t.totalCost),label:"Total Cost"},{icon:"📞",value:Li(t.totalRequests),label:"API Requests"},{icon:"🧠",value:Li(i.total),label:"Trajectories"},{icon:"📝",value:Li(n.total),label:"Chat Sessions"},{icon:"🏆",value:Li(r.totalRuns),label:"Benchmark Runs"},{icon:"📦",value:Li(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:Li(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:Li(((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:Li(((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($a,{width:"100%",height:260,children:s.jsxs(La,{data:l,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(qi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Wr,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(Hr,{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=>[t_(h),"Cost"]}),s.jsx(fn,{dataKey:"value",radius:[4,4,0,0],children:l.map(h=>s.jsx(Mc,{fill:Sie[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($a,{width:"100%",height:260,children:s.jsxs(La,{data:c,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(qi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Wr,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(Hr,{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 n_={planner:"📋","context-gatherer":"📂",writer:"✏️",reviewer:"👁️",tester:"🧪",debugger:"🐛",runner:"▶️",git:"🔀",package:"📦","github-release":"🏷️",security:"🔒",orchestrator:"🎯"},r_={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"},i_={pending:{icon:"⏳",label:"Pending"},running:{icon:"▶️",label:"Running"},completed:{icon:"✅",label:"Done"},failed:{icon:"❌",label:"Failed"}},Eie={pending:"#6e7681",running:"#58a6ff",completed:"#3fb950",failed:"#f85149"};function _ie(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 Nie(e,t){const n=[],r=new Set,i=_ie(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 Di(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 a_(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit"}):""}function jie(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 Aie({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(()=>jie((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,I=Math.min(1,Math.max(0,(_-C.left)/T));c(I*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:a_(_.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:["⏱ ",Di(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:[Di(l)," / ",Di(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=r_[_.agentType]||"#58a6ff",C=Eie[_.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:I=>{I.stopPropagation(),d(!1),c((_.start+_.width/2)*m)},title:`${Zm[_.agentType]||_.agentType}: ${_.description}`,children:[s.jsx("span",{className:"phase-block-icon",children:n_[_.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:`${Di(l)} elapsed`})]}),s.jsxs("div",{className:"phase-ticks",children:[s.jsx("span",{children:"0"}),s.jsx("span",{children:Di(Math.round(m/2))}),s.jsx("span",{children:Di(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:n_[y.agentType]||"⚙️"}),s.jsx("span",{className:"phase-detail-agent",style:{color:r_[y.agentType]||"#58a6ff"},children:Zm[y.agentType]||y.agentType}),s.jsxs("span",{className:`phase-status-badge phase-status-${y.status}`,children:[i_[y.status].icon," ",i_[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?Di(y.dur):`~${Di(y.dur)}`]}),y.startedAt?s.jsxs("span",{children:["🕐 ",a_(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."})]})})]})}function Qm(e){return e===void 0?"—":`$${e.toFixed(5)}`}function s_(e){if(e===void 0||!Number.isFinite(e)||e<0)return"—";if(e<1e3)return`${Math.round(e)}ms`;const t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;const n=Math.floor(t/60);return n<60?`${n}m ${String(Math.round(t%60)).padStart(2,"0")}s`:`${Math.floor(n/60)}h ${String(n%60).padStart(2,"0")}m`}function Jm(e){return e===void 0?"—":e.toLocaleString("en-US")}function Tie({jobs:e}){const t=E.useMemo(()=>e.filter(u=>u.batchStats.length>0),[e]),[n,r]=E.useState(null);if(t.length===0)return null;const i=t.find(u=>u.id===n)??t[0],a=i.batchStats,o=a.filter(u=>u.durationMs!==void 0),l=o.reduce((u,d)=>u+(d.durationMs??0),0),c=o.length>0?l/o.length:void 0;return s.jsxs("div",{className:"dag-timeline-section","data-testid":"batch-economy",children:[s.jsxs("h3",{className:"section-subtitle",children:["📊 Per-batch cost & latency"," ",s.jsx("span",{className:"timeline-subtitle",children:"— measured, not estimated"})]}),t.length>1&&s.jsx("div",{className:"dag-loop-turn-meta",style:{marginBottom:8},children:t.slice(0,5).map(u=>s.jsx("button",{type:"button",className:"dag-loop-turn-chip",onClick:()=>r(u.id),style:{cursor:"pointer",opacity:u.id===i.id?1:.55,fontWeight:u.id===i.id?600:400},children:u.progressLine??u.goal.slice(0,40)},u.id))}),s.jsxs("div",{className:"dag-loop-turn-meta",style:{marginBottom:8},children:[s.jsxs("span",{className:"dag-loop-turn-chip",children:[i.kind==="long-form"?"📖":"🛠️"," ",i.status]}),s.jsxs("span",{className:"dag-loop-turn-chip",children:[i.progress,"% done"]}),s.jsxs("span",{className:"dag-loop-turn-chip",children:[i.batches," batch",i.batches===1?"":"es"]}),s.jsxs("span",{className:"dag-loop-turn-chip dag-loop-turn-chip-dim",children:[Jm(i.tokens)," tokens · ",Qm(i.costUsd)]}),i.stopReason&&s.jsxs("span",{className:"dag-loop-turn-chip dag-loop-turn-chip-dim",children:["stopped: ",i.stopReason]})]}),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:"Batch"}),s.jsx("th",{children:"Done"}),s.jsx("th",{children:"Tokens"}),s.jsx("th",{children:"Cost"}),s.jsx("th",{children:"Time"})]})}),s.jsxs("tbody",{children:[a.map(u=>s.jsxs("tr",{children:[s.jsx("td",{children:u.index}),s.jsx("td",{children:`${Math.round(u.progress)}%`}),s.jsx("td",{children:Jm(u.tokens)}),s.jsx("td",{children:Qm(u.costUsd)}),s.jsx("td",{children:s_(u.durationMs)})]},u.index)),a.some(u=>u.error)&&s.jsx("tr",{children:s.jsxs("td",{colSpan:5,style:{opacity:.75},children:["✗ failures:"," ",a.filter(u=>u.error).map(u=>`#${u.index} ${u.error}`).join(" · ")]})}),s.jsxs("tr",{children:[s.jsx("td",{children:s.jsx("strong",{children:"total"})}),s.jsx("td",{children:s.jsx("strong",{children:`${i.progress}%`})}),s.jsx("td",{children:s.jsx("strong",{children:Jm(i.tokens)})}),s.jsx("td",{children:s.jsx("strong",{children:Qm(i.costUsd)})}),s.jsx("td",{children:s.jsx("strong",{children:c===void 0?"—":`~${s_(c)} avg`})})]})]})]})})]})}const o_={planner:"📋","context-gatherer":"📂",writer:"✏️",reviewer:"👁️",tester:"🧪",debugger:"🐛",runner:"▶️",git:"🔀",package:"📦","github-release":"🏷️",security:"🔒",orchestrator:"🎯"},eg={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"},Cie={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"}},l_={pending:"⏳ Pending",running:"▶️ Running",completed:"✅ Done",failed:"❌ Failed"},Ms={trivial:{icon:"🟢",color:"#3fb950"},simple:{icon:"🔵",color:"#58a6ff"},moderate:{icon:"🟡",color:"#d29922"},complex:{icon:"🟠",color:"#f0883e"},critical:{icon:"🔴",color:"#f85149"}},tg={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 Oie(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 ng(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 c_(e){return e?new Date(e).toLocaleTimeString("en-US",{minute:"2-digit",second:"2-digit"}):""}function Pie({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 Mie({data:e}){var A,Z;const t=e==null?void 0:e.dag,n=(A=e==null?void 0:e.memory)==null?void 0:A.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(P=>{i(P),c(P.engine),d(P.engineExplanation),h(P.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(()=>Nie(p,e==null?void 0:e.pipelineRuns),[p,e==null?void 0:e.pipelineRuns]),b=L=>{o(L)},x=!!(p&&(p.nodes.length>0||p.active)),k=y.length>0,S=!!v,w=((Z=e==null?void 0:e.unattendedJobs)==null?void 0:Z.jobs)??[],_=w.some(L=>L.batchStats.length>0);if(!x&&!k&&!S&&!_)return s.jsx(Pie,{memoryTotal:n});const{nodes:N,edges:C,pipeline:T,active:I}=p??{nodes:[],edges:[],pipeline:null,active:!1},{layoutNodes:M,svgW:$,svgH:R}=Oie(N,C),z=N.filter(L=>L.status==="running").length,D=N.filter(L=>L.status==="completed").length,U=N.filter(L=>L.status==="failed").length,O=N.filter(L=>L.status==="pending").length,F=N.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(Aie,{runs:y,onScrub:b})]}),s.jsx(Tie,{jobs:w}),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:["⏱ ",ng(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((L,P)=>s.jsxs("span",{className:`dag-loop-tool ${L.ok===!1?"dag-loop-tool-error":""}`,title:L.error||`${L.tool}${L.durationMs!==void 0?` · ${L.durationMs}ms`:""}`,children:[L.ok===!1?"❌":"✓"," ",L.tool]},`${L.tool}-${P}`))})]}),x&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`dag-status-bar ${I?"active":""}`,children:[s.jsxs("div",{className:"dag-pipeline-name",children:[I&&s.jsx("span",{className:"dag-live-dot"}),T||"Execution Pipeline"]}),s.jsxs("div",{className:"dag-pipeline-meta",children:[I&&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"]}),z>0&&s.jsxs("span",{className:"dag-running-badge",children:["▶ ",z," running"]}),O>0&&s.jsxs("span",{className:"dag-pending-badge",children:["⏳ ",O," pending"]}),s.jsxs("span",{className:"dag-completed-badge",children:["✅ ",D," done"]}),U>0&&s.jsxs("span",{className:"dag-failed-badge",children:["❌ ",U," failed"]})]})]}),s.jsx("div",{className:"dag-container",children:s.jsxs("svg",{width:$,height:R,viewBox:`0 0 ${$} ${R}`,children:[s.jsxs("defs",{children:[C.map(L=>s.jsx("marker",{id:`arrow-${L.from}-${L.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-${L.from}-${L.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"})]})]})]}),C.map(L=>{const P=M.find(Y=>Y.id===L.from),ce=M.find(Y=>Y.id===L.to);if(!P||!ce)return null;const we=P.x+P.w,pe=P.y+P.h/2,Pe=ce.x,G=ce.y+ce.h/2,X=(we+Pe)/2,ae=ce.status,le=ae==="failed"?"#f85149":ae==="running"?"#58a6ff":ae==="completed"?"#3fb950":"#30363d";return s.jsx("g",{children:s.jsx("path",{d:`M ${we} ${pe} C ${X} ${pe}, ${X} ${G}, ${Pe} ${G}`,fill:"none",stroke:le,strokeWidth:ae==="pending"?1.5:2.5,strokeOpacity:ae==="pending"?.3:.8,markerEnd:`url(#arrow-${L.from}-${L.to})`,className:"dag-edge"})},`edge-${L.from}-${L.to}`)}),M.map(L=>{const P=Cie[L.status];eg[L.agentType];const ce=o_[L.agentType]||"⚙️",we=tg[L.agentType]||L.agentType,pe=a===L.id,Pe=L.status==="running";return s.jsxs("g",{onClick:()=>o(pe?null:L.id),style:{cursor:"pointer"},className:"dag-node-group",children:[pe&&s.jsx("rect",{x:L.x-4,y:L.y-4,width:L.w+8,height:L.h+8,rx:10,ry:10,fill:"none",stroke:"#58a6ff",strokeWidth:2,strokeOpacity:.5}),s.jsx("rect",{x:L.x,y:L.y,width:L.w,height:L.h,rx:8,ry:8,fill:P.bg,stroke:P.stroke,strokeWidth:Pe?2.5:1.5,strokeOpacity:.9,className:Pe?"dag-node-running":"",filter:Pe?"url(#glow)":void 0}),s.jsxs("text",{x:L.x+10,y:L.y+22,fill:"#e6edf3",fontSize:10,fontWeight:600,children:[ce," ",we]}),s.jsx("text",{x:L.x+L.w-10,y:L.y+22,textAnchor:"end",fill:P.text,fontSize:9,fontWeight:500,children:l_[L.status]}),s.jsx("text",{x:L.x+10,y:L.y+40,fill:"#8b949e",fontSize:9,children:L.description.length>28?L.description.slice(0,26)+"..":L.description}),L.complexity&&Ms[L.complexity]&&s.jsxs("text",{x:L.x+10,y:L.y+54,fill:Ms[L.complexity].color,fontSize:8,fontWeight:600,children:[Ms[L.complexity].icon," ",L.complexity]}),s.jsx("text",{x:L.x+10,y:L.y+56,fill:"#6e7681",fontSize:8,children:ng(L.startedAt,L.completedAt)}),s.jsx("text",{x:L.x+L.w-10,y:L.y+56,textAnchor:"end",fill:"#6e7681",fontSize:8,children:c_(L.startedAt||L.completedAt)}),(L.status==="failed"||pe)&&L.summary&&s.jsx("foreignObject",{x:Math.max(10,L.x-80),y:L.y+L.h+6,width:L.w+160,height:36,children:s.jsx("div",{className:"dag-node-summary",style:{color:L.status==="failed"?"#f85149":"#8b949e",fontSize:"10px",lineHeight:1.4,background:"rgba(13,17,23,0.9)",padding:"4px 8px",borderRadius:"4px",border:`1px solid ${L.status==="failed"?"rgba(248,81,73,0.3)":"rgba(48,54,61,0.5)"}`,maxHeight:"32px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:L.summary})})]},`node-${L.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:M.map(L=>s.jsxs("tr",{className:`dag-row dag-row-${L.status}`,children:[s.jsx("td",{className:"dag-cell-step",children:L.step}),s.jsxs("td",{className:"dag-cell-agent",children:[s.jsx("span",{className:"dag-agent-dot",style:{background:eg[L.agentType]||"#58a6ff"}}),tg[L.agentType]||L.agentType]}),s.jsx("td",{className:"dag-cell-complexity",children:L.complexity&&Ms[L.complexity]?s.jsxs("span",{style:{color:Ms[L.complexity].color,fontSize:12},children:[Ms[L.complexity].icon," ",L.complexity]}):s.jsx("span",{style:{color:"#6e7681",fontSize:12},children:"—"})}),s.jsx("td",{className:`dag-cell-status dag-status-${L.status}`,children:l_[L.status]}),s.jsx("td",{className:"dag-cell-duration",children:ng(L.startedAt,L.completedAt)}),s.jsx("td",{className:"dag-cell-time",children:c_(L.startedAt||L.completedAt)}),s.jsx("td",{className:"dag-cell-summary",children:L.summary||L.description||"--"})]},L.id))})]})}),s.jsx("h3",{className:"section-subtitle",children:"Agent Types"}),s.jsxs("div",{className:"dag-legend",children:[Object.entries(o_).map(([L,P])=>s.jsxs("div",{className:"legend-item",children:[s.jsx("span",{className:"legend-dot",style:{background:eg[L]||"#58a6ff"}}),s.jsx("span",{className:"legend-icon",children:P}),s.jsx("span",{className:"legend-label",children:tg[L]||L})]},L)),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 Rs(e){return e==null||e<1e-5?"$0.00":e<.01?"$"+e.toFixed(6):"$"+e.toFixed(4)}function Ll(e){return e==null?"0":e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}function Rie(e){return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Iie({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:Rs(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:Ll(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:Ll(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:Rs(t.measuredCost)}),s.jsxs("span",{className:"cost-label",children:[Ll(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:Rs(t.estimatedCost)}),s.jsxs("span",{className:"cost-label",children:[Ll(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:Rs(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:Rs(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:Rie(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:Rs(a.costUsd)}),s.jsxs("span",{className:"request-tokens",children:[Ll(a.totalTokens)," tok"]})]},o))})]})}function $ie(e){return e==null?"$0.00":"$"+e.toFixed(6)}function md(e){return e==null?"0%":(e*100).toFixed(1)+"%"}function Lie({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:md(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:$ie(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($a,{width:"100%",height:260,children:s.jsxs(La,{data:c,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(qi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Wr,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(Hr,{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(Mc,{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($a,{width:"100%",height:260,children:s.jsxs(La,{data:c,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(qi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Wr,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(Hr,{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($a,{width:"100%",height:260,children:s.jsxs(La,{data:c,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(qi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Wr,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(Hr,{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:md(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:md(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:md(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($a,{width:"100%",height:260,children:s.jsxs(La,{data:l,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(qi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Wr,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(Hr,{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(Mc,{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($a,{width:"100%",height:260,children:s.jsxs(La,{data:l,margin:{top:20,right:20,left:10,bottom:40},children:[s.jsx(qi,{strokeDasharray:"3 3",stroke:"#21262d"}),s.jsx(Wr,{dataKey:"name",tick:{fill:"#8b949e",fontSize:11},axisLine:{stroke:"#30363d"}}),s.jsx(Hr,{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(Ya,{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 rg(e){return e==null?"0":e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}function Die({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:rg(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:[rg(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:[rg(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 Bie=new Set(["local","lmstudio","vllm"]),zie=new Set([]),yh={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"}},Fie=[3,4,5],JP=12e3,u_=[300,700],Uie=6e4,Wie=5e3;function Hie(e){return new Promise(t=>setTimeout(t,e))}async function eM(e,t){const n=new AbortController,r=setTimeout(()=>n.abort(),t);try{return await fetch(e,{signal:n.signal})}finally{clearTimeout(r)}}function tM(e){return e instanceof TypeError||e instanceof Error&&e.name==="AbortError"}async function Gie(e){let t=null,n=!1;for(let r=0;;r++){try{const i=await eM("/api/models",JP);if(!i.ok)t=i.status;else{const a=await si(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(!tM(i))throw i;n=!0,e==null||e()}if(r>=u_.length)throw new Error(n?"Dashboard server unreachable — is it still running? Retrying automatically…":`Model health endpoint failed (HTTP ${t})`);await Hie(u_[r])}}async function qie(e){for(let t=0;;t++)try{const n=await eM("/api/model-registry",JP);return n.ok?await si(n):null}catch(n){if(!tM(n)||t>=1)return null;e==null||e()}}function Kie(e){return e==="available"?"Available":e==="limited"?"Limited":"Unavailable"}function Vie(e){return e==="available"?"Ready":e==="limited"?"Limited":"Down"}function nM(e){return{local:"💻",groq:"🟢",nim:"🔶",gemini:"🔷",openrouter:"🟣",openai:"🤖",anthropic:"🔮",mistral:"🌀",cohere:"🧠",together:"🟢",deepinfra:"🌐",fireworks:"🎆",perplexity:"❓",azure:"🔵",anyscale:"🔷",lmstudio:"🎨",vllm:"⚡"}[e]||"🔌"}function f0(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 d_({status:e,label:t}){const n=yh[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 Yie({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 Xie({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 gd({provider:e}){const[t,n]=E.useState(!1),r=yh[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(d_,{status:e.overallStatus,label:Kie(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:yh[a.status].dot,marginRight:8}}),a.name]}),s.jsx("td",{style:{padding:"8px 12px"},children:s.jsx(d_,{status:a.status,label:Vie(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 rM(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 Zie(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 Qie({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 Jie({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 eae({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 tae({entry:e}){const t=Zie(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(Qie,{rate:e.partialRate??0}),e.partialHistory&&e.partialHistory.length>=2&&s.jsx(eae,{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(Jie,{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?rM(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 nae({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:nM(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:f0(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(tae,{entry:i},i.model))})]})})]})}function rae(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 iae({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"})]})]})]}),rae(e.keyHygiene),e.providers.map(t=>s.jsx(nae,{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 aae={chat:"💬",execute:"⚙️",plan:"🗺️",edit:"✏️",skill:"🧩",learn:"📚",ci:"🔁",doctor:"🩺",probe:"🔭","spot-check":"🧪",telemetry:"📡",usage:"🧮"};function sae(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 oae(e){return aae[e]||"🎯"}function lae(e){return e?new Date(e).toLocaleDateString()+" "+new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"—"}function qa({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 cae(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 uae(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 dae({timeline:e}){const[t,n]=E.useState(()=>uae(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?cae(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(qa,{provider:m.provider,model:m.model,reason:m.errorType,killed:!0},`${m.provider}|${m.model}|${m.outcome}`):m.outcome==="verified"?s.jsx(qa,{provider:m.provider,model:m.model},`${m.provider}|${m.model}|${m.outcome}`):m.outcome==="partial"?s.jsx(qa,{provider:m.provider,model:m.model,reason:m.errorType,partial:!0,streamedChunks:m.streamedChunks},`${m.provider}|${m.model}|${m.outcome}`):s.jsx(qa,{provider:m.provider,model:m.model,reason:m.errorType,transient:!0},`${m.provider}|${m.model}|${m.outcome}`))})]})]})}function fae({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:oae(e.action)}),s.jsxs("div",{style:{flex:1},children:[s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"#e6edf3",marginBottom:2},children:sae(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(qa,{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(qa,{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(qa,{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(dae,{timeline:e.timeline})]})]})}function hae({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:lae(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(fae,{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 yd({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 pae({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 mae({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:"}),Fie.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 gae({model:e,provider:t}){const n=yh[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:[nM(t)," ",f0(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 ",rM(e.resetsInMs)]})]})})}function yae({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)||f0(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(gae,{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 vae(){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-documentation/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 bae(){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 xae(){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()},Wie)}async function v(){a(!0),l(null),g.current=!1;try{const[b,x]=await Promise.all([Gie(()=>{g.current=!0}),qie(()=>{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,Uie);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)zie.has(N.provider)?S.push(N):Bie.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(Yie,{onRefresh:v,loading:i}),s.jsx(bae,{}),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(Xie,{data:e}),(()=>{const{available:b,local:x,speech:k,unavailable:S}=y(e);return s.jsxs(s.Fragment,{children:[s.jsx(yd,{icon:"✅",title:"Available Cloud Providers",count:b.length}),b.map(w=>s.jsx(gd,{provider:w},w.provider)),s.jsx(yd,{icon:"🏠",title:"Local Providers",count:x.length}),x.map(w=>s.jsx(gd,{provider:w},w.provider)),s.jsx(yd,{icon:"⛔",title:"Unavailable Providers",count:S.length}),S.map(w=>s.jsx(gd,{provider:w},w.provider)),s.jsx(yd,{icon:"🎙️",title:"Speech / TTS Providers",count:k.length}),k.map(w=>s.jsx(gd,{provider:w},w.provider))]})})(),s.jsx(pae,{value:d,onChange:f,totalCount:e.providers.reduce((b,x)=>b+x.models.length,0)}),s.jsx(mae,{value:c,onChange:u}),s.jsx(yae,{providers:e.providers,colsPerRow:c,searchQuery:d}),n&&s.jsx(iae,{data:n}),n&&s.jsx(hae,{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(vae,{}),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 wae={local:"💻",groq:"🟢",nim:"🔶",gemini:"🔷",openrouter:"🟣"},Sae={local:"Ollama (Local)",groq:"Groq",nim:"NVIDIA NIM",gemini:"Gemini",openrouter:"OpenRouter"},kae={trivial:"🟢",simple:"🔵",moderate:"🟡",complex:"🟠",critical:"🔴"},iM={trivial:"🟢 trivial",simple:"🔵 simple",moderate:"🟡 moderate",complex:"🟠 complex",critical:"🔴 critical"},Eae={chat:"💬 chat",orchestrator:"🔀 orchestrator",explain:"🔍 explain",benchmark:"📈 benchmark",eval:"🎯 eval"},ja=[{key:"request",icon:"🎯",title:"Request"},{key:"candidates",icon:"⚖️",title:"Candidates"},{key:"exclusions",icon:"🚫",title:"Exclusions"},{key:"pick",icon:"✅",title:"Pick"}],_ae=2400;function ig(e){return wae[e]||"🔌"}function f_(e){return Sae[e]||e}function h0(e){return e&&Eae[e]||e||"unknown"}function Nae(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 h_(e){const t=Math.ceil(e/6e4);return t>=60?`${Math.floor(t/60)}h ${t%60}m`:`${t}m`}const jae=8;function p_(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 ${h_(r.resetsInMs)}`:"quota exhausted — parked":r&&r.cooldownRemaining>0?`circuit-breaker cooldown — ${h_(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 Aae(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,jae)){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:p_(g,e)})),p=(o=d.find(g=>g.provider===c.provider))==null?void 0:o.reason;r.push({id:c.id,label:`${h0(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:p_(g,e)})),p=u[0];r.push({id:`profile-${c.complexity}`,label:`${iM[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 Tae(e,t){switch(e){case"request":return`A ${t.complexity} task arrives${t.source?` from ${h0(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 Cae({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 Oae({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 Pae({routing:e}){const t=E.useMemo(()=>Aae(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)%ja.length)},_ae);return()=>clearInterval(p)},[o,t.length]),t.length===0)return null;const c=t.find(p=>p.id===n)??t[0],u=ja[i],d=()=>{a(p=>(p+ja.length-1)%ja.length),l(!1)},f=()=>{a(p=>(p+1)%ja.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(Oae,{icon:u.icon,title:`${i+1}. ${u.title}${i>0?` — ${c.complexity}`:""}`,narration:Tae(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:[kae[c.complexity]||"•"," ",iM[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:h0(c.source)}),c.timestamp&&s.jsx("span",{style:{fontSize:11,color:"#6e7681",marginLeft:"auto"},children:Nae(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:[ig(p.provider)," ",f_(p.provider).split(" ")[0],m&&" 👑"]}),s.jsx(Cae,{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:[ig(p.provider)," ",f_(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:[ig(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:ag,children:"◀"}),s.jsx("button",{onClick:h,"aria-label":o?"Pause playback":"Play playback",style:{...ag,minWidth:84,color:o?"#d29922":"#3fb950"},children:o?"⏸ Pause":"▶ Play"}),s.jsx("button",{onClick:f,"aria-label":"Next step",style:ag,children:"▶"}),s.jsx("div",{style:{display:"flex",gap:6,marginLeft:8},children:ja.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,"/",ja.length]})]})]})}const ag={background:"#21262d",color:"#e6edf3",border:"1px solid #30363d",borderRadius:8,padding:"6px 12px",fontSize:13,cursor:"pointer",transition:"background 0.15s"},Mae={local:"💻",groq:"🟢",nim:"🔶",gemini:"🔷",openrouter:"🟣"},Rae={local:"Ollama (Local)",groq:"Groq",nim:"NVIDIA NIM",gemini:"Gemini",openrouter:"OpenRouter"},aM={trivial:"🟢",simple:"🔵",moderate:"🟡",complex:"🟠",critical:"🔴"};function Cr(e){return Mae[e]||"🔌"}function ca(e){return Rae[e]||e}function vh(e,t=1){return`${(e*100).toFixed(t)}%`}function Iae(e){return`$${e.toFixed(6)}`}function Zn({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 p0({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 to(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 $ae(){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 Lae={chat:"💬 chat",orchestrator:"🔀 orchestrator",explain:"🔍 explain",benchmark:"📈 benchmark",eval:"🎯 eval"},Dae={trivial:"🟢 trivial",simple:"🔵 simple",moderate:"🟡 moderate",complex:"🟠 complex",critical:"🔴 critical"};function sM(e){return Lae[e]||e}function oM(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 m_(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 Bae({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 zae({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(Zn,{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(Bae,{label:`${Cr(i)} ${ca(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:[sM(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 Fae({history:e}){return e.length?s.jsx(Zn,{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:oM(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:sM(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:[Cr(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:Dae[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 Uae({routing:e}){return e.preference.length?s.jsx(Zn,{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:[aM[t.complexity]||"•"," ",t.complexity]}),s.jsx("td",{style:{padding:"10px 12px",whiteSpace:"nowrap"},children:s.jsxs("span",{style:{color:"#3fb950",fontWeight:600},children:[Cr(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:[Cr(n.provider)," ",ca(n.provider).split(" ")[0]]}),s.jsx(p0,{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:to("#1c2128","#6e7681"),children:["🎯 fit ",n.capabilityFit,"%"]}),n.costSource==="measured"&&n.costBasis?s.jsxs("span",{style:to("#12291a","#3fb950","#3fb950"),children:["📏 measured ",n.costBasis.inputTokens.toLocaleString(),"→",n.costBasis.outputTokens.toLocaleString()," tok"]}):s.jsx("span",{style:to("#1c2128","#8b949e"),children:"📐 estimated"}),n.contextUtilization!==void 0&&n.contextWindowTokens!==void 0&&s.jsxs("span",{style:to("#1c2128","#58a6ff","#58a6ff"),children:["⏳ ctx ",n.contextUtilization,"% (",n.contextWindowTokens.toLocaleString()," tok)"]})]})]},n.provider))})]},t.complexity))})]})})}):null}function Wae({routing:e}){return e.providers.length?s.jsx(Zn,{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:[Cr(t.provider)," ",ca(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(p0,{value:t.avgQuality,color:"#58a6ff"}),s.jsx("span",{style:{fontFamily:"'SFMono-Regular', Consolas, monospace",fontSize:12,color:"#8b949e",width:44,textAlign:"right"},children:vh(t.avgQuality)})]})}),s.jsx("td",{style:{padding:"10px 12px",color:t.passRate>=.8?"#3fb950":"#d29922"},children:vh(t.passRate)}),s.jsx("td",{style:{padding:"10px 12px",fontFamily:"'SFMono-Regular', Consolas, monospace",color:"#8b949e"},children:Iae(t.totalCostUsd)})]},t.provider))})]})})}):null}const g_=["trivial","simple","moderate","complex","critical"];function Hae(e){return e>=.7?"#3fb950":e>=.45?"#d29922":"#f85149"}function Gae({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(Zn,{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"}),g_.map(r=>s.jsxs("th",{style:{padding:"8px 10px",textAlign:"center",fontWeight:500},children:[aM[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:[Cr(r)," ",ca(r).split(" ")[0]]}),g_.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:Hae(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 qae(e,t=1){return`${e>0?"+":""}${(e*100).toFixed(t)}%`}function Kae({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 Vae({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(Zn,{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:qae(i.delta)}),s.jsx("span",{style:{fontSize:11,color:"#6e7681",flex:1},children:i.note}),s.jsx(Kae,{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 Yae({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(Zn,{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:Cr(r.provider)}),s.jsx("span",{style:{fontSize:13,fontWeight:600,color:"#e6edf3"},children:ca(r.provider)}),r.trusted?s.jsxs("span",{style:to("#3fb95026","#238636","#3fb950"),children:["trusted · ",r.samples," samples"]}):s.jsxs("span",{style:to("#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 ",vh(r.winRate,0)]}),s.jsx(p0,{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 Xae({routing:e}){return e.bestModels.length?s.jsx(Zn,{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:[Cr(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:[vh(t.successRate,0)," success"]})," · ",t.runs," run",t.runs!==1?"s":""]})]},`${t.agentType}-${t.model}`))})}):null}function Zae({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(Zn,{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 Qae({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(Zn,{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:[Cr(u.provider)," ",ca(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:m_(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:[Cr(u.provider)," ",ca(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 ",m_(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:[Cr(u.provider)," ",ca(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:oM(u.timestamp)})]},`${u.timestamp}-${d}`)})})]})]})}function Ud({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 Jae({governance:e}){var r,i,a,o,l;if(!e.enabled)return s.jsx(Zn,{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(Zn,{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(Ud,{ok:!c.deny,children:[c.deny?"⛔":"✅"," ",c.label,": ",c.items.join(", ")]},c.label)),n.map(c=>s.jsx(Ud,{children:c},c)),t.length===0&&n.length===0&&s.jsx(Ud,{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 ese({rbac:e}){const t=n=>n==="admin"?"#d29922":n==="operator"?"#3fb950":"#8b949e";return s.jsxs(Zn,{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(Ud,{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 tse({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($ae,{}):s.jsxs(s.Fragment,{children:[a&&t&&s.jsx(Pae,{routing:t}),f&&t.governance&&s.jsx(Jae,{governance:t.governance}),(t==null?void 0:t.rbac)&&s.jsx(ese,{rbac:t.rbac}),r&&s.jsx(zae,{usage:t.usage}),i&&s.jsx(Fae,{history:t.history}),o&&s.jsx(Gae,{bandit:t.bandit}),l&&s.jsx(Vae,{promotion:t.promotion}),c&&t.ml&&s.jsx(Yae,{ml:t.ml}),u&&s.jsx(Qae,{quota:t.quota}),d&&s.jsx(Zae,{retrieval:t.retrieval}),s.jsx(Uae,{routing:t}),s.jsx(Wae,{routing:t}),s.jsx(Xae,{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 y_={chat:"💬",execute:"⚙️",plan:"🗺️",edit:"✏️",skill:"🧩",learn:"📚",ci:"🔁",doctor:"🩺",probe:"🔭","spot-check":"🧪",telemetry:"📡",usage:"🧮","ide-chat":"💬","ide-inline":"✍️","ide-execute":"⚙️"};function nse(e){return new Date(e).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function vd(e){return e!==void 0?`${e}ms`:"—"}function lM(e){return e===0?"#3fb950":e<.2?"#d29922":"#f85149"}function rse({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:lM(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 ise({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(rse,{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:[y_[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:[y_[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:lM(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:vd((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?vd(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?vd(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?vd(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:nse(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 ase={local:"💻",groq:"🟢",nim:"🔶",gemini:"🔷",openrouter:"🟣"},sse={planner:"🗺️",writer:"✍️",reviewer:"🔎",tester:"🧪",debugger:"🐛",runner:"🏃","context-gatherer":"📂",memory:"🧠","self-improver":"📈"};function ose(e){return ase[e]||"🔌"}function lse(e){return sse[e]||"🤖"}function cM(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 m0(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 ac(e){return e==null?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}function cse(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 Vv({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 use(){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 dse({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:lse(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:[ose(e.provider)," ",e.provider,"/",e.model]}),s.jsx("span",{style:{width:70,fontSize:11,color:"#6e7681",textAlign:"right"},children:m0(e.latencyMs)}),s.jsxs("span",{style:{width:86,fontSize:11,color:"#6e7681",fontFamily:"'SFMono-Regular', Consolas, monospace",textAlign:"right"},children:[ac(e.inputTokens),"→",ac(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 (",ac(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 fse({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(Vv,{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:["🕓 ",cM(e.startedAt)]}),(()=>{const l=cse(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:["⏱ ",m0(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:["🧮 ",ac(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(dse,{step:l},l.seq))]})}function hse({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(fse,{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:cM(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:["⏱ ",m0(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:["🧮 ",ac(r.totalTokens)," tok"]}),a&&s.jsxs("span",{children:["🤖 ",a.slice(0,60)]})]})]},r.id)})})}function pse(){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(Vv,{icon:"⏳",title:"Loading…",children:s.jsx("div",{style:{color:"#8b949e",fontSize:13},children:"Fetching reasoning traces…"})}),n&&e===null&&s.jsx(Vv,{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(use,{}),e!==null&&e.length>0&&s.jsx(hse,{traces:e})]})}function sg(e){if(e.trim()==="")return null;const t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function mse({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 I=S.quota[T]||{};w[T]={provider:T,tokens:((_=I.tokensPerWindow)==null?void 0:_.toString())??"",requests:((N=I.requestsPerWindow)==null?void 0:N.toString())??"",windowMs:((C=I.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=sg(N.tokens),I=sg(N.requests),M=sg(N.windowMs);T!==null&&(C.tokensPerWindow=T),I!==null&&(C.requestsPerWindow=I),M!==null&&(C.windowMs=M),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 gse={pass:"✅",warn:"⚠️",fail:"❌"},yse={pass:"PASS",warn:"WARN",fail:"FAIL"},vse={env:"Environment",config:"Config",vault:"Vault",local:"Local (no key)",none:"Not configured"};function v_({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:[gse[e.status]," ",yse[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 bse(){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(!1),[h,p]=E.useState(""),[g,m]=E.useState(""),[v,y]=E.useState(null),[b,x]=E.useState(null),[k,S]=E.useState(""),[w,_]=E.useState(""),[N,C]=E.useState(""),[T,I]=E.useState(null),[M,$]=E.useState(!1),[R,z]=E.useState([]),[D,U]=E.useState(null),[O,F]=E.useState(""),[A,Z]=E.useState(""),[L,P]=E.useState("viewer"),[ce,we]=E.useState([]),[pe,Pe]=E.useState({}),[G,X]=E.useState(null),[ae,le]=E.useState({}),[Y,_e]=E.useState(""),[Ee,je]=E.useState(null),[ve,$e]=E.useState(null),fe=E.useCallback(async()=>{r(!0),a(null);const q=await ee.fetchAdminChecks();t(q),q||a("Could not reach the dashboard server, or the server is older than this panel. Run `buff dashboard` to start it."),r(!1)},[]),vt=E.useCallback(async()=>{const q=await ee.fetchAdminCatalog();q&&q.length>0&&we(q)},[]),Le=E.useCallback(async()=>{const q=await ee.fetchAdminUsers();q.ok&&q.users&&z(q.users)},[]);E.useEffect(()=>{let q=!0;return ee.fetchAdminAuthStatus().then(me=>{if(q){if(!me){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:me.configured,authenticated:me.authenticated}),u(me.authenticated),y(me.role??null),x(me.user??null),f(me.mustChangePassword===!0),me.authenticated?(fe(),vt(),Le()):r(!1)}}),()=>{q=!1}},[fe,vt,Le]);const Ae=v==="admin",He=()=>{u(!1),l(q=>q&&{...q,authenticated:!1}),I("Session expired — log in again.")},Ie=async q=>{q.preventDefault(),$(!0),I(null);const me=await ee.adminLogin(k,w);me.ok?(u(!0),l({configured:!0,authenticated:!0}),y(me.role??"admin"),x(me.user??null),S(""),_(""),ee.fetchAdminAuthStatus().then(Re=>{Re&&f(Re.mustChangePassword===!0)}),fe(),vt(),Le()):I(me.error||"Login failed."),$(!1)},xn=async q=>{if(q.preventDefault(),$(!0),I(null),w.length<8){I("Password must be at least 8 characters."),$(!1);return}if(w!==N){I("Passwords do not match."),$(!1);return}const me=await ee.adminSetup(k,w);me.ok?(u(!0),l({configured:!0,authenticated:!0}),y(me.role??"admin"),x(me.user??null),S(""),_(""),C(""),fe(),vt(),Le()):I(me.error||"Setup failed."),$(!1)},$t=async()=>{await ee.adminLogout(),u(!1),l(q=>q&&{...q,authenticated:!1}),y(null),x(null),t(null),Pe({}),le({}),z([])},W=async()=>{if(!window.confirm("Stop the running gateway? Channels will stop responding until you restart it with `buff gateway start`."))return;$e("gateway"),je(null);const q=await ee.shutdown("gateway");$e(null),q.ok?je(q.stopped?"✅ Gateway stopped.":`ℹ️ ${q.reason||"No running gateway found — nothing to stop."}`):(je(`❌ ${q.error||"Stop failed."}`),q.unauthorized&&He())},V=async()=>{window.confirm("Shut down the dashboard? This page will disconnect and the server will exit. Restart with `buff dashboard`.")&&($e("dashboard"),je("🛑 Shutting down the dashboard — this page will disconnect…"),await ee.shutdown("dashboard"),$e(null),je("ℹ️ The dashboard server did not stop (see the server terminal). You can also stop it with `buff dashboard stop`."))},oe=async q=>{if(q.preventDefault(),U(null),A.length<8){U("Password must be at least 8 characters.");return}const me=await ee.addAdminUser(O,A,L);me.ok?(F(""),Z(""),U("✅ User added"),Le()):(U(`❌ ${me.error||"Failed to add user"}`),me.unauthorized&&He())},he=async q=>{if(!window.confirm(`Remove dashboard user '${q}'?`))return;U(null);const me=await ee.removeAdminUser(q);me.ok?(U(`✅ Removed ${q}`),Le()):(U(`❌ ${me.error||"Failed to remove user"}`),me.unauthorized&&He())},xe=(q,me,Re)=>{Pe(Ce=>({...Ce,[q]:{...Ce[q]||{},[me]:Re}}))},Qe=async q=>{X(q),le({});const me=pe[q]||{},Re=await ee.saveProvider(q,me);Re.ok?(t(Ce=>{if(!Ce)return Ce;const Rr=Ce.providers.some(gr=>gr.type===q)?Ce.providers.map(gr=>gr.type===q&&Re.provider?Re.provider:gr):Re.provider?[...Ce.providers,Re.provider]:Ce.providers;return{...Ce,providers:Rr}}),Pe(Ce=>{const Fn={...Ce};return delete Fn[q],Fn}),le(Ce=>({...Ce,[q]:"✅ Saved"}))):(le(Ce=>({...Ce,[q]:`❌ ${Re.error||"Save failed"}`})),Re.unauthorized&&He()),X(null)},Lt=async q=>{if(!window.confirm(`Remove ${q}'s API key and configuration? This cannot be undone.`))return;X(q),le({});const me=await ee.deleteProvider(q);me.ok?me.envSourced?(t(Re=>Re&&{...Re,providers:Re.providers.map(Ce=>Ce.type===q&&me.provider||Ce)}),le(Re=>({...Re,[q]:`⚠️ Key comes from ${me.envVar?`$${me.envVar}`:"an env var"} — unset it there to remove it (config can't override the env).`}))):(t(Re=>Re&&{...Re,providers:Re.providers.filter(Ce=>Ce.type!==q)}),Pe(Re=>{const Ce={...Re};return delete Ce[q],Ce})):(le(Re=>({...Re,[q]:`❌ ${me.error||"Remove failed"}`})),me.unauthorized&&He()),X(null)},Ct=async q=>{X(q);const me=await ee.testProvider(q);le(Re=>{var Ce;return{...Re,[q]:me.ok?`✅ Connected — ${((Ce=me.models)==null?void 0:Ce.length)??0} model(s) reachable`:`❌ ${me.error||"Connection failed"}`}}),X(null)},An=()=>{Y&&(Pe(q=>({...q,[Y]:{}})),_e(""))};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 q=!o.configured;return s.jsxs("div",{className:"admin-header",children:[s.jsxs("h2",{className:"section-title",children:["🛠️ Admin — ",q?"Set up access":"Log in"]}),s.jsx("p",{className:"admin-subtitle",children:q?"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:q?xn:Ie,children:[s.jsxs("label",{children:[s.jsx("span",{children:"Username"}),s.jsx("input",{type:"text",value:k,onChange:me=>S(me.target.value),autoComplete:"username",placeholder:"admin"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Password"}),s.jsx("input",{type:"password",value:w,onChange:me=>_(me.target.value),autoComplete:q?"new-password":"current-password",placeholder:"••••••••"})]}),q?s.jsxs("label",{children:[s.jsx("span",{children:"Confirm password"}),s.jsx("input",{type:"password",value:N,onChange:me=>C(me.target.value),autoComplete:"new-password",placeholder:"••••••••"})]}):null,T?s.jsx("div",{className:"admin-error",children:T}):null,s.jsx("button",{className:"admin-refresh-btn",type:"submit",disabled:M||!k||!w,children:M?"⏳ …":q?"🔐 Create admin":"🔐 Log in"}),q?s.jsxs("p",{className:"admin-hint",children:["Automation alternative: set ",s.jsx("code",{children:"NUVIRA_DASHBOARD_ADMIN_USER"})," and"," ",s.jsx("code",{children:"NUVIRA_DASHBOARD_ADMIN_PASSWORD"})," in the dashboard's environment."]}):null]})]})}if(d){const q=h.length>0&&h.length<8,me=g.length>0&&g!==h,Re=async Ce=>{if(Ce.preventDefault(),q||me||!h)return;$(!0),I(null);const Fn=await ee.changeAdminPassword(w,h);Fn.ok?(f(!1),_(""),p(""),m(""),fe(),vt(),Le()):I(Fn.error||"Could not change the password."),$(!1)};return s.jsxs("div",{className:"admin-header",children:[s.jsx("h2",{className:"section-title",children:"🔐 Set your own password"}),s.jsxs("p",{className:"admin-subtitle",children:["This dashboard is running on its ",s.jsx("strong",{children:"published default password"}),", so anyone who can reach this port can sign in. Until you replace it, the agent will refuse to save anything — API keys, provider settings, users."]}),s.jsxs("form",{className:"admin-gate-form",onSubmit:Re,children:[s.jsxs("label",{children:[s.jsx("span",{children:"Current password"}),s.jsx("input",{type:"password",value:w,onChange:Ce=>_(Ce.target.value),autoComplete:"current-password",placeholder:"admin"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"New password"}),s.jsx("input",{type:"password",value:h,onChange:Ce=>p(Ce.target.value),autoComplete:"new-password",placeholder:"at least 8 characters"})]}),q?s.jsx("div",{className:"admin-error",children:"Use at least 8 characters."}):null,s.jsxs("label",{children:[s.jsx("span",{children:"Confirm new password"}),s.jsx("input",{type:"password",value:g,onChange:Ce=>m(Ce.target.value),autoComplete:"new-password",placeholder:"repeat it"})]}),me?s.jsx("div",{className:"admin-error",children:"The two passwords do not match."}):null,T?s.jsx("div",{className:"admin-error",children:T}):null,s.jsx("button",{className:"admin-refresh-btn",type:"submit",disabled:M||!w||!h||q||me,children:M?"⏳ …":"🔐 Save new password"})]})]})}const Ot=(e==null?void 0:e.system.filter(q=>q.status==="pass").length)??0,dt=(e==null?void 0:e.system.filter(q=>q.status==="warn").length)??0,Tn=(e==null?void 0:e.system.filter(q=>q.status==="fail").length)??0,Qt=(e==null?void 0:e.enterprise.filter(q=>q.status==="pass").length)??0,ws=(e==null?void 0:e.enterprise.filter(q=>q.status==="warn").length)??0,ka=(e==null?void 0:e.enterprise.filter(q=>q.status==="fail").length)??0,mr=(e==null?void 0:e.providers)??[],Jt=q=>{const me=ce.find(Re=>Re.id===q);return me||{label:q}};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"admin-header",children:[s.jsxs("h2",{className:"section-title",children:["🛠️ Admin — Command Runner & Configuration",b?s.jsxs("span",{className:`admin-role-badge admin-role-${v||"viewer"}`,children:[b," · ",v||"viewer"]}):null]}),s.jsxs("div",{className:"admin-header-actions",children:[s.jsx("button",{className:"admin-refresh-btn",onClick:()=>void fe(),disabled:n,children:n?"⏳ Running checks…":"🔄 Refresh (run all commands)"}),Ae||v==="operator"?s.jsx("button",{className:"admin-logout-btn",onClick:()=>void W(),disabled:ve!==null,title:"Stop the running gateway (buff gateway stop)",children:ve==="gateway"?"⏳ Stopping…":"⏻ Stop gateway"}):null,Ae?s.jsx("button",{className:"admin-logout-btn",onClick:()=>void V(),disabled:ve!==null,title:"Shut down this dashboard server (buff dashboard stop)",children:ve==="dashboard"?"⏳ Stopping…":"🛑 Stop dashboard"}):null,s.jsx("button",{className:"admin-logout-btn",onClick:()=>void $t(),children:"🚪 Log out"})]})]}),Ee?s.jsx("div",{className:"admin-error",children:Ee}):null,Ae?null:s.jsxs("div",{className:"admin-readonly-note",children:["🔒 Your role (",s.jsx("code",{children:v||"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:Ot+Qt}),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:dt+ws}),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:Tn+ka}),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:mr.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(q=>s.jsx(v_,{check:q},q.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(q=>s.jsx(v_,{check:q},q.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:[mr.map(q=>{const me=Jt(q.type),Re=pe[q.type]||{};return s.jsxs("tr",{children:[s.jsxs("td",{className:"admin-provider-type",children:[me.icon?`${me.icon} `:"",me.label,s.jsxs("div",{className:"admin-provider-sub",children:[q.type," · ",vse[q.keySource]||q.keySource]}),q.keySource==="env"?s.jsxs("div",{className:"admin-hint",children:["comes from ",me.envVar||"env var"," — change it there, config can't override it"]}):q.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 ${q.configured?"admin-check-pass":"admin-check-warn"}`,children:q.configured?"✅ Configured":"⚠️ Not configured"})}),s.jsx("td",{children:me.keyless?s.jsx("div",{className:"admin-hint",children:"No key needed (probed)"}):Ae?s.jsx("input",{className:"admin-input admin-key-input",type:"password","aria-label":`${q.type} API key`,placeholder:q.keyMasked||"set a new key…",value:Re.apiKey??"",onChange:Ce=>xe(q.type,"apiKey",Ce.target.value),autoComplete:"new-password"}):s.jsx("div",{className:"admin-hint",children:q.keyMasked||"—"})}),s.jsx("td",{children:Ae?s.jsx("input",{className:"admin-input",type:"text","aria-label":`${q.type} base URL`,placeholder:q.baseUrl||"default endpoint",value:Re.baseUrl??"",onChange:Ce=>xe(q.type,"baseUrl",Ce.target.value)}):s.jsx("div",{className:"admin-hint",children:q.baseUrl?q.baseUrl.replace(/^https?:\/\/(?:[^@/]*@)?/,""):"default endpoint"})}),s.jsx("td",{children:Ae?s.jsx("input",{className:"admin-input",type:"text","aria-label":`${q.type} model`,placeholder:q.model||"default model",value:Re.model??"",onChange:Ce=>xe(q.type,"model",Ce.target.value)}):s.jsx("div",{className:"admin-hint",children:q.model||"default model"})}),s.jsx("td",{children:Ae?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"admin-row-actions",children:[s.jsx("button",{className:"admin-mini-btn",disabled:G===q.type,onClick:()=>void Qe(q.type),children:"💾 Save"}),s.jsx("button",{className:"admin-mini-btn",disabled:G===q.type,title:"Tests the SAVED configuration — save first to test a new key",onClick:()=>void Ct(q.type),children:"🔌 Test"}),s.jsx("button",{className:"admin-mini-btn admin-mini-danger",disabled:G===q.type,onClick:()=>void Lt(q.type),children:"🗑 Remove"})]}),ae[q.type]?s.jsx("div",{className:"admin-row-msg",children:ae[q.type]}):null]}):s.jsx("div",{className:"admin-hint",children:"read-only"})})]},q.type)}),mr.length===0?s.jsx("tr",{children:s.jsx("td",{colSpan:6,className:"admin-empty-cell",children:"No providers configured yet."})}):null]})]})}),Ae&&ce.length>0?s.jsxs("div",{className:"admin-add-provider",children:[s.jsxs("select",{className:"admin-input",value:Y,onChange:q=>_e(q.target.value),children:[s.jsx("option",{value:"",children:"Add a provider…"}),ce.filter(q=>!mr.some(me=>me.type===q.id)).map(q=>s.jsxs("option",{value:q.id,children:[q.icon?`${q.icon} `:"",q.label," (",q.id,")"]},q.id))]}),s.jsx("button",{className:"admin-mini-btn",disabled:!Y,onClick:An,children:"➕ Add"})]}):null,s.jsx(mse,{authed:c,role:v||"viewer"}),Ae?s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"section-subtitle",children:"👥 Dashboard Users (role.manage)"}),s.jsxs("div",{className:"admin-users-list",children:[R.map(q=>s.jsxs("div",{className:"admin-user-row",children:[s.jsx("span",{className:"admin-user-name",children:q.user}),s.jsx("span",{className:`admin-role-badge admin-role-${q.role}`,children:q.role}),s.jsxs("span",{className:"admin-user-since",children:["since ",new Date(q.createdAt).toLocaleDateString()]}),q.user!==b?s.jsx("button",{className:"admin-mini-btn admin-mini-danger",onClick:()=>void he(q.user),children:"🗑 Remove user"}):s.jsx("span",{className:"admin-hint",children:"you"})]},q.user)),R.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:oe,children:[s.jsxs("label",{children:[s.jsx("span",{children:"Username"}),s.jsx("input",{type:"text",value:O,onChange:q=>F(q.target.value),autoComplete:"off"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Password (min 8 chars)"}),s.jsx("input",{type:"password",value:A,onChange:q=>Z(q.target.value),autoComplete:"new-password"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Role"}),s.jsxs("select",{value:L,onChange:q=>P(q.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"})]})]}),D?s.jsx("div",{className:"admin-row-msg",children:D}):null,s.jsx("button",{className:"admin-refresh-btn",type:"submit",disabled:!O||!A,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 uM(e){return String(e??"").replace(/\d{3,}/g,t=>t.slice(0,2)+"***")}const xse={idle:"Not paired",pairing:"⏳ Pairing…",paired:"✅ Paired",failed:"❌ Pairing failed",cancelled:"⏹ Cancelled",error:"💥 Pairing error"};function wse({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:xse[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?_:uM(_)]})]},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 Sse({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 $=await ee.getPlatformConfigs();S.current&&i($)},[t]);E.useEffect(()=>(w(),()=>{S.current=!1}),[w]);const _=async($,R)=>{c($),d(null);const z=await ee.setPlatformConfig($,R);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 $=>{if(!window.confirm(`Remove ${$} transport config? Tokens will be deleted from ~/.buff/.env.`))return;c($),d(null);const R=await ee.removePlatformConfig($);if(S.current){if(c(null),R.unauthorized||R.forbidden){t(R.error);return}d({kind:R.ok?"ok":"err",text:R.ok?"Removed.":R.error||"Remove failed."}),R.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=$=>{e&&(h($),g(0),v(Object.fromEntries($.envVars.map(R=>[R.varName,R.value]))),k(null))},I=async()=>{if(!f||!e)return;b(!0),k(null);const $=await ee.setPlatformConfig(f.platform,m);if(b(!1),$.unauthorized||$.forbidden){t($.error);return}$.ok?(k({kind:"ok",text:"✅ Token saved! The transport is now active."}),w()):k({kind:"err",text:$.error||"Save failed."})};if(r===null)return s.jsx("div",{className:"empty-state",children:"Loading platform transports…"});const M=f?C[f.platform]:null;return n==="table"?s.jsxs(s.Fragment,{children:[f&&M?s.jsx("div",{className:"wizard-overlay",onClick:()=>h(null),children:s.jsxs("div",{className:"wizard-modal",onClick:$=>$.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:M.steps.map(($,R)=>s.jsx("li",{children:$},R))}),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($=>s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:$.prompt}),s.jsx("input",{type:$.secret?"password":"text",value:m[$.varName]??"",onChange:R=>v(z=>({...z,[$.varName]:R.target.value})),placeholder:$.secret?"••••••••":"value",autoComplete:"off",spellCheck:!1,autoFocus:!0})]},$.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 I(),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:M.postSetup.map(($,R)=>s.jsx("li",{children:$},R))})]}):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($=>s.jsxs(H.Fragment,{children:[s.jsxs("tr",{className:`platform-config-row ${$.configured?"configured":""}`,children:[s.jsxs("td",{className:"platform-config-name",children:[s.jsx("span",{className:"hub-platform-label",children:$.label}),s.jsx("span",{className:"hub-card-id",children:$.platform})]}),s.jsxs("td",{children:[s.jsx("span",{className:`status-dot ${$.configured?"connected":"reconnecting"}`}),s.jsx("span",{className:"platform-config-status-text",children:$.configured?"Active":"Not configured"})]}),s.jsxs("td",{className:"platform-config-actions",children:[$.configured?null:s.jsx("button",{type:"button",className:"wizard-start-btn",onClick:()=>T($),disabled:!e,children:"🚀 Getting Started"}),$.setupUrl?s.jsx("a",{href:$.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===$.platform?null:$.platform),disabled:!e,children:a===$.platform?"▴ Close":$.configured?"✎ Edit":"⚙ Configure"}),$.configured?s.jsx("button",{type:"button",className:"admin-mini-btn contact-delete-btn",onClick:()=>void N($.platform),disabled:!e,children:"🗑️"}):null]}),s.jsx("td",{className:"platform-config-cli",children:s.jsxs("code",{children:["buff gateway setup ",$.platform]})})]}),a===$.platform?s.jsx("tr",{className:"platform-config-expanded",children:s.jsx("td",{colSpan:4,children:s.jsxs("div",{className:"platform-config-form",children:[$.envVars.map(R=>s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:R.prompt}),s.jsx("input",{type:R.secret?"password":"text",value:R.value,readOnly:!0,className:"platform-config-readonly",placeholder:R.secret?"••••••••":"value"})]},R.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]},$.platform))})]})})]}):s.jsxs(s.Fragment,{children:[f&&M?s.jsx("div",{className:"wizard-overlay",onClick:()=>h(null),children:s.jsxs("div",{className:"wizard-modal",onClick:$=>$.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:M.steps.map(($,R)=>s.jsx("li",{children:$},R))}),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($=>s.jsxs("label",{className:"hub-send-target",children:[s.jsx("span",{className:"admin-hint",children:$.prompt}),s.jsx("input",{type:$.secret?"password":"text",value:m[$.varName]??"",onChange:R=>v(z=>({...z,[$.varName]:R.target.value})),placeholder:$.secret?"••••••••":"value",autoComplete:"off",spellCheck:!1,autoFocus:!0})]},$.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 I(),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:M.postSetup.map(($,R)=>s.jsx("li",{children:$},R))})]}):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($=>s.jsx(kse,{entry:$,canWrite:e,busy:l===$.platform,expanded:a===$.platform,onToggle:()=>o(a===$.platform?null:$.platform),onSave:R=>void _($.platform,R),onRemove:()=>void N($.platform),onStartWizard:()=>T($)},$.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 kse(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 Ese=[{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:"🧠"}],_se={pending:"⏳ pending",sent:"✅ sent",failed:"❌ failed"};function Nse(){var W0,H0,G0,q0,K0,V0,Y0,X0,Z0;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,I]=E.useState(null),[M,$]=E.useState(null),[R,z]=E.useState({}),[D,U]=E.useState(""),[O,F]=E.useState(""),[A,Z]=E.useState(!1),[L,P]=E.useState(null),[ce,we]=E.useState(!1),[pe,Pe]=E.useState({}),[G,X]=E.useState(!1),[ae,le]=E.useState(null),[Y,_e]=E.useState({}),[Ee,je]=E.useState({}),[ve,$e]=E.useState({}),[fe,vt]=E.useState(!1),[Le,Ae]=E.useState(null),[He,Ie]=E.useState(""),[xn,$t]=E.useState(null),[W,V]=E.useState(!1),[oe,he]=E.useState(new Map),[xe,Qe]=E.useState(new Set),[Lt,Ct]=E.useState(!1),[An,Ot]=E.useState([]),[dt,Tn]=E.useState(""),[Qt,ws]=E.useState(null),[ka,mr]=E.useState(""),[Jt,q]=E.useState([]),[me,Re]=E.useState(0),[Ce,Fn]=E.useState(0),[Rr,gr]=E.useState(!0),[Fe,Ss]=E.useState(!1),[ei,Ht]=E.useState(!1),Ci=20,Oi=E.useRef(null),Pi=E.useCallback(async(j=!1)=>{if(Fe)return;const K=j?0:Ce;Ss(!0);try{const ne=await ee.fetchGatewayConversations({offset:K,limit:Ci,q:He||void 0});ne.ok&&ne.conversations&&(q(re=>j?ne.conversations:[...re,...ne.conversations]),Re(ne.total??0),Fn(K+ne.conversations.length),gr(ne.hasMore??!1))}catch{}Ss(!1)},[Fe,Ce,He]);E.useEffect(()=>{e==="conversations"&&!ei&&!Fe&&(Ht(!0),Pi(!0))},[e,ei,Fe,Pi]),E.useEffect(()=>{const j=Oi.current;if(!j)return;const K=new IntersectionObserver(ne=>{var re;(re=ne[0])!=null&&re.isIntersecting&&Rr&&!Fe&&Pi(!1)},{threshold:.1});return K.observe(j),()=>K.disconnect()},[Rr,Fe,Pi]),E.useEffect(()=>{const j=setTimeout(()=>{e==="conversations"&&ei&&(q([]),Fn(0),gr(!0),Pi(!0))},300);return()=>clearTimeout(j)},[He]),E.useEffect(()=>ee.onTypingEvent(K=>{he(ne=>{const re=new Map(ne),de=`${K.platform}:${K.channelId}`;return K.typing?re.set(de,{platform:K.platform,channelId:K.channelId,startedAt:Date.now()}):re.delete(de),re})}),[]);const Fp=E.useCallback((j,K)=>{K.stopPropagation(),Qe(ne=>{const re=new Set(ne);return re.has(j)?re.delete(j):re.add(j),re})},[]),ul=E.useCallback(()=>{Qe(j=>j.size===Jt.length?new Set:new Set(Jt.map(K=>K.key)))},[Jt]),ks=E.useCallback(async()=>{if(xe.size!==0){Ct(!0);try{await ee.exportGatewayConversations([...xe])}catch{}Ct(!1)}},[xe]);E.useEffect(()=>{e==="conversations"&&ee.getAllConversationTags().then(j=>{j.ok&&j.tags&&Ot(j.tags)})},[e]);const Up=E.useCallback(async(j,K)=>{if(!K.trim())return;(await ee.addConversationTag(j,K.trim())).ok&&(q(re=>re.map(de=>de.key===j?{...de,tags:[...de.tags??[],K.trim().toLowerCase()]}:de)),Ot(re=>re.includes(K.trim().toLowerCase())?re:[...re,K.trim().toLowerCase()].sort())),ws(null),mr("")},[]),Ou=E.useCallback(async(j,K)=>{(await ee.removeConversationTag(j,K)).ok&&q(re=>re.map(de=>de.key===j?{...de,tags:(de.tags??[]).filter(Oe=>Oe!==K)}:de))},[]),Wp=E.useCallback((j,K)=>{K.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 be=ht.role==="user"?ne:"Agent",Nt=new Date(ht.ts).toLocaleString();re.push(`[${Nt}] ${be}:`),re.push(ht.content),re.push("")}const de=new Blob([re.join(`
|
|
135
135
|
`)],{type:"text/plain;charset=utf-8"}),Oe=URL.createObjectURL(de),it=document.createElement("a");it.href=Oe,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(Oe)},[]),Hp=E.useCallback((j,K)=>{K.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 jge(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:Ige[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(z0,{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=YN(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 ZN({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 zge({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 Fge({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 Uge(e){return e==="done"?"✅":e==="running"?"🔄":e==="blocked"?"⛔":"⬜"}function QN({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:Uge(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 JN({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:Rge(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 _g(){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 Wge(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 ej(){var Ru,Iu,$u,Ii,Lu;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,I]=E.useState(null),M=E.useRef([]),$=E.useRef([]),R=E.useRef(null),z=E.useRef(null),D=E.useRef(null),[U,O]=E.useState(""),F=E.useRef(""),A=E.useRef(null),[Z,L]=E.useState(null),P=E.useRef(_g()),ce=E.useRef(""),[we,pe]=E.useState([]),[Pe,G]=E.useState(!0),[X,ae]=E.useState(""),[le,Y]=E.useState(null),[_e,Ee]=E.useState(""),[je,ve]=E.useState([]),[$e,fe]=E.useState(null),[vt,Le]=E.useState(!1),Ae=E.useRef(null),He=E.useRef(null),[Ie,xn]=E.useState(null),[$t,W]=E.useState(null),[V,oe]=E.useState([]),[he,xe]=E.useState(""),[Qe,Lt]=E.useState(""),[Ct,An]=E.useState(!1),[Ot,dt]=E.useState(""),[Tn,Qt]=E.useState([]),[ws,ka]=E.useState(null),[mr,Jt]=E.useState(!1),[q,me]=E.useState([]),[Re,Ce]=E.useState([]),[Fn,Rr]=E.useState(""),gr=E.useRef(null),Fe=E.useRef(null),Ss=E.useRef(null),ei=E.useRef(null),[Ht,Ci]=E.useState(null),[Oi,Pi]=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=Ss.current)==null?void 0:B.scrollTo)==null||te.call(B,{top:Ss.current.scrollHeight})}catch{}},[n,o,h]),E.useEffect(()=>()=>{var B;(B=Fe.current)==null||B.call(Fe),Fe.current=null},[]);const Fp=E.useCallback(async B=>{var ke,ri;(ke=Fe.current)==null||ke.call(Fe),Fe.current=null;const te=await ee.getChatSession(B);if(!te)return;P.current=B,r(te.turns.map(qt=>({role:qt.role,content:qt.content,...qt.role==="assistant"?{followups:[],artifacts:VN(qt.content)}:{}}))),p([]),M.current=[],m([]),$.current=[],y(null),R.current=null,x(null),z.current=null,S(null),D.current=null,F.current="",O(""),L(null),u(""),f(null),I(null),Ci(null),G(!0);const J=te.projectPath;if(J){if(W(J),(Ie==null?void 0:Ie.path)===J)return;(ri=ei.current)==null||ri.call(ei,J)}else W(null)},[Ie]),ul=E.useCallback(()=>{var B;(B=Fe.current)==null||B.call(Fe),Fe.current=null,P.current=_g(),W(null),r([]),p([]),M.current=[],m([]),$.current=[],y(null),R.current=null,x(null),z.current=null,S(null),D.current=null,F.current="",O(""),L(null),u(""),f(null),I(null),Ci(null),ve([]),fe(null),a(""),G(!0)},[]),ks=E.useCallback(B=>{ve(te=>[...te,B].slice(-10))},[]),Up=E.useCallback(B=>{ve(te=>te.filter((J,ke)=>ke!==B))},[]),Ou=E.useCallback(async B=>{if(!B)return;if(B.size>XN){u(`Attachment "${B.name}" is too large (max ${Math.round(XN/1024)} KB).`);return}const te=await B.text();ks({name:B.name,content:te,kind:"file"})},[ks]),Wp=E.useCallback(B=>{const te=B.currentTarget,J=B.clipboardData.getData("text")||"";J.length>=Mge&&(He.current={start:te.selectionStart,end:te.selectionEnd},fe({text:J}))},[]),Hp=E.useCallback(()=>{const B=$e;if(!B)return;const te=He.current;a(J=>te?J.slice(0,te.start)+J.slice(te.end):J),ks({name:"pasted-text.txt",content:B.text,kind:"paste"}),fe(null),He.current=null},[$e,ks]),dl=E.useCallback(B=>{Y(B.id),Ee(B.title==="(untitled conversation)"?"":B.title)},[]),Pu=E.useCallback(async B=>{const te=await ee.renameChatSession(B,_e);te.ok?pe(J=>J.map(ke=>ke.id===B?{...ke,title:_e.trim()||ke.title}:ke)):u(te.error||"Could not rename the session."),Y(null),Ee("")},[_e]),Mu=E.useCallback(async B=>{const te=await ee.deleteChatSession(B);te.ok?(pe(J=>J.filter(ke=>ke.id!==B)),P.current===B&&ul()):u(te.error||"Could not delete the session.")},[ul]),fl=(e==null?void 0:e.authenticated)===!0&&(e.role==="admin"||e.role==="operator");E.useEffect(()=>{fl&&(ee.listChatSessions().then(B=>{Array.isArray(B)&&pe(B)}),ee.listProjects().then(B=>{Array.isArray(B)&&oe(B)}))},[fl]);const yr=E.useCallback(async B=>{const te=B.trim();if(!te)return;Lt("");const J=await ee.attachProject(te);if(J.ok&&J.project){xn(J.project),xe("");const ke=await ee.listProjects();Array.isArray(ke)&&oe(ke)}else Lt(J.error||"Could not attach that directory.")},[]);ei.current=yr;const Es=E.useCallback(async B=>{An(!0),Jt(!0),Rr("");const te=await ee.browseDirectories(B,{showDrives:!B});te.ok&&(dt(te.path),Qt(te.entries),ka(te.parent),te.drives&&me(te.drives),te.breadcrumbs&&Ce(te.breadcrumbs)),Jt(!1)},[]),Ea=E.useCallback(async B=>{Jt(!0),Rr("");const te=await ee.browseDirectories(B);te.ok&&(dt(te.path),Qt(te.entries),ka(te.parent),te.breadcrumbs&&Ce(te.breadcrumbs)),Jt(!1)},[]),_s=E.useCallback(async()=>{if(!Ot)return;const B=await ee.browseDirectories(Ot);B.ok&&Qt(B.entries)},[Ot]);E.useEffect(()=>ee.onChatRetryEvent(te=>{if(te.sessionId!==P.current){ee.listChatSessions().then(J=>{Array.isArray(J)&&pe(J)});return}r(J=>[...J,{role:"assistant",content:te.content}]),te.kind==="answer"&&L(null)}),[]),E.useEffect(()=>(Ct&&Ot&&(gr.current=setInterval(()=>{_s()},5e3)),()=>{gr.current&&clearInterval(gr.current)}),[Ct,Ot,_s]);const hl=E.useCallback(async()=>{if(typeof window<"u"&&"showDirectoryPicker"in window)try{const J=(await window.showDirectoryPicker({mode:"read"})).name;if(!J){Es();return}Lt(""),l(!0);const ke=await ee.resolveFolder(J);l(!1),ke.ok&&ke.path?(xe(ke.path),yr(ke.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}Es()},[Es,yr]),Je=E.useCallback(async(B,te)=>{var vr,On;const J=B.trim(),ke=Array.isArray(te)?te:je,ri=!Array.isArray(te)&&(te==null?void 0:te.skipResolve)===!0;if(!J&&ke.length===0||o)return;if(u(""),f(null),p([]),M.current=[],m([]),$.current=[],y(null),R.current=null,x(null),z.current=null,S(null),D.current=null,r(Se=>[...Se,{role:"user",content:J,attachments:ke.length>0?ke:void 0}]),a(""),ve([]),fe(null),ce.current=J||`[${ke.length} attachment(s)]`,l(!0),G(!1),!ri){const ft=((await ee.chatResolve(J)).matches??[])[0]??null;if(ft&&ft.command&&!ft.ambiguous&&ft.score>=.6){I({ask:J,top:ft}),l(!1);return}if(ft&&ft.ambiguous&&!T){I({ask:J,top:ft}),l(!1);return}}const qt=P.current,Cn=new AbortController;A.current=Cn,L(null),(vr=Fe.current)==null||vr.call(Fe),Fe.current=ee.subscribeChat(qt,{onToken:Se=>{F.current+=Se,O(F.current)},onProgress:Se=>{M.current=[...M.current,Se],p(M.current)},onQuestion:Se=>{Ci(Se),Pi(new Set)},onTool:Se=>{const Ue=[...$.current],ft=Ue.findIndex(on=>on.id===Se.id),wt={id:Se.id,tool:Se.tool,phase:Se.phase,args:Se.args,ok:Se.ok,result:Se.result,error:Se.error,durationMs:Se.durationMs};ft>=0?Ue[ft]=wt:Ue.push(wt),$.current=Ue,m(Ue)},onPlan:Se=>{const Ue={goal:Se.goal,steps:Se.steps,revision:Se.revision};R.current=Ue,y(Ue)},onDiff:Se=>{const Ue={files:Se.files,summary:Se.summary};z.current=Ue,x(Ue)},onSkillDraft:Se=>{const Ue={name:Se.name,description:Se.description,markdown:Se.markdown,updatedAt:Se.updatedAt,status:"pending"};D.current=Ue,S(Ue)},onSecretRequest:Se=>{_(Ue=>{const ft=Ue.findIndex(wt=>wt.skillName===Se.skillName);if(ft>=0){const wt=[...Ue];return wt[ft]=Se,wt}return[...Ue,Se]})},onExecutionResult:Se=>{C(Ue=>[...Ue,Se])}});const en=await ee.chatSend(qt,J||`(see ${ke.length} attachment${ke.length===1?"":"s"})`,{projectPath:Ie==null?void 0:Ie.path,attachments:ke.map(Se=>({name:Se.name,content:Se.content,kind:Se.kind}))},Cn.signal);if(A.current=null,(On=Fe.current)==null||On.call(Fe),Fe.current=null,F.current="",O(""),en.ok){f(en.generationFailed?null:`${en.provider??"provider"}${en.model?` / ${en.model}`:" (auto-routed)"}`),L(en.generationFailed&&!en.retryQueued?J:null);const Se=en.content||"(the agent produced no text — try rephrasing)";r(Ue=>[...Ue,{role:"assistant",content:Se,error:en.generationFailed,followups:en.followups,steps:M.current,tools:$.current,plan:R.current,diff:z.current,draft:D.current,artifacts:VN(Se)}])}else Cn.signal.aborted?(u(""),L(null)):en.unauthorized?(t(Se=>Se&&{...Se,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."),L(J));l(!1),G(!0)},[o,Ie,je]),pl=E.useCallback(()=>{var B;(B=A.current)==null||B.abort()},[]),_a=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.")},[]),ml=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.")},[]),gl=E.useCallback(B=>{Je(`Revise the skill draft "${B}" — improve it per your best judgment and present it again.`)},[Je]),Mi=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(ke=>ke.reason==="provider-credential"?`${ke.name} is a provider credential — set it up as a provider, skills never receive it.`:`${ke.name} was not saved (${ke.reason}).`).join(" "))},[]),yl=E.useCallback(async B=>{const ke=((await ee.chatResolve(B)).matches??[])[0]??null;if(!(ke!=null&&ke.command)){I(null);return}I(null),l(!0);const ri=ke.command.split(/\s+/),qt=await ee.startTask(ri,6e4);if(!qt.ok||!qt.task){u(qt.error||"The command could not be started."),l(!1);return}const Cn=qt.task.id,en={id:Cn,command:ke.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 vr=ft=>r(wt=>wt.map(on=>on.task&&on.task.id===Cn?{...on,task:{...on.task,...ft}}:on));let On=null;On=ee.subscribeTask(Cn,{onLog:ft=>r(wt=>wt.map(on=>on.task&&on.task.id===Cn?{...on,task:{...on.task,logs:[...on.task.logs,ft]}}:on)),onStatus:ft=>{vr({status:ft}),ft!=="running"&&(ee.getTask(Cn).then(wt=>{wt!=null&&wt.task&&vr({exitCode:wt.task.exitCode,durationMs:wt.task.durationMs,logs:wt.task.logs??[]})}),On==null||On(),l(!1))}});const Se=await ee.getTask(Cn);Se!=null&&Se.task&&vr({status:Se.task.status,exitCode:Se.task.exitCode,durationMs:Se.task.durationMs,logs:Se.task.logs??[]});const Ue=await ee.getTask(Cn);Ue!=null&&Ue.task&&Ue.task.status!=="running"&&(On==null||On(),vr({status:Ue.task.status,exitCode:Ue.task.exitCode,durationMs:Ue.task.durationMs,logs:Ue.task.logs??[]}),l(!1))},[]),Ri=E.useCallback(B=>{I(null),Je(B,{skipResolve:!0})},[Je]),Ns=E.useCallback(B=>{if(B.length===0)return;const te=Ie?` in the attached project ${Ie.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,Ie]),js=E.useCallback(async B=>{await ee.cancelTask(B)},[]),ti=E.useCallback(async B=>{const te=Ht;if(!te)return;Ci(null);const J=await ee.chatRespond(P.current,te.questionId,B);J.ok||u(J.error||"The question could not be answered — try sending your message again.")},[Ht]),ni=E.useCallback(()=>{if(!Ht)return;const B=Ht.multiSelect?[...Oi]:[...Oi][0];Ht.multiSelect?ti({index:[...Oi]}):ti(B!==void 0?{index:B}:{index:-1})},[Ht,Oi,ti]),Gp=E.useCallback(()=>{Ht&&ti({index:-1})},[Ht,ti]),qp=E.useCallback(B=>{Pi(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]),Ir=E.useCallback(async()=>{var te;(te=Fe.current)==null||te.call(Fe),Fe.current=null,P.current=_g(),r([]),p([]),M.current=[],m([]),$.current=[],y(null),R.current=null,x(null),z.current=null,S(null),D.current=null,F.current="",O(""),L(null),u(""),f(null),I(null),Ci(null);const B=await ee.listChatSessions();Array.isArray(B)&&pe(B)},[]),Gt=((Ru=[...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:Ru.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 Ir(),disabled:o||n.length===0,children:"🗑 New conversation"})]})]}),e!=null&&e.authenticated?fl?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"chat-project-bar",children:Ie?s.jsxs("div",{className:"chat-project-attached",children:[s.jsx("span",{className:"chat-project-icon",children:"📁"}),s.jsx("span",{className:"chat-project-name",children:Ie.name}),s.jsxs("span",{className:"chat-project-meta",children:[Ie.fileCount," files · ",Ie.symbolCount," symbols",Ie.truncated?" · truncated map":""]}),s.jsx("span",{className:"chat-project-path",title:Ie.path,children:Ie.path}),s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>xn(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 yr(B.path),children:B.name},B.path))}):null,s.jsx("input",{className:"chat-project-input",value:he,onChange:B=>xe(B.target.value),onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),yr(he))},placeholder:"or type a path, e.g. ~/code/my-app",disabled:o}),s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void yr(he),disabled:o||!he.trim(),children:"Attach"}),s.jsx("button",{type:"button",className:"admin-mini-btn",onClick:()=>void hl(),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,Ct?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:()=>An(!1),title:"Close",children:"✕"}),s.jsx("div",{className:"chat-browse-breadcrumbs",children:q.length>0&&!Ot?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 Es(),children:"🏠"}),Re.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 Ea(B.path),children:B.name})]},B.path))]})})]}),q.length>0&&!Ot?s.jsx("div",{className:"chat-browse-drives",children:q.map(B=>s.jsx("button",{type:"button",className:"chat-browse-drive",onClick:()=>void Ea(B.path),children:B.name},B.path))}):null,Tn.length>5?s.jsx("div",{className:"chat-browse-search",children:s.jsx("input",{type:"text",className:"chat-browse-filter",placeholder:"🔍 Filter folders…",value:Fn,onChange:B=>Rr(B.target.value),autoFocus:!0})}):null,s.jsx("div",{className:"chat-browse-list",children:mr?s.jsx("span",{className:"admin-hint",children:"Loading…"}):Tn.length===0?s.jsx("span",{className:"admin-hint",children:"No subdirectories found"}):Tn.filter(B=>!Fn||B.name.toLowerCase().includes(Fn.toLowerCase())).map(B=>s.jsxs("button",{type:"button",className:"chat-browse-entry",onClick:()=>void Ea(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 _s(),title:"Refresh folder list",children:"🔄"}),s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>{An(!1),yr(Ot)},disabled:!Ot,children:"📁 Select this folder"})]})]}):null]})}),$t&&(!Ie||Ie.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})]}),Ie?s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void yr($t),children:"📁 Switch to it"}):s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void yr($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:ul,children:"+ New"}),s.jsx("button",{type:"button",className:"chat-mini-action",title:"Collapse history",onClick:()=>G(!1),children:"▸"})]})]}),s.jsx("input",{className:"chat-session-search",placeholder:"Search conversations…",value:X,onChange:B=>ae(B.target.value)}),we.length===0?s.jsx("div",{className:"chat-sidebar-empty",children:"No past conversations yet."}):s.jsx("div",{className:"chat-sidebar-list",children:Wge(we,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===P.current?" chat-session-active":""}`,children:le===J.id?s.jsxs("div",{className:"chat-session-rename",children:[s.jsx("input",{autoFocus:!0,value:_e,onChange:ke=>Ee(ke.target.value),onKeyDown:ke=>{ke.key==="Enter"&&Pu(J.id),ke.key==="Escape"&&Y(null)},placeholder:"Session title"}),s.jsx("button",{type:"button",className:"chat-mini-action",onClick:()=>void Pu(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:()=>dl(J),children:"✏️"}),s.jsx("button",{type:"button",className:"chat-mini-action",title:"Delete",onClick:()=>void Mu(J.id),children:"🗑"})]})]})},J.id))]},B))})]}):s.jsx("div",{className:"chat-rail",children:s.jsx("button",{type:"button",className:"chat-rail-btn",onClick:()=>G(!0),title:"Show history",children:"📁"})}),s.jsxs("div",{className:"chat-main",children:[s.jsxs("div",{className:"chat-thread",ref:Ss,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(HN,{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,ke)=>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})]},ke))]}):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(Td,{diff:B.diff,selectable:!0,onCommitAccepted:Ns})]}):null,B.role==="assistant"&&B.artifacts&&(B.artifacts.diffs.length>0||B.artifacts.results.length>0||B.artifacts.deploys.length>0)?s.jsxs(Dge,{children:[B.artifacts.diffs.map((J,ke)=>s.jsx("div",{"data-artifact-card":!0,tabIndex:0,role:"group","aria-label":`Diff: ${J.summary}`,className:"chat-artifact-item",children:Ie?s.jsx(Td,{diff:J,selectable:!0,onCommitAccepted:Ns}):s.jsx(Td,{diff:J,lockedHint:"Attach a project to review and commit these changes."})},`diff-${ke}`)),B.artifacts.results.map((J,ke)=>s.jsx("div",{"data-artifact-card":!0,tabIndex:0,role:"group","aria-label":`Result: ${J.title}`,className:"chat-artifact-item",children:s.jsx($ge,{result:J})},`result-${ke}`)),B.artifacts.deploys.map((J,ke)=>s.jsx("div",{"data-artifact-card":!0,tabIndex:0,role:"group","aria-label":`Deployment: ${J.url}`,className:"chat-artifact-item",children:s.jsx(Lge,{deploy:J})},`deploy-${ke}`))]}):null,B.role==="assistant"&&B.task?s.jsx(Bge,{task:B.task,onCancel:B.task.status==="running"?()=>void js(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(ZN,{draft:B.draft,onAccept:_a,onReject:ml,onEdit:gl})]}):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(QN,{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(JN,{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,ke)=>s.jsx("div",{children:J.trim()},ke))})]}):null]},te)),o?s.jsxs("div",{className:"chat-bubble chat-assistant",children:[s.jsx("div",{className:"chat-bubble-role",children:"🤖 Agent"}),v?s.jsx(QN,{plan:v}):null,b?s.jsx(Td,{diff:b}):null,k?s.jsx(ZN,{draft:k,onAccept:_a,onReject:ml,onEdit:gl}):null,w.map(B=>s.jsx(zge,{request:B,onSave:Mi},B.skillName)),N.map((B,te)=>s.jsx(Fge,{result:B},`${B.skillName}-${te}`)),s.jsx(JN,{tools:g,live:!0}),U?s.jsx("div",{className:"chat-bubble-text chat-streaming",children:s.jsx(HN,{text:U})}):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,Z&&!o?s.jsxs("div",{className:"chat-retry-row",children:[s.jsx("button",{className:"admin-refresh-btn",type:"button",onClick:()=>void Je(Z),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:(Iu=T.top)!=null&&Iu.ambiguous&&(($u=T.top.options)!=null&&$u.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:()=>{I(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:(Ii=T.top)==null?void 0:Ii.command})}),(Lu=T.top)!=null&&Lu.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 yl(T.ask),children:"▶ Run"}),s.jsx("button",{className:"admin-mini-btn",type:"button",onClick:()=>Ri(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${Oi.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:ni,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${vt?" chat-composer-drag":""}`,onSubmit:B=>{B.preventDefault(),Je(i)},onDragOver:B=>{B.preventDefault(),Le(!0)},onDragLeave:()=>Le(!1),onDrop:B=>{var J;B.preventDefault(),Le(!1);const te=Array.from(((J=B.dataTransfer)==null?void 0:J.files)??[]);for(const ke of te.slice(0,10))Ou(ke)},children:[$e?s.jsxs("div",{className:"chat-paste-offer",children:[s.jsxs("span",{className:"admin-hint",children:["📄 You pasted ",$e.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:()=>{fe(null),He.current=null},children:"Keep inline"})]}):null,je.length>0?s.jsx("div",{className:"chat-attach-row",children:je.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:Ae,type:"file",style:{display:"none"},onChange:B=>{var J;const te=(J=B.target.files)==null?void 0:J[0];te&&Ou(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||je.length>=10,onClick:()=>{var B;return(B=Ae.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===""&&ce.current&&(B.preventDefault(),a(ce.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:pl,children:"⏹ Cancel"}):null,s.jsx("button",{className:"admin-refresh-btn",type:"submit",disabled:o||!i.trim()&&je.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 Hge={running:"⏳ running",done:"✅ done",failed:"❌ failed",cancelled:"⏹ cancelled",timeout:"⏰ timed out",error:"💥 error"};function o2({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(I=>({stream:I.stream,text:I.text}))),(T=y.current)==null||T.call(y),y.current=ee.subscribeTask(N.id,{onLog:I=>m(M=>[...M,{stream:I.stream,text:I.text}]),onStatus:I=>{p(M=>M&&{...M,status:I}),I!=="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:Hge[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 Gge=[{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 tj(e){return typeof e!="number"?"—":`${Math.round(e*100)}%`}function qge(e){return new Date(e).toLocaleString()}function Kge({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(o2,{presets:Gge,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:qge(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:tj(r.summary.completionRate)}),s.jsx("td",{children:tj(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 Vge=[{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 Yge(){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(o2,{presets:Vge,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 Ng={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 Xge(){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 F=Ng[O.platform];y((F==null?void 0:F.testTarget)??""),x("Hello from agent-nuvira!"),_(null)},I=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."}))},M=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),I()):p({kind:"err",text:O.error||"Save failed."})},$=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 R=e.filter(O=>O.configured).length,z=e.filter(O=>n==="configured"?O.configured:n==="unconfigured"?!O.configured:!0),D=i?Ng[i.platform]:null;function U(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:R}),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-R}),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 F=Ng[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:(F==null?void 0:F.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:(F==null?void 0:F.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:U(0),children:"1"}),s.jsx("span",{className:U(1),children:"2"}),s.jsx("span",{className:U(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,F)=>s.jsx("li",{children:O},F))}),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:F=>u(A=>({...A,[O.varName]:F.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 M(),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 $(),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 Zge=[{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)"}],nj=[{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 Qge({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(nj.filter(R=>R.checked).map(R=>R.name)),[_,N]=E.useState(!1),[C,T]=E.useState(null),I=E.useCallback(async()=>{const R=await ee.getBedrockStatus();d.current&&r(R)},[]);E.useEffect(()=>(I(),()=>{d.current=!1}),[I]);const M=async()=>{l(!0),a(null);try{const R=await ee.probeBedrock((n==null?void 0:n.region)||"us-east-1");if(!d.current)return;R.ok&&R.models&&(a(R.models),u("test"))}catch{}finally{d.current&&l(!1)}},$=async()=>{N(!0),T(null);try{const R={BEDROCK_REGION:x};f==="bearer"&&p?R.AWS_BEARER_TOKEN=p:f==="iam"&&(m&&(R.AWS_ACCESS_KEY_ID=m),y&&(R.AWS_SECRET_ACCESS_KEY=y));const z=await ee.setupBedrock(R);if(!d.current)return;z.ok?(T({kind:"ok",text:"✅ Configuration saved! Running connectivity test…"}),u("overview"),await I(),setTimeout(()=>void M(),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 M(),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:R=>g(R.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:R=>v(R.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:R=>b(R.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:R=>k(R.target.value),children:Zge.map(R=>s.jsx("option",{value:R.value,children:R.label},R.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:nj.map(R=>s.jsxs("label",{className:`bedrock-family-card ${S.includes(R.name)?"selected":""}`,children:[s.jsx("input",{type:"checkbox",checked:S.includes(R.name),onChange:z=>{z.target.checked?w(D=>[...D,R.name]):w(D=>D.filter(U=>U!==R.name))}}),s.jsxs("div",{children:[s.jsx("strong",{children:R.name}),s.jsxs("span",{children:[R.models.length," model(s)"]})]})]},R.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 $(),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(R=>s.jsxs("div",{className:`bedrock-probe-card bedrock-probe-${R.status}`,children:[s.jsx("span",{className:"bedrock-probe-icon",children:R.status==="accessible"?"✅":R.status==="permission-denied"?"🔒":R.status==="not-found"?"⚫":"❌"}),s.jsx("span",{className:"bedrock-probe-id",children:R.modelId}),s.jsx("span",{className:"bedrock-probe-status",children:R.status==="accessible"?"Ready":R.status==="permission-denied"?`Need access (HTTP ${R.httpStatus})`:R.status==="not-found"?"Not in this region":"Error"})]},R.modelId))}),i.some(R=>R.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 jg=["whatsapp","whatsapp_cloud","telegram","signal","slack","discord","email"];function Jge(){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,I]=E.useState(!1),[M,$]=E.useState(12e4),R=E.useCallback(async()=>{r(!0);const G=await ee.getContacts();G.ok&&G.contacts&&t(G.contacts);const X=await ee.gatewayPolicies();if(X.ok&&X.policies){const ae={};for(const le of jg){const Y=X.policies[le];Y&&(ae[le]={...Y.outboundSenders!==void 0?{outboundSenders:Y.outboundSenders}:{},...Y.requireApprovedTarget!==void 0?{requireApprovedTarget:Y.requireApprovedTarget}:{}})}m(ae),y(ae)}C(X.askUserWait===!0),I(X.askUserWait===!0),typeof X.askUserTimeoutMs=="number"&&$(X.askUserTimeoutMs),r(!1)},[]);E.useEffect(()=>{R()},[R]);const z=e.filter(G=>i==="all"||G.status===i),D=async G=>{p(null);const X=await ee.approveContact(G.platform,G.name);p(X.ok?{kind:"ok",text:`✅ ${G.name} approved.`}:{kind:"err",text:X.error||"Failed."}),R()},U=async G=>{p(null);const X=await ee.rejectContact(G.platform,G.name);p(X.ok?{kind:"ok",text:`🚫 ${G.name} rejected.`}:{kind:"err",text:X.error||"Failed."}),R()},O=async G=>{p(null);const X=await ee.deleteContact(G.platform,G.name);p(X.ok?{kind:"ok",text:`🗑️ ${G.name} deleted.`}:{kind:"err",text:X.error||"Failed."}),R()},F=async()=>{if(!o)return;p(null);const G=await ee.updateContact(o.platform,o.id,{name:c,phone:d});p(G.ok?{kind:"ok",text:`✅ ${c} updated.`}:{kind:"err",text:G.error||"Failed."}),l(null),R()},A=G=>G==="approved"?s.jsx("span",{className:"contact-status-badge approved",children:"✅ Approved"}):G==="pending"?s.jsx("span",{className:"contact-status-badge pending",children:"⏳ Pending"}):s.jsx("span",{className:"contact-status-badge rejected",children:"🚫 Rejected"}),Z=G=>({telegram:"✈️",whatsapp:"📱",whatsapp_cloud:"📱",email:"📧",slack:"💬",discord:"🎮"})[G]||"🔌",L=G=>G?new Date(G).toLocaleString():"—",P=G=>{const X=(b[G]??"").trim();X&&(m(ae=>{var _e;const le={...ae[G]??{}},Y=le.outboundSenders??((_e=v[G])==null?void 0:_e.outboundSenders)??[];return Y.some(Ee=>Ee.toLowerCase()===X.toLowerCase())||(le.outboundSenders=[...Y,X]),{...ae,[G]:le}}),x(ae=>({...ae,[G]:""})))},ce=(G,X)=>{m(ae=>{var _e;const le={...ae[G]??{}},Y=le.outboundSenders??((_e=v[G])==null?void 0:_e.outboundSenders)??[];return le.outboundSenders=Y.filter(Ee=>Ee.toLowerCase()!==X.toLowerCase()),{...ae,[G]:le}})},we=G=>{m(X=>{const ae={...X[G]??{}};return ae.requireApprovedTarget=ae.requireApprovedTarget!==!0,{...X,[G]:ae}})},pe=G=>{m(X=>{const ae={...X[G]??{}};return delete ae.outboundSenders,{...X,[G]:ae}})},Pe=async()=>{_(!0),S(null);const G={};for(const le of jg){const Y=g[le]??{},_e=v[le]??{};(JSON.stringify(Y.outboundSenders??null)!==JSON.stringify(_e.outboundSenders??null)||!!Y.requireApprovedTarget!=!!_e.requireApprovedTarget)&&(G[le]={...Y.outboundSenders!==void 0?{outboundSenders:Y.outboundSenders}:{outboundSenders:null},requireApprovedTarget:!!Y.requireApprovedTarget})}const X=N!==T;if(Object.keys(G).length===0&&!X){_(!1),S({kind:"ok",text:"No changes to save."});return}const ae=await ee.saveGatewayPolicies(G,void 0,void 0,{wait:N,timeoutMs:M});ae.ok?(S({kind:"ok",text:"✅ Send authority saved."}),R()):S({kind:"err",text:ae.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(G=>s.jsx("button",{type:"button",className:i===G?"platforms-filter-btn active":"platforms-filter-btn",onClick:()=>a(G),children:G==="all"?`All (${e.length})`:G==="approved"?`✅ Approved (${e.filter(X=>X.status==="approved").length})`:G==="pending"?`⏳ Pending (${e.filter(X=>X.status==="pending").length})`:`🚫 Rejected (${e.filter(X=>X.status==="rejected").length})`},G)),s.jsx("button",{type:"button",className:"admin-refresh-btn",onClick:()=>void R(),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(G=>s.jsxs("tr",{className:`contact-row status-${G.status}`,children:[s.jsxs("td",{children:[Z(G.platform)," ",G.platform]}),s.jsx("td",{className:"contact-name",children:G.name}),s.jsx("td",{className:"contact-id",children:s.jsx("code",{children:G.id})}),s.jsx("td",{className:"contact-phone",children:G.phone||"—"}),s.jsx("td",{children:A(G.status)}),s.jsx("td",{className:"contact-date",children:L(G.registeredAt||G.addedAt)}),s.jsxs("td",{className:"contact-actions",children:[G.status!=="approved"&&s.jsx("button",{className:"admin-mini-btn contact-approve-btn",onClick:()=>void D(G),children:"✅ Approve"}),G.status!=="rejected"&&s.jsx("button",{className:"admin-mini-btn contact-reject-btn",onClick:()=>void U(G),children:"🚫 Reject"}),s.jsx("button",{className:"admin-mini-btn",onClick:()=>{l(G),u(G.name),f(G.phone||"")},children:"✏️ Edit"}),s.jsx("button",{className:"admin-mini-btn contact-delete-btn",onClick:()=>void O(G),children:"🗑️"})]})]},`${G.platform}:${G.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:jg.map(G=>{const X=g[G]??{},ae=X.outboundSenders??[],le=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:[Z(G)," ",G]}),le?s.jsx("span",{className:"hub-chip",children:"open"}):s.jsx("span",{className:"hub-chip",children:"restricted"})]}),s.jsx("div",{className:"hub-alias-list",children:le?s.jsx("span",{className:"admin-hint",children:"Open — anyone who can trigger the agent may send to others."}):ae.length===0?s.jsx("span",{className:"admin-hint",children:"(empty — nobody may send to others)"}):ae.map(Y=>s.jsxs("div",{className:"hub-alias-row",children:[s.jsx("span",{className:"hub-chip",children:Y}),s.jsx("button",{className:"admin-refresh-btn",disabled:w,onClick:()=>ce(G,Y),children:"✕"})]},`sa-${G}-${Y}`))}),s.jsxs("div",{className:"hub-send-form",children:[s.jsx("input",{type:"text",value:b[G]??"",onChange:Y=>x(_e=>({..._e,[G]:Y.target.value})),placeholder:"sender id, or Allow-All",disabled:w}),s.jsx("button",{className:"admin-refresh-btn",disabled:w||!(b[G]??"").trim(),onClick:()=>P(G),children:"+ Sender"}),le?null:s.jsx("button",{className:"admin-refresh-btn",disabled:w,onClick:()=>pe(G),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:()=>we(G)}),s.jsx("span",{className:"admin-hint",children:"Require approved recipients"})]})]},`sa-${G}`)})}),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(G=>!G)}),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(M/1e3),disabled:w,onChange:G=>$(Math.max(5,Math.min(600,Number(G.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:G=>G.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:G=>u(G.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:G=>f(G.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 F(),children:"Save"})]})]})]})})]})}function fo(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 eye(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 tye(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 nye({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: ${fo(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: ${fo(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: ${fo(i)}`,children:s.jsx("div",{className:"timeline-bar-fill use",style:{width:`${l}%`}})})]})}function rye(){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=eye(b.status,b.lastProbedAt,b.errorRate),S=tye(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: ",fo(x-b.lastProbedAt)]}),b.lastVerifiedAt>0&&s.jsxs("span",{children:["Verified: ",fo(x-b.lastVerifiedAt)]}),b.lastUsedAt>0&&s.jsxs("span",{children:["Used: ",fo(x-b.lastUsedAt)]}),b.latencyMs!==void 0&&s.jsxs("span",{children:[b.latencyMs,"ms"]})]})]}),s.jsx(nye,{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 Ta(e){return e==null?"0":e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}function iye(e){return e==null?"0%":(e*100).toFixed(1)+"%"}function aye({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:Ta(t.total)}),s.jsx("div",{className:"stat-label",children:"Trajectories"})]}),s.jsxs("div",{className:"stat-card",children:[s.jsx("div",{className:"stat-value",children:iye(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:Ta((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:Ta(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:Ta(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:Ta(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?` · ${Ta(a.last7d)} recall(s) this week, ${Ta(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 sye(e){return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function oye({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:["📅 ",sye(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 lye({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 cye({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 uye(){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?dye(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(cye,{envVars:n,onSave:(m,v)=>void h(m,v),onDelete:m=>void p(m),onTest:g,readOnly:!d})]})}function dye(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 fye(){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(qL,{connected:n,lastUpdated:i,children:s.jsxs(jL,{children:[s.jsx(at,{path:"/",element:s.jsx(ej,{})}),s.jsx(at,{path:"/overview",element:s.jsx(kie,{data:e})}),s.jsx(at,{path:"/chat",element:s.jsx(h1,{to:"/",replace:!0})}),s.jsx(at,{path:"/dag",element:s.jsx(Mie,{data:e})}),s.jsx(at,{path:"/costs",element:s.jsx(Iie,{data:e})}),s.jsx(at,{path:"/benchmarks",element:s.jsx(Lie,{data:e})}),s.jsx(at,{path:"/models",element:s.jsx(xae,{})}),s.jsx(at,{path:"/models/timeline",element:s.jsx(rye,{})}),s.jsx(at,{path:"/routing",element:s.jsx(tse,{data:e})}),s.jsx(at,{path:"/requests",element:s.jsx(ise,{data:e})}),s.jsx(at,{path:"/traces",element:s.jsx(pse,{})}),s.jsx(at,{path:"/hub",element:s.jsx(Nse,{})}),s.jsx(at,{path:"/tasks",element:s.jsx(Tse,{})}),s.jsx(at,{path:"/chat",element:s.jsx(ej,{})}),s.jsx(at,{path:"/evals",element:s.jsx(Kge,{data:e})}),s.jsx(at,{path:"/platforms",element:s.jsx(Xge,{})}),s.jsx(at,{path:"/bedrock",element:s.jsx(Qge,{canWrite:!0,sessionExpired:c=>console.error(c)})}),s.jsx(at,{path:"/contacts",element:s.jsx(Jge,{})}),s.jsx(at,{path:"/gateway",element:s.jsx(Yge,{})}),s.jsx(at,{path:"/env",element:s.jsx(uye,{})}),s.jsx(at,{path:"/memory",element:s.jsx(aye,{data:e})}),s.jsx(at,{path:"/history",element:s.jsx(oye,{data:e})}),s.jsx(at,{path:"/executions",element:s.jsx(lye,{onFetch:c=>ee.fetchExecutionAudit(c)})}),s.jsx(at,{path:"/system",element:s.jsx(Die,{data:e})}),s.jsx(at,{path:"/admin",element:s.jsx(bse,{})}),s.jsx(at,{path:"*",element:s.jsx(h1,{to:"/",replace:!0})})]})})}mT(document.getElementById("root")).render(s.jsx(E.StrictMode,{children:s.jsx(IL,{children:s.jsx(fye,{})})}));
|
|
207
|
-
//# sourceMappingURL=index-
|
|
207
|
+
//# sourceMappingURL=index-CxDj7p6i.js.map
|