agentic-ui-libs 0.2.0-beta.23 → 0.2.0-beta.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +12 -12
- package/dist/ui-libs.umd.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -27965,7 +27965,7 @@ function ib({
|
|
|
27965
27965
|
const c = Wt(() => {
|
|
27966
27966
|
var R;
|
|
27967
27967
|
return e.type === "GuardrailsInputScan" || e.type === "GuardrailsOutputScan" || ((R = e.name) == null ? void 0 : R.toLowerCase().includes("guardrail"));
|
|
27968
|
-
}, [e.type, e.name]), u = Wt(() => c ? ["summary", "
|
|
27968
|
+
}, [e.type, e.name]), u = Wt(() => c ? ["summary", "response"] : e.type === "ProxyWorker" ? ["request", "response"] : e.type === "llm" ? ["summary", "request", "response"] : e.type === "tool" ? ["request", "response", "logs"] : [], [e.type, c]), [f, d] = ce(u[0]), m = a ? a.has(e.id) : !1, g = e.children && e.children.length > 0, [v, h] = ce(null), [b, w] = ce(!1), [x, T] = ce(null), [y, O] = ce(!1), [S, A] = ce(!1), E = ["llm"], C = 5, j = 2e3;
|
|
27969
27969
|
console.log("🔧 DebugCard - Props received:", {
|
|
27970
27970
|
nodeId: e.id,
|
|
27971
27971
|
nodeName: e.name,
|
|
@@ -28327,16 +28327,7 @@ function ib({
|
|
|
28327
28327
|
}
|
|
28328
28328
|
);
|
|
28329
28329
|
}
|
|
28330
|
-
return
|
|
28331
|
-
Et,
|
|
28332
|
-
{
|
|
28333
|
-
data: e.output,
|
|
28334
|
-
title: "Full Scanner Output",
|
|
28335
|
-
maxHeight: "250px",
|
|
28336
|
-
defaultExpanded: !1,
|
|
28337
|
-
defaultViewMode: "plain"
|
|
28338
|
-
}
|
|
28339
|
-
) : /* @__PURE__ */ p.jsx(
|
|
28330
|
+
return /* @__PURE__ */ p.jsx(
|
|
28340
28331
|
Et,
|
|
28341
28332
|
{
|
|
28342
28333
|
data: e.input,
|
|
@@ -28379,7 +28370,16 @@ function ib({
|
|
|
28379
28370
|
}
|
|
28380
28371
|
);
|
|
28381
28372
|
}
|
|
28382
|
-
return /* @__PURE__ */ p.jsx(
|
|
28373
|
+
return c && (e.output || e.error) ? /* @__PURE__ */ p.jsx(
|
|
28374
|
+
Et,
|
|
28375
|
+
{
|
|
28376
|
+
data: e.error || e.output,
|
|
28377
|
+
title: e.error ? "Error Output" : "Full Scanner Output",
|
|
28378
|
+
maxHeight: "250px",
|
|
28379
|
+
defaultExpanded: !1,
|
|
28380
|
+
defaultViewMode: "plain"
|
|
28381
|
+
}
|
|
28382
|
+
) : /* @__PURE__ */ p.jsx(
|
|
28383
28383
|
Et,
|
|
28384
28384
|
{
|
|
28385
28385
|
data: e.output,
|
package/dist/ui-libs.umd.js
CHANGED
|
@@ -291,7 +291,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
291
291
|
<path d="M6 5.5H3M4 7.5H3M7 3.5H3M9 3.4V8.6C9 9.44008 9 9.86012 8.83651 10.181C8.6927 10.4632 8.46323 10.6927 8.18099 10.8365C7.86012 11 7.44008 11 6.6 11H3.4C2.55992 11 2.13988 11 1.81901 10.8365C1.53677 10.6927 1.3073 10.4632 1.16349 10.181C1 9.86012 1 9.44008 1 8.6V3.4C1 2.55992 1 2.13988 1.16349 1.81901C1.3073 1.53677 1.53677 1.3073 1.81901 1.16349C2.13988 1 2.55992 1 3.4 1H6.6C7.44008 1 7.86012 1 8.18099 1.16349C8.46323 1.3073 8.6927 1.53677 8.83651 1.81901C9 2.13988 9 2.55992 9 3.4Z" stroke="#7A5AF8" stroke-width="1.33" stroke-linecap="round" stroke-linejoin="round"/>
|
|
292
292
|
</svg>`,MCP:`<svg width="14" height="14" viewBox="0 0 22 23" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
293
293
|
<path d="M1.8125 10.7455L10.647 1.91124C11.8411 0.717087 13.7773 0.717087 14.9714 1.91124C16.1655 3.10539 16.1655 5.0415 14.9714 6.23565M14.9714 6.23565L8.29911 12.9077M14.9714 6.23565C16.1655 5.0415 18.1018 5.0415 19.2958 6.23565C20.4899 7.4298 20.4899 9.36593 19.2958 10.56L11.7665 18.0893C11.3443 18.5115 11.3443 19.1961 11.7665 19.6182L13.164 21.0158M16.9479 8.58236L10.2756 15.2547C9.08153 16.4488 7.1453 16.4488 5.95123 15.2547C4.75716 14.0605 4.75716 12.1244 5.95123 10.9303L12.6234 4.25814" stroke="#101828" stroke-width="2.00016" stroke-linecap="round" stroke-linejoin="round"/>
|
|
294
|
-
</svg>`},UB=(e,t)=>{const r=e.toLowerCase();if(r.includes("code"))return Ft.inlineTool;if(r.includes("workflow")||r.includes("library"))return Ft.toolLibrary;if(r.includes("knowledge"))return Ft.KNOWLEDGE;if(r.includes("mcp"))return Ft.MCP;if(Ft[e])return Ft[e];const n=t.toLowerCase();return n.includes("code")||n.includes("inline")||n.includes("calculate")?Ft.inlineTool:n.includes("library")||n.includes("workflow")?Ft.toolLibrary:n.includes("knowledge")||n.includes("document")||n.includes("fetch")?Ft.KNOWLEDGE:n.includes("mcp")||n.includes("protocol")?Ft.MCP:Ft.toolLibrary},xi=({icon:e,iconSource:t="agent",size:r="small",className:n="",name:a="Unknown",toolType:i,provider:o,modelName:s})=>{const[l,u]=S.useState(!1),[c,f]=S.useState(!1),[d,m]=S.useState(!1),g=LB(e),v=FB[r];if(t==="model"){const w=$0(o),x=()=>{m(!0)};if(d){const T=o?o.charAt(0).toUpperCase():"🤖";return p.jsx("div",{className:`${v} rounded-[8px] bg-gray-200 flex items-center justify-center ${n}`,children:p.jsx("span",{className:"text-gray-900 text-xs font-bold",children:T})})}return p.jsx("img",{src:w,alt:s||a,className:`${v} rounded-[8px] p-[4px] ${n}`,onError:x})}if(g!=null&&g.name&&g.name!=="fallback"&&!l){const w=BB(g,t),x=()=>{u(!0)};return p.jsx("img",{src:w,alt:a,className:`${v} rounded-[8px] p-[4px] object-cover ${n}`,onError:x})}if(l&&!c&&t==="agent"){const w=`${window.location.origin}/agenticai/assets/agent-avatars/avatar1.svg`,x=()=>{f(!0)};return p.jsx("img",{src:w,alt:a,className:`${v} rounded-[8px] p-[4px] object-cover ${n}`,onError:x})}if(t==="model"){const w=$0(o),x=()=>{m(!0)};if(d){const T=o?o.charAt(0).toUpperCase():"🤖";return p.jsx("div",{className:`${v} rounded-[8px] bg-gray-200 flex items-center justify-center ${n}`,children:p.jsx("span",{className:"text-gray-900 text-xs font-bold",children:T})})}return p.jsx("img",{src:w,alt:s||a,className:`${v} rounded-[8px] p-[4px] ${n}`,onError:x})}const h=g||RB(a,t);if(t==="workflowtool"){const w=i||h.type||"toolLibrary",x=UB(w,a);return p.jsx("div",{className:`${v} rounded-[8px] flex items-center justify-center bg-gray-100 ${n}`,children:p.jsx("div",{dangerouslySetInnerHTML:{__html:x}})})}const b=`${window.location.origin}/agenticai/assets/agent-avatars/avatar1.svg`;return p.jsx("img",{src:b,alt:a,className:`${v} rounded-[8px] p-[4px] object-cover ${n}`})},k0=({data:e,className:t})=>{const[r,n]=S.useState(5),a=()=>{n(o=>Math.min(o+10,e.length))},i=o=>o>=1e3?`${Math.floor(o/1e3)}k`:o.toString();return p.jsxs("div",{className:le("w-full",t),children:[p.jsxs("div",{className:"grid grid-cols-4 items-center gap-4 px-[16px] py-[12px] bg-gray-50 border-b border-gray-200 text-xs font-medium text-gray-600",children:[p.jsx("div",{className:"text-left",children:"Name"}),p.jsx("div",{className:"text-center",children:"Runs"}),p.jsx("div",{className:"text-center",children:"Response Time"}),p.jsx("div",{className:"text-center",children:"Tokens"})]}),p.jsx("div",{className:"divide-y divide-gray-100",children:e.slice(0,r).map((o,s)=>p.jsxs("div",{className:"grid grid-cols-4 items-center gap-4 px-[16px] py-[12px] cursor-pointer transition-colors duration-150 border-b border-gray-200",children:[p.jsxs("div",{className:"flex items-center gap-[8px]",children:[p.jsx("div",{className:"flex-shrink-0",children:p.jsx(xi,{icon:o.icon,iconSource:"agent",size:"small",name:o.name||"Unknown Agent"})}),p.jsx("div",{className:"min-w-0 flex-1 w-full",children:p.jsx("div",{className:"text-xs font-medium text-gray-700 truncate",children:o.name||"Unknown Agent"})})]}),p.jsx("div",{className:"text-center font-medium text-xs text-gray-700",children:o.runs?i(o.runs):"-"}),p.jsx("div",{className:"text-center font-medium text-xs text-gray-700",children:o.responseTime||"-"}),p.jsx("div",{className:"text-center font-medium text-xs text-gray-700",children:o.tokens?i(o.tokens):"-"})]},o.id||s))}),r<e.length&&p.jsx("div",{className:"flex justify-center",children:p.jsx("button",{onClick:a,className:"px-[16px] py-[8px] text-xs font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors duration-150",children:"Load 10 more"})})]})};function WB(e){const t=(e==null?void 0:e.toLowerCase())||"";return["inlinetool","inlineTool","code tool","code","tool","event","EVENT"].includes(e)||["inlinetool","inlineTool","code tool","code","tool","event"].includes(t)?"bg-orange-100 text-orange-800 border-orange-200":["toollibrary","toolLibrary","workflow tool"].includes(e)||["toollibrary","toollibrary","workflow tool"].includes(t)?"bg-blue-100 text-blue-800 border-blue-200":["mcp","MCP","mcpTool","mcpTool"].includes(e)||["mcp","mcptool"].includes(t)?"bg-green-100 text-green-800 border-green-200":["knowledge","KNOWLEDGE","knowledge tool"].includes(e)||["knowledge","knowledge tool"].includes(t)?"bg-purple-100 text-purple-800 border-purple-200":"bg-gray-100 text-gray-800 border-gray-200"}function zB(e){const t=(e==null?void 0:e.toLowerCase())||"";return["inlinetool","code tool","code","tool","event","inlineTool"].includes(t)?"Code Tool":["toollibrary","workflow tool"].includes(t)?"Workflow Tool":["mcp","mcptool"].includes(t)?"MCP Tool":["knowledge","knowledge tool","knowledge"].includes(t)||e==="KNOWLEDGE"?"Knowledge":e==="inlineTool"?"Code Tool":e==="toolLibrary"?"Workflow Tool":e==="KNOWLEDGE"?"Knowledge":e==="MCP"||e==="mcpTool"?"MCP Tool":"Code Tool"}const N0=({data:e,className:t})=>{const[r,n]=S.useState(5),a=()=>{n(o=>Math.min(o+10,e.length))},i=o=>o>=1e3?`${Math.floor(o/1e3)}k`:o.toString();return p.jsxs("div",{className:le("w-full",t),children:[p.jsxs("div",{className:"grid grid-cols-4 items-center gap-4 px-[16px] py-[12px] bg-gray-50 border-b border-gray-200 text-xs font-medium text-gray-600",children:[p.jsx("div",{className:"text-left",children:"Name"}),p.jsx("div",{className:"text-center",children:"Type"}),p.jsx("div",{className:"text-center",children:"Runs"}),p.jsx("div",{className:"text-center",children:"Response Time"})]}),p.jsx("div",{className:"divide-y divide-gray-100",children:e.slice(0,r).map((o,s)=>p.jsxs("div",{className:"grid grid-cols-4 items-center gap-4 px-[16px] py-[12px] cursor-pointer transition-colors duration-150 border-b border-gray-200",children:[p.jsxs("div",{className:"flex items-center gap-[8px]",children:[p.jsx("div",{className:"flex-shrink-0",children:p.jsx(xi,{icon:o.icon,iconSource:"workflowtool",size:"small",name:o.name||"Unknown Tool",toolType:o.toolType||o.type})}),p.jsx("div",{className:"min-w-0 flex-1 w-full",children:p.jsx("div",{className:"text-xs font-medium text-gray-700 truncate",children:o.name||"Unknown Tool"})})]}),p.jsx("div",{className:"flex items-center justify-center",children:p.jsx("span",{className:le("inline-flex items-center px-[10px] py-[4px] rounded-full text-xs font-medium border",WB(o.toolType||o.type||"Default")),children:zB(o.toolType||o.type||"Default")})}),p.jsx("div",{className:"text-center font-medium text-xs text-gray-700",children:o.runs?i(o.runs):"-"}),p.jsx("div",{className:"text-center font-medium text-xs text-gray-700",children:o.responseTime||"-"})]},o.id||s))}),r<e.length&&p.jsx("div",{className:"flex justify-center",children:p.jsx("button",{onClick:a,className:"px-[16px] py-[8px] text-xs font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors duration-150",children:"Load 10 more"})})]})},VB=e=>{if(!e)return"/assets/icons/models/custom-api.svg";const t=e.toLowerCase(),r={openai:"Open AI.svg","open ai":"Open AI.svg",chatopenai:"Open AI.svg",gpt:"Open AI.svg",anthropic:"Anthropic.svg",claude:"Anthropic.svg",google:"Google.svg",gemini:"Google.svg",chatgooglegenerativeai:"Google.svg",googlegenerativeai:"Google.svg",palm:"Google.svg",azurechatopenai:"Azure Open AI.svg","azure open ai":"Azure Open AI.svg",azureopenai:"Azure Open AI.svg","azure openai":"Azure Open AI.svg",azure:"Azure Open AI.svg",aws:"AWS Bedrock.svg",bedrock:"AWS Bedrock.svg","aws bedrock":"AWS Bedrock.svg",awsbedrock:"AWS Bedrock.svg",amazon:"AWS Bedrock.svg",cohere:"Cohere.svg",api:"API.svg",custom:"custom-api.svg","custom-api":"custom-api.svg",customapi:"custom-api.svg"};if(r[t])return`assets/icons/models/${r[t]}`;for(const[n,a]of Object.entries(r))if(t.includes(n)||n.includes(t))return`assets/icons/models/${a}`;return"assets/icons/models/custom-api.svg"},GB=e=>{if(!e)return"";const t=e.toLowerCase(),r={openai:"OpenAI","open ai":"OpenAI",chatopenai:"OpenAI",gpt:"OpenAI",anthropic:"Anthropic",claude:"Anthropic",google:"Google",gemini:"Google Gemini",chatgooglegenerativeai:"Google Gemini",googlegenerativeai:"Google Gemini",palm:"Google PaLM",azurechatopenai:"Azure OpenAI","azure open ai":"Azure OpenAI",azureopenai:"Azure OpenAI","azure openai":"Azure OpenAI",azure:"Azure OpenAI",aws:"AWS Bedrock",bedrock:"AWS Bedrock","aws bedrock":"AWS Bedrock",awsbedrock:"AWS Bedrock",amazon:"AWS Bedrock",cohere:"Cohere",meta:"Meta",llama:"Meta LLaMA",mistral:"Mistral",huggingface:"Hugging Face",together:"Together AI",replicate:"Replicate"};if(r[t])return r[t];for(const[n,a]of Object.entries(r))if(t.includes(n)||n.includes(t))return a;return e.charAt(0).toUpperCase()+e.slice(1)},HB=({provider:e})=>{const[t,r]=S.useState(!1),n=VB(e),a=()=>{r(!0)};if(t){const i=e?e.charAt(0).toUpperCase():"🤖";return p.jsx("div",{className:"w-6 h-6 rounded-full bg-gray-500 flex items-center justify-center",children:p.jsx("span",{className:"text-white text-xs font-bold",children:i})})}return p.jsx("img",{src:n,alt:e||"Model",className:"w-6 h-6 rounded",onError:a})},M0=({data:e,className:t})=>{const[r,n]=S.useState(5),a=()=>{n(o=>Math.min(o+10,e.length))},i=o=>o>=1e3?`${Math.floor(o/1e3)}k`:o.toString();return p.jsxs("div",{className:le("w-full",t),children:[p.jsxs("div",{className:"grid grid-cols-4 items-center gap-4 px-[16px] py-[12px] bg-gray-50 border-b border-gray-200 text-xs font-medium text-gray-600",children:[p.jsx("div",{className:"text-left",children:"Model Name"}),p.jsx("div",{className:"text-center",children:"Runs"}),p.jsx("div",{className:"text-center",children:"Tokens"}),p.jsx("div",{className:"text-center",children:"Response Time"})]}),p.jsx("div",{className:"divide-y divide-gray-100",children:e.slice(0,r).map((o,s)=>p.jsxs("div",{className:"grid grid-cols-4 items-center gap-4 px-[16px] py-[12px] cursor-pointer transition-colors duration-150 border-b border-gray-200",children:[p.jsxs("div",{className:"flex items-center gap-[8px]",children:[p.jsx("div",{className:"flex-shrink-0",children:p.jsx(HB,{provider:o.provider})}),p.jsxs("div",{className:"min-w-0 flex-1 w-full",children:[p.jsx("div",{className:"text-xs font-medium text-gray-700 truncate",children:o.name||o.modelName||"Unknown Model"}),o.provider&&p.jsx("div",{className:"text-xs text-gray-500 truncate",children:GB(o.provider)})]})]}),p.jsx("div",{className:"text-center font-medium text-xs text-gray-700",children:i(o.runs||0)}),p.jsx("div",{className:"text-center font-medium text-xs text-gray-700",children:i(o.tokens||o.totalTokens||0)}),p.jsx("div",{className:"text-center font-medium text-xs text-gray-700",children:o.responseTime||(o.avgResponseTime?`${o.avgResponseTime}ms`:"N/A")})]},o.id||s))}),r<e.length&&p.jsx("div",{className:"flex justify-center",children:p.jsx("button",{onClick:a,className:"px-[16px] py-[8px] text-xs font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors duration-150",children:"Load 10 more"})})]})},qB=e=>{switch(e){case"agentRuns":return{title:"Agent Runs",entityName:"Agents"};case"toolRuns":return{title:"Tool Runs",entityName:"Tools"};case"modelRuns":return{title:"Model Runs",entityName:"Models"};default:return{title:"Runs",entityName:"Items"}}},KB=e=>e>=1e3?`${Math.floor(e/1e3)}k`:e.toString(),D0=({isOpen:e,onClose:t,date:r,metricType:n,data:a,totalRuns:i,className:o})=>{var O;const s=qB(n),[l,u]=S.useState(10),[c,f]=S.useState("all"),[d,m]=S.useState(!1),g=[{label:`All ${s.entityName}`,value:"all"},...a.map(A=>({label:A.name,value:A.id}))],v=c==="all"?a:a.filter(A=>A.id===c),h=()=>{f("all"),m(!1),u(10),t()};S.useEffect(()=>{const A=C=>{C.key==="Escape"&&h()},j=C=>{d&&(C.target.closest(".filter-dropdown")||m(!1))};return e&&(document.addEventListener("keydown",A),document.addEventListener("mousedown",j),document.body.style.overflow="hidden"),()=>{document.removeEventListener("keydown",A),document.removeEventListener("mousedown",j),document.body.style.overflow="unset"}},[e,d,h]),S.useEffect(()=>{e&&(f("all"),m(!1),u(10))},[e]);const b=A=>new Date(A).toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric"}),w=()=>{u(A=>Math.min(A+10,v.length))},x=A=>{f(A),m(!1),u(10)};if(!e)return null;const T=v.slice(0,l),y=((O=g.find(A=>A.value===c))==null?void 0:O.label)||`All ${s.entityName}`;return p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 transition-opacity duration-300",onClick:h}),p.jsxs("div",{className:le("fixed right-0 top-0 h-full w-[600px] bg-white shadow-[0px_20px_24px_-4px_rgba(16,24,40,0.08),0px_8px_8px_-4px_rgba(16,24,40,0.03)] z-50 transform transition-transform duration-300 ease-in-out",e?"translate-x-0":"translate-x-full",o),children:[p.jsxs("div",{className:"flex items-center justify-between px-6 py-3 border-b border-[#d0d5dd]",children:[p.jsx("h2",{className:"text-lg font-semibold text-[#101828]",children:s.title}),p.jsx("button",{onClick:h,className:"p-2 hover:bg-gray-100 rounded-lg transition-colors",children:p.jsx(Nf,{className:"h-5 w-5 text-[#101828]"})})]}),p.jsxs("div",{className:"flex flex-col h-[calc(100%-64px)] p-6 gap-6",children:[p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsxs("div",{className:"text-sm font-medium text-[#344054]",children:[s.title," (",b(r),")"]}),p.jsxs("div",{className:"w-[210px] relative filter-dropdown",children:[p.jsxs("button",{onClick:()=>m(!d),className:"w-full bg-white border border-[#d0d5dd] rounded-lg px-3.5 py-2.5 flex items-center justify-between text-sm text-[#101828] hover:bg-gray-50 transition-colors",children:[p.jsx("span",{children:y}),p.jsx(fr,{className:"h-4 w-4 text-[#101828]"})]}),d&&p.jsx("div",{className:"absolute top-full left-0 right-0 mt-1 bg-white border border-[#d0d5dd] rounded-lg shadow-lg z-10 max-h-60 overflow-y-auto",children:g.map(A=>p.jsx("button",{onClick:()=>x(A.value),className:le("w-full px-3.5 py-2.5 text-left text-sm hover:bg-gray-50 transition-colors",c===A.value?"bg-blue-50 text-blue-700":"text-[#101828]"),children:A.label},A.value))})]})]}),p.jsxs("div",{className:"flex-1 overflow-hidden",children:[p.jsx("div",{className:"bg-[#f9fafb] border-b border-[#eaecf0] px-2 py-2",children:p.jsxs("div",{className:"grid grid-cols-4 gap-3 items-center",children:[p.jsx("div",{className:"col-span-2 px-0 py-2",children:p.jsx("div",{className:"text-xs font-medium text-[#475467]",children:"Name"})}),p.jsx("div",{className:"flex justify-center px-0 py-2",children:p.jsx("div",{className:"text-xs font-medium text-[#475467]",children:"Runs"})}),p.jsx("div",{className:"flex justify-center px-0 py-2",children:p.jsx("div",{className:"text-xs font-medium text-[#475467]",children:"Response Time"})})]})}),p.jsx("div",{className:"overflow-y-auto max-h-[calc(100%-40px)]",children:T.length===0?p.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-center",children:[p.jsxs("h3",{className:"text-md font-medium text-gray-900 mb-[8px]",children:["No ",s.title.toLowerCase()," for this date"]}),p.jsxs("p",{className:"text-xs text-gray-500",children:["There were no ",s.title.toLowerCase()," recorded on ",b(r),"."]})]}):p.jsxs(p.Fragment,{children:[T.map((A,j)=>p.jsxs("div",{className:"grid grid-cols-4 gap-3 items-center px-2 py-3 border-b border-[#eaecf0] hover:bg-gray-50 transition-colors",children:[p.jsxs("div",{className:"col-span-2 flex items-center gap-2",children:[p.jsx("div",{className:"flex-shrink-0",children:p.jsx(xi,{icon:A.icon,iconSource:n==="agentRuns"?"agent":n==="toolRuns"?"workflowtool":"model",size:"small",name:A.name,toolType:A.toolType||A.type,provider:A.provider,modelName:A.modelName})}),p.jsxs("div",{className:"min-w-0 flex-1",children:[p.jsx("div",{className:"text-sm font-medium text-[#101828] truncate",children:A.name}),n==="modelRuns"&&A.provider&&p.jsx("div",{className:"text-xs text-[#475467] truncate",children:A.provider})]})]}),p.jsx("div",{className:"flex justify-center",children:p.jsx("div",{className:"text-xs font-medium text-[#475467]",children:KB(A.runs)})}),p.jsx("div",{className:"flex justify-center",children:p.jsx("div",{className:"text-xs font-medium text-[#475467]",children:A.responseTime})})]},A.id||j)),l<v.length&&p.jsx("div",{className:"flex justify-center",children:p.jsx("button",{onClick:w,className:"bg-white border border-[#d0d5dd] rounded px-3 py-1 text-xs font-medium text-[#344054] hover:bg-gray-50 transition-colors",children:"Load 10 more"})})]})})]})]})]})]})};class I0{constructor(t=""){kt(this,"API_PATH","/tracing/api/trpc/metrics.getMetrics");kt(this,"baseUrl","");kt(this,"endpoints",{});this.baseUrl=t,this.initializeEndpoints()}setBaseUrl(t){this.baseUrl=t,this.initializeEndpoints()}getEndpoint(t){return this.endpoints[t]||{endpoint:"",method:"GET"}}getBaseUrl(){return this.baseUrl}initializeEndpoints(){const t=`${this.baseUrl}${this.API_PATH}`;this.endpoints["usage-analytics.cards"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH},this.endpoints["usage-analytics.sessions.timeseries"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH},this.endpoints["usage-analytics.messages.timeseries"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH},this.endpoints["usage-analytics.users.timeseries"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH},this.endpoints["usage-analytics.tokens.timeseries"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH},this.endpoints["runs.cards"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH},this.endpoints["runs.agent-runs.timeseries"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH},this.endpoints["runs.model-runs.timeseries"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH},this.endpoints["runs.tool-runs.timeseries"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH}}getAvailableEndpoints(){return Object.keys(this.endpoints)}hasEndpoint(t){return t in this.endpoints}}class L0{constructor(t){kt(this,"endpointsService");kt(this,"defaultHeaders");kt(this,"timeout");this.endpointsService=new I0(t.baseUrl),this.defaultHeaders={"Content-Type":"application/json",...t.defaultHeaders},this.timeout=t.timeout||3e4}updateConfig(t){t.baseUrl&&this.endpointsService.setBaseUrl(t.baseUrl),t.defaultHeaders&&(this.defaultHeaders={...this.defaultHeaders,...t.defaultHeaders}),t.timeout&&(this.timeout=t.timeout)}async invoke(t,r,n,a){const i=this.endpointsService.getEndpoint(t);if(!i.endpoint)throw new Error(`Endpoint not found for service: ${t}`);const o=this.prepareRequest(i,r,n);try{const s=new AbortController,l=setTimeout(()=>s.abort(),(a==null?void 0:a.timeout)||this.timeout),u=await fetch(o.url,{method:o.method,headers:o.headers,body:o.body,signal:(a==null?void 0:a.signal)||s.signal});if(clearTimeout(l),!u.ok)throw new Error(`HTTP Error: ${u.status} ${u.statusText}`);return await u.json()}catch(s){throw s instanceof Error?s.name==="AbortError"?new Error("Request timeout"):s:new Error("Unknown error occurred during API call")}}prepareRequest(t,r,n){const a={...this.defaultHeaders,...n},i={};Object.entries(a).forEach(([l,u])=>{u!==void 0&&(i[l]=u)});let o=t.endpoint,s;if(t.method==="GET"&&r){const l=this.buildQueryParams(r);o+=`?${l}`}else r&&(s=JSON.stringify(r));return{url:o,method:t.method,headers:i,body:s}}buildQueryParams(t){const r={json:t},n=new URLSearchParams;return n.append("input",JSON.stringify(r)),n.append("rnd",Math.random().toString(36).substring(7)),n.toString()}getBaseUrl(){return this.endpointsService.getBaseUrl()}hasEndpoint(t){return this.endpointsService.hasEndpoint(t)}getAvailableEndpoints(){return this.endpointsService.getAvailableEndpoints()}}class Yt{constructor(t){kt(this,"apiInvoker");kt(this,"projectId");kt(this,"environment");kt(this,"defaultTimeRange");const r={baseUrl:t.baseUrl,defaultHeaders:t.headers,timeout:3e4};this.apiInvoker=new L0(r),this.projectId=t.projectId,this.environment=t.environment,this.defaultTimeRange=t.defaultTimeRange}updateConfig(t){(t.baseUrl||t.headers)&&this.apiInvoker.updateConfig({baseUrl:t.baseUrl,defaultHeaders:t.headers}),t.projectId&&(this.projectId=t.projectId),t.environment&&(this.environment=t.environment),t.defaultTimeRange&&(this.defaultTimeRange=t.defaultTimeRange,console.log("🔄 API Service: Updated defaultTimeRange:",this.defaultTimeRange))}getDefaultTimeRange(){return this.defaultTimeRange||Yt.getDateRange(7)}async fetchEnvironments(){try{const r=`${this.apiInvoker.getBaseUrl()}/aaa/api/v1/apps/${this.projectId}/environments?rnd=${Math.random().toString(36).substring(2,8)}`;console.log("🌍 Fetching environments for project:",this.projectId),console.log("🔗 Environment API URL:",r);const n=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json",...this.apiInvoker.defaultHeaders}});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);const a=await n.json();return console.log("✅ Environments fetched successfully:",a.map(i=>({name:i.envName,enabled:i.isEnabled,status:i.status}))),a}catch(t){throw console.error("❌ Error fetching environments:",t),t}}async fetchUsageAnalyticsCards(t,r,n,a=[]){const i=n||Yt.getTimeDimension(t,r);console.log("📊 Fetching usage analytics cards:",{dateRange:{fromTimestamp:t,toTimestamp:r},providedTimeDimension:n,resolvedTimeDimension:i});const o={projectId:this.projectId,type:"cards",category:"usage-analytics",envId:this.environment,fromTimestamp:t,toTimestamp:r,filter:a,includeTrends:!0,timeDimension:i};return(await this.apiInvoker.invoke("usage-analytics.cards",o)).result.data.json}async fetchRunsCards(t,r,n,a=[]){const i=n||Yt.getTimeDimension(t,r);console.log("📊 Fetching runs cards:",{dateRange:{fromTimestamp:t,toTimestamp:r},providedTimeDimension:n,resolvedTimeDimension:i});const o={projectId:this.projectId,type:"cards",category:"runs",envId:this.environment,fromTimestamp:t,toTimestamp:r,filter:a,includeTrends:!0,timeDimension:i};return(await this.apiInvoker.invoke("runs.cards",o)).result.data.json}async fetchTimeSeriesData(t,r,n,a,i,o=[]){const s=i||Yt.getTimeDimension(n,a);console.log("📊 Fetching time series data:",{metric:t,category:r,dateRange:{fromTimestamp:n,toTimestamp:a},providedTimeDimension:i,resolvedTimeDimension:s});const l=`${r}.${t}.timeseries`,u={projectId:this.projectId,type:"time-series",category:r,envId:this.environment,fromTimestamp:n,toTimestamp:a,filter:o,metric:t,timeDimension:s};return(await this.apiInvoker.invoke(l,u)).result.data.json}transformUsageAnalyticsCards(t){const r=t.data.trends;console.log("Transforming usage analytics cards with trends:",r);const n=a=>a>0?"increase":"decrease";return[{title:"Users",value:t.data.users,metricType:"users",icon:"users",info:"Number of unique users who interacted with the app",highlighted:!0,change:r!=null&&r.users?{value:Math.abs(r.users.changePercent),type:n(r.users.changePercent)}:void 0},{title:"Sessions",value:t.data.sessions,metricType:"sessions",icon:"activity",info:"Number of conversations initiated with the app",highlighted:!1,change:r!=null&&r.sessions?{value:Math.abs(r.sessions.changePercent),type:n(r.sessions.changePercent)}:void 0},{title:"Messages",value:t.data.messages.total,metricType:"messages",icon:"message-circle",info:"Total messages exchanged between users and the app",highlighted:!1,change:r!=null&&r.messages?{value:Math.abs(r.messages.changePercent.total),type:n(r.messages.changePercent.total)}:void 0},{title:"Tokens",value:t.data.tokens.total,metricType:"tokens",icon:"coins",info:"Total input and output tokens processed by the app for all interactions",highlighted:!1,change:r!=null&&r.tokens?{value:Math.abs(r.tokens.changePercent.total),type:n(r.tokens.changePercent.total)}:void 0}]}transformRunsCards(t){const r=t.data.trends;console.log("Transforming runs cards with trends:",r);const n=a=>a>0?"increase":"decrease";return[{title:"Agent Runs",value:t.data.agentRuns,metricType:"agentRuns",icon:"bot",info:"Number of times the AI agents were executed to handle user requests",highlighted:!0,change:r!=null&&r.agentRuns?{value:Math.abs(r.agentRuns.changePercent),type:n(r.agentRuns.changePercent)}:void 0},{title:"Tool Runs",value:t.data.toolRuns.total,metricType:"toolRuns",icon:"wrench",info:"Number of times various tools were triggered by the AI agents to complete tasks",highlighted:!1,change:r!=null&&r.toolRuns?{value:Math.abs(r.toolRuns.changePercent.total),type:n(r.toolRuns.changePercent.total)}:void 0},{title:"Model Runs",value:t.data.modelRuns,metricType:"modelRuns",icon:"cpu",info:"Number of times the AI agents called various language models to generate responses",highlighted:!1,change:r!=null&&r.modelRuns?{value:Math.abs(r.modelRuns.changePercent),type:n(r.modelRuns.changePercent)}:void 0}]}transformTimeSeriesDataForMetric(t,r){var a;if(console.log("=== METRIC-SPECIFIC TRANSFORM DEBUG ==="),console.log("Raw TimeSeriesResponse:",JSON.stringify(t,null,2)),console.log("Metric type:",r),!t||!t.data||!Array.isArray(t.data))return console.error("Invalid time series data structure:",t),[];const n=t.data.map((i,o)=>{console.log(`Processing point ${o}:`,i);const s=new Date(i.timestamp),l=s.toISOString().split("T")[0],u=s.toLocaleDateString("en-US",{month:"short",day:"numeric"}),c={date:l,timestamp:u,formattedDate:u,count:i.count||0,value:i.count||0,input_tokens:i.input_tokens||0,output_tokens:i.output_tokens||0,total_tokens:(i.input_tokens||0)+(i.output_tokens||0),inputTokens:i.input_tokens||0,outputTokens:i.output_tokens||0,totalTokens:(i.input_tokens||0)+(i.output_tokens||0),listView:i.listView||[],index:o};switch(r){case"users":c.users=i.count||0;break;case"sessions":c.sessions=i.count||0;break;case"messages":c.messages=i.count||0;break;case"tokens":c.tokens=i.count||0,i.input_tokens||i.output_tokens?c.totalTokens=(i.input_tokens||0)+(i.output_tokens||0):c.totalTokens=i.count||0;break;case"agentRuns":c.agentRuns=i.count||0;break;case"toolRuns":c.toolRuns=i.count||0;break;case"modelRuns":c.modelRuns=i.count||0;break;default:c.users=i.count||0,c.sessions=i.count||0,c.messages=i.count||0,c.tokens=i.count||0,c.agentRuns=i.count||0,c.toolRuns=i.count||0,c.modelRuns=i.count||0}return console.log(`Transformed point ${o} for metric ${r}:`,c),c});return console.log("Final transformed data array:",JSON.stringify(n,null,2)),console.log("Sample transformed point for chart:",n[0]),console.log("Populated metric property:",r,"=",(a=n[0])==null?void 0:a[r||"count"]),console.log("=== END METRIC-SPECIFIC TRANSFORM DEBUG ==="),n}transformTimeSeriesData(t){return this.transformTimeSeriesDataForMetric(t)}transformAgentsListViewToTable(t){return Array.isArray(t)?t.map((r,n)=>{var o,s;let a="",i=null;if(r.icon)try{if(i=typeof r.icon=="string"?JSON.parse(r.icon):r.icon,i.name){const l=((o=r.agentName)==null?void 0:o.replace(/\s+/g,""))||`agent${n}`,u=((s=i.color)==null?void 0:s.replace("#",""))||"b6e3f4";a=`https://api.dicebear.com/7.x/avataaars/svg?seed=${l}&backgroundColor=${u}&backgroundType=solid`}}catch{console.warn("Failed to parse icon data:",r.icon)}return{id:`agent-${n+1}`,name:r.agentName||`Agent ${n+1}`,runs:r.count||0,responseTime:r.avgResponseTime?r.avgResponseTime<1e3?`${Math.round(r.avgResponseTime)}ms`:`${(r.avgResponseTime/1e3).toFixed(2)}s`:"0ms",tokens:r.tokens||Math.floor((r.count||0)*150),successRate:r.successRate?`${Math.round(r.successRate)}%`:"95%",lastRun:r.lastRun||new Date(Date.now()-Math.random()*7*24*60*60*1e3).toLocaleDateString(),avatar:a||`https://api.dicebear.com/7.x/avataaars/svg?seed=agent${n}&backgroundColor=b6e3f4,c0aede,d1d4f9&backgroundType=solid`,icon:r.icon||void 0}}):(console.warn("Invalid listView data for agents:",t),[])}transformToolsListViewToTable(t){return Array.isArray(t)?t.map((r,n)=>({id:`tool-${n+1}`,name:r.toolName||r.tool_name||`Tool ${n+1}`,type:r.type||r.toolType||r.tool_type||"Code Tool",runs:r.count||0,responseTime:r.avgResponseTime?r.avgResponseTime<1e3?`${Math.round(r.avgResponseTime)}ms`:`${(r.avgResponseTime/1e3).toFixed(2)}s`:"0ms",tokens:r.tokens||Math.floor((r.count||0)*50),successRate:r.successRate?`${Math.round(r.successRate)}%`:"92%",lastRun:r.lastRun||new Date(Date.now()-Math.random()*7*24*60*60*1e3).toLocaleDateString(),icon:r.icon||r.tool_icon||void 0})):(console.warn("Invalid listView data for tools:",t),[])}transformModelsListViewToTable(t){return Array.isArray(t)?t.map((r,n)=>({id:`model-${n+1}`,name:r.modelName||`Model ${n+1}`,modelName:r.modelName,provider:r.provider,runs:r.count||0,responseTime:r.avgResponseTime?r.avgResponseTime<1e3?`${Math.round(r.avgResponseTime)}ms`:`${(r.avgResponseTime/1e3).toFixed(2)}s`:"0ms",avgResponseTime:r.avgResponseTime,tokens:r.tokens||r.totalTokens||Math.floor((r.count||0)*300),totalTokens:r.totalTokens||r.tokens,successRate:r.successRate?`${Math.round(r.successRate)}%`:"98%",lastRun:r.lastRun||new Date(Date.now()-Math.random()*7*24*60*60*1e3).toLocaleDateString(),icon:r.icon})):(console.warn("Invalid listView data for models:",t),[])}extractAgentControlOptions(t){if(!Array.isArray(t))return[{label:"All Agents",value:"all"}];const r=[{label:"All Agents",value:"all"}];return t.forEach(n=>{var a;if(n.agentName){let i="";try{if(n.icon){const o=typeof n.icon=="string"?JSON.parse(n.icon):n.icon;if(o.name){const s=n.agentName.replace(/\s+/g,""),l=((a=o.color)==null?void 0:a.replace("#",""))||"b6e3f4";i=`https://api.dicebear.com/7.x/avataaars/svg?seed=${s}&backgroundColor=${l}&backgroundType=solid`}}}catch{console.warn("Failed to parse icon data for control:",n.icon)}r.push({label:n.agentName,value:n.agentName.replace(/\s+/g,"").toLowerCase(),avatar:i||`https://api.dicebear.com/7.x/avataaars/svg?seed=${n.agentName.replace(/\s+/g,"")}&backgroundColor=b6e3f4,c0aede,d1d4f9&backgroundType=solid`})}}),r}extractToolControlOptions(t){if(!Array.isArray(t))return[{label:"All Tools",value:"all"}];const r=[{label:"All Tools",value:"all"}];return t.forEach(n=>{const a=n.toolName||n.tool_name;if(a){let i=function(o){if(!o)return"Code Tool";const s=o.toLowerCase();return["inlinetool","code tool","code","event"].includes(s)?"Code Tool":["toollibrary","workflow tool"].includes(s)?"Workflow Tool":["mcp","mcptool"].includes(s)?"MCP Tool":["knowledge","knowledge tool"].includes(s)||o==="KNOWLEDGE"?"Knowledge":o==="inlineTool"?"Code Tool":o==="toolLibrary"?"Workflow Tool":o==="MCP"||o==="mcpTool"?"MCP Tool":"Code Tool"};r.push({label:a,value:a.replace(/[-]/g,""),icon:n.icon||n.tool_icon||void 0,type:n.type||i(n.toolType||n.tool_type)})}}),r}extractModelControlOptions(t){if(!Array.isArray(t))return[{label:"All Models",value:"all"}];const r=[{label:"All Models",value:"all"}];return t.forEach(n=>{n.modelName&&r.push({label:n.modelName,value:n.modelName.replace(/[-\.]/g,""),icon:n.icon,type:n.provider})}),r}async fetchTimeSeriesDataWithTableData(t,r,n,a,i,o=[]){const s=await this.fetchTimeSeriesData(t,r,n,a,i,o);let l=[];s.data.forEach(d=>{d.listView&&Array.isArray(d.listView)&&(l=[...l,...d.listView])});const u=this.aggregateListViewItems(l);let c=[],f=[];return t==="agent-runs"?(c=this.transformAgentsListViewToTable(u),f=this.extractAgentControlOptions(u)):t==="tool-runs"?(c=this.transformToolsListViewToTable(u),f=this.extractToolControlOptions(u)):t==="model-runs"&&(c=this.transformModelsListViewToTable(u),f=this.extractModelControlOptions(u)),{chartData:this.transformTimeSeriesDataForMetric(s,t.replace("-","")),tableData:c,controlOptions:f}}aggregateListViewItems(t){const r=new Map;return t.forEach(n=>{const a=n.agentName||n.toolName||n.modelName||"unknown";if(r.has(a)){const i=r.get(a);i.count=(i.count||0)+(n.count||0),i.avgResponseTime=i.avgResponseTime&&n.avgResponseTime?(i.avgResponseTime+n.avgResponseTime)/2:i.avgResponseTime||n.avgResponseTime,i.tokens=(i.tokens||0)+(n.tokens||0)}else r.set(a,{...n})}),Array.from(r.values())}async fetchEnhancedMetricsData(t,r,n,a=[]){try{const[i,o,s]=await Promise.all([this.fetchTimeSeriesDataWithTableData("agent-runs","runs",t,r,n,a),this.fetchTimeSeriesDataWithTableData("tool-runs","runs",t,r,n,a),this.fetchTimeSeriesDataWithTableData("model-runs","runs",t,r,n,a)]);return{agents:i,tools:o,models:s}}catch(i){throw console.error("Error fetching enhanced metrics data:",i),i}}async transformRunsCardsWithEnhancedData(t,r,n,a,i=[]){const o=t.data.trends,s=m=>m>0?"increase":"decrease",[l,u,c,f]=await Promise.all([this.fetchTimeSeriesDataWithTableData("agent-runs","runs",r,n,a,i),this.fetchTimeSeriesDataWithTableData("tool-runs","runs",r,n,a,i),this.fetchTimeSeriesDataWithTableData("model-runs","runs",r,n,a,i),this.fetchTimeSeriesData("tool-runs","runs",r,n,a,i)]),d=this.transformTimeSeriesDataForToolRuns(f);return[{title:"Agent Runs",value:t.data.agentRuns,metricType:"agentRuns",icon:"bot",highlighted:!0,info:"Number of times the AI agents were executed to handle user requests",change:o!=null&&o.agentRuns?{value:Math.abs(o.agentRuns.changePercent),type:s(o.agentRuns.changePercent)}:void 0,view:{type:"chart",chart:{type:"line",title:"Agent Runs",data:l.chartData,dataKey:"agentRuns",color:"#0BA5EC",yAxisLabel:"Number of Agent Runs",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:r.split("T")[0],end:n.split("T")[0]}},table:{title:"Agent Runs",data:l.tableData,columns:[{key:"name",title:"Name",width:200,align:"left"},{key:"runs",title:"Runs",width:100,align:"right",formatter:m=>`${Math.floor(m/1e3)}k`},{key:"responseTime",title:"Response Time",width:120,align:"right"},{key:"tokens",title:"Tokens",width:100,align:"right",formatter:m=>`${Math.floor(m/1e3)}k`}]}},controls:{dropdown:{label:"All Agents",options:l.controlOptions,defaultValue:["all"],multiSelect:!0,searchable:!0},toggle:{chartView:!0,tableView:!0}}},{title:"Tool Runs",value:t.data.toolRuns.total,metricType:"toolRuns",icon:"wrench",info:"Number of times various tools were triggered by the AI agents to complete tasks",highlighted:!1,change:o!=null&&o.toolRuns?{value:Math.abs(o.toolRuns.changePercent.total),type:s(o.toolRuns.changePercent.total)}:void 0,view:{type:"chart",chart:{type:"line",title:"Tool Runs",data:d,yAxisLabel:"Number of Tool Runs",lines:[{dataKey:"toolRuns",color:"#667085",label:"Tool Runs"},{dataKey:"codeTools",color:"#F38744",label:"Code Tools"},{dataKey:"workflowTools",color:"#2970FF",label:"Workflow Tools"},{dataKey:"knowledgeTools",color:"#7A5AF8",label:"Knowledge"},{dataKey:"mcpTools",color:"#47CD89",label:"MCP Tools"}],height:300,showGrid:!0,showLegend:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:r.split("T")[0],end:n.split("T")[0]}},table:{title:"Tool Runs",data:u.tableData,columns:[{key:"name",title:"Name",width:200,align:"left"},{key:"type",title:"Type",width:150,align:"left"},{key:"runs",title:"Runs",width:100,align:"right",formatter:m=>`${Math.floor(m/1e3)}k`},{key:"responseTime",title:"Response Time",width:120,align:"right"}]}},controls:{dropdown:{label:"All Tools",options:u.controlOptions,defaultValue:["all"],multiSelect:!0,searchable:!0},toggle:{chartView:!0,tableView:!0}}},{title:"Model Runs",value:t.data.modelRuns,metricType:"modelRuns",icon:"cpu",highlighted:!1,info:"Number of times the AI agents called various language models to generate responses",change:o!=null&&o.modelRuns?{value:Math.abs(o.modelRuns.changePercent),type:s(o.modelRuns.changePercent)}:void 0,view:{type:"chart",chart:{type:"line",title:"Model Runs",data:c.chartData,dataKey:"modelRuns",color:"#47CD89",yAxisLabel:"Number of Model Runs",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:r.split("T")[0],end:n.split("T")[0]}},table:{title:"Model Runs",data:c.tableData,columns:[{key:"name",title:"Model Name",width:200,align:"left"},{key:"runs",title:"Runs",width:100,align:"right",formatter:m=>`${Math.floor(m/1e3)}k`},{key:"tokens",title:"Tokens",width:120,align:"right",formatter:m=>`${Math.floor(m/1e3)}k`},{key:"responseTime",title:"Response Time",width:120,align:"right"}]}},controls:{dropdown:{label:"All Models",options:c.controlOptions,defaultValue:["all"],multiSelect:!0,searchable:!0},toggle:{chartView:!0,tableView:!0}}}]}async transformUsageAnalyticsCardsWithEnhancedData(t,r,n,a,i=[]){const o=t.data.trends,s=d=>d>0?"increase":"decrease",[l,u,c,f]=await Promise.all([this.fetchTimeSeriesData("users","usage-analytics",r,n,a,i),this.fetchTimeSeriesData("sessions","usage-analytics",r,n,a,i),this.fetchTimeSeriesData("messages","usage-analytics",r,n,a,i),this.fetchTimeSeriesData("tokens","usage-analytics",r,n,a,i)]);return[{title:"Users",value:t.data.users,metricType:"users",icon:"users",highlighted:!0,info:"Number of unique users who interacted with the app",change:o!=null&&o.users?{value:Math.abs(o.users.changePercent),type:s(o.users.changePercent)}:void 0,view:{type:"chart",chart:{type:"line",title:"Total Users",data:this.transformTimeSeriesDataForMetric(l,"users"),dataKey:"users",color:"#4E5BA6",yAxisLabel:"Number of Users",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:r.split("T")[0],end:n.split("T")[0]}}}},{title:"Sessions",value:t.data.sessions,metricType:"sessions",icon:"activity",highlighted:!1,info:"Number of conversations initiated with the app",change:o!=null&&o.sessions?{value:Math.abs(o.sessions.changePercent),type:s(o.sessions.changePercent)}:void 0,view:{type:"chart",chart:{type:"line",title:"Total Sessions",data:this.transformTimeSeriesDataForMetric(u,"sessions"),dataKey:"sessions",color:"#0BA5EC",yAxisLabel:"Number of Sessions",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:r.split("T")[0],end:n.split("T")[0]}}}},{title:"Messages",value:t.data.messages.total,metricType:"messages",icon:"message-circle",info:"Total messages exchanged between users and the app",highlighted:!1,change:o!=null&&o.messages?{value:Math.abs(o.messages.changePercent.total),type:s(o.messages.changePercent.total)}:void 0,view:{type:"chart",chart:{type:"line",title:"Total Messages",data:this.transformTimeSeriesDataForMetric(c,"messages"),dataKey:"messages",color:"#E478FA",yAxisLabel:"Number of Messages",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:r.split("T")[0],end:n.split("T")[0]}}}},{title:"Tokens",value:t.data.tokens.total,metricType:"tokens",icon:"coins",info:"Total input and output tokens processed by the app for all interactions",highlighted:!1,change:o!=null&&o.tokens?{value:Math.abs(o.tokens.changePercent.total),type:s(o.tokens.changePercent.total)}:void 0,view:{type:"chart",chart:{type:"line",title:"Token Usage Breakdown",data:this.transformTimeSeriesDataForMetric(f,"tokens"),yAxisLabel:"Number of Tokens",lines:[{dataKey:"totalTokens",color:"#FF692E",label:"Total Tokens"},{dataKey:"inputTokens",color:"#5925DC",label:"Input Tokens"},{dataKey:"outputTokens",color:"#E478FA",label:"Output Tokens"}],height:300,showGrid:!0,showLegend:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:r.split("T")[0],end:n.split("T")[0]}}}}]}transformTimeSeriesDataForToolRuns(t){if(console.log("=== TOOL RUNS SPECIFIC TRANSFORM DEBUG ==="),console.log("Raw TimeSeriesResponse for tool runs:",JSON.stringify(t,null,2)),!t||!t.data||!Array.isArray(t.data))return console.error("Invalid time series data structure:",t),[];const r=t.data.map((n,a)=>{console.log(`Processing point ${a}:`,n);const i=new Date(n.timestamp),o=i.toISOString().split("T")[0],s=i.toLocaleDateString("en-US",{month:"short",day:"numeric"}),l=n.count||0;let u=0,c=0,f=0,d=0;if(n.listView&&Array.isArray(n.listView)){n.listView.forEach(v=>{const h=v.count||0,b=(v.toolType||v.tool_type||"").toLowerCase(),w=(v.toolName||v.tool_name||"").toLowerCase();console.log("Processing listView item:",{toolType:b,toolName:w,count:h});const x=b.toLowerCase();["inlinetool","inlineTool","tool","code","codetool","event","EVENT"].includes(b)||["inlinetool","tool","code","codetool","event"].includes(x)?u+=h:["toollibrary","toolLibrary","workflow","workflowtool"].includes(b)||["toollibrary","workflow","workflowtool"].includes(x)?c+=h:["knowledge","KNOWLEDGE","knowledgetool"].includes(b)||["knowledge","knowledgetool"].includes(x)?f+=h:["mcp","MCP","mcptool","mcpTool"].includes(b)||["mcp","mcptool"].includes(x)?d+=h:(console.log(`Unknown tool type '${b}' for tool '${w}', defaulting to code tools`),u+=h)}),console.log(`Calculated breakdown for point ${a}:`,{codeTools:u,workflowTools:c,knowledgeTools:f,mcpTools:d,total:u+c+f+d,expectedTotal:l});const g=u+c+f+d;if(Math.abs(g-l)>1){console.warn(`Breakdown total (${g}) doesn't match expected total (${l}) for point ${a}`);const v=l-g;u+=v,console.log(`Adjusted codeTools by ${v} to balance total`)}}else console.log(`No listView data for point ${a}, assigning all ${l} to codeTools`),u=l;const m={date:o,timestamp:s,formattedDate:s,toolRuns:l,value:l,count:l,codeTools:u,workflowTools:c,knowledgeTools:f,mcpTools:d,input_tokens:n.input_tokens||0,output_tokens:n.output_tokens||0,total_tokens:(n.input_tokens||0)+(n.output_tokens||0),inputTokens:n.input_tokens||0,outputTokens:n.output_tokens||0,totalTokens:(n.input_tokens||0)+(n.output_tokens||0),listView:n.listView||[],index:a};return console.log(`Transformed tool runs point ${a}:`,m),m});return console.log("Final tool runs transformed data:",JSON.stringify(r,null,2)),console.log("=== END TOOL RUNS SPECIFIC TRANSFORM DEBUG ==="),r}async fetchAllCardsData(t,r,n=[]){try{const[a,i]=await Promise.all([this.fetchUsageAnalyticsCards(t,r,void 0,n),this.fetchRunsCards(t,r,void 0,n)]);return{usageAnalytics:this.transformUsageAnalyticsCards(a),runs:this.transformRunsCards(i)}}catch(a){throw console.error("Error fetching cards data:",a),a}}async fetchAllCardsDataWithEnhancedViews(t,r,n,a=[]){try{const[i,o]=await Promise.all([this.fetchUsageAnalyticsCards(t,r,n,a),this.fetchRunsCards(t,r,n,a)]),[s,l]=await Promise.all([this.transformUsageAnalyticsCardsWithEnhancedData(i,t,r,n,a),this.transformRunsCardsWithEnhancedData(o,t,r,n,a)]);return{usageAnalytics:s,runs:l}}catch(i){throw console.error("Error fetching enhanced cards data:",i),i}}async fetchDefaultTimeSeriesData(t,r,n,a=[]){try{const[i,o]=await Promise.all([this.fetchTimeSeriesData("sessions","usage-analytics",t,r,n,a),this.fetchTimeSeriesData("agent-runs","runs",t,r,n,a)]);return{sessions:this.transformTimeSeriesData(i),agentRuns:this.transformTimeSeriesData(o)}}catch(i){throw console.error("Error fetching default time series data:",i),i}}transformListViewForSlider(t,r){return Array.isArray(t)?t.map((n,a)=>{const i={id:`${r}-${a+1}`,runs:n.count||0,responseTime:n.avgResponseTime?n.avgResponseTime<1e3?`${Math.round(n.avgResponseTime)}ms`:`${(n.avgResponseTime/1e3).toFixed(2)}s`:"0ms",successRate:n.successRate?`${Math.round(n.successRate)}%`:void 0,tokens:n.totalTokens||n.tokens||0,icon:n.icon||n.tool_icon||void 0,aiModel:"gpt-4o"};switch(r){case"agentRuns":return{...i,name:n.agentName||`Agent ${a+1}`,type:"Agent",aiModel:this.extractAIModel(n)||"gpt-4o"};case"toolRuns":return{...i,name:n.toolName||n.tool_name||`Tool ${a+1}`,type:n.type||n.toolType||n.tool_type||"Code Tool",toolType:n.toolType||n.tool_type,aiModel:this.extractAIModel(n)||"gpt-4o"};case"modelRuns":return{...i,name:n.modelName||`Model ${a+1}`,modelName:n.modelName,provider:n.provider,type:n.provider||"Model",aiModel:n.modelName||n.model||"gpt-4o"};default:return{...i,name:`Item ${a+1}`,type:"Unknown",aiModel:"gpt-4o"}}}):(console.warn("Invalid listView data for slider:",t),[])}extractAIModel(t){if(t.modelName)return t.modelName;if(t.model)return t.model;if(t.llmModel)return t.llmModel;if(t.aiModel)return t.aiModel;const r=["gpt-4o","gpt-4o-mini","claude-3-5-haiku"];return r[Math.floor(Math.random()*r.length)]}static getDateRange(t=7){const r=new Date,n=new Date;return n.setDate(r.getDate()-t),{fromTimestamp:n.toISOString(),toTimestamp:r.toISOString()}}static getTimeDimension(t,r){const n=new Date(t),a=new Date(r),i=new Date(n.getFullYear(),n.getMonth(),n.getDate()),o=new Date(a.getFullYear(),a.getMonth(),a.getDate()),s=o.getTime()-i.getTime(),l=s/(1e3*60*60*24),u=i.toISOString().split("T")[0],c=o.toISOString().split("T")[0],f=u===c,d=new Date(n.getFullYear(),n.getMonth(),n.getDate()),m=f&&Math.abs(n.getTime()-d.getTime())<1e3,g=Math.abs(a.getTime()-n.getTime()),v=g<60*1e3;return console.log("🕐 TimeDimension calculation:",{fromTimestamp:t,toTimestamp:r,fromDateStr:u,toDateStr:c,diffInMs:s,diffInDays:l,isSameCalendarDay:f,isTodayPattern:m,timeDiffInMs:g,isVeryClose:v,fromStartOfDay:d.toISOString(),recommended:f||m||v||l<=1?"hour":l<=31?"day":l<=90?"week":"month"}),f||m||v||l<=1?"hour":"day"}getAvailableMetrics(){return{"usage-analytics":["sessions","messages","users","tokens"],runs:["agent-runs","model-runs","tool-runs"]}}}const R0=({config:e,className:t,isLoading:r,context:n})=>{const{type:a,chart:i,table:o,layout:s="vertical"}=e,[l,u]=S.useState({isOpen:!1,date:"",metricType:"agentRuns",data:[],totalRuns:0}),c=(v,h)=>{console.log("Chart data point clicked in ViewRenderer:",{chartData:v,date:h,context:n});const b=n==null?void 0:n.metricType;if(!b||!["agentRuns","toolRuns","modelRuns"].includes(b)){console.log("Slider not applicable for metric type:",b);return}const w=v.listView||[];console.log("ListView data for clicked date:",w);const T=new Yt({baseUrl:"",projectId:"",environment:""}).transformListViewForSlider(w,b),y=v[b]||v.count||0;console.log("Opening slider with data:",{date:h,metricType:b,sliderData:T,totalRuns:y}),u({isOpen:!0,date:h,metricType:b,data:T,totalRuns:y})},f=()=>{u(v=>({...v,isOpen:!1}))},d=()=>i?(console.log("ViewRenderer - Chart config:",i),console.log("ViewRenderer - Chart data:",i.data),console.log("ViewRenderer - Context:",n),p.jsx("div",{className:"flex-1",children:p.jsx(E0,{config:i,isLoading:r,onDataPointClick:c})})):null,m=()=>o?(n==null?void 0:n.metricType)==="agentRuns"?p.jsx("div",{className:"flex-1 min-h-[380px]",children:p.jsx(k0,{data:o.data})}):(n==null?void 0:n.metricType)==="toolRuns"?p.jsx("div",{className:"flex-1 min-h-[380px]",children:p.jsx(N0,{data:o.data})}):(n==null?void 0:n.metricType)==="modelRuns"?p.jsx("div",{className:"flex-1 min-h-[380px]",children:p.jsx(M0,{data:o.data})}):p.jsx("div",{className:"flex-1 min-h-[380px]",children:p.jsx(C0,{config:o})}):null,g=()=>{switch(a){case"chart":return d();case"table":return m();case"mixed":return p.jsxs("div",{className:le("flex gap-6",s==="horizontal"?"flex-row":"flex-col"),children:[d(),m()]});default:return p.jsxs("div",{className:"p-4 text-center text-gray-500",children:["Unsupported view type: ",a]})}};return p.jsxs(p.Fragment,{children:[p.jsx("div",{className:le("w-full",t),children:g()}),p.jsx(D0,{isOpen:l.isOpen,onClose:f,date:l.date,metricType:l.metricType,data:l.data,totalRuns:l.totalRuns})]})},Ns=({options:e,value:t,placeholder:r="Select an option",onChange:n,className:a,disabled:i=!1})=>{const[o,s]=S.useState(!1),[l,u]=S.useState(t||""),c=S.useRef(null),f=e.find(g=>g.value===l);S.useEffect(()=>{const g=v=>{c.current&&!c.current.contains(v.target)&&s(!1)};return o&&document.addEventListener("mousedown",g),()=>{document.removeEventListener("mousedown",g)}},[o]);const d=g=>{i||(u(g),s(!1),n==null||n(g))},m=()=>{i||s(!o)};return p.jsxs("div",{ref:c,className:le("relative",a),children:[p.jsxs("button",{type:"button",className:le("flex h-[40px] text-left w-full items-center rounded-lg border border-gray-300 bg-white px-[14px] py-[10px] medium shadow-none outline-none focus-visible:border-ring focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-gray-25 transition-colors",a),onClick:m,disabled:i,children:[p.jsxs("div",{className:"flex items-center gap-[8px] w-full",children:[p.jsx("span",{className:"text-xs font-medium text-gray-400 uppercase",children:"ENV"}),p.jsx("span",{className:le("truncate w-full",!f&&"text-gray-700 font-medium text-sm"),children:f?f.label:r})]}),p.jsx(fr,{className:le("h-[16px] w-[16px] text-gray-400 transition-transform duration-200",o&&"rotate-180")})]}),o&&!i&&p.jsx("div",{className:"absolute p-[4px] w-full top-full left-0 z-50 mt-1 bg-popover max-h-[300px] overflow-y-auto text-popover-foreground overflow-x-hidden overflow-y-auto rounded-md border shadow-md",children:e.map(g=>{const v=l===g.value;return p.jsxs("div",{role:"option",className:"relative group",children:[p.jsx("button",{className:le("focus:bg-gray-50 rounded-[4px] hover:bg-gray-50 focus:text-accent-foreground relative flex w-full cursor-pointer select-none items-center px-[14px] py-[10px] text-sm text-left outline-none transition-colors",g.disabled?"opacity-50 cursor-not-allowed text-gray-400":v?"bg-blue-50 text-blue-900 font-medium":"text-gray-900 hover:bg-gray-50"),onClick:()=>!g.disabled&&d(g.value),disabled:g.disabled,children:p.jsx("span",{className:"block whitespace-nowrap w-full",children:g.label})}),g.label.length>25&&p.jsx("div",{className:"absolute left-full top-0 ml-2 z-[60] opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none",children:p.jsxs("div",{className:"bg-gray-900 text-white text-xs rounded-md px-3 py-2 whitespace-nowrap shadow-lg",children:[g.label,p.jsx("div",{className:"absolute left-0 top-1/2 transform -translate-x-full -translate-y-1/2 w-0 h-0 border-t-4 border-b-4 border-r-4 border-transparent border-r-gray-900"})]})})]},g.value)})})]})},B0=({options:e,value:t,defaultValue:r,placeholder:n="Select...",multiSelect:a=!1,searchable:i=!1,onChange:o,className:s,maxItems:l=100,maxLabelLength:u=30})=>{const[c,f]=S.useState(!1),[d,m]=S.useState(""),[g,v]=S.useState(()=>{const $=t||r;return a?Array.isArray($)?$:$?[$]:[]:$?[Array.isArray($)?$[0]:$]:[]}),h=S.useRef(null);S.useEffect(()=>{const $=P=>{h.current&&!h.current.contains(P.target)&&f(!1)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[]);const b=($,P=u)=>$.length<=P?$:$.substring(0,P)+"...",w=i?e.filter($=>$.label.toLowerCase().includes(d.toLowerCase())):e,x=w.slice(0,l),T=w.length>l,y=$=>{let P;if(a){if($==="all"){A();return}if(g.includes($))P=g.filter(F=>F!==$),P=P.filter(F=>F!=="all");else{P=g.filter(R=>R!=="all"),P=[...P,$];const F=w.filter(R=>R.value!=="all").map(R=>R.value),N=P.filter(R=>R!=="all");N.length===F.length&&(P=["all",...N])}}else P=[$],f(!1);v(P);const _=a?P:P[0]||"";o==null||o(_)},O=()=>{if(!a)return{checked:!1,indeterminate:!1};const $=w.filter(_=>_.value!=="all").map(_=>_.value),P=g.filter(_=>_!=="all"&&$.includes(_));return g.includes("all")&&P.length===0?{checked:!1,indeterminate:!1}:P.length===0?{checked:!1,indeterminate:!1}:P.length===$.length?{checked:!0,indeterminate:!1}:{checked:!1,indeterminate:!0}},A=()=>{if(!a)return;const $=O(),P=w.filter(_=>_.value!=="all").map(_=>_.value);if($.checked)v(["all"]),o==null||o(["all"]);else{const _=["all",...P];v(_),o==null||o(_)}},j=()=>{v(["all"]),o==null||o(a?["all"]:"all")},C=()=>{if(!a){if(g.length===0)return n;const F=e.find(N=>N.value===g[0]);return(F==null?void 0:F.label)||n}const $=g.filter(F=>F!=="all"),P=g.includes("all");if($.length===0)return n;if($.length===1){const F=e.find(N=>N.value===$[0]);return(F==null?void 0:F.label)||n}const _=e.filter(F=>F.value!=="all").length;return $.length===_?"All selected":`${$.length} selected`};return p.jsxs("div",{className:le("relative",s),ref:h,children:[p.jsxs("button",{type:"button",onClick:()=>f(!c),className:le("w-full flex items-center justify-between px-[12px] py-[8px] text-left text-xs","border border-gray-300 rounded-md bg-white hover:bg-gray-50","focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500","transition-colors duration-150"),children:[p.jsx("span",{className:le("truncate",g.length===0&&"text-gray-500"),children:C()}),p.jsx(fr,{className:le("w-[16px] h-[16px] text-gray-400 transition-transform duration-150",c&&"transform rotate-180")})]}),c&&p.jsxs("div",{className:"absolute z-50 min-w-[300px] w-max max-w-lg mt-[4px] bg-white border border-gray-200 rounded-md shadow-lg max-h-80 overflow-hidden",children:[i&&p.jsx("div",{className:"p-[12px] border-b border-gray-100",children:p.jsxs("div",{className:"relative",children:[p.jsx(kf,{className:"absolute left-[12px] top-1/2 transform -translate-y-1/2 w-[16px] h-[16px] text-gray-400"}),p.jsx("input",{type:"text",placeholder:`Search ${n.toLowerCase()}...`,value:d,onChange:$=>m($.target.value),className:"w-full pl-[36px] pr-[12px] py-[8px] text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"})]})}),a&&p.jsxs("div",{className:"flex items-center justify-between px-[12px] py-[8px] border-b border-gray-100 bg-gray-50",children:[p.jsxs("button",{type:"button",onClick:A,className:"flex items-center text-xs font-medium text-gray-700 hover:text-gray-900",children:[p.jsx("div",{className:le("flex items-center justify-center w-[16px] h-[16px] mr-[8px] border transition-colors duration-150",(()=>{const $=O();return $.indeterminate||$.checked?"bg-blue-600 border-blue-600 text-white":"border-gray-300 bg-white"})()),children:(()=>{const $=O();return $.indeterminate?p.jsx("div",{className:"w-[8px] h-[4px] bg-white rounded"}):$.checked?p.jsx("svg",{className:"w-[12px] h-[12px]",fill:"currentColor",viewBox:"0 0 20 20",children:p.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})}):null})()}),"Select all"]}),p.jsx("button",{type:"button",onClick:j,className:"text-sm font-medium text-blue-600 hover:text-blue-800",children:"Clear"})]}),p.jsxs("div",{className:"max-h-60 overflow-y-auto",children:[x.length===0?p.jsx("div",{className:"px-[12px] py-[16px] text-sm text-gray-500 text-center",children:"No options found"}):x.map($=>{let P;return $.value==="all"?null:(P=g.includes($.value),p.jsxs("div",{className:"relative group",children:[p.jsxs("div",{onClick:()=>y($.value),className:le("flex items-center px-[12px] py-[8px] cursor-pointer hover:bg-gray-50","transition-colors duration-150",P&&"bg-gray-50"),children:[a?p.jsx("div",{className:le("flex items-center justify-center w-[16px] h-[16px] mr-[12px] border","transition-colors duration-150",P?"bg-blue-600 border-blue-600 text-white":"border-gray-300 bg-white"),children:P&&p.jsx("svg",{className:"w-[12px] h-[12px]",fill:"currentColor",viewBox:"0 0 20 20",children:p.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})}):p.jsx("div",{className:le("w-[16px] h-[16px] mr-[12px] rounded-full border-2 transition-colors duration-150",P?"border-blue-600 bg-blue-600":"border-gray-300"),children:P&&p.jsx("div",{className:"w-full h-full rounded-full bg-white scale-50"})}),p.jsx("span",{className:le("flex-1 text-xs whitespace-nowrap truncate",P?"font-medium text-gray-700":"text-gray-500"),children:b($.label)})]}),$.label.length>u&&p.jsx("div",{className:"absolute left-full top-1/2 transform -translate-y-1/2 ml-2 z-[80] opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none",children:p.jsxs("div",{className:"bg-gray-900 text-white text-xs rounded-md px-[12px] py-[8px] shadow-lg max-w-xs break-words whitespace-normal",children:[$.label,p.jsx("div",{className:"absolute left-0 top-1/2 transform -translate-x-full -translate-y-1/2 w-0 h-0 border-t-4 border-b-4 border-r-4 border-transparent border-r-gray-900"})]})})]},$.value))}),T&&p.jsxs("div",{className:"px-[12px] py-[8px] text-xs text-gray-500 bg-gray-50 border-t border-gray-100",children:[p.jsxs("div",{className:"text-center font-medium",children:["+",w.length-l," more items"]}),i&&p.jsx("div",{className:"text-center mt-1 text-gray-400",children:"Use search above to find specific items"})]})]})]})]})},F0=({config:e,className:t})=>{var s;const{dropdown:r,buttons:n,toggle:a}=e,i=l=>{const u=l.toLowerCase();return u.includes("agent")?"agent":u.includes("tool")?"workflowtool":"app"},o=l=>{const u=l.toLowerCase();return u.includes("agent")?{maxItems:50,maxLabelLength:25}:u.includes("tool")?{maxItems:30,maxLabelLength:20}:{maxItems:40,maxLabelLength:25}};return p.jsxs("div",{className:le("flex items-center gap-3",t),children:[r&&p.jsx(p.Fragment,{children:r.multiSelect?p.jsx(B0,{options:r.options,value:r.defaultValue,placeholder:r.label,multiSelect:r.multiSelect,searchable:r.searchable,onChange:r.onChange,className:"w-48",iconSource:i(r.label),maxItems:o(r.label).maxItems,maxLabelLength:o(r.label).maxLabelLength}):p.jsx(Ns,{options:r.options,value:Array.isArray(r.defaultValue)?r.defaultValue[0]:r.defaultValue||((s=r.options[0])==null?void 0:s.value),placeholder:r.label,onChange:l=>{var u;return(u=r.onChange)==null?void 0:u.call(r,l)},className:"w-48"})}),n&&n.length>0&&p.jsx("div",{className:"flex items-center border border-gray-200 rounded-lg overflow-hidden",children:n.map((l,u)=>p.jsx("button",{onClick:()=>{var c;return(c=l.onClick)==null?void 0:c.call(l,l.value)},className:le("px-[12px] py-[8px] text-xs font-medium transition-colors","hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-inset",l.active?"bg-white text-gray-900 shadow-[0 1px 3px 0 rgba(16, 24, 40, 0.08), 0 1px 2px 0 rgba(16, 24, 40, 0.08)]":"text-gray-500 bg-white",u>0&&"border-l border-gray-200"),children:l.icon&&p.jsx("span",{className:"mr-[8px]",children:l.icon})},l.value))}),a&&p.jsxs("div",{className:"flex items-center gap-[4px] border border-gray-200 bg-gray-50 overflow-hidden p-[2px] rounded-[6px]",children:[p.jsx("button",{onClick:()=>{var l;return(l=a.onToggle)==null?void 0:l.call(a,"chart")},className:le("px-[12px] py-[8px] rounded-[4px] text-xs font-medium transition-colors flex items-center gap-2","hover:bg-white ",a.chartView?"bg-white text-gray-900 shadow-md":"text-gray-500 bg-white"),children:p.jsx(Sb,{className:"w-[16px] h-[16px]"})}),p.jsx("button",{onClick:()=>{var l;return(l=a.onToggle)==null?void 0:l.call(a,"table")},className:le("px-[12px] rounded-[4px] py-[8px] text-xs font-medium transition-colors flex items-center gap-2","hover:bg-white ",a.tableView?"bg-white text-gray-900 shadow-md":"text-gray-500 bg-white"),children:p.jsx(Mb,{className:"w-[16px] h-[16px]"})})]})]})},U0=({section:e,className:t,isLoading:r,isChartLoading:n,onMetricClick:a})=>{var Z;const{id:i,title:o,description:s,metrics:l,view:u,controls:c,layout:f}=e,[d,m]=S.useState(u.type),[g,v]=S.useState("chart"),h=()=>i==="usage-analytics"?"users":i==="runs"?"agentRuns":"users",[b,w]=S.useState(h()),[x,T]=S.useState("all"),y=E=>{var z,H,I,V,X;const B=j();(z=B==null?void 0:B.controls)!=null&&z.toggle?(v(E),(I=(H=B.controls.toggle).onToggle)==null||I.call(H,E)):(m(E),(X=(V=c==null?void 0:c.toggle)==null?void 0:V.onToggle)==null||X.call(V,E))},O=E=>{var H,I;const B=E.metricType||E.title.toLowerCase();w(B);const z=l.find(V=>(V.metricType||V.title.toLowerCase())===B);(I=(H=z==null?void 0:z.controls)==null?void 0:H.dropdown)!=null&&I.multiSelect?T(["all"]):T("all"),a==null||a(E)},A=E=>{var z,H,I;T(E);const B=l.find(V=>(V.metricType||V.title.toLowerCase())===b);(I=(H=(z=B==null?void 0:B.controls)==null?void 0:z.dropdown)==null?void 0:H.onChange)==null||I.call(H,E)},j=()=>l.find(E=>(E.metricType||E.title.toLowerCase())===b)||null,C=E=>Array.isArray(E)?E.filter(z=>z!=="all").length>0:E!=="all",$=E=>Array.isArray(E)?E.filter(B=>B!=="all"):E!=="all"?[E]:[],P=E=>{var I,V,X,re,L,W,G,J,M;const B=((V=(I=E.view)==null?void 0:I.chart)==null?void 0:V.data)||((X=u.chart)==null?void 0:X.data)||[];if(!C(x))return B;const z=E.metricType,H=$(x);if(H.length===1){const Q=H[0],K=j(),se=(W=(L=(re=K==null?void 0:K.controls)==null?void 0:re.dropdown)==null?void 0:L.options)==null?void 0:W.find(fe=>fe.value===Q),ne=se==null?void 0:se.label;return console.log("🔍 Filtering chart data:",{metricType:z,singleFilter:Q,selectedLabel:ne,baseDataSample:B[0]}),B.map(fe=>{let ue=0;return fe.listView&&Array.isArray(fe.listView)&&(ue=fe.listView.filter(Ge=>z==="agentRuns"&&Ge.agentName?Ge.agentName===ne||Ge.agentName.toLowerCase()===(ne==null?void 0:ne.toLowerCase()):z==="toolRuns"&&Ge.toolName?Ge.toolName===ne||Ge.toolName.toLowerCase()===(ne==null?void 0:ne.toLowerCase()):z==="modelRuns"&&Ge.modelName?Ge.modelName===ne||Ge.modelName.toLowerCase()===(ne==null?void 0:ne.toLowerCase()):!1).reduce((Ge,ut)=>Ge+(ut.count||0),0)),console.log("📊 Filtered value for",ne,":",ue),{...fe,[z]:ue}})}if(H.length>1){const Q=j(),se=(((M=(J=(G=Q==null?void 0:Q.controls)==null?void 0:G.dropdown)==null?void 0:J.options)==null?void 0:M.filter(ne=>H.includes(ne.value)))||[]).map(ne=>ne.label);return B.map(ne=>{let fe=0;return ne.listView&&Array.isArray(ne.listView)&&(fe=ne.listView.filter(Ee=>z==="agentRuns"&&Ee.agentName?se.some(Oe=>Ee.agentName===Oe||Ee.agentName.toLowerCase()===(Oe==null?void 0:Oe.toLowerCase())):z==="toolRuns"&&Ee.toolName?se.some(Oe=>Ee.toolName===Oe||Ee.toolName.toLowerCase()===(Oe==null?void 0:Oe.toLowerCase())):z==="modelRuns"&&Ee.modelName?se.some(Oe=>Ee.modelName===Oe||Ee.modelName.toLowerCase()===(Oe==null?void 0:Oe.toLowerCase())):!1).reduce((Ee,Oe)=>Ee+(Oe.count||0),0)),{...ne,[z]:fe}})}return B},_=E=>{var I;if(!((I=E.view)!=null&&I.chart))return null;const B=P(E),z=()=>{var X,re,L,W,G,J;if(!C(x)||!((X=E.controls)!=null&&X.dropdown))return((L=(re=E.view)==null?void 0:re.chart)==null?void 0:L.title)||E.title;const V=$(x);if(V.length===1){const M=(W=E.controls.dropdown.options)==null?void 0:W.find(Q=>Q.value===V[0]);return M?`${M.label}`:((J=(G=E.view)==null?void 0:G.chart)==null?void 0:J.title)||E.title}return`${V.length} selected`},H=$(x);return E.metricType==="toolRuns"&&H.length===1?{...E.view.chart,data:B,title:z(),lines:void 0,dataKey:"toolRuns",color:"#f97316",showLegend:!1}:E.metricType==="modelRuns"&&H.length===1?{...E.view.chart,data:B,title:z(),dataKey:"modelRuns",color:"#10b981",showLegend:!1}:{...E.view.chart,data:B,title:z()}},F=(E,B)=>{if(!C(x))return E;const z=$(x);if(z.length===1){const H=z[0];if(i==="runs"&&B==="agentRuns")return E.map(I=>({...I,agentRuns:I[H]||0}));if(i==="runs"&&B==="toolRuns")return E.map(I=>({...I,toolRuns:I[H.replace(/[-]/g,"")]||0}));if(i==="runs"&&B==="modelRuns")return E.map(I=>({...I,modelRuns:I[H.replace(/[-\.]/g,"")]||0}))}return E},N=E=>{var I;const B=((I=u.chart)==null?void 0:I.data)||[],z=F(B,E),H=V=>{var re,L;if(!C(x))return V;const X=$(x);if(X.length===1){const W=(L=(re=c==null?void 0:c.dropdown)==null?void 0:re.options)==null?void 0:L.find(G=>G.value===X[0]);return W?`${W.label}`:V}return`${X.length} selected`};switch(E){case"users":return{type:"line",title:"Total Users",data:B,dataKey:"users",color:"#8b5cf6",yAxisLabel:"Number of Users",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}};case"sessions":return{type:"line",title:"Total Sessions",data:B,dataKey:"sessions",color:"#06b6d4",yAxisLabel:"Number of Sessions",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}};case"messages":return{type:"line",title:"Total Messages",data:B,dataKey:"messages",color:"#ec4899",yAxisLabel:"Number of Messages",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}};case"tokens":return{type:"line",title:"Token Usage Breakdown",data:B,yAxisLabel:"Number of Tokens",lines:[{dataKey:"totalTokens",color:"#f59e0b",label:"Total Tokens"},{dataKey:"inputTokens",color:"#3b82f6",label:"Input Tokens"},{dataKey:"outputTokens",color:"#ec4899",label:"Output Tokens"}],height:300,showGrid:!0,showLegend:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}};case"agentRuns":return{type:"line",title:H("Agent Runs"),data:z,dataKey:"agentRuns",color:"#06b6d4",yAxisLabel:"Number of Agent Runs",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}};case"toolRuns":return $(x).length===1?{type:"line",title:H("Tool Runs"),data:F(B,"toolRuns"),dataKey:"toolRuns",color:"#f97316",yAxisLabel:"Number of Tool Runs",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}}:{type:"line",title:"Tool Runs",data:z,yAxisLabel:"Number of Tool Runs",lines:[{dataKey:"toolRuns",color:"#06b6d4",label:"Tool Runs"},{dataKey:"codeTools",color:"#f97316",label:"Code Tools"},{dataKey:"workflowTools",color:"#10b981",label:"Workflow Tools"},{dataKey:"knowledgeTools",color:"#8b5cf6",label:"Knowledge"},{dataKey:"mcpTools",color:"#ef4444",label:"MCP Tools"}],height:300,showGrid:!0,showLegend:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}};case"modelRuns":return $(x).length===1?{type:"line",title:H("Model Runs"),data:F(B,"modelRuns"),dataKey:"modelRuns",color:"#10b981",yAxisLabel:"Number of Model Runs",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}}:{type:"line",title:H("Model Runs"),data:z,dataKey:"modelRuns",color:"#10b981",yAxisLabel:"Number of Model Runs",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}};default:return null}},R=(()=>{const E=j();return E!=null&&E.controls?{...E.controls,dropdown:E.controls.dropdown?{...E.controls.dropdown,onChange:A}:void 0,toggle:E.controls.toggle?{...E.controls.toggle,chartView:g==="chart",tableView:g==="table",onToggle:y}:void 0}:c?{...c,dropdown:c.dropdown?{...c.dropdown,onChange:A}:void 0,toggle:c.toggle?{...c.toggle,chartView:d==="chart",tableView:d==="table",onToggle:y}:void 0}:void 0})(),U=(()=>{var z,H,I,V,X,re,L,W,G,J;const E=j();if(E!=null&&E.view){if((z=E.controls)!=null&&z.toggle){if(g==="table"&&E.view.table){let Q=E.view.table.data;if(E.metricType==="agentRuns"&&C(x)){const K=$(x);if(K.length>0){const se=((V=(I=(H=E.controls)==null?void 0:H.dropdown)==null?void 0:I.options)==null?void 0:V.filter(ne=>K.includes(ne.value)))||[];se.length>0&&(Q=Q.filter(ne=>se.some(fe=>ne.name===fe.label||ne.name&&ne.name.toLowerCase().includes(fe.label.toLowerCase()))))}}if(E.metricType==="toolRuns"&&C(x)){const K=$(x);if(K.length>0){const se=((L=(re=(X=E.controls)==null?void 0:X.dropdown)==null?void 0:re.options)==null?void 0:L.filter(ne=>K.includes(ne.value)))||[];se.length>0&&(Q=Q.filter(ne=>se.some(fe=>ne.name===fe.label||ne.name&&ne.name.toLowerCase().includes(fe.label.toLowerCase()))))}}if(E.metricType==="modelRuns"&&C(x)){const K=$(x);if(K.length>0){const se=((J=(G=(W=E.controls)==null?void 0:W.dropdown)==null?void 0:G.options)==null?void 0:J.filter(ne=>K.includes(ne.value)))||[];se.length>0&&(Q=Q.filter(ne=>se.some(fe=>ne.name===fe.label||ne.name&&ne.name.toLowerCase().includes(fe.label.toLowerCase()))))}}return{type:"table",table:{...E.view.table,data:Q}}}else if(g==="chart"&&E.view.chart)return{type:"chart",chart:_(E)||E.view.chart}}const M=_(E);return M?{...E.view,chart:M}:E.view}const B=N(b);return B?{type:"chart",chart:B}:{...u,type:d}})(),q=()=>l.map(E=>{const B=E.metricType||E.title.toLowerCase();return{...E,highlighted:E.highlighted||B===b}});return p.jsxs("div",{className:le("bg-white flex flex-col gap-[16px] rounded-lg border border-gray-200 py-[16px] px-[24px]",t),style:{gridColumn:f!=null&&f.span?`span ${f.span}`:void 0,order:f==null?void 0:f.order},children:[o&&p.jsxs("div",{className:"w-full",children:[p.jsx("h1",{className:"text-md font-medium text-gray-700",children:o}),s&&p.jsx("p",{className:"text-xs text-gray-500",children:s})]}),p.jsx("div",{className:"flex flex-col sm:flex-row gap-[16px]",children:r?p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"flex-1",children:p.jsx(bi,{})}),p.jsx("div",{className:"flex-1",children:p.jsx(bi,{})}),p.jsx("div",{className:"flex-1",children:p.jsx(bi,{})}),p.jsx("div",{className:"flex-1",children:p.jsx(bi,{})})]}):q().map((E,B)=>p.jsx("div",{className:"flex-1",children:p.jsx(Wf,{data:E,onClick:O,isFirst:B===0})},`${i}-metric-${B}`))}),p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsx("div",{children:j()&&p.jsx("h3",{className:"text-md font-medium text-gray-700",children:(Z=j())==null?void 0:Z.title})}),R&&p.jsx(F0,{config:R})]}),p.jsx(R0,{config:U,isLoading:r||n,context:{sectionId:i,metricType:b}})]})},df=S.forwardRef(({className:e,variant:t="default",size:r="md",children:n,...a},i)=>{const o="inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",s={default:"bg-blue-600 hover:bg-blue-700 focus:bg-blue-700 focus:shadow-sm text-white py-2 px-3",outline:"border-gray-300 border bg-white text-gray-700 hover:text-gray-800 hover:bg-gray-50 focus:bg-gray-50 focus:shadow-sm",ghost:"border border-error-600 bg-error-500 text-white hover:border-error-600 hover:bg-error-600"},l={sm:"h-[32px] rounded-md gap-1.5 px-[14px] py-[10px]",md:"h-[40px] rounded-md px-[14px] py-[10px]",lg:"h-[48px] rounded-md px-[16px] py-[12px]"};return p.jsx("button",{className:le(o,s[t],l[r],e),ref:i,...a,children:n})});df.displayName="Button";function Ms(e){"@babel/helpers - typeof";return Ms=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},Ms(e)}function Ct(e){if(e===null||e===!0||e===!1)return NaN;var t=Number(e);return isNaN(t)?t:t<0?Math.ceil(t):Math.floor(t)}function Le(e,t){if(t.length<e)throw new TypeError(e+" argument"+(e>1?"s":"")+" required, but only "+t.length+" present")}function Ve(e){Le(1,arguments);var t=Object.prototype.toString.call(e);return e instanceof Date||Ms(e)==="object"&&t==="[object Date]"?new Date(e.getTime()):typeof e=="number"||t==="[object Number]"?new Date(e):((typeof e=="string"||t==="[object String]")&&typeof console<"u"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function YB(e,t){Le(2,arguments);var r=Ve(e),n=Ct(t);return isNaN(n)?new Date(NaN):(n&&r.setDate(r.getDate()+n),r)}function pf(e,t){Le(2,arguments);var r=Ve(e),n=Ct(t);if(isNaN(n))return new Date(NaN);if(!n)return r;var a=r.getDate(),i=new Date(r.getTime());i.setMonth(r.getMonth()+n+1,0);var o=i.getDate();return a>=o?i:(r.setFullYear(i.getFullYear(),i.getMonth(),a),r)}function XB(e,t){Le(2,arguments);var r=Ve(e).getTime(),n=Ct(t);return new Date(r+n)}var ZB={};function wi(){return ZB}function JB(e,t){var r,n,a,i,o,s;Le(1,arguments);var l=wi(),u=Ct((r=(n=(a=(i=void 0)!==null&&i!==void 0?i:void 0)!==null&&a!==void 0?a:l.weekStartsOn)!==null&&n!==void 0?n:(o=l.locale)===null||o===void 0||(s=o.options)===null||s===void 0?void 0:s.weekStartsOn)!==null&&r!==void 0?r:0);if(!(u>=0&&u<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var c=Ve(e),f=c.getDay(),d=(f<u?7:0)+f-u;return c.setDate(c.getDate()-d),c.setHours(0,0,0,0),c}function QB(e){var t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),e.getTime()-t.getTime()}function aa(e){Le(1,arguments);var t=Ve(e);return t.setHours(0,0,0,0),t}function Oi(e,t){Le(2,arguments);var r=aa(e),n=aa(t);return r.getTime()===n.getTime()}function eF(e){return Le(1,arguments),e instanceof Date||Ms(e)==="object"&&Object.prototype.toString.call(e)==="[object Date]"}function tF(e){if(Le(1,arguments),!eF(e)&&typeof e!="number")return!1;var t=Ve(e);return!isNaN(Number(t))}function rF(e){Le(1,arguments);var t=Ve(e);return t.setHours(23,59,59,999),t}function nF(e){Le(1,arguments);var t=Ve(e);return t.setDate(1),t.setHours(0,0,0,0),t}function aF(e,t){Le(2,arguments);var r=Ct(t);return XB(e,-r)}var iF=864e5;function oF(e){Le(1,arguments);var t=Ve(e),r=t.getTime();t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0);var n=t.getTime(),a=r-n;return Math.floor(a/iF)+1}function Ds(e){Le(1,arguments);var t=1,r=Ve(e),n=r.getUTCDay(),a=(n<t?7:0)+n-t;return r.setUTCDate(r.getUTCDate()-a),r.setUTCHours(0,0,0,0),r}function W0(e){Le(1,arguments);var t=Ve(e),r=t.getUTCFullYear(),n=new Date(0);n.setUTCFullYear(r+1,0,4),n.setUTCHours(0,0,0,0);var a=Ds(n),i=new Date(0);i.setUTCFullYear(r,0,4),i.setUTCHours(0,0,0,0);var o=Ds(i);return t.getTime()>=a.getTime()?r+1:t.getTime()>=o.getTime()?r:r-1}function sF(e){Le(1,arguments);var t=W0(e),r=new Date(0);r.setUTCFullYear(t,0,4),r.setUTCHours(0,0,0,0);var n=Ds(r);return n}var lF=6048e5;function uF(e){Le(1,arguments);var t=Ve(e),r=Ds(t).getTime()-sF(t).getTime();return Math.round(r/lF)+1}function Is(e,t){var r,n,a,i,o,s,l,u;Le(1,arguments);var c=wi(),f=Ct((r=(n=(a=(i=t==null?void 0:t.weekStartsOn)!==null&&i!==void 0?i:t==null||(o=t.locale)===null||o===void 0||(s=o.options)===null||s===void 0?void 0:s.weekStartsOn)!==null&&a!==void 0?a:c.weekStartsOn)!==null&&n!==void 0?n:(l=c.locale)===null||l===void 0||(u=l.options)===null||u===void 0?void 0:u.weekStartsOn)!==null&&r!==void 0?r:0);if(!(f>=0&&f<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var d=Ve(e),m=d.getUTCDay(),g=(m<f?7:0)+m-f;return d.setUTCDate(d.getUTCDate()-g),d.setUTCHours(0,0,0,0),d}function z0(e,t){var r,n,a,i,o,s,l,u;Le(1,arguments);var c=Ve(e),f=c.getUTCFullYear(),d=wi(),m=Ct((r=(n=(a=(i=t==null?void 0:t.firstWeekContainsDate)!==null&&i!==void 0?i:t==null||(o=t.locale)===null||o===void 0||(s=o.options)===null||s===void 0?void 0:s.firstWeekContainsDate)!==null&&a!==void 0?a:d.firstWeekContainsDate)!==null&&n!==void 0?n:(l=d.locale)===null||l===void 0||(u=l.options)===null||u===void 0?void 0:u.firstWeekContainsDate)!==null&&r!==void 0?r:1);if(!(m>=1&&m<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var g=new Date(0);g.setUTCFullYear(f+1,0,m),g.setUTCHours(0,0,0,0);var v=Is(g,t),h=new Date(0);h.setUTCFullYear(f,0,m),h.setUTCHours(0,0,0,0);var b=Is(h,t);return c.getTime()>=v.getTime()?f+1:c.getTime()>=b.getTime()?f:f-1}function cF(e,t){var r,n,a,i,o,s,l,u;Le(1,arguments);var c=wi(),f=Ct((r=(n=(a=(i=t==null?void 0:t.firstWeekContainsDate)!==null&&i!==void 0?i:t==null||(o=t.locale)===null||o===void 0||(s=o.options)===null||s===void 0?void 0:s.firstWeekContainsDate)!==null&&a!==void 0?a:c.firstWeekContainsDate)!==null&&n!==void 0?n:(l=c.locale)===null||l===void 0||(u=l.options)===null||u===void 0?void 0:u.firstWeekContainsDate)!==null&&r!==void 0?r:1),d=z0(e,t),m=new Date(0);m.setUTCFullYear(d,0,f),m.setUTCHours(0,0,0,0);var g=Is(m,t);return g}var fF=6048e5;function dF(e,t){Le(1,arguments);var r=Ve(e),n=Is(r,t).getTime()-cF(r,t).getTime();return Math.round(n/fF)+1}function $e(e,t){for(var r=e<0?"-":"",n=Math.abs(e).toString();n.length<t;)n="0"+n;return r+n}var _r={y:function(t,r){var n=t.getUTCFullYear(),a=n>0?n:1-n;return $e(r==="yy"?a%100:a,r.length)},M:function(t,r){var n=t.getUTCMonth();return r==="M"?String(n+1):$e(n+1,2)},d:function(t,r){return $e(t.getUTCDate(),r.length)},a:function(t,r){var n=t.getUTCHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h:function(t,r){return $e(t.getUTCHours()%12||12,r.length)},H:function(t,r){return $e(t.getUTCHours(),r.length)},m:function(t,r){return $e(t.getUTCMinutes(),r.length)},s:function(t,r){return $e(t.getUTCSeconds(),r.length)},S:function(t,r){var n=r.length,a=t.getUTCMilliseconds(),i=Math.floor(a*Math.pow(10,n-3));return $e(i,r.length)}},ia={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},pF={G:function(t,r,n){var a=t.getUTCFullYear()>0?1:0;switch(r){case"G":case"GG":case"GGG":return n.era(a,{width:"abbreviated"});case"GGGGG":return n.era(a,{width:"narrow"});case"GGGG":default:return n.era(a,{width:"wide"})}},y:function(t,r,n){if(r==="yo"){var a=t.getUTCFullYear(),i=a>0?a:1-a;return n.ordinalNumber(i,{unit:"year"})}return _r.y(t,r)},Y:function(t,r,n,a){var i=z0(t,a),o=i>0?i:1-i;if(r==="YY"){var s=o%100;return $e(s,2)}return r==="Yo"?n.ordinalNumber(o,{unit:"year"}):$e(o,r.length)},R:function(t,r){var n=W0(t);return $e(n,r.length)},u:function(t,r){var n=t.getUTCFullYear();return $e(n,r.length)},Q:function(t,r,n){var a=Math.ceil((t.getUTCMonth()+1)/3);switch(r){case"Q":return String(a);case"QQ":return $e(a,2);case"Qo":return n.ordinalNumber(a,{unit:"quarter"});case"QQQ":return n.quarter(a,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(a,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(a,{width:"wide",context:"formatting"})}},q:function(t,r,n){var a=Math.ceil((t.getUTCMonth()+1)/3);switch(r){case"q":return String(a);case"qq":return $e(a,2);case"qo":return n.ordinalNumber(a,{unit:"quarter"});case"qqq":return n.quarter(a,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(a,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(a,{width:"wide",context:"standalone"})}},M:function(t,r,n){var a=t.getUTCMonth();switch(r){case"M":case"MM":return _r.M(t,r);case"Mo":return n.ordinalNumber(a+1,{unit:"month"});case"MMM":return n.month(a,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(a,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(a,{width:"wide",context:"formatting"})}},L:function(t,r,n){var a=t.getUTCMonth();switch(r){case"L":return String(a+1);case"LL":return $e(a+1,2);case"Lo":return n.ordinalNumber(a+1,{unit:"month"});case"LLL":return n.month(a,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(a,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(a,{width:"wide",context:"standalone"})}},w:function(t,r,n,a){var i=dF(t,a);return r==="wo"?n.ordinalNumber(i,{unit:"week"}):$e(i,r.length)},I:function(t,r,n){var a=uF(t);return r==="Io"?n.ordinalNumber(a,{unit:"week"}):$e(a,r.length)},d:function(t,r,n){return r==="do"?n.ordinalNumber(t.getUTCDate(),{unit:"date"}):_r.d(t,r)},D:function(t,r,n){var a=oF(t);return r==="Do"?n.ordinalNumber(a,{unit:"dayOfYear"}):$e(a,r.length)},E:function(t,r,n){var a=t.getUTCDay();switch(r){case"E":case"EE":case"EEE":return n.day(a,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(a,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(a,{width:"short",context:"formatting"});case"EEEE":default:return n.day(a,{width:"wide",context:"formatting"})}},e:function(t,r,n,a){var i=t.getUTCDay(),o=(i-a.weekStartsOn+8)%7||7;switch(r){case"e":return String(o);case"ee":return $e(o,2);case"eo":return n.ordinalNumber(o,{unit:"day"});case"eee":return n.day(i,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(i,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(i,{width:"short",context:"formatting"});case"eeee":default:return n.day(i,{width:"wide",context:"formatting"})}},c:function(t,r,n,a){var i=t.getUTCDay(),o=(i-a.weekStartsOn+8)%7||7;switch(r){case"c":return String(o);case"cc":return $e(o,r.length);case"co":return n.ordinalNumber(o,{unit:"day"});case"ccc":return n.day(i,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(i,{width:"narrow",context:"standalone"});case"cccccc":return n.day(i,{width:"short",context:"standalone"});case"cccc":default:return n.day(i,{width:"wide",context:"standalone"})}},i:function(t,r,n){var a=t.getUTCDay(),i=a===0?7:a;switch(r){case"i":return String(i);case"ii":return $e(i,r.length);case"io":return n.ordinalNumber(i,{unit:"day"});case"iii":return n.day(a,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(a,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(a,{width:"short",context:"formatting"});case"iiii":default:return n.day(a,{width:"wide",context:"formatting"})}},a:function(t,r,n){var a=t.getUTCHours(),i=a/12>=1?"pm":"am";switch(r){case"a":case"aa":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(i,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(i,{width:"wide",context:"formatting"})}},b:function(t,r,n){var a=t.getUTCHours(),i;switch(a===12?i=ia.noon:a===0?i=ia.midnight:i=a/12>=1?"pm":"am",r){case"b":case"bb":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(i,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(i,{width:"wide",context:"formatting"})}},B:function(t,r,n){var a=t.getUTCHours(),i;switch(a>=17?i=ia.evening:a>=12?i=ia.afternoon:a>=4?i=ia.morning:i=ia.night,r){case"B":case"BB":case"BBB":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(i,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(i,{width:"wide",context:"formatting"})}},h:function(t,r,n){if(r==="ho"){var a=t.getUTCHours()%12;return a===0&&(a=12),n.ordinalNumber(a,{unit:"hour"})}return _r.h(t,r)},H:function(t,r,n){return r==="Ho"?n.ordinalNumber(t.getUTCHours(),{unit:"hour"}):_r.H(t,r)},K:function(t,r,n){var a=t.getUTCHours()%12;return r==="Ko"?n.ordinalNumber(a,{unit:"hour"}):$e(a,r.length)},k:function(t,r,n){var a=t.getUTCHours();return a===0&&(a=24),r==="ko"?n.ordinalNumber(a,{unit:"hour"}):$e(a,r.length)},m:function(t,r,n){return r==="mo"?n.ordinalNumber(t.getUTCMinutes(),{unit:"minute"}):_r.m(t,r)},s:function(t,r,n){return r==="so"?n.ordinalNumber(t.getUTCSeconds(),{unit:"second"}):_r.s(t,r)},S:function(t,r){return _r.S(t,r)},X:function(t,r,n,a){var i=a._originalDate||t,o=i.getTimezoneOffset();if(o===0)return"Z";switch(r){case"X":return G0(o);case"XXXX":case"XX":return Zr(o);case"XXXXX":case"XXX":default:return Zr(o,":")}},x:function(t,r,n,a){var i=a._originalDate||t,o=i.getTimezoneOffset();switch(r){case"x":return G0(o);case"xxxx":case"xx":return Zr(o);case"xxxxx":case"xxx":default:return Zr(o,":")}},O:function(t,r,n,a){var i=a._originalDate||t,o=i.getTimezoneOffset();switch(r){case"O":case"OO":case"OOO":return"GMT"+V0(o,":");case"OOOO":default:return"GMT"+Zr(o,":")}},z:function(t,r,n,a){var i=a._originalDate||t,o=i.getTimezoneOffset();switch(r){case"z":case"zz":case"zzz":return"GMT"+V0(o,":");case"zzzz":default:return"GMT"+Zr(o,":")}},t:function(t,r,n,a){var i=a._originalDate||t,o=Math.floor(i.getTime()/1e3);return $e(o,r.length)},T:function(t,r,n,a){var i=a._originalDate||t,o=i.getTime();return $e(o,r.length)}};function V0(e,t){var r=e>0?"-":"+",n=Math.abs(e),a=Math.floor(n/60),i=n%60;if(i===0)return r+String(a);var o=t;return r+String(a)+o+$e(i,2)}function G0(e,t){if(e%60===0){var r=e>0?"-":"+";return r+$e(Math.abs(e)/60,2)}return Zr(e,t)}function Zr(e,t){var r=t||"",n=e>0?"-":"+",a=Math.abs(e),i=$e(Math.floor(a/60),2),o=$e(a%60,2);return n+i+r+o}var H0=function(t,r){switch(t){case"P":return r.date({width:"short"});case"PP":return r.date({width:"medium"});case"PPP":return r.date({width:"long"});case"PPPP":default:return r.date({width:"full"})}},q0=function(t,r){switch(t){case"p":return r.time({width:"short"});case"pp":return r.time({width:"medium"});case"ppp":return r.time({width:"long"});case"pppp":default:return r.time({width:"full"})}},hF=function(t,r){var n=t.match(/(P+)(p+)?/)||[],a=n[1],i=n[2];if(!i)return H0(t,r);var o;switch(a){case"P":o=r.dateTime({width:"short"});break;case"PP":o=r.dateTime({width:"medium"});break;case"PPP":o=r.dateTime({width:"long"});break;case"PPPP":default:o=r.dateTime({width:"full"});break}return o.replace("{{date}}",H0(a,r)).replace("{{time}}",q0(i,r))},mF={p:q0,P:hF},gF=["D","DD"],vF=["YY","YYYY"];function yF(e){return gF.indexOf(e)!==-1}function bF(e){return vF.indexOf(e)!==-1}function K0(e,t,r){if(e==="YYYY")throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(t,"`) for formatting years to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="YY")throw new RangeError("Use `yy` instead of `YY` (in `".concat(t,"`) for formatting years to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="D")throw new RangeError("Use `d` instead of `D` (in `".concat(t,"`) for formatting days of the month to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="DD")throw new RangeError("Use `dd` instead of `DD` (in `".concat(t,"`) for formatting days of the month to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"))}var xF={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},wF=function(t,r,n){var a,i=xF[t];return typeof i=="string"?a=i:r===1?a=i.one:a=i.other.replace("{{count}}",r.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+a:a+" ago":a};function hf(e){return function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=t.width?String(t.width):e.defaultWidth,n=e.formats[r]||e.formats[e.defaultWidth];return n}}var OF={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},SF={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},AF={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},TF={date:hf({formats:OF,defaultWidth:"full"}),time:hf({formats:SF,defaultWidth:"full"}),dateTime:hf({formats:AF,defaultWidth:"full"})},jF={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},PF=function(t,r,n,a){return jF[t]};function Si(e){return function(t,r){var n=r!=null&&r.context?String(r.context):"standalone",a;if(n==="formatting"&&e.formattingValues){var i=e.defaultFormattingWidth||e.defaultWidth,o=r!=null&&r.width?String(r.width):i;a=e.formattingValues[o]||e.formattingValues[i]}else{var s=e.defaultWidth,l=r!=null&&r.width?String(r.width):e.defaultWidth;a=e.values[l]||e.values[s]}var u=e.argumentCallback?e.argumentCallback(t):t;return a[u]}}var _F={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},EF={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},CF={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},$F={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},kF={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},NF={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},MF=function(t,r){var n=Number(t),a=n%100;if(a>20||a<10)switch(a%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},DF={ordinalNumber:MF,era:Si({values:_F,defaultWidth:"wide"}),quarter:Si({values:EF,defaultWidth:"wide",argumentCallback:function(t){return t-1}}),month:Si({values:CF,defaultWidth:"wide"}),day:Si({values:$F,defaultWidth:"wide"}),dayPeriod:Si({values:kF,defaultWidth:"wide",formattingValues:NF,defaultFormattingWidth:"wide"})};function Ai(e){return function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=r.width,a=n&&e.matchPatterns[n]||e.matchPatterns[e.defaultMatchWidth],i=t.match(a);if(!i)return null;var o=i[0],s=n&&e.parsePatterns[n]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(s)?LF(s,function(f){return f.test(o)}):IF(s,function(f){return f.test(o)}),u;u=e.valueCallback?e.valueCallback(l):l,u=r.valueCallback?r.valueCallback(u):u;var c=t.slice(o.length);return{value:u,rest:c}}}function IF(e,t){for(var r in e)if(e.hasOwnProperty(r)&&t(e[r]))return r}function LF(e,t){for(var r=0;r<e.length;r++)if(t(e[r]))return r}function RF(e){return function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=t.match(e.matchPattern);if(!n)return null;var a=n[0],i=t.match(e.parsePattern);if(!i)return null;var o=e.valueCallback?e.valueCallback(i[0]):i[0];o=r.valueCallback?r.valueCallback(o):o;var s=t.slice(a.length);return{value:o,rest:s}}}var BF=/^(\d+)(th|st|nd|rd)?/i,FF=/\d+/i,UF={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},WF={any:[/^b/i,/^(a|c)/i]},zF={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},VF={any:[/1/i,/2/i,/3/i,/4/i]},GF={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},HF={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},qF={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},KF={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},YF={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},XF={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},ZF={ordinalNumber:RF({matchPattern:BF,parsePattern:FF,valueCallback:function(t){return parseInt(t,10)}}),era:Ai({matchPatterns:UF,defaultMatchWidth:"wide",parsePatterns:WF,defaultParseWidth:"any"}),quarter:Ai({matchPatterns:zF,defaultMatchWidth:"wide",parsePatterns:VF,defaultParseWidth:"any",valueCallback:function(t){return t+1}}),month:Ai({matchPatterns:GF,defaultMatchWidth:"wide",parsePatterns:HF,defaultParseWidth:"any"}),day:Ai({matchPatterns:qF,defaultMatchWidth:"wide",parsePatterns:KF,defaultParseWidth:"any"}),dayPeriod:Ai({matchPatterns:YF,defaultMatchWidth:"any",parsePatterns:XF,defaultParseWidth:"any"})},JF={code:"en-US",formatDistance:wF,formatLong:TF,formatRelative:PF,localize:DF,match:ZF,options:{weekStartsOn:0,firstWeekContainsDate:1}},QF=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,eU=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,tU=/^'([^]*?)'?$/,rU=/''/g,nU=/[a-zA-Z]/;function Ls(e,t,r){var n,a,i,o,s,l,u,c,f,d,m,g,v,h;Le(2,arguments);var b=String(t),w=wi(),x=(n=(a=void 0)!==null&&a!==void 0?a:w.locale)!==null&&n!==void 0?n:JF,T=Ct((i=(o=(s=(l=void 0)!==null&&l!==void 0?l:void 0)!==null&&s!==void 0?s:w.firstWeekContainsDate)!==null&&o!==void 0?o:(u=w.locale)===null||u===void 0||(c=u.options)===null||c===void 0?void 0:c.firstWeekContainsDate)!==null&&i!==void 0?i:1);if(!(T>=1&&T<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var y=Ct((f=(d=(m=(g=void 0)!==null&&g!==void 0?g:void 0)!==null&&m!==void 0?m:w.weekStartsOn)!==null&&d!==void 0?d:(v=w.locale)===null||v===void 0||(h=v.options)===null||h===void 0?void 0:h.weekStartsOn)!==null&&f!==void 0?f:0);if(!(y>=0&&y<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");if(!x.localize)throw new RangeError("locale must contain localize property");if(!x.formatLong)throw new RangeError("locale must contain formatLong property");var O=Ve(e);if(!tF(O))throw new RangeError("Invalid time value");var A=QB(O),j=aF(O,A),C={firstWeekContainsDate:T,weekStartsOn:y,locale:x,_originalDate:O},$=b.match(eU).map(function(P){var _=P[0];if(_==="p"||_==="P"){var F=mF[_];return F(P,x.formatLong)}return P}).join("").match(QF).map(function(P){if(P==="''")return"'";var _=P[0];if(_==="'")return aU(P);var F=pF[_];if(F)return bF(P)&&K0(P,t,String(e)),yF(P)&&K0(P,t,String(e)),F(j,P,x.localize,C);if(_.match(nU))throw new RangeError("Format string contains an unescaped latin alphabet character `"+_+"`");return P}).join("");return $}function aU(e){var t=e.match(tU);return t?t[1].replace(rU,"'"):e}function Y0(e,t){Le(2,arguments);var r=Ve(e),n=Ve(t);return r.getTime()<n.getTime()}function iU(e,t){Le(2,arguments);var r=Ve(e).getTime(),n=Ve(t.start).getTime(),a=Ve(t.end).getTime();if(!(n<=a))throw new RangeError("Invalid interval");return r>=n&&r<=a}function Rs(e,t){Le(2,arguments);var r=Ct(t);return YB(e,-r)}function oU(e,t){Le(2,arguments);var r=Ct(t);return pf(e,-r)}const mf=({children:e})=>{const[t,r]=S.useState(!1);return S.useEffect(()=>(r(!0),()=>r(!1)),[]),t?en.createPortal(e,document.body):null};function X0({className:e,defaultValue:t,onDateRangeChange:r}){console.log("🗓️ DateRangePicker component rendered with props:",{className:e,defaultValue:t,hasCallback:!!r});const n=[{label:"Today",value:"today",dateRange:{from:aa(new Date),to:new Date}},{label:"Yesterday",value:"yesterday",dateRange:{from:aa(Rs(new Date,1)),to:rF(Rs(new Date,1))}},{label:"This week",value:"thisWeek",dateRange:{from:JB(new Date),to:new Date}},{label:"Last 7 days",value:"7d",dateRange:{from:aa(Rs(new Date,6)),to:new Date}},{label:"This month",value:"thisMonth",dateRange:{from:nF(new Date),to:new Date}},{label:"Last 30 days",value:"30d",dateRange:{from:aa(Rs(new Date,29)),to:new Date}}],a=t?n.find(k=>k.value===t):null;console.log("📅 DateRangePicker initialization:",{defaultValue:t,defaultPreset:a==null?void 0:a.label,hasDateRange:!!(a!=null&&a.dateRange),allPresetValues:n.map(k=>k.value),foundPreset:!!a});const[i,o]=S.useState(a==null?void 0:a.dateRange),[s,l]=S.useState(a==null?void 0:a.dateRange),[u,c]=S.useState(!1),[f,d]=S.useState((a==null?void 0:a.label)||null),[m,g]=S.useState((a==null?void 0:a.label)||null),[v,h]=S.useState(new Date),[b,w]=S.useState(null),[x,T]=S.useState({top:0,left:0}),y=S.useRef(null),O=S.useRef(null);S.useEffect(()=>{var k,U;console.log("📅 DateRangePicker useEffect running:",{hasDefaultPreset:!!a,hasOnDateRangeChange:!!r,currentDate:i,currentLabel:f,defaultValue:t,defaultPresetLabel:a==null?void 0:a.label,defaultPresetValue:a==null?void 0:a.value}),a!=null&&a.dateRange&&r?(console.log("📅 DateRangePicker: Setting initial default value:",{label:a.label,dateRange:a.dateRange,from:(k=a.dateRange.from)==null?void 0:k.toLocaleDateString(),to:(U=a.dateRange.to)==null?void 0:U.toLocaleDateString()}),r(a.dateRange)):console.log("📅 DateRangePicker: NOT setting initial value because:",{hasDefaultPreset:!!a,hasDateRange:!!(a!=null&&a.dateRange),hasCallback:!!r,presetLabelsAvailable:n.map(q=>`${q.value}:${q.label}`)})},[]),S.useEffect(()=>{t&&(a!=null&&a.dateRange)&&(console.log("📅 DateRangePicker: DefaultValue changed, updating state:",{defaultValue:t,label:a.label}),o(a.dateRange),d(a.label),l(a.dateRange),g(a.label))},[t]);const A=()=>{if(!O.current)return;const k=O.current.getBoundingClientRect(),U=window.scrollY,q=window.scrollX,Z=window.innerWidth,E=window.innerHeight,B=720,z=450;let H=k.bottom+U+8,I=k.left+q;I+B>Z&&(I=k.right+q-B),I+B>Z&&(I=Z-B-20),H+z>E&&(H=k.top+U-z-8),I<20&&(I=20),H<20&&(H=20),T({top:H,left:I})};S.useEffect(()=>{const k=()=>{u&&A()};return u&&(window.addEventListener("resize",k),window.addEventListener("scroll",k)),()=>{window.removeEventListener("resize",k),window.removeEventListener("scroll",k)}},[u]);const j=(k,U)=>{if(l(k),g(U),w(null),k.from){const q=new Date(k.from.getFullYear(),k.from.getMonth(),1);h(q)}},C=k=>{if(!b)w(k),l({from:k,to:k}),g(null);else{const U=Y0(k,b)?k:b,q=Y0(k,b)?b:k;l({from:U,to:q}),w(null),g(null)}},$=()=>{o(s),d(m),r==null||r(s),c(!1),w(null)},P=()=>{l(void 0),g(null),o(void 0),d(null),r==null||r(void 0),c(!1),w(null)},_=k=>{k?(l(i),g(f),w(null),setTimeout(A,0)):(l(i),g(f),w(null)),c(k)},F=(k,U)=>(console.log("📅 formatDateRange called with:",{presetLabel:U,hasDateRange:!!(k!=null&&k.from)}),U||(k!=null&&k.from?!k.to||Oi(k.from,k.to)?Ls(k.from,"MMM dd, yyyy"):`${Ls(k.from,"MMM dd, yyyy")} - ${Ls(k.to,"MMM dd, yyyy")}`:"Pick a date range")),N=(k=0)=>{const U=pf(v,k),q=U.getFullYear(),Z=U.getMonth(),E=new Date(q,Z,1),z=new Date(q,Z+1,0).getDate(),H=E.getDay(),I=["January","February","March","April","May","June","July","August","September","October","November","December"],V=["Su","Mo","Tu","We","Th","Fr","Sa"],X=[],L=new Date(q,Z-1,0).getDate();for(let J=H-1;J>=0;J--){const M=L-J,Q=new Date(q,Z-1,M);X.push(p.jsx("button",{onClick:()=>C(Q),className:"h-[32px] w-[32px] text-xs text-gray-400 hover:bg-gray-100 rounded-full flex items-center justify-center",children:M},`prev-${M}`))}for(let J=1;J<=z;J++){const M=new Date(q,Z,J),Q=Oi(M,new Date),K=(s==null?void 0:s.from)&&(s==null?void 0:s.to)&&iU(M,{start:s.from,end:s.to}),se=(s==null?void 0:s.from)&&Oi(M,s.from),ne=(s==null?void 0:s.to)&&Oi(M,s.to),fe=b&&Oi(M,b);let ue="h-[32px] w-[32px] text-xs hover:bg-gray-100 hover:text-gray-900 hover:font-medium rounded-full flex items-center justify-center transition-colors text-gray-700 ";Q&&(ue+="font-semibold "),fe||se||ne?ue+="!bg-blue-500 !text-white !hover:bg-blue-500 !hover:text-white font-semibold":K&&(ue+="bg-blue-100 text-blue-900 hover:bg-blue-100 hover:text-blue-900 font-semibold"),X.push(p.jsx("button",{onClick:()=>C(M),className:ue,children:J},`current-${J}`))}const G=Math.ceil((H+z)/7)*7-H-z;for(let J=1;J<=G;J++){const M=new Date(q,Z+1,J);X.push(p.jsx("button",{onClick:()=>C(M),className:"h-[32px] w-[32px] text-sm text-gray-500 hover:bg-gray-100 rounded-full flex items-center justify-center",children:J},`next-${J}`))}return p.jsxs("div",{className:"p-[12px]",children:[p.jsxs("div",{className:"flex items-center justify-between mb-3",children:[k===0&&p.jsx("button",{onClick:()=>h(oU(v,1)),className:"p-[4px] hover:bg-gray-100 rounded",children:p.jsx(Tb,{className:"h-[16px] w-[16px]"})}),p.jsxs("div",{className:"font-semibold text-sm text-gray-700",children:[I[Z]," ",q]}),k===1&&p.jsx("button",{onClick:()=>h(pf(v,1)),className:"p-[4px] hover:bg-gray-100 rounded",children:p.jsx(ki,{className:"h-[16px] w-[16px]"})})]}),p.jsx("div",{className:"grid grid-cols-7 gap-1 mb-2",children:V.map(J=>p.jsx("div",{className:"h-[32px] flex items-center justify-center text-xs font-medium text-gray-700 w-full text-center",children:J},J))}),p.jsx("div",{className:"grid grid-cols-7 gap-1",children:X})]})},R=()=>"fixed bg-white border border-gray-200 rounded-lg shadow-xl z-[99999]";return p.jsxs("div",{className:`relative ${e}`,children:[p.jsxs("button",{ref:O,onClick:()=>_(!u),className:`min-w-[200px] px-[12px] py-[8px] text-left border border-gray-300 rounded-md shadow-sm bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 flex items-center ${i?"text-gray-900":"text-gray-500"}`,children:[p.jsx(Af,{className:"mr-2 h-[16px] w-[16px]"}),(()=>{const k=F(i,f);return console.log("📅 Button display text:",{displayText:k,date:i,selectedPresetLabel:f}),k})()]}),u&&p.jsxs(mf,{children:[p.jsx("div",{className:"fixed inset-0 z-[99998] bg-black bg-opacity-10",onClick:()=>_(!1)}),p.jsxs("div",{ref:y,className:R(),style:{top:x.top,left:x.left,width:"720px",minWidth:"720px",maxHeight:"90vh"},onClick:k=>k.stopPropagation(),children:[p.jsxs("div",{className:"flex",children:[p.jsxs("div",{className:"flex flex-col gap-1 p-[12px] border-r border-gray-200 w-[160px] flex-shrink-0",children:[p.jsx("div",{className:"text-sm font-medium text-gray-500 mb-2",children:"Quick Filters"}),n.map(k=>p.jsx("button",{onClick:()=>j(k.dateRange,k.label),className:`text-left px-[12px] py-[8px] text-sm text-gray-900 rounded hover:bg-gray-100 transition-colors ${m===k.label?"bg-gray-100 medium":""}`,children:k.label},k.label))]}),p.jsxs("div",{className:"flex flex-1",children:[N(0),N(1)]})]}),p.jsxs("div",{className:"border-t border-gray-200 bg-gray-50 p-[12px] flex justify-end gap-2",children:[p.jsx("button",{onClick:P,className:"px-[12px] py-[8px] text-sm border border-gray-300 rounded hover:bg-gray-50 transition-colors",children:"Clear"}),p.jsx("button",{onClick:$,disabled:!(s!=null&&s.from),className:"px-[12px] py-[8px] text-sm bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"Apply"})]})]})]})]})}const sU=({config:e,appConfig:t,className:r,onExport:n,onDraftChange:a,onTimeRangeChange:i})=>{var F;const{title:o,subtitle:s,sections:l,globalControls:u,layout:c={columns:12,gap:24,responsive:!0}}=e,[f,d]=S.useState(!1),[m,g]=S.useState({}),[v,h]=S.useState(l),[b,w]=S.useState([]),[x,T]=S.useState(!1),y=S.useRef(null);S.useEffect(()=>{if(t)try{y.current=new Yt(t),O(),A()}catch(N){console.error("Failed to initialize API service:",N)}},[t]);const O=async()=>{if(!(!y.current||!t)){T(!0);try{const N=await y.current.fetchEnvironments();w(N),console.log("🌍 Environments loaded:",N.map(R=>R.envName))}catch(N){console.error("Error loading environments:",N)}finally{T(!1)}}},A=async()=>{if(!(!y.current||!t)){d(!0);try{const N=y.current.getDefaultTimeRange();console.log("📊 Loading dashboard data with date range:",{fromTimestamp:N.fromTimestamp,toTimestamp:N.toTimestamp,fromDate:new Date(N.fromTimestamp).toLocaleDateString(),toDate:new Date(N.toTimestamp).toLocaleDateString()});const R=await y.current.fetchAllCardsDataWithEnhancedViews(N.fromTimestamp,N.toTimestamp);console.log("✅ Enhanced cards data loaded successfully:",R),console.log("📈 Data covers period:",{from:new Date(N.fromTimestamp).toLocaleDateString(),to:new Date(N.toTimestamp).toLocaleDateString()});const k=l.map(U=>U.id==="usage-analytics"?(console.log("Updating usage-analytics section with enhanced data"),{...U,metrics:R.usageAnalytics}):U.id==="runs"?(console.log("Updating runs section with enhanced data including table and controls"),{...U,metrics:R.runs}):U);h(k)}catch(N){console.error("Error loading initial data:",N),h(l)}finally{d(!1)}}},j=async(N,R)=>{if(!(!y.current||!t||!R.metricType)){h(k=>k.map(U=>U.id===N?{...U,metrics:U.metrics.map(q=>({...q,highlighted:q.metricType===R.metricType}))}:U)),g(k=>({...k,[N]:!0}));try{const k=t.defaultTimeRange||Yt.getDateRange(7);let U,q;if(["users","sessions","messages","tokens"].includes(R.metricType))U="usage-analytics",q=R.metricType;else if(["agentRuns","toolRuns","modelRuns"].includes(R.metricType))U="runs",q=R.metricType==="agentRuns"?"agent-runs":R.metricType==="toolRuns"?"tool-runs":"model-runs";else return;const Z=await y.current.fetchTimeSeriesData(q,U,k.fromTimestamp,k.toTimestamp),E=y.current.transformTimeSeriesDataForMetric(Z,R.metricType);console.log("Time series response for",R.title,":",Z),console.log("Transformed data for",R.title,":",E),console.log("Metric type used for transformation:",R.metricType);const z=(H=>({users:"users",sessions:"sessions",messages:"messages",tokens:"totalTokens",agentRuns:"agentRuns",toolRuns:"toolRuns",modelRuns:"modelRuns"})[H]||"count")(R.metricType||"count");console.log("Using dataKey for metric",R.metricType,":",z),h(H=>H.map(I=>{if(I.id===N){const V={...I,view:{...I.view,chart:I.view.chart?{...I.view.chart,data:E,dataKey:z,lines:[{dataKey:z,color:I.view.chart.color||"#3b82f6",label:R.title,strokeWidth:2}]}:{type:"line",data:E,dataKey:z,lines:[{dataKey:z,color:"#3b82f6",label:R.title,strokeWidth:2}],yAxisLabel:R.title}}};return console.log("Updated section for",N,":",V),console.log("Chart config set:",V.view.chart),V}return I}))}catch(k){console.error("Error loading metric data:",k)}finally{g(k=>({...k,[N]:!1}))}}},C=N=>{var R,k;if((k=(R=u==null?void 0:u.draft)==null?void 0:R.onChange)==null||k.call(R,N),a==null||a(N),t&&y.current){const U={...t,environment:N};y.current.updateConfig(U),A()}},$=N=>{var R,k;if(console.log("🗓️ Time range change requested:",N),typeof N=="string"&&((k=(R=u==null?void 0:u.timeRange)==null?void 0:R.onChange)==null||k.call(R,N)),i==null||i(N),t&&y.current){let U=null;if(typeof N=="object"&&N.from&&N.to)U={fromTimestamp:N.from.toISOString(),toTimestamp:N.to.toISOString()},console.log("📅 Converting DateRange to API format:",U);else if(typeof N=="string"){const Z={"24h":1,"7d":7,"30d":30,"90d":90}[N];Z&&(U=Yt.getDateRange(Z),console.log(`📅 Converting preset "${N}" (${Z} days) to API format:`,U))}if(U){const q={...t,defaultTimeRange:U};console.log("🔄 Updating API configuration with new date range:",q.defaultTimeRange),y.current.updateConfig(q),console.log("🚀 Reloading dashboard data with new date range..."),A()}else console.warn("⚠️ Unable to convert time range value to API format:",N)}},P=(N="csv")=>{var R,k;(k=(R=u==null?void 0:u.export)==null?void 0:R.onExport)==null||k.call(R,N),n==null||n()},_=Object.values(m).some(N=>N);return p.jsxs("div",{className:le("w-full h-full flex flex-col overflow-hidden",r),children:[p.jsxs("div",{className:"flex flex-col gap-2 w-full p-[24px] pb-[12px]",children:[p.jsx("h1",{className:"text-lg font-bold text-gray-900 w-full",children:o}),p.jsxs("div",{className:"flex items-center gap-2 w-full",children:[s&&p.jsx("p",{className:"text-gray-500 text-xs w-full",children:s}),p.jsxs("div",{className:"flex items-center gap-2 justify-end flex-shrink-0",children:[(f||_)&&p.jsxs("div",{className:"flex items-center gap-2 text-sm medium text-gray-500",children:[p.jsx(kb,{className:"h-[16px] w-[16px] animate-spin"}),"Loading..."]}),u&&p.jsxs(p.Fragment,{children:[u.draft&&p.jsx(Ns,{options:b.length>0?b.map(N=>({label:N.envName.charAt(0).toUpperCase()+N.envName.slice(1),value:N.envName})):u.draft.options,value:u.draft.defaultValue,placeholder:x?"Loading environments...":u.draft.label,onChange:C,className:"min-w-[200px]",disabled:f||_||x}),u.timeRange&&(u.timeRange.useDatePicker?(console.log("🗓️ Dashboard: Rendering DateRangePicker with defaultValue:",u.timeRange.defaultValue),p.jsx(X0,{defaultValue:u.timeRange.defaultValue,onDateRangeChange:N=>{console.log("🗓️ Dashboard: DateRangePicker callback received:",N),N&&$(N)}})):p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx(Af,{className:"h-4 w-4 text-gray-500"}),p.jsx(Ns,{options:u.timeRange.options||[],value:u.timeRange.defaultValue,placeholder:u.timeRange.label,onChange:$,className:"min-w-[200px]",disabled:f||_})]})),((F=u.export)==null?void 0:F.enabled)&&p.jsxs(df,{variant:"outline",onClick:()=>P(),className:"gap-2",disabled:f||_,children:[p.jsx(jb,{className:"h-4 w-4"}),"Export"]})]})]})]})]}),p.jsx("div",{className:le("grid gap-6 p-[24px] pt-[8px] overflow-y-auto",c.responsive&&"grid-cols-1 lg:grid-cols-12"),style:{gridTemplateColumns:c.responsive?void 0:`repeat(${c.columns}, minmax(0, 1fr))`,gap:c.gap?`${c.gap}px`:void 0},children:v.map(N=>{var R,k,U,q;return p.jsx(U0,{section:N,isLoading:f,isChartLoading:m[N.id]||!1,onMetricClick:Z=>j(N.id,Z),className:le(c.responsive&&((R=N.layout)==null?void 0:R.span)===12&&"lg:col-span-12",c.responsive&&((k=N.layout)==null?void 0:k.span)===6&&"lg:col-span-6",c.responsive&&((U=N.layout)==null?void 0:U.span)===4&&"lg:col-span-4",c.responsive&&((q=N.layout)==null?void 0:q.span)===3&&"lg:col-span-3")},N.id)})})]})};class Z0{static buildSessionTree(t,r){var i;const n=this.groupEventsByRun(t),a=[];for(const[o,s]of n.entries()){const l=this.buildRunTree(o,s);a.push(l)}return a.sort((o,s)=>new Date(o.startTime).getTime()-new Date(s.startTime).getTime()),{sessionId:r||((i=t[0])==null?void 0:i.sessionId)||"unknown",runs:a}}static groupEventsByRun(t){const r=new Map;return t.forEach(n=>{const a=n.runId;r.has(a)||r.set(a,[]),r.get(a).push(n)}),r}static buildRunTree(t,r){var v;const n=new Map;r.forEach(h=>{const b=`${h.data.id}|${h.data.name}|${h.data.toolName}`;n.has(b)||n.set(b,{});const w=n.get(b);h.type==="node_started"?w.started=h:h.type==="node_completed"&&(w.completed=h)});const a=[];for(const[,h]of n.entries()){const b=h.started,w=h.completed;if(!b)continue;const x=this.createTreeNodeFromEvents(b,w,t);a.push(x)}const i=this.buildNodeHierarchy(a),o=r.filter(h=>h.runId===t),s=Math.min(...o.map(h=>new Date(h.data.timestamp).getTime())),l=o.filter(h=>h.type==="node_completed"),u=l.length>0?Math.max(...l.map(h=>new Date(h.data.timestamp).getTime())):void 0,c=this.calculateRunStatus(o),f=u&&s?u-s:void 0,d=this.calculateRunTokens(o),m=this.extractUserInput(o),g=this.extractFinalOutput(o);return{runId:t,startTime:new Date(s).toISOString(),endTime:u?new Date(u).toISOString():void 0,status:c,rootNodes:i,duration:f,totalTokens:d>0?d:void 0,sessionId:((v=o[0])==null?void 0:v.sessionId)||"unknown",userInput:m,finalOutput:g}}static createTreeNodeFromEvents(t,r,n){const a=t.data.timestamp,i=r==null?void 0:r.data.timestamp,o=i&&a?new Date(i).getTime()-new Date(a).getTime():void 0,s=r||t,l=s.data.type==="llm"||s.data.type==="tool"||s.data.type==="GuardrailsInputScan"||s.data.type==="GuardrailsOutputScan"||s.data.type==="Agent"||s.data.type==="External Orchestrator"||s.data.type==="ProxyWorker",u=l?t.data.input:void 0;let c,f;r&&(l&&(c=r.data.output),f=r.data.error);const d=this.extractLLMUsage(c,r==null?void 0:r.data.metadata),{toolInvocations:m,isResponse:g}=this.extractToolInvocations(c);console.log("toolInvocations",m),console.log("isResponse",g);const v=s.data.type==="llm"?this.extractProvider(s.data.name||s.data.toolName):void 0;return{id:s.data.id,parentId:s.data.parentId,runId:n||"unknown",name:s.data.name,type:s.data.type,status:(r==null?void 0:r.data.status)||t.data.status,startTime:a,endTime:i,duration:o,icon:s.data.icon,input:u,output:c,error:f,children:[],level:0,isExpanded:!1,llmUsage:d,toolInvocations:m,isResponse:g,metadata:{...s.data.metadata,provider:v}}}static buildNodeHierarchy(t){const r=new Map;t.forEach(a=>r.set(a.id,a));const n=[];return t.forEach(a=>{if(a.parentId&&r.has(a.parentId)){const i=r.get(a.parentId);i.children.push(a),a.level=i.level+1}else n.push(a),a.level=0}),n.sort((a,i)=>new Date(a.startTime).getTime()-new Date(i.startTime).getTime()),n.forEach(a=>this.sortChildren(a)),n}static extractLLMUsage(t,r){var n,a,i;if(r!=null&&r.usage_metadata)return r.usage_metadata;if(!(!t||typeof t!="object")){if(t.usage_metadata)return t.usage_metadata;if((n=t.metadata)!=null&&n.usage_metadata)return t.metadata.usage_metadata;if(Array.isArray(t)){const o=t[0];if((a=o==null?void 0:o.additional_kwargs)!=null&&a.llmUsageMetadata)return o.additional_kwargs.llmUsageMetadata}else if((i=t.additional_kwargs)!=null&&i.llmUsageMetadata)return t.additional_kwargs.llmUsageMetadata}}static extractToolInvocations(t){if(!t||typeof t!="object")return{};if(t.name&&t.tool_call_id){const r=t.name==="route_to_user"||t.toolName==="route_to_user";return{toolInvocations:[t],isResponse:r}}if(Array.isArray(t)){const r=t.filter(n=>n&&typeof n=="object"&&(n.name==="route_to_user"||n.toolName==="route_to_user")&&n.tool_call_id);if(r.length>0){const n=r.some(a=>a.name==="route_to_user"||a.toolName==="route_to_user");return{toolInvocations:r,isResponse:n}}}if(t.tool_calls&&Array.isArray(t.tool_calls)){const r=t.tool_calls.filter(n=>n&&typeof n=="object"&&(n.name==="route_to_user"||n.toolName==="route_to_user")&&n.tool_call_id);if(r.length>0){const n=r.some(a=>a.name==="route_to_user"||a.toolName==="route_to_user");return{toolInvocations:r,isResponse:n}}}return{}}static extractProvider(t){if(!t)return;const r=t.toLowerCase();if(r.includes("gemini"))return"google";if(r.includes("gpt")||r.includes("openai"))return"openai";if(r.includes("claude")||r.includes("anthropic"))return"anthropic";if(r.includes("azure"))return"azure";if(r.includes("cohere"))return"cohere";const n=t.split("-");if(n.length>0){const a=n[0].toLowerCase();if(["gemini","gpt","claude","cohere"].includes(a))return a==="gemini"?"google":a==="gpt"?"openai":a==="claude"?"anthropic":a}return"custom"}static sortChildren(t){t&&(t.children.sort((r,n)=>new Date(r.startTime).getTime()-new Date(n.startTime).getTime()),t.children.forEach(r=>this.sortChildren(r)))}static calculateRunStatus(t){const r=t.some(a=>a.data.status==="running"),n=t.some(a=>a.data.status==="failed"||a.data.status==="errored");return r?"running":n?"failed":"completed"}static extractUserInput(t){const r=t.filter(n=>n.type==="node_started"&&n.data.type==="llm").sort((n,a)=>new Date(n.data.timestamp).getTime()-new Date(a.data.timestamp).getTime());if(r.length>0){const n=r[0];if(n.data.input){if(typeof n.data.input=="string")return n.data.input;if(typeof n.data.input=="object")return JSON.stringify(n.data.input)}}}static containsRouteToUserTool(t){return!t||typeof t!="object"?!1:Array.isArray(t)?t.some(r=>r&&typeof r=="object"&&(r.name==="route_to_user"||r.toolName==="route_to_user")):t.name==="route_to_user"||t.toolName==="route_to_user"}static extractMessageFromLLMOutput(t){var r,n,a;if(!(!t||typeof t!="object")){if(console.log("Extracting message from LLM output:",JSON.stringify(t,null,2)),Array.isArray(t)){const i=t.find(o=>o&&typeof o=="object"&&(o.name==="route_to_user"||o.toolName==="route_to_user"));if(i){if((r=i.args)!=null&&r.message)return console.log("Found message in LLM array format: routeToUserTool.args.message"),i.args.message;if(i.message)return console.log("Found message in LLM array format: routeToUserTool.message"),i.message;if((n=i.output)!=null&&n.message)return console.log("Found message in LLM array format: routeToUserTool.output.message"),i.output.message}}else if(t.name==="route_to_user"||t.toolName==="route_to_user"){if((a=t.args)!=null&&a.message)return console.log("Found message in LLM single format: output.args.message"),t.args.message;if(t.message)return console.log("Found message in LLM single format: output.message"),t.message}console.log("No message found in LLM output")}}static extractFinalOutput(t){var o,s,l,u,c,f,d,m,g,v;const r=t.filter(h=>h.type==="node_completed"&&h.data.error&&(h.data.status==="errored"||h.data.status==="failed"));if(r.length>0){const h=r.sort((b,w)=>new Date(w.timestamp).getTime()-new Date(b.timestamp).getTime());return typeof h[0].data.error=="string"?h[0].data.error:JSON.stringify(h[0].data.error)}const n=t.filter(h=>h.type==="node_completed"&&h.data.type==="tool"&&(h.data.name==="route_to_user"||h.data.toolName==="route_to_user")),a=t.filter(h=>h.type==="node_completed"&&h.data.type==="llm"&&h.data.output&&this.containsRouteToUserTool(h.data.output));n.length>0&&console.log("Found route_to_user tool events:",n.length),a.length>0&&console.log("Found LLM events with route_to_user:",a.length);const i=[...n,...a];if(i.sort((h,b)=>new Date(h.timestamp).getTime()-new Date(b.timestamp).getTime()),i.length>0){const h=i[i.length-1];if(h.data.type==="llm")return this.extractMessageFromLLMOutput(h.data.output)}if(n.length>0){const b=n[n.length-1].data.output;if(console.log("Route to user output structure:",JSON.stringify(b,null,2)),b)if(Array.isArray(b)){const w=b.find(x=>x&&typeof x=="object"&&(x.name==="route_to_user"||x.toolName==="route_to_user"));if(w){if((o=w.args)!=null&&o.message)return console.log("Found message in array format: routeToUserTool.args.message"),w.args.message;if(w.message)return console.log("Found message in array format: routeToUserTool.message"),w.message;if((s=w.output)!=null&&s.message)return console.log("Found message in array format: routeToUserTool.output.message"),w.output.message}}else{if((l=b.args)!=null&&l.message)return console.log("Found message at: output.args.message"),b.args.message;if(b.message)return console.log("Found message at: output.message"),b.message;if((u=b.output)!=null&&u.message)return console.log("Found message at: output.output.message"),b.output.message;if((c=b.input)!=null&&c.message)return console.log("Found message at: output.input.message"),b.input.message;if((d=(f=b.input)==null?void 0:f.args)!=null&&d.message)return console.log("Found message at: output.input.args.message"),b.input.args.message;if((m=b.data)!=null&&m.message)return console.log("Found message at: output.data.message"),b.data.message;if((g=b.result)!=null&&g.message)return console.log("Found message at: output.result.message"),b.result.message;if(typeof b=="string")try{const w=JSON.parse(b);if((v=w.args)!=null&&v.message)return console.log("Found message in parsed string: parsed.args.message"),w.args.message;if(w.message)return console.log("Found message in parsed string: parsed.message"),w.message}catch{if(b.length>10&&!b.includes("{")&&!b.includes("["))return console.log("Using output string directly as message"),b}try{return JSON.stringify(b)}catch{return b}}console.log("No message found in route_to_user output paths")}}static calculateRunTokens(t){let r=0;return t.forEach(n=>{const a=this.extractLLMUsage(n.data.output,n.data.metadata);a!=null&&a.total_tokens&&(r+=a.total_tokens)}),r}static updateTree(t,r,n){return this.buildSessionTree(n,t.sessionId)}static mergeEvents(t,r){return[...t,...r].sort((a,i)=>new Date(a.timestamp).getTime()-new Date(i.timestamp).getTime())}}const J0=({value:e,onChange:t,language:r="text",readOnly:n=!1,placeholder:a="",className:i,autoFocus:o=!1})=>{const[s,l]=S.useState(e),[u,c]=S.useState(!1),[f,d]=S.useState(!1),m=S.useRef(null);S.useEffect(()=>{l(e)},[e]);function g(){navigator.clipboard.writeText(s).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})}function v(x){const T=x.target.value;l(T),t==null||t(T)}const h=()=>p.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b bg-gray-100",children:[p.jsx("span",{className:"text-xs font-mono uppercase text-gray-500",children:r}),p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("button",{type:"button",className:"p-1 rounded hover:bg-gray-200",onClick:g,title:f?"Copied!":"Copy",children:p.jsx(Pf,{size:16,className:f?"text-green-500":""})}),p.jsx("button",{type:"button",className:"p-1 rounded hover:bg-gray-200",onClick:()=>c(!u),title:u?"Minimize":"Maximize",children:u?p.jsx(Eb,{size:16}):p.jsx($f,{size:16})})]})]}),b=()=>p.jsx("textarea",{ref:m,spellCheck:!1,readOnly:n,placeholder:a,autoFocus:o,className:"flex-1 w-full h-full resize-none p-3 font-mono text-sm outline-none bg-transparent",value:s,onChange:v}),w=p.jsxs("div",{className:le("flex flex-col h-full w-full border rounded-md bg-background",i),style:{minHeight:"200px"},children:[p.jsx(h,{}),p.jsx(b,{})]});return u?p.jsx(mf,{children:p.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",children:p.jsx("div",{className:"w-full h-full max-h-[calc(100vh-2rem)]",children:w})})}):w};J0.displayName="CodeEditor";const Q0=S.forwardRef(({className:e,...t},r)=>p.jsx("span",{ref:r,className:le("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));Q0.displayName="Avatar";const eb=S.forwardRef(({className:e,...t},r)=>p.jsx("img",{ref:r,className:le("aspect-square h-full w-full",e),...t}));eb.displayName="AvatarImage";const tb=S.forwardRef(({className:e,...t},r)=>p.jsx("span",{ref:r,className:le("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));tb.displayName="AvatarFallback";const rb=S.forwardRef(({className:e,children:t,...r},n)=>p.jsx("div",{ref:n,className:le("rounded-lg border bg-card text-card-foreground shadow-sm",e),...r,children:t}));rb.displayName="Card";const lU=S.forwardRef(({className:e,children:t,...r},n)=>p.jsx("div",{ref:n,className:le("flex flex-col space-y-1.5 p-6",e),...r,children:t}));lU.displayName="CardHeader";const uU=S.forwardRef(({className:e,children:t,...r},n)=>p.jsx("h3",{ref:n,className:le("text-2xl font-semibold leading-none tracking-tight",e),...r,children:t}));uU.displayName="CardTitle";const cU=S.forwardRef(({className:e,children:t,...r},n)=>p.jsx("div",{ref:n,className:le("p-6 pt-0",e),...r,children:t}));cU.displayName="CardContent";const Ti=({text:e,className:t="",iconClassName:r="",title:n="Copy to clipboard",onCopySuccess:a,onCopyError:i,tooltipText:o="Copied!",tooltipPosition:s="bottom",size:l="md"})=>{const[u,c]=S.useState(!1),f=()=>{switch(l){case"sm":return{button:"p-1",icon:"w-3 h-3",tooltip:"text-xs py-1 px-2"};case"lg":return{button:"p-2",icon:"w-5 h-5",tooltip:"text-sm py-2 px-3"};default:return{button:"p-1.5",icon:"w-4 h-4",tooltip:"text-xs py-1 px-2"}}},d=()=>{const h="absolute bg-gray-800 text-white rounded whitespace-nowrap z-50";switch(s){case"bottom":return`${h} top-full mt-1 left-1/2 -translate-x-1/2`;case"left":return`${h} right-full mr-1 top-1/2 -translate-y-1/2`;case"right":return`${h} left-full ml-1 top-1/2 -translate-y-1/2`;default:return`${h} bottom-full mb-1 left-1/2 -translate-x-1/2`}},m=f(),g=S.useCallback(()=>{c(!0),setTimeout(()=>c(!1),1e3)},[]),v=S.useCallback(async()=>{try{if(navigator.clipboard&&navigator.clipboard.writeText){await navigator.clipboard.writeText(e),g(),a==null||a();return}const h=document.createElement("textarea");h.value=e,h.style.position="fixed",h.style.left="-999999px",h.style.top="-999999px",document.body.appendChild(h),h.focus(),h.select();try{document.execCommand("copy"),g(),a==null||a()}catch(b){const w=b instanceof Error?b:new Error("Copy failed");console.warn("Copy to clipboard failed:",w),i==null||i(w)}finally{document.body.removeChild(h)}}catch(h){const b=h instanceof Error?h:new Error("Copy failed");console.warn("Copy to clipboard failed:",b),i==null||i(b)}},[e,g,a,i]);return p.jsxs("div",{className:"relative inline-flex",children:[p.jsx("button",{onClick:v,className:`${m.button} hover:bg-gray-100 rounded transition-colors ${t}`,title:n,children:p.jsx(Pf,{className:`${m.icon} text-gray-400 ${r}`})}),p.jsx("div",{className:`${d()} ${m.tooltip} transition-opacity duration-150 ${u?"opacity-100 animate-fade-in":"opacity-0 pointer-events-none"}`,style:{visibility:u?"visible":"hidden"},children:o})]})},fU=({isOpen:e,onClose:t,title:r,data:n,initialViewMode:a="plain",modalHeight:i="50vh"})=>{const[o,s]=S.useState(a),l=S.useMemo(()=>{if(n==null)return!1;if(typeof n=="string")try{return JSON.parse(n),!0}catch{return!1}return typeof n=="object"},[n]),u=c=>{c.target===c.currentTarget&&t()};return e?p.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4",onClick:u,children:p.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-6xl w-full flex flex-col",style:{height:i},children:[p.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200",children:[p.jsxs("div",{className:"flex items-center gap-4",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx(Vs,{className:"w-5 h-5 text-gray-400"}),p.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:r})]}),l&&p.jsxs("div",{className:"flex items-center gap-1 ml-4 pl-4 border-l border-gray-200",children:[p.jsx("button",{onClick:()=>s("plain"),className:`p-1.5 hover:bg-gray-200 rounded transition-colors ${o==="plain"?"bg-gray-200":""}`,title:"Plain JSON view",children:p.jsx(Of,{className:"w-4 h-4 text-gray-400"})}),p.jsx("button",{onClick:()=>s("interactive"),className:`p-1.5 hover:bg-gray-200 rounded transition-colors ${o==="interactive"?"bg-gray-200":""}`,title:"Interactive JSON view (fold/unfold)",children:p.jsx(Ef,{className:"w-4 h-4 text-gray-400"})})]})]}),p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx(Ti,{text:typeof n=="string"?n:JSON.stringify(n,null,2),title:"Copy content",className:"p-2 rounded-lg",iconClassName:"w-4 h-4 text-gray-500"}),p.jsx("button",{onClick:t,className:"p-2 hover:bg-gray-100 rounded-lg transition-colors",title:"Close",children:p.jsx(Nf,{className:"w-4 h-4 text-gray-500"})})]})]}),p.jsx("div",{className:"flex-1 overflow-hidden",children:p.jsx(xt,{data:n,showHeader:!1,className:"h-full border-0",defaultExpanded:!0,viewMode:o,onViewModeChange:s})})]})}):null},dU=({data:e,level:t=0,expandedKeys:r=new Set,onToggleKey:n,keyPath:a=""})=>{const i=t*16,o=(s,l,u)=>{const c=u?`${u}.${l}`:l||"";if(s===null)return p.jsx("span",{className:"text-gray-400 italic",children:"null"});if(s===void 0)return p.jsx("span",{className:"text-gray-400 italic",children:"undefined"});if(typeof s=="boolean")return p.jsx("span",{className:"text-purple-600 font-medium",children:String(s)});if(typeof s=="number")return p.jsx("span",{className:"text-blue-600 font-medium",children:s});if(typeof s=="string"){const f=s.length>100,d=f&&!r.has(`${c}._string`)?`${s.substring(0,100)}...`:s;return p.jsxs("div",{className:"inline",children:[p.jsxs("span",{className:"text-green-600",children:['"',d,'"']}),f&&p.jsx("button",{onClick:()=>n==null?void 0:n(`${c}._string`),className:"ml-2 text-xs text-blue-500 hover:text-blue-700 underline",children:r.has(`${c}._string`)?"Show less":"Show more"})]})}if(Array.isArray(s)){const f=r.has(c);return s.length===0?p.jsx("span",{className:"text-gray-500",children:"[]"}):p.jsxs("div",{children:[p.jsxs("div",{className:"flex items-center",children:[p.jsxs("button",{onClick:()=>n==null?void 0:n(c),className:"flex items-center gap-1 hover:bg-gray-100 p-1 rounded transition-colors",children:[f?p.jsx(fr,{className:"w-3 h-3 text-gray-400"}):p.jsx(ki,{className:"w-3 h-3 text-gray-400"}),p.jsxs("span",{className:"text-gray-600 text-xs",children:["Array[",s.length,"]"]})]}),!f&&p.jsx("span",{className:"text-gray-400 ml-2",children:"[...]"})]}),f&&p.jsx("div",{className:"ml-4 mt-1",children:s.map((m,g)=>p.jsxs("div",{className:"flex items-start gap-2 py-1",style:{marginLeft:`${i}px`},children:[p.jsxs("span",{className:"text-gray-400 text-xs mt-0.5 min-w-[20px]",children:[g,":"]}),p.jsx("div",{className:"flex-1",children:o(m,String(g),`${c}[${g}]`)})]},g))})]})}if(typeof s=="object"){const f=Object.keys(s),d=r.has(c);return f.length===0?p.jsx("span",{className:"text-gray-500",children:"{}"}):p.jsxs("div",{children:[p.jsxs("div",{className:"flex items-center",children:[p.jsxs("button",{onClick:()=>n==null?void 0:n(c),className:"flex items-center gap-1 hover:bg-gray-100 p-1 rounded transition-colors",children:[d?p.jsx(fr,{className:"w-3 h-3 text-gray-400"}):p.jsx(ki,{className:"w-3 h-3 text-gray-400"}),p.jsxs("span",{className:"text-gray-600 text-xs",children:["Object ","{",f.length," ",f.length===1?"key":"keys","}"]})]}),!d&&p.jsx("span",{className:"text-gray-400 ml-2",children:"{ ... }"})]}),d&&p.jsx("div",{className:"ml-4 mt-1",children:f.map(g=>p.jsxs("div",{className:"flex items-start gap-2 py-1",style:{marginLeft:`${i}px`},children:[p.jsxs("span",{className:"text-blue-700 text-xs mt-0.5 font-medium min-w-fit",children:['"',g,'":']}),p.jsx("div",{className:"flex-1",children:o(s[g],g,c)})]},g))})]})}return p.jsx("span",{className:"text-gray-600",children:String(s)})};return p.jsx("div",{className:"text-xs",children:o(e,"",a)})},nb=e=>{const t=[];if(t.push(""),e==null)return t;let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{return t}return typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).forEach(n=>{t.push(n)}),Array.isArray(r)&&r.forEach((n,a)=>{t.push(`[${a}]`)}),t},xt=({data:e,padding:t="p-3",title:r="Data",className:n="",maxHeight:a="300px",showHeader:i=!0,defaultExpanded:o=!1,defaultViewMode:s="plain",viewMode:l,onViewModeChange:u,modalHeight:c="50vh"})=>{const[f,d]=S.useState(!1),[m,g]=S.useState(s),v=S.useMemo(()=>o?new Set([""]):new Set(nb(e)),[e,o]),[h,b]=S.useState(v);S.useEffect(()=>{o||b(new Set(nb(e)))},[e,o]);const w=l!==void 0,x=w?l:m,T=$=>{w?u==null||u($):g($)},{isValidJson:y,displayContent:O}=S.useMemo(()=>{if(e==null)return{isValidJson:!1,displayContent:e===null?"null":"undefined"};if(typeof e=="string")try{return{isValidJson:!0,displayContent:JSON.parse(e)}}catch{return{isValidJson:!1,displayContent:e}}return typeof e=="object"?{isValidJson:!0,displayContent:e}:{isValidJson:!1,displayContent:String(e)}},[e]),A=S.useCallback($=>{b(P=>{const _=new Set(P);return _.has($)?_.delete($):_.add($),_})},[]),j=S.useCallback(()=>{d(!0)},[]),C=S.useCallback(()=>{d(!1)},[]);return p.jsxs(p.Fragment,{children:[p.jsxs("div",{className:`bg-white border border-gray-200 rounded-md overflow-hidden ${n}`,children:[i&&p.jsxs("div",{className:"bg-gray-50 border-b border-gray-200 px-4 py-2 flex items-center justify-between",children:[y&&p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("button",{onClick:()=>T("plain"),className:`p-1 hover:bg-gray-200 rounded transition-colors ${x==="plain"?"bg-gray-200":""}`,title:"Plain JSON view",children:p.jsx(Of,{className:"w-4 h-4 text-gray-400"})}),p.jsx("button",{onClick:()=>T("interactive"),className:`p-1 hover:bg-gray-200 rounded transition-colors ${x==="interactive"?"bg-gray-200":""}`,title:"Interactive JSON view (fold/unfold)",children:p.jsx(Ef,{className:"w-4 h-4 text-gray-400"})})]}),p.jsx("div",{className:"flex-1"}),p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("button",{onClick:j,className:"p-1 hover:bg-gray-200 rounded transition-colors",title:"Expand to full screen",children:p.jsx($f,{className:"w-4 h-4 text-gray-400"})}),p.jsx(Ti,{text:y?JSON.stringify(O,null,2):O,title:"Copy content",className:"p-1",iconClassName:"w-4 h-4 text-gray-400"})]})]}),p.jsxs("div",{className:`${t||"p-3"} overflow-auto bg-white`,style:{maxHeight:a},children:[y?x==="interactive"?p.jsx(dU,{data:O,expandedKeys:h,onToggleKey:A,keyPath:""}):p.jsx("div",{className:"text-xs text-gray-700 whitespace-pre",children:JSON.stringify(O,null,2)}):p.jsx("div",{className:"text-xs text-gray-700 whitespace-pre-wrap",children:O}),!O&&O!==0&&O!==!1&&p.jsx("div",{className:"text-center text-gray-400 text-sm py-8",children:"No data available"})]})]}),p.jsx(fU,{isOpen:f,onClose:C,title:r,data:O,initialViewMode:x,modalHeight:c})]})};class ab{constructor(t){kt(this,"config");this.config=t}async getObservationById(t){var r,n;console.log("🚀 OBSERVATION API CALL:",{observationId:t.observationId,traceId:t.traceId,projectId:t.projectId,tracingUrl:this.config.tracingUrl});try{const a={json:{observationId:t.observationId,traceId:t.traceId,projectId:t.projectId}},i=encodeURIComponent(JSON.stringify(a)),o=`${this.config.tracingUrl}/tracing/api/trpc/observations.byId?input=${i}`;console.log("📤 Making observation GET request to:",o),console.log("📤 Headers:",this.config.headers);const s=await fetch(o,{method:"GET",headers:this.config.headers});if(console.log("📥 Observation response status:",s.status),console.log("📥 Observation response ok:",s.ok),!s.ok){const c=await s.text();throw console.error("❌ Observation API Error:",c),new Error(`HTTP error! status: ${s.status}, response: ${c}`)}const l=await s.json();console.log("✅ Observation API Response:",l);const u=((n=(r=l==null?void 0:l.result)==null?void 0:r.data)==null?void 0:n.json)||null;return console.log("📊 Extracted observation data:",u),u}catch(a){return console.error("❌ Error fetching observation data:",a),null}}async getTraceById(t){var r,n,a;console.log("🚀 TRACE API CALL:",{traceId:t.traceId,projectId:t.projectId,tracingUrl:this.config.tracingUrl});try{const i={json:{traceId:t.traceId,projectId:t.projectId}},o=encodeURIComponent(JSON.stringify(i)),s=`${this.config.tracingUrl}/tracing/api/trpc/traces.byIdWithObservationsAndScores?input=${o}&pollingApi=true&skipGlobalToast=true`;console.log("📤 Making trace GET request to:",s),console.log("📤 Headers:",this.config.headers);const l=await fetch(s,{method:"GET",headers:this.config.headers});if(console.log("📥 Trace response status:",l.status),console.log("📥 Trace response ok:",l.ok),!l.ok){const d=await l.text();throw console.error("❌ Trace API Error:",d),new Error(`HTTP error! status: ${l.status}, response: ${d}`)}const u=await l.json();console.log("✅ Trace API Response:",u);const f=[...((a=(n=(r=u==null?void 0:u.result)==null?void 0:r.data)==null?void 0:n.json)==null?void 0:a.observations)||[]].sort((d,m)=>new Date(d.startTime).getTime()-new Date(m.startTime).getTime());return console.log("📊 Sorted observations:",f.length,"total"),f}catch(i){return console.error("❌ Error fetching trace data:",i),null}}matchNodeToObservationById(t,r){console.log("🔍 Matching node to observation by ID:",{nodeId:t,totalObservations:r.length});const n=r.find(a=>{let i=a.metadata;if(typeof i=="string")try{i=JSON.parse(i)}catch(s){return console.warn("Failed to parse metadata string:",s),!1}if(!(i!=null&&i.pipeTraceId)||(i==null?void 0:i._pipeSeq)===void 0)return!1;const o=`${i.pipeTraceId}.${i._pipeSeq}`;return console.log("Comparing:",{nodeId:t,observationNodeId:o,match:t===o}),t===o});if(!n){const a=t.split("_");if(a.length===2){const[,i]=a,o=parseInt(i,10);if(!isNaN(o)){const s=r.find(l=>{let u=l.metadata;if(typeof u=="string")try{u=JSON.parse(u)}catch(c){return console.warn("Failed to parse metadata string in fallback:",c),!1}return(u==null?void 0:u._pipeSeq)===o});if(s){let l=s.metadata;if(typeof l=="string")try{l=JSON.parse(l)}catch{}return console.log("✅ Matched observation by sequence:",{id:s.id,name:s.name,type:s.type,_pipeSeq:l==null?void 0:l._pipeSeq}),s}}}}if(n){let a=n.metadata;if(typeof a=="string")try{a=JSON.parse(a)}catch{}console.log("✅ Matched observation:",{id:n.id,name:n.name,type:n.type,pipeTraceId:a==null?void 0:a.pipeTraceId,_pipeSeq:a==null?void 0:a._pipeSeq})}else console.log("✅ Matched observation: No match found");return n||null}sleep(t){return new Promise(r=>setTimeout(r,t))}async getObservationForNode(t,r,n,a=5,i=2e3){console.log("🔄 Getting observation for node by ID with retry logic:",{nodeId:t,traceId:r,projectId:n,maxRetries:a,retryDelay:i});let o=null;for(let s=1;s<=a;s++)try{console.log(`📊 Attempt ${s}/${a} for node ${t}`);const l=await this.getTraceById({traceId:r,projectId:n});if(!l||l.length===0){if(console.log(`❌ Attempt ${s}: No observations found for trace`),o=new Error("No observations found for trace"),s<a){console.log(`⏳ Waiting ${i}ms before retry...`),await this.sleep(i);continue}return null}const u=this.matchNodeToObservationById(t,l);if(!u){if(console.log(`❌ Attempt ${s}: No matching observation found for node ID: ${t}`),o=new Error(`No matching observation found for node ID: ${t}`),s<a){console.log(`⏳ Waiting ${i}ms before retry...`),await this.sleep(i);continue}return null}const c=await this.getObservationById({observationId:u.id,traceId:r,projectId:n});if(c)return console.log(`✅ Success on attempt ${s}: Found observation data for node ${t}`),c;if(o=new Error("No detailed data returned"),s<a){console.log(`⏳ No data returned, waiting ${i}ms before retry...`),await this.sleep(i);continue}}catch(l){if(o=l,console.error(`❌ Attempt ${s} failed:`,l),s<a){console.log(`⏳ Waiting ${i}ms before retry...`),await this.sleep(i);continue}}return console.error("❌ All retries exhausted. Last error:",o),null}updateConfig(t){this.config=t}getConfig(){return this.config}}function ib({node:e,onToggle:t,isExpanded:r=!1,onNodeClick:n,selectedNodeIds:a,showDetailView:i=!0,apiConfig:o,projectId:s,nodeIndex:l=0}){const u=S.useMemo(()=>{var L;return e.type==="GuardrailsInputScan"||e.type==="GuardrailsOutputScan"||((L=e.name)==null?void 0:L.toLowerCase().includes("guardrail"))},[e.type,e.name]),c=S.useMemo(()=>u?["summary","request"]:e.type==="ProxyWorker"?["request","response"]:e.type==="llm"?["summary","request","response"]:e.type==="tool"?["request","response","logs"]:[],[e.type,u]),[f,d]=S.useState(c[0]),m=a?a.has(e.id):!1,g=e.children&&e.children.length>0,[v,h]=S.useState(null),[b,w]=S.useState(!1),[x,T]=S.useState(null),[y,O]=S.useState(!1),[A,j]=S.useState(!1),C=["llm"],$=5,P=2e3;console.log("🔧 DebugCard - Props received:",{nodeId:e.id,nodeName:e.name,nodeType:e.type,nodeIndex:l,hasApiConfig:!!o,apiConfigDetails:o?{tracingUrl:o.tracingUrl,projectId:o.projectId,hasHeaders:!!o.headers}:null,projectIdProp:s,propsMatch:(o==null?void 0:o.projectId)===s});const _=S.useMemo(()=>(console.log("🔧 DebugCard - Creating ApiService:",{hasApiConfig:!!o,willCreateService:!!o}),o?new ab(o):null),[o]),F=S.useMemo(()=>C.includes(e.type),[e.type]),N=S.useCallback(async()=>{if(!F){console.log("🔍 DebugCard - Node type not API-enabled:",e.type);return}if(!_||!s||y){console.log("🔍 DebugCard - API call skipped:",{hasApiService:!!_,hasProjectId:!!s,hasLoadedApi:y,isApiEnabledNode:F,nodeType:e.type,reason:_?s?"Already loaded":"No project ID":"No API service"});return}w(!0),T(null),j(!1);try{const L=await _.getObservationForNode(e.id,e.runId,s,$,P);if(L){const W={...L};try{typeof L.input=="string"?W.input=JSON.parse(L.input):L.input&&typeof L.input=="object"&&(W.input=JSON.parse(JSON.stringify(L.input,null,2)))}catch{W.input=L.input||{}}try{typeof L.output=="string"?W.output=JSON.parse(L.output):L.output&&typeof L.output=="object"&&(W.output=JSON.parse(JSON.stringify(L.output,null,2)))}catch{W.output=L.output||{}}h(W),O(!0),j(!1)}else console.log("📊 All API retries exhausted, using fallback node data"),T("API data unavailable after retries, showing local data"),j(!0),O(!0)}catch(L){console.error("Error fetching observation data:",L),T("API data unavailable, showing local data"),j(!0),O(!0)}finally{w(!1)}},[_,s,e.id,e.runId,F]);S.useEffect(()=>{c.includes(f)||d(c[0])},[c,f]),S.useEffect(()=>{h(null),w(!1),T(null),O(!1),j(!1)},[e.id]);const R=S.useCallback(L=>{d(L),console.log("🔍 DebugCard - Tab clicked:",{nodeId:e.id,nodeName:e.name,nodeType:e.type,clickedTab:L,isApiEnabledNode:F,hasApiService:!!_,hasProjectId:!!s,hasLoadedApi:y,isLoadingApi:b}),(L==="request"||L==="response")&&F&&_&&s&&!y&&!b&&(console.log("🚀 DebugCard - Triggering API call for API-enabled node:",e.id),N())},[_,s,y,b,N,e.id,F]),k=L=>{L.stopPropagation(),t&&t(e.id)},U=()=>{c.length===0&&g&&t?t(e.id):n&&i&&n(e)},q=()=>{switch(e.status){case"completed":return p.jsx("svg",{className:"flex-shrink-0",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:p.jsx("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M6 0.5C2.96243 0.5 0.5 2.96243 0.5 6C0.5 9.03757 2.96243 11.5 6 11.5C9.03757 11.5 11.5 9.03757 11.5 6C11.5 2.96243 9.03757 0.5 6 0.5ZM8.60355 4.85355C8.79882 4.65829 8.79882 4.34171 8.60355 4.14645C8.40829 3.95118 8.09171 3.95118 7.89645 4.14645L5.25 6.79289L4.10355 5.64645C3.90829 5.45118 3.59171 5.45118 3.39645 5.64645C3.20118 5.84171 3.20118 6.15829 3.39645 6.35355L4.89645 7.85355C5.09171 8.04882 5.40829 8.04882 5.60355 7.85355L8.60355 4.85355Z",fill:"#17B26A"})});case"failed":case"errored":return p.jsx("div",{className:"w-[12px] h-[12px] rounded-full bg-red-500"});case"running":return p.jsx("div",{className:"w-[12px] h-[12px] rounded-full bg-yellow-500 animate-pulse"});default:return p.jsx("div",{className:"w-[12px] h-[12px] rounded-full bg-gray-400"})}},Z=()=>{var W,G;if(u)return p.jsx("div",{className:"flex-shrink-0 relative w-[24px] h-[24px] bg-gray-200 rounded-[8px] flex items-center justify-center",children:p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"17",height:"21",viewBox:"0 0 17 21",fill:"none",className:"w-[16px] h-[16px]",children:p.jsx("path",{d:"M2.86876 3.16135L2.51444 2.22622V2.22622L2.86876 3.16135ZM1.60989 3.76534L0.944868 3.01852L0.944868 3.01852L1.60989 3.76534ZM1.11768 4.483L2.05352 4.83544L1.11768 4.483ZM8.70562 1.33287L8.35129 2.26799V2.26799L8.70562 1.33287ZM8.32871 1.21247L8.18424 2.20198L8.32871 1.21247ZM7.69438 1.33287L8.04871 2.26799H8.04871L7.69438 1.33287ZM8.07129 1.21247L8.21576 2.20198L8.07129 1.21247ZM15.2823 4.483L14.3465 4.83544L15.2823 4.483ZM13.5312 3.16135L13.1769 4.09647L13.5312 3.16135ZM14.7901 3.76534L15.4551 3.01852V3.01852L14.7901 3.76534ZM8.82819 18.9787L9.33601 19.8402L8.82819 18.9787ZM8.38871 19.1854L8.17694 18.2081H8.17694L8.38871 19.1854ZM7.57181 18.9787L8.07962 18.1173L7.57181 18.9787ZM8.01129 19.1854L8.22306 18.2081L8.01129 19.1854ZM7.10461 9.12831L7.45541 10.0648C7.72607 9.96337 7.93963 9.74983 8.04104 9.47917L7.10461 9.12831ZM8.2 6.20474L9.13643 5.85388H7.26357L8.2 6.20474ZM9.29539 9.12831L8.35897 9.47917C8.46038 9.74983 8.67393 9.96337 8.94459 10.0648L9.29539 9.12831ZM12.25 10.2351L12.6008 11.1716L12.6008 9.29868L12.25 10.2351ZM9.29539 11.3419L8.94459 10.4055C8.66955 10.5085 8.4537 10.7273 8.35435 11.0037L9.29539 11.3419ZM8.2 14.3892L7.25895 14.7275H9.14105L8.2 14.3892ZM7.10461 11.3419L8.04565 11.0037C7.9463 10.7273 7.73045 10.5085 7.45541 10.4055L7.10461 11.3419ZM4.15 10.2351L3.7992 9.29868L3.7992 11.1716L4.15 10.2351ZM9.33601 19.8402C10.251 19.3009 11.9823 18.176 13.4966 16.582C15.0004 14.999 16.4 12.8356 16.4 10.2351H14.4C14.4 12.0983 13.3903 13.79 12.0466 15.2045C10.7133 16.608 9.15867 17.6231 8.32038 18.1173L9.33601 19.8402ZM16.4 10.2351V5.88609H14.4V10.2351H16.4ZM13.8856 2.22622L9.05994 0.397748L8.35129 2.26799L13.1769 4.09647L13.8856 2.22622ZM7.34006 0.397749L2.51444 2.22622L3.22309 4.09647L8.04871 2.26799L7.34006 0.397749ZM0 5.88609V10.2351H2V5.88609H0ZM0 10.2351C0 12.8356 1.39958 14.999 2.90343 16.582C4.41773 18.176 6.14904 19.3009 7.06399 19.8402L8.07962 18.1173C7.24133 17.6231 5.68674 16.608 4.35344 15.2045C3.00971 13.79 2 12.0983 2 10.2351H0ZM2.51444 2.22622C1.91725 2.4525 1.36429 2.64503 0.944868 3.01852L2.27492 4.51216C2.352 4.44352 2.47279 4.38077 3.22309 4.09647L2.51444 2.22622ZM2 5.88609C2 5.07787 2.01549 4.93642 2.05352 4.83544L0.181849 4.13057C-0.0154909 4.65457 0 5.24018 0 5.88609H2ZM0.944868 3.01852C0.60414 3.32193 0.342573 3.70379 0.181849 4.13057L2.05352 4.83544C2.10072 4.71011 2.17703 4.59933 2.27492 4.51216L0.944868 3.01852ZM9.05994 0.397748C8.91343 0.342231 8.70233 0.256421 8.47319 0.222965L8.18424 2.20198C8.15508 2.19772 8.14261 2.19201 8.16863 2.20063C8.18278 2.20531 8.2032 2.21249 8.23486 2.22419C8.26671 2.23595 8.30339 2.24984 8.35129 2.26799L9.05994 0.397748ZM8.04871 2.26799C8.09661 2.24984 8.13329 2.23595 8.16514 2.22419C8.1968 2.21249 8.21722 2.20531 8.23137 2.20063C8.25739 2.19201 8.24492 2.19772 8.21576 2.20198L7.92681 0.222965C7.69767 0.256422 7.48657 0.342232 7.34005 0.397749L8.04871 2.26799ZM8.47319 0.222965C8.29201 0.196512 8.10799 0.196512 7.92681 0.222965L8.21576 2.20198C8.20532 2.20351 8.19468 2.20351 8.18424 2.20198L8.47319 0.222965ZM16.4 5.88609C16.4 5.24018 16.4155 4.65457 16.2182 4.13057L14.3465 4.83544C14.3845 4.93642 14.4 5.07787 14.4 5.88609H16.4ZM13.1769 4.09647C13.9272 4.38077 14.048 4.44352 14.1251 4.51216L15.4551 3.01852C15.0357 2.64503 14.4827 2.4525 13.8856 2.22622L13.1769 4.09647ZM16.2182 4.13057C16.0574 3.70379 15.7959 3.32193 15.4551 3.01852L14.1251 4.51216C14.223 4.59933 14.2993 4.7101 14.3465 4.83544L16.2182 4.13057ZM8.32038 18.1173C8.2687 18.1477 8.2323 18.1692 8.20084 18.1871C8.17008 18.2046 8.15362 18.2132 8.14482 18.2175C8.13738 18.2212 8.14003 18.2195 8.14934 18.2161C8.15948 18.2124 8.16954 18.2097 8.17694 18.2081L8.60048 20.1627C8.9274 20.0919 9.16869 19.9388 9.33601 19.8402L8.32038 18.1173ZM7.06399 19.8402C7.23131 19.9388 7.4726 20.0919 7.79952 20.1627L8.22306 18.2081C8.23046 18.2097 8.24052 18.2124 8.25066 18.2161C8.25997 18.2195 8.26262 18.2212 8.25518 18.2175C8.24638 18.2132 8.22992 18.2046 8.19916 18.1871C8.1677 18.1692 8.1313 18.1477 8.07962 18.1173L7.06399 19.8402ZM8.17694 18.2081C8.18757 18.2058 8.19524 18.2045 8.19954 18.2039C8.20396 18.2032 8.20647 18.203 8.20701 18.2029C8.20764 18.2029 8.20489 18.2031 8.2 18.2031C8.19511 18.2031 8.19236 18.2029 8.19299 18.2029C8.19353 18.203 8.19604 18.2032 8.20046 18.2039C8.20476 18.2045 8.21243 18.2058 8.22306 18.2081L7.79952 20.1627C8.04819 20.2166 8.35181 20.2166 8.60048 20.1627L8.17694 18.2081ZM8.04104 9.47917L9.13643 6.5556L7.26357 5.85388L6.16818 8.77745L8.04104 9.47917ZM7.26357 6.5556L8.35897 9.47917L10.2318 8.77745L9.13643 5.85388L7.26357 6.5556ZM8.94459 10.0648L11.8992 11.1716L12.6008 9.29868L9.6462 8.19186L8.94459 10.0648ZM11.8992 9.29868L8.94459 10.4055L9.6462 12.2784L12.6008 11.1716L11.8992 9.29868ZM8.35435 11.0037L7.25895 14.0509L9.14105 14.7275L10.2364 11.6802L8.35435 11.0037ZM9.14105 14.0509L8.04565 11.0037L6.16356 11.6802L7.25895 14.7275L9.14105 14.0509ZM7.45541 10.4055L4.5008 9.29868L3.7992 11.1716L6.75381 12.2784L7.45541 10.4055ZM4.5008 11.1716L7.45541 10.0648L6.75381 8.19186L3.7992 9.29868L4.5008 11.1716Z",fill:"#101828"})})});let L="agent";switch(e.type){case"Agent":L="agent";break;case"llm":L="model";break;case"tool":L="workflowtool";break;case"ProxyWorker":L="app";break;default:L="agent"}return p.jsx(xi,{icon:e.icon,iconSource:L,size:"small",name:e.name,className:"w-[24px] h-[24px]",toolType:e.type==="tool"?(W=e.metadata)==null?void 0:W.type:void 0,provider:e.type==="llm"?(G=e.metadata)==null?void 0:G.provider:void 0,modelName:e.type==="llm"?e.name:void 0})},E=L=>L?L<1e3?`${L}ms`:`${(L/1e3).toFixed(2)}s`:"",B=L=>{if(!L)return"Tool";switch(L){case"route_to_user":return"Response to User";default:return L.split("_").map(W=>W.charAt(0).toUpperCase()+W.slice(1)).join(" ")}},z=()=>c,H=()=>{var J,M;let L=e.toolInvocations||[];e.type==="llm"&&Array.isArray(e.output)&&(L=e.output.filter(Q=>Q&&typeof Q=="object"&&Q.name&&Q.tool_call_id));const W=L.length>0||e.children&&e.children.length>0,G=e.isResponse||L.length>0&&L[0].name==="route_to_user";return W?p.jsxs("div",{className:"space-y-1",children:[p.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[p.jsx("span",{className:"text-xs text-gray-600",children:G?"Responded":"Invoked"}),L.length>0&&L.map((Q,K)=>p.jsxs("div",{className:"flex items-center gap-[4px] px-[8px] py-[2px] border border-gray-300 rounded-[4px] text-xs",children:[Q.isAgentHandoff?p.jsx(Sf,{className:"w-[12px] h-[12px] text-blue-500 flex-shrink-0"}):p.jsx(Vs,{className:"w-[12px] h-[12px] text-blue-500 flex-shrink-0"}),p.jsx("span",{className:"text-gray-600 truncate",children:B(Q.name||Q.toolName)})]},Q.tool_call_id||K)),L.length===0&&e.children&&e.children.length>0&&e.children.map((Q,K)=>p.jsxs("div",{className:"flex items-center gap-[4px] px-[8px] py-[2px] border border-gray-300 rounded-[4px] text-xs",children:[Q.type==="tool"?p.jsx(Vs,{className:"w-[12px] h-[12px] text-green-500 flex-shrink-0"}):p.jsx(Sf,{className:"w-[12px] h-[12px] text-blue-500 flex-shrink-0"}),p.jsx("span",{className:"text-gray-600 truncate",children:Q.name||"Unknown"})]},Q.id||K))]}),L.length>0&&((M=(J=L[0])==null?void 0:J.args)==null?void 0:M.reason)&&p.jsxs("div",{children:[p.jsx("div",{className:"text-xs font-medium text-gray-400 mb-[4px]",children:"Reason"}),p.jsx("div",{className:"text-xs text-gray-600",children:L[0].args.reason})]})]}):e.output&&!W?p.jsx("div",{className:"space-y-1",children:p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"text-xs text-gray-600",children:"Generated"}),p.jsxs("div",{className:"flex items-center gap-[4px] px-[8px] py-[4px] border border-gray-200 rounded text-xs",children:[p.jsx(Nb,{className:"w-[12px] h-[12px] text-purple-500"}),p.jsx("span",{className:"text-gray-600",children:"Response"})]})]})}):p.jsx("div",{className:"text-xs text-gray-500 italic",children:"No actions taken"})},I=L=>{var W,G,J,M;if(!(!L||typeof L!="object")){if(Array.isArray(L)){const Q=L.find(K=>K&&typeof K=="object"&&(K.name==="route_to_user"||K.toolName==="route_to_user"));if(Q)return((W=Q.args)==null?void 0:W.message)||Q.message||((G=Q.output)==null?void 0:G.message)}else if(L.name==="route_to_user"||L.toolName==="route_to_user")return((J=L.args)==null?void 0:J.message)||L.message||((M=L.output)==null?void 0:M.message);if(L.message&&typeof L.message=="string")return L.message;if(L.content&&typeof L.content=="string")return L.content;if(L.text&&typeof L.text=="string")return L.text}},V=()=>{if(!e.output)return null;const L=I(e.output);return p.jsx(xt,{padding:"py-1",data:L||e.output,title:"",showHeader:!1,maxHeight:"120px",defaultExpanded:!0,className:"border-0"})},X=()=>{if(!u||!e.output)return null;const L=e.error?e.error:e.output,W=L.scannersData,G=L.endFlow,J=L.endFlowMsg;return W?p.jsxs("div",{className:"space-y-3",children:[G&&J&&p.jsxs("div",{className:"flex items-start gap-2 p-3 bg-red-50 border border-red-200 rounded-md",children:[p.jsx(Gs,{className:"w-4 h-4 text-red-500 flex-shrink-0 mt-0.5"}),p.jsxs("div",{className:"text-xs text-red-700",children:[p.jsx("div",{className:"font-medium",children:"Guardrail Stopped"}),p.jsx("div",{className:"mt-1",children:J})]})]}),p.jsx("div",{className:"space-y-1",children:Object.entries(W).map(([M,Q])=>{if(M==="error"&&Q.scannerOutput)return p.jsxs("div",{className:"flex items-center justify-between p-1",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx(Gs,{className:"w-4 h-4 text-red-500 flex-shrink-0"}),p.jsx("span",{className:"text-xs text-gray-700 capitalize",children:"Error Scanner"})]}),p.jsx("div",{className:"flex items-center gap-3",children:p.jsx("span",{className:"text-xs text-gray-500",children:Q.scannerOutput.Duration})})]},M);if(Q.scannerOutput){const K=Q.scannerOutput.Validity,se=Q.scannerOutput.RiskScore,ne=Q.scannerOutput.Duration;let fe="text-gray-500",ue="bg-gray-100";return se!==void 0&&(se===0?(fe="text-green-600",ue="bg-green-50"):se<=3?(fe="text-yellow-600",ue="bg-yellow-50"):se<=6?(fe="text-orange-600",ue="bg-orange-50"):(fe="text-red-600",ue="bg-red-50")),p.jsxs("div",{className:"flex items-center justify-between p-1",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[K?p.jsx(Ab,{className:"w-4 h-4 text-green-500 flex-shrink-0"}):p.jsx(Gs,{className:"w-4 h-4 text-red-500 flex-shrink-0"}),p.jsx("span",{className:"text-xs text-gray-700",children:M.replace(/([A-Z])/g," $1").trim()})]}),p.jsxs("div",{className:"flex items-center gap-3",children:[se!==void 0&&p.jsxs("div",{className:`px-2 py-0.5 rounded text-xs font-medium ${ue} ${fe}`,children:["Risk: ",se]}),p.jsx("span",{className:"text-xs text-gray-500",children:ne})]})]},M)}return null})})]}):null},re=()=>{switch(f){case"summary":if(u)return p.jsxs("div",{className:"space-y-1",children:[e.input&&p.jsxs("div",{className:"border-b border-gray-100 pb-[8px]",children:[p.jsx("div",{className:"text-xs font-medium text-gray-400 mb-[8px]",children:"Input"}),p.jsx(xt,{padding:"py-1",data:e.input,title:"",showHeader:!1,maxHeight:"150px",defaultExpanded:!0,className:"border-0"})]}),(e.output||e.error)&&p.jsxs("div",{children:[p.jsx("div",{className:"text-xs font-medium text-gray-400 mb-[8px]",children:"Result"}),e.error&&!u?typeof e.error=="string"?p.jsx("div",{className:"text-xs text-gray-600",children:e.error}):p.jsx(xt,{padding:"py-1",data:e.error,title:"",showHeader:!1,maxHeight:"120px",defaultExpanded:!0,className:"border-0"}):X()]})]});let L=!1;return e.type==="llm"&&Array.isArray(e.output)&&(L=e.output.some(G=>G&&typeof G=="object"&&G.name&&G.tool_call_id)),p.jsxs("div",{className:"space-y-1",children:[e.input&&p.jsxs("div",{className:"border-b border-gray-100 pb-[8px]",children:[p.jsx("div",{className:"text-xs font-medium text-gray-400 mb-[8px]",children:"Input"}),p.jsx(xt,{padding:"py-1",data:e.input,title:"",showHeader:!1,maxHeight:"120px",defaultExpanded:!0,className:"border-0"})]}),p.jsxs("div",{className:"border-b border-gray-100 pb-2",children:[p.jsx("div",{className:"text-xs font-medium text-gray-400 mb-[4px]",children:"Action"}),H()]}),e.output&&!L&&p.jsxs("div",{className:"border-b border-gray-100 pb-[8px]",children:[p.jsx("div",{className:"text-xs font-medium text-gray-400 mb-[4px]",children:"Output"}),V()]}),e.error&&p.jsxs("div",{className:"border-b border-gray-100 pb-[8px]",children:[p.jsx("div",{className:"text-xs font-medium text-gray-400 mb-[4px]",children:"Error"}),typeof e.error=="string"?p.jsx("div",{className:"text-xs text-red-600",children:e.error}):p.jsx(xt,{padding:"py-1",data:e.error,title:"",showHeader:!1,maxHeight:"120px",defaultExpanded:!0,className:"border-0"})]})]});case"request":if(F&&_){if(b)return p.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[p.jsx(Cf,{className:"w-5 h-5 animate-spin text-blue-500 mb-2 mx-auto"}),p.jsx("div",{className:"text-sm text-gray-600",children:"Loading request data from API..."}),p.jsx("div",{className:"text-xs text-gray-400 mt-1",children:"Trace data may take a few seconds to be available"})]});if(x&&!A)return p.jsx("div",{className:"flex items-center justify-center py-8",children:p.jsxs("div",{className:"text-center",children:[p.jsx("div",{className:"text-red-500 text-sm mb-2",children:"Failed to load API data"}),p.jsx("div",{className:"text-xs text-gray-500",children:x}),p.jsx("button",{onClick:N,className:"mt-2 px-3 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600",children:"Retry"})]})});if(!A&&(v!=null&&v.input))return p.jsx(xt,{data:v.input,title:"Request Data (API)",maxHeight:"250px",defaultExpanded:!1,defaultViewMode:"plain"})}return u&&e.output?p.jsx(xt,{data:e.output,title:"Full Scanner Output",maxHeight:"250px",defaultExpanded:!1,defaultViewMode:"plain"}):p.jsx(xt,{data:e.input,title:A?"Request Data (Fallback)":"Request Data",maxHeight:"250px",defaultExpanded:!1,defaultViewMode:"plain"});case"response":if(F&&_){if(b)return p.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[p.jsx(Cf,{className:"w-5 h-5 animate-spin text-blue-500 mb-2 mx-auto"}),p.jsx("div",{className:"text-sm text-gray-600",children:"Loading response data from API..."}),p.jsx("div",{className:"text-xs text-gray-400 mt-1",children:"Trace data may take a few seconds to be available"})]});if(x&&!A)return p.jsx("div",{className:"flex items-center justify-center py-8",children:p.jsxs("div",{className:"text-center",children:[p.jsx("div",{className:"text-red-500 text-sm mb-2",children:"Failed to load API data"}),p.jsx("div",{className:"text-xs text-gray-500",children:x}),p.jsx("button",{onClick:N,className:"mt-2 px-3 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600",children:"Retry"})]})});if(!A&&(v!=null&&v.output))return p.jsx(xt,{data:v.output,title:"Response Data (API)",maxHeight:"250px",defaultExpanded:!1,defaultViewMode:"plain"})}return p.jsx(xt,{data:e.output,title:A?"Response Data (Fallback)":"Response Data",maxHeight:"250px",defaultExpanded:!1,defaultViewMode:"plain"});case"logs":const W={executionLog:[e.startTime&&{timestamp:new Date(e.startTime).toISOString(),level:"INFO",message:`${e.type==="tool"?"Tool":"Node"} execution started`,context:{nodeId:e.id,name:e.name,type:e.type}},e.status==="completed"&&{timestamp:new Date(e.endTime||e.startTime).toISOString(),level:"INFO",message:"Response received",context:{status:e.status,duration:e.duration,llmUsage:e.llmUsage}},e.endTime&&{timestamp:new Date(e.endTime).toISOString(),level:"SUCCESS",message:`${e.type==="tool"?"Tool":"Node"} execution completed`,context:{endTime:e.endTime,totalDuration:e.duration?`${e.duration}ms`:"unknown"}}].filter(Boolean),metadata:{totalLogs:0,startTime:e.startTime,endTime:e.endTime,duration:e.duration,status:e.status}};return W.metadata.totalLogs=W.executionLog.length,p.jsx(xt,{data:W,title:"Execution Logs",maxHeight:"250px",defaultExpanded:!0,defaultViewMode:"plain"});default:return null}};return p.jsxs("div",{className:"bg-white w-full",children:[p.jsx("div",{className:`flex items-center pl-[8px] pr-[8px] relative transition-colors cursor-pointer w-full
|
|
294
|
+
</svg>`},UB=(e,t)=>{const r=e.toLowerCase();if(r.includes("code"))return Ft.inlineTool;if(r.includes("workflow")||r.includes("library"))return Ft.toolLibrary;if(r.includes("knowledge"))return Ft.KNOWLEDGE;if(r.includes("mcp"))return Ft.MCP;if(Ft[e])return Ft[e];const n=t.toLowerCase();return n.includes("code")||n.includes("inline")||n.includes("calculate")?Ft.inlineTool:n.includes("library")||n.includes("workflow")?Ft.toolLibrary:n.includes("knowledge")||n.includes("document")||n.includes("fetch")?Ft.KNOWLEDGE:n.includes("mcp")||n.includes("protocol")?Ft.MCP:Ft.toolLibrary},xi=({icon:e,iconSource:t="agent",size:r="small",className:n="",name:a="Unknown",toolType:i,provider:o,modelName:s})=>{const[l,u]=S.useState(!1),[c,f]=S.useState(!1),[d,m]=S.useState(!1),g=LB(e),v=FB[r];if(t==="model"){const w=$0(o),x=()=>{m(!0)};if(d){const T=o?o.charAt(0).toUpperCase():"🤖";return p.jsx("div",{className:`${v} rounded-[8px] bg-gray-200 flex items-center justify-center ${n}`,children:p.jsx("span",{className:"text-gray-900 text-xs font-bold",children:T})})}return p.jsx("img",{src:w,alt:s||a,className:`${v} rounded-[8px] p-[4px] ${n}`,onError:x})}if(g!=null&&g.name&&g.name!=="fallback"&&!l){const w=BB(g,t),x=()=>{u(!0)};return p.jsx("img",{src:w,alt:a,className:`${v} rounded-[8px] p-[4px] object-cover ${n}`,onError:x})}if(l&&!c&&t==="agent"){const w=`${window.location.origin}/agenticai/assets/agent-avatars/avatar1.svg`,x=()=>{f(!0)};return p.jsx("img",{src:w,alt:a,className:`${v} rounded-[8px] p-[4px] object-cover ${n}`,onError:x})}if(t==="model"){const w=$0(o),x=()=>{m(!0)};if(d){const T=o?o.charAt(0).toUpperCase():"🤖";return p.jsx("div",{className:`${v} rounded-[8px] bg-gray-200 flex items-center justify-center ${n}`,children:p.jsx("span",{className:"text-gray-900 text-xs font-bold",children:T})})}return p.jsx("img",{src:w,alt:s||a,className:`${v} rounded-[8px] p-[4px] ${n}`,onError:x})}const h=g||RB(a,t);if(t==="workflowtool"){const w=i||h.type||"toolLibrary",x=UB(w,a);return p.jsx("div",{className:`${v} rounded-[8px] flex items-center justify-center bg-gray-100 ${n}`,children:p.jsx("div",{dangerouslySetInnerHTML:{__html:x}})})}const b=`${window.location.origin}/agenticai/assets/agent-avatars/avatar1.svg`;return p.jsx("img",{src:b,alt:a,className:`${v} rounded-[8px] p-[4px] object-cover ${n}`})},k0=({data:e,className:t})=>{const[r,n]=S.useState(5),a=()=>{n(o=>Math.min(o+10,e.length))},i=o=>o>=1e3?`${Math.floor(o/1e3)}k`:o.toString();return p.jsxs("div",{className:le("w-full",t),children:[p.jsxs("div",{className:"grid grid-cols-4 items-center gap-4 px-[16px] py-[12px] bg-gray-50 border-b border-gray-200 text-xs font-medium text-gray-600",children:[p.jsx("div",{className:"text-left",children:"Name"}),p.jsx("div",{className:"text-center",children:"Runs"}),p.jsx("div",{className:"text-center",children:"Response Time"}),p.jsx("div",{className:"text-center",children:"Tokens"})]}),p.jsx("div",{className:"divide-y divide-gray-100",children:e.slice(0,r).map((o,s)=>p.jsxs("div",{className:"grid grid-cols-4 items-center gap-4 px-[16px] py-[12px] cursor-pointer transition-colors duration-150 border-b border-gray-200",children:[p.jsxs("div",{className:"flex items-center gap-[8px]",children:[p.jsx("div",{className:"flex-shrink-0",children:p.jsx(xi,{icon:o.icon,iconSource:"agent",size:"small",name:o.name||"Unknown Agent"})}),p.jsx("div",{className:"min-w-0 flex-1 w-full",children:p.jsx("div",{className:"text-xs font-medium text-gray-700 truncate",children:o.name||"Unknown Agent"})})]}),p.jsx("div",{className:"text-center font-medium text-xs text-gray-700",children:o.runs?i(o.runs):"-"}),p.jsx("div",{className:"text-center font-medium text-xs text-gray-700",children:o.responseTime||"-"}),p.jsx("div",{className:"text-center font-medium text-xs text-gray-700",children:o.tokens?i(o.tokens):"-"})]},o.id||s))}),r<e.length&&p.jsx("div",{className:"flex justify-center",children:p.jsx("button",{onClick:a,className:"px-[16px] py-[8px] text-xs font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors duration-150",children:"Load 10 more"})})]})};function WB(e){const t=(e==null?void 0:e.toLowerCase())||"";return["inlinetool","inlineTool","code tool","code","tool","event","EVENT"].includes(e)||["inlinetool","inlineTool","code tool","code","tool","event"].includes(t)?"bg-orange-100 text-orange-800 border-orange-200":["toollibrary","toolLibrary","workflow tool"].includes(e)||["toollibrary","toollibrary","workflow tool"].includes(t)?"bg-blue-100 text-blue-800 border-blue-200":["mcp","MCP","mcpTool","mcpTool"].includes(e)||["mcp","mcptool"].includes(t)?"bg-green-100 text-green-800 border-green-200":["knowledge","KNOWLEDGE","knowledge tool"].includes(e)||["knowledge","knowledge tool"].includes(t)?"bg-purple-100 text-purple-800 border-purple-200":"bg-gray-100 text-gray-800 border-gray-200"}function zB(e){const t=(e==null?void 0:e.toLowerCase())||"";return["inlinetool","code tool","code","tool","event","inlineTool"].includes(t)?"Code Tool":["toollibrary","workflow tool"].includes(t)?"Workflow Tool":["mcp","mcptool"].includes(t)?"MCP Tool":["knowledge","knowledge tool","knowledge"].includes(t)||e==="KNOWLEDGE"?"Knowledge":e==="inlineTool"?"Code Tool":e==="toolLibrary"?"Workflow Tool":e==="KNOWLEDGE"?"Knowledge":e==="MCP"||e==="mcpTool"?"MCP Tool":"Code Tool"}const N0=({data:e,className:t})=>{const[r,n]=S.useState(5),a=()=>{n(o=>Math.min(o+10,e.length))},i=o=>o>=1e3?`${Math.floor(o/1e3)}k`:o.toString();return p.jsxs("div",{className:le("w-full",t),children:[p.jsxs("div",{className:"grid grid-cols-4 items-center gap-4 px-[16px] py-[12px] bg-gray-50 border-b border-gray-200 text-xs font-medium text-gray-600",children:[p.jsx("div",{className:"text-left",children:"Name"}),p.jsx("div",{className:"text-center",children:"Type"}),p.jsx("div",{className:"text-center",children:"Runs"}),p.jsx("div",{className:"text-center",children:"Response Time"})]}),p.jsx("div",{className:"divide-y divide-gray-100",children:e.slice(0,r).map((o,s)=>p.jsxs("div",{className:"grid grid-cols-4 items-center gap-4 px-[16px] py-[12px] cursor-pointer transition-colors duration-150 border-b border-gray-200",children:[p.jsxs("div",{className:"flex items-center gap-[8px]",children:[p.jsx("div",{className:"flex-shrink-0",children:p.jsx(xi,{icon:o.icon,iconSource:"workflowtool",size:"small",name:o.name||"Unknown Tool",toolType:o.toolType||o.type})}),p.jsx("div",{className:"min-w-0 flex-1 w-full",children:p.jsx("div",{className:"text-xs font-medium text-gray-700 truncate",children:o.name||"Unknown Tool"})})]}),p.jsx("div",{className:"flex items-center justify-center",children:p.jsx("span",{className:le("inline-flex items-center px-[10px] py-[4px] rounded-full text-xs font-medium border",WB(o.toolType||o.type||"Default")),children:zB(o.toolType||o.type||"Default")})}),p.jsx("div",{className:"text-center font-medium text-xs text-gray-700",children:o.runs?i(o.runs):"-"}),p.jsx("div",{className:"text-center font-medium text-xs text-gray-700",children:o.responseTime||"-"})]},o.id||s))}),r<e.length&&p.jsx("div",{className:"flex justify-center",children:p.jsx("button",{onClick:a,className:"px-[16px] py-[8px] text-xs font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors duration-150",children:"Load 10 more"})})]})},VB=e=>{if(!e)return"/assets/icons/models/custom-api.svg";const t=e.toLowerCase(),r={openai:"Open AI.svg","open ai":"Open AI.svg",chatopenai:"Open AI.svg",gpt:"Open AI.svg",anthropic:"Anthropic.svg",claude:"Anthropic.svg",google:"Google.svg",gemini:"Google.svg",chatgooglegenerativeai:"Google.svg",googlegenerativeai:"Google.svg",palm:"Google.svg",azurechatopenai:"Azure Open AI.svg","azure open ai":"Azure Open AI.svg",azureopenai:"Azure Open AI.svg","azure openai":"Azure Open AI.svg",azure:"Azure Open AI.svg",aws:"AWS Bedrock.svg",bedrock:"AWS Bedrock.svg","aws bedrock":"AWS Bedrock.svg",awsbedrock:"AWS Bedrock.svg",amazon:"AWS Bedrock.svg",cohere:"Cohere.svg",api:"API.svg",custom:"custom-api.svg","custom-api":"custom-api.svg",customapi:"custom-api.svg"};if(r[t])return`assets/icons/models/${r[t]}`;for(const[n,a]of Object.entries(r))if(t.includes(n)||n.includes(t))return`assets/icons/models/${a}`;return"assets/icons/models/custom-api.svg"},GB=e=>{if(!e)return"";const t=e.toLowerCase(),r={openai:"OpenAI","open ai":"OpenAI",chatopenai:"OpenAI",gpt:"OpenAI",anthropic:"Anthropic",claude:"Anthropic",google:"Google",gemini:"Google Gemini",chatgooglegenerativeai:"Google Gemini",googlegenerativeai:"Google Gemini",palm:"Google PaLM",azurechatopenai:"Azure OpenAI","azure open ai":"Azure OpenAI",azureopenai:"Azure OpenAI","azure openai":"Azure OpenAI",azure:"Azure OpenAI",aws:"AWS Bedrock",bedrock:"AWS Bedrock","aws bedrock":"AWS Bedrock",awsbedrock:"AWS Bedrock",amazon:"AWS Bedrock",cohere:"Cohere",meta:"Meta",llama:"Meta LLaMA",mistral:"Mistral",huggingface:"Hugging Face",together:"Together AI",replicate:"Replicate"};if(r[t])return r[t];for(const[n,a]of Object.entries(r))if(t.includes(n)||n.includes(t))return a;return e.charAt(0).toUpperCase()+e.slice(1)},HB=({provider:e})=>{const[t,r]=S.useState(!1),n=VB(e),a=()=>{r(!0)};if(t){const i=e?e.charAt(0).toUpperCase():"🤖";return p.jsx("div",{className:"w-6 h-6 rounded-full bg-gray-500 flex items-center justify-center",children:p.jsx("span",{className:"text-white text-xs font-bold",children:i})})}return p.jsx("img",{src:n,alt:e||"Model",className:"w-6 h-6 rounded",onError:a})},M0=({data:e,className:t})=>{const[r,n]=S.useState(5),a=()=>{n(o=>Math.min(o+10,e.length))},i=o=>o>=1e3?`${Math.floor(o/1e3)}k`:o.toString();return p.jsxs("div",{className:le("w-full",t),children:[p.jsxs("div",{className:"grid grid-cols-4 items-center gap-4 px-[16px] py-[12px] bg-gray-50 border-b border-gray-200 text-xs font-medium text-gray-600",children:[p.jsx("div",{className:"text-left",children:"Model Name"}),p.jsx("div",{className:"text-center",children:"Runs"}),p.jsx("div",{className:"text-center",children:"Tokens"}),p.jsx("div",{className:"text-center",children:"Response Time"})]}),p.jsx("div",{className:"divide-y divide-gray-100",children:e.slice(0,r).map((o,s)=>p.jsxs("div",{className:"grid grid-cols-4 items-center gap-4 px-[16px] py-[12px] cursor-pointer transition-colors duration-150 border-b border-gray-200",children:[p.jsxs("div",{className:"flex items-center gap-[8px]",children:[p.jsx("div",{className:"flex-shrink-0",children:p.jsx(HB,{provider:o.provider})}),p.jsxs("div",{className:"min-w-0 flex-1 w-full",children:[p.jsx("div",{className:"text-xs font-medium text-gray-700 truncate",children:o.name||o.modelName||"Unknown Model"}),o.provider&&p.jsx("div",{className:"text-xs text-gray-500 truncate",children:GB(o.provider)})]})]}),p.jsx("div",{className:"text-center font-medium text-xs text-gray-700",children:i(o.runs||0)}),p.jsx("div",{className:"text-center font-medium text-xs text-gray-700",children:i(o.tokens||o.totalTokens||0)}),p.jsx("div",{className:"text-center font-medium text-xs text-gray-700",children:o.responseTime||(o.avgResponseTime?`${o.avgResponseTime}ms`:"N/A")})]},o.id||s))}),r<e.length&&p.jsx("div",{className:"flex justify-center",children:p.jsx("button",{onClick:a,className:"px-[16px] py-[8px] text-xs font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors duration-150",children:"Load 10 more"})})]})},qB=e=>{switch(e){case"agentRuns":return{title:"Agent Runs",entityName:"Agents"};case"toolRuns":return{title:"Tool Runs",entityName:"Tools"};case"modelRuns":return{title:"Model Runs",entityName:"Models"};default:return{title:"Runs",entityName:"Items"}}},KB=e=>e>=1e3?`${Math.floor(e/1e3)}k`:e.toString(),D0=({isOpen:e,onClose:t,date:r,metricType:n,data:a,totalRuns:i,className:o})=>{var O;const s=qB(n),[l,u]=S.useState(10),[c,f]=S.useState("all"),[d,m]=S.useState(!1),g=[{label:`All ${s.entityName}`,value:"all"},...a.map(A=>({label:A.name,value:A.id}))],v=c==="all"?a:a.filter(A=>A.id===c),h=()=>{f("all"),m(!1),u(10),t()};S.useEffect(()=>{const A=C=>{C.key==="Escape"&&h()},j=C=>{d&&(C.target.closest(".filter-dropdown")||m(!1))};return e&&(document.addEventListener("keydown",A),document.addEventListener("mousedown",j),document.body.style.overflow="hidden"),()=>{document.removeEventListener("keydown",A),document.removeEventListener("mousedown",j),document.body.style.overflow="unset"}},[e,d,h]),S.useEffect(()=>{e&&(f("all"),m(!1),u(10))},[e]);const b=A=>new Date(A).toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric"}),w=()=>{u(A=>Math.min(A+10,v.length))},x=A=>{f(A),m(!1),u(10)};if(!e)return null;const T=v.slice(0,l),y=((O=g.find(A=>A.value===c))==null?void 0:O.label)||`All ${s.entityName}`;return p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 transition-opacity duration-300",onClick:h}),p.jsxs("div",{className:le("fixed right-0 top-0 h-full w-[600px] bg-white shadow-[0px_20px_24px_-4px_rgba(16,24,40,0.08),0px_8px_8px_-4px_rgba(16,24,40,0.03)] z-50 transform transition-transform duration-300 ease-in-out",e?"translate-x-0":"translate-x-full",o),children:[p.jsxs("div",{className:"flex items-center justify-between px-6 py-3 border-b border-[#d0d5dd]",children:[p.jsx("h2",{className:"text-lg font-semibold text-[#101828]",children:s.title}),p.jsx("button",{onClick:h,className:"p-2 hover:bg-gray-100 rounded-lg transition-colors",children:p.jsx(Nf,{className:"h-5 w-5 text-[#101828]"})})]}),p.jsxs("div",{className:"flex flex-col h-[calc(100%-64px)] p-6 gap-6",children:[p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsxs("div",{className:"text-sm font-medium text-[#344054]",children:[s.title," (",b(r),")"]}),p.jsxs("div",{className:"w-[210px] relative filter-dropdown",children:[p.jsxs("button",{onClick:()=>m(!d),className:"w-full bg-white border border-[#d0d5dd] rounded-lg px-3.5 py-2.5 flex items-center justify-between text-sm text-[#101828] hover:bg-gray-50 transition-colors",children:[p.jsx("span",{children:y}),p.jsx(fr,{className:"h-4 w-4 text-[#101828]"})]}),d&&p.jsx("div",{className:"absolute top-full left-0 right-0 mt-1 bg-white border border-[#d0d5dd] rounded-lg shadow-lg z-10 max-h-60 overflow-y-auto",children:g.map(A=>p.jsx("button",{onClick:()=>x(A.value),className:le("w-full px-3.5 py-2.5 text-left text-sm hover:bg-gray-50 transition-colors",c===A.value?"bg-blue-50 text-blue-700":"text-[#101828]"),children:A.label},A.value))})]})]}),p.jsxs("div",{className:"flex-1 overflow-hidden",children:[p.jsx("div",{className:"bg-[#f9fafb] border-b border-[#eaecf0] px-2 py-2",children:p.jsxs("div",{className:"grid grid-cols-4 gap-3 items-center",children:[p.jsx("div",{className:"col-span-2 px-0 py-2",children:p.jsx("div",{className:"text-xs font-medium text-[#475467]",children:"Name"})}),p.jsx("div",{className:"flex justify-center px-0 py-2",children:p.jsx("div",{className:"text-xs font-medium text-[#475467]",children:"Runs"})}),p.jsx("div",{className:"flex justify-center px-0 py-2",children:p.jsx("div",{className:"text-xs font-medium text-[#475467]",children:"Response Time"})})]})}),p.jsx("div",{className:"overflow-y-auto max-h-[calc(100%-40px)]",children:T.length===0?p.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-center",children:[p.jsxs("h3",{className:"text-md font-medium text-gray-900 mb-[8px]",children:["No ",s.title.toLowerCase()," for this date"]}),p.jsxs("p",{className:"text-xs text-gray-500",children:["There were no ",s.title.toLowerCase()," recorded on ",b(r),"."]})]}):p.jsxs(p.Fragment,{children:[T.map((A,j)=>p.jsxs("div",{className:"grid grid-cols-4 gap-3 items-center px-2 py-3 border-b border-[#eaecf0] hover:bg-gray-50 transition-colors",children:[p.jsxs("div",{className:"col-span-2 flex items-center gap-2",children:[p.jsx("div",{className:"flex-shrink-0",children:p.jsx(xi,{icon:A.icon,iconSource:n==="agentRuns"?"agent":n==="toolRuns"?"workflowtool":"model",size:"small",name:A.name,toolType:A.toolType||A.type,provider:A.provider,modelName:A.modelName})}),p.jsxs("div",{className:"min-w-0 flex-1",children:[p.jsx("div",{className:"text-sm font-medium text-[#101828] truncate",children:A.name}),n==="modelRuns"&&A.provider&&p.jsx("div",{className:"text-xs text-[#475467] truncate",children:A.provider})]})]}),p.jsx("div",{className:"flex justify-center",children:p.jsx("div",{className:"text-xs font-medium text-[#475467]",children:KB(A.runs)})}),p.jsx("div",{className:"flex justify-center",children:p.jsx("div",{className:"text-xs font-medium text-[#475467]",children:A.responseTime})})]},A.id||j)),l<v.length&&p.jsx("div",{className:"flex justify-center",children:p.jsx("button",{onClick:w,className:"bg-white border border-[#d0d5dd] rounded px-3 py-1 text-xs font-medium text-[#344054] hover:bg-gray-50 transition-colors",children:"Load 10 more"})})]})})]})]})]})]})};class I0{constructor(t=""){kt(this,"API_PATH","/tracing/api/trpc/metrics.getMetrics");kt(this,"baseUrl","");kt(this,"endpoints",{});this.baseUrl=t,this.initializeEndpoints()}setBaseUrl(t){this.baseUrl=t,this.initializeEndpoints()}getEndpoint(t){return this.endpoints[t]||{endpoint:"",method:"GET"}}getBaseUrl(){return this.baseUrl}initializeEndpoints(){const t=`${this.baseUrl}${this.API_PATH}`;this.endpoints["usage-analytics.cards"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH},this.endpoints["usage-analytics.sessions.timeseries"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH},this.endpoints["usage-analytics.messages.timeseries"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH},this.endpoints["usage-analytics.users.timeseries"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH},this.endpoints["usage-analytics.tokens.timeseries"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH},this.endpoints["runs.cards"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH},this.endpoints["runs.agent-runs.timeseries"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH},this.endpoints["runs.model-runs.timeseries"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH},this.endpoints["runs.tool-runs.timeseries"]={endpoint:t,method:"GET",baseEndpoint:this.API_PATH}}getAvailableEndpoints(){return Object.keys(this.endpoints)}hasEndpoint(t){return t in this.endpoints}}class L0{constructor(t){kt(this,"endpointsService");kt(this,"defaultHeaders");kt(this,"timeout");this.endpointsService=new I0(t.baseUrl),this.defaultHeaders={"Content-Type":"application/json",...t.defaultHeaders},this.timeout=t.timeout||3e4}updateConfig(t){t.baseUrl&&this.endpointsService.setBaseUrl(t.baseUrl),t.defaultHeaders&&(this.defaultHeaders={...this.defaultHeaders,...t.defaultHeaders}),t.timeout&&(this.timeout=t.timeout)}async invoke(t,r,n,a){const i=this.endpointsService.getEndpoint(t);if(!i.endpoint)throw new Error(`Endpoint not found for service: ${t}`);const o=this.prepareRequest(i,r,n);try{const s=new AbortController,l=setTimeout(()=>s.abort(),(a==null?void 0:a.timeout)||this.timeout),u=await fetch(o.url,{method:o.method,headers:o.headers,body:o.body,signal:(a==null?void 0:a.signal)||s.signal});if(clearTimeout(l),!u.ok)throw new Error(`HTTP Error: ${u.status} ${u.statusText}`);return await u.json()}catch(s){throw s instanceof Error?s.name==="AbortError"?new Error("Request timeout"):s:new Error("Unknown error occurred during API call")}}prepareRequest(t,r,n){const a={...this.defaultHeaders,...n},i={};Object.entries(a).forEach(([l,u])=>{u!==void 0&&(i[l]=u)});let o=t.endpoint,s;if(t.method==="GET"&&r){const l=this.buildQueryParams(r);o+=`?${l}`}else r&&(s=JSON.stringify(r));return{url:o,method:t.method,headers:i,body:s}}buildQueryParams(t){const r={json:t},n=new URLSearchParams;return n.append("input",JSON.stringify(r)),n.append("rnd",Math.random().toString(36).substring(7)),n.toString()}getBaseUrl(){return this.endpointsService.getBaseUrl()}hasEndpoint(t){return this.endpointsService.hasEndpoint(t)}getAvailableEndpoints(){return this.endpointsService.getAvailableEndpoints()}}class Yt{constructor(t){kt(this,"apiInvoker");kt(this,"projectId");kt(this,"environment");kt(this,"defaultTimeRange");const r={baseUrl:t.baseUrl,defaultHeaders:t.headers,timeout:3e4};this.apiInvoker=new L0(r),this.projectId=t.projectId,this.environment=t.environment,this.defaultTimeRange=t.defaultTimeRange}updateConfig(t){(t.baseUrl||t.headers)&&this.apiInvoker.updateConfig({baseUrl:t.baseUrl,defaultHeaders:t.headers}),t.projectId&&(this.projectId=t.projectId),t.environment&&(this.environment=t.environment),t.defaultTimeRange&&(this.defaultTimeRange=t.defaultTimeRange,console.log("🔄 API Service: Updated defaultTimeRange:",this.defaultTimeRange))}getDefaultTimeRange(){return this.defaultTimeRange||Yt.getDateRange(7)}async fetchEnvironments(){try{const r=`${this.apiInvoker.getBaseUrl()}/aaa/api/v1/apps/${this.projectId}/environments?rnd=${Math.random().toString(36).substring(2,8)}`;console.log("🌍 Fetching environments for project:",this.projectId),console.log("🔗 Environment API URL:",r);const n=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json",...this.apiInvoker.defaultHeaders}});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);const a=await n.json();return console.log("✅ Environments fetched successfully:",a.map(i=>({name:i.envName,enabled:i.isEnabled,status:i.status}))),a}catch(t){throw console.error("❌ Error fetching environments:",t),t}}async fetchUsageAnalyticsCards(t,r,n,a=[]){const i=n||Yt.getTimeDimension(t,r);console.log("📊 Fetching usage analytics cards:",{dateRange:{fromTimestamp:t,toTimestamp:r},providedTimeDimension:n,resolvedTimeDimension:i});const o={projectId:this.projectId,type:"cards",category:"usage-analytics",envId:this.environment,fromTimestamp:t,toTimestamp:r,filter:a,includeTrends:!0,timeDimension:i};return(await this.apiInvoker.invoke("usage-analytics.cards",o)).result.data.json}async fetchRunsCards(t,r,n,a=[]){const i=n||Yt.getTimeDimension(t,r);console.log("📊 Fetching runs cards:",{dateRange:{fromTimestamp:t,toTimestamp:r},providedTimeDimension:n,resolvedTimeDimension:i});const o={projectId:this.projectId,type:"cards",category:"runs",envId:this.environment,fromTimestamp:t,toTimestamp:r,filter:a,includeTrends:!0,timeDimension:i};return(await this.apiInvoker.invoke("runs.cards",o)).result.data.json}async fetchTimeSeriesData(t,r,n,a,i,o=[]){const s=i||Yt.getTimeDimension(n,a);console.log("📊 Fetching time series data:",{metric:t,category:r,dateRange:{fromTimestamp:n,toTimestamp:a},providedTimeDimension:i,resolvedTimeDimension:s});const l=`${r}.${t}.timeseries`,u={projectId:this.projectId,type:"time-series",category:r,envId:this.environment,fromTimestamp:n,toTimestamp:a,filter:o,metric:t,timeDimension:s};return(await this.apiInvoker.invoke(l,u)).result.data.json}transformUsageAnalyticsCards(t){const r=t.data.trends;console.log("Transforming usage analytics cards with trends:",r);const n=a=>a>0?"increase":"decrease";return[{title:"Users",value:t.data.users,metricType:"users",icon:"users",info:"Number of unique users who interacted with the app",highlighted:!0,change:r!=null&&r.users?{value:Math.abs(r.users.changePercent),type:n(r.users.changePercent)}:void 0},{title:"Sessions",value:t.data.sessions,metricType:"sessions",icon:"activity",info:"Number of conversations initiated with the app",highlighted:!1,change:r!=null&&r.sessions?{value:Math.abs(r.sessions.changePercent),type:n(r.sessions.changePercent)}:void 0},{title:"Messages",value:t.data.messages.total,metricType:"messages",icon:"message-circle",info:"Total messages exchanged between users and the app",highlighted:!1,change:r!=null&&r.messages?{value:Math.abs(r.messages.changePercent.total),type:n(r.messages.changePercent.total)}:void 0},{title:"Tokens",value:t.data.tokens.total,metricType:"tokens",icon:"coins",info:"Total input and output tokens processed by the app for all interactions",highlighted:!1,change:r!=null&&r.tokens?{value:Math.abs(r.tokens.changePercent.total),type:n(r.tokens.changePercent.total)}:void 0}]}transformRunsCards(t){const r=t.data.trends;console.log("Transforming runs cards with trends:",r);const n=a=>a>0?"increase":"decrease";return[{title:"Agent Runs",value:t.data.agentRuns,metricType:"agentRuns",icon:"bot",info:"Number of times the AI agents were executed to handle user requests",highlighted:!0,change:r!=null&&r.agentRuns?{value:Math.abs(r.agentRuns.changePercent),type:n(r.agentRuns.changePercent)}:void 0},{title:"Tool Runs",value:t.data.toolRuns.total,metricType:"toolRuns",icon:"wrench",info:"Number of times various tools were triggered by the AI agents to complete tasks",highlighted:!1,change:r!=null&&r.toolRuns?{value:Math.abs(r.toolRuns.changePercent.total),type:n(r.toolRuns.changePercent.total)}:void 0},{title:"Model Runs",value:t.data.modelRuns,metricType:"modelRuns",icon:"cpu",info:"Number of times the AI agents called various language models to generate responses",highlighted:!1,change:r!=null&&r.modelRuns?{value:Math.abs(r.modelRuns.changePercent),type:n(r.modelRuns.changePercent)}:void 0}]}transformTimeSeriesDataForMetric(t,r){var a;if(console.log("=== METRIC-SPECIFIC TRANSFORM DEBUG ==="),console.log("Raw TimeSeriesResponse:",JSON.stringify(t,null,2)),console.log("Metric type:",r),!t||!t.data||!Array.isArray(t.data))return console.error("Invalid time series data structure:",t),[];const n=t.data.map((i,o)=>{console.log(`Processing point ${o}:`,i);const s=new Date(i.timestamp),l=s.toISOString().split("T")[0],u=s.toLocaleDateString("en-US",{month:"short",day:"numeric"}),c={date:l,timestamp:u,formattedDate:u,count:i.count||0,value:i.count||0,input_tokens:i.input_tokens||0,output_tokens:i.output_tokens||0,total_tokens:(i.input_tokens||0)+(i.output_tokens||0),inputTokens:i.input_tokens||0,outputTokens:i.output_tokens||0,totalTokens:(i.input_tokens||0)+(i.output_tokens||0),listView:i.listView||[],index:o};switch(r){case"users":c.users=i.count||0;break;case"sessions":c.sessions=i.count||0;break;case"messages":c.messages=i.count||0;break;case"tokens":c.tokens=i.count||0,i.input_tokens||i.output_tokens?c.totalTokens=(i.input_tokens||0)+(i.output_tokens||0):c.totalTokens=i.count||0;break;case"agentRuns":c.agentRuns=i.count||0;break;case"toolRuns":c.toolRuns=i.count||0;break;case"modelRuns":c.modelRuns=i.count||0;break;default:c.users=i.count||0,c.sessions=i.count||0,c.messages=i.count||0,c.tokens=i.count||0,c.agentRuns=i.count||0,c.toolRuns=i.count||0,c.modelRuns=i.count||0}return console.log(`Transformed point ${o} for metric ${r}:`,c),c});return console.log("Final transformed data array:",JSON.stringify(n,null,2)),console.log("Sample transformed point for chart:",n[0]),console.log("Populated metric property:",r,"=",(a=n[0])==null?void 0:a[r||"count"]),console.log("=== END METRIC-SPECIFIC TRANSFORM DEBUG ==="),n}transformTimeSeriesData(t){return this.transformTimeSeriesDataForMetric(t)}transformAgentsListViewToTable(t){return Array.isArray(t)?t.map((r,n)=>{var o,s;let a="",i=null;if(r.icon)try{if(i=typeof r.icon=="string"?JSON.parse(r.icon):r.icon,i.name){const l=((o=r.agentName)==null?void 0:o.replace(/\s+/g,""))||`agent${n}`,u=((s=i.color)==null?void 0:s.replace("#",""))||"b6e3f4";a=`https://api.dicebear.com/7.x/avataaars/svg?seed=${l}&backgroundColor=${u}&backgroundType=solid`}}catch{console.warn("Failed to parse icon data:",r.icon)}return{id:`agent-${n+1}`,name:r.agentName||`Agent ${n+1}`,runs:r.count||0,responseTime:r.avgResponseTime?r.avgResponseTime<1e3?`${Math.round(r.avgResponseTime)}ms`:`${(r.avgResponseTime/1e3).toFixed(2)}s`:"0ms",tokens:r.tokens||Math.floor((r.count||0)*150),successRate:r.successRate?`${Math.round(r.successRate)}%`:"95%",lastRun:r.lastRun||new Date(Date.now()-Math.random()*7*24*60*60*1e3).toLocaleDateString(),avatar:a||`https://api.dicebear.com/7.x/avataaars/svg?seed=agent${n}&backgroundColor=b6e3f4,c0aede,d1d4f9&backgroundType=solid`,icon:r.icon||void 0}}):(console.warn("Invalid listView data for agents:",t),[])}transformToolsListViewToTable(t){return Array.isArray(t)?t.map((r,n)=>({id:`tool-${n+1}`,name:r.toolName||r.tool_name||`Tool ${n+1}`,type:r.type||r.toolType||r.tool_type||"Code Tool",runs:r.count||0,responseTime:r.avgResponseTime?r.avgResponseTime<1e3?`${Math.round(r.avgResponseTime)}ms`:`${(r.avgResponseTime/1e3).toFixed(2)}s`:"0ms",tokens:r.tokens||Math.floor((r.count||0)*50),successRate:r.successRate?`${Math.round(r.successRate)}%`:"92%",lastRun:r.lastRun||new Date(Date.now()-Math.random()*7*24*60*60*1e3).toLocaleDateString(),icon:r.icon||r.tool_icon||void 0})):(console.warn("Invalid listView data for tools:",t),[])}transformModelsListViewToTable(t){return Array.isArray(t)?t.map((r,n)=>({id:`model-${n+1}`,name:r.modelName||`Model ${n+1}`,modelName:r.modelName,provider:r.provider,runs:r.count||0,responseTime:r.avgResponseTime?r.avgResponseTime<1e3?`${Math.round(r.avgResponseTime)}ms`:`${(r.avgResponseTime/1e3).toFixed(2)}s`:"0ms",avgResponseTime:r.avgResponseTime,tokens:r.tokens||r.totalTokens||Math.floor((r.count||0)*300),totalTokens:r.totalTokens||r.tokens,successRate:r.successRate?`${Math.round(r.successRate)}%`:"98%",lastRun:r.lastRun||new Date(Date.now()-Math.random()*7*24*60*60*1e3).toLocaleDateString(),icon:r.icon})):(console.warn("Invalid listView data for models:",t),[])}extractAgentControlOptions(t){if(!Array.isArray(t))return[{label:"All Agents",value:"all"}];const r=[{label:"All Agents",value:"all"}];return t.forEach(n=>{var a;if(n.agentName){let i="";try{if(n.icon){const o=typeof n.icon=="string"?JSON.parse(n.icon):n.icon;if(o.name){const s=n.agentName.replace(/\s+/g,""),l=((a=o.color)==null?void 0:a.replace("#",""))||"b6e3f4";i=`https://api.dicebear.com/7.x/avataaars/svg?seed=${s}&backgroundColor=${l}&backgroundType=solid`}}}catch{console.warn("Failed to parse icon data for control:",n.icon)}r.push({label:n.agentName,value:n.agentName.replace(/\s+/g,"").toLowerCase(),avatar:i||`https://api.dicebear.com/7.x/avataaars/svg?seed=${n.agentName.replace(/\s+/g,"")}&backgroundColor=b6e3f4,c0aede,d1d4f9&backgroundType=solid`})}}),r}extractToolControlOptions(t){if(!Array.isArray(t))return[{label:"All Tools",value:"all"}];const r=[{label:"All Tools",value:"all"}];return t.forEach(n=>{const a=n.toolName||n.tool_name;if(a){let i=function(o){if(!o)return"Code Tool";const s=o.toLowerCase();return["inlinetool","code tool","code","event"].includes(s)?"Code Tool":["toollibrary","workflow tool"].includes(s)?"Workflow Tool":["mcp","mcptool"].includes(s)?"MCP Tool":["knowledge","knowledge tool"].includes(s)||o==="KNOWLEDGE"?"Knowledge":o==="inlineTool"?"Code Tool":o==="toolLibrary"?"Workflow Tool":o==="MCP"||o==="mcpTool"?"MCP Tool":"Code Tool"};r.push({label:a,value:a.replace(/[-]/g,""),icon:n.icon||n.tool_icon||void 0,type:n.type||i(n.toolType||n.tool_type)})}}),r}extractModelControlOptions(t){if(!Array.isArray(t))return[{label:"All Models",value:"all"}];const r=[{label:"All Models",value:"all"}];return t.forEach(n=>{n.modelName&&r.push({label:n.modelName,value:n.modelName.replace(/[-\.]/g,""),icon:n.icon,type:n.provider})}),r}async fetchTimeSeriesDataWithTableData(t,r,n,a,i,o=[]){const s=await this.fetchTimeSeriesData(t,r,n,a,i,o);let l=[];s.data.forEach(d=>{d.listView&&Array.isArray(d.listView)&&(l=[...l,...d.listView])});const u=this.aggregateListViewItems(l);let c=[],f=[];return t==="agent-runs"?(c=this.transformAgentsListViewToTable(u),f=this.extractAgentControlOptions(u)):t==="tool-runs"?(c=this.transformToolsListViewToTable(u),f=this.extractToolControlOptions(u)):t==="model-runs"&&(c=this.transformModelsListViewToTable(u),f=this.extractModelControlOptions(u)),{chartData:this.transformTimeSeriesDataForMetric(s,t.replace("-","")),tableData:c,controlOptions:f}}aggregateListViewItems(t){const r=new Map;return t.forEach(n=>{const a=n.agentName||n.toolName||n.modelName||"unknown";if(r.has(a)){const i=r.get(a);i.count=(i.count||0)+(n.count||0),i.avgResponseTime=i.avgResponseTime&&n.avgResponseTime?(i.avgResponseTime+n.avgResponseTime)/2:i.avgResponseTime||n.avgResponseTime,i.tokens=(i.tokens||0)+(n.tokens||0)}else r.set(a,{...n})}),Array.from(r.values())}async fetchEnhancedMetricsData(t,r,n,a=[]){try{const[i,o,s]=await Promise.all([this.fetchTimeSeriesDataWithTableData("agent-runs","runs",t,r,n,a),this.fetchTimeSeriesDataWithTableData("tool-runs","runs",t,r,n,a),this.fetchTimeSeriesDataWithTableData("model-runs","runs",t,r,n,a)]);return{agents:i,tools:o,models:s}}catch(i){throw console.error("Error fetching enhanced metrics data:",i),i}}async transformRunsCardsWithEnhancedData(t,r,n,a,i=[]){const o=t.data.trends,s=m=>m>0?"increase":"decrease",[l,u,c,f]=await Promise.all([this.fetchTimeSeriesDataWithTableData("agent-runs","runs",r,n,a,i),this.fetchTimeSeriesDataWithTableData("tool-runs","runs",r,n,a,i),this.fetchTimeSeriesDataWithTableData("model-runs","runs",r,n,a,i),this.fetchTimeSeriesData("tool-runs","runs",r,n,a,i)]),d=this.transformTimeSeriesDataForToolRuns(f);return[{title:"Agent Runs",value:t.data.agentRuns,metricType:"agentRuns",icon:"bot",highlighted:!0,info:"Number of times the AI agents were executed to handle user requests",change:o!=null&&o.agentRuns?{value:Math.abs(o.agentRuns.changePercent),type:s(o.agentRuns.changePercent)}:void 0,view:{type:"chart",chart:{type:"line",title:"Agent Runs",data:l.chartData,dataKey:"agentRuns",color:"#0BA5EC",yAxisLabel:"Number of Agent Runs",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:r.split("T")[0],end:n.split("T")[0]}},table:{title:"Agent Runs",data:l.tableData,columns:[{key:"name",title:"Name",width:200,align:"left"},{key:"runs",title:"Runs",width:100,align:"right",formatter:m=>`${Math.floor(m/1e3)}k`},{key:"responseTime",title:"Response Time",width:120,align:"right"},{key:"tokens",title:"Tokens",width:100,align:"right",formatter:m=>`${Math.floor(m/1e3)}k`}]}},controls:{dropdown:{label:"All Agents",options:l.controlOptions,defaultValue:["all"],multiSelect:!0,searchable:!0},toggle:{chartView:!0,tableView:!0}}},{title:"Tool Runs",value:t.data.toolRuns.total,metricType:"toolRuns",icon:"wrench",info:"Number of times various tools were triggered by the AI agents to complete tasks",highlighted:!1,change:o!=null&&o.toolRuns?{value:Math.abs(o.toolRuns.changePercent.total),type:s(o.toolRuns.changePercent.total)}:void 0,view:{type:"chart",chart:{type:"line",title:"Tool Runs",data:d,yAxisLabel:"Number of Tool Runs",lines:[{dataKey:"toolRuns",color:"#667085",label:"Tool Runs"},{dataKey:"codeTools",color:"#F38744",label:"Code Tools"},{dataKey:"workflowTools",color:"#2970FF",label:"Workflow Tools"},{dataKey:"knowledgeTools",color:"#7A5AF8",label:"Knowledge"},{dataKey:"mcpTools",color:"#47CD89",label:"MCP Tools"}],height:300,showGrid:!0,showLegend:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:r.split("T")[0],end:n.split("T")[0]}},table:{title:"Tool Runs",data:u.tableData,columns:[{key:"name",title:"Name",width:200,align:"left"},{key:"type",title:"Type",width:150,align:"left"},{key:"runs",title:"Runs",width:100,align:"right",formatter:m=>`${Math.floor(m/1e3)}k`},{key:"responseTime",title:"Response Time",width:120,align:"right"}]}},controls:{dropdown:{label:"All Tools",options:u.controlOptions,defaultValue:["all"],multiSelect:!0,searchable:!0},toggle:{chartView:!0,tableView:!0}}},{title:"Model Runs",value:t.data.modelRuns,metricType:"modelRuns",icon:"cpu",highlighted:!1,info:"Number of times the AI agents called various language models to generate responses",change:o!=null&&o.modelRuns?{value:Math.abs(o.modelRuns.changePercent),type:s(o.modelRuns.changePercent)}:void 0,view:{type:"chart",chart:{type:"line",title:"Model Runs",data:c.chartData,dataKey:"modelRuns",color:"#47CD89",yAxisLabel:"Number of Model Runs",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:r.split("T")[0],end:n.split("T")[0]}},table:{title:"Model Runs",data:c.tableData,columns:[{key:"name",title:"Model Name",width:200,align:"left"},{key:"runs",title:"Runs",width:100,align:"right",formatter:m=>`${Math.floor(m/1e3)}k`},{key:"tokens",title:"Tokens",width:120,align:"right",formatter:m=>`${Math.floor(m/1e3)}k`},{key:"responseTime",title:"Response Time",width:120,align:"right"}]}},controls:{dropdown:{label:"All Models",options:c.controlOptions,defaultValue:["all"],multiSelect:!0,searchable:!0},toggle:{chartView:!0,tableView:!0}}}]}async transformUsageAnalyticsCardsWithEnhancedData(t,r,n,a,i=[]){const o=t.data.trends,s=d=>d>0?"increase":"decrease",[l,u,c,f]=await Promise.all([this.fetchTimeSeriesData("users","usage-analytics",r,n,a,i),this.fetchTimeSeriesData("sessions","usage-analytics",r,n,a,i),this.fetchTimeSeriesData("messages","usage-analytics",r,n,a,i),this.fetchTimeSeriesData("tokens","usage-analytics",r,n,a,i)]);return[{title:"Users",value:t.data.users,metricType:"users",icon:"users",highlighted:!0,info:"Number of unique users who interacted with the app",change:o!=null&&o.users?{value:Math.abs(o.users.changePercent),type:s(o.users.changePercent)}:void 0,view:{type:"chart",chart:{type:"line",title:"Total Users",data:this.transformTimeSeriesDataForMetric(l,"users"),dataKey:"users",color:"#4E5BA6",yAxisLabel:"Number of Users",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:r.split("T")[0],end:n.split("T")[0]}}}},{title:"Sessions",value:t.data.sessions,metricType:"sessions",icon:"activity",highlighted:!1,info:"Number of conversations initiated with the app",change:o!=null&&o.sessions?{value:Math.abs(o.sessions.changePercent),type:s(o.sessions.changePercent)}:void 0,view:{type:"chart",chart:{type:"line",title:"Total Sessions",data:this.transformTimeSeriesDataForMetric(u,"sessions"),dataKey:"sessions",color:"#0BA5EC",yAxisLabel:"Number of Sessions",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:r.split("T")[0],end:n.split("T")[0]}}}},{title:"Messages",value:t.data.messages.total,metricType:"messages",icon:"message-circle",info:"Total messages exchanged between users and the app",highlighted:!1,change:o!=null&&o.messages?{value:Math.abs(o.messages.changePercent.total),type:s(o.messages.changePercent.total)}:void 0,view:{type:"chart",chart:{type:"line",title:"Total Messages",data:this.transformTimeSeriesDataForMetric(c,"messages"),dataKey:"messages",color:"#E478FA",yAxisLabel:"Number of Messages",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:r.split("T")[0],end:n.split("T")[0]}}}},{title:"Tokens",value:t.data.tokens.total,metricType:"tokens",icon:"coins",info:"Total input and output tokens processed by the app for all interactions",highlighted:!1,change:o!=null&&o.tokens?{value:Math.abs(o.tokens.changePercent.total),type:s(o.tokens.changePercent.total)}:void 0,view:{type:"chart",chart:{type:"line",title:"Token Usage Breakdown",data:this.transformTimeSeriesDataForMetric(f,"tokens"),yAxisLabel:"Number of Tokens",lines:[{dataKey:"totalTokens",color:"#FF692E",label:"Total Tokens"},{dataKey:"inputTokens",color:"#5925DC",label:"Input Tokens"},{dataKey:"outputTokens",color:"#E478FA",label:"Output Tokens"}],height:300,showGrid:!0,showLegend:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:r.split("T")[0],end:n.split("T")[0]}}}}]}transformTimeSeriesDataForToolRuns(t){if(console.log("=== TOOL RUNS SPECIFIC TRANSFORM DEBUG ==="),console.log("Raw TimeSeriesResponse for tool runs:",JSON.stringify(t,null,2)),!t||!t.data||!Array.isArray(t.data))return console.error("Invalid time series data structure:",t),[];const r=t.data.map((n,a)=>{console.log(`Processing point ${a}:`,n);const i=new Date(n.timestamp),o=i.toISOString().split("T")[0],s=i.toLocaleDateString("en-US",{month:"short",day:"numeric"}),l=n.count||0;let u=0,c=0,f=0,d=0;if(n.listView&&Array.isArray(n.listView)){n.listView.forEach(v=>{const h=v.count||0,b=(v.toolType||v.tool_type||"").toLowerCase(),w=(v.toolName||v.tool_name||"").toLowerCase();console.log("Processing listView item:",{toolType:b,toolName:w,count:h});const x=b.toLowerCase();["inlinetool","inlineTool","tool","code","codetool","event","EVENT"].includes(b)||["inlinetool","tool","code","codetool","event"].includes(x)?u+=h:["toollibrary","toolLibrary","workflow","workflowtool"].includes(b)||["toollibrary","workflow","workflowtool"].includes(x)?c+=h:["knowledge","KNOWLEDGE","knowledgetool"].includes(b)||["knowledge","knowledgetool"].includes(x)?f+=h:["mcp","MCP","mcptool","mcpTool"].includes(b)||["mcp","mcptool"].includes(x)?d+=h:(console.log(`Unknown tool type '${b}' for tool '${w}', defaulting to code tools`),u+=h)}),console.log(`Calculated breakdown for point ${a}:`,{codeTools:u,workflowTools:c,knowledgeTools:f,mcpTools:d,total:u+c+f+d,expectedTotal:l});const g=u+c+f+d;if(Math.abs(g-l)>1){console.warn(`Breakdown total (${g}) doesn't match expected total (${l}) for point ${a}`);const v=l-g;u+=v,console.log(`Adjusted codeTools by ${v} to balance total`)}}else console.log(`No listView data for point ${a}, assigning all ${l} to codeTools`),u=l;const m={date:o,timestamp:s,formattedDate:s,toolRuns:l,value:l,count:l,codeTools:u,workflowTools:c,knowledgeTools:f,mcpTools:d,input_tokens:n.input_tokens||0,output_tokens:n.output_tokens||0,total_tokens:(n.input_tokens||0)+(n.output_tokens||0),inputTokens:n.input_tokens||0,outputTokens:n.output_tokens||0,totalTokens:(n.input_tokens||0)+(n.output_tokens||0),listView:n.listView||[],index:a};return console.log(`Transformed tool runs point ${a}:`,m),m});return console.log("Final tool runs transformed data:",JSON.stringify(r,null,2)),console.log("=== END TOOL RUNS SPECIFIC TRANSFORM DEBUG ==="),r}async fetchAllCardsData(t,r,n=[]){try{const[a,i]=await Promise.all([this.fetchUsageAnalyticsCards(t,r,void 0,n),this.fetchRunsCards(t,r,void 0,n)]);return{usageAnalytics:this.transformUsageAnalyticsCards(a),runs:this.transformRunsCards(i)}}catch(a){throw console.error("Error fetching cards data:",a),a}}async fetchAllCardsDataWithEnhancedViews(t,r,n,a=[]){try{const[i,o]=await Promise.all([this.fetchUsageAnalyticsCards(t,r,n,a),this.fetchRunsCards(t,r,n,a)]),[s,l]=await Promise.all([this.transformUsageAnalyticsCardsWithEnhancedData(i,t,r,n,a),this.transformRunsCardsWithEnhancedData(o,t,r,n,a)]);return{usageAnalytics:s,runs:l}}catch(i){throw console.error("Error fetching enhanced cards data:",i),i}}async fetchDefaultTimeSeriesData(t,r,n,a=[]){try{const[i,o]=await Promise.all([this.fetchTimeSeriesData("sessions","usage-analytics",t,r,n,a),this.fetchTimeSeriesData("agent-runs","runs",t,r,n,a)]);return{sessions:this.transformTimeSeriesData(i),agentRuns:this.transformTimeSeriesData(o)}}catch(i){throw console.error("Error fetching default time series data:",i),i}}transformListViewForSlider(t,r){return Array.isArray(t)?t.map((n,a)=>{const i={id:`${r}-${a+1}`,runs:n.count||0,responseTime:n.avgResponseTime?n.avgResponseTime<1e3?`${Math.round(n.avgResponseTime)}ms`:`${(n.avgResponseTime/1e3).toFixed(2)}s`:"0ms",successRate:n.successRate?`${Math.round(n.successRate)}%`:void 0,tokens:n.totalTokens||n.tokens||0,icon:n.icon||n.tool_icon||void 0,aiModel:"gpt-4o"};switch(r){case"agentRuns":return{...i,name:n.agentName||`Agent ${a+1}`,type:"Agent",aiModel:this.extractAIModel(n)||"gpt-4o"};case"toolRuns":return{...i,name:n.toolName||n.tool_name||`Tool ${a+1}`,type:n.type||n.toolType||n.tool_type||"Code Tool",toolType:n.toolType||n.tool_type,aiModel:this.extractAIModel(n)||"gpt-4o"};case"modelRuns":return{...i,name:n.modelName||`Model ${a+1}`,modelName:n.modelName,provider:n.provider,type:n.provider||"Model",aiModel:n.modelName||n.model||"gpt-4o"};default:return{...i,name:`Item ${a+1}`,type:"Unknown",aiModel:"gpt-4o"}}}):(console.warn("Invalid listView data for slider:",t),[])}extractAIModel(t){if(t.modelName)return t.modelName;if(t.model)return t.model;if(t.llmModel)return t.llmModel;if(t.aiModel)return t.aiModel;const r=["gpt-4o","gpt-4o-mini","claude-3-5-haiku"];return r[Math.floor(Math.random()*r.length)]}static getDateRange(t=7){const r=new Date,n=new Date;return n.setDate(r.getDate()-t),{fromTimestamp:n.toISOString(),toTimestamp:r.toISOString()}}static getTimeDimension(t,r){const n=new Date(t),a=new Date(r),i=new Date(n.getFullYear(),n.getMonth(),n.getDate()),o=new Date(a.getFullYear(),a.getMonth(),a.getDate()),s=o.getTime()-i.getTime(),l=s/(1e3*60*60*24),u=i.toISOString().split("T")[0],c=o.toISOString().split("T")[0],f=u===c,d=new Date(n.getFullYear(),n.getMonth(),n.getDate()),m=f&&Math.abs(n.getTime()-d.getTime())<1e3,g=Math.abs(a.getTime()-n.getTime()),v=g<60*1e3;return console.log("🕐 TimeDimension calculation:",{fromTimestamp:t,toTimestamp:r,fromDateStr:u,toDateStr:c,diffInMs:s,diffInDays:l,isSameCalendarDay:f,isTodayPattern:m,timeDiffInMs:g,isVeryClose:v,fromStartOfDay:d.toISOString(),recommended:f||m||v||l<=1?"hour":l<=31?"day":l<=90?"week":"month"}),f||m||v||l<=1?"hour":"day"}getAvailableMetrics(){return{"usage-analytics":["sessions","messages","users","tokens"],runs:["agent-runs","model-runs","tool-runs"]}}}const R0=({config:e,className:t,isLoading:r,context:n})=>{const{type:a,chart:i,table:o,layout:s="vertical"}=e,[l,u]=S.useState({isOpen:!1,date:"",metricType:"agentRuns",data:[],totalRuns:0}),c=(v,h)=>{console.log("Chart data point clicked in ViewRenderer:",{chartData:v,date:h,context:n});const b=n==null?void 0:n.metricType;if(!b||!["agentRuns","toolRuns","modelRuns"].includes(b)){console.log("Slider not applicable for metric type:",b);return}const w=v.listView||[];console.log("ListView data for clicked date:",w);const T=new Yt({baseUrl:"",projectId:"",environment:""}).transformListViewForSlider(w,b),y=v[b]||v.count||0;console.log("Opening slider with data:",{date:h,metricType:b,sliderData:T,totalRuns:y}),u({isOpen:!0,date:h,metricType:b,data:T,totalRuns:y})},f=()=>{u(v=>({...v,isOpen:!1}))},d=()=>i?(console.log("ViewRenderer - Chart config:",i),console.log("ViewRenderer - Chart data:",i.data),console.log("ViewRenderer - Context:",n),p.jsx("div",{className:"flex-1",children:p.jsx(E0,{config:i,isLoading:r,onDataPointClick:c})})):null,m=()=>o?(n==null?void 0:n.metricType)==="agentRuns"?p.jsx("div",{className:"flex-1 min-h-[380px]",children:p.jsx(k0,{data:o.data})}):(n==null?void 0:n.metricType)==="toolRuns"?p.jsx("div",{className:"flex-1 min-h-[380px]",children:p.jsx(N0,{data:o.data})}):(n==null?void 0:n.metricType)==="modelRuns"?p.jsx("div",{className:"flex-1 min-h-[380px]",children:p.jsx(M0,{data:o.data})}):p.jsx("div",{className:"flex-1 min-h-[380px]",children:p.jsx(C0,{config:o})}):null,g=()=>{switch(a){case"chart":return d();case"table":return m();case"mixed":return p.jsxs("div",{className:le("flex gap-6",s==="horizontal"?"flex-row":"flex-col"),children:[d(),m()]});default:return p.jsxs("div",{className:"p-4 text-center text-gray-500",children:["Unsupported view type: ",a]})}};return p.jsxs(p.Fragment,{children:[p.jsx("div",{className:le("w-full",t),children:g()}),p.jsx(D0,{isOpen:l.isOpen,onClose:f,date:l.date,metricType:l.metricType,data:l.data,totalRuns:l.totalRuns})]})},Ns=({options:e,value:t,placeholder:r="Select an option",onChange:n,className:a,disabled:i=!1})=>{const[o,s]=S.useState(!1),[l,u]=S.useState(t||""),c=S.useRef(null),f=e.find(g=>g.value===l);S.useEffect(()=>{const g=v=>{c.current&&!c.current.contains(v.target)&&s(!1)};return o&&document.addEventListener("mousedown",g),()=>{document.removeEventListener("mousedown",g)}},[o]);const d=g=>{i||(u(g),s(!1),n==null||n(g))},m=()=>{i||s(!o)};return p.jsxs("div",{ref:c,className:le("relative",a),children:[p.jsxs("button",{type:"button",className:le("flex h-[40px] text-left w-full items-center rounded-lg border border-gray-300 bg-white px-[14px] py-[10px] medium shadow-none outline-none focus-visible:border-ring focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-gray-25 transition-colors",a),onClick:m,disabled:i,children:[p.jsxs("div",{className:"flex items-center gap-[8px] w-full",children:[p.jsx("span",{className:"text-xs font-medium text-gray-400 uppercase",children:"ENV"}),p.jsx("span",{className:le("truncate w-full",!f&&"text-gray-700 font-medium text-sm"),children:f?f.label:r})]}),p.jsx(fr,{className:le("h-[16px] w-[16px] text-gray-400 transition-transform duration-200",o&&"rotate-180")})]}),o&&!i&&p.jsx("div",{className:"absolute p-[4px] w-full top-full left-0 z-50 mt-1 bg-popover max-h-[300px] overflow-y-auto text-popover-foreground overflow-x-hidden overflow-y-auto rounded-md border shadow-md",children:e.map(g=>{const v=l===g.value;return p.jsxs("div",{role:"option",className:"relative group",children:[p.jsx("button",{className:le("focus:bg-gray-50 rounded-[4px] hover:bg-gray-50 focus:text-accent-foreground relative flex w-full cursor-pointer select-none items-center px-[14px] py-[10px] text-sm text-left outline-none transition-colors",g.disabled?"opacity-50 cursor-not-allowed text-gray-400":v?"bg-blue-50 text-blue-900 font-medium":"text-gray-900 hover:bg-gray-50"),onClick:()=>!g.disabled&&d(g.value),disabled:g.disabled,children:p.jsx("span",{className:"block whitespace-nowrap w-full",children:g.label})}),g.label.length>25&&p.jsx("div",{className:"absolute left-full top-0 ml-2 z-[60] opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none",children:p.jsxs("div",{className:"bg-gray-900 text-white text-xs rounded-md px-3 py-2 whitespace-nowrap shadow-lg",children:[g.label,p.jsx("div",{className:"absolute left-0 top-1/2 transform -translate-x-full -translate-y-1/2 w-0 h-0 border-t-4 border-b-4 border-r-4 border-transparent border-r-gray-900"})]})})]},g.value)})})]})},B0=({options:e,value:t,defaultValue:r,placeholder:n="Select...",multiSelect:a=!1,searchable:i=!1,onChange:o,className:s,maxItems:l=100,maxLabelLength:u=30})=>{const[c,f]=S.useState(!1),[d,m]=S.useState(""),[g,v]=S.useState(()=>{const $=t||r;return a?Array.isArray($)?$:$?[$]:[]:$?[Array.isArray($)?$[0]:$]:[]}),h=S.useRef(null);S.useEffect(()=>{const $=P=>{h.current&&!h.current.contains(P.target)&&f(!1)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[]);const b=($,P=u)=>$.length<=P?$:$.substring(0,P)+"...",w=i?e.filter($=>$.label.toLowerCase().includes(d.toLowerCase())):e,x=w.slice(0,l),T=w.length>l,y=$=>{let P;if(a){if($==="all"){A();return}if(g.includes($))P=g.filter(F=>F!==$),P=P.filter(F=>F!=="all");else{P=g.filter(R=>R!=="all"),P=[...P,$];const F=w.filter(R=>R.value!=="all").map(R=>R.value),N=P.filter(R=>R!=="all");N.length===F.length&&(P=["all",...N])}}else P=[$],f(!1);v(P);const _=a?P:P[0]||"";o==null||o(_)},O=()=>{if(!a)return{checked:!1,indeterminate:!1};const $=w.filter(_=>_.value!=="all").map(_=>_.value),P=g.filter(_=>_!=="all"&&$.includes(_));return g.includes("all")&&P.length===0?{checked:!1,indeterminate:!1}:P.length===0?{checked:!1,indeterminate:!1}:P.length===$.length?{checked:!0,indeterminate:!1}:{checked:!1,indeterminate:!0}},A=()=>{if(!a)return;const $=O(),P=w.filter(_=>_.value!=="all").map(_=>_.value);if($.checked)v(["all"]),o==null||o(["all"]);else{const _=["all",...P];v(_),o==null||o(_)}},j=()=>{v(["all"]),o==null||o(a?["all"]:"all")},C=()=>{if(!a){if(g.length===0)return n;const F=e.find(N=>N.value===g[0]);return(F==null?void 0:F.label)||n}const $=g.filter(F=>F!=="all"),P=g.includes("all");if($.length===0)return n;if($.length===1){const F=e.find(N=>N.value===$[0]);return(F==null?void 0:F.label)||n}const _=e.filter(F=>F.value!=="all").length;return $.length===_?"All selected":`${$.length} selected`};return p.jsxs("div",{className:le("relative",s),ref:h,children:[p.jsxs("button",{type:"button",onClick:()=>f(!c),className:le("w-full flex items-center justify-between px-[12px] py-[8px] text-left text-xs","border border-gray-300 rounded-md bg-white hover:bg-gray-50","focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500","transition-colors duration-150"),children:[p.jsx("span",{className:le("truncate",g.length===0&&"text-gray-500"),children:C()}),p.jsx(fr,{className:le("w-[16px] h-[16px] text-gray-400 transition-transform duration-150",c&&"transform rotate-180")})]}),c&&p.jsxs("div",{className:"absolute z-50 min-w-[300px] w-max max-w-lg mt-[4px] bg-white border border-gray-200 rounded-md shadow-lg max-h-80 overflow-hidden",children:[i&&p.jsx("div",{className:"p-[12px] border-b border-gray-100",children:p.jsxs("div",{className:"relative",children:[p.jsx(kf,{className:"absolute left-[12px] top-1/2 transform -translate-y-1/2 w-[16px] h-[16px] text-gray-400"}),p.jsx("input",{type:"text",placeholder:`Search ${n.toLowerCase()}...`,value:d,onChange:$=>m($.target.value),className:"w-full pl-[36px] pr-[12px] py-[8px] text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"})]})}),a&&p.jsxs("div",{className:"flex items-center justify-between px-[12px] py-[8px] border-b border-gray-100 bg-gray-50",children:[p.jsxs("button",{type:"button",onClick:A,className:"flex items-center text-xs font-medium text-gray-700 hover:text-gray-900",children:[p.jsx("div",{className:le("flex items-center justify-center w-[16px] h-[16px] mr-[8px] border transition-colors duration-150",(()=>{const $=O();return $.indeterminate||$.checked?"bg-blue-600 border-blue-600 text-white":"border-gray-300 bg-white"})()),children:(()=>{const $=O();return $.indeterminate?p.jsx("div",{className:"w-[8px] h-[4px] bg-white rounded"}):$.checked?p.jsx("svg",{className:"w-[12px] h-[12px]",fill:"currentColor",viewBox:"0 0 20 20",children:p.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})}):null})()}),"Select all"]}),p.jsx("button",{type:"button",onClick:j,className:"text-sm font-medium text-blue-600 hover:text-blue-800",children:"Clear"})]}),p.jsxs("div",{className:"max-h-60 overflow-y-auto",children:[x.length===0?p.jsx("div",{className:"px-[12px] py-[16px] text-sm text-gray-500 text-center",children:"No options found"}):x.map($=>{let P;return $.value==="all"?null:(P=g.includes($.value),p.jsxs("div",{className:"relative group",children:[p.jsxs("div",{onClick:()=>y($.value),className:le("flex items-center px-[12px] py-[8px] cursor-pointer hover:bg-gray-50","transition-colors duration-150",P&&"bg-gray-50"),children:[a?p.jsx("div",{className:le("flex items-center justify-center w-[16px] h-[16px] mr-[12px] border","transition-colors duration-150",P?"bg-blue-600 border-blue-600 text-white":"border-gray-300 bg-white"),children:P&&p.jsx("svg",{className:"w-[12px] h-[12px]",fill:"currentColor",viewBox:"0 0 20 20",children:p.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})}):p.jsx("div",{className:le("w-[16px] h-[16px] mr-[12px] rounded-full border-2 transition-colors duration-150",P?"border-blue-600 bg-blue-600":"border-gray-300"),children:P&&p.jsx("div",{className:"w-full h-full rounded-full bg-white scale-50"})}),p.jsx("span",{className:le("flex-1 text-xs whitespace-nowrap truncate",P?"font-medium text-gray-700":"text-gray-500"),children:b($.label)})]}),$.label.length>u&&p.jsx("div",{className:"absolute left-full top-1/2 transform -translate-y-1/2 ml-2 z-[80] opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none",children:p.jsxs("div",{className:"bg-gray-900 text-white text-xs rounded-md px-[12px] py-[8px] shadow-lg max-w-xs break-words whitespace-normal",children:[$.label,p.jsx("div",{className:"absolute left-0 top-1/2 transform -translate-x-full -translate-y-1/2 w-0 h-0 border-t-4 border-b-4 border-r-4 border-transparent border-r-gray-900"})]})})]},$.value))}),T&&p.jsxs("div",{className:"px-[12px] py-[8px] text-xs text-gray-500 bg-gray-50 border-t border-gray-100",children:[p.jsxs("div",{className:"text-center font-medium",children:["+",w.length-l," more items"]}),i&&p.jsx("div",{className:"text-center mt-1 text-gray-400",children:"Use search above to find specific items"})]})]})]})]})},F0=({config:e,className:t})=>{var s;const{dropdown:r,buttons:n,toggle:a}=e,i=l=>{const u=l.toLowerCase();return u.includes("agent")?"agent":u.includes("tool")?"workflowtool":"app"},o=l=>{const u=l.toLowerCase();return u.includes("agent")?{maxItems:50,maxLabelLength:25}:u.includes("tool")?{maxItems:30,maxLabelLength:20}:{maxItems:40,maxLabelLength:25}};return p.jsxs("div",{className:le("flex items-center gap-3",t),children:[r&&p.jsx(p.Fragment,{children:r.multiSelect?p.jsx(B0,{options:r.options,value:r.defaultValue,placeholder:r.label,multiSelect:r.multiSelect,searchable:r.searchable,onChange:r.onChange,className:"w-48",iconSource:i(r.label),maxItems:o(r.label).maxItems,maxLabelLength:o(r.label).maxLabelLength}):p.jsx(Ns,{options:r.options,value:Array.isArray(r.defaultValue)?r.defaultValue[0]:r.defaultValue||((s=r.options[0])==null?void 0:s.value),placeholder:r.label,onChange:l=>{var u;return(u=r.onChange)==null?void 0:u.call(r,l)},className:"w-48"})}),n&&n.length>0&&p.jsx("div",{className:"flex items-center border border-gray-200 rounded-lg overflow-hidden",children:n.map((l,u)=>p.jsx("button",{onClick:()=>{var c;return(c=l.onClick)==null?void 0:c.call(l,l.value)},className:le("px-[12px] py-[8px] text-xs font-medium transition-colors","hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-inset",l.active?"bg-white text-gray-900 shadow-[0 1px 3px 0 rgba(16, 24, 40, 0.08), 0 1px 2px 0 rgba(16, 24, 40, 0.08)]":"text-gray-500 bg-white",u>0&&"border-l border-gray-200"),children:l.icon&&p.jsx("span",{className:"mr-[8px]",children:l.icon})},l.value))}),a&&p.jsxs("div",{className:"flex items-center gap-[4px] border border-gray-200 bg-gray-50 overflow-hidden p-[2px] rounded-[6px]",children:[p.jsx("button",{onClick:()=>{var l;return(l=a.onToggle)==null?void 0:l.call(a,"chart")},className:le("px-[12px] py-[8px] rounded-[4px] text-xs font-medium transition-colors flex items-center gap-2","hover:bg-white ",a.chartView?"bg-white text-gray-900 shadow-md":"text-gray-500 bg-white"),children:p.jsx(Sb,{className:"w-[16px] h-[16px]"})}),p.jsx("button",{onClick:()=>{var l;return(l=a.onToggle)==null?void 0:l.call(a,"table")},className:le("px-[12px] rounded-[4px] py-[8px] text-xs font-medium transition-colors flex items-center gap-2","hover:bg-white ",a.tableView?"bg-white text-gray-900 shadow-md":"text-gray-500 bg-white"),children:p.jsx(Mb,{className:"w-[16px] h-[16px]"})})]})]})},U0=({section:e,className:t,isLoading:r,isChartLoading:n,onMetricClick:a})=>{var Z;const{id:i,title:o,description:s,metrics:l,view:u,controls:c,layout:f}=e,[d,m]=S.useState(u.type),[g,v]=S.useState("chart"),h=()=>i==="usage-analytics"?"users":i==="runs"?"agentRuns":"users",[b,w]=S.useState(h()),[x,T]=S.useState("all"),y=E=>{var z,H,I,V,X;const B=j();(z=B==null?void 0:B.controls)!=null&&z.toggle?(v(E),(I=(H=B.controls.toggle).onToggle)==null||I.call(H,E)):(m(E),(X=(V=c==null?void 0:c.toggle)==null?void 0:V.onToggle)==null||X.call(V,E))},O=E=>{var H,I;const B=E.metricType||E.title.toLowerCase();w(B);const z=l.find(V=>(V.metricType||V.title.toLowerCase())===B);(I=(H=z==null?void 0:z.controls)==null?void 0:H.dropdown)!=null&&I.multiSelect?T(["all"]):T("all"),a==null||a(E)},A=E=>{var z,H,I;T(E);const B=l.find(V=>(V.metricType||V.title.toLowerCase())===b);(I=(H=(z=B==null?void 0:B.controls)==null?void 0:z.dropdown)==null?void 0:H.onChange)==null||I.call(H,E)},j=()=>l.find(E=>(E.metricType||E.title.toLowerCase())===b)||null,C=E=>Array.isArray(E)?E.filter(z=>z!=="all").length>0:E!=="all",$=E=>Array.isArray(E)?E.filter(B=>B!=="all"):E!=="all"?[E]:[],P=E=>{var I,V,X,re,L,W,G,J,M;const B=((V=(I=E.view)==null?void 0:I.chart)==null?void 0:V.data)||((X=u.chart)==null?void 0:X.data)||[];if(!C(x))return B;const z=E.metricType,H=$(x);if(H.length===1){const Q=H[0],K=j(),se=(W=(L=(re=K==null?void 0:K.controls)==null?void 0:re.dropdown)==null?void 0:L.options)==null?void 0:W.find(fe=>fe.value===Q),ne=se==null?void 0:se.label;return console.log("🔍 Filtering chart data:",{metricType:z,singleFilter:Q,selectedLabel:ne,baseDataSample:B[0]}),B.map(fe=>{let ue=0;return fe.listView&&Array.isArray(fe.listView)&&(ue=fe.listView.filter(Ge=>z==="agentRuns"&&Ge.agentName?Ge.agentName===ne||Ge.agentName.toLowerCase()===(ne==null?void 0:ne.toLowerCase()):z==="toolRuns"&&Ge.toolName?Ge.toolName===ne||Ge.toolName.toLowerCase()===(ne==null?void 0:ne.toLowerCase()):z==="modelRuns"&&Ge.modelName?Ge.modelName===ne||Ge.modelName.toLowerCase()===(ne==null?void 0:ne.toLowerCase()):!1).reduce((Ge,ut)=>Ge+(ut.count||0),0)),console.log("📊 Filtered value for",ne,":",ue),{...fe,[z]:ue}})}if(H.length>1){const Q=j(),se=(((M=(J=(G=Q==null?void 0:Q.controls)==null?void 0:G.dropdown)==null?void 0:J.options)==null?void 0:M.filter(ne=>H.includes(ne.value)))||[]).map(ne=>ne.label);return B.map(ne=>{let fe=0;return ne.listView&&Array.isArray(ne.listView)&&(fe=ne.listView.filter(Ee=>z==="agentRuns"&&Ee.agentName?se.some(Oe=>Ee.agentName===Oe||Ee.agentName.toLowerCase()===(Oe==null?void 0:Oe.toLowerCase())):z==="toolRuns"&&Ee.toolName?se.some(Oe=>Ee.toolName===Oe||Ee.toolName.toLowerCase()===(Oe==null?void 0:Oe.toLowerCase())):z==="modelRuns"&&Ee.modelName?se.some(Oe=>Ee.modelName===Oe||Ee.modelName.toLowerCase()===(Oe==null?void 0:Oe.toLowerCase())):!1).reduce((Ee,Oe)=>Ee+(Oe.count||0),0)),{...ne,[z]:fe}})}return B},_=E=>{var I;if(!((I=E.view)!=null&&I.chart))return null;const B=P(E),z=()=>{var X,re,L,W,G,J;if(!C(x)||!((X=E.controls)!=null&&X.dropdown))return((L=(re=E.view)==null?void 0:re.chart)==null?void 0:L.title)||E.title;const V=$(x);if(V.length===1){const M=(W=E.controls.dropdown.options)==null?void 0:W.find(Q=>Q.value===V[0]);return M?`${M.label}`:((J=(G=E.view)==null?void 0:G.chart)==null?void 0:J.title)||E.title}return`${V.length} selected`},H=$(x);return E.metricType==="toolRuns"&&H.length===1?{...E.view.chart,data:B,title:z(),lines:void 0,dataKey:"toolRuns",color:"#f97316",showLegend:!1}:E.metricType==="modelRuns"&&H.length===1?{...E.view.chart,data:B,title:z(),dataKey:"modelRuns",color:"#10b981",showLegend:!1}:{...E.view.chart,data:B,title:z()}},F=(E,B)=>{if(!C(x))return E;const z=$(x);if(z.length===1){const H=z[0];if(i==="runs"&&B==="agentRuns")return E.map(I=>({...I,agentRuns:I[H]||0}));if(i==="runs"&&B==="toolRuns")return E.map(I=>({...I,toolRuns:I[H.replace(/[-]/g,"")]||0}));if(i==="runs"&&B==="modelRuns")return E.map(I=>({...I,modelRuns:I[H.replace(/[-\.]/g,"")]||0}))}return E},N=E=>{var I;const B=((I=u.chart)==null?void 0:I.data)||[],z=F(B,E),H=V=>{var re,L;if(!C(x))return V;const X=$(x);if(X.length===1){const W=(L=(re=c==null?void 0:c.dropdown)==null?void 0:re.options)==null?void 0:L.find(G=>G.value===X[0]);return W?`${W.label}`:V}return`${X.length} selected`};switch(E){case"users":return{type:"line",title:"Total Users",data:B,dataKey:"users",color:"#8b5cf6",yAxisLabel:"Number of Users",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}};case"sessions":return{type:"line",title:"Total Sessions",data:B,dataKey:"sessions",color:"#06b6d4",yAxisLabel:"Number of Sessions",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}};case"messages":return{type:"line",title:"Total Messages",data:B,dataKey:"messages",color:"#ec4899",yAxisLabel:"Number of Messages",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}};case"tokens":return{type:"line",title:"Token Usage Breakdown",data:B,yAxisLabel:"Number of Tokens",lines:[{dataKey:"totalTokens",color:"#f59e0b",label:"Total Tokens"},{dataKey:"inputTokens",color:"#3b82f6",label:"Input Tokens"},{dataKey:"outputTokens",color:"#ec4899",label:"Output Tokens"}],height:300,showGrid:!0,showLegend:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}};case"agentRuns":return{type:"line",title:H("Agent Runs"),data:z,dataKey:"agentRuns",color:"#06b6d4",yAxisLabel:"Number of Agent Runs",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}};case"toolRuns":return $(x).length===1?{type:"line",title:H("Tool Runs"),data:F(B,"toolRuns"),dataKey:"toolRuns",color:"#f97316",yAxisLabel:"Number of Tool Runs",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}}:{type:"line",title:"Tool Runs",data:z,yAxisLabel:"Number of Tool Runs",lines:[{dataKey:"toolRuns",color:"#06b6d4",label:"Tool Runs"},{dataKey:"codeTools",color:"#f97316",label:"Code Tools"},{dataKey:"workflowTools",color:"#10b981",label:"Workflow Tools"},{dataKey:"knowledgeTools",color:"#8b5cf6",label:"Knowledge"},{dataKey:"mcpTools",color:"#ef4444",label:"MCP Tools"}],height:300,showGrid:!0,showLegend:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}};case"modelRuns":return $(x).length===1?{type:"line",title:H("Model Runs"),data:F(B,"modelRuns"),dataKey:"modelRuns",color:"#10b981",yAxisLabel:"Number of Model Runs",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}}:{type:"line",title:H("Model Runs"),data:z,dataKey:"modelRuns",color:"#10b981",yAxisLabel:"Number of Model Runs",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}};default:return null}},R=(()=>{const E=j();return E!=null&&E.controls?{...E.controls,dropdown:E.controls.dropdown?{...E.controls.dropdown,onChange:A}:void 0,toggle:E.controls.toggle?{...E.controls.toggle,chartView:g==="chart",tableView:g==="table",onToggle:y}:void 0}:c?{...c,dropdown:c.dropdown?{...c.dropdown,onChange:A}:void 0,toggle:c.toggle?{...c.toggle,chartView:d==="chart",tableView:d==="table",onToggle:y}:void 0}:void 0})(),U=(()=>{var z,H,I,V,X,re,L,W,G,J;const E=j();if(E!=null&&E.view){if((z=E.controls)!=null&&z.toggle){if(g==="table"&&E.view.table){let Q=E.view.table.data;if(E.metricType==="agentRuns"&&C(x)){const K=$(x);if(K.length>0){const se=((V=(I=(H=E.controls)==null?void 0:H.dropdown)==null?void 0:I.options)==null?void 0:V.filter(ne=>K.includes(ne.value)))||[];se.length>0&&(Q=Q.filter(ne=>se.some(fe=>ne.name===fe.label||ne.name&&ne.name.toLowerCase().includes(fe.label.toLowerCase()))))}}if(E.metricType==="toolRuns"&&C(x)){const K=$(x);if(K.length>0){const se=((L=(re=(X=E.controls)==null?void 0:X.dropdown)==null?void 0:re.options)==null?void 0:L.filter(ne=>K.includes(ne.value)))||[];se.length>0&&(Q=Q.filter(ne=>se.some(fe=>ne.name===fe.label||ne.name&&ne.name.toLowerCase().includes(fe.label.toLowerCase()))))}}if(E.metricType==="modelRuns"&&C(x)){const K=$(x);if(K.length>0){const se=((J=(G=(W=E.controls)==null?void 0:W.dropdown)==null?void 0:G.options)==null?void 0:J.filter(ne=>K.includes(ne.value)))||[];se.length>0&&(Q=Q.filter(ne=>se.some(fe=>ne.name===fe.label||ne.name&&ne.name.toLowerCase().includes(fe.label.toLowerCase()))))}}return{type:"table",table:{...E.view.table,data:Q}}}else if(g==="chart"&&E.view.chart)return{type:"chart",chart:_(E)||E.view.chart}}const M=_(E);return M?{...E.view,chart:M}:E.view}const B=N(b);return B?{type:"chart",chart:B}:{...u,type:d}})(),q=()=>l.map(E=>{const B=E.metricType||E.title.toLowerCase();return{...E,highlighted:E.highlighted||B===b}});return p.jsxs("div",{className:le("bg-white flex flex-col gap-[16px] rounded-lg border border-gray-200 py-[16px] px-[24px]",t),style:{gridColumn:f!=null&&f.span?`span ${f.span}`:void 0,order:f==null?void 0:f.order},children:[o&&p.jsxs("div",{className:"w-full",children:[p.jsx("h1",{className:"text-md font-medium text-gray-700",children:o}),s&&p.jsx("p",{className:"text-xs text-gray-500",children:s})]}),p.jsx("div",{className:"flex flex-col sm:flex-row gap-[16px]",children:r?p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"flex-1",children:p.jsx(bi,{})}),p.jsx("div",{className:"flex-1",children:p.jsx(bi,{})}),p.jsx("div",{className:"flex-1",children:p.jsx(bi,{})}),p.jsx("div",{className:"flex-1",children:p.jsx(bi,{})})]}):q().map((E,B)=>p.jsx("div",{className:"flex-1",children:p.jsx(Wf,{data:E,onClick:O,isFirst:B===0})},`${i}-metric-${B}`))}),p.jsxs("div",{className:"flex items-center justify-between",children:[p.jsx("div",{children:j()&&p.jsx("h3",{className:"text-md font-medium text-gray-700",children:(Z=j())==null?void 0:Z.title})}),R&&p.jsx(F0,{config:R})]}),p.jsx(R0,{config:U,isLoading:r||n,context:{sectionId:i,metricType:b}})]})},df=S.forwardRef(({className:e,variant:t="default",size:r="md",children:n,...a},i)=>{const o="inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",s={default:"bg-blue-600 hover:bg-blue-700 focus:bg-blue-700 focus:shadow-sm text-white py-2 px-3",outline:"border-gray-300 border bg-white text-gray-700 hover:text-gray-800 hover:bg-gray-50 focus:bg-gray-50 focus:shadow-sm",ghost:"border border-error-600 bg-error-500 text-white hover:border-error-600 hover:bg-error-600"},l={sm:"h-[32px] rounded-md gap-1.5 px-[14px] py-[10px]",md:"h-[40px] rounded-md px-[14px] py-[10px]",lg:"h-[48px] rounded-md px-[16px] py-[12px]"};return p.jsx("button",{className:le(o,s[t],l[r],e),ref:i,...a,children:n})});df.displayName="Button";function Ms(e){"@babel/helpers - typeof";return Ms=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},Ms(e)}function Ct(e){if(e===null||e===!0||e===!1)return NaN;var t=Number(e);return isNaN(t)?t:t<0?Math.ceil(t):Math.floor(t)}function Le(e,t){if(t.length<e)throw new TypeError(e+" argument"+(e>1?"s":"")+" required, but only "+t.length+" present")}function Ve(e){Le(1,arguments);var t=Object.prototype.toString.call(e);return e instanceof Date||Ms(e)==="object"&&t==="[object Date]"?new Date(e.getTime()):typeof e=="number"||t==="[object Number]"?new Date(e):((typeof e=="string"||t==="[object String]")&&typeof console<"u"&&(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn(new Error().stack)),new Date(NaN))}function YB(e,t){Le(2,arguments);var r=Ve(e),n=Ct(t);return isNaN(n)?new Date(NaN):(n&&r.setDate(r.getDate()+n),r)}function pf(e,t){Le(2,arguments);var r=Ve(e),n=Ct(t);if(isNaN(n))return new Date(NaN);if(!n)return r;var a=r.getDate(),i=new Date(r.getTime());i.setMonth(r.getMonth()+n+1,0);var o=i.getDate();return a>=o?i:(r.setFullYear(i.getFullYear(),i.getMonth(),a),r)}function XB(e,t){Le(2,arguments);var r=Ve(e).getTime(),n=Ct(t);return new Date(r+n)}var ZB={};function wi(){return ZB}function JB(e,t){var r,n,a,i,o,s;Le(1,arguments);var l=wi(),u=Ct((r=(n=(a=(i=void 0)!==null&&i!==void 0?i:void 0)!==null&&a!==void 0?a:l.weekStartsOn)!==null&&n!==void 0?n:(o=l.locale)===null||o===void 0||(s=o.options)===null||s===void 0?void 0:s.weekStartsOn)!==null&&r!==void 0?r:0);if(!(u>=0&&u<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var c=Ve(e),f=c.getDay(),d=(f<u?7:0)+f-u;return c.setDate(c.getDate()-d),c.setHours(0,0,0,0),c}function QB(e){var t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),e.getTime()-t.getTime()}function aa(e){Le(1,arguments);var t=Ve(e);return t.setHours(0,0,0,0),t}function Oi(e,t){Le(2,arguments);var r=aa(e),n=aa(t);return r.getTime()===n.getTime()}function eF(e){return Le(1,arguments),e instanceof Date||Ms(e)==="object"&&Object.prototype.toString.call(e)==="[object Date]"}function tF(e){if(Le(1,arguments),!eF(e)&&typeof e!="number")return!1;var t=Ve(e);return!isNaN(Number(t))}function rF(e){Le(1,arguments);var t=Ve(e);return t.setHours(23,59,59,999),t}function nF(e){Le(1,arguments);var t=Ve(e);return t.setDate(1),t.setHours(0,0,0,0),t}function aF(e,t){Le(2,arguments);var r=Ct(t);return XB(e,-r)}var iF=864e5;function oF(e){Le(1,arguments);var t=Ve(e),r=t.getTime();t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0);var n=t.getTime(),a=r-n;return Math.floor(a/iF)+1}function Ds(e){Le(1,arguments);var t=1,r=Ve(e),n=r.getUTCDay(),a=(n<t?7:0)+n-t;return r.setUTCDate(r.getUTCDate()-a),r.setUTCHours(0,0,0,0),r}function W0(e){Le(1,arguments);var t=Ve(e),r=t.getUTCFullYear(),n=new Date(0);n.setUTCFullYear(r+1,0,4),n.setUTCHours(0,0,0,0);var a=Ds(n),i=new Date(0);i.setUTCFullYear(r,0,4),i.setUTCHours(0,0,0,0);var o=Ds(i);return t.getTime()>=a.getTime()?r+1:t.getTime()>=o.getTime()?r:r-1}function sF(e){Le(1,arguments);var t=W0(e),r=new Date(0);r.setUTCFullYear(t,0,4),r.setUTCHours(0,0,0,0);var n=Ds(r);return n}var lF=6048e5;function uF(e){Le(1,arguments);var t=Ve(e),r=Ds(t).getTime()-sF(t).getTime();return Math.round(r/lF)+1}function Is(e,t){var r,n,a,i,o,s,l,u;Le(1,arguments);var c=wi(),f=Ct((r=(n=(a=(i=t==null?void 0:t.weekStartsOn)!==null&&i!==void 0?i:t==null||(o=t.locale)===null||o===void 0||(s=o.options)===null||s===void 0?void 0:s.weekStartsOn)!==null&&a!==void 0?a:c.weekStartsOn)!==null&&n!==void 0?n:(l=c.locale)===null||l===void 0||(u=l.options)===null||u===void 0?void 0:u.weekStartsOn)!==null&&r!==void 0?r:0);if(!(f>=0&&f<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");var d=Ve(e),m=d.getUTCDay(),g=(m<f?7:0)+m-f;return d.setUTCDate(d.getUTCDate()-g),d.setUTCHours(0,0,0,0),d}function z0(e,t){var r,n,a,i,o,s,l,u;Le(1,arguments);var c=Ve(e),f=c.getUTCFullYear(),d=wi(),m=Ct((r=(n=(a=(i=t==null?void 0:t.firstWeekContainsDate)!==null&&i!==void 0?i:t==null||(o=t.locale)===null||o===void 0||(s=o.options)===null||s===void 0?void 0:s.firstWeekContainsDate)!==null&&a!==void 0?a:d.firstWeekContainsDate)!==null&&n!==void 0?n:(l=d.locale)===null||l===void 0||(u=l.options)===null||u===void 0?void 0:u.firstWeekContainsDate)!==null&&r!==void 0?r:1);if(!(m>=1&&m<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var g=new Date(0);g.setUTCFullYear(f+1,0,m),g.setUTCHours(0,0,0,0);var v=Is(g,t),h=new Date(0);h.setUTCFullYear(f,0,m),h.setUTCHours(0,0,0,0);var b=Is(h,t);return c.getTime()>=v.getTime()?f+1:c.getTime()>=b.getTime()?f:f-1}function cF(e,t){var r,n,a,i,o,s,l,u;Le(1,arguments);var c=wi(),f=Ct((r=(n=(a=(i=t==null?void 0:t.firstWeekContainsDate)!==null&&i!==void 0?i:t==null||(o=t.locale)===null||o===void 0||(s=o.options)===null||s===void 0?void 0:s.firstWeekContainsDate)!==null&&a!==void 0?a:c.firstWeekContainsDate)!==null&&n!==void 0?n:(l=c.locale)===null||l===void 0||(u=l.options)===null||u===void 0?void 0:u.firstWeekContainsDate)!==null&&r!==void 0?r:1),d=z0(e,t),m=new Date(0);m.setUTCFullYear(d,0,f),m.setUTCHours(0,0,0,0);var g=Is(m,t);return g}var fF=6048e5;function dF(e,t){Le(1,arguments);var r=Ve(e),n=Is(r,t).getTime()-cF(r,t).getTime();return Math.round(n/fF)+1}function $e(e,t){for(var r=e<0?"-":"",n=Math.abs(e).toString();n.length<t;)n="0"+n;return r+n}var _r={y:function(t,r){var n=t.getUTCFullYear(),a=n>0?n:1-n;return $e(r==="yy"?a%100:a,r.length)},M:function(t,r){var n=t.getUTCMonth();return r==="M"?String(n+1):$e(n+1,2)},d:function(t,r){return $e(t.getUTCDate(),r.length)},a:function(t,r){var n=t.getUTCHours()/12>=1?"pm":"am";switch(r){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h:function(t,r){return $e(t.getUTCHours()%12||12,r.length)},H:function(t,r){return $e(t.getUTCHours(),r.length)},m:function(t,r){return $e(t.getUTCMinutes(),r.length)},s:function(t,r){return $e(t.getUTCSeconds(),r.length)},S:function(t,r){var n=r.length,a=t.getUTCMilliseconds(),i=Math.floor(a*Math.pow(10,n-3));return $e(i,r.length)}},ia={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},pF={G:function(t,r,n){var a=t.getUTCFullYear()>0?1:0;switch(r){case"G":case"GG":case"GGG":return n.era(a,{width:"abbreviated"});case"GGGGG":return n.era(a,{width:"narrow"});case"GGGG":default:return n.era(a,{width:"wide"})}},y:function(t,r,n){if(r==="yo"){var a=t.getUTCFullYear(),i=a>0?a:1-a;return n.ordinalNumber(i,{unit:"year"})}return _r.y(t,r)},Y:function(t,r,n,a){var i=z0(t,a),o=i>0?i:1-i;if(r==="YY"){var s=o%100;return $e(s,2)}return r==="Yo"?n.ordinalNumber(o,{unit:"year"}):$e(o,r.length)},R:function(t,r){var n=W0(t);return $e(n,r.length)},u:function(t,r){var n=t.getUTCFullYear();return $e(n,r.length)},Q:function(t,r,n){var a=Math.ceil((t.getUTCMonth()+1)/3);switch(r){case"Q":return String(a);case"QQ":return $e(a,2);case"Qo":return n.ordinalNumber(a,{unit:"quarter"});case"QQQ":return n.quarter(a,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(a,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(a,{width:"wide",context:"formatting"})}},q:function(t,r,n){var a=Math.ceil((t.getUTCMonth()+1)/3);switch(r){case"q":return String(a);case"qq":return $e(a,2);case"qo":return n.ordinalNumber(a,{unit:"quarter"});case"qqq":return n.quarter(a,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(a,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(a,{width:"wide",context:"standalone"})}},M:function(t,r,n){var a=t.getUTCMonth();switch(r){case"M":case"MM":return _r.M(t,r);case"Mo":return n.ordinalNumber(a+1,{unit:"month"});case"MMM":return n.month(a,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(a,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(a,{width:"wide",context:"formatting"})}},L:function(t,r,n){var a=t.getUTCMonth();switch(r){case"L":return String(a+1);case"LL":return $e(a+1,2);case"Lo":return n.ordinalNumber(a+1,{unit:"month"});case"LLL":return n.month(a,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(a,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(a,{width:"wide",context:"standalone"})}},w:function(t,r,n,a){var i=dF(t,a);return r==="wo"?n.ordinalNumber(i,{unit:"week"}):$e(i,r.length)},I:function(t,r,n){var a=uF(t);return r==="Io"?n.ordinalNumber(a,{unit:"week"}):$e(a,r.length)},d:function(t,r,n){return r==="do"?n.ordinalNumber(t.getUTCDate(),{unit:"date"}):_r.d(t,r)},D:function(t,r,n){var a=oF(t);return r==="Do"?n.ordinalNumber(a,{unit:"dayOfYear"}):$e(a,r.length)},E:function(t,r,n){var a=t.getUTCDay();switch(r){case"E":case"EE":case"EEE":return n.day(a,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(a,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(a,{width:"short",context:"formatting"});case"EEEE":default:return n.day(a,{width:"wide",context:"formatting"})}},e:function(t,r,n,a){var i=t.getUTCDay(),o=(i-a.weekStartsOn+8)%7||7;switch(r){case"e":return String(o);case"ee":return $e(o,2);case"eo":return n.ordinalNumber(o,{unit:"day"});case"eee":return n.day(i,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(i,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(i,{width:"short",context:"formatting"});case"eeee":default:return n.day(i,{width:"wide",context:"formatting"})}},c:function(t,r,n,a){var i=t.getUTCDay(),o=(i-a.weekStartsOn+8)%7||7;switch(r){case"c":return String(o);case"cc":return $e(o,r.length);case"co":return n.ordinalNumber(o,{unit:"day"});case"ccc":return n.day(i,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(i,{width:"narrow",context:"standalone"});case"cccccc":return n.day(i,{width:"short",context:"standalone"});case"cccc":default:return n.day(i,{width:"wide",context:"standalone"})}},i:function(t,r,n){var a=t.getUTCDay(),i=a===0?7:a;switch(r){case"i":return String(i);case"ii":return $e(i,r.length);case"io":return n.ordinalNumber(i,{unit:"day"});case"iii":return n.day(a,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(a,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(a,{width:"short",context:"formatting"});case"iiii":default:return n.day(a,{width:"wide",context:"formatting"})}},a:function(t,r,n){var a=t.getUTCHours(),i=a/12>=1?"pm":"am";switch(r){case"a":case"aa":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(i,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(i,{width:"wide",context:"formatting"})}},b:function(t,r,n){var a=t.getUTCHours(),i;switch(a===12?i=ia.noon:a===0?i=ia.midnight:i=a/12>=1?"pm":"am",r){case"b":case"bb":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(i,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(i,{width:"wide",context:"formatting"})}},B:function(t,r,n){var a=t.getUTCHours(),i;switch(a>=17?i=ia.evening:a>=12?i=ia.afternoon:a>=4?i=ia.morning:i=ia.night,r){case"B":case"BB":case"BBB":return n.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(i,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(i,{width:"wide",context:"formatting"})}},h:function(t,r,n){if(r==="ho"){var a=t.getUTCHours()%12;return a===0&&(a=12),n.ordinalNumber(a,{unit:"hour"})}return _r.h(t,r)},H:function(t,r,n){return r==="Ho"?n.ordinalNumber(t.getUTCHours(),{unit:"hour"}):_r.H(t,r)},K:function(t,r,n){var a=t.getUTCHours()%12;return r==="Ko"?n.ordinalNumber(a,{unit:"hour"}):$e(a,r.length)},k:function(t,r,n){var a=t.getUTCHours();return a===0&&(a=24),r==="ko"?n.ordinalNumber(a,{unit:"hour"}):$e(a,r.length)},m:function(t,r,n){return r==="mo"?n.ordinalNumber(t.getUTCMinutes(),{unit:"minute"}):_r.m(t,r)},s:function(t,r,n){return r==="so"?n.ordinalNumber(t.getUTCSeconds(),{unit:"second"}):_r.s(t,r)},S:function(t,r){return _r.S(t,r)},X:function(t,r,n,a){var i=a._originalDate||t,o=i.getTimezoneOffset();if(o===0)return"Z";switch(r){case"X":return G0(o);case"XXXX":case"XX":return Zr(o);case"XXXXX":case"XXX":default:return Zr(o,":")}},x:function(t,r,n,a){var i=a._originalDate||t,o=i.getTimezoneOffset();switch(r){case"x":return G0(o);case"xxxx":case"xx":return Zr(o);case"xxxxx":case"xxx":default:return Zr(o,":")}},O:function(t,r,n,a){var i=a._originalDate||t,o=i.getTimezoneOffset();switch(r){case"O":case"OO":case"OOO":return"GMT"+V0(o,":");case"OOOO":default:return"GMT"+Zr(o,":")}},z:function(t,r,n,a){var i=a._originalDate||t,o=i.getTimezoneOffset();switch(r){case"z":case"zz":case"zzz":return"GMT"+V0(o,":");case"zzzz":default:return"GMT"+Zr(o,":")}},t:function(t,r,n,a){var i=a._originalDate||t,o=Math.floor(i.getTime()/1e3);return $e(o,r.length)},T:function(t,r,n,a){var i=a._originalDate||t,o=i.getTime();return $e(o,r.length)}};function V0(e,t){var r=e>0?"-":"+",n=Math.abs(e),a=Math.floor(n/60),i=n%60;if(i===0)return r+String(a);var o=t;return r+String(a)+o+$e(i,2)}function G0(e,t){if(e%60===0){var r=e>0?"-":"+";return r+$e(Math.abs(e)/60,2)}return Zr(e,t)}function Zr(e,t){var r=t||"",n=e>0?"-":"+",a=Math.abs(e),i=$e(Math.floor(a/60),2),o=$e(a%60,2);return n+i+r+o}var H0=function(t,r){switch(t){case"P":return r.date({width:"short"});case"PP":return r.date({width:"medium"});case"PPP":return r.date({width:"long"});case"PPPP":default:return r.date({width:"full"})}},q0=function(t,r){switch(t){case"p":return r.time({width:"short"});case"pp":return r.time({width:"medium"});case"ppp":return r.time({width:"long"});case"pppp":default:return r.time({width:"full"})}},hF=function(t,r){var n=t.match(/(P+)(p+)?/)||[],a=n[1],i=n[2];if(!i)return H0(t,r);var o;switch(a){case"P":o=r.dateTime({width:"short"});break;case"PP":o=r.dateTime({width:"medium"});break;case"PPP":o=r.dateTime({width:"long"});break;case"PPPP":default:o=r.dateTime({width:"full"});break}return o.replace("{{date}}",H0(a,r)).replace("{{time}}",q0(i,r))},mF={p:q0,P:hF},gF=["D","DD"],vF=["YY","YYYY"];function yF(e){return gF.indexOf(e)!==-1}function bF(e){return vF.indexOf(e)!==-1}function K0(e,t,r){if(e==="YYYY")throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(t,"`) for formatting years to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="YY")throw new RangeError("Use `yy` instead of `YY` (in `".concat(t,"`) for formatting years to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="D")throw new RangeError("Use `d` instead of `D` (in `".concat(t,"`) for formatting days of the month to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));if(e==="DD")throw new RangeError("Use `dd` instead of `DD` (in `".concat(t,"`) for formatting days of the month to the input `").concat(r,"`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"))}var xF={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},wF=function(t,r,n){var a,i=xF[t];return typeof i=="string"?a=i:r===1?a=i.one:a=i.other.replace("{{count}}",r.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+a:a+" ago":a};function hf(e){return function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=t.width?String(t.width):e.defaultWidth,n=e.formats[r]||e.formats[e.defaultWidth];return n}}var OF={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},SF={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},AF={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},TF={date:hf({formats:OF,defaultWidth:"full"}),time:hf({formats:SF,defaultWidth:"full"}),dateTime:hf({formats:AF,defaultWidth:"full"})},jF={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},PF=function(t,r,n,a){return jF[t]};function Si(e){return function(t,r){var n=r!=null&&r.context?String(r.context):"standalone",a;if(n==="formatting"&&e.formattingValues){var i=e.defaultFormattingWidth||e.defaultWidth,o=r!=null&&r.width?String(r.width):i;a=e.formattingValues[o]||e.formattingValues[i]}else{var s=e.defaultWidth,l=r!=null&&r.width?String(r.width):e.defaultWidth;a=e.values[l]||e.values[s]}var u=e.argumentCallback?e.argumentCallback(t):t;return a[u]}}var _F={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},EF={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},CF={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},$F={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},kF={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},NF={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},MF=function(t,r){var n=Number(t),a=n%100;if(a>20||a<10)switch(a%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},DF={ordinalNumber:MF,era:Si({values:_F,defaultWidth:"wide"}),quarter:Si({values:EF,defaultWidth:"wide",argumentCallback:function(t){return t-1}}),month:Si({values:CF,defaultWidth:"wide"}),day:Si({values:$F,defaultWidth:"wide"}),dayPeriod:Si({values:kF,defaultWidth:"wide",formattingValues:NF,defaultFormattingWidth:"wide"})};function Ai(e){return function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=r.width,a=n&&e.matchPatterns[n]||e.matchPatterns[e.defaultMatchWidth],i=t.match(a);if(!i)return null;var o=i[0],s=n&&e.parsePatterns[n]||e.parsePatterns[e.defaultParseWidth],l=Array.isArray(s)?LF(s,function(f){return f.test(o)}):IF(s,function(f){return f.test(o)}),u;u=e.valueCallback?e.valueCallback(l):l,u=r.valueCallback?r.valueCallback(u):u;var c=t.slice(o.length);return{value:u,rest:c}}}function IF(e,t){for(var r in e)if(e.hasOwnProperty(r)&&t(e[r]))return r}function LF(e,t){for(var r=0;r<e.length;r++)if(t(e[r]))return r}function RF(e){return function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=t.match(e.matchPattern);if(!n)return null;var a=n[0],i=t.match(e.parsePattern);if(!i)return null;var o=e.valueCallback?e.valueCallback(i[0]):i[0];o=r.valueCallback?r.valueCallback(o):o;var s=t.slice(a.length);return{value:o,rest:s}}}var BF=/^(\d+)(th|st|nd|rd)?/i,FF=/\d+/i,UF={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},WF={any:[/^b/i,/^(a|c)/i]},zF={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},VF={any:[/1/i,/2/i,/3/i,/4/i]},GF={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},HF={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},qF={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},KF={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},YF={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},XF={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},ZF={ordinalNumber:RF({matchPattern:BF,parsePattern:FF,valueCallback:function(t){return parseInt(t,10)}}),era:Ai({matchPatterns:UF,defaultMatchWidth:"wide",parsePatterns:WF,defaultParseWidth:"any"}),quarter:Ai({matchPatterns:zF,defaultMatchWidth:"wide",parsePatterns:VF,defaultParseWidth:"any",valueCallback:function(t){return t+1}}),month:Ai({matchPatterns:GF,defaultMatchWidth:"wide",parsePatterns:HF,defaultParseWidth:"any"}),day:Ai({matchPatterns:qF,defaultMatchWidth:"wide",parsePatterns:KF,defaultParseWidth:"any"}),dayPeriod:Ai({matchPatterns:YF,defaultMatchWidth:"any",parsePatterns:XF,defaultParseWidth:"any"})},JF={code:"en-US",formatDistance:wF,formatLong:TF,formatRelative:PF,localize:DF,match:ZF,options:{weekStartsOn:0,firstWeekContainsDate:1}},QF=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,eU=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,tU=/^'([^]*?)'?$/,rU=/''/g,nU=/[a-zA-Z]/;function Ls(e,t,r){var n,a,i,o,s,l,u,c,f,d,m,g,v,h;Le(2,arguments);var b=String(t),w=wi(),x=(n=(a=void 0)!==null&&a!==void 0?a:w.locale)!==null&&n!==void 0?n:JF,T=Ct((i=(o=(s=(l=void 0)!==null&&l!==void 0?l:void 0)!==null&&s!==void 0?s:w.firstWeekContainsDate)!==null&&o!==void 0?o:(u=w.locale)===null||u===void 0||(c=u.options)===null||c===void 0?void 0:c.firstWeekContainsDate)!==null&&i!==void 0?i:1);if(!(T>=1&&T<=7))throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");var y=Ct((f=(d=(m=(g=void 0)!==null&&g!==void 0?g:void 0)!==null&&m!==void 0?m:w.weekStartsOn)!==null&&d!==void 0?d:(v=w.locale)===null||v===void 0||(h=v.options)===null||h===void 0?void 0:h.weekStartsOn)!==null&&f!==void 0?f:0);if(!(y>=0&&y<=6))throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");if(!x.localize)throw new RangeError("locale must contain localize property");if(!x.formatLong)throw new RangeError("locale must contain formatLong property");var O=Ve(e);if(!tF(O))throw new RangeError("Invalid time value");var A=QB(O),j=aF(O,A),C={firstWeekContainsDate:T,weekStartsOn:y,locale:x,_originalDate:O},$=b.match(eU).map(function(P){var _=P[0];if(_==="p"||_==="P"){var F=mF[_];return F(P,x.formatLong)}return P}).join("").match(QF).map(function(P){if(P==="''")return"'";var _=P[0];if(_==="'")return aU(P);var F=pF[_];if(F)return bF(P)&&K0(P,t,String(e)),yF(P)&&K0(P,t,String(e)),F(j,P,x.localize,C);if(_.match(nU))throw new RangeError("Format string contains an unescaped latin alphabet character `"+_+"`");return P}).join("");return $}function aU(e){var t=e.match(tU);return t?t[1].replace(rU,"'"):e}function Y0(e,t){Le(2,arguments);var r=Ve(e),n=Ve(t);return r.getTime()<n.getTime()}function iU(e,t){Le(2,arguments);var r=Ve(e).getTime(),n=Ve(t.start).getTime(),a=Ve(t.end).getTime();if(!(n<=a))throw new RangeError("Invalid interval");return r>=n&&r<=a}function Rs(e,t){Le(2,arguments);var r=Ct(t);return YB(e,-r)}function oU(e,t){Le(2,arguments);var r=Ct(t);return pf(e,-r)}const mf=({children:e})=>{const[t,r]=S.useState(!1);return S.useEffect(()=>(r(!0),()=>r(!1)),[]),t?en.createPortal(e,document.body):null};function X0({className:e,defaultValue:t,onDateRangeChange:r}){console.log("🗓️ DateRangePicker component rendered with props:",{className:e,defaultValue:t,hasCallback:!!r});const n=[{label:"Today",value:"today",dateRange:{from:aa(new Date),to:new Date}},{label:"Yesterday",value:"yesterday",dateRange:{from:aa(Rs(new Date,1)),to:rF(Rs(new Date,1))}},{label:"This week",value:"thisWeek",dateRange:{from:JB(new Date),to:new Date}},{label:"Last 7 days",value:"7d",dateRange:{from:aa(Rs(new Date,6)),to:new Date}},{label:"This month",value:"thisMonth",dateRange:{from:nF(new Date),to:new Date}},{label:"Last 30 days",value:"30d",dateRange:{from:aa(Rs(new Date,29)),to:new Date}}],a=t?n.find(k=>k.value===t):null;console.log("📅 DateRangePicker initialization:",{defaultValue:t,defaultPreset:a==null?void 0:a.label,hasDateRange:!!(a!=null&&a.dateRange),allPresetValues:n.map(k=>k.value),foundPreset:!!a});const[i,o]=S.useState(a==null?void 0:a.dateRange),[s,l]=S.useState(a==null?void 0:a.dateRange),[u,c]=S.useState(!1),[f,d]=S.useState((a==null?void 0:a.label)||null),[m,g]=S.useState((a==null?void 0:a.label)||null),[v,h]=S.useState(new Date),[b,w]=S.useState(null),[x,T]=S.useState({top:0,left:0}),y=S.useRef(null),O=S.useRef(null);S.useEffect(()=>{var k,U;console.log("📅 DateRangePicker useEffect running:",{hasDefaultPreset:!!a,hasOnDateRangeChange:!!r,currentDate:i,currentLabel:f,defaultValue:t,defaultPresetLabel:a==null?void 0:a.label,defaultPresetValue:a==null?void 0:a.value}),a!=null&&a.dateRange&&r?(console.log("📅 DateRangePicker: Setting initial default value:",{label:a.label,dateRange:a.dateRange,from:(k=a.dateRange.from)==null?void 0:k.toLocaleDateString(),to:(U=a.dateRange.to)==null?void 0:U.toLocaleDateString()}),r(a.dateRange)):console.log("📅 DateRangePicker: NOT setting initial value because:",{hasDefaultPreset:!!a,hasDateRange:!!(a!=null&&a.dateRange),hasCallback:!!r,presetLabelsAvailable:n.map(q=>`${q.value}:${q.label}`)})},[]),S.useEffect(()=>{t&&(a!=null&&a.dateRange)&&(console.log("📅 DateRangePicker: DefaultValue changed, updating state:",{defaultValue:t,label:a.label}),o(a.dateRange),d(a.label),l(a.dateRange),g(a.label))},[t]);const A=()=>{if(!O.current)return;const k=O.current.getBoundingClientRect(),U=window.scrollY,q=window.scrollX,Z=window.innerWidth,E=window.innerHeight,B=720,z=450;let H=k.bottom+U+8,I=k.left+q;I+B>Z&&(I=k.right+q-B),I+B>Z&&(I=Z-B-20),H+z>E&&(H=k.top+U-z-8),I<20&&(I=20),H<20&&(H=20),T({top:H,left:I})};S.useEffect(()=>{const k=()=>{u&&A()};return u&&(window.addEventListener("resize",k),window.addEventListener("scroll",k)),()=>{window.removeEventListener("resize",k),window.removeEventListener("scroll",k)}},[u]);const j=(k,U)=>{if(l(k),g(U),w(null),k.from){const q=new Date(k.from.getFullYear(),k.from.getMonth(),1);h(q)}},C=k=>{if(!b)w(k),l({from:k,to:k}),g(null);else{const U=Y0(k,b)?k:b,q=Y0(k,b)?b:k;l({from:U,to:q}),w(null),g(null)}},$=()=>{o(s),d(m),r==null||r(s),c(!1),w(null)},P=()=>{l(void 0),g(null),o(void 0),d(null),r==null||r(void 0),c(!1),w(null)},_=k=>{k?(l(i),g(f),w(null),setTimeout(A,0)):(l(i),g(f),w(null)),c(k)},F=(k,U)=>(console.log("📅 formatDateRange called with:",{presetLabel:U,hasDateRange:!!(k!=null&&k.from)}),U||(k!=null&&k.from?!k.to||Oi(k.from,k.to)?Ls(k.from,"MMM dd, yyyy"):`${Ls(k.from,"MMM dd, yyyy")} - ${Ls(k.to,"MMM dd, yyyy")}`:"Pick a date range")),N=(k=0)=>{const U=pf(v,k),q=U.getFullYear(),Z=U.getMonth(),E=new Date(q,Z,1),z=new Date(q,Z+1,0).getDate(),H=E.getDay(),I=["January","February","March","April","May","June","July","August","September","October","November","December"],V=["Su","Mo","Tu","We","Th","Fr","Sa"],X=[],L=new Date(q,Z-1,0).getDate();for(let J=H-1;J>=0;J--){const M=L-J,Q=new Date(q,Z-1,M);X.push(p.jsx("button",{onClick:()=>C(Q),className:"h-[32px] w-[32px] text-xs text-gray-400 hover:bg-gray-100 rounded-full flex items-center justify-center",children:M},`prev-${M}`))}for(let J=1;J<=z;J++){const M=new Date(q,Z,J),Q=Oi(M,new Date),K=(s==null?void 0:s.from)&&(s==null?void 0:s.to)&&iU(M,{start:s.from,end:s.to}),se=(s==null?void 0:s.from)&&Oi(M,s.from),ne=(s==null?void 0:s.to)&&Oi(M,s.to),fe=b&&Oi(M,b);let ue="h-[32px] w-[32px] text-xs hover:bg-gray-100 hover:text-gray-900 hover:font-medium rounded-full flex items-center justify-center transition-colors text-gray-700 ";Q&&(ue+="font-semibold "),fe||se||ne?ue+="!bg-blue-500 !text-white !hover:bg-blue-500 !hover:text-white font-semibold":K&&(ue+="bg-blue-100 text-blue-900 hover:bg-blue-100 hover:text-blue-900 font-semibold"),X.push(p.jsx("button",{onClick:()=>C(M),className:ue,children:J},`current-${J}`))}const G=Math.ceil((H+z)/7)*7-H-z;for(let J=1;J<=G;J++){const M=new Date(q,Z+1,J);X.push(p.jsx("button",{onClick:()=>C(M),className:"h-[32px] w-[32px] text-sm text-gray-500 hover:bg-gray-100 rounded-full flex items-center justify-center",children:J},`next-${J}`))}return p.jsxs("div",{className:"p-[12px]",children:[p.jsxs("div",{className:"flex items-center justify-between mb-3",children:[k===0&&p.jsx("button",{onClick:()=>h(oU(v,1)),className:"p-[4px] hover:bg-gray-100 rounded",children:p.jsx(Tb,{className:"h-[16px] w-[16px]"})}),p.jsxs("div",{className:"font-semibold text-sm text-gray-700",children:[I[Z]," ",q]}),k===1&&p.jsx("button",{onClick:()=>h(pf(v,1)),className:"p-[4px] hover:bg-gray-100 rounded",children:p.jsx(ki,{className:"h-[16px] w-[16px]"})})]}),p.jsx("div",{className:"grid grid-cols-7 gap-1 mb-2",children:V.map(J=>p.jsx("div",{className:"h-[32px] flex items-center justify-center text-xs font-medium text-gray-700 w-full text-center",children:J},J))}),p.jsx("div",{className:"grid grid-cols-7 gap-1",children:X})]})},R=()=>"fixed bg-white border border-gray-200 rounded-lg shadow-xl z-[99999]";return p.jsxs("div",{className:`relative ${e}`,children:[p.jsxs("button",{ref:O,onClick:()=>_(!u),className:`min-w-[200px] px-[12px] py-[8px] text-left border border-gray-300 rounded-md shadow-sm bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 flex items-center ${i?"text-gray-900":"text-gray-500"}`,children:[p.jsx(Af,{className:"mr-2 h-[16px] w-[16px]"}),(()=>{const k=F(i,f);return console.log("📅 Button display text:",{displayText:k,date:i,selectedPresetLabel:f}),k})()]}),u&&p.jsxs(mf,{children:[p.jsx("div",{className:"fixed inset-0 z-[99998] bg-black bg-opacity-10",onClick:()=>_(!1)}),p.jsxs("div",{ref:y,className:R(),style:{top:x.top,left:x.left,width:"720px",minWidth:"720px",maxHeight:"90vh"},onClick:k=>k.stopPropagation(),children:[p.jsxs("div",{className:"flex",children:[p.jsxs("div",{className:"flex flex-col gap-1 p-[12px] border-r border-gray-200 w-[160px] flex-shrink-0",children:[p.jsx("div",{className:"text-sm font-medium text-gray-500 mb-2",children:"Quick Filters"}),n.map(k=>p.jsx("button",{onClick:()=>j(k.dateRange,k.label),className:`text-left px-[12px] py-[8px] text-sm text-gray-900 rounded hover:bg-gray-100 transition-colors ${m===k.label?"bg-gray-100 medium":""}`,children:k.label},k.label))]}),p.jsxs("div",{className:"flex flex-1",children:[N(0),N(1)]})]}),p.jsxs("div",{className:"border-t border-gray-200 bg-gray-50 p-[12px] flex justify-end gap-2",children:[p.jsx("button",{onClick:P,className:"px-[12px] py-[8px] text-sm border border-gray-300 rounded hover:bg-gray-50 transition-colors",children:"Clear"}),p.jsx("button",{onClick:$,disabled:!(s!=null&&s.from),className:"px-[12px] py-[8px] text-sm bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"Apply"})]})]})]})]})}const sU=({config:e,appConfig:t,className:r,onExport:n,onDraftChange:a,onTimeRangeChange:i})=>{var F;const{title:o,subtitle:s,sections:l,globalControls:u,layout:c={columns:12,gap:24,responsive:!0}}=e,[f,d]=S.useState(!1),[m,g]=S.useState({}),[v,h]=S.useState(l),[b,w]=S.useState([]),[x,T]=S.useState(!1),y=S.useRef(null);S.useEffect(()=>{if(t)try{y.current=new Yt(t),O(),A()}catch(N){console.error("Failed to initialize API service:",N)}},[t]);const O=async()=>{if(!(!y.current||!t)){T(!0);try{const N=await y.current.fetchEnvironments();w(N),console.log("🌍 Environments loaded:",N.map(R=>R.envName))}catch(N){console.error("Error loading environments:",N)}finally{T(!1)}}},A=async()=>{if(!(!y.current||!t)){d(!0);try{const N=y.current.getDefaultTimeRange();console.log("📊 Loading dashboard data with date range:",{fromTimestamp:N.fromTimestamp,toTimestamp:N.toTimestamp,fromDate:new Date(N.fromTimestamp).toLocaleDateString(),toDate:new Date(N.toTimestamp).toLocaleDateString()});const R=await y.current.fetchAllCardsDataWithEnhancedViews(N.fromTimestamp,N.toTimestamp);console.log("✅ Enhanced cards data loaded successfully:",R),console.log("📈 Data covers period:",{from:new Date(N.fromTimestamp).toLocaleDateString(),to:new Date(N.toTimestamp).toLocaleDateString()});const k=l.map(U=>U.id==="usage-analytics"?(console.log("Updating usage-analytics section with enhanced data"),{...U,metrics:R.usageAnalytics}):U.id==="runs"?(console.log("Updating runs section with enhanced data including table and controls"),{...U,metrics:R.runs}):U);h(k)}catch(N){console.error("Error loading initial data:",N),h(l)}finally{d(!1)}}},j=async(N,R)=>{if(!(!y.current||!t||!R.metricType)){h(k=>k.map(U=>U.id===N?{...U,metrics:U.metrics.map(q=>({...q,highlighted:q.metricType===R.metricType}))}:U)),g(k=>({...k,[N]:!0}));try{const k=t.defaultTimeRange||Yt.getDateRange(7);let U,q;if(["users","sessions","messages","tokens"].includes(R.metricType))U="usage-analytics",q=R.metricType;else if(["agentRuns","toolRuns","modelRuns"].includes(R.metricType))U="runs",q=R.metricType==="agentRuns"?"agent-runs":R.metricType==="toolRuns"?"tool-runs":"model-runs";else return;const Z=await y.current.fetchTimeSeriesData(q,U,k.fromTimestamp,k.toTimestamp),E=y.current.transformTimeSeriesDataForMetric(Z,R.metricType);console.log("Time series response for",R.title,":",Z),console.log("Transformed data for",R.title,":",E),console.log("Metric type used for transformation:",R.metricType);const z=(H=>({users:"users",sessions:"sessions",messages:"messages",tokens:"totalTokens",agentRuns:"agentRuns",toolRuns:"toolRuns",modelRuns:"modelRuns"})[H]||"count")(R.metricType||"count");console.log("Using dataKey for metric",R.metricType,":",z),h(H=>H.map(I=>{if(I.id===N){const V={...I,view:{...I.view,chart:I.view.chart?{...I.view.chart,data:E,dataKey:z,lines:[{dataKey:z,color:I.view.chart.color||"#3b82f6",label:R.title,strokeWidth:2}]}:{type:"line",data:E,dataKey:z,lines:[{dataKey:z,color:"#3b82f6",label:R.title,strokeWidth:2}],yAxisLabel:R.title}}};return console.log("Updated section for",N,":",V),console.log("Chart config set:",V.view.chart),V}return I}))}catch(k){console.error("Error loading metric data:",k)}finally{g(k=>({...k,[N]:!1}))}}},C=N=>{var R,k;if((k=(R=u==null?void 0:u.draft)==null?void 0:R.onChange)==null||k.call(R,N),a==null||a(N),t&&y.current){const U={...t,environment:N};y.current.updateConfig(U),A()}},$=N=>{var R,k;if(console.log("🗓️ Time range change requested:",N),typeof N=="string"&&((k=(R=u==null?void 0:u.timeRange)==null?void 0:R.onChange)==null||k.call(R,N)),i==null||i(N),t&&y.current){let U=null;if(typeof N=="object"&&N.from&&N.to)U={fromTimestamp:N.from.toISOString(),toTimestamp:N.to.toISOString()},console.log("📅 Converting DateRange to API format:",U);else if(typeof N=="string"){const Z={"24h":1,"7d":7,"30d":30,"90d":90}[N];Z&&(U=Yt.getDateRange(Z),console.log(`📅 Converting preset "${N}" (${Z} days) to API format:`,U))}if(U){const q={...t,defaultTimeRange:U};console.log("🔄 Updating API configuration with new date range:",q.defaultTimeRange),y.current.updateConfig(q),console.log("🚀 Reloading dashboard data with new date range..."),A()}else console.warn("⚠️ Unable to convert time range value to API format:",N)}},P=(N="csv")=>{var R,k;(k=(R=u==null?void 0:u.export)==null?void 0:R.onExport)==null||k.call(R,N),n==null||n()},_=Object.values(m).some(N=>N);return p.jsxs("div",{className:le("w-full h-full flex flex-col overflow-hidden",r),children:[p.jsxs("div",{className:"flex flex-col gap-2 w-full p-[24px] pb-[12px]",children:[p.jsx("h1",{className:"text-lg font-bold text-gray-900 w-full",children:o}),p.jsxs("div",{className:"flex items-center gap-2 w-full",children:[s&&p.jsx("p",{className:"text-gray-500 text-xs w-full",children:s}),p.jsxs("div",{className:"flex items-center gap-2 justify-end flex-shrink-0",children:[(f||_)&&p.jsxs("div",{className:"flex items-center gap-2 text-sm medium text-gray-500",children:[p.jsx(kb,{className:"h-[16px] w-[16px] animate-spin"}),"Loading..."]}),u&&p.jsxs(p.Fragment,{children:[u.draft&&p.jsx(Ns,{options:b.length>0?b.map(N=>({label:N.envName.charAt(0).toUpperCase()+N.envName.slice(1),value:N.envName})):u.draft.options,value:u.draft.defaultValue,placeholder:x?"Loading environments...":u.draft.label,onChange:C,className:"min-w-[200px]",disabled:f||_||x}),u.timeRange&&(u.timeRange.useDatePicker?(console.log("🗓️ Dashboard: Rendering DateRangePicker with defaultValue:",u.timeRange.defaultValue),p.jsx(X0,{defaultValue:u.timeRange.defaultValue,onDateRangeChange:N=>{console.log("🗓️ Dashboard: DateRangePicker callback received:",N),N&&$(N)}})):p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx(Af,{className:"h-4 w-4 text-gray-500"}),p.jsx(Ns,{options:u.timeRange.options||[],value:u.timeRange.defaultValue,placeholder:u.timeRange.label,onChange:$,className:"min-w-[200px]",disabled:f||_})]})),((F=u.export)==null?void 0:F.enabled)&&p.jsxs(df,{variant:"outline",onClick:()=>P(),className:"gap-2",disabled:f||_,children:[p.jsx(jb,{className:"h-4 w-4"}),"Export"]})]})]})]})]}),p.jsx("div",{className:le("grid gap-6 p-[24px] pt-[8px] overflow-y-auto",c.responsive&&"grid-cols-1 lg:grid-cols-12"),style:{gridTemplateColumns:c.responsive?void 0:`repeat(${c.columns}, minmax(0, 1fr))`,gap:c.gap?`${c.gap}px`:void 0},children:v.map(N=>{var R,k,U,q;return p.jsx(U0,{section:N,isLoading:f,isChartLoading:m[N.id]||!1,onMetricClick:Z=>j(N.id,Z),className:le(c.responsive&&((R=N.layout)==null?void 0:R.span)===12&&"lg:col-span-12",c.responsive&&((k=N.layout)==null?void 0:k.span)===6&&"lg:col-span-6",c.responsive&&((U=N.layout)==null?void 0:U.span)===4&&"lg:col-span-4",c.responsive&&((q=N.layout)==null?void 0:q.span)===3&&"lg:col-span-3")},N.id)})})]})};class Z0{static buildSessionTree(t,r){var i;const n=this.groupEventsByRun(t),a=[];for(const[o,s]of n.entries()){const l=this.buildRunTree(o,s);a.push(l)}return a.sort((o,s)=>new Date(o.startTime).getTime()-new Date(s.startTime).getTime()),{sessionId:r||((i=t[0])==null?void 0:i.sessionId)||"unknown",runs:a}}static groupEventsByRun(t){const r=new Map;return t.forEach(n=>{const a=n.runId;r.has(a)||r.set(a,[]),r.get(a).push(n)}),r}static buildRunTree(t,r){var v;const n=new Map;r.forEach(h=>{const b=`${h.data.id}|${h.data.name}|${h.data.toolName}`;n.has(b)||n.set(b,{});const w=n.get(b);h.type==="node_started"?w.started=h:h.type==="node_completed"&&(w.completed=h)});const a=[];for(const[,h]of n.entries()){const b=h.started,w=h.completed;if(!b)continue;const x=this.createTreeNodeFromEvents(b,w,t);a.push(x)}const i=this.buildNodeHierarchy(a),o=r.filter(h=>h.runId===t),s=Math.min(...o.map(h=>new Date(h.data.timestamp).getTime())),l=o.filter(h=>h.type==="node_completed"),u=l.length>0?Math.max(...l.map(h=>new Date(h.data.timestamp).getTime())):void 0,c=this.calculateRunStatus(o),f=u&&s?u-s:void 0,d=this.calculateRunTokens(o),m=this.extractUserInput(o),g=this.extractFinalOutput(o);return{runId:t,startTime:new Date(s).toISOString(),endTime:u?new Date(u).toISOString():void 0,status:c,rootNodes:i,duration:f,totalTokens:d>0?d:void 0,sessionId:((v=o[0])==null?void 0:v.sessionId)||"unknown",userInput:m,finalOutput:g}}static createTreeNodeFromEvents(t,r,n){const a=t.data.timestamp,i=r==null?void 0:r.data.timestamp,o=i&&a?new Date(i).getTime()-new Date(a).getTime():void 0,s=r||t,l=s.data.type==="llm"||s.data.type==="tool"||s.data.type==="GuardrailsInputScan"||s.data.type==="GuardrailsOutputScan"||s.data.type==="Agent"||s.data.type==="External Orchestrator"||s.data.type==="ProxyWorker",u=l?t.data.input:void 0;let c,f;r&&(l&&(c=r.data.output),f=r.data.error);const d=this.extractLLMUsage(c,r==null?void 0:r.data.metadata),{toolInvocations:m,isResponse:g}=this.extractToolInvocations(c);console.log("toolInvocations",m),console.log("isResponse",g);const v=s.data.type==="llm"?this.extractProvider(s.data.name||s.data.toolName):void 0;return{id:s.data.id,parentId:s.data.parentId,runId:n||"unknown",name:s.data.name,type:s.data.type,status:(r==null?void 0:r.data.status)||t.data.status,startTime:a,endTime:i,duration:o,icon:s.data.icon,input:u,output:c,error:f,children:[],level:0,isExpanded:!1,llmUsage:d,toolInvocations:m,isResponse:g,metadata:{...s.data.metadata,provider:v}}}static buildNodeHierarchy(t){const r=new Map;t.forEach(a=>r.set(a.id,a));const n=[];return t.forEach(a=>{if(a.parentId&&r.has(a.parentId)){const i=r.get(a.parentId);i.children.push(a),a.level=i.level+1}else n.push(a),a.level=0}),n.sort((a,i)=>new Date(a.startTime).getTime()-new Date(i.startTime).getTime()),n.forEach(a=>this.sortChildren(a)),n}static extractLLMUsage(t,r){var n,a,i;if(r!=null&&r.usage_metadata)return r.usage_metadata;if(!(!t||typeof t!="object")){if(t.usage_metadata)return t.usage_metadata;if((n=t.metadata)!=null&&n.usage_metadata)return t.metadata.usage_metadata;if(Array.isArray(t)){const o=t[0];if((a=o==null?void 0:o.additional_kwargs)!=null&&a.llmUsageMetadata)return o.additional_kwargs.llmUsageMetadata}else if((i=t.additional_kwargs)!=null&&i.llmUsageMetadata)return t.additional_kwargs.llmUsageMetadata}}static extractToolInvocations(t){if(!t||typeof t!="object")return{};if(t.name&&t.tool_call_id){const r=t.name==="route_to_user"||t.toolName==="route_to_user";return{toolInvocations:[t],isResponse:r}}if(Array.isArray(t)){const r=t.filter(n=>n&&typeof n=="object"&&(n.name==="route_to_user"||n.toolName==="route_to_user")&&n.tool_call_id);if(r.length>0){const n=r.some(a=>a.name==="route_to_user"||a.toolName==="route_to_user");return{toolInvocations:r,isResponse:n}}}if(t.tool_calls&&Array.isArray(t.tool_calls)){const r=t.tool_calls.filter(n=>n&&typeof n=="object"&&(n.name==="route_to_user"||n.toolName==="route_to_user")&&n.tool_call_id);if(r.length>0){const n=r.some(a=>a.name==="route_to_user"||a.toolName==="route_to_user");return{toolInvocations:r,isResponse:n}}}return{}}static extractProvider(t){if(!t)return;const r=t.toLowerCase();if(r.includes("gemini"))return"google";if(r.includes("gpt")||r.includes("openai"))return"openai";if(r.includes("claude")||r.includes("anthropic"))return"anthropic";if(r.includes("azure"))return"azure";if(r.includes("cohere"))return"cohere";const n=t.split("-");if(n.length>0){const a=n[0].toLowerCase();if(["gemini","gpt","claude","cohere"].includes(a))return a==="gemini"?"google":a==="gpt"?"openai":a==="claude"?"anthropic":a}return"custom"}static sortChildren(t){t&&(t.children.sort((r,n)=>new Date(r.startTime).getTime()-new Date(n.startTime).getTime()),t.children.forEach(r=>this.sortChildren(r)))}static calculateRunStatus(t){const r=t.some(a=>a.data.status==="running"),n=t.some(a=>a.data.status==="failed"||a.data.status==="errored");return r?"running":n?"failed":"completed"}static extractUserInput(t){const r=t.filter(n=>n.type==="node_started"&&n.data.type==="llm").sort((n,a)=>new Date(n.data.timestamp).getTime()-new Date(a.data.timestamp).getTime());if(r.length>0){const n=r[0];if(n.data.input){if(typeof n.data.input=="string")return n.data.input;if(typeof n.data.input=="object")return JSON.stringify(n.data.input)}}}static containsRouteToUserTool(t){return!t||typeof t!="object"?!1:Array.isArray(t)?t.some(r=>r&&typeof r=="object"&&(r.name==="route_to_user"||r.toolName==="route_to_user")):t.name==="route_to_user"||t.toolName==="route_to_user"}static extractMessageFromLLMOutput(t){var r,n,a;if(!(!t||typeof t!="object")){if(console.log("Extracting message from LLM output:",JSON.stringify(t,null,2)),Array.isArray(t)){const i=t.find(o=>o&&typeof o=="object"&&(o.name==="route_to_user"||o.toolName==="route_to_user"));if(i){if((r=i.args)!=null&&r.message)return console.log("Found message in LLM array format: routeToUserTool.args.message"),i.args.message;if(i.message)return console.log("Found message in LLM array format: routeToUserTool.message"),i.message;if((n=i.output)!=null&&n.message)return console.log("Found message in LLM array format: routeToUserTool.output.message"),i.output.message}}else if(t.name==="route_to_user"||t.toolName==="route_to_user"){if((a=t.args)!=null&&a.message)return console.log("Found message in LLM single format: output.args.message"),t.args.message;if(t.message)return console.log("Found message in LLM single format: output.message"),t.message}console.log("No message found in LLM output")}}static extractFinalOutput(t){var o,s,l,u,c,f,d,m,g,v;const r=t.filter(h=>h.type==="node_completed"&&h.data.error&&(h.data.status==="errored"||h.data.status==="failed"));if(r.length>0){const h=r.sort((b,w)=>new Date(w.timestamp).getTime()-new Date(b.timestamp).getTime());return typeof h[0].data.error=="string"?h[0].data.error:JSON.stringify(h[0].data.error)}const n=t.filter(h=>h.type==="node_completed"&&h.data.type==="tool"&&(h.data.name==="route_to_user"||h.data.toolName==="route_to_user")),a=t.filter(h=>h.type==="node_completed"&&h.data.type==="llm"&&h.data.output&&this.containsRouteToUserTool(h.data.output));n.length>0&&console.log("Found route_to_user tool events:",n.length),a.length>0&&console.log("Found LLM events with route_to_user:",a.length);const i=[...n,...a];if(i.sort((h,b)=>new Date(h.timestamp).getTime()-new Date(b.timestamp).getTime()),i.length>0){const h=i[i.length-1];if(h.data.type==="llm")return this.extractMessageFromLLMOutput(h.data.output)}if(n.length>0){const b=n[n.length-1].data.output;if(console.log("Route to user output structure:",JSON.stringify(b,null,2)),b)if(Array.isArray(b)){const w=b.find(x=>x&&typeof x=="object"&&(x.name==="route_to_user"||x.toolName==="route_to_user"));if(w){if((o=w.args)!=null&&o.message)return console.log("Found message in array format: routeToUserTool.args.message"),w.args.message;if(w.message)return console.log("Found message in array format: routeToUserTool.message"),w.message;if((s=w.output)!=null&&s.message)return console.log("Found message in array format: routeToUserTool.output.message"),w.output.message}}else{if((l=b.args)!=null&&l.message)return console.log("Found message at: output.args.message"),b.args.message;if(b.message)return console.log("Found message at: output.message"),b.message;if((u=b.output)!=null&&u.message)return console.log("Found message at: output.output.message"),b.output.message;if((c=b.input)!=null&&c.message)return console.log("Found message at: output.input.message"),b.input.message;if((d=(f=b.input)==null?void 0:f.args)!=null&&d.message)return console.log("Found message at: output.input.args.message"),b.input.args.message;if((m=b.data)!=null&&m.message)return console.log("Found message at: output.data.message"),b.data.message;if((g=b.result)!=null&&g.message)return console.log("Found message at: output.result.message"),b.result.message;if(typeof b=="string")try{const w=JSON.parse(b);if((v=w.args)!=null&&v.message)return console.log("Found message in parsed string: parsed.args.message"),w.args.message;if(w.message)return console.log("Found message in parsed string: parsed.message"),w.message}catch{if(b.length>10&&!b.includes("{")&&!b.includes("["))return console.log("Using output string directly as message"),b}try{return JSON.stringify(b)}catch{return b}}console.log("No message found in route_to_user output paths")}}static calculateRunTokens(t){let r=0;return t.forEach(n=>{const a=this.extractLLMUsage(n.data.output,n.data.metadata);a!=null&&a.total_tokens&&(r+=a.total_tokens)}),r}static updateTree(t,r,n){return this.buildSessionTree(n,t.sessionId)}static mergeEvents(t,r){return[...t,...r].sort((a,i)=>new Date(a.timestamp).getTime()-new Date(i.timestamp).getTime())}}const J0=({value:e,onChange:t,language:r="text",readOnly:n=!1,placeholder:a="",className:i,autoFocus:o=!1})=>{const[s,l]=S.useState(e),[u,c]=S.useState(!1),[f,d]=S.useState(!1),m=S.useRef(null);S.useEffect(()=>{l(e)},[e]);function g(){navigator.clipboard.writeText(s).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})}function v(x){const T=x.target.value;l(T),t==null||t(T)}const h=()=>p.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b bg-gray-100",children:[p.jsx("span",{className:"text-xs font-mono uppercase text-gray-500",children:r}),p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("button",{type:"button",className:"p-1 rounded hover:bg-gray-200",onClick:g,title:f?"Copied!":"Copy",children:p.jsx(Pf,{size:16,className:f?"text-green-500":""})}),p.jsx("button",{type:"button",className:"p-1 rounded hover:bg-gray-200",onClick:()=>c(!u),title:u?"Minimize":"Maximize",children:u?p.jsx(Eb,{size:16}):p.jsx($f,{size:16})})]})]}),b=()=>p.jsx("textarea",{ref:m,spellCheck:!1,readOnly:n,placeholder:a,autoFocus:o,className:"flex-1 w-full h-full resize-none p-3 font-mono text-sm outline-none bg-transparent",value:s,onChange:v}),w=p.jsxs("div",{className:le("flex flex-col h-full w-full border rounded-md bg-background",i),style:{minHeight:"200px"},children:[p.jsx(h,{}),p.jsx(b,{})]});return u?p.jsx(mf,{children:p.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",children:p.jsx("div",{className:"w-full h-full max-h-[calc(100vh-2rem)]",children:w})})}):w};J0.displayName="CodeEditor";const Q0=S.forwardRef(({className:e,...t},r)=>p.jsx("span",{ref:r,className:le("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));Q0.displayName="Avatar";const eb=S.forwardRef(({className:e,...t},r)=>p.jsx("img",{ref:r,className:le("aspect-square h-full w-full",e),...t}));eb.displayName="AvatarImage";const tb=S.forwardRef(({className:e,...t},r)=>p.jsx("span",{ref:r,className:le("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));tb.displayName="AvatarFallback";const rb=S.forwardRef(({className:e,children:t,...r},n)=>p.jsx("div",{ref:n,className:le("rounded-lg border bg-card text-card-foreground shadow-sm",e),...r,children:t}));rb.displayName="Card";const lU=S.forwardRef(({className:e,children:t,...r},n)=>p.jsx("div",{ref:n,className:le("flex flex-col space-y-1.5 p-6",e),...r,children:t}));lU.displayName="CardHeader";const uU=S.forwardRef(({className:e,children:t,...r},n)=>p.jsx("h3",{ref:n,className:le("text-2xl font-semibold leading-none tracking-tight",e),...r,children:t}));uU.displayName="CardTitle";const cU=S.forwardRef(({className:e,children:t,...r},n)=>p.jsx("div",{ref:n,className:le("p-6 pt-0",e),...r,children:t}));cU.displayName="CardContent";const Ti=({text:e,className:t="",iconClassName:r="",title:n="Copy to clipboard",onCopySuccess:a,onCopyError:i,tooltipText:o="Copied!",tooltipPosition:s="bottom",size:l="md"})=>{const[u,c]=S.useState(!1),f=()=>{switch(l){case"sm":return{button:"p-1",icon:"w-3 h-3",tooltip:"text-xs py-1 px-2"};case"lg":return{button:"p-2",icon:"w-5 h-5",tooltip:"text-sm py-2 px-3"};default:return{button:"p-1.5",icon:"w-4 h-4",tooltip:"text-xs py-1 px-2"}}},d=()=>{const h="absolute bg-gray-800 text-white rounded whitespace-nowrap z-50";switch(s){case"bottom":return`${h} top-full mt-1 left-1/2 -translate-x-1/2`;case"left":return`${h} right-full mr-1 top-1/2 -translate-y-1/2`;case"right":return`${h} left-full ml-1 top-1/2 -translate-y-1/2`;default:return`${h} bottom-full mb-1 left-1/2 -translate-x-1/2`}},m=f(),g=S.useCallback(()=>{c(!0),setTimeout(()=>c(!1),1e3)},[]),v=S.useCallback(async()=>{try{if(navigator.clipboard&&navigator.clipboard.writeText){await navigator.clipboard.writeText(e),g(),a==null||a();return}const h=document.createElement("textarea");h.value=e,h.style.position="fixed",h.style.left="-999999px",h.style.top="-999999px",document.body.appendChild(h),h.focus(),h.select();try{document.execCommand("copy"),g(),a==null||a()}catch(b){const w=b instanceof Error?b:new Error("Copy failed");console.warn("Copy to clipboard failed:",w),i==null||i(w)}finally{document.body.removeChild(h)}}catch(h){const b=h instanceof Error?h:new Error("Copy failed");console.warn("Copy to clipboard failed:",b),i==null||i(b)}},[e,g,a,i]);return p.jsxs("div",{className:"relative inline-flex",children:[p.jsx("button",{onClick:v,className:`${m.button} hover:bg-gray-100 rounded transition-colors ${t}`,title:n,children:p.jsx(Pf,{className:`${m.icon} text-gray-400 ${r}`})}),p.jsx("div",{className:`${d()} ${m.tooltip} transition-opacity duration-150 ${u?"opacity-100 animate-fade-in":"opacity-0 pointer-events-none"}`,style:{visibility:u?"visible":"hidden"},children:o})]})},fU=({isOpen:e,onClose:t,title:r,data:n,initialViewMode:a="plain",modalHeight:i="50vh"})=>{const[o,s]=S.useState(a),l=S.useMemo(()=>{if(n==null)return!1;if(typeof n=="string")try{return JSON.parse(n),!0}catch{return!1}return typeof n=="object"},[n]),u=c=>{c.target===c.currentTarget&&t()};return e?p.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4",onClick:u,children:p.jsxs("div",{className:"bg-white rounded-lg shadow-xl max-w-6xl w-full flex flex-col",style:{height:i},children:[p.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200",children:[p.jsxs("div",{className:"flex items-center gap-4",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx(Vs,{className:"w-5 h-5 text-gray-400"}),p.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:r})]}),l&&p.jsxs("div",{className:"flex items-center gap-1 ml-4 pl-4 border-l border-gray-200",children:[p.jsx("button",{onClick:()=>s("plain"),className:`p-1.5 hover:bg-gray-200 rounded transition-colors ${o==="plain"?"bg-gray-200":""}`,title:"Plain JSON view",children:p.jsx(Of,{className:"w-4 h-4 text-gray-400"})}),p.jsx("button",{onClick:()=>s("interactive"),className:`p-1.5 hover:bg-gray-200 rounded transition-colors ${o==="interactive"?"bg-gray-200":""}`,title:"Interactive JSON view (fold/unfold)",children:p.jsx(Ef,{className:"w-4 h-4 text-gray-400"})})]})]}),p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx(Ti,{text:typeof n=="string"?n:JSON.stringify(n,null,2),title:"Copy content",className:"p-2 rounded-lg",iconClassName:"w-4 h-4 text-gray-500"}),p.jsx("button",{onClick:t,className:"p-2 hover:bg-gray-100 rounded-lg transition-colors",title:"Close",children:p.jsx(Nf,{className:"w-4 h-4 text-gray-500"})})]})]}),p.jsx("div",{className:"flex-1 overflow-hidden",children:p.jsx(xt,{data:n,showHeader:!1,className:"h-full border-0",defaultExpanded:!0,viewMode:o,onViewModeChange:s})})]})}):null},dU=({data:e,level:t=0,expandedKeys:r=new Set,onToggleKey:n,keyPath:a=""})=>{const i=t*16,o=(s,l,u)=>{const c=u?`${u}.${l}`:l||"";if(s===null)return p.jsx("span",{className:"text-gray-400 italic",children:"null"});if(s===void 0)return p.jsx("span",{className:"text-gray-400 italic",children:"undefined"});if(typeof s=="boolean")return p.jsx("span",{className:"text-purple-600 font-medium",children:String(s)});if(typeof s=="number")return p.jsx("span",{className:"text-blue-600 font-medium",children:s});if(typeof s=="string"){const f=s.length>100,d=f&&!r.has(`${c}._string`)?`${s.substring(0,100)}...`:s;return p.jsxs("div",{className:"inline",children:[p.jsxs("span",{className:"text-green-600",children:['"',d,'"']}),f&&p.jsx("button",{onClick:()=>n==null?void 0:n(`${c}._string`),className:"ml-2 text-xs text-blue-500 hover:text-blue-700 underline",children:r.has(`${c}._string`)?"Show less":"Show more"})]})}if(Array.isArray(s)){const f=r.has(c);return s.length===0?p.jsx("span",{className:"text-gray-500",children:"[]"}):p.jsxs("div",{children:[p.jsxs("div",{className:"flex items-center",children:[p.jsxs("button",{onClick:()=>n==null?void 0:n(c),className:"flex items-center gap-1 hover:bg-gray-100 p-1 rounded transition-colors",children:[f?p.jsx(fr,{className:"w-3 h-3 text-gray-400"}):p.jsx(ki,{className:"w-3 h-3 text-gray-400"}),p.jsxs("span",{className:"text-gray-600 text-xs",children:["Array[",s.length,"]"]})]}),!f&&p.jsx("span",{className:"text-gray-400 ml-2",children:"[...]"})]}),f&&p.jsx("div",{className:"ml-4 mt-1",children:s.map((m,g)=>p.jsxs("div",{className:"flex items-start gap-2 py-1",style:{marginLeft:`${i}px`},children:[p.jsxs("span",{className:"text-gray-400 text-xs mt-0.5 min-w-[20px]",children:[g,":"]}),p.jsx("div",{className:"flex-1",children:o(m,String(g),`${c}[${g}]`)})]},g))})]})}if(typeof s=="object"){const f=Object.keys(s),d=r.has(c);return f.length===0?p.jsx("span",{className:"text-gray-500",children:"{}"}):p.jsxs("div",{children:[p.jsxs("div",{className:"flex items-center",children:[p.jsxs("button",{onClick:()=>n==null?void 0:n(c),className:"flex items-center gap-1 hover:bg-gray-100 p-1 rounded transition-colors",children:[d?p.jsx(fr,{className:"w-3 h-3 text-gray-400"}):p.jsx(ki,{className:"w-3 h-3 text-gray-400"}),p.jsxs("span",{className:"text-gray-600 text-xs",children:["Object ","{",f.length," ",f.length===1?"key":"keys","}"]})]}),!d&&p.jsx("span",{className:"text-gray-400 ml-2",children:"{ ... }"})]}),d&&p.jsx("div",{className:"ml-4 mt-1",children:f.map(g=>p.jsxs("div",{className:"flex items-start gap-2 py-1",style:{marginLeft:`${i}px`},children:[p.jsxs("span",{className:"text-blue-700 text-xs mt-0.5 font-medium min-w-fit",children:['"',g,'":']}),p.jsx("div",{className:"flex-1",children:o(s[g],g,c)})]},g))})]})}return p.jsx("span",{className:"text-gray-600",children:String(s)})};return p.jsx("div",{className:"text-xs",children:o(e,"",a)})},nb=e=>{const t=[];if(t.push(""),e==null)return t;let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch{return t}return typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).forEach(n=>{t.push(n)}),Array.isArray(r)&&r.forEach((n,a)=>{t.push(`[${a}]`)}),t},xt=({data:e,padding:t="p-3",title:r="Data",className:n="",maxHeight:a="300px",showHeader:i=!0,defaultExpanded:o=!1,defaultViewMode:s="plain",viewMode:l,onViewModeChange:u,modalHeight:c="50vh"})=>{const[f,d]=S.useState(!1),[m,g]=S.useState(s),v=S.useMemo(()=>o?new Set([""]):new Set(nb(e)),[e,o]),[h,b]=S.useState(v);S.useEffect(()=>{o||b(new Set(nb(e)))},[e,o]);const w=l!==void 0,x=w?l:m,T=$=>{w?u==null||u($):g($)},{isValidJson:y,displayContent:O}=S.useMemo(()=>{if(e==null)return{isValidJson:!1,displayContent:e===null?"null":"undefined"};if(typeof e=="string")try{return{isValidJson:!0,displayContent:JSON.parse(e)}}catch{return{isValidJson:!1,displayContent:e}}return typeof e=="object"?{isValidJson:!0,displayContent:e}:{isValidJson:!1,displayContent:String(e)}},[e]),A=S.useCallback($=>{b(P=>{const _=new Set(P);return _.has($)?_.delete($):_.add($),_})},[]),j=S.useCallback(()=>{d(!0)},[]),C=S.useCallback(()=>{d(!1)},[]);return p.jsxs(p.Fragment,{children:[p.jsxs("div",{className:`bg-white border border-gray-200 rounded-md overflow-hidden ${n}`,children:[i&&p.jsxs("div",{className:"bg-gray-50 border-b border-gray-200 px-4 py-2 flex items-center justify-between",children:[y&&p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("button",{onClick:()=>T("plain"),className:`p-1 hover:bg-gray-200 rounded transition-colors ${x==="plain"?"bg-gray-200":""}`,title:"Plain JSON view",children:p.jsx(Of,{className:"w-4 h-4 text-gray-400"})}),p.jsx("button",{onClick:()=>T("interactive"),className:`p-1 hover:bg-gray-200 rounded transition-colors ${x==="interactive"?"bg-gray-200":""}`,title:"Interactive JSON view (fold/unfold)",children:p.jsx(Ef,{className:"w-4 h-4 text-gray-400"})})]}),p.jsx("div",{className:"flex-1"}),p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("button",{onClick:j,className:"p-1 hover:bg-gray-200 rounded transition-colors",title:"Expand to full screen",children:p.jsx($f,{className:"w-4 h-4 text-gray-400"})}),p.jsx(Ti,{text:y?JSON.stringify(O,null,2):O,title:"Copy content",className:"p-1",iconClassName:"w-4 h-4 text-gray-400"})]})]}),p.jsxs("div",{className:`${t||"p-3"} overflow-auto bg-white`,style:{maxHeight:a},children:[y?x==="interactive"?p.jsx(dU,{data:O,expandedKeys:h,onToggleKey:A,keyPath:""}):p.jsx("div",{className:"text-xs text-gray-700 whitespace-pre",children:JSON.stringify(O,null,2)}):p.jsx("div",{className:"text-xs text-gray-700 whitespace-pre-wrap",children:O}),!O&&O!==0&&O!==!1&&p.jsx("div",{className:"text-center text-gray-400 text-sm py-8",children:"No data available"})]})]}),p.jsx(fU,{isOpen:f,onClose:C,title:r,data:O,initialViewMode:x,modalHeight:c})]})};class ab{constructor(t){kt(this,"config");this.config=t}async getObservationById(t){var r,n;console.log("🚀 OBSERVATION API CALL:",{observationId:t.observationId,traceId:t.traceId,projectId:t.projectId,tracingUrl:this.config.tracingUrl});try{const a={json:{observationId:t.observationId,traceId:t.traceId,projectId:t.projectId}},i=encodeURIComponent(JSON.stringify(a)),o=`${this.config.tracingUrl}/tracing/api/trpc/observations.byId?input=${i}`;console.log("📤 Making observation GET request to:",o),console.log("📤 Headers:",this.config.headers);const s=await fetch(o,{method:"GET",headers:this.config.headers});if(console.log("📥 Observation response status:",s.status),console.log("📥 Observation response ok:",s.ok),!s.ok){const c=await s.text();throw console.error("❌ Observation API Error:",c),new Error(`HTTP error! status: ${s.status}, response: ${c}`)}const l=await s.json();console.log("✅ Observation API Response:",l);const u=((n=(r=l==null?void 0:l.result)==null?void 0:r.data)==null?void 0:n.json)||null;return console.log("📊 Extracted observation data:",u),u}catch(a){return console.error("❌ Error fetching observation data:",a),null}}async getTraceById(t){var r,n,a;console.log("🚀 TRACE API CALL:",{traceId:t.traceId,projectId:t.projectId,tracingUrl:this.config.tracingUrl});try{const i={json:{traceId:t.traceId,projectId:t.projectId}},o=encodeURIComponent(JSON.stringify(i)),s=`${this.config.tracingUrl}/tracing/api/trpc/traces.byIdWithObservationsAndScores?input=${o}&pollingApi=true&skipGlobalToast=true`;console.log("📤 Making trace GET request to:",s),console.log("📤 Headers:",this.config.headers);const l=await fetch(s,{method:"GET",headers:this.config.headers});if(console.log("📥 Trace response status:",l.status),console.log("📥 Trace response ok:",l.ok),!l.ok){const d=await l.text();throw console.error("❌ Trace API Error:",d),new Error(`HTTP error! status: ${l.status}, response: ${d}`)}const u=await l.json();console.log("✅ Trace API Response:",u);const f=[...((a=(n=(r=u==null?void 0:u.result)==null?void 0:r.data)==null?void 0:n.json)==null?void 0:a.observations)||[]].sort((d,m)=>new Date(d.startTime).getTime()-new Date(m.startTime).getTime());return console.log("📊 Sorted observations:",f.length,"total"),f}catch(i){return console.error("❌ Error fetching trace data:",i),null}}matchNodeToObservationById(t,r){console.log("🔍 Matching node to observation by ID:",{nodeId:t,totalObservations:r.length});const n=r.find(a=>{let i=a.metadata;if(typeof i=="string")try{i=JSON.parse(i)}catch(s){return console.warn("Failed to parse metadata string:",s),!1}if(!(i!=null&&i.pipeTraceId)||(i==null?void 0:i._pipeSeq)===void 0)return!1;const o=`${i.pipeTraceId}.${i._pipeSeq}`;return console.log("Comparing:",{nodeId:t,observationNodeId:o,match:t===o}),t===o});if(!n){const a=t.split("_");if(a.length===2){const[,i]=a,o=parseInt(i,10);if(!isNaN(o)){const s=r.find(l=>{let u=l.metadata;if(typeof u=="string")try{u=JSON.parse(u)}catch(c){return console.warn("Failed to parse metadata string in fallback:",c),!1}return(u==null?void 0:u._pipeSeq)===o});if(s){let l=s.metadata;if(typeof l=="string")try{l=JSON.parse(l)}catch{}return console.log("✅ Matched observation by sequence:",{id:s.id,name:s.name,type:s.type,_pipeSeq:l==null?void 0:l._pipeSeq}),s}}}}if(n){let a=n.metadata;if(typeof a=="string")try{a=JSON.parse(a)}catch{}console.log("✅ Matched observation:",{id:n.id,name:n.name,type:n.type,pipeTraceId:a==null?void 0:a.pipeTraceId,_pipeSeq:a==null?void 0:a._pipeSeq})}else console.log("✅ Matched observation: No match found");return n||null}sleep(t){return new Promise(r=>setTimeout(r,t))}async getObservationForNode(t,r,n,a=5,i=2e3){console.log("🔄 Getting observation for node by ID with retry logic:",{nodeId:t,traceId:r,projectId:n,maxRetries:a,retryDelay:i});let o=null;for(let s=1;s<=a;s++)try{console.log(`📊 Attempt ${s}/${a} for node ${t}`);const l=await this.getTraceById({traceId:r,projectId:n});if(!l||l.length===0){if(console.log(`❌ Attempt ${s}: No observations found for trace`),o=new Error("No observations found for trace"),s<a){console.log(`⏳ Waiting ${i}ms before retry...`),await this.sleep(i);continue}return null}const u=this.matchNodeToObservationById(t,l);if(!u){if(console.log(`❌ Attempt ${s}: No matching observation found for node ID: ${t}`),o=new Error(`No matching observation found for node ID: ${t}`),s<a){console.log(`⏳ Waiting ${i}ms before retry...`),await this.sleep(i);continue}return null}const c=await this.getObservationById({observationId:u.id,traceId:r,projectId:n});if(c)return console.log(`✅ Success on attempt ${s}: Found observation data for node ${t}`),c;if(o=new Error("No detailed data returned"),s<a){console.log(`⏳ No data returned, waiting ${i}ms before retry...`),await this.sleep(i);continue}}catch(l){if(o=l,console.error(`❌ Attempt ${s} failed:`,l),s<a){console.log(`⏳ Waiting ${i}ms before retry...`),await this.sleep(i);continue}}return console.error("❌ All retries exhausted. Last error:",o),null}updateConfig(t){this.config=t}getConfig(){return this.config}}function ib({node:e,onToggle:t,isExpanded:r=!1,onNodeClick:n,selectedNodeIds:a,showDetailView:i=!0,apiConfig:o,projectId:s,nodeIndex:l=0}){const u=S.useMemo(()=>{var L;return e.type==="GuardrailsInputScan"||e.type==="GuardrailsOutputScan"||((L=e.name)==null?void 0:L.toLowerCase().includes("guardrail"))},[e.type,e.name]),c=S.useMemo(()=>u?["summary","response"]:e.type==="ProxyWorker"?["request","response"]:e.type==="llm"?["summary","request","response"]:e.type==="tool"?["request","response","logs"]:[],[e.type,u]),[f,d]=S.useState(c[0]),m=a?a.has(e.id):!1,g=e.children&&e.children.length>0,[v,h]=S.useState(null),[b,w]=S.useState(!1),[x,T]=S.useState(null),[y,O]=S.useState(!1),[A,j]=S.useState(!1),C=["llm"],$=5,P=2e3;console.log("🔧 DebugCard - Props received:",{nodeId:e.id,nodeName:e.name,nodeType:e.type,nodeIndex:l,hasApiConfig:!!o,apiConfigDetails:o?{tracingUrl:o.tracingUrl,projectId:o.projectId,hasHeaders:!!o.headers}:null,projectIdProp:s,propsMatch:(o==null?void 0:o.projectId)===s});const _=S.useMemo(()=>(console.log("🔧 DebugCard - Creating ApiService:",{hasApiConfig:!!o,willCreateService:!!o}),o?new ab(o):null),[o]),F=S.useMemo(()=>C.includes(e.type),[e.type]),N=S.useCallback(async()=>{if(!F){console.log("🔍 DebugCard - Node type not API-enabled:",e.type);return}if(!_||!s||y){console.log("🔍 DebugCard - API call skipped:",{hasApiService:!!_,hasProjectId:!!s,hasLoadedApi:y,isApiEnabledNode:F,nodeType:e.type,reason:_?s?"Already loaded":"No project ID":"No API service"});return}w(!0),T(null),j(!1);try{const L=await _.getObservationForNode(e.id,e.runId,s,$,P);if(L){const W={...L};try{typeof L.input=="string"?W.input=JSON.parse(L.input):L.input&&typeof L.input=="object"&&(W.input=JSON.parse(JSON.stringify(L.input,null,2)))}catch{W.input=L.input||{}}try{typeof L.output=="string"?W.output=JSON.parse(L.output):L.output&&typeof L.output=="object"&&(W.output=JSON.parse(JSON.stringify(L.output,null,2)))}catch{W.output=L.output||{}}h(W),O(!0),j(!1)}else console.log("📊 All API retries exhausted, using fallback node data"),T("API data unavailable after retries, showing local data"),j(!0),O(!0)}catch(L){console.error("Error fetching observation data:",L),T("API data unavailable, showing local data"),j(!0),O(!0)}finally{w(!1)}},[_,s,e.id,e.runId,F]);S.useEffect(()=>{c.includes(f)||d(c[0])},[c,f]),S.useEffect(()=>{h(null),w(!1),T(null),O(!1),j(!1)},[e.id]);const R=S.useCallback(L=>{d(L),console.log("🔍 DebugCard - Tab clicked:",{nodeId:e.id,nodeName:e.name,nodeType:e.type,clickedTab:L,isApiEnabledNode:F,hasApiService:!!_,hasProjectId:!!s,hasLoadedApi:y,isLoadingApi:b}),(L==="request"||L==="response")&&F&&_&&s&&!y&&!b&&(console.log("🚀 DebugCard - Triggering API call for API-enabled node:",e.id),N())},[_,s,y,b,N,e.id,F]),k=L=>{L.stopPropagation(),t&&t(e.id)},U=()=>{c.length===0&&g&&t?t(e.id):n&&i&&n(e)},q=()=>{switch(e.status){case"completed":return p.jsx("svg",{className:"flex-shrink-0",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:p.jsx("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M6 0.5C2.96243 0.5 0.5 2.96243 0.5 6C0.5 9.03757 2.96243 11.5 6 11.5C9.03757 11.5 11.5 9.03757 11.5 6C11.5 2.96243 9.03757 0.5 6 0.5ZM8.60355 4.85355C8.79882 4.65829 8.79882 4.34171 8.60355 4.14645C8.40829 3.95118 8.09171 3.95118 7.89645 4.14645L5.25 6.79289L4.10355 5.64645C3.90829 5.45118 3.59171 5.45118 3.39645 5.64645C3.20118 5.84171 3.20118 6.15829 3.39645 6.35355L4.89645 7.85355C5.09171 8.04882 5.40829 8.04882 5.60355 7.85355L8.60355 4.85355Z",fill:"#17B26A"})});case"failed":case"errored":return p.jsx("div",{className:"w-[12px] h-[12px] rounded-full bg-red-500"});case"running":return p.jsx("div",{className:"w-[12px] h-[12px] rounded-full bg-yellow-500 animate-pulse"});default:return p.jsx("div",{className:"w-[12px] h-[12px] rounded-full bg-gray-400"})}},Z=()=>{var W,G;if(u)return p.jsx("div",{className:"flex-shrink-0 relative w-[24px] h-[24px] bg-gray-200 rounded-[8px] flex items-center justify-center",children:p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"17",height:"21",viewBox:"0 0 17 21",fill:"none",className:"w-[16px] h-[16px]",children:p.jsx("path",{d:"M2.86876 3.16135L2.51444 2.22622V2.22622L2.86876 3.16135ZM1.60989 3.76534L0.944868 3.01852L0.944868 3.01852L1.60989 3.76534ZM1.11768 4.483L2.05352 4.83544L1.11768 4.483ZM8.70562 1.33287L8.35129 2.26799V2.26799L8.70562 1.33287ZM8.32871 1.21247L8.18424 2.20198L8.32871 1.21247ZM7.69438 1.33287L8.04871 2.26799H8.04871L7.69438 1.33287ZM8.07129 1.21247L8.21576 2.20198L8.07129 1.21247ZM15.2823 4.483L14.3465 4.83544L15.2823 4.483ZM13.5312 3.16135L13.1769 4.09647L13.5312 3.16135ZM14.7901 3.76534L15.4551 3.01852V3.01852L14.7901 3.76534ZM8.82819 18.9787L9.33601 19.8402L8.82819 18.9787ZM8.38871 19.1854L8.17694 18.2081H8.17694L8.38871 19.1854ZM7.57181 18.9787L8.07962 18.1173L7.57181 18.9787ZM8.01129 19.1854L8.22306 18.2081L8.01129 19.1854ZM7.10461 9.12831L7.45541 10.0648C7.72607 9.96337 7.93963 9.74983 8.04104 9.47917L7.10461 9.12831ZM8.2 6.20474L9.13643 5.85388H7.26357L8.2 6.20474ZM9.29539 9.12831L8.35897 9.47917C8.46038 9.74983 8.67393 9.96337 8.94459 10.0648L9.29539 9.12831ZM12.25 10.2351L12.6008 11.1716L12.6008 9.29868L12.25 10.2351ZM9.29539 11.3419L8.94459 10.4055C8.66955 10.5085 8.4537 10.7273 8.35435 11.0037L9.29539 11.3419ZM8.2 14.3892L7.25895 14.7275H9.14105L8.2 14.3892ZM7.10461 11.3419L8.04565 11.0037C7.9463 10.7273 7.73045 10.5085 7.45541 10.4055L7.10461 11.3419ZM4.15 10.2351L3.7992 9.29868L3.7992 11.1716L4.15 10.2351ZM9.33601 19.8402C10.251 19.3009 11.9823 18.176 13.4966 16.582C15.0004 14.999 16.4 12.8356 16.4 10.2351H14.4C14.4 12.0983 13.3903 13.79 12.0466 15.2045C10.7133 16.608 9.15867 17.6231 8.32038 18.1173L9.33601 19.8402ZM16.4 10.2351V5.88609H14.4V10.2351H16.4ZM13.8856 2.22622L9.05994 0.397748L8.35129 2.26799L13.1769 4.09647L13.8856 2.22622ZM7.34006 0.397749L2.51444 2.22622L3.22309 4.09647L8.04871 2.26799L7.34006 0.397749ZM0 5.88609V10.2351H2V5.88609H0ZM0 10.2351C0 12.8356 1.39958 14.999 2.90343 16.582C4.41773 18.176 6.14904 19.3009 7.06399 19.8402L8.07962 18.1173C7.24133 17.6231 5.68674 16.608 4.35344 15.2045C3.00971 13.79 2 12.0983 2 10.2351H0ZM2.51444 2.22622C1.91725 2.4525 1.36429 2.64503 0.944868 3.01852L2.27492 4.51216C2.352 4.44352 2.47279 4.38077 3.22309 4.09647L2.51444 2.22622ZM2 5.88609C2 5.07787 2.01549 4.93642 2.05352 4.83544L0.181849 4.13057C-0.0154909 4.65457 0 5.24018 0 5.88609H2ZM0.944868 3.01852C0.60414 3.32193 0.342573 3.70379 0.181849 4.13057L2.05352 4.83544C2.10072 4.71011 2.17703 4.59933 2.27492 4.51216L0.944868 3.01852ZM9.05994 0.397748C8.91343 0.342231 8.70233 0.256421 8.47319 0.222965L8.18424 2.20198C8.15508 2.19772 8.14261 2.19201 8.16863 2.20063C8.18278 2.20531 8.2032 2.21249 8.23486 2.22419C8.26671 2.23595 8.30339 2.24984 8.35129 2.26799L9.05994 0.397748ZM8.04871 2.26799C8.09661 2.24984 8.13329 2.23595 8.16514 2.22419C8.1968 2.21249 8.21722 2.20531 8.23137 2.20063C8.25739 2.19201 8.24492 2.19772 8.21576 2.20198L7.92681 0.222965C7.69767 0.256422 7.48657 0.342232 7.34005 0.397749L8.04871 2.26799ZM8.47319 0.222965C8.29201 0.196512 8.10799 0.196512 7.92681 0.222965L8.21576 2.20198C8.20532 2.20351 8.19468 2.20351 8.18424 2.20198L8.47319 0.222965ZM16.4 5.88609C16.4 5.24018 16.4155 4.65457 16.2182 4.13057L14.3465 4.83544C14.3845 4.93642 14.4 5.07787 14.4 5.88609H16.4ZM13.1769 4.09647C13.9272 4.38077 14.048 4.44352 14.1251 4.51216L15.4551 3.01852C15.0357 2.64503 14.4827 2.4525 13.8856 2.22622L13.1769 4.09647ZM16.2182 4.13057C16.0574 3.70379 15.7959 3.32193 15.4551 3.01852L14.1251 4.51216C14.223 4.59933 14.2993 4.7101 14.3465 4.83544L16.2182 4.13057ZM8.32038 18.1173C8.2687 18.1477 8.2323 18.1692 8.20084 18.1871C8.17008 18.2046 8.15362 18.2132 8.14482 18.2175C8.13738 18.2212 8.14003 18.2195 8.14934 18.2161C8.15948 18.2124 8.16954 18.2097 8.17694 18.2081L8.60048 20.1627C8.9274 20.0919 9.16869 19.9388 9.33601 19.8402L8.32038 18.1173ZM7.06399 19.8402C7.23131 19.9388 7.4726 20.0919 7.79952 20.1627L8.22306 18.2081C8.23046 18.2097 8.24052 18.2124 8.25066 18.2161C8.25997 18.2195 8.26262 18.2212 8.25518 18.2175C8.24638 18.2132 8.22992 18.2046 8.19916 18.1871C8.1677 18.1692 8.1313 18.1477 8.07962 18.1173L7.06399 19.8402ZM8.17694 18.2081C8.18757 18.2058 8.19524 18.2045 8.19954 18.2039C8.20396 18.2032 8.20647 18.203 8.20701 18.2029C8.20764 18.2029 8.20489 18.2031 8.2 18.2031C8.19511 18.2031 8.19236 18.2029 8.19299 18.2029C8.19353 18.203 8.19604 18.2032 8.20046 18.2039C8.20476 18.2045 8.21243 18.2058 8.22306 18.2081L7.79952 20.1627C8.04819 20.2166 8.35181 20.2166 8.60048 20.1627L8.17694 18.2081ZM8.04104 9.47917L9.13643 6.5556L7.26357 5.85388L6.16818 8.77745L8.04104 9.47917ZM7.26357 6.5556L8.35897 9.47917L10.2318 8.77745L9.13643 5.85388L7.26357 6.5556ZM8.94459 10.0648L11.8992 11.1716L12.6008 9.29868L9.6462 8.19186L8.94459 10.0648ZM11.8992 9.29868L8.94459 10.4055L9.6462 12.2784L12.6008 11.1716L11.8992 9.29868ZM8.35435 11.0037L7.25895 14.0509L9.14105 14.7275L10.2364 11.6802L8.35435 11.0037ZM9.14105 14.0509L8.04565 11.0037L6.16356 11.6802L7.25895 14.7275L9.14105 14.0509ZM7.45541 10.4055L4.5008 9.29868L3.7992 11.1716L6.75381 12.2784L7.45541 10.4055ZM4.5008 11.1716L7.45541 10.0648L6.75381 8.19186L3.7992 9.29868L4.5008 11.1716Z",fill:"#101828"})})});let L="agent";switch(e.type){case"Agent":L="agent";break;case"llm":L="model";break;case"tool":L="workflowtool";break;case"ProxyWorker":L="app";break;default:L="agent"}return p.jsx(xi,{icon:e.icon,iconSource:L,size:"small",name:e.name,className:"w-[24px] h-[24px]",toolType:e.type==="tool"?(W=e.metadata)==null?void 0:W.type:void 0,provider:e.type==="llm"?(G=e.metadata)==null?void 0:G.provider:void 0,modelName:e.type==="llm"?e.name:void 0})},E=L=>L?L<1e3?`${L}ms`:`${(L/1e3).toFixed(2)}s`:"",B=L=>{if(!L)return"Tool";switch(L){case"route_to_user":return"Response to User";default:return L.split("_").map(W=>W.charAt(0).toUpperCase()+W.slice(1)).join(" ")}},z=()=>c,H=()=>{var J,M;let L=e.toolInvocations||[];e.type==="llm"&&Array.isArray(e.output)&&(L=e.output.filter(Q=>Q&&typeof Q=="object"&&Q.name&&Q.tool_call_id));const W=L.length>0||e.children&&e.children.length>0,G=e.isResponse||L.length>0&&L[0].name==="route_to_user";return W?p.jsxs("div",{className:"space-y-1",children:[p.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[p.jsx("span",{className:"text-xs text-gray-600",children:G?"Responded":"Invoked"}),L.length>0&&L.map((Q,K)=>p.jsxs("div",{className:"flex items-center gap-[4px] px-[8px] py-[2px] border border-gray-300 rounded-[4px] text-xs",children:[Q.isAgentHandoff?p.jsx(Sf,{className:"w-[12px] h-[12px] text-blue-500 flex-shrink-0"}):p.jsx(Vs,{className:"w-[12px] h-[12px] text-blue-500 flex-shrink-0"}),p.jsx("span",{className:"text-gray-600 truncate",children:B(Q.name||Q.toolName)})]},Q.tool_call_id||K)),L.length===0&&e.children&&e.children.length>0&&e.children.map((Q,K)=>p.jsxs("div",{className:"flex items-center gap-[4px] px-[8px] py-[2px] border border-gray-300 rounded-[4px] text-xs",children:[Q.type==="tool"?p.jsx(Vs,{className:"w-[12px] h-[12px] text-green-500 flex-shrink-0"}):p.jsx(Sf,{className:"w-[12px] h-[12px] text-blue-500 flex-shrink-0"}),p.jsx("span",{className:"text-gray-600 truncate",children:Q.name||"Unknown"})]},Q.id||K))]}),L.length>0&&((M=(J=L[0])==null?void 0:J.args)==null?void 0:M.reason)&&p.jsxs("div",{children:[p.jsx("div",{className:"text-xs font-medium text-gray-400 mb-[4px]",children:"Reason"}),p.jsx("div",{className:"text-xs text-gray-600",children:L[0].args.reason})]})]}):e.output&&!W?p.jsx("div",{className:"space-y-1",children:p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"text-xs text-gray-600",children:"Generated"}),p.jsxs("div",{className:"flex items-center gap-[4px] px-[8px] py-[4px] border border-gray-200 rounded text-xs",children:[p.jsx(Nb,{className:"w-[12px] h-[12px] text-purple-500"}),p.jsx("span",{className:"text-gray-600",children:"Response"})]})]})}):p.jsx("div",{className:"text-xs text-gray-500 italic",children:"No actions taken"})},I=L=>{var W,G,J,M;if(!(!L||typeof L!="object")){if(Array.isArray(L)){const Q=L.find(K=>K&&typeof K=="object"&&(K.name==="route_to_user"||K.toolName==="route_to_user"));if(Q)return((W=Q.args)==null?void 0:W.message)||Q.message||((G=Q.output)==null?void 0:G.message)}else if(L.name==="route_to_user"||L.toolName==="route_to_user")return((J=L.args)==null?void 0:J.message)||L.message||((M=L.output)==null?void 0:M.message);if(L.message&&typeof L.message=="string")return L.message;if(L.content&&typeof L.content=="string")return L.content;if(L.text&&typeof L.text=="string")return L.text}},V=()=>{if(!e.output)return null;const L=I(e.output);return p.jsx(xt,{padding:"py-1",data:L||e.output,title:"",showHeader:!1,maxHeight:"120px",defaultExpanded:!0,className:"border-0"})},X=()=>{if(!u||!e.output)return null;const L=e.error?e.error:e.output,W=L.scannersData,G=L.endFlow,J=L.endFlowMsg;return W?p.jsxs("div",{className:"space-y-3",children:[G&&J&&p.jsxs("div",{className:"flex items-start gap-2 p-3 bg-red-50 border border-red-200 rounded-md",children:[p.jsx(Gs,{className:"w-4 h-4 text-red-500 flex-shrink-0 mt-0.5"}),p.jsxs("div",{className:"text-xs text-red-700",children:[p.jsx("div",{className:"font-medium",children:"Guardrail Stopped"}),p.jsx("div",{className:"mt-1",children:J})]})]}),p.jsx("div",{className:"space-y-1",children:Object.entries(W).map(([M,Q])=>{if(M==="error"&&Q.scannerOutput)return p.jsxs("div",{className:"flex items-center justify-between p-1",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx(Gs,{className:"w-4 h-4 text-red-500 flex-shrink-0"}),p.jsx("span",{className:"text-xs text-gray-700 capitalize",children:"Error Scanner"})]}),p.jsx("div",{className:"flex items-center gap-3",children:p.jsx("span",{className:"text-xs text-gray-500",children:Q.scannerOutput.Duration})})]},M);if(Q.scannerOutput){const K=Q.scannerOutput.Validity,se=Q.scannerOutput.RiskScore,ne=Q.scannerOutput.Duration;let fe="text-gray-500",ue="bg-gray-100";return se!==void 0&&(se===0?(fe="text-green-600",ue="bg-green-50"):se<=3?(fe="text-yellow-600",ue="bg-yellow-50"):se<=6?(fe="text-orange-600",ue="bg-orange-50"):(fe="text-red-600",ue="bg-red-50")),p.jsxs("div",{className:"flex items-center justify-between p-1",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[K?p.jsx(Ab,{className:"w-4 h-4 text-green-500 flex-shrink-0"}):p.jsx(Gs,{className:"w-4 h-4 text-red-500 flex-shrink-0"}),p.jsx("span",{className:"text-xs text-gray-700",children:M.replace(/([A-Z])/g," $1").trim()})]}),p.jsxs("div",{className:"flex items-center gap-3",children:[se!==void 0&&p.jsxs("div",{className:`px-2 py-0.5 rounded text-xs font-medium ${ue} ${fe}`,children:["Risk: ",se]}),p.jsx("span",{className:"text-xs text-gray-500",children:ne})]})]},M)}return null})})]}):null},re=()=>{switch(f){case"summary":if(u)return p.jsxs("div",{className:"space-y-1",children:[e.input&&p.jsxs("div",{className:"border-b border-gray-100 pb-[8px]",children:[p.jsx("div",{className:"text-xs font-medium text-gray-400 mb-[8px]",children:"Input"}),p.jsx(xt,{padding:"py-1",data:e.input,title:"",showHeader:!1,maxHeight:"150px",defaultExpanded:!0,className:"border-0"})]}),(e.output||e.error)&&p.jsxs("div",{children:[p.jsx("div",{className:"text-xs font-medium text-gray-400 mb-[8px]",children:"Result"}),e.error&&!u?typeof e.error=="string"?p.jsx("div",{className:"text-xs text-gray-600",children:e.error}):p.jsx(xt,{padding:"py-1",data:e.error,title:"",showHeader:!1,maxHeight:"120px",defaultExpanded:!0,className:"border-0"}):X()]})]});let L=!1;return e.type==="llm"&&Array.isArray(e.output)&&(L=e.output.some(G=>G&&typeof G=="object"&&G.name&&G.tool_call_id)),p.jsxs("div",{className:"space-y-1",children:[e.input&&p.jsxs("div",{className:"border-b border-gray-100 pb-[8px]",children:[p.jsx("div",{className:"text-xs font-medium text-gray-400 mb-[8px]",children:"Input"}),p.jsx(xt,{padding:"py-1",data:e.input,title:"",showHeader:!1,maxHeight:"120px",defaultExpanded:!0,className:"border-0"})]}),p.jsxs("div",{className:"border-b border-gray-100 pb-2",children:[p.jsx("div",{className:"text-xs font-medium text-gray-400 mb-[4px]",children:"Action"}),H()]}),e.output&&!L&&p.jsxs("div",{className:"border-b border-gray-100 pb-[8px]",children:[p.jsx("div",{className:"text-xs font-medium text-gray-400 mb-[4px]",children:"Output"}),V()]}),e.error&&p.jsxs("div",{className:"border-b border-gray-100 pb-[8px]",children:[p.jsx("div",{className:"text-xs font-medium text-gray-400 mb-[4px]",children:"Error"}),typeof e.error=="string"?p.jsx("div",{className:"text-xs text-red-600",children:e.error}):p.jsx(xt,{padding:"py-1",data:e.error,title:"",showHeader:!1,maxHeight:"120px",defaultExpanded:!0,className:"border-0"})]})]});case"request":if(F&&_){if(b)return p.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[p.jsx(Cf,{className:"w-5 h-5 animate-spin text-blue-500 mb-2 mx-auto"}),p.jsx("div",{className:"text-sm text-gray-600",children:"Loading request data from API..."}),p.jsx("div",{className:"text-xs text-gray-400 mt-1",children:"Trace data may take a few seconds to be available"})]});if(x&&!A)return p.jsx("div",{className:"flex items-center justify-center py-8",children:p.jsxs("div",{className:"text-center",children:[p.jsx("div",{className:"text-red-500 text-sm mb-2",children:"Failed to load API data"}),p.jsx("div",{className:"text-xs text-gray-500",children:x}),p.jsx("button",{onClick:N,className:"mt-2 px-3 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600",children:"Retry"})]})});if(!A&&(v!=null&&v.input))return p.jsx(xt,{data:v.input,title:"Request Data (API)",maxHeight:"250px",defaultExpanded:!1,defaultViewMode:"plain"})}return p.jsx(xt,{data:e.input,title:A?"Request Data (Fallback)":"Request Data",maxHeight:"250px",defaultExpanded:!1,defaultViewMode:"plain"});case"response":if(F&&_){if(b)return p.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[p.jsx(Cf,{className:"w-5 h-5 animate-spin text-blue-500 mb-2 mx-auto"}),p.jsx("div",{className:"text-sm text-gray-600",children:"Loading response data from API..."}),p.jsx("div",{className:"text-xs text-gray-400 mt-1",children:"Trace data may take a few seconds to be available"})]});if(x&&!A)return p.jsx("div",{className:"flex items-center justify-center py-8",children:p.jsxs("div",{className:"text-center",children:[p.jsx("div",{className:"text-red-500 text-sm mb-2",children:"Failed to load API data"}),p.jsx("div",{className:"text-xs text-gray-500",children:x}),p.jsx("button",{onClick:N,className:"mt-2 px-3 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600",children:"Retry"})]})});if(!A&&(v!=null&&v.output))return p.jsx(xt,{data:v.output,title:"Response Data (API)",maxHeight:"250px",defaultExpanded:!1,defaultViewMode:"plain"})}return u&&(e.output||e.error)?p.jsx(xt,{data:e.error||e.output,title:e.error?"Error Output":"Full Scanner Output",maxHeight:"250px",defaultExpanded:!1,defaultViewMode:"plain"}):p.jsx(xt,{data:e.output,title:A?"Response Data (Fallback)":"Response Data",maxHeight:"250px",defaultExpanded:!1,defaultViewMode:"plain"});case"logs":const W={executionLog:[e.startTime&&{timestamp:new Date(e.startTime).toISOString(),level:"INFO",message:`${e.type==="tool"?"Tool":"Node"} execution started`,context:{nodeId:e.id,name:e.name,type:e.type}},e.status==="completed"&&{timestamp:new Date(e.endTime||e.startTime).toISOString(),level:"INFO",message:"Response received",context:{status:e.status,duration:e.duration,llmUsage:e.llmUsage}},e.endTime&&{timestamp:new Date(e.endTime).toISOString(),level:"SUCCESS",message:`${e.type==="tool"?"Tool":"Node"} execution completed`,context:{endTime:e.endTime,totalDuration:e.duration?`${e.duration}ms`:"unknown"}}].filter(Boolean),metadata:{totalLogs:0,startTime:e.startTime,endTime:e.endTime,duration:e.duration,status:e.status}};return W.metadata.totalLogs=W.executionLog.length,p.jsx(xt,{data:W,title:"Execution Logs",maxHeight:"250px",defaultExpanded:!0,defaultViewMode:"plain"});default:return null}};return p.jsxs("div",{className:"bg-white w-full",children:[p.jsx("div",{className:`flex items-center pl-[8px] pr-[8px] relative transition-colors cursor-pointer w-full
|
|
295
295
|
`,onClick:U,children:p.jsxs("div",{className:"flex items-center gap-[10px] w-full",children:[p.jsx("div",{className:"p-[2px] relative top-[1px] rounded hover:bg-gray-200 cursor-pointer flex-shrink-0 z-[2]",onClick:L=>{L.stopPropagation(),g?k(L):n&&n(e)},title:g?r?"Collapse":"Expand":"Show details",children:p.jsx(ki,{className:`w-[12px] h-[12px] text-gray-600 transition-transform ${g&&r||m&&c.length>0?"rotate-90":""}`})}),p.jsxs("div",{className:"flex items-center gap-[8px] w-full py-[8px] border-b border-gray-200",children:[p.jsx("div",{className:"flex-shrink-0 rounded-[8px] bg-[#B2DDFF]",children:Z()}),p.jsx("span",{className:"font-semibold text-gray-900 text-xs truncate w-full",title:e.type==="llm"?e.name:void 0,children:u?e.type==="GuardrailsInputScan"?"Input Guardrails Scanner":"Output Guardrails Scanner":e.type==="llm"?"AI Model Call":e.type==="tool"?B(e.name):e.name}),p.jsxs("div",{className:"flex items-center gap-[12px] text-[10px] text-gray-500",children:[e.type==="Agent"&&(()=>{var W;const L=(W=e.children)==null?void 0:W.find(G=>G.type==="llm");return L!=null&&L.name?p.jsx("span",{className:"text-[10px] text-gray-500 truncate max-w-[100px]",title:L.name,children:L.name}):null})(),(e.type==="Agent"||e.type==="llm"||u)&&(()=>{var W,G,J;let L=e.llmUsage;if(e.type==="Agent"&&e.children){const M=e.children.filter(Q=>Q.type==="llm");M.length>0&&(L=M.reduce((Q,K)=>K.llmUsage?{input_tokens:((Q==null?void 0:Q.input_tokens)||0)+(K.llmUsage.input_tokens||0),output_tokens:((Q==null?void 0:Q.output_tokens)||0)+(K.llmUsage.output_tokens||0),total_tokens:((Q==null?void 0:Q.total_tokens)||0)+(K.llmUsage.total_tokens||0)}:Q,null))}return L!=null&&L.total_tokens?p.jsxs("span",{className:"text-[10px] text-gray-500 whitespace-nowrap cursor-help",title:`Input: ${((W=L.input_tokens)==null?void 0:W.toLocaleString())||0} tokens
|
|
296
296
|
Output: ${((G=L.output_tokens)==null?void 0:G.toLocaleString())||0} tokens
|
|
297
297
|
Total: ${((J=L.total_tokens)==null?void 0:J.toLocaleString())||0} tokens`,children:[L.total_tokens.toLocaleString()," Tokens"]}):null})(),e.duration&&p.jsxs("div",{className:"flex items-center gap-[4px]",children:[p.jsx(jf,{className:"w-[12px] h-[12px]"}),p.jsx("span",{className:"text-[10px] text-gray-500 whitespace-nowrap",children:E(e.duration)})]})]}),p.jsx("div",{className:"flex-shrink-0",children:q()})]})]})}),m&&c.length>0&&i&&p.jsxs("div",{className:"w-full pl-[32px] relative",children:[p.jsx("div",{className:"absolute top-[-40px] left-[16px] w-[1px] border-l border-dashed border-gray-200 h-[calc(100%+40px)] z-[1]"}),p.jsxs("div",{className:"px-[4px] py-[8px] w-full",children:[p.jsx("div",{className:"bg-gray-50 rounded-[4px] p-[4px] inline-flex gap-[4px] mb-[8px] border border-gray-200",children:z().map(L=>p.jsx("button",{onClick:()=>R(L),className:`px-[8px] py-[4px] text-xs font-medium rounded-[4px] text-gray-500 hover:text-gray-700 hover:shadow-tab hover:bg-white transition-colors ${f===L?"bg-white text-gray-900 shadow-tab":"text-gray-500 hover:text-gray-700 hover:bg-white"}`,children:L.charAt(0).toUpperCase()+L.slice(1)},L))}),p.jsx("div",{className:"px-[4px]",children:re()})]})]}),r&&g&&p.jsxs("div",{className:"w-full pl-[32px] relative",children:[p.jsx("div",{className:"absolute top-[-40px] left-[16px] w-[1px] border-l border-dashed border-gray-200 h-[calc(100%+40px)] z-[1]"}),e.children.map((L,W)=>p.jsx(ib,{node:L,onToggle:t,isExpanded:L.isExpanded,onNodeClick:n,selectedNodeIds:a,showDetailView:i,apiConfig:o,projectId:s,nodeIndex:W},L.id))]})]})}const ob=S.forwardRef(({executionEvents:e,sessionId:t,config:r={},onNodeExpand:n,onNodeCollapse:a,className:i=""},o)=>{const[s,l]=S.useState(new Set),[u,c]=S.useState(new Set),[f,d]=S.useState(new Set),{expansionMode:m="none",showExpansionControls:g=!1,defaultDetailView:v=!0,apiConfig:h}=r;console.log("🔧 DebugPanel - Config received:",{hasConfig:!!r,hasApiConfig:!!r.apiConfig,apiConfigDetails:r.apiConfig?{tracingUrl:r.apiConfig.tracingUrl,projectId:r.apiConfig.projectId,hasHeaders:!!r.apiConfig.headers}:null});const b=S.useCallback(I=>!(h!=null&&h.tracingUrl)||!(h!=null&&h.projectId)?null:`${h.tracingUrl.replace(/\/(api|trace-api).*$/,"")}/project/${h.projectId}/sessions/${I}`,[h]),w=S.useCallback(I=>!(h!=null&&h.tracingUrl)||!(h!=null&&h.projectId)?null:`${h.tracingUrl.replace(/\/(api|trace-api).*$/,"")}/project/${h.projectId}/traces/${I}`,[h]),[x,T]=S.useState(m),[y,O]=S.useState(e),A=S.useRef(e.length);S.useEffect(()=>{O(e),e.length===0?(l(new Set),c(new Set),d(new Set),$.current=!1,A.current=0):(e.length>A.current&&($.current=!0),A.current=e.length)},[e,v]);const j=S.useRef(0),C=S.useRef(null),$=S.useRef(!1);S.useImperativeHandle(o,()=>({addEvent:I=>{O(V=>[...V,I]),$.current=!0},addEvents:I=>{O(V=>[...V,...I]),$.current=!0},clearEvents:()=>{O([]),l(new Set),c(new Set),d(new Set),$.current=!1}}),[]);const P=S.useMemo(()=>{const I=Z0.buildSessionTree(y,t);return C.current=I,I},[y,t]),_=I=>{const V=[],X=re=>{V.push(re.id),re.children.forEach(L=>X(L))};return I.runs.forEach(re=>{re.rootNodes.forEach(L=>X(L))}),V},F=S.useCallback(()=>{const I=_(P);l(new Set(I));const V=P.runs.map(X=>X.runId);d(new Set(V))},[P]),N=S.useCallback(()=>{if(x==="none"){const I=new Set;P.runs.forEach(V=>{V.rootNodes.forEach(X=>{I.add(X.id)})}),l(I)}else l(new Set)},[x,P]),R=S.useCallback(()=>{if(P.runs.length>0){const I=P.runs[P.runs.length-1];if(I.rootNodes.length>0){const V=I.rootNodes[I.rootNodes.length-1],X=[],re=L=>{if(X.push(L.id),L.children.length>0){const W=L.children[L.children.length-1];re(W)}};re(V),l(new Set(X)),d(L=>{const W=new Set(L);return W.add(I.runId),W})}}},[P]),k=S.useCallback(I=>{const V=P.runs.find(G=>G.runId===I);if(!V)return;const X=new Set,re=G=>{X.add(G.id),G.children.forEach(J=>re(J))};V.rootNodes.forEach(G=>re(G));const L=Array.from(X).filter(G=>{const J=M=>{if(M.id===G)return M;for(const Q of M.children){const K=J(Q);if(K)return K}return null};for(const M of V.rootNodes){const Q=J(M);if(Q&&(Q.type==="llm"||Q.type==="tool"||Q.type==="GuardrailsInputScan"||Q.type==="GuardrailsOutputScan"||Q.type==="ProxyWorker"))return!0}return!1});L.some(G=>u.has(G))?c(G=>{const J=new Set(G);return X.forEach(M=>J.delete(M)),J}):(l(G=>{const J=new Set(G);return X.forEach(M=>J.add(M)),J}),c(G=>{const J=new Set(G);return L.forEach(M=>J.add(M)),J}))},[P,s,u]);S.useEffect(()=>{if(x==="none"&&P.runs.length>0){const I=_(P);l(new Set(I))}},[x,P]);const U=S.useRef(null);S.useEffect(()=>{y.length>j.current&&U.current&&setTimeout(()=>{U.current&&U.current.scrollTo({top:U.current.scrollHeight,behavior:"smooth"})},100),j.current=y.length},[y.length]),S.useEffect(()=>{if(y.length>0&&P.runs.length>0){if($.current){switch(x){case"all":const I=_(P);l(new Set(I));break;case"last":R();break;case"none":if(s.size===0){const V=_(P);l(new Set(V))}break}$.current=!1}d(I=>{const V=new Set(I);return P.runs.forEach(X=>{V.has(X.runId)||V.add(X.runId)}),V})}},[P,x,R,s.size]);const q=S.useCallback(I=>{l(V=>{const X=new Set(V);return X.has(I)?(X.delete(I),a==null||a(I)):(X.add(I),n==null||n(I)),X})},[n,a]),Z=S.useCallback(I=>{c(V=>{const X=new Set(V);return X.has(I.id)?X.delete(I.id):X.add(I.id),X})},[]),E=S.useCallback(I=>{d(V=>{const X=new Set(V);return X.has(I)?X.delete(I):X.add(I),X})},[]),B=S.useCallback(I=>({...I,isExpanded:s.has(I.id),children:I.children.map(X=>B(X))}),[s]),z=I=>I?I<1e3?`${I}ms`:`${(I/1e3).toFixed(2)}s`:"",H=I=>I?I>=1e6?`${(I/1e6).toFixed(1)}M tokens`:I>=1e3?`${(I/1e3).toFixed(1)}K tokens`:`${I} tokens`:"";return P.runs.length?p.jsx("div",{className:`flex flex-col h-full bg-white ${i}`,children:p.jsxs("div",{className:"flex flex-col gap-[16px] p-[24px] overflow-y-auto overflow-x-hidden",ref:U,children:[p.jsxs("div",{className:"flex items-center w-full gap-[16px]",children:[p.jsx("div",{className:"text-xs text-gray-400 whitespace-nowrap flex-shrink-0",children:"Session initiated"}),p.jsx("div",{className:"flex-1 h-[1px] border-t border-dashed border-gray-300 w-full"}),p.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-400 flex-shrink-0",children:[p.jsx("span",{children:P.sessionId}),p.jsx(Ti,{text:P.sessionId,title:"Copy session ID",size:"sm",className:"p-[4px]",iconClassName:"w-[12px] h-[12px]"}),b(P.sessionId)&&p.jsx("button",{className:"p-[4px] hover:bg-gray-100 rounded transition-colors",title:"Open session in external viewer",onClick:()=>{const I=b(P.sessionId);I&&window.open(I,"_blank")},children:p.jsx(_f,{className:"w-[12px] h-[12px]"})})]})]}),g&&p.jsxs("div",{className:"flex items-center justify-between gap-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"text-xs font-medium text-gray-700",children:"Expansion:"}),p.jsxs("button",{onClick:F,className:"flex items-center gap-1 px-2 py-1 text-xs bg-white hover:bg-gray-50 border border-gray-300 rounded transition-colors",title:"Expand all nodes",children:[p.jsx($b,{className:"w-3 h-3"}),"Expand All"]}),p.jsxs("button",{onClick:R,className:"flex items-center gap-1 px-2 py-1 text-xs bg-white hover:bg-gray-50 border border-gray-300 rounded transition-colors",title:"Expand only the last execution path",children:[p.jsx(Pb,{className:"w-3 h-3"}),"Expand Last"]}),p.jsxs("button",{onClick:N,className:"flex items-center gap-1 px-2 py-1 text-xs bg-white hover:bg-gray-50 border border-gray-300 rounded transition-colors",title:"Collapse all nodes",children:[p.jsx(Cb,{className:"w-3 h-3"}),"Collapse All"]})]}),p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx("span",{className:"text-xs font-medium text-gray-700",children:"Live Mode:"}),p.jsxs("select",{value:x,onChange:I=>T(I.target.value),className:"text-xs px-2 py-1 bg-white border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500",title:"Control auto-expansion behavior during live updates",children:[p.jsx("option",{value:"all",children:"Expand All"}),p.jsx("option",{value:"last",children:"Expand Last"}),p.jsx("option",{value:"none",children:"No Auto-Expand"})]})]})]}),P.runs.map(I=>p.jsxs("div",{className:"flex flex-col gap-1",children:[p.jsxs("div",{className:"rounded-[8px] border border-gray-300 bg-white overflow-hidden",children:[p.jsx("div",{className:"flex flex-col w-full",children:p.jsxs("div",{className:"flex items-center gap-2 p-[8px] bg-gray-50",children:[p.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:"flex-shrink-0",children:p.jsx("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M10.8277 1.33398C11.3643 1.33398 11.8072 1.33396 12.168 1.36343C12.5428 1.39405 12.8872 1.45978 13.2108 1.62463C13.7125 1.8803 14.1205 2.28825 14.3762 2.79001C14.541 3.11356 14.6067 3.45803 14.6374 3.83276C14.6668 4.19356 14.6668 4.63646 14.6668 5.1731V9.0235C14.6668 9.47003 14.6668 9.83861 14.6462 10.1404C14.6249 10.4532 14.5792 10.7426 14.4638 11.0211C14.1932 11.6746 13.674 12.1937 13.0206 12.4643C12.7421 12.5797 12.4527 12.6254 12.1399 12.6467C11.8381 12.6673 11.4695 12.6673 11.023 12.6673H11.0002C10.6424 12.6673 10.5714 12.6715 10.5136 12.6852C10.4129 12.7089 10.3191 12.7558 10.2397 12.8221C10.1941 12.8602 10.1481 12.9145 9.9335 13.2007L8.94888 14.5135C8.88665 14.5965 8.81628 14.6904 8.74857 14.7657C8.6739 14.8487 8.54979 14.971 8.36264 15.0438C8.1295 15.1344 7.87083 15.1344 7.6377 15.0438C7.45054 14.971 7.32641 14.8487 7.25174 14.7657C7.18403 14.6904 7.11368 14.5965 7.05145 14.5135L6.06683 13.2007C5.85221 12.9145 5.80624 12.8602 5.76065 12.8221C5.68119 12.7558 5.58739 12.7089 5.48666 12.6852C5.42887 12.6715 5.35786 12.6673 5.00015 12.6673H4.9773C4.53078 12.6673 4.16221 12.6673 3.86047 12.6467C3.54762 12.6254 3.25822 12.5797 2.97968 12.4643C2.32627 12.1937 1.80712 11.6746 1.53647 11.0211C1.42109 10.7426 1.37541 10.4532 1.35407 10.1404C1.33348 9.83861 1.33349 9.47003 1.3335 9.0235V5.17313C1.33349 4.63648 1.33347 4.19356 1.36295 3.83276C1.39356 3.45803 1.45929 3.11356 1.62415 2.79001C1.87981 2.28825 2.28776 1.8803 2.78952 1.62463C3.11308 1.45978 3.45755 1.39405 3.83228 1.36343C4.19307 1.33396 4.63599 1.33398 5.17264 1.33398H10.8277ZM10.4715 4.52924C10.2112 4.2689 9.78906 4.26889 9.52872 4.52924L6.66681 7.39114V5.6673C6.6668 5.29912 6.36834 5.00064 6.00015 5.00064C5.63197 5.00064 5.33351 5.29912 5.3335 5.6673V9.00064C5.3335 9.17745 5.40373 9.34702 5.52875 9.47205C5.65377 9.59707 5.82334 9.6673 6.00015 9.6673H9.3335L9.35068 9.66708C9.71092 9.65796 10.0002 9.36308 10.0002 9.00064C10.0001 8.63821 9.71092 8.34332 9.35068 8.3342L9.3335 8.33398H7.60962L10.4715 5.47205C10.7319 5.2117 10.7319 4.78958 10.4715 4.52924Z",fill:"#079455"})}),p.jsx("div",{className:"flex-1 cursor-pointer select-none truncate",onClick:()=>E(I.runId),title:I.userInput,children:p.jsx("span",{className:"text-xs text-gray-900 truncate",children:I.userInput||`Run ${I.runId}`})}),p.jsx("button",{onClick:V=>{V.stopPropagation(),k(I.runId)},className:"p-1 hover:bg-gray-200 rounded transition-colors flex-shrink-0",title:(()=>{const V=new Set,X=L=>{V.add(L.id),L.children.forEach(W=>X(W))};return I.rootNodes.forEach(L=>X(L)),Array.from(V).some(L=>u.has(L))?"Hide all node details in this run":"Show all node details in this run"})(),children:(()=>{const V=new Set,X=L=>{V.add(L.id),L.children.forEach(W=>X(W))};return I.rootNodes.forEach(L=>X(L)),Array.from(V).some(L=>u.has(L))?p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"8",height:"12",viewBox:"0 0 8 12",fill:"none",children:p.jsx("path",{d:"M0.666992 0.666016L4.00033 3.99935L7.33366 0.666016M0.666992 11.3327L4.00033 7.99935L7.33366 11.3327",stroke:"#98A2B3",strokeWidth:"1.33333",strokeLinecap:"round",strokeLinejoin:"round"})}):p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"8",height:"12",viewBox:"0 0 8 12",fill:"none",children:p.jsx("path",{d:"M0.666992 11.3327L4.00033 7.99935L7.33366 11.3327M0.666992 0.666016L4.00033 3.99935L7.33366 0.666016",stroke:"#98A2B3",strokeWidth:"1.33333",strokeLinecap:"round",strokeLinejoin:"round"})})})()}),p.jsx("button",{onClick:V=>{V.stopPropagation(),E(I.runId)},className:"p-1 hover:bg-gray-200 rounded transition-colors flex-shrink-0",title:f.has(I.runId)?"Collapse run":"Expand run",children:p.jsx(fr,{className:`w-[16px] h-[16px] text-gray-400 transition-transform ${f.has(I.runId)?"rotate-180":""}`})})]})}),f.has(I.runId)&&p.jsx("div",{className:"bg-white w-full flex flex-col",children:I.rootNodes&&I.rootNodes.map((V,X)=>{var re;return p.jsx("div",{className:"w-full",children:p.jsx(ib,{node:B(V),onToggle:q,isExpanded:s.has(V.id),onNodeClick:Z,selectedNodeIds:u,showDetailView:!0,apiConfig:r.apiConfig,projectId:(re=r.apiConfig)==null?void 0:re.projectId,nodeIndex:X})},V.id)})}),(()=>{const V=L=>{let W,G;const J=M=>{var Q,K,se,ne,fe;for(const ue of M){if(ue.type==="tool"&&(ue.name==="route_to_user"||ue.name==="route_to_user")&&ue.output&&(typeof ue.output=="string"?G=ue.output:(Q=ue.output)!=null&&Q.message?G=ue.output.message:(K=ue.output)!=null&&K.result&&(G=ue.output.result)),ue.type==="llm"&&Array.isArray(ue.output)){const Ee=ue.output.find(Oe=>(Oe==null?void 0:Oe.name)==="route_to_user"||(Oe==null?void 0:Oe.toolName)==="route_to_user");Ee&&((se=Ee.args)!=null&&se.message?G=Ee.args.message:Ee.message&&(G=Ee.message))}ue.output&&!G&&(typeof ue.output=="string"?W=ue.output:Array.isArray(ue.output)||((ne=ue.output)!=null&&ne.message?W=ue.output.message:(fe=ue.output)!=null&&fe.result?W=ue.output.result:typeof ue.output=="object"&&!ue.output.name&&!ue.output.toolName&&(W=JSON.stringify(ue.output)))),ue.children&&ue.children.length>0&&J(ue.children)}};return J(L),G||W},re=(I.rootNodes?V(I.rootNodes):void 0)||I.finalOutput;return re?p.jsxs("div",{className:"p-[8px] bg-gray-50 flex items-center gap-[8px] w-full border-t border-gray-200",children:[p.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:"flex-shrink-0",children:p.jsx("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M10.8277 1.33398C11.3643 1.33398 11.8072 1.33396 12.168 1.36343C12.5428 1.39405 12.8872 1.45978 13.2108 1.62463C13.7125 1.8803 14.1205 2.28825 14.3762 2.79001C14.541 3.11356 14.6067 3.45803 14.6374 3.83276C14.6668 4.19356 14.6668 4.63646 14.6668 5.1731V9.0235C14.6668 9.47003 14.6668 9.83861 14.6462 10.1404C14.6249 10.4532 14.5792 10.7426 14.4638 11.0211C14.1932 11.6746 13.674 12.1937 13.0206 12.4643C12.7421 12.5797 12.4527 12.6254 12.1399 12.6467C11.8381 12.6673 11.4695 12.6673 11.023 12.6673H11.0002C10.6424 12.6673 10.5714 12.6715 10.5136 12.6852C10.4129 12.7089 10.3191 12.7558 10.2397 12.8221C10.1941 12.8602 10.1481 12.9145 9.9335 13.2007L8.94888 14.5135C8.88665 14.5965 8.81628 14.6904 8.74857 14.7657C8.6739 14.8487 8.54979 14.971 8.36264 15.0438C8.1295 15.1344 7.87083 15.1344 7.6377 15.0438C7.45054 14.971 7.32641 14.8487 7.25174 14.7657C7.18403 14.6904 7.11368 14.5965 7.05145 14.5135L6.06683 13.2007C5.85221 12.9145 5.80624 12.8602 5.76065 12.8221C5.68119 12.7558 5.58739 12.7089 5.48666 12.6852C5.42887 12.6715 5.35786 12.6673 5.00015 12.6673H4.9773C4.53078 12.6673 4.16221 12.6673 3.86047 12.6467C3.54762 12.6254 3.25822 12.5797 2.97968 12.4643C2.32627 12.1937 1.80712 11.6746 1.53647 11.0211C1.42109 10.7426 1.37541 10.4532 1.35407 10.1404C1.33348 9.83861 1.33349 9.47003 1.3335 9.0235V5.17313C1.33349 4.63648 1.33347 4.19356 1.36295 3.83276C1.39356 3.45803 1.45929 3.11356 1.62415 2.79001C1.87981 2.28825 2.28776 1.8803 2.78952 1.62463C3.11308 1.45978 3.45755 1.39405 3.83228 1.36343C4.19307 1.33396 4.63599 1.33398 5.17264 1.33398H10.8277ZM6.66653 4.33398C6.29835 4.334 5.99988 4.63246 5.99988 5.00064C5.99988 5.36882 6.29835 5.66729 6.66653 5.6673H8.39041L5.52847 8.52924C5.26813 8.78958 5.26813 9.2117 5.52847 9.47205C5.78882 9.73239 6.21093 9.73239 6.47128 9.47205L9.33322 6.61011V8.33398C9.33323 8.70217 9.6317 9.00064 9.99988 9.00064C10.3681 9.00064 10.6665 8.70217 10.6665 8.33398V5.00064C10.6665 4.63821 10.3773 4.34333 10.0171 4.3342L9.99988 4.33398H6.66653Z",fill:"#155EEF"})}),p.jsx("span",{className:"flex-1 text-xs text-gray-900 truncate",title:re,children:re}),p.jsxs("div",{className:"flex items-center gap-[8px] flex-shrink-0",children:[I.duration&&p.jsxs("div",{className:"flex items-center gap-[4px]",children:[p.jsx(jf,{className:"w-[12px] h-[12px] text-gray-400"}),p.jsx("span",{className:"text-[10px] text-gray-500 whitespace-nowrap",children:z(I.duration)})]}),I.totalTokens&&p.jsx("span",{className:"text-[10px] text-gray-500 whitespace-nowrap",children:H(I.totalTokens)})]})]}):null})()]}),p.jsxs("div",{className:"flex items-center justify-end gap-2 py-1",children:[p.jsx("span",{className:"text-xs text-gray-400",children:I.runId}),p.jsxs("div",{className:"flex items-center gap-2",children:[p.jsx(Ti,{text:I.runId,title:"Copy run ID",size:"sm",className:"p-1",iconClassName:"w-3 h-3"}),w(I.runId)&&p.jsx("button",{className:"p-1 hover:bg-gray-100 rounded transition-colors",title:"Open trace in external viewer",onClick:()=>{const V=w(I.runId);V&&window.open(V,"_blank")},children:p.jsx(_f,{className:"w-3 h-3 text-gray-400"})})]})]})]},I.runId))]})}):p.jsx("div",{className:`flex flex-col h-full ${i}`,children:p.jsx("div",{className:"flex items-center justify-center h-full",children:p.jsx("p",{className:"text-gray-500 text-sm",children:"No execution events to display"})})})});ob.displayName="DebugPanel";const Bs=["Portfolio Analysis Expert","Mortgage Evaluator","Credit Risk Specialist","Asset Valuation Analyst","Liability Assessment Advisor"],Fs=["calculate-creditScore","calculate-risk","calculate-mortgage","analyse-expenses","fetch-statement"],Us=["gpt-4o","gpt-4o-mini","gpt-3.5-turbo","claude-3-5-sonnet","claude-3-5-haiku","claude-3-opus","gemini-1.5-pro","gemini-1.5-flash","llama-3.1-405b","llama-3.1-70b"],pU=(e=30)=>{const t=[],r=new Date;for(let n=e-1;n>=0;n--){const a=new Date(r);a.setDate(r.getDate()-n);const i=600+Math.sin(n*.1)*100,o=Math.floor(i+Math.random()*100),s=Math.floor(o*3.5+Math.random()*200),l=Math.floor(s*2.9+Math.random()*500),u=Math.floor(l*.9+Math.random()*300),c=Math.floor(u*.6),f=u-c,d=Math.floor(s*.8+Math.random()*100),m=Math.floor(d*12+Math.random()*500),g=Math.floor(d*8+Math.random()*300),v=Math.floor(m*.3+Math.random()*100),h=Math.floor(m*.25+Math.random()*80),b=Math.floor(m*.2+Math.random()*60),w=Math.floor(m*.15+Math.random()*50),x={};Bs.forEach(O=>{const A=O.replace(/\s+/g,"").toLowerCase(),j=Math.floor(d/Bs.length);x[A]=Math.floor(j+Math.random()*(j*.5))});const T={};Fs.forEach(O=>{const A=O.replace(/[-]/g,""),j=Math.floor(m/Fs.length);T[A]=Math.floor(j+Math.random()*(j*.8))});const y={};Us.forEach(O=>{const A=O.replace(/[-\.]/g,""),j=Math.floor(g/Us.length);y[A]=Math.floor(j+Math.random()*(j*.6))}),t.push({date:a.toISOString().split("T")[0],users:o,sessions:s,messages:l,totalTokens:u,inputTokens:c,outputTokens:f,agentRuns:d,toolRuns:m,modelRuns:g,codeTools:v,workflowTools:h,knowledgeTools:b,mcpTools:w,...x,...T,...y,value:o})}return t},hU=()=>{const e=[],t=['{"name":"avatar14","color":"#F6D0FE","type":"human"}','{"name":"avatar2","color":"#3B82F6","type":"human"}','{"name":"avatar7","color":"#EF4444","type":"human"}','{"name":"avatar12","color":"#10B981","type":"human"}','{"name":"avatar8","color":"#F59E0B","type":"human"}'];return Bs.forEach((r,n)=>{e.push({id:`agent-${n+1}`,name:r,runs:Math.floor(Math.random()*8e3)+4e3,responseTime:`${Math.floor(Math.random()*120)+15}s`,tokens:Math.floor(Math.random()*4e5)+1e5,successRate:`${Math.floor(Math.random()*20)+80}%`,lastRun:new Date(Date.now()-Math.random()*7*24*60*60*1e3).toLocaleDateString(),avatar:`https://api.dicebear.com/7.x/avataaars/svg?seed=${r.replace(/\s+/g,"")}&backgroundColor=b6e3f4,c0aede,d1d4f9&backgroundType=solid`,icon:t[n]||t[0]})}),e},mU=()=>{const e=r=>r.includes("calculate-creditscore")?"Code Tool":r.includes("calculate-risk")?"Workflow Tool":r.includes("calculate-mortgage")?"MCP Tool":r.includes("analyse-expenses")?"Workflow Tool":r.includes("fetch-statement")?"Knowledge":"Code Tool",t=['{"name":"calculator","color":"#EF6820","type":"inlineTool"}','{"name":"workflow","color":"#155EEF","type":"toolLibrary"}','{"name":"mcptool","color":"#101828","type":"MCP"}','{"name":"expenses","color":"#155EEF","type":"toolLibrary"}','{"name":"knowledge","color":"#7A5AF8","type":"KNOWLEDGE"}'];return Fs.map((r,n)=>({id:`tool-${n+1}`,name:r,type:e(r),runs:Math.floor(Math.random()*8e3)+4e3,responseTime:`${Math.floor(Math.random()*90)+15}s`,tokens:Math.floor(Math.random()*2e4)+5e3,successRate:`${Math.floor(Math.random()*15)+85}%`,lastRun:new Date(Date.now()-Math.random()*7*24*60*60*1e3).toLocaleDateString(),icon:t[n]||t[0]}))},gU=()=>Us.map((e,t)=>({id:`model-${t+1}`,name:e,runs:Math.floor(Math.random()*8e3)+4e3,responseTime:`${Math.floor(Math.random()*120)+15}s`,tokens:Math.floor(Math.random()*5e5)+1e5,successRate:`${Math.floor(Math.random()*15)+85}%`,lastRun:new Date(Date.now()-Math.random()*7*24*60*60*1e3).toLocaleDateString()})),Jr=pU(),vU=hU(),yU=mU(),bU=gU(),xU={id:"main-dashboard",title:"Dashboard",subtitle:"Monitor and review the usage of your agentic app.",version:"1.0.0",globalControls:{draft:{label:"Draft",options:[{label:"Current Draft",value:"current"},{label:"Previous Draft",value:"previous"},{label:"All Drafts",value:"all"}],defaultValue:"current"},timeRange:{label:"Time Range",options:[{label:"This month",value:"month"},{label:"Last 7 days",value:"week"},{label:"Last 30 days",value:"30days"},{label:"Last 90 days",value:"90days"}],defaultValue:"month"},export:{enabled:!0,formats:["csv","json","pdf"]}},layout:{columns:12,gap:24,responsive:!0},sections:[{id:"sessions",title:"Sessions",description:"User engagement and session analytics",metrics:[{title:"Users",value:3384,change:{value:6,type:"increase"},info:"Total number of unique users",metricType:"users",view:{type:"chart",chart:{type:"line",title:"Total Users",data:Jr,dataKey:"users",color:"#8b5cf6",yAxisLabel:"Number of Users",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}}}},{title:"Sessions",value:11847,change:{value:18,type:"increase"},info:"Total number of user sessions",metricType:"sessions",view:{type:"chart",chart:{type:"line",title:"Total Sessions",data:Jr,dataKey:"sessions",color:"#06b6d4",yAxisLabel:"Number of Sessions",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}}}},{title:"Messages",value:34563,change:{value:5,type:"increase"},info:"Total messages exchanged",metricType:"messages",view:{type:"chart",chart:{type:"line",title:"Total Messages",data:Jr,dataKey:"messages",color:"#e879f9",yAxisLabel:"Number of Messages",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}}}},{title:"Tokens",value:32044,change:{value:44,type:"increase"},info:"Total tokens processed",metricType:"tokens",view:{type:"chart",chart:{type:"line",title:"Token Usage Breakdown",data:Jr,yAxisLabel:"Number of Tokens",lines:[{dataKey:"totalTokens",color:"#f97316",label:"Total Tokens"},{dataKey:"inputTokens",color:"#3b82f6",label:"Input Tokens"},{dataKey:"outputTokens",color:"#e879f9",label:"Output Tokens"}],height:300,showGrid:!0,showLegend:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}}}}],view:{type:"chart"},layout:{span:12,order:1}},{id:"runs",title:"Runs",description:"Agent, tool, and model execution analytics",metrics:[{title:"Agent Runs",value:3384,change:{value:6,type:"increase"},info:"Number of agent executions",metricType:"agentRuns",view:{type:"chart",chart:{type:"line",title:"Agent Runs",data:Jr,dataKey:"agentRuns",color:"#06b6d4",yAxisLabel:"Number of Agent Runs",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}},table:{title:"Agent Runs",data:vU,columns:[{key:"name",title:"Name",width:200,align:"left"},{key:"runs",title:"Runs",width:100,align:"right",formatter:e=>`${Math.floor(e/1e3)}k`},{key:"responseTime",title:"Response Time",width:120,align:"right"},{key:"tokens",title:"Tokens",width:100,align:"right",formatter:e=>`${Math.floor(e/1e3)}k`}]}},controls:{dropdown:{label:"All Agents",options:[{label:"All Agents",value:"all"},...Bs.map(e=>({label:e,value:e.replace(/\s+/g,"").toLowerCase(),avatar:`https://api.dicebear.com/7.x/avataaars/svg?seed=${e.replace(/\s+/g,"")}&backgroundColor=b6e3f4,c0aede,d1d4f9&backgroundType=solid`}))],defaultValue:["all"],multiSelect:!0,searchable:!0},toggle:{chartView:!0,tableView:!0}}},{title:"Tool Runs",value:34563,change:{value:5,type:"increase"},info:"Number of tool executions",metricType:"toolRuns",view:{type:"chart",chart:{type:"line",title:"Tool Runs",data:Jr,yAxisLabel:"Number of Tool Runs",lines:[{dataKey:"toolRuns",color:"#06b6d4",label:"Tool Runs"},{dataKey:"codeTools",color:"#f97316",label:"Code Tools"},{dataKey:"workflowTools",color:"#10b981",label:"Workflow Tools"},{dataKey:"knowledgeTools",color:"#8b5cf6",label:"Knowledge"},{dataKey:"mcpTools",color:"#ef4444",label:"MCP Tools"}],height:300,showGrid:!0,showLegend:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}},table:{title:"Tool Runs",data:yU,columns:[{key:"name",title:"Name",width:200,align:"left"},{key:"type",title:"Type",width:150,align:"left"},{key:"runs",title:"Runs",width:100,align:"right",formatter:e=>`${Math.floor(e/1e3)}k`},{key:"responseTime",title:"Response Time",width:120,align:"right"}]}},controls:{dropdown:{label:"All Tools",options:[{label:"All Tools",value:"all"},...Fs.map((e,t)=>{const r=['{"name":"calculator","color":"#EF6820","type":"inlineTool"}','{"name":"workflow","color":"#155EEF","type":"toolLibrary"}','{"name":"mcptool","color":"#101828","type":"MCP"}','{"name":"expenses","color":"#155EEF","type":"toolLibrary"}','{"name":"knowledge","color":"#7A5AF8","type":"KNOWLEDGE"}'],n=a=>a.includes("calculate-creditscore")?"Code Tool":a.includes("calculate-risk")?"Workflow Tool":a.includes("calculate-mortgage")?"MCP Tool":a.includes("analyse-expenses")?"Workflow Tool":a.includes("fetch-statement")?"Knowledge":"Code Tool";return{label:e,value:e.replace(/[-]/g,""),icon:r[t]||r[0],type:n(e)}})],defaultValue:["all"],multiSelect:!0,searchable:!0},toggle:{chartView:!0,tableView:!0}}},{title:"Model Runs",value:32044,change:{value:44,type:"increase"},info:"Number of model inferences",metricType:"modelRuns",view:{type:"chart",chart:{type:"line",title:"Model Runs",data:Jr,dataKey:"modelRuns",color:"#10b981",yAxisLabel:"Number of Model Runs",height:300,showGrid:!0,curve:"monotone",tooltip:{show:!0,style:"dark"},dateRange:{start:"2025-05-06",end:"2025-06-05"}},table:{title:"Model Runs",data:bU,columns:[{key:"name",title:"Model Name",width:200,align:"left"},{key:"runs",title:"Runs",width:100,align:"right",formatter:e=>`${Math.floor(e/1e3)}k`},{key:"tokens",title:"Tokens",width:120,align:"right",formatter:e=>`${Math.floor(e/1e3)}k`},{key:"responseTime",title:"Response Time",width:120,align:"right"}]}},controls:{dropdown:{label:"All Models",options:[{label:"All Models",value:"all"},...Us.map(e=>{const t=r=>{const n=r.toLowerCase();return n.includes("gpt")||n.includes("openai")?"⚡":n.includes("claude")||n.includes("anthropic")?"A":n.includes("gemini")||n.includes("google")?"G":n.includes("llama")||n.includes("meta")?"M":"🤖"};return{label:e,value:e.replace(/[-\.]/g,""),icon:t(e)}})],defaultValue:["all"],multiSelect:!0,searchable:!0},toggle:{chartView:!0,tableView:!0}}}],view:{type:"chart"},layout:{span:12,order:2}}]},Xt={primary:["#8b5cf6","#06b6d4","#f97316","#10b981","#ec4899","#f59e0b","#3b82f6","#ef4444"],secondary:["#a78bfa","#22d3ee","#fb923c","#34d399","#f472b6","#fbbf24","#60a5fa","#f87171"],accent:["#6366f1","#8b5cf6","#d946ef","#06b6d4","#84cc16","#eab308"],semantic:{success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#3b82f6"},gradients:{purple:["#8b5cf6","#a78bfa"],cyan:["#06b6d4","#22d3ee"],orange:["#f97316","#fb923c"],green:["#10b981","#34d399"],sunset:["#f97316","#ec4899"],ocean:["#06b6d4","#3b82f6"],forest:["#10b981","#84cc16"]}},wU={primary:["#7c3aed","#0891b2","#ea580c","#059669","#db2777","#d97706","#2563eb","#dc2626"],secondary:["#8b5cf6","#06b6d4","#f97316","#10b981","#ec4899","#f59e0b","#3b82f6","#ef4444"],accent:["#4f46e5","#7c3aed","#c026d3","#0891b2","#65a30d","#ca8a04"],semantic:{success:"#059669",warning:"#d97706",error:"#dc2626",info:"#2563eb"}},OU={primary:["#a78bfa","#22d3ee","#fb923c","#34d399","#f472b6","#fbbf24","#60a5fa","#f87171"],secondary:["#c4b5fd","#67e8f9","#fdba74","#6ee7b7","#f9a8d4","#fcd34d","#93c5fd","#fca5a5"],accent:["#818cf8","#a78bfa","#e879f9","#22d3ee","#a3e635","#facc15"],semantic:{success:"#34d399",warning:"#fbbf24",error:"#f87171",info:"#60a5fa"}},SU={primary:["#1f2937","#374151","#6b7280","#9ca3af","#3b82f6","#1d4ed8","#10b981","#f59e0b"],secondary:["#4b5563","#6b7280","#9ca3af","#d1d5db","#60a5fa","#3b82f6","#34d399","#fbbf24"],accent:["#2563eb","#1d4ed8","#059669","#0891b2","#d97706","#b45309"],semantic:{success:"#059669",warning:"#d97706",error:"#dc2626",info:"#1d4ed8"}},sb=(e,t)=>e.primary[t%e.primary.length],ji=(e,t)=>e.semantic[t],AU=(e,t)=>{var r;return((r=e.gradients)==null?void 0:r[t])||[e.primary[0],e.primary[1]]},lb=(e,t=Xt)=>e.map((r,n)=>({...r,color:sb(t,n)})),Ws=((e=30)=>{const t=[],r=new Date;for(let n=e-1;n>=0;n--){const a=new Date(r);a.setDate(r.getDate()-n);const i=600+Math.sin(n*.1)*100,o=Math.floor(i+Math.random()*100),s=Math.floor(o*3.5+Math.random()*200),l=Math.floor(s*2.9+Math.random()*500),u=Math.floor(l*.9+Math.random()*300),c=Math.floor(u*.6),f=u-c,d=Math.floor(s*.8+Math.random()*100),m=Math.floor(d*12+Math.random()*500),g=Math.floor(d*8+Math.random()*300);t.push({date:a.toISOString().split("T")[0],users:o,sessions:s,messages:l,totalTokens:u,inputTokens:c,outputTokens:f,agentRuns:d,toolRuns:m,modelRuns:g,value:o})}return t})(),TU={id:"enhanced-dashboard",title:"Enhanced Color Configuration Dashboard",subtitle:"Demonstrating all color configuration options",version:"1.0.0",globalControls:{draft:{label:"Draft",options:[{label:"Current Draft",value:"current"},{label:"Previous Draft",value:"previous"}],defaultValue:"current"},timeRange:{label:"Time Range",options:[{label:"Last 7 days",value:"week"},{label:"Last 30 days",value:"30days"}],defaultValue:"30days"},export:{enabled:!0,formats:["csv","json"]}},layout:{columns:12,gap:24,responsive:!0},sections:[{id:"manual-colors",title:"Manual Color Assignment",description:"Each line has manually assigned colors",metrics:[{title:"Total Users",value:3384,change:{value:6,type:"increase"},info:"Manually colored chart"}],view:{type:"chart",chart:{type:"line",title:"Manual Color Configuration",data:Ws,lines:[{dataKey:"users",color:"#8b5cf6",label:"Users",strokeWidth:3},{dataKey:"sessions",color:"#06b6d4",label:"Sessions",strokeWidth:2},{dataKey:"messages",color:"#f97316",label:"Messages",strokeWidth:2,strokeDasharray:"5 5"}],dateRange:{start:"2025-05-06",end:"2025-06-05"},tooltip:{show:!0,style:"dark"},height:300,showLegend:!1}},layout:{span:6,order:1}},{id:"auto-colors",title:"Auto-Assigned Colors",description:"Colors automatically assigned from palette",metrics:[{title:"Agent Runs",value:3384,change:{value:6,type:"increase"},info:"Auto-colored from palette"}],view:{type:"chart",chart:{type:"line",title:"Auto Color Assignment",data:Ws,lines:lb([{dataKey:"agentRuns",label:"Agent Runs"},{dataKey:"toolRuns",label:"Tool Runs"},{dataKey:"modelRuns",label:"Model Runs"},{dataKey:"totalTokens",label:"Total Tokens"}],Xt),dateRange:{start:"2025-05-06",end:"2025-06-05"},tooltip:{show:!0,style:"dark"},height:300,showLegend:!1}},layout:{span:6,order:2}},{id:"semantic-colors",title:"Semantic Colors",description:"Using semantic colors for different data types",metrics:[{title:"Success Rate",value:"94.2%",change:{value:2,type:"increase"},info:"Using semantic success color"},{title:"Error Rate",value:"5.8%",change:{value:1,type:"decrease"},info:"Using semantic error color"}],view:{type:"chart",chart:{type:"line",title:"Semantic Color Usage",data:Ws,lines:[{dataKey:"users",color:ji(Xt,"success"),label:"Successful Operations",strokeWidth:3},{dataKey:"sessions",color:ji(Xt,"warning"),label:"Warning Events",strokeWidth:2},{dataKey:"messages",color:ji(Xt,"error"),label:"Error Events",strokeWidth:2},{dataKey:"totalTokens",color:ji(Xt,"info"),label:"Info Events",strokeWidth:2}],dateRange:{start:"2025-05-06",end:"2025-06-05"},tooltip:{show:!0,style:"dark"},height:300,showLegend:!1}},layout:{span:12,order:3}},{id:"single-custom",title:"Single Line Custom Color",description:"Single line chart with custom color and styling",metrics:[{title:"Total Messages",value:34563,change:{value:5,type:"increase"},info:"Custom styled single line"}],view:{type:"chart",chart:{type:"line",title:"Custom Single Line",data:Ws,dataKey:"messages",color:"#ec4899",dateRange:{start:"2025-05-06",end:"2025-06-05"},tooltip:{show:!0,style:"dark"},height:250,showGrid:!0,curve:"monotone"}},layout:{span:12,order:4}}]},jU={manualColors:{line1:"#8b5cf6",line2:"#06b6d4",line3:"#f97316",line4:"#10b981"},paletteColors:Xt.primary,semanticColors:Xt.semantic,gradientColors:Xt.gradients},PU={baseUrl:window.location.protocol+"//"+window.location.hostname,dashboardType:"agenticDashboard",projectId:"aa-bdbfa4eb-c7c4-4350-be96-d778188c2c4b",environment:"draft",headers:{authorization:"Bearer 2amvsUbh87obVLVYjbNnXCbXnOr-plekM7-qjKt2EJIZnZuAV2KT9WSTG0L4U33X",accountId:"6290f982fb880154e99bbede","Content-Type":"application/json"},defaultTimeRange:{fromTimestamp:new Date(Date.now()-7*24*60*60*1e3).toISOString(),toTimestamp:new Date().toISOString()},refreshInterval:3e4},_U={id:"agentic-analytics-dashboard",title:"Dashboard",subtitle:"Monitor and review the usage of your agentic app",sections:[{id:"usage-analytics",title:"Session Analytics",metrics:[{title:"Users",value:0,metricType:"users",highlighted:!0},{title:"Sessions",value:0,metricType:"sessions",highlighted:!1},{title:"Messages",value:0,metricType:"messages",highlighted:!1},{title:"Tokens",value:0,metricType:"tokens",highlighted:!1}],view:{type:"chart",chart:{type:"line",title:"Usage Over Time",data:[],lines:[{dataKey:"count",color:"#3B82F6",label:"Count",strokeWidth:2}],xAxisLabel:"Date",yAxisLabel:"Count",tooltip:{show:!0,formatter:(e,t)=>[`${e}`,t]}}},layout:{span:12}},{id:"runs",title:"Execution Analytics",metrics:[{title:"Agent Runs",value:0,metricType:"agentRuns",highlighted:!0},{title:"Tool Runs",value:0,metricType:"toolRuns",highlighted:!1},{title:"Model Runs",value:0,metricType:"modelRuns",highlighted:!1}],view:{type:"chart",chart:{type:"line",title:"Execution Runs Over Time",data:[],lines:[{dataKey:"count",color:"#10B981",label:"Runs",strokeWidth:2}],xAxisLabel:"Date",yAxisLabel:"Count",tooltip:{show:!0,formatter:(e,t)=>[`${e}`,t]}}},layout:{span:12}}],globalControls:{draft:{label:"Environment",options:[{label:"Draft",value:"draft"},{label:"Production",value:"production"},{label:"Staging",value:"staging"}],defaultValue:"draft"},timeRange:{label:"Time Range",useDatePicker:!0,options:[{label:"Last 7 days",value:"7d"},{label:"Last 30 days",value:"30d"}],defaultValue:"7d"},export:{enabled:!1,formats:["csv","json"],onExport:e=>{console.log(`Exporting in ${e} format`)}}},layout:{columns:12,gap:24,responsive:!0}},EU=`
|