+
${t.model} ${t.provider?`(${t.provider})`:""}
+
+
+
+
+
+ | Cost Type |
+ Per Request |
+ ${null!==t.daily_cost?"Daily | ":""}
+ ${null!==t.monthly_cost?"Monthly | ":""}
+
+
+ | Input Cost |
+ ${tA(t.input_cost_per_request)} |
+ ${null!==t.daily_cost?`${tA(t.daily_input_cost)} | `:""}
+ ${null!==t.monthly_cost?`${tA(t.monthly_input_cost)} | `:""}
+
+
+ | Output Cost |
+ ${tA(t.output_cost_per_request)} |
+ ${null!==t.daily_cost?`${tA(t.daily_output_cost)} | `:""}
+ ${null!==t.monthly_cost?`${tA(t.monthly_output_cost)} | `:""}
+
+
+ | Margin/Fee |
+ ${tA(t.margin_cost_per_request)} |
+ ${null!==t.daily_cost?`${tA(t.daily_margin_cost)} | `:""}
+ ${null!==t.monthly_cost?`${tA(t.monthly_margin_cost)} | `:""}
+
+
+ | Total |
+ ${tA(t.cost_per_request)} |
+ ${null!==t.daily_cost?`${tA(t.daily_cost)} | `:""}
+ ${null!==t.monthly_cost?`${tA(t.monthly_cost)} | `:""}
+
+
+
+ `}).join("")}
+
+
+
+
+ `;t.document.write(l),t.document.close(),t.onload=()=>{t.print()}})(e),a(!1)},children:[(0,t.jsx)(tS.FilePdfOutlined,{className:"mr-3 text-red-500"}),"Export as PDF"]}),(0,t.jsxs)("button",{className:"flex items-center w-full px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors",onClick:()=>{(e=>{let t=e.entries.filter(e=>null!==e.result),s=[["LLM Multi-Model Cost Estimate Report"],["Generated",new Date().toLocaleString()],[""]];for(let a of(s.push(["COMBINED TOTALS"],["Total Per Request",e.totals.cost_per_request.toString()],["Total Daily",e.totals.daily_cost?.toString()||"-"],["Total Monthly",e.totals.monthly_cost?.toString()||"-"],["Margin Per Request",e.totals.margin_per_request.toString()],["Daily Margin",e.totals.daily_margin?.toString()||"-"],["Monthly Margin",e.totals.monthly_margin?.toString()||"-"],[""]),s.push(["Model","Provider","Input Tokens","Output Tokens","Requests/Day","Requests/Month","Cost/Request","Daily Cost","Monthly Cost","Input Cost/Req","Output Cost/Req","Margin/Req"]),t)){let e=a.result;s.push([e.model,e.provider||"-",e.input_tokens.toString(),e.output_tokens.toString(),e.num_requests_per_day?.toString()||"-",e.num_requests_per_month?.toString()||"-",e.cost_per_request.toString(),e.daily_cost?.toString()||"-",e.monthly_cost?.toString()||"-",e.input_cost_per_request.toString(),e.output_cost_per_request.toString(),e.margin_cost_per_request.toString()])}let a=new Blob([s.map(e=>e.map(e=>`"${e}"`).join(",")).join("\n")],{type:"text/csv;charset=utf-8;"}),l=window.URL.createObjectURL(a),r=document.createElement("a");r.href=l,r.download=`cost_estimate_multi_model_${new Date().toISOString().split("T")[0]}.csv`,document.body.appendChild(r),r.click(),document.body.removeChild(r),window.URL.revokeObjectURL(l)})(e),a(!1)},children:[(0,t.jsx)(tL,{className:"mr-3 text-green-600"}),"Export as CSV"]})]})]}):null},tD=e=>null==e?"-":0===e?"$0":e<1e-4?`$${e.toExponential(2)}`:e<1?`$${e.toFixed(4)}`:`$${(0,eO.formatNumberWithCommas)(e,2,!0)}`,tE=({result:e,loading:s,timePeriod:a})=>{let l="day"===a?"Daily":"Monthly",r="day"===a?e.daily_cost:e.monthly_cost,i="day"===a?e.daily_input_cost:e.monthly_input_cost,n="day"===a?e.daily_output_cost:e.monthly_output_cost,o="day"===a?e.daily_margin_cost:e.monthly_margin_cost,d="day"===a?e.num_requests_per_day:e.num_requests_per_month;return(0,t.jsxs)("div",{className:"space-y-3 bg-gray-50 p-4 rounded-lg",children:[s&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-gray-500 text-sm",children:[(0,t.jsx)(eF.Spin,{indicator:(0,t.jsx)(tN.LoadingOutlined,{spin:!0}),size:"small"}),(0,t.jsx)("span",{children:"Updating..."})]}),(0,t.jsxs)("div",{className:"grid grid-cols-4 gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(g.Text,{className:"text-xs text-gray-500 block",children:"Total/Request"}),(0,t.jsx)(g.Text,{className:"text-base font-semibold text-blue-600",children:tD(e.cost_per_request)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(g.Text,{className:"text-xs text-gray-500 block",children:"Input Cost"}),(0,t.jsx)(g.Text,{className:"text-sm",children:tD(e.input_cost_per_request)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(g.Text,{className:"text-xs text-gray-500 block",children:"Output Cost"}),(0,t.jsx)(g.Text,{className:"text-sm",children:tD(e.output_cost_per_request)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(g.Text,{className:"text-xs text-gray-500 block",children:"Margin Fee"}),(0,t.jsx)(g.Text,{className:`text-sm ${e.margin_cost_per_request>0?"text-amber-600":""}`,children:tD(e.margin_cost_per_request)})]})]}),null!==r&&(0,t.jsxs)("div",{className:"grid grid-cols-4 gap-4 pt-2 border-t border-gray-200",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)(g.Text,{className:"text-xs text-gray-500 block",children:[l," Total (",null==d?"-":(0,eO.formatNumberWithCommas)(d,0,!0)," req)"]}),(0,t.jsx)(g.Text,{className:`text-base font-semibold ${"day"===a?"text-green-600":"text-purple-600"}`,children:tD(r)})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(g.Text,{className:"text-xs text-gray-500 block",children:[l," Input"]}),(0,t.jsx)(g.Text,{className:"text-sm",children:tD(i)})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(g.Text,{className:"text-xs text-gray-500 block",children:[l," Output"]}),(0,t.jsx)(g.Text,{className:"text-sm",children:tD(n)})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(g.Text,{className:"text-xs text-gray-500 block",children:[l," Margin Fee"]}),(0,t.jsx)(g.Text,{className:`text-sm ${(o??0)>0?"text-amber-600":""}`,children:tD(o)})]})]}),(e.input_cost_per_token||e.output_cost_per_token)&&(0,t.jsxs)("div",{className:"text-xs text-gray-400 pt-2 border-t border-gray-200",children:["Token Pricing: "," ",e.input_cost_per_token&&(0,t.jsxs)("span",{children:["Input $",(0,eO.formatNumberWithCommas)(1e6*e.input_cost_per_token,2),"/1M"]}),e.input_cost_per_token&&e.output_cost_per_token&&" | ",e.output_cost_per_token&&(0,t.jsxs)("span",{children:["Output $",(0,eO.formatNumberWithCommas)(1e6*e.output_cost_per_token,2),"/1M"]})]})]})},tz=({multiResult:e,timePeriod:s})=>{let[a,l]=(0,i.useState)(new Set),r=e.entries.filter(e=>null!==e.result),o=e.entries.filter(e=>e.loading),d=e.entries.filter(e=>null!==e.error),c=r.length>0,m=o.length>0,u=d.length>0;if(!c&&!m&&!u)return(0,t.jsx)("div",{className:"py-6 text-center border border-dashed border-gray-300 rounded-lg bg-gray-50",children:(0,t.jsx)(g.Text,{className:"text-gray-500",children:"Select models above to see cost estimates"})});if(!c&&m&&!u)return(0,t.jsxs)("div",{className:"py-6 text-center",children:[(0,t.jsx)(eF.Spin,{indicator:(0,t.jsx)(tN.LoadingOutlined,{spin:!0})}),(0,t.jsx)(g.Text,{className:"text-gray-500 block mt-2",children:"Calculating costs..."})]});if(!c&&u)return(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)(F.Divider,{className:"my-4"}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(g.Text,{className:"text-base font-semibold text-gray-900",children:"Cost Estimates"}),m&&(0,t.jsx)(eF.Spin,{indicator:(0,t.jsx)(tN.LoadingOutlined,{spin:!0}),size:"small"})]}),d.map(e=>(0,t.jsxs)("div",{className:"text-sm text-red-600 bg-red-50 p-3 rounded-lg border border-red-200",children:[(0,t.jsxs)("span",{className:"font-medium",children:[e.entry.model||"Unknown model",": "]}),e.error]},e.entry.id))]});let p=e.totals.margin_per_request>0,x="day"===s?"Daily":"Monthly",h=[{title:"Model",dataIndex:"model",key:"model",render:(e,s)=>(0,t.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"font-medium text-sm",children:e}),s.provider&&(0,t.jsx)(I.Tag,{color:"blue",className:"text-xs",children:s.provider}),s.loading&&(0,t.jsx)(eF.Spin,{indicator:(0,t.jsx)(tN.LoadingOutlined,{spin:!0}),size:"small"})]}),s.error&&(0,t.jsxs)("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1 rounded",children:["⚠️ ",s.error]}),s.hasZeroCost&&!s.error&&(0,t.jsx)("div",{className:"text-xs text-amber-600 bg-amber-50 px-2 py-1 rounded",children:"⚠️ No pricing data found for this model. Set base_model in config."})]})},{title:"Per Request",dataIndex:"cost_per_request",key:"cost_per_request",align:"right",render:(e,s)=>s.error?(0,t.jsx)("span",{className:"text-gray-400",children:"-"}):(0,t.jsx)("span",{className:"font-mono text-sm",children:tD(e)})},{title:"Margin Fee",dataIndex:"margin_cost_per_request",key:"margin_cost_per_request",align:"right",render:(e,s)=>s.error?(0,t.jsx)("span",{className:"text-gray-400",children:"-"}):(0,t.jsx)("span",{className:`font-mono text-sm ${(e??0)>0?"text-amber-600":"text-gray-400"}`,children:tD(e)})},{title:x,dataIndex:"day"===s?"daily_cost":"monthly_cost",key:"period_cost",align:"right",render:(e,s)=>s.error?(0,t.jsx)("span",{className:"text-gray-400",children:"-"}):(0,t.jsx)("span",{className:"font-mono text-sm",children:tD(e)})},{title:"",key:"expand",width:40,render:(e,s)=>s.error?null:(0,t.jsx)(n.Button,{size:"xs",variant:"light",onClick:()=>{var e;return e=s.id,void l(t=>{let s=new Set(t);return s.has(e)?s.delete(e):s.add(e),s})},className:"text-gray-400 hover:text-gray-600",children:a.has(s.id)?(0,t.jsx)(tw.DownOutlined,{}):(0,t.jsx)(tk.RightOutlined,{})})}],y=e.entries.filter(e=>e.entry.model).map(e=>({key:e.entry.id,id:e.entry.id,model:e.result?.model||e.entry.model,provider:e.result?.provider,cost_per_request:e.result?.cost_per_request??null,margin_cost_per_request:e.result?.margin_cost_per_request??null,daily_cost:e.result?.daily_cost??null,monthly_cost:e.result?.monthly_cost??null,error:e.error,loading:e.loading,hasZeroCost:e.result&&0===e.result.cost_per_request}));return(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)(F.Divider,{className:"my-4"}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(g.Text,{className:"text-base font-semibold text-gray-900",children:"Cost Estimates"}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[m&&(0,t.jsx)(eF.Spin,{indicator:(0,t.jsx)(tN.LoadingOutlined,{spin:!0}),size:"small"}),(0,t.jsx)(tM,{multiResult:e})]})]}),(0,t.jsxs)(ts.Card,{size:"small",className:"bg-gradient-to-r from-slate-50 to-blue-50 border-slate-200",children:[(0,t.jsxs)(t_.Row,{gutter:[16,8],children:[(0,t.jsx)(tv.Col,{xs:24,sm:12,children:(0,t.jsx)(tg,{title:(0,t.jsx)("span",{className:"text-xs",children:"Total Per Request"}),value:tD(e.totals.cost_per_request),valueStyle:{color:"#1890ff",fontSize:"18px",fontFamily:"monospace"}})}),(0,t.jsx)(tv.Col,{xs:24,sm:12,children:(0,t.jsx)(tg,{title:(0,t.jsxs)("span",{className:"text-xs",children:["Total ",x]}),value:tD("day"===s?e.totals.daily_cost:e.totals.monthly_cost),valueStyle:{color:"day"===s?"#52c41a":"#722ed1",fontSize:"18px",fontFamily:"monospace"}})})]}),p&&(0,t.jsxs)(t_.Row,{gutter:[16,8],className:"mt-3 pt-3 border-t border-slate-200",children:[(0,t.jsxs)(tv.Col,{xs:24,sm:12,children:[(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Margin Fee/Request"}),(0,t.jsx)("div",{className:"text-sm font-mono text-amber-600",children:tD(e.totals.margin_per_request)})]}),(0,t.jsxs)(tv.Col,{xs:24,sm:12,children:[(0,t.jsxs)("div",{className:"text-xs text-gray-500",children:[x," Margin Fee"]}),(0,t.jsx)("div",{className:"text-sm font-mono text-amber-600",children:tD("day"===s?e.totals.daily_margin:e.totals.monthly_margin)})]})]})]}),y.length>0&&(0,t.jsx)(te.Table,{columns:h,dataSource:y,pagination:!1,size:"small",className:"border border-gray-200 rounded-lg",expandable:{expandedRowKeys:Array.from(a),expandedRowRender:e=>{let a=r.find(t=>t.entry.id===e.id);return a?.result?(0,t.jsx)("div",{className:"py-2",children:(0,t.jsx)(tE,{result:a.result,loading:a.loading,timePeriod:s})}):null},showExpandColumn:!1}})]})},tO=()=>({id:`entry-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,model:"",input_tokens:1e3,output_tokens:500,num_requests_per_day:void 0,num_requests_per_month:void 0}),tR=({accessToken:e,models:s})=>{let[a,l]=(0,i.useState)([tO()]),[r,n]=(0,i.useState)("month"),{debouncedFetchForEntry:o,removeEntry:d,getMultiModelResult:c}=function(e){let[t,s]=(0,i.useState)(new Map),a=(0,i.useRef)(new Map),l=(0,i.useCallback)(async t=>{if(!e||!t.model)return void s(e=>{let s=new Map(e);return s.set(t.id,{entry:t,result:null,loading:!1,error:null}),s});s(e=>{let s=new Map(e),a=s.get(t.id);return s.set(t.id,{entry:t,result:a?.result??null,loading:!0,error:null}),s});try{let a=(0,N.getProxyBaseUrl)(),l=a?`${a}/cost/estimate`:"/cost/estimate",r={model:t.model,input_tokens:t.input_tokens||0,output_tokens:t.output_tokens||0,num_requests_per_day:t.num_requests_per_day||null,num_requests_per_month:t.num_requests_per_month||null},i=await fetch(l,{method:"POST",headers:{[(0,N.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(i.ok){let e=await i.json();s(s=>{let a=new Map(s);return a.set(t.id,{entry:t,result:e,loading:!1,error:null}),a})}else{let e=await i.json(),a=e.detail?.error||e.detail||"Failed to estimate cost";s(e=>{let s=new Map(e);return s.set(t.id,{entry:t,result:null,loading:!1,error:a}),s})}}catch(e){console.error("Error estimating cost:",e),s(e=>{let s=new Map(e);return s.set(t.id,{entry:t,result:null,loading:!1,error:"Network error"}),s})}},[e]),r=(0,i.useCallback)(e=>{let t=a.current.get(e.id);t&&clearTimeout(t);let s=setTimeout(()=>{l(e)},500);a.current.set(e.id,s)},[l]),n=(0,i.useCallback)(e=>{let t=a.current.get(e);t&&(clearTimeout(t),a.current.delete(e)),s(t=>{let s=new Map(t);return s.delete(e),s})},[]);return(0,i.useEffect)(()=>{let e=a.current;return()=>{e.forEach(e=>clearTimeout(e)),e.clear()}},[]),{debouncedFetchForEntry:r,removeEntry:n,getMultiModelResult:(0,i.useCallback)(e=>{let s=e.map(e=>{let s=t.get(e.id);return{entry:e,result:s?.result??null,loading:s?.loading??!1,error:s?.error??null}}),a=0,l=null,r=null,i=0,n=null,o=null;for(let e of s)e.result&&(a+=e.result.cost_per_request,i+=e.result.margin_cost_per_request,null!==e.result.daily_cost&&(l=(l??0)+e.result.daily_cost),null!==e.result.daily_margin_cost&&(n=(n??0)+e.result.daily_margin_cost),null!==e.result.monthly_cost&&(r=(r??0)+e.result.monthly_cost),null!==e.result.monthly_margin_cost&&(o=(o??0)+e.result.monthly_margin_cost));return{entries:s,totals:{cost_per_request:a,daily_cost:l,monthly_cost:r,margin_per_request:i,daily_margin:n,monthly_margin:o}}},[t])}}(e),m=(0,i.useCallback)((e,t,s)=>{l(a=>{let l=a.map(a=>a.id===e?{...a,[t]:s}:a),r=l.find(t=>t.id===e);return r&&r.model&&o(r),l})},[o]),u=(0,i.useCallback)(e=>{n(e),l(t=>t.map(t=>({...t,num_requests_per_day:"day"===e?t.num_requests_per_day:void 0,num_requests_per_month:"month"===e?t.num_requests_per_month:void 0})))},[]),p=(0,i.useCallback)(()=>{l(e=>[...e,tO()])},[]),x=(0,i.useCallback)(e=>{l(t=>t.filter(t=>t.id!==e)),d(e)},[d]),h=c(a),g=[{title:"Model",dataIndex:"model",key:"model",width:"35%",render:(e,a)=>(0,t.jsx)(k.Select,{showSearch:!0,placeholder:"Select a model",value:a.model||void 0,onChange:e=>m(a.id,"model",e),optionFilterProp:"label",filterOption:(e,t)=>String(t?.label??"").toLowerCase().includes(e.toLowerCase()),options:s.map(e=>({value:e,label:e})),style:{width:"100%"},size:"small"})},{title:"Input Tokens",dataIndex:"input_tokens",key:"input_tokens",width:"18%",render:(e,s)=>(0,t.jsx)(L.InputNumber,{min:0,value:s.input_tokens,onChange:e=>m(s.id,"input_tokens",e??0),style:{width:"100%"},size:"small",formatter:e=>`${e}`.replace(/\B(?=(\d{3})+(?!\d))/g,",")})},{title:"Output Tokens",dataIndex:"output_tokens",key:"output_tokens",width:"18%",render:(e,s)=>(0,t.jsx)(L.InputNumber,{min:0,value:s.output_tokens,onChange:e=>m(s.id,"output_tokens",e??0),style:{width:"100%"},size:"small",formatter:e=>`${e}`.replace(/\B(?=(\d{3})+(?!\d))/g,",")})},{title:`Requests/${"day"===r?"Day":"Month"}`,dataIndex:"day"===r?"num_requests_per_day":"num_requests_per_month",key:"num_requests",width:"20%",render:(e,s)=>(0,t.jsx)(L.InputNumber,{min:0,value:"day"===r?s.num_requests_per_day:s.num_requests_per_month,onChange:e=>m(s.id,"day"===r?"num_requests_per_day":"num_requests_per_month",e??void 0),style:{width:"100%"},size:"small",placeholder:"-",formatter:e=>e?`${e}`.replace(/\B(?=(\d{3})+(?!\d))/g,","):""})},{title:"",key:"actions",width:50,render:(e,s)=>(0,t.jsx)(V.Button,{type:"text",icon:(0,t.jsx)(tt.DeleteOutlined,{}),onClick:()=>x(s.id),disabled:1===a.length,danger:!0,size:"small"})}];return(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("div",{className:"flex items-center justify-end mb-2",children:(0,t.jsxs)(T.Radio.Group,{value:r,onChange:e=>u(e.target.value),size:"small",optionType:"button",buttonStyle:"solid",children:[(0,t.jsx)(T.Radio.Button,{value:"day",children:"Per Day"}),(0,t.jsx)(T.Radio.Button,{value:"month",children:"Per Month"})]})}),(0,t.jsx)(te.Table,{columns:g,dataSource:a,rowKey:"id",pagination:!1,size:"small",footer:()=>(0,t.jsx)(V.Button,{type:"dashed",onClick:p,icon:(0,t.jsx)(H.PlusOutlined,{}),className:"w-full",children:"Add Another Model"})}),(0,t.jsx)(tz,{multiResult:h,timePeriod:r})]})};var tB=e.i(270377),tq=e.i(778917),t$=e.i(664659);let tU=({items:e,children:s="Docs",className:a=""})=>{let[l,r]=(0,i.useState)(!1),n=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=e=>{n.current&&!n.current.contains(e.target)&&r(!1)};return l&&document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[l]),(0,t.jsxs)("div",{className:`relative inline-block ${a}`,ref:n,children:[(0,t.jsxs)("button",{type:"button",onClick:()=>r(!l),className:"inline-flex items-center gap-1 text-gray-500 hover:text-gray-700 text-xs transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1 rounded px-2 py-1","aria-expanded":l,"aria-haspopup":"true",children:[(0,t.jsx)("span",{children:s}),(0,t.jsx)(t$.ChevronDown,{className:`h-3 w-3 transition-transform ${l?"rotate-180":""}`,"aria-hidden":"true"})]}),l&&(0,t.jsx)("div",{className:"absolute right-0 mt-1 w-56 bg-white rounded-lg shadow-lg border border-gray-200 py-1 z-50",children:e.map((e,s)=>(0,t.jsxs)("a",{href:e.href,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-between px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors",onClick:()=>r(!1),children:[(0,t.jsx)("span",{children:e.label}),(0,t.jsx)(tq.ExternalLink,{className:"h-3.5 w-3.5 text-gray-400 flex-shrink-0 ml-2","aria-hidden":"true"})]},s))})]})};var tV=e.i(673709);let tH=()=>{let[e,s]=(0,i.useState)(""),[a,l]=(0,i.useState)(""),r=(0,i.useMemo)(()=>{let t=parseFloat(e),s=parseFloat(a);if(isNaN(t)||isNaN(s)||0===t||0===s)return null;let l=t+s,r=s/l*100;return{originalCost:l.toFixed(10),finalCost:t.toFixed(10),discountAmount:s.toFixed(10),discountPercentage:r.toFixed(2)}},[e,a]);return(0,t.jsxs)("div",{className:"space-y-4 pt-2",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(g.Text,{className:"font-medium text-gray-900 text-sm mb-1",children:"Cost Calculation"}),(0,t.jsxs)(g.Text,{className:"text-xs text-gray-600",children:["Discounts are applied to provider costs: ",(0,t.jsx)("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs",children:"final_cost = base_cost × (1 - discount%/100)"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(g.Text,{className:"font-medium text-gray-900 text-sm mb-1",children:"Example"}),(0,t.jsx)(g.Text,{className:"text-xs text-gray-600",children:"A 5% discount on a $10.00 request results in: $10.00 × (1 - 0.05) = $9.50"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(g.Text,{className:"font-medium text-gray-900 text-sm mb-1",children:"Valid Range"}),(0,t.jsx)(g.Text,{className:"text-xs text-gray-600",children:"Discount percentages must be between 0% and 100%"})]}),(0,t.jsxs)("div",{className:"pt-4 border-t border-gray-200",children:[(0,t.jsx)(g.Text,{className:"font-medium text-gray-900 text-sm mb-2",children:"Validating Discounts"}),(0,t.jsx)(g.Text,{className:"text-xs text-gray-600 mb-3",children:"Make a test request and check the response headers to verify discounts are applied:"}),(0,t.jsx)(tV.default,{language:"bash",code:`curl -X POST -i http://your-proxy:4000/chat/completions \\
+ -H "Content-Type: application/json" \\
+ -H "Authorization: Bearer sk-1234" \\
+ -d '{
+ "model": "gemini/gemini-2.5-pro",
+ "messages": [{"role": "user", "content": "Hello"}]
+ }'`}),(0,t.jsx)(g.Text,{className:"text-xs text-gray-600 mt-3 mb-2",children:"Look for these headers in the response:"}),(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("code",{className:"bg-gray-100 px-2 py-1 rounded text-xs font-mono text-gray-800 whitespace-nowrap",children:"x-litellm-response-cost"}),(0,t.jsx)(g.Text,{className:"text-xs text-gray-600",children:"Final cost after discount"})]}),(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("code",{className:"bg-gray-100 px-2 py-1 rounded text-xs font-mono text-gray-800 whitespace-nowrap",children:"x-litellm-response-cost-original"}),(0,t.jsx)(g.Text,{className:"text-xs text-gray-600",children:"Original cost before discount"})]}),(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("code",{className:"bg-gray-100 px-2 py-1 rounded text-xs font-mono text-gray-800 whitespace-nowrap",children:"x-litellm-response-cost-discount-amount"}),(0,t.jsx)(g.Text,{className:"text-xs text-gray-600",children:"Amount discounted"})]})]})]}),(0,t.jsxs)("div",{className:"pt-4 border-t border-gray-200",children:[(0,t.jsx)(g.Text,{className:"font-medium text-gray-900 text-sm mb-3",children:"Discount Calculator"}),(0,t.jsx)(g.Text,{className:"text-xs text-gray-600 mb-3",children:"Enter values from your response headers to verify the discount:"}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mb-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs font-medium text-gray-700 mb-1",children:"Response Cost (x-litellm-response-cost)"}),(0,t.jsx)(eQ.TextInput,{placeholder:"0.0171938125",value:e,onValueChange:s,className:"text-sm"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs font-medium text-gray-700 mb-1",children:"Discount Amount (x-litellm-response-cost-discount-amount)"}),(0,t.jsx)(eQ.TextInput,{placeholder:"0.0009049375",value:a,onValueChange:l,className:"text-sm"})]})]}),r&&(0,t.jsxs)("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4",children:[(0,t.jsx)(g.Text,{className:"text-sm font-medium text-blue-900 mb-2",children:"Calculated Results"}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(g.Text,{className:"text-xs text-blue-800",children:"Original Cost:"}),(0,t.jsxs)("code",{className:"text-xs font-mono text-blue-900",children:["$",r.originalCost]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(g.Text,{className:"text-xs text-blue-800",children:"Final Cost:"}),(0,t.jsxs)("code",{className:"text-xs font-mono text-blue-900",children:["$",r.finalCost]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(g.Text,{className:"text-xs text-blue-800",children:"Discount Amount:"}),(0,t.jsxs)("code",{className:"text-xs font-mono text-blue-900",children:["$",r.discountAmount]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between pt-2 border-t border-blue-300",children:[(0,t.jsx)(g.Text,{className:"text-xs font-semibold text-blue-900",children:"Discount Applied:"}),(0,t.jsxs)(g.Text,{className:"text-sm font-bold text-blue-900",children:[r.discountPercentage,"%"]})]})]})]})]})]})};var tG=e.i(689020);let tK=[{label:"Custom pricing for models",href:"https://docs.litellm.ai/docs/proxy/custom_pricing"},{label:"Spend tracking",href:"https://docs.litellm.ai/docs/proxy/cost_tracking"}],tW=({userID:e,userRole:s,accessToken:a})=>{let[l,r]=(0,i.useState)(void 0),[o,d]=(0,i.useState)(""),[c,m]=(0,i.useState)(!0),[u,p]=(0,i.useState)(!1),[x,h]=(0,i.useState)(!1),[j,f]=(0,i.useState)(void 0),[b,_]=(0,i.useState)("percentage"),[v,k]=(0,i.useState)(""),[C,S]=(0,i.useState)(""),[T,I]=(0,i.useState)([]),[F]=w.Form.useForm(),[L]=w.Form.useForm(),[A,P]=y.Modal.useModal(),M="proxy_admin"===s||"Admin"===s,{discountConfig:D,fetchDiscountConfig:E,handleAddProvider:z,handleRemoveProvider:O,handleDiscountChange:R}=function({accessToken:e}){let[t,s]=(0,i.useState)({}),a=(0,i.useCallback)(async()=>{try{let t=(0,N.getProxyBaseUrl)(),a=t?`${t}/config/cost_discount_config`:"/config/cost_discount_config",l=await fetch(a,{method:"GET",headers:{[(0,N.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(l.ok){let e=await l.json();s(e.values||{})}else console.error("Failed to fetch discount config")}catch(e){console.error("Error fetching discount config:",e),ez.default.fromBackend("Failed to fetch discount configuration")}},[e]),l=(0,i.useCallback)(async t=>{try{let s=(0,N.getProxyBaseUrl)(),l=s?`${s}/config/cost_discount_config`:"/config/cost_discount_config",r=await fetch(l,{method:"PATCH",headers:{[(0,N.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(r.ok)ez.default.success("Discount configuration updated successfully"),await a();else{let e=await r.json(),t=e.detail?.error||e.detail||"Failed to update settings";ez.default.fromBackend(t)}}catch(e){console.error("Error updating discount config:",e),ez.default.fromBackend("Failed to update discount configuration")}},[e,a]),r=(0,i.useCallback)(async(e,a)=>{if(!e||!a)return ez.default.fromBackend("Please select a provider and enter discount percentage"),!1;let r=parseFloat(a);if(isNaN(r)||r<0||r>100)return ez.default.fromBackend("Discount must be between 0% and 100%"),!1;let i=e5(e);if(!i)return ez.default.fromBackend("Invalid provider selected"),!1;if(t[i])return ez.default.fromBackend(`Discount for ${e2.Providers[e]} already exists. Edit it in the table above.`),!1;let n={...t,[i]:r/100};return s(n),await l(n),!0},[t,l]),n=(0,i.useCallback)(async e=>{let a={...t};delete a[e],s(a),await l(a)},[t,l]),o=(0,i.useCallback)(async(e,a)=>{let r=parseFloat(a);if(!isNaN(r)&&r>=0&&r<=1){let a={...t,[e]:r};s(a),await l(a)}},[t,l]);return{discountConfig:t,setDiscountConfig:s,fetchDiscountConfig:a,saveDiscountConfig:l,handleAddProvider:r,handleRemoveProvider:n,handleDiscountChange:o}}({accessToken:a}),{marginConfig:B,fetchMarginConfig:q,handleAddMargin:$,handleRemoveMargin:U,handleMarginChange:V}=function({accessToken:e}){let[t,s]=(0,i.useState)({}),a=(0,i.useCallback)(async()=>{try{let t=(0,N.getProxyBaseUrl)(),a=t?`${t}/config/cost_margin_config`:"/config/cost_margin_config",l=await fetch(a,{method:"GET",headers:{[(0,N.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(l.ok){let e=await l.json();s(e.values||{})}else console.error("Failed to fetch margin config")}catch(e){console.error("Error fetching margin config:",e),ez.default.fromBackend("Failed to fetch margin configuration")}},[e]),l=(0,i.useCallback)(async t=>{try{let s=(0,N.getProxyBaseUrl)(),l=s?`${s}/config/cost_margin_config`:"/config/cost_margin_config",r=await fetch(l,{method:"PATCH",headers:{[(0,N.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(r.ok)ez.default.success("Margin configuration updated successfully"),await a();else{let e=await r.json(),t=e.detail?.error||e.detail||"Failed to update settings";ez.default.fromBackend(t)}}catch(e){console.error("Error updating margin config:",e),ez.default.fromBackend("Failed to update margin configuration")}},[e,a]),r=(0,i.useCallback)(async e=>{let a,r,{selectedProvider:i,marginType:n,percentageValue:o,fixedAmountValue:d}=e;if(!i)return ez.default.fromBackend("Please select a provider"),!1;if("global"===i)a="global";else{let e=e5(i);if(!e)return ez.default.fromBackend("Invalid provider selected"),!1;a=e}if(t[a]){let e="global"===a?"Global":e2.Providers[i];return ez.default.fromBackend(`Margin for ${e} already exists. Edit it in the table above.`),!1}if("percentage"===n){let e=parseFloat(o);if(isNaN(e)||e<0||e>1e3)return ez.default.fromBackend("Percentage must be between 0% and 1000%"),!1;r=e/100}else{let e=parseFloat(d);if(isNaN(e)||e<0)return ez.default.fromBackend("Fixed amount must be non-negative"),!1;r={fixed_amount:e}}let c={...t,[a]:r};return s(c),await l(c),!0},[t,l]),n=(0,i.useCallback)(async e=>{let a={...t};delete a[e],s(a),await l(a)},[t,l]),o=(0,i.useCallback)(async(e,a)=>{let r={...t,[e]:a};s(r),await l(r)},[t,l]);return{marginConfig:t,setMarginConfig:s,fetchMarginConfig:a,saveMarginConfig:l,handleAddMargin:r,handleRemoveMargin:n,handleMarginChange:o}}({accessToken:a});(0,i.useEffect)(()=>{a&&(Promise.all([E(),q()]).finally(()=>{m(!1)}),(async()=>{try{let e=await (0,tG.fetchAvailableModels)(a);I(e.map(e=>e.model_group))}catch(e){console.error("Error fetching models:",e)}})())},[a,E,q]);let H=async()=>{await z(l,o)&&(r(void 0),d(""),p(!1))},G=async(e,s)=>{A.confirm({title:"Remove Provider Discount",icon:(0,t.jsx)(tB.ExclamationCircleOutlined,{}),content:`Are you sure you want to remove the discount for ${s}?`,okText:"Remove",okType:"danger",cancelText:"Cancel",onOk:()=>O(e)})},K=async()=>{await $({selectedProvider:j,marginType:b,percentageValue:v,fixedAmountValue:C})&&(f(void 0),k(""),S(""),_("percentage"),h(!1))},W=async(e,s)=>{A.confirm({title:"Remove Provider Margin",icon:(0,t.jsx)(tB.ExclamationCircleOutlined,{}),content:`Are you sure you want to remove the margin for ${s}?`,okText:"Remove",okType:"danger",cancelText:"Cancel",onOk:()=>U(e)})};return a?(0,t.jsxs)("div",{className:"w-full p-8",children:[P,(0,t.jsx)("div",{className:"flex flex-col md:flex-row items-start md:items-center justify-between mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(ew.Title,{children:"Cost Tracking Settings"}),(0,t.jsx)(tU,{items:tK})]}),(0,t.jsx)(g.Text,{className:"text-gray-500 mt-1",children:"Configure cost discounts and margins for different LLM providers. Changes are saved automatically."})]})}),(0,t.jsxs)("div",{className:"bg-white rounded-lg shadow w-full max-w-full space-y-4",children:[M&&(0,t.jsxs)(eG.Accordion,{children:[(0,t.jsx)(eK.AccordionHeader,{className:"px-6 py-4",children:(0,t.jsxs)("div",{className:"flex flex-col items-start w-full",children:[(0,t.jsx)(g.Text,{className:"text-lg font-semibold text-gray-900",children:"Provider Discounts"}),(0,t.jsx)(g.Text,{className:"text-sm text-gray-500 mt-1",children:"Apply percentage-based discounts to reduce costs for specific providers"})]})}),(0,t.jsx)(eW.AccordionBody,{className:"px-0",children:(0,t.jsxs)(eC.TabGroup,{children:[(0,t.jsxs)(eS.TabList,{className:"px-6 pt-4",children:[(0,t.jsx)(ek.Tab,{children:"Discounts"}),(0,t.jsx)(ek.Tab,{children:"Test It"})]}),(0,t.jsxs)(eI.TabPanels,{children:[(0,t.jsx)(eT.TabPanel,{children:(0,t.jsxs)("div",{className:"p-6",children:[(0,t.jsx)("div",{className:"flex justify-end mb-4",children:(0,t.jsx)(n.Button,{onClick:()=>p(!0),children:"+ Add Provider Discount"})}),c?(0,t.jsx)("div",{className:"py-12 text-center",children:(0,t.jsx)(g.Text,{className:"text-gray-500",children:"Loading configuration..."})}):Object.keys(D).length>0?(0,t.jsx)(e3,{discountConfig:D,onDiscountChange:R,onRemoveProvider:G}):(0,t.jsxs)("div",{className:"py-16 px-6 text-center",children:[(0,t.jsx)("svg",{className:"mx-auto h-12 w-12 text-gray-400 mb-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,t.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),(0,t.jsx)(g.Text,{className:"text-gray-700 font-medium mb-2",children:"No provider discounts configured"}),(0,t.jsx)(g.Text,{className:"text-gray-500 text-sm",children:'Click "Add Provider Discount" to get started'})]})]})}),(0,t.jsx)(eT.TabPanel,{children:(0,t.jsx)("div",{className:"px-6 pb-4",children:(0,t.jsx)(tH,{})})})]})]})})]}),M&&(0,t.jsxs)(eG.Accordion,{children:[(0,t.jsx)(eK.AccordionHeader,{className:"px-6 py-4",children:(0,t.jsxs)("div",{className:"flex flex-col items-start w-full",children:[(0,t.jsx)(g.Text,{className:"text-lg font-semibold text-gray-900",children:"Fee/Price Margin"}),(0,t.jsx)(g.Text,{className:"text-sm text-gray-500 mt-1",children:"Add fees or margins to LLM costs for internal billing and cost recovery"})]})}),(0,t.jsx)(eW.AccordionBody,{className:"px-0",children:(0,t.jsxs)("div",{className:"p-6",children:[(0,t.jsx)("div",{className:"flex justify-end mb-4",children:(0,t.jsx)(n.Button,{onClick:()=>h(!0),children:"+ Add Provider Margin"})}),c?(0,t.jsx)("div",{className:"py-12 text-center",children:(0,t.jsx)(g.Text,{className:"text-gray-500",children:"Loading configuration..."})}):Object.keys(B).length>0?(0,t.jsx)(e7,{marginConfig:B,onMarginChange:V,onRemoveProvider:W}):(0,t.jsxs)("div",{className:"py-16 px-6 text-center",children:[(0,t.jsx)("svg",{className:"mx-auto h-12 w-12 text-gray-400 mb-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,t.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),(0,t.jsx)(g.Text,{className:"text-gray-700 font-medium mb-2",children:"No provider margins configured"}),(0,t.jsx)(g.Text,{className:"text-gray-500 text-sm",children:'Click "Add Provider Margin" to get started'})]})]})})]}),(0,t.jsxs)(eG.Accordion,{defaultOpen:!0,children:[(0,t.jsx)(eK.AccordionHeader,{className:"px-6 py-4",children:(0,t.jsxs)("div",{className:"flex flex-col items-start w-full",children:[(0,t.jsx)(g.Text,{className:"text-lg font-semibold text-gray-900",children:"Pricing Calculator"}),(0,t.jsx)(g.Text,{className:"text-sm text-gray-500 mt-1",children:"Estimate LLM costs based on expected token usage and request volume"})]})}),(0,t.jsx)(eW.AccordionBody,{className:"px-0",children:(0,t.jsx)("div",{className:"p-6",children:(0,t.jsx)(tR,{accessToken:a,models:T})})})]})]}),(0,t.jsx)(y.Modal,{title:(0,t.jsx)("div",{className:"flex items-center space-x-3 pb-4 border-b border-gray-100",children:(0,t.jsx)("h2",{className:"text-xl font-semibold text-gray-900",children:"Add Provider Discount"})}),open:u,width:1e3,onCancel:()=>{p(!1),F.resetFields(),r(void 0),d("")},footer:null,className:"top-8",styles:{body:{padding:"24px"},header:{padding:"24px 24px 0 24px",border:"none"}},children:(0,t.jsxs)("div",{className:"mt-6",children:[(0,t.jsx)(g.Text,{className:"text-sm text-gray-600 mb-6",children:"Select a provider and set its discount percentage. Enter a value between 0% and 100% (e.g., 5 for a 5% discount)."}),(0,t.jsx)(w.Form,{form:F,onFinish:()=>{H()},layout:"vertical",className:"space-y-6",children:(0,t.jsx)(e8,{discountConfig:D,selectedProvider:l,newDiscount:o,onProviderChange:r,onDiscountChange:d,onAddProvider:H})})]})}),(0,t.jsx)(y.Modal,{title:(0,t.jsx)("div",{className:"flex items-center space-x-3 pb-4 border-b border-gray-100",children:(0,t.jsx)("h2",{className:"text-xl font-semibold text-gray-900",children:"Add Provider Margin"})}),open:x,width:1e3,onCancel:()=>{h(!1),L.resetFields(),f(void 0),k(""),S(""),_("percentage")},footer:null,className:"top-8",styles:{body:{padding:"24px"},header:{padding:"24px 24px 0 24px",border:"none"}},children:(0,t.jsxs)("div",{className:"mt-6",children:[(0,t.jsx)(g.Text,{className:"text-sm text-gray-600 mb-6",children:'Select a provider (or "Global" for all providers) and configure the margin. You can use percentage-based or fixed amount.'}),(0,t.jsx)(w.Form,{form:L,layout:"vertical",className:"space-y-6",children:(0,t.jsx)(e9,{marginConfig:B,selectedProvider:j,marginType:b,percentageValue:v,fixedAmountValue:C,onProviderChange:f,onMarginTypeChange:_,onPercentageChange:k,onFixedAmountChange:S,onAddProvider:K})})]})})]}):null};var tQ=e.i(226898),tY=e.i(973706),tJ=e.i(447566),tX=e.i(602073),tZ=e.i(313603),t0=e.i(285027),t1=e.i(266027),t2=e.i(653496),t4=e.i(149192),t5=e.i(788191);let t6=`Evaluate whether this guardrail's decision was correct.
+Analyze the user input, the guardrail action taken, and determine if it was appropriate.
+
+Consider:
+— Was the user's intent genuinely harmful or policy-violating?
+— Was the guardrail's action (block / flag / pass) appropriate?
+— Could this be a false positive or false negative?
+
+Return a structured verdict with confidence and justification.`,t3=`{
+ "verdict": "correct" | "false_positive" | "false_negative",
+ "confidence": 0.0,
+ "justification": "string",
+ "risk_category": "string",
+ "suggested_action": "keep" | "adjust threshold" | "add allowlist"
+}
+`;function t8({open:e,onClose:s,guardrailName:a,accessToken:l,onRunEvaluation:r}){let[n,o]=(0,i.useState)(t6),[d,c]=(0,i.useState)(t3),[m,u]=(0,i.useState)(null),[p,x]=(0,i.useState)([]),[h,g]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!e||!l)return void x([]);let t=!1;return g(!0),(0,tG.fetchAvailableModels)(l).then(e=>{t||x(e)}).catch(()=>{t||x([])}).finally(()=>{t||g(!1)}),()=>{t=!0}},[e,l]);let j=p.map(e=>({value:e.model_group,label:e.model_group}));return(0,t.jsxs)(y.Modal,{title:"Evaluation Settings",open:e,onCancel:s,width:640,footer:null,closeIcon:(0,t.jsx)(t4.CloseOutlined,{}),destroyOnClose:!0,children:[(0,t.jsx)("p",{className:"text-sm text-gray-500 mb-4",children:a?`Configure AI evaluation for ${a}`:"Configure AI evaluation for re-running on logs"}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-1.5",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Evaluation Prompt"}),(0,t.jsx)("button",{type:"button",onClick:()=>o(t6),className:"text-xs text-indigo-600 hover:text-indigo-700",children:"Reset to default"})]}),(0,t.jsx)(C.Input.TextArea,{value:n,onChange:e=>o(e.target.value),rows:6,className:"font-mono text-sm"}),(0,t.jsx)("p",{className:"text-xs text-gray-400 mt-1",children:"System prompt sent to the evaluation model. Output is structured via response_format."})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1.5",children:"Response Schema"}),(0,t.jsx)("p",{className:"text-xs text-gray-400 mb-1",children:"response_format: json_schema"}),(0,t.jsx)(C.Input.TextArea,{value:d,onChange:e=>c(e.target.value),rows:6,className:"font-mono text-sm"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1.5",children:"Model"}),(0,t.jsx)(k.Select,{placeholder:h?"Loading models…":"Select a model",value:m??void 0,onChange:u,options:j,style:{width:"100%"},showSearch:!0,optionFilterProp:"label",loading:h,notFoundContent:l?"No models available":"Sign in to see models"})]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-end gap-2 mt-6 pt-4 border-t border-gray-100",children:[(0,t.jsx)(V.Button,{onClick:s,children:"Cancel"}),(0,t.jsx)(V.Button,{type:"primary",icon:(0,t.jsx)(t5.PlayCircleOutlined,{}),onClick:()=>{m&&(r?.({prompt:n,schema:d,model:m}),s())},disabled:!m,children:"Run Evaluation"})]})]})}var t7=e.i(166540);e.i(3565);var t9=e.i(502626);let se={blocked:{icon:t4.CloseOutlined,color:"text-red-600",bg:"bg-red-50",border:"border-red-200",label:"Blocked"},passed:{icon:v.CheckCircleOutlined,color:"text-green-600",bg:"bg-green-50",border:"border-green-200",label:"Passed"},flagged:{icon:t0.WarningOutlined,color:"text-amber-600",bg:"bg-amber-50",border:"border-amber-200",label:"Flagged"}};function st({guardrailName:e,filterAction:s="all",logs:a=[],logsLoading:l=!1,totalLogs:r,accessToken:n=null,startDate:o="",endDate:d=""}){let[c,m]=(0,i.useState)(10),[u,p]=(0,i.useState)(s),[x,h]=(0,i.useState)(null),[g,y]=(0,i.useState)(!1),j=a.filter(e=>"all"===u||e.action===u).slice(0,c),f=r??a.length,b=o?(0,t7.default)(o).utc().format("YYYY-MM-DD HH:mm:ss"):(0,t7.default)().subtract(24,"hours").utc().format("YYYY-MM-DD HH:mm:ss"),_=d?(0,t7.default)(d).utc().endOf("day").format("YYYY-MM-DD HH:mm:ss"):(0,t7.default)().utc().format("YYYY-MM-DD HH:mm:ss"),{data:v}=(0,t1.useQuery)({queryKey:["spend-log-by-request",x,b,_],queryFn:async()=>n&&x?await (0,N.uiSpendLogsCall)({accessToken:n,start_date:b,end_date:_,page:1,page_size:10,params:{request_id:x}}):null,enabled:!!(n&&x&&g)}),w=v?.data?.[0]??null;return(0,t.jsxs)("div",{className:"bg-white border border-gray-200 rounded-lg",children:[(0,t.jsx)("div",{className:"p-4 border-b border-gray-200",children:(0,t.jsxs)("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h3",{className:"text-base font-semibold text-gray-900",children:e?`Logs — ${e}`:"Request Logs"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:l?"Loading…":a.length>0?`Showing ${j.length} of ${f} entries`:"No logs for this period. Select a guardrail and date range."})]}),a.length>0&&(0,t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,t.jsx)("div",{className:"flex items-center gap-1",children:["all","blocked","flagged","passed"].map(e=>(0,t.jsx)(V.Button,{type:u===e?"primary":"default",size:"small",onClick:()=>p(e),children:e.charAt(0).toUpperCase()+e.slice(1)},e))}),(0,t.jsx)("div",{className:"h-4 w-px bg-gray-200"}),(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)("span",{className:"text-xs text-gray-500 mr-1",children:"Sample:"}),[10,50,100].map(e=>(0,t.jsx)(V.Button,{type:c===e?"primary":"default",size:"small",onClick:()=>m(e),children:e},e))]})]})]})}),l&&(0,t.jsx)("div",{className:"flex items-center justify-center py-12",children:(0,t.jsx)(eF.Spin,{})}),!l&&0===j.length&&(0,t.jsx)("div",{className:"py-12 text-center text-sm text-gray-500",children:"No logs to display. Adjust filters or date range."}),!l&&j.length>0&&(0,t.jsx)("div",{className:"divide-y divide-gray-100",children:j.map(e=>{let s=se[e.action],a=s.icon;return(0,t.jsxs)("button",{type:"button",onClick:()=>{h(e.id),y(!0)},className:"w-full text-left px-4 py-3 hover:bg-gray-50 transition-colors flex items-start gap-3",children:[(0,t.jsx)(a,{className:`w-4 h-4 mt-0.5 flex-shrink-0 ${s.color}`}),(0,t.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[(0,t.jsx)("span",{className:`inline-flex items-center px-2 py-0.5 text-xs font-medium rounded border ${s.bg} ${s.color} ${s.border}`,children:s.label}),(0,t.jsx)("span",{className:"text-xs text-gray-400",children:e.timestamp}),(0,t.jsx)("span",{className:"text-xs text-gray-400",children:"·"}),e.model&&(0,t.jsx)("span",{className:"text-xs text-gray-500",children:e.model})]}),(0,t.jsx)("p",{className:"text-sm text-gray-800 truncate",children:e.input_snippet??e.input??"—"})]}),(0,t.jsx)(tw.DownOutlined,{className:"w-4 h-4 text-gray-400 flex-shrink-0 mt-1"})]},e.id)})}),(0,t.jsx)(t9.LogDetailsDrawer,{open:g,onClose:()=>{y(!1),h(null)},logEntry:w,accessToken:n,allLogs:w?[w]:[],startTime:b})]})}function ss({label:e,value:s,valueColor:a="text-gray-900",icon:l,subtitle:r}){return(0,t.jsxs)("div",{className:"h-full bg-white border border-gray-200 rounded-lg p-5 flex flex-col",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-600",children:e}),l&&(0,t.jsx)("span",{className:"text-gray-400",children:l})]}),(0,t.jsx)("div",{className:`text-3xl font-semibold ${a} tracking-tight`,children:s}),r&&(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:r})]})}let sa={healthy:{bg:"bg-green-50",text:"text-green-700",dot:"bg-green-500"},warning:{bg:"bg-amber-50",text:"text-amber-700",dot:"bg-amber-500"},critical:{bg:"bg-red-50",text:"text-red-700",dot:"bg-red-500"}};function sl({guardrailId:e,onBack:s,accessToken:a=null,startDate:l,endDate:r}){let[n,o]=(0,i.useState)("overview"),[d,c]=(0,i.useState)(!1),[m,u]=(0,i.useState)(1),{data:p,isLoading:x,error:h}=(0,t1.useQuery)({queryKey:["guardrails-usage-detail",e,l,r],queryFn:()=>(0,N.getGuardrailsUsageDetail)(a,e,l,r),enabled:!!a&&!!e}),{data:g,isLoading:y}=(0,t1.useQuery)({queryKey:["guardrails-usage-logs",e,m,50],queryFn:()=>(0,N.getGuardrailsUsageLogs)(a,{guardrailId:e,page:m,pageSize:50,startDate:l,endDate:r}),enabled:!!a&&!!e}),j=(0,i.useMemo)(()=>(g?.logs??[]).map(e=>({id:e.id,timestamp:e.timestamp,action:e.action,score:e.score,model:e.model,input_snippet:e.input_snippet,output_snippet:e.output_snippet,reason:e.reason})),[g?.logs]),f=p?{name:p.guardrail_name,description:p.description??"",status:p.status,provider:p.provider,type:p.type,requestsEvaluated:p.requestsEvaluated,failRate:p.failRate,avgScore:p.avgScore,avgLatency:p.avgLatency}:{name:e,description:"",status:"healthy",provider:"—",type:"—",requestsEvaluated:0,failRate:0,avgScore:void 0,avgLatency:void 0},b=sa[f.status]??sa.healthy;return x&&!p?(0,t.jsx)("div",{className:"flex items-center justify-center py-12",children:(0,t.jsx)(eF.Spin,{size:"large"})}):h&&!p?(0,t.jsxs)("div",{children:[(0,t.jsx)(V.Button,{type:"link",icon:(0,t.jsx)(tJ.ArrowLeftOutlined,{}),onClick:s,className:"pl-0 mb-4",children:"Back to Overview"}),(0,t.jsx)("p",{className:"text-red-600",children:"Failed to load guardrail details."})]}):(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsx)(V.Button,{type:"link",icon:(0,t.jsx)(tJ.ArrowLeftOutlined,{}),onClick:s,className:"pl-0 mb-4",children:"Back to Overview"}),(0,t.jsxs)("div",{className:"flex items-start justify-between",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-3 mb-1",children:[(0,t.jsx)(tX.SafetyOutlined,{className:"text-xl text-gray-400"}),(0,t.jsx)("h1",{className:"text-xl font-semibold text-gray-900",children:f.name}),(0,t.jsxs)("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-0.5 text-xs font-medium rounded-full ${b.bg} ${b.text}`,children:[(0,t.jsx)("span",{className:`w-1.5 h-1.5 rounded-full ${b.dot}`}),f.status.charAt(0).toUpperCase()+f.status.slice(1)]})]}),(0,t.jsx)("p",{className:"text-sm text-gray-500 ml-8",children:f.description})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"inline-flex items-center px-2.5 py-1 text-xs font-medium rounded-md bg-indigo-50 text-indigo-700 border border-indigo-200",children:f.provider}),(0,t.jsx)(V.Button,{type:"default",icon:(0,t.jsx)(tZ.SettingOutlined,{}),onClick:()=>c(!0),title:"Evaluation settings"})]})]})]}),(0,t.jsx)(t2.Tabs,{activeKey:n,onChange:o,items:[{key:"overview",label:"Overview"},{key:"logs",label:"Logs"}]}),"overview"===n&&(0,t.jsxs)("div",{className:"space-y-6 mt-4",children:[(0,t.jsxs)(t_.Row,{gutter:[16,16],children:[(0,t.jsx)(tv.Col,{xs:12,md:8,children:(0,t.jsx)(ss,{label:"Requests Evaluated",value:f.requestsEvaluated.toLocaleString()})}),(0,t.jsx)(tv.Col,{xs:12,md:8,children:(0,t.jsx)(ss,{label:"Fail Rate",value:`${f.failRate}%`,valueColor:f.failRate>15?"text-red-600":f.failRate>5?"text-amber-600":"text-green-600",subtitle:`${Math.round(f.requestsEvaluated*f.failRate/100).toLocaleString()} blocked`,icon:f.failRate>15?(0,t.jsx)(t0.WarningOutlined,{className:"text-red-400"}):void 0})}),(0,t.jsx)(tv.Col,{xs:12,md:8,children:(0,t.jsx)(ss,{label:"Avg. latency added",value:null!=f.avgLatency?`${Math.round(f.avgLatency)}ms`:"—",valueColor:null!=f.avgLatency?f.avgLatency>150?"text-red-600":f.avgLatency>50?"text-amber-600":"text-green-600":"text-gray-500",subtitle:null!=f.avgLatency?"Per request (avg)":"No data"})})]}),(0,t.jsx)(st,{guardrailName:f.name,filterAction:"all",logs:j,logsLoading:y,totalLogs:g?.total??0,accessToken:a,startDate:l,endDate:r})]}),"logs"===n&&(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(st,{guardrailName:f.name,logs:j,logsLoading:y,totalLogs:g?.total??0,accessToken:a,startDate:l,endDate:r})}),(0,t.jsx)(t8,{open:d,onClose:()=>c(!1),guardrailName:f.name,accessToken:a})]})}let sr={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M917 211.1l-199.2 24c-6.6.8-9.4 8.9-4.7 13.6l59.3 59.3-226 226-101.8-101.7c-6.3-6.3-16.4-6.2-22.6 0L100.3 754.1a8.03 8.03 0 000 11.3l45 45.2c3.1 3.1 8.2 3.1 11.3 0L433.3 534 535 635.7c6.3 6.2 16.4 6.2 22.6 0L829 364.5l59.3 59.3a8.01 8.01 0 0013.6-4.7l24-199.2c.7-5.1-3.7-9.5-8.9-8.8z"}}]},name:"rise",theme:"outlined"};var si=i.forwardRef(function(e,t){return i.createElement(tF.default,(0,tT.default)({},e,{ref:t,icon:sr}))}),sn=e.i(898586),so=e.i(584935);function sd({data:e}){let s=e&&e.length>0?e:[];return(0,t.jsxs)(o.Card,{className:"bg-white border border-gray-200",children:[(0,t.jsx)(ew.Title,{className:"text-base font-semibold text-gray-900 mb-4",children:"Request Outcomes Over Time"}),(0,t.jsx)("div",{className:"h-80 min-h-[280px]",children:s.length>0?(0,t.jsx)(so.BarChart,{data:s,index:"date",categories:["passed","blocked"],colors:["green","red"],valueFormatter:e=>e.toLocaleString(),yAxisWidth:48,showLegend:!0,stack:!0}):(0,t.jsx)("div",{className:"flex items-center justify-center h-full text-sm text-gray-500",children:"No chart data for this period"})})]})}let sc={Bedrock:"bg-orange-100 text-orange-700 border-orange-200","Google Cloud":"bg-sky-100 text-sky-700 border-sky-200",LiteLLM:"bg-indigo-100 text-indigo-700 border-indigo-200",Custom:"bg-gray-100 text-gray-600 border-gray-200"};function sm({accessToken:e=null,startDate:s,endDate:a,onSelectGuardrail:l}){let[r,n]=(0,i.useState)("failRate"),[o,d]=(0,i.useState)("desc"),[c,m]=(0,i.useState)(!1),{data:u,isLoading:p,error:x}=(0,t1.useQuery)({queryKey:["guardrails-usage-overview",s,a],queryFn:()=>(0,N.getGuardrailsUsageOverview)(e,s,a),enabled:!!e}),h=u?.rows??[],g=(0,i.useMemo)(()=>{let e,t,s,a;return u?{totalRequests:u.totalRequests??0,totalBlocked:u.totalBlocked??0,passRate:String(u.passRate??0),avgLatency:h.length?Math.round(h.reduce((e,t)=>e+(t.avgLatency??0),0)/h.length):0,count:h.length}:(e=h.reduce((e,t)=>e+t.requestsEvaluated,0),t=h.reduce((e,t)=>e+Math.round(t.requestsEvaluated*t.failRate/100),0),s=e>0?((1-t/e)*100).toFixed(1):"0",{totalRequests:e,totalBlocked:t,passRate:s,avgLatency:(a=h.filter(e=>null!=e.avgLatency)).length>0?Math.round(a.reduce((e,t)=>e+(t.avgLatency??0),0)/a.length):0,count:h.length})},[u,h]),y=u?.chart,j=(0,i.useMemo)(()=>[...h].sort((e,t)=>{let s="desc"===o?-1:1,a=e[r]??0,l=t[r]??0;return(Number(a)-Number(l))*s}),[h,r,o]),f=[{title:"Guardrail",dataIndex:"name",key:"name",render:(e,s)=>(0,t.jsx)("button",{type:"button",className:"text-sm font-medium text-gray-900 hover:text-indigo-600 text-left",onClick:()=>l(s.id),children:e})},{title:"Provider",dataIndex:"provider",key:"provider",render:e=>(0,t.jsx)("span",{className:`inline-flex items-center px-2 py-0.5 text-xs font-medium rounded border ${sc[e]??sc.Custom}`,children:e})},{title:"Requests",dataIndex:"requestsEvaluated",key:"requestsEvaluated",align:"right",sorter:!0,sortOrder:"requestsEvaluated"===r?"desc"===o?"descend":"ascend":null,render:e=>e.toLocaleString()},{title:"Fail Rate",dataIndex:"failRate",key:"failRate",align:"right",sorter:!0,sortOrder:"failRate"===r?"desc"===o?"descend":"ascend":null,render:(e,s)=>(0,t.jsxs)("span",{className:e>15?"text-red-600":e>5?"text-amber-600":"text-green-600",children:[e,"%","up"===s.trend&&(0,t.jsx)("span",{className:"ml-1 text-xs text-red-400",children:"↑"}),"down"===s.trend&&(0,t.jsx)("span",{className:"ml-1 text-xs text-green-400",children:"↓"})]})},{title:"Avg. latency added",dataIndex:"avgLatency",key:"avgLatency",align:"right",sorter:!0,sortOrder:"avgLatency"===r?"desc"===o?"descend":"ascend":null,render:e=>(0,t.jsx)("span",{className:null==e?"text-gray-400":e>150?"text-red-600":e>50?"text-amber-600":"text-green-600",children:null!=e?`${e}ms`:"—"})},{title:"Status",dataIndex:"status",key:"status",align:"center",render:e=>(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,t.jsx)("span",{className:`w-2 h-2 rounded-full ${"healthy"===e?"bg-green-500":"warning"===e?"bg-amber-500":"bg-red-500"}`}),(0,t.jsx)("span",{className:"text-xs text-gray-600 capitalize",children:e})]})}],b=["failRate","requestsEvaluated","avgLatency"];return(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-start justify-between mb-5",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-1",children:[(0,t.jsx)(tX.SafetyOutlined,{className:"text-lg text-indigo-500"}),(0,t.jsx)("h1",{className:"text-xl font-semibold text-gray-900",children:"Guardrails Monitor"})]}),(0,t.jsx)("p",{className:"text-sm text-gray-500",children:"Monitor guardrail performance across all requests"})]}),(0,t.jsx)("div",{className:"flex items-center gap-3",children:(0,t.jsx)(V.Button,{type:"default",icon:(0,t.jsx)(tC.DownloadOutlined,{}),title:"Coming soon",children:"Export Data"})})]}),(0,t.jsxs)(t_.Row,{gutter:[16,16],className:"mb-6",children:[(0,t.jsx)(tv.Col,{xs:12,sm:12,md:8,flex:"1 0 20%",children:(0,t.jsx)(ss,{label:"Total Evaluations",value:g.totalRequests.toLocaleString()})}),(0,t.jsx)(tv.Col,{xs:12,sm:12,md:8,flex:"1 0 20%",children:(0,t.jsx)(ss,{label:"Blocked Requests",value:g.totalBlocked.toLocaleString(),valueColor:"text-red-600",icon:(0,t.jsx)(t0.WarningOutlined,{className:"text-red-400"})})}),(0,t.jsx)(tv.Col,{xs:12,sm:12,md:8,flex:"1 0 20%",children:(0,t.jsx)(ss,{label:"Pass Rate",value:`${g.passRate}%`,valueColor:"text-green-600",icon:(0,t.jsx)(si,{className:"text-green-400"})})}),(0,t.jsx)(tv.Col,{xs:12,sm:12,md:8,flex:"1 0 20%",children:(0,t.jsx)(ss,{label:"Avg. latency added",value:`${g.avgLatency}ms`,valueColor:g.avgLatency>150?"text-red-600":g.avgLatency>50?"text-amber-600":"text-green-600"})}),(0,t.jsx)(tv.Col,{xs:12,sm:12,md:8,flex:"1 0 20%",children:(0,t.jsx)(ss,{label:"Active Guardrails",value:g.count})})]}),(0,t.jsx)("div",{className:"mb-6",children:(0,t.jsx)(sd,{data:y})}),(0,t.jsxs)(ts.Card,{className:"border border-gray-200 rounded-lg bg-white",styles:{body:{padding:0}},children:[(p||x)&&(0,t.jsxs)("div",{className:"px-6 py-4 border-b border-gray-200 flex items-center gap-2",children:[p&&(0,t.jsx)(eF.Spin,{size:"small"}),x&&(0,t.jsx)("span",{className:"text-sm text-red-600",children:"Failed to load data. Try again."})]}),(0,t.jsxs)("div",{className:"px-6 py-4 border-b border-gray-200 flex items-start justify-between gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(sn.Typography.Title,{level:5,className:"!mb-0 text-gray-900",children:"Guardrail Performance"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:"Click a guardrail to view details, logs, and configuration"})]}),(0,t.jsx)("div",{className:"flex items-center gap-2",children:(0,t.jsx)(V.Button,{type:"default",icon:(0,t.jsx)(tZ.SettingOutlined,{}),onClick:()=>m(!0),title:"Evaluation settings"})})]}),(0,t.jsx)(te.Table,{columns:f,dataSource:j,rowKey:"id",pagination:!1,loading:p,onChange:(e,t,s)=>{s?.field&&b.includes(s.field)&&(n(s.field),d("ascend"===s.order?"asc":"desc"))},locale:0!==h.length||p?void 0:{emptyText:"No data for this period"},onRow:e=>({onClick:()=>l(e.id),style:{cursor:"pointer"}})})]}),(0,t.jsx)(t8,{open:c,onClose:()=>m(!1),accessToken:e})]})}let su=new Date,sp=new Date;function sx({accessToken:e=null}){let[s,a]=(0,i.useState)({type:"overview"}),l=(0,i.useMemo)(()=>new Date(sp),[]),r=(0,i.useMemo)(()=>new Date(su),[]),[n,o]=(0,i.useState)({from:l,to:r}),d=n.from?(0,N.formatDate)(n.from):"",c=n.to?(0,N.formatDate)(n.to):"",m=(0,i.useCallback)(e=>{o(e)},[]);return(0,t.jsxs)("div",{className:"p-6 w-full min-w-0 flex-1",children:[(0,t.jsx)("div",{className:"flex items-center justify-end mb-4",children:(0,t.jsx)(tY.default,{value:n,onValueChange:m,label:"",showTimeRange:!1})}),"overview"===s.type?(0,t.jsx)(sm,{accessToken:e,startDate:d,endDate:c,onSelectGuardrail:e=>{a({type:"detail",guardrailId:e})}}):(0,t.jsx)(sl,{guardrailId:s.guardrailId,onBack:()=>{a({type:"overview"})},accessToken:e,startDate:d,endDate:c})]})}sp.setDate(sp.getDate()-7);var sh=e.i(487304),sg=e.i(760221);e.i(111790);var sy=e.i(280881),sj=e.i(934879),sf=e.i(402874),sb=e.i(797305),s_=e.i(109799),sv=e.i(747871),sN=e.i(56567),sw=e.i(468133),sk=e.i(645526),sC=e.i(91979),sS=e.i(525720),sT=e.i(372943),sI=e.i(95684),sF=e.i(497650),sL=e.i(368869),sA=e.i(998573),sP=e.i(438100),sM=e.i(475254);let sD=(0,sM.default)("layers",[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]]);var sE=e.i(988846),sz=e.i(98740),sz=sz;function sO({size:e,fontSize:s}){let a=(0,t.jsx)(tN.LoadingOutlined,{style:s?{fontSize:s}:void 0,spin:!0});return(0,t.jsx)(eF.Spin,{indicator:a,size:e})}var sR=e.i(363256),sB=e.i(9314),sq=e.i(552130),s$=e.i(533882),sU=e.i(651904),sV=e.i(460285),sH=e.i(435451),sG=e.i(916940),sK=e.i(127952),sW=e.i(162386);let sQ=(e,t,s)=>"Admin"===e||!!s&&!!t&&s.some(e=>e.members?.some(e=>e.user_id===t&&"org_admin"===e.user_role)),sY=(e,t,s)=>"Admin"===e?s||[]:s&&t?s.filter(e=>e.members?.some(e=>e.user_id===t&&"org_admin"===e.user_role)):[],sJ=({teams:e,searchParams:s,accessToken:a,setTeams:l,userID:r,userRole:n,organizations:o,premiumUser:d=!1})=>{let c,m,u,p;console.log(`organizations: ${JSON.stringify(o)}`);let{data:x}=(0,s_.useOrganizations)(),[h,g]=(0,i.useState)(!0),[j,b]=(0,i.useState)(null),[v,S]=(0,i.useState)(1),[T,F]=(0,i.useState)(10),[L,A]=(0,i.useState)(0),[P,M]=(0,i.useState)(null),[D,E]=(0,i.useState)(null),[O,R]=(0,i.useState)({team_id:"",team_alias:"",organization_id:"",sort_by:"created_at",sort_order:"desc"}),q=(0,i.useRef)(null),[$,G]=(0,i.useState)(!1),K=async(e={})=>{if(!a)return;let t=e.page??v,s=e.size??T,i=e.sortBy??O.sort_by,o=e.sortOrder??O.sort_order,d=e.organizationID??O.organization_id,c=e.teamAlias??O.team_alias;g(!0),b(null);try{let e=await (0,eV.teamListCall)(a,t,s,{organizationID:d||null,team_alias:c||null,userID:"Admin"!==n&&"Admin Viewer"!==n?r:null,sortBy:i||null,sortOrder:o||null});l(e.teams??[]),A(e.total??0)}catch(e){b(e?.message||"Failed to fetch teams")}finally{g(!1)}};(0,i.useEffect)(()=>{K()},[a]);let[W]=w.Form.useForm(),[Q]=w.Form.useForm(),[Y,J]=(0,i.useState)(""),[X,Z]=(0,i.useState)(!1),[ee,et]=(0,i.useState)(null),[es,ea]=(0,i.useState)(null),[el,er]=(0,i.useState)(!1),[ei,en]=(0,i.useState)(!1),[eo,ed]=(0,i.useState)(!1),[ec,em]=(0,i.useState)(!1),[eu,ep]=(0,i.useState)([]),[ex,eh]=(0,i.useState)(!1),[eg,ef]=(0,i.useState)(null),[eb,e_]=(0,i.useState)([]),[ev,ew]=(0,i.useState)({}),[ek,eC]=(0,i.useState)(!1),[eS,eT]=(0,i.useState)([]),[eI,eF]=(0,i.useState)([]),[eL,eA]=(0,i.useState)([]),[eP,eM]=(0,i.useState)([]),[eD,eE]=(0,i.useState)(!1),[eB,eq]=(0,i.useState)({}),[e$,eU]=(0,i.useState)(null),[eH,eY]=(0,i.useState)(0);(0,i.useEffect)(()=>{let e;console.log(`currentOrgForCreateTeam: ${D}`);let t=(e=[],D&&D.models.length>0?(console.log(`organization.models: ${D.models}`),e=D.models):e=eu,(0,B.unfurlWildcardModelsInList)(e,eu));console.log(`models: ${t}`),e_(t),W.setFieldValue("models",[])},[D,eu]),(0,i.useEffect)(()=>{if(ei){let e=sY(n,r,o);if(1===e.length){let t=e[0];W.setFieldValue("organization_id",t.organization_id),E(t)}else W.setFieldValue("organization_id",P?.organization_id||null),E(P)}},[ei,n,r,o,P]),(0,i.useEffect)(()=>{let e=async()=>{try{if(null==a)return;let e=(await (0,N.getPoliciesList)(a)).policies.map(e=>e.policy_name);eF(e)}catch(e){console.error("Failed to fetch policies:",e)}};(async()=>{try{if(null==a)return;let e=(await (0,N.getGuardrailsList)(a)).guardrails.map(e=>e.guardrail_name);eT(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})(),e()},[a]);let eJ=async()=>{try{if(null==a)return;let e=await (0,N.fetchMCPAccessGroups)(a);eM(e)}catch(e){console.error("Failed to fetch MCP access groups:",e)}};(0,i.useEffect)(()=>{eJ()},[a]),(0,i.useEffect)(()=>{e&&ew(e.reduce((e,t)=>(e[t.team_id]={keys:t.keys||[],team_info:{members_with_roles:t.members_with_roles||[]}},e),{}))},[e]);let eX=async e=>{ef(e),eh(!0)},eZ=async()=>{if(null!=eg&&null!=e&&null!=a)try{eC(!0),await (0,N.teamDeleteCall)(a,eg.team_id),await K(),ez.default.success("Team deleted successfully")}catch(e){ez.default.fromBackend("Error deleting the team: "+e)}finally{eC(!1),eh(!1),ef(null)}};(0,i.useEffect)(()=>{(async()=>{try{if(null===r||null===n||null===a)return;let e=await (0,B.fetchAvailableModelsForTeamOrKey)(r,n,a);e&&ep(e)}catch(e){console.error("Error fetching user models:",e)}})()},[a,r,n,e]);let e0=async t=>{try{if(console.log(`formValues: ${JSON.stringify(t)}`),null!=a){let s=t?.team_alias,l=e?.map(e=>e.team_alias)??[],r=t?.organization_id||P?.organization_id;if(""===r||"string"!=typeof r?t.organization_id=null:t.organization_id=r.trim(),l.includes(s))throw Error(`Team alias ${s} already exists, please pick another alias`);if(ez.default.info("Creating Team"),eL.length>0){let e={};if(t.metadata)try{e=JSON.parse(t.metadata)}catch(e){console.warn("Invalid JSON in metadata field, starting with empty object")}e={...e,logging:eL.filter(e=>e.callback_name)},t.metadata=JSON.stringify(e)}if(t.secret_manager_settings&&"string"==typeof t.secret_manager_settings)if(""===t.secret_manager_settings.trim())delete t.secret_manager_settings;else try{t.secret_manager_settings=JSON.parse(t.secret_manager_settings)}catch(e){throw Error("Failed to parse secret manager settings: "+e)}if(t.allowed_vector_store_ids&&t.allowed_vector_store_ids.length>0||t.allowed_mcp_servers_and_groups&&(t.allowed_mcp_servers_and_groups.servers?.length>0||t.allowed_mcp_servers_and_groups.accessGroups?.length>0||t.allowed_mcp_servers_and_groups.toolPermissions)){if(t.object_permission={},t.allowed_vector_store_ids&&t.allowed_vector_store_ids.length>0&&(t.object_permission.vector_stores=t.allowed_vector_store_ids,delete t.allowed_vector_store_ids),t.allowed_mcp_servers_and_groups){let{servers:e,accessGroups:s}=t.allowed_mcp_servers_and_groups;e&&e.length>0&&(t.object_permission.mcp_servers=e),s&&s.length>0&&(t.object_permission.mcp_access_groups=s),delete t.allowed_mcp_servers_and_groups}t.mcp_tool_permissions&&Object.keys(t.mcp_tool_permissions).length>0&&(t.object_permission||(t.object_permission={}),t.object_permission.mcp_tool_permissions=t.mcp_tool_permissions,delete t.mcp_tool_permissions)}if(t.allowed_mcp_access_groups&&t.allowed_mcp_access_groups.length>0&&(t.object_permission||(t.object_permission={}),t.object_permission.mcp_access_groups=t.allowed_mcp_access_groups,delete t.allowed_mcp_access_groups),t.allowed_agents_and_groups){let{agents:e,accessGroups:s}=t.allowed_agents_and_groups;t.object_permission||(t.object_permission={}),e&&e.length>0&&(t.object_permission.agents=e),s&&s.length>0&&(t.object_permission.agent_access_groups=s),delete t.allowed_agents_and_groups}Object.keys(eB).length>0&&(t.model_aliases=eB),e$?.router_settings&&Object.values(e$.router_settings).some(e=>null!=e&&""!==e)&&(t.router_settings=e$.router_settings),await (0,N.teamCreateCall)(a,t),ez.default.success("Team created"),await K({page:v,size:T}),W.resetFields(),eA([]),eq({}),eU(null),eY(e=>e+1),en(!1)}}catch(e){console.error("Error creating the team:",e),ez.default.fromBackend("Error creating the team: "+e)}},e1=async(e,t)=>{let s={...O,[e]:t};if(R(s),S(1),a)try{let e=await (0,eV.teamListCall)(a,1,T,{organizationID:s.organization_id||null,team_alias:s.team_alias||null,userID:"Admin"!==n&&"Admin Viewer"!==n?r:null,sortBy:s.sort_by||null,sortOrder:s.sort_order||null});l(e.teams??[]),A(e.total??0)}catch(e){console.error("Error fetching teams:",e)}},{token:e2}=sL.theme.useToken(),{Title:e4,Text:e5}=sn.Typography,{Content:e6}=sT.Layout,e3=(0,i.useMemo)(()=>[{title:"Team ID",dataIndex:"team_id",key:"team_id",width:170,ellipsis:!0,render:(e,s)=>(0,t.jsx)(f.Tooltip,{title:e,children:(0,t.jsx)(e5,{ellipsis:!0,className:"text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs cursor-pointer",style:{fontSize:14,padding:"1px 8px"},onClick:()=>ea(s.team_id),"data-testid":"team-id-cell",children:e})})},{title:"Team Alias",dataIndex:"team_alias",key:"team_alias",ellipsis:!0,sorter:!0,render:e=>(0,t.jsx)(e5,{style:{fontSize:14},children:e||(0,t.jsx)(e5,{type:"secondary",italic:!0,children:"—"})})},{title:"Organization",key:"organization",width:160,ellipsis:!0,render:(e,s)=>{let a=((e,t)=>{if(!e||!t)return e||"N/A";let s=t.find(t=>t.organization_id===e);return s?.organization_alias||e})(s.organization_id,x||o);return s.organization_id?(0,t.jsx)(e5,{ellipsis:!0,style:{fontSize:14},children:a}):(0,t.jsx)(e5,{type:"secondary",children:"—"})}},{title:"Resources",key:"resources",width:240,render:(e,s)=>{let a=ev?.[s.team_id]?.team_info?.members_with_roles?.length??0,l=s.models?.length??0,r=ev?.[s.team_id]?.keys?.length??0;return(0,t.jsxs)(sS.Flex,{gap:12,align:"center",children:[(0,t.jsx)(f.Tooltip,{title:`${a} Members`,children:(0,t.jsx)(I.Tag,{color:"purple",style:{fontSize:14,padding:"2px 8px",margin:0},children:(0,t.jsxs)(sS.Flex,{align:"center",gap:6,children:[(0,t.jsx)(sz.default,{size:14}),a]})})}),(0,t.jsx)(f.Tooltip,{title:`${l} Models`,children:(0,t.jsx)(I.Tag,{color:"blue",style:{fontSize:14,padding:"2px 8px",margin:0},children:(0,t.jsxs)(sS.Flex,{align:"center",gap:6,children:[(0,t.jsx)(sD,{size:14}),l]})})}),(0,t.jsx)(f.Tooltip,{title:`${r} Keys`,children:(0,t.jsx)(I.Tag,{color:"cyan",style:{fontSize:14,padding:"2px 8px",margin:0},children:(0,t.jsxs)(sS.Flex,{align:"center",gap:6,children:[(0,t.jsx)(sP.KeyIcon,{size:14}),r]})})})]})}},{title:"Spend / Budget",key:"spend",width:200,sorter:!0,render:(e,s)=>{let a=s.spend??0,l=s.max_budget,r=`$${a.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}`,i=null!=l?`$${l.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}`:"Unlimited",n=null!=l&&l>0?Math.min(a/l*100,100):null;return(0,t.jsxs)(sS.Flex,{vertical:!0,gap:2,children:[(0,t.jsxs)(e5,{style:{fontSize:13},children:[r,(0,t.jsxs)(e5,{type:"secondary",style:{fontSize:12},children:[" / ",i]})]}),null!=n&&(0,t.jsx)(sF.Progress,{percent:n,size:"small",showInfo:!1,strokeColor:n>=90?"#ff4d4f":n>=70?"#faad14":"#1677ff",style:{marginBottom:0}})]})}},{title:"Created",dataIndex:"created_at",key:"created_at",width:130,ellipsis:!0,sorter:!0,render:e=>(0,t.jsx)(e5,{type:"secondary",style:{fontSize:13},children:e?new Date(e).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):"—"})},{title:"Actions",key:"actions",width:120,align:"right",render:(e,s)=>(0,t.jsxs)(U.Space,{size:4,children:[(0,t.jsx)(eR.default,{variant:"Copy",tooltipText:"Copy Team ID",onClick:()=>{navigator.clipboard.writeText(s.team_id).then(()=>sA.message.success("Team ID copied")).catch(()=>sA.message.error("Failed to copy"))}}),"Admin"===n&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(eR.default,{variant:"Edit",tooltipText:"Edit team",dataTestId:"edit-team-button",onClick:()=>{ea(s.team_id),er(!0)}}),(0,t.jsx)(eR.default,{variant:"Delete",tooltipText:"Delete team",dataTestId:"delete-team-button",onClick:()=>eX(s)})]})]})}],[n,ev,x,o]),e8=(0,i.useMemo)(()=>e??[],[e]),e7=[{key:"your-teams",label:"Your Teams",children:(0,t.jsxs)(t.Fragment,{children:[(0,t.jsxs)(ts.Card,{styles:{body:{padding:0}},children:[(0,t.jsxs)(sS.Flex,{justify:"space-between",align:"center",style:{padding:"12px 16px"},children:[(0,t.jsxs)(sS.Flex,{gap:12,align:"center",children:[(0,t.jsx)(C.Input,{prefix:(0,t.jsx)(sE.SearchIcon,{size:16}),suffix:$?(0,t.jsx)(sO,{size:"small"}):null,placeholder:"Search teams by name...",onChange:e=>{var t;return t=e.target.value,void(q.current&&clearTimeout(q.current),G(!0),q.current=setTimeout(async()=>{try{R(e=>({...e,team_alias:t})),S(1),await K({page:1,teamAlias:t})}finally{G(!1)}},300))},allowClear:!0,style:{maxWidth:400}}),(0,t.jsx)(sR.default,{organizations:o,value:O.organization_id||void 0,onChange:e=>e1("organization_id",e||""),loading:h})]}),(0,t.jsx)(sI.Pagination,{current:v,total:L,pageSize:T,onChange:(e,t)=>{S(e),F(t),K({page:e,size:t})},size:"small",showTotal:e=>`${e} teams`,showSizeChanger:!0,pageSizeOptions:["10","20","50"]})]}),h?(0,t.jsx)(sS.Flex,{justify:"center",align:"center",style:{padding:"80px 0"},children:(0,t.jsx)(sO,{fontSize:48})}):j?(0,t.jsxs)(sS.Flex,{vertical:!0,align:"center",gap:16,style:{padding:"64px 0"},children:[(0,t.jsx)(e5,{type:"danger",style:{fontSize:15},children:"Failed to load teams"}),(0,t.jsx)(e5,{type:"secondary",style:{fontSize:13},children:j}),(0,t.jsx)(V.Button,{icon:(0,t.jsx)(sC.ReloadOutlined,{}),onClick:()=>{K()},children:"Retry"})]}):(0,t.jsx)(te.Table,{columns:e3,dataSource:e8,rowKey:"team_id",pagination:!1,onChange:(e,t,s)=>{let a=Array.isArray(s)?s[0]:s,l=a.order?a.columnKey:"created_at",r="ascend"===a.order?"asc":(a.order,"desc");R(e=>({...e,sort_by:l,sort_order:r})),K({sortBy:l,sortOrder:r})},locale:{emptyText:(0,t.jsxs)("div",{style:{padding:"64px 0",textAlign:"center"},children:[(0,t.jsx)(sk.TeamOutlined,{style:{fontSize:40,color:"#d9d9d9",marginBottom:12}}),(0,t.jsx)("div",{children:(0,t.jsx)(e5,{style:{fontSize:15,color:"#595959"},children:"No teams yet"})}),(0,t.jsx)("div",{style:{marginTop:4},children:(0,t.jsx)(e5,{type:"secondary",style:{fontSize:13},children:"Create your first team to organize members and manage access to models."})}),sQ(n,r,o)&&(0,t.jsx)(V.Button,{type:"primary",icon:(0,t.jsx)(H.PlusOutlined,{}),onClick:()=>en(!0),style:{marginTop:16},"data-testid":"create-team-button",children:"Create Team"})]})},scroll:{x:1e3},size:"middle"})]}),(0,t.jsx)(sK.default,{isOpen:ex,title:"Delete Team?",alertMessage:eg?.keys?.length===0?void 0:`Warning: This team has ${eg?.keys?.length} keys associated with it. Deleting the team will also delete all associated keys. This action is irreversible.`,message:"Are you sure you want to delete this team and all its keys? This action cannot be undone.",resourceInformationTitle:"Team Information",resourceInformation:[{label:"Team ID",value:eg?.team_id,code:!0},{label:"Team Name",value:eg?.team_alias},{label:"Keys",value:eg?.keys?.length},{label:"Members",value:eg?.members_with_roles?.length}],requiredConfirmation:eg?.team_alias,onCancel:()=>{eh(!1),ef(null)},onOk:eZ,confirmLoading:ek})]})},{key:"available-teams",label:"Available Teams",children:(0,t.jsx)(sv.default,{accessToken:a,userID:r})},...(0,eN.isProxyAdminRole)(n||"")?[{key:"default-settings",label:"Default Team Settings",children:(0,t.jsx)(sw.default,{accessToken:a,userID:r||"",userRole:n||""})}]:[]];return(0,t.jsxs)(e6,{style:{padding:e2.paddingLG,paddingInline:2*e2.paddingLG},children:[es?(0,t.jsx)(sN.default,{teamId:es,onUpdate:e=>{l(t=>null==t?t:t.map(t=>e.team_id===t.team_id?(0,eO.updateExistingKeys)(t,e):t)),K()},onClose:()=>{ea(null),er(!1)},accessToken:a,is_team_admin:(e=>{if(null==e||null==e.members_with_roles)return!1;for(let t=0;t