+
${t.model} ${t.provider?`(${t.provider})`:""}
+
+
+
+
+
+ | Cost Type |
+ Per Request |
+ ${null!==t.daily_cost?"Daily | ":""}
+ ${null!==t.monthly_cost?"Monthly | ":""}
+
+
+ | Input Cost |
+ ${tM(t.input_cost_per_request)} |
+ ${null!==t.daily_cost?`${tM(t.daily_input_cost)} | `:""}
+ ${null!==t.monthly_cost?`${tM(t.monthly_input_cost)} | `:""}
+
+
+ | Output Cost |
+ ${tM(t.output_cost_per_request)} |
+ ${null!==t.daily_cost?`${tM(t.daily_output_cost)} | `:""}
+ ${null!==t.monthly_cost?`${tM(t.monthly_output_cost)} | `:""}
+
+
+ | Margin/Fee |
+ ${tM(t.margin_cost_per_request)} |
+ ${null!==t.daily_cost?`${tM(t.daily_margin_cost)} | `:""}
+ ${null!==t.monthly_cost?`${tM(t.monthly_margin_cost)} | `:""}
+
+
+ | Total |
+ ${tM(t.cost_per_request)} |
+ ${null!==t.daily_cost?`${tM(t.daily_cost)} | `:""}
+ ${null!==t.monthly_cost?`${tM(t.monthly_cost)} | `:""}
+
+
+
+ `}).join("")}
+
+
+
+
+ `;t.document.write(l),t.document.close(),t.onload=()=>{t.print()}})(e),a(!1)},children:[(0,t.jsx)(tI.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)(tA,{className:"mr-3 text-green-600"}),"Export as CSV"]})]})]}):null},tO=e=>null==e?"-":0===e?"$0":e<1e-4?`$${e.toExponential(2)}`:e<1?`$${e.toFixed(4)}`:`$${(0,eB.formatNumberWithCommas)(e,2,!0)}`,tR=({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)(eL.Spin,{indicator:(0,t.jsx)(tk.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)(b.Text,{className:"text-xs text-gray-500 block",children:"Total/Request"}),(0,t.jsx)(b.Text,{className:"text-base font-semibold text-blue-600",children:tO(e.cost_per_request)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(b.Text,{className:"text-xs text-gray-500 block",children:"Input Cost"}),(0,t.jsx)(b.Text,{className:"text-sm",children:tO(e.input_cost_per_request)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(b.Text,{className:"text-xs text-gray-500 block",children:"Output Cost"}),(0,t.jsx)(b.Text,{className:"text-sm",children:tO(e.output_cost_per_request)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(b.Text,{className:"text-xs text-gray-500 block",children:"Margin Fee"}),(0,t.jsx)(b.Text,{className:`text-sm ${e.margin_cost_per_request>0?"text-amber-600":""}`,children:tO(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)(b.Text,{className:"text-xs text-gray-500 block",children:[l," Total (",null==d?"-":(0,eB.formatNumberWithCommas)(d,0,!0)," req)"]}),(0,t.jsx)(b.Text,{className:`text-base font-semibold ${"day"===a?"text-green-600":"text-purple-600"}`,children:tO(r)})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(b.Text,{className:"text-xs text-gray-500 block",children:[l," Input"]}),(0,t.jsx)(b.Text,{className:"text-sm",children:tO(i)})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(b.Text,{className:"text-xs text-gray-500 block",children:[l," Output"]}),(0,t.jsx)(b.Text,{className:"text-sm",children:tO(n)})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(b.Text,{className:"text-xs text-gray-500 block",children:[l," Margin Fee"]}),(0,t.jsx)(b.Text,{className:`text-sm ${(o??0)>0?"text-amber-600":""}`,children:tO(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,eB.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,eB.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),n=e.entries.filter(e=>e.loading),o=e.entries.filter(e=>null!==e.error),d=r.length>0,c=n.length>0,u=o.length>0;if(!d&&!c&&!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)(b.Text,{className:"text-gray-500",children:"Select models above to see cost estimates"})});if(!d&&c&&!u)return(0,t.jsxs)("div",{className:"py-6 text-center",children:[(0,t.jsx)(eL.Spin,{indicator:(0,t.jsx)(tk.LoadingOutlined,{spin:!0})}),(0,t.jsx)(b.Text,{className:"text-gray-500 block mt-2",children:"Calculating costs..."})]});if(!d&&u)return(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)(M.Divider,{className:"my-4"}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(b.Text,{className:"text-base font-semibold text-gray-900",children:"Cost Estimates"}),c&&(0,t.jsx)(eL.Spin,{indicator:(0,t.jsx)(tk.LoadingOutlined,{spin:!0}),size:"small"})]}),o.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 x=e.totals.margin_per_request>0,p="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)(A.Tag,{color:"blue",className:"text-xs",children:s.provider}),s.loading&&(0,t.jsx)(eL.Spin,{indicator:(0,t.jsx)(tk.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:tO(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:tO(e)})},{title:p,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:tO(e)})},{title:"",key:"expand",width:40,render:(e,s)=>s.error?null:(0,t.jsx)(m.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)(tC.DownOutlined,{}):(0,t.jsx)(tS.RightOutlined,{})})}],g=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)(M.Divider,{className:"my-4"}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(b.Text,{className:"text-base font-semibold text-gray-900",children:"Cost Estimates"}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[c&&(0,t.jsx)(eL.Spin,{indicator:(0,t.jsx)(tk.LoadingOutlined,{spin:!0}),size:"small"}),(0,t.jsx)(tE,{multiResult:e})]})]}),(0,t.jsxs)(tl.Card,{size:"small",className:"bg-gradient-to-r from-slate-50 to-blue-50 border-slate-200",children:[(0,t.jsxs)(tN.Row,{gutter:[16,8],children:[(0,t.jsx)(tw.Col,{xs:24,sm:12,children:(0,t.jsx)(tj,{title:(0,t.jsx)("span",{className:"text-xs",children:"Total Per Request"}),value:tO(e.totals.cost_per_request),valueStyle:{color:"#1890ff",fontSize:"18px",fontFamily:"monospace"}})}),(0,t.jsx)(tw.Col,{xs:24,sm:12,children:(0,t.jsx)(tj,{title:(0,t.jsxs)("span",{className:"text-xs",children:["Total ",p]}),value:tO("day"===s?e.totals.daily_cost:e.totals.monthly_cost),valueStyle:{color:"day"===s?"#52c41a":"#722ed1",fontSize:"18px",fontFamily:"monospace"}})})]}),x&&(0,t.jsxs)(tN.Row,{gutter:[16,8],className:"mt-3 pt-3 border-t border-slate-200",children:[(0,t.jsxs)(tw.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:tO(e.totals.margin_per_request)})]}),(0,t.jsxs)(tw.Col,{xs:24,sm:12,children:[(0,t.jsxs)("div",{className:"text-xs text-gray-500",children:[p," Margin Fee"]}),(0,t.jsx)("div",{className:"text-sm font-mono text-amber-600",children:tO("day"===s?e.totals.daily_margin:e.totals.monthly_margin)})]})]})]}),g.length>0&&(0,t.jsx)(ts.Table,{columns:h,dataSource:g,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)(tR,{result:a.result,loading:a.loading,timePeriod:s})}):null},showExpandColumn:!1}})]})},tB=()=>({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}),tq=({accessToken:e,models:s})=>{let[a,r]=(0,i.useState)([tB()]),[n,o]=(0,i.useState)("month"),{debouncedFetchForEntry:d,removeEntry:c,getMultiModelResult:m}=function(e){let[t,s]=(0,i.useState)(new Map),a=(0,i.useRef)(new Map),r=(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,l.getProxyBaseUrl)(),r=a?`${a}/cost/estimate`:"/cost/estimate",i={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},n=await fetch(r,{method:"POST",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i)});if(n.ok){let e=await n.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 n.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]),n=(0,i.useCallback)(e=>{let t=a.current.get(e.id);t&&clearTimeout(t);let s=setTimeout(()=>{r(e)},500);a.current.set(e.id,s)},[r]),o=(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:n,removeEntry:o,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),u=(0,i.useCallback)((e,t,s)=>{r(a=>{let l=a.map(a=>a.id===e?{...a,[t]:s}:a),r=l.find(t=>t.id===e);return r&&r.model&&d(r),l})},[d]),x=(0,i.useCallback)(e=>{o(e),r(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)(()=>{r(e=>[...e,tB()])},[]),h=(0,i.useCallback)(e=>{r(t=>t.filter(t=>t.id!==e)),c(e)},[c]),g=m(a),y=[{title:"Model",dataIndex:"model",key:"model",width:"35%",render:(e,a)=>(0,t.jsx)(I.Select,{showSearch:!0,placeholder:"Select a model",value:a.model||void 0,onChange:e=>u(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)(D.InputNumber,{min:0,value:s.input_tokens,onChange:e=>u(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)(D.InputNumber,{min:0,value:s.output_tokens,onChange:e=>u(s.id,"output_tokens",e??0),style:{width:"100%"},size:"small",formatter:e=>`${e}`.replace(/\B(?=(\d{3})+(?!\d))/g,",")})},{title:`Requests/${"day"===n?"Day":"Month"}`,dataIndex:"day"===n?"num_requests_per_day":"num_requests_per_month",key:"num_requests",width:"20%",render:(e,s)=>(0,t.jsx)(D.InputNumber,{min:0,value:"day"===n?s.num_requests_per_day:s.num_requests_per_month,onChange:e=>u(s.id,"day"===n?"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)(G.Button,{type:"text",icon:(0,t.jsx)(ta.DeleteOutlined,{}),onClick:()=>h(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)(L.Radio.Group,{value:n,onChange:e=>x(e.target.value),size:"small",optionType:"button",buttonStyle:"solid",children:[(0,t.jsx)(L.Radio.Button,{value:"day",children:"Per Day"}),(0,t.jsx)(L.Radio.Button,{value:"month",children:"Per Month"})]})}),(0,t.jsx)(ts.Table,{columns:y,dataSource:a,rowKey:"id",pagination:!1,size:"small",footer:()=>(0,t.jsx)(G.Button,{type:"dashed",onClick:p,icon:(0,t.jsx)(K.PlusOutlined,{}),className:"w-full",children:"Add Another Model"})}),(0,t.jsx)(tz,{multiResult:g,timePeriod:n})]})};var t$=e.i(270377),tU=e.i(778917),tH=e.i(664659);let tV=({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)(tH.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)(tU.ExternalLink,{className:"h-3.5 w-3.5 text-gray-400 flex-shrink-0 ml-2","aria-hidden":"true"})]},s))})]})};var tG=e.i(673709);let tK=()=>{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)(b.Text,{className:"font-medium text-gray-900 text-sm mb-1",children:"Cost Calculation"}),(0,t.jsxs)(b.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)(b.Text,{className:"font-medium text-gray-900 text-sm mb-1",children:"Example"}),(0,t.jsx)(b.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)(b.Text,{className:"font-medium text-gray-900 text-sm mb-1",children:"Valid Range"}),(0,t.jsx)(b.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)(b.Text,{className:"font-medium text-gray-900 text-sm mb-2",children:"Validating Discounts"}),(0,t.jsx)(b.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)(tG.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)(b.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)(b.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)(b.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)(b.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)(b.Text,{className:"font-medium text-gray-900 text-sm mb-3",children:"Discount Calculator"}),(0,t.jsx)(b.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)(eJ.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)(eJ.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)(b.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)(b.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)(b.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)(b.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)(b.Text,{className:"text-xs font-semibold text-blue-900",children:"Discount Applied:"}),(0,t.jsxs)(b.Text,{className:"text-sm font-bold text-blue-900",children:[r.discountPercentage,"%"]})]})]})]})]})]})};var tW=e.i(689020);let tQ=[{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"}],tY=({userID:e,userRole:s,accessToken:a})=>{let[r,n]=(0,i.useState)(void 0),[o,d]=(0,i.useState)(""),[c,u]=(0,i.useState)(!0),[x,p]=(0,i.useState)(!1),[h,g]=(0,i.useState)(!1),[y,j]=(0,i.useState)(void 0),[f,v]=(0,i.useState)("percentage"),[N,w]=(0,i.useState)(""),[k,C]=(0,i.useState)(""),[T,I]=(0,i.useState)([]),[F]=S.Form.useForm(),[P]=S.Form.useForm(),[L,A]=_.Modal.useModal(),M="proxy_admin"===s||"Admin"===s,{discountConfig:D,fetchDiscountConfig:E,handleAddProvider:O,handleRemoveProvider:R,handleDiscountChange:z}=function({accessToken:e}){let[t,s]=(0,i.useState)({}),a=(0,i.useCallback)(async()=>{try{let t=(0,l.getProxyBaseUrl)(),a=t?`${t}/config/cost_discount_config`:"/config/cost_discount_config",r=await fetch(a,{method:"GET",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(r.ok){let e=await r.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]),r=(0,i.useCallback)(async t=>{try{let s=(0,l.getProxyBaseUrl)(),r=s?`${s}/config/cost_discount_config`:"/config/cost_discount_config",i=await fetch(r,{method:"PATCH",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(i.ok)ez.default.success("Discount configuration updated successfully"),await a();else{let e=await i.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]),n=(0,i.useCallback)(async(e,a)=>{if(!e||!a)return ez.default.fromBackend("Please select a provider and enter discount percentage"),!1;let l=parseFloat(a);if(isNaN(l)||l<0||l>100)return ez.default.fromBackend("Discount must be between 0% and 100%"),!1;let i=e3(e);if(!i)return ez.default.fromBackend("Invalid provider selected"),!1;if(t[i])return ez.default.fromBackend(`Discount for ${e5.Providers[e]} already exists. Edit it in the table above.`),!1;let n={...t,[i]:l/100};return s(n),await r(n),!0},[t,r]),o=(0,i.useCallback)(async e=>{let a={...t};delete a[e],s(a),await r(a)},[t,r]),d=(0,i.useCallback)(async(e,a)=>{let l=parseFloat(a);if(!isNaN(l)&&l>=0&&l<=1){let a={...t,[e]:l};s(a),await r(a)}},[t,r]);return{discountConfig:t,setDiscountConfig:s,fetchDiscountConfig:a,saveDiscountConfig:r,handleAddProvider:n,handleRemoveProvider:o,handleDiscountChange:d}}({accessToken:a}),{marginConfig:B,fetchMarginConfig:q,handleAddMargin:$,handleRemoveMargin:U,handleMarginChange:H}=function({accessToken:e}){let[t,s]=(0,i.useState)({}),a=(0,i.useCallback)(async()=>{try{let t=(0,l.getProxyBaseUrl)(),a=t?`${t}/config/cost_margin_config`:"/config/cost_margin_config",r=await fetch(a,{method:"GET",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(r.ok){let e=await r.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]),r=(0,i.useCallback)(async t=>{try{let s=(0,l.getProxyBaseUrl)(),r=s?`${s}/config/cost_margin_config`:"/config/cost_margin_config",i=await fetch(r,{method:"PATCH",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(i.ok)ez.default.success("Margin configuration updated successfully"),await a();else{let e=await i.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]),n=(0,i.useCallback)(async e=>{let a,l,{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=e3(i);if(!e)return ez.default.fromBackend("Invalid provider selected"),!1;a=e}if(t[a]){let e="global"===a?"Global":e5.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;l=e/100}else{let e=parseFloat(d);if(isNaN(e)||e<0)return ez.default.fromBackend("Fixed amount must be non-negative"),!1;l={fixed_amount:e}}let c={...t,[a]:l};return s(c),await r(c),!0},[t,r]),o=(0,i.useCallback)(async e=>{let a={...t};delete a[e],s(a),await r(a)},[t,r]),d=(0,i.useCallback)(async(e,a)=>{let l={...t,[e]:a};s(l),await r(l)},[t,r]);return{marginConfig:t,setMarginConfig:s,fetchMarginConfig:a,saveMarginConfig:r,handleAddMargin:n,handleRemoveMargin:o,handleMarginChange:d}}({accessToken:a});(0,i.useEffect)(()=>{a&&(Promise.all([E(),q()]).finally(()=>{u(!1)}),(async()=>{try{let e=await (0,tW.fetchAvailableModels)(a);I(e.map(e=>e.model_group))}catch(e){console.error("Error fetching models:",e)}})())},[a,E,q]);let V=async()=>{await O(r,o)&&(n(void 0),d(""),p(!1))},G=async(e,s)=>{L.confirm({title:"Remove Provider Discount",icon:(0,t.jsx)(t$.ExclamationCircleOutlined,{}),content:`Are you sure you want to remove the discount for ${s}?`,okText:"Remove",okType:"danger",cancelText:"Cancel",onOk:()=>R(e)})},K=async()=>{await $({selectedProvider:y,marginType:f,percentageValue:N,fixedAmountValue:k})&&(j(void 0),w(""),C(""),v("percentage"),g(!1))},W=async(e,s)=>{L.confirm({title:"Remove Provider Margin",icon:(0,t.jsx)(t$.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:[A,(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)(eC.Title,{children:"Cost Tracking Settings"}),(0,t.jsx)(tV,{items:tQ})]}),(0,t.jsx)(b.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)(eW.Accordion,{children:[(0,t.jsx)(eQ.AccordionHeader,{className:"px-6 py-4",children:(0,t.jsxs)("div",{className:"flex flex-col items-start w-full",children:[(0,t.jsx)(b.Text,{className:"text-lg font-semibold text-gray-900",children:"Provider Discounts"}),(0,t.jsx)(b.Text,{className:"text-sm text-gray-500 mt-1",children:"Apply percentage-based discounts to reduce costs for specific providers"})]})}),(0,t.jsx)(eY.AccordionBody,{className:"px-0",children:(0,t.jsxs)(eT.TabGroup,{children:[(0,t.jsxs)(eI.TabList,{className:"px-6 pt-4",children:[(0,t.jsx)(eS.Tab,{children:"Discounts"}),(0,t.jsx)(eS.Tab,{children:"Test It"})]}),(0,t.jsxs)(eP.TabPanels,{children:[(0,t.jsx)(eF.TabPanel,{children:(0,t.jsxs)("div",{className:"p-6",children:[(0,t.jsx)("div",{className:"flex justify-end mb-4",children:(0,t.jsx)(m.Button,{onClick:()=>p(!0),children:"+ Add Provider Discount"})}),c?(0,t.jsx)("div",{className:"py-12 text-center",children:(0,t.jsx)(b.Text,{className:"text-gray-500",children:"Loading configuration..."})}):Object.keys(D).length>0?(0,t.jsx)(e7,{discountConfig:D,onDiscountChange:z,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)(b.Text,{className:"text-gray-700 font-medium mb-2",children:"No provider discounts configured"}),(0,t.jsx)(b.Text,{className:"text-gray-500 text-sm",children:'Click "Add Provider Discount" to get started'})]})]})}),(0,t.jsx)(eF.TabPanel,{children:(0,t.jsx)("div",{className:"px-6 pb-4",children:(0,t.jsx)(tK,{})})})]})]})})]}),M&&(0,t.jsxs)(eW.Accordion,{children:[(0,t.jsx)(eQ.AccordionHeader,{className:"px-6 py-4",children:(0,t.jsxs)("div",{className:"flex flex-col items-start w-full",children:[(0,t.jsx)(b.Text,{className:"text-lg font-semibold text-gray-900",children:"Fee/Price Margin"}),(0,t.jsx)(b.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)(eY.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)(m.Button,{onClick:()=>g(!0),children:"+ Add Provider Margin"})}),c?(0,t.jsx)("div",{className:"py-12 text-center",children:(0,t.jsx)(b.Text,{className:"text-gray-500",children:"Loading configuration..."})}):Object.keys(B).length>0?(0,t.jsx)(te,{marginConfig:B,onMarginChange:H,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)(b.Text,{className:"text-gray-700 font-medium mb-2",children:"No provider margins configured"}),(0,t.jsx)(b.Text,{className:"text-gray-500 text-sm",children:'Click "Add Provider Margin" to get started'})]})]})})]}),(0,t.jsxs)(eW.Accordion,{defaultOpen:!0,children:[(0,t.jsx)(eQ.AccordionHeader,{className:"px-6 py-4",children:(0,t.jsxs)("div",{className:"flex flex-col items-start w-full",children:[(0,t.jsx)(b.Text,{className:"text-lg font-semibold text-gray-900",children:"Pricing Calculator"}),(0,t.jsx)(b.Text,{className:"text-sm text-gray-500 mt-1",children:"Estimate LLM costs based on expected token usage and request volume"})]})}),(0,t.jsx)(eY.AccordionBody,{className:"px-0",children:(0,t.jsx)("div",{className:"p-6",children:(0,t.jsx)(tq,{accessToken:a,models:T})})})]})]}),(0,t.jsx)(_.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:x,width:1e3,onCancel:()=>{p(!1),F.resetFields(),n(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)(b.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)(S.Form,{form:F,onFinish:()=>{V()},layout:"vertical",className:"space-y-6",children:(0,t.jsx)(e9,{discountConfig:D,selectedProvider:r,newDiscount:o,onProviderChange:n,onDiscountChange:d,onAddProvider:V})})]})}),(0,t.jsx)(_.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:h,width:1e3,onCancel:()=>{g(!1),P.resetFields(),j(void 0),w(""),C(""),v("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)(b.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)(S.Form,{form:P,layout:"vertical",className:"space-y-6",children:(0,t.jsx)(tt,{marginConfig:B,selectedProvider:y,marginType:f,percentageValue:N,fixedAmountValue:k,onProviderChange:j,onMarginTypeChange:v,onPercentageChange:w,onFixedAmountChange:C,onAddProvider:K})})]})})]}):null};var tJ=e.i(226898),tX=e.i(973706),tZ=e.i(447566),t0=e.i(602073),t1=e.i(313603),t2=e.i(285027),t4=e.i(266027),t5=e.i(309426),t6=e.i(350967),t3=e.i(653496),t8=e.i(149192),t7=e.i(788191);let t9=`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.`,se=`{
+ "verdict": "correct" | "false_positive" | "false_negative",
+ "confidence": 0.0,
+ "justification": "string",
+ "risk_category": "string",
+ "suggested_action": "keep" | "adjust threshold" | "add allowlist"
+}
+`;function st({open:e,onClose:s,guardrailName:a,accessToken:l,onRunEvaluation:r}){let[n,o]=(0,i.useState)(t9),[d,c]=(0,i.useState)(se),[m,u]=(0,i.useState)(null),[x,p]=(0,i.useState)([]),[h,g]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!e||!l)return void p([]);let t=!1;return g(!0),(0,tW.fetchAvailableModels)(l).then(e=>{t||p(e)}).catch(()=>{t||p([])}).finally(()=>{t||g(!1)}),()=>{t=!0}},[e,l]);let y=x.map(e=>({value:e.model_group,label:e.model_group}));return(0,t.jsxs)(_.Modal,{title:"Evaluation Settings",open:e,onCancel:s,width:640,footer:null,closeIcon:(0,t.jsx)(t8.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(t9),className:"text-xs text-indigo-600 hover:text-indigo-700",children:"Reset to default"})]}),(0,t.jsx)(F.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)(F.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)(I.Select,{placeholder:h?"Loading models…":"Select a model",value:m??void 0,onChange:u,options:y,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)(G.Button,{onClick:s,children:"Cancel"}),(0,t.jsx)(G.Button,{type:"primary",icon:(0,t.jsx)(t7.PlayCircleOutlined,{}),onClick:()=>{m&&(r?.({prompt:n,schema:d,model:m}),s())},disabled:!m,children:"Run Evaluation"})]})]})}var ss=e.i(166540);e.i(3565);var sa=e.i(502626);let sl={blocked:{icon:t8.CloseOutlined,color:"text-red-600",bg:"bg-red-50",border:"border-red-200",label:"Blocked"},passed:{icon:C.CheckCircleOutlined,color:"text-green-600",bg:"bg-green-50",border:"border-green-200",label:"Passed"},flagged:{icon:t2.WarningOutlined,color:"text-amber-600",bg:"bg-amber-50",border:"border-amber-200",label:"Flagged"}};function sr({guardrailName:e,filterAction:s="all",logs:a=[],logsLoading:r=!1,totalLogs:n,accessToken:o=null,startDate:d="",endDate:c=""}){let[m,u]=(0,i.useState)(10),[x,p]=(0,i.useState)(s),[h,g]=(0,i.useState)(null),[y,j]=(0,i.useState)(!1),f=a.filter(e=>"all"===x||e.action===x).slice(0,m),b=n??a.length,_=d?(0,ss.default)(d).utc().format("YYYY-MM-DD HH:mm:ss"):(0,ss.default)().subtract(24,"hours").utc().format("YYYY-MM-DD HH:mm:ss"),v=c?(0,ss.default)(c).utc().endOf("day").format("YYYY-MM-DD HH:mm:ss"):(0,ss.default)().utc().format("YYYY-MM-DD HH:mm:ss"),{data:N}=(0,t4.useQuery)({queryKey:["spend-log-by-request",h,_,v],queryFn:async()=>o&&h?await (0,l.uiSpendLogsCall)({accessToken:o,start_date:_,end_date:v,page:1,page_size:10,params:{request_id:h}}):null,enabled:!!(o&&h&&y)}),w=N?.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:r?"Loading…":a.length>0?`Showing ${f.length} of ${b} 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)(G.Button,{type:x===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)(G.Button,{type:m===e?"primary":"default",size:"small",onClick:()=>u(e),children:e},e))]})]})]})}),r&&(0,t.jsx)("div",{className:"flex items-center justify-center py-12",children:(0,t.jsx)(eL.Spin,{})}),!r&&0===f.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."}),!r&&f.length>0&&(0,t.jsx)("div",{className:"divide-y divide-gray-100",children:f.map(e=>{let s=sl[e.action],a=s.icon;return(0,t.jsxs)("button",{type:"button",onClick:()=>{g(e.id),j(!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)(tC.DownOutlined,{className:"w-4 h-4 text-gray-400 flex-shrink-0 mt-1"})]},e.id)})}),(0,t.jsx)(sa.LogDetailsDrawer,{open:y,onClose:()=>{j(!1),g(null)},logEntry:w,accessToken:o,allLogs:w?[w]:[],startTime:_})]})}function si({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 sn={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 so({guardrailId:e,onBack:s,accessToken:a=null,startDate:r,endDate:n}){let[o,d]=(0,i.useState)("overview"),[c,m]=(0,i.useState)(!1),[u,x]=(0,i.useState)(1),{data:p,isLoading:h,error:g}=(0,t4.useQuery)({queryKey:["guardrails-usage-detail",e,r,n],queryFn:()=>(0,l.getGuardrailsUsageDetail)(a,e,r,n),enabled:!!a&&!!e}),{data:y,isLoading:j}=(0,t4.useQuery)({queryKey:["guardrails-usage-logs",e,u,50],queryFn:()=>(0,l.getGuardrailsUsageLogs)(a,{guardrailId:e,page:u,pageSize:50,startDate:r,endDate:n}),enabled:!!a&&!!e}),f=(0,i.useMemo)(()=>(y?.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})),[y?.logs]),b=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},_=sn[b.status]??sn.healthy;return h&&!p?(0,t.jsx)("div",{className:"flex items-center justify-center py-12",children:(0,t.jsx)(eL.Spin,{size:"large"})}):g&&!p?(0,t.jsxs)("div",{children:[(0,t.jsx)(G.Button,{type:"link",icon:(0,t.jsx)(tZ.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)(G.Button,{type:"link",icon:(0,t.jsx)(tZ.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)(t0.SafetyOutlined,{className:"text-xl text-gray-400"}),(0,t.jsx)("h1",{className:"text-xl font-semibold text-gray-900",children:b.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 ${_.bg} ${_.text}`,children:[(0,t.jsx)("span",{className:`w-1.5 h-1.5 rounded-full ${_.dot}`}),b.status.charAt(0).toUpperCase()+b.status.slice(1)]})]}),(0,t.jsx)("p",{className:"text-sm text-gray-500 ml-8",children:b.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:b.provider}),(0,t.jsx)(G.Button,{type:"default",icon:(0,t.jsx)(t1.SettingOutlined,{}),onClick:()=>m(!0),title:"Evaluation settings"})]})]})]}),(0,t.jsx)(t3.Tabs,{activeKey:o,onChange:d,items:[{key:"overview",label:"Overview"},{key:"logs",label:"Logs"}]}),"overview"===o&&(0,t.jsxs)("div",{className:"space-y-6 mt-4",children:[(0,t.jsxs)(t6.Grid,{numItems:2,numItemsMd:5,className:"gap-4",children:[(0,t.jsx)(t5.Col,{children:(0,t.jsx)(si,{label:"Requests Evaluated",value:b.requestsEvaluated.toLocaleString()})}),(0,t.jsx)(t5.Col,{children:(0,t.jsx)(si,{label:"Fail Rate",value:`${b.failRate}%`,valueColor:b.failRate>15?"text-red-600":b.failRate>5?"text-amber-600":"text-green-600",subtitle:`${Math.round(b.requestsEvaluated*b.failRate/100).toLocaleString()} blocked`,icon:b.failRate>15?(0,t.jsx)(t2.WarningOutlined,{className:"text-red-400"}):void 0})}),(0,t.jsx)(t5.Col,{children:(0,t.jsx)(si,{label:"Avg. latency added",value:null!=b.avgLatency?`${Math.round(b.avgLatency)}ms`:"—",valueColor:null!=b.avgLatency?b.avgLatency>150?"text-red-600":b.avgLatency>50?"text-amber-600":"text-green-600":"text-gray-500",subtitle:null!=b.avgLatency?"Per request (avg)":"No data"})})]}),(0,t.jsx)(sr,{guardrailName:b.name,filterAction:"all",logs:f,logsLoading:j,totalLogs:y?.total??0,accessToken:a,startDate:r,endDate:n})]}),"logs"===o&&(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(sr,{guardrailName:b.name,logs:f,logsLoading:j,totalLogs:y?.total??0,accessToken:a,startDate:r,endDate:n})}),(0,t.jsx)(st,{open:c,onClose:()=>m(!1),guardrailName:b.name,accessToken:a})]})}let sd={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 sc=i.forwardRef(function(e,t){return i.createElement(tL.default,(0,tF.default)({},e,{ref:t,icon:sd}))}),sm=e.i(584935);function su({data:e}){let s=e&&e.length>0?e:[];return(0,t.jsxs)(u.Card,{className:"bg-white border border-gray-200",children:[(0,t.jsx)(eC.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)(sm.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 sx={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 sp({accessToken:e=null,startDate:s,endDate:a,onSelectGuardrail:r}){let[n,o]=(0,i.useState)("failRate"),[d,c]=(0,i.useState)("desc"),[m,x]=(0,i.useState)(!1),{data:p,isLoading:h,error:g}=(0,t4.useQuery)({queryKey:["guardrails-usage-overview",s,a],queryFn:()=>(0,l.getGuardrailsUsageOverview)(e,s,a),enabled:!!e}),y=p?.rows??[],j=(0,i.useMemo)(()=>{let e,t,s,a;return p?{totalRequests:p.totalRequests??0,totalBlocked:p.totalBlocked??0,passRate:String(p.passRate??0),avgLatency:y.length?Math.round(y.reduce((e,t)=>e+(t.avgLatency??0),0)/y.length):0,count:y.length}:(e=y.reduce((e,t)=>e+t.requestsEvaluated,0),t=y.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=y.filter(e=>null!=e.avgLatency)).length>0?Math.round(a.reduce((e,t)=>e+(t.avgLatency??0),0)/a.length):0,count:y.length})},[p,y]),f=p?.chart,b=(0,i.useMemo)(()=>[...y].sort((e,t)=>{let s="desc"===d?-1:1,a=e[n]??0,l=t[n]??0;return(Number(a)-Number(l))*s}),[y,n,d]),_=[{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:()=>r(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 ${sx[e]??sx.Custom}`,children:e})},{title:"Requests",dataIndex:"requestsEvaluated",key:"requestsEvaluated",align:"right",sorter:!0,sortOrder:"requestsEvaluated"===n?"desc"===d?"descend":"ascend":null,render:e=>e.toLocaleString()},{title:"Fail Rate",dataIndex:"failRate",key:"failRate",align:"right",sorter:!0,sortOrder:"failRate"===n?"desc"===d?"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"===n?"desc"===d?"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})]})}],v=["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)(t0.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)(G.Button,{type:"default",icon:(0,t.jsx)(tT.DownloadOutlined,{}),title:"Coming soon",children:"Export Data"})})]}),(0,t.jsxs)(t6.Grid,{numItems:2,numItemsLg:5,className:"gap-4 mb-6 items-stretch",children:[(0,t.jsx)(t5.Col,{className:"flex flex-col",children:(0,t.jsx)(si,{label:"Total Evaluations",value:j.totalRequests.toLocaleString()})}),(0,t.jsx)(t5.Col,{className:"flex flex-col",children:(0,t.jsx)(si,{label:"Blocked Requests",value:j.totalBlocked.toLocaleString(),valueColor:"text-red-600",icon:(0,t.jsx)(t2.WarningOutlined,{className:"text-red-400"})})}),(0,t.jsx)(t5.Col,{className:"flex flex-col",children:(0,t.jsx)(si,{label:"Pass Rate",value:`${j.passRate}%`,valueColor:"text-green-600",icon:(0,t.jsx)(sc,{className:"text-green-400"})})}),(0,t.jsx)(t5.Col,{className:"flex flex-col",children:(0,t.jsx)(si,{label:"Avg. latency added",value:`${j.avgLatency}ms`,valueColor:j.avgLatency>150?"text-red-600":j.avgLatency>50?"text-amber-600":"text-green-600"})}),(0,t.jsx)(t5.Col,{className:"flex flex-col",children:(0,t.jsx)(si,{label:"Active Guardrails",value:j.count})})]}),(0,t.jsx)("div",{className:"mb-6",children:(0,t.jsx)(su,{data:f})}),(0,t.jsxs)(u.Card,{className:"bg-white border border-gray-200 rounded-lg",children:[(h||g)&&(0,t.jsxs)("div",{className:"px-6 py-4 border-b border-gray-200 flex items-center gap-2",children:[h&&(0,t.jsx)(eL.Spin,{size:"small"}),g&&(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)(eC.Title,{className:"text-base font-semibold 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)(G.Button,{type:"default",icon:(0,t.jsx)(t1.SettingOutlined,{}),onClick:()=>x(!0),title:"Evaluation settings"})})]}),(0,t.jsx)(ts.Table,{columns:_,dataSource:b,rowKey:"id",pagination:!1,loading:h,onChange:(e,t,s)=>{s?.field&&v.includes(s.field)&&(o(s.field),c("ascend"===s.order?"asc":"desc"))},locale:0!==y.length||h?void 0:{emptyText:"No data for this period"},onRow:e=>({onClick:()=>r(e.id),style:{cursor:"pointer"}})})]}),(0,t.jsx)(st,{open:m,onClose:()=>x(!1),accessToken:e})]})}let sh=new Date,sg=new Date;function sy({accessToken:e=null}){let[s,a]=(0,i.useState)({type:"overview"}),r=(0,i.useMemo)(()=>new Date(sg),[]),n=(0,i.useMemo)(()=>new Date(sh),[]),[o,d]=(0,i.useState)({from:r,to:n}),c=o.from?(0,l.formatDate)(o.from):"",m=o.to?(0,l.formatDate)(o.to):"",u=(0,i.useCallback)(e=>{d(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)(tX.default,{value:o,onValueChange:u,label:"",showTimeRange:!1})}),"overview"===s.type?(0,t.jsx)(sp,{accessToken:e,startDate:c,endDate:m,onSelectGuardrail:e=>{a({type:"detail",guardrailId:e})}}):(0,t.jsx)(so,{guardrailId:s.guardrailId,onBack:()=>{a({type:"overview"})},accessToken:e,startDate:c,endDate:m})]})}sg.setDate(sg.getDate()-7);var sj=e.i(487304),sf=e.i(760221);e.i(111790);var sb=e.i(280881),s_=e.i(934879),sv=e.i(402874),sN=e.i(797305),sw=e.i(109799),sk=e.i(747871),sC=e.i(56567),sS=e.i(468133),sT=e.i(871943),sI=e.i(502547),sF=e.i(278587),sP=e.i(655913),sL=e.i(38419),sA=e.i(78334),sM=e.i(555436),sD=e.i(284614),sE=e.i(206929),sO=e.i(35983),sR=e.i(898586),sz=e.i(9314),sB=e.i(552130),sq=e.i(533882),s$=e.i(651904),sU=e.i(460285),sH=e.i(435451),sV=e.i(916940),sG=e.i(127952),sK=e.i(162386);let sW=(e,t,s)=>"Admin"===e||!!s&&!!t&&s.some(e=>e.members?.some(e=>e.user_id===t&&"org_admin"===e.user_role)),sQ=(e,t,s)=>"Admin"===e?s||[]:s&&t?s.filter(e=>e.members?.some(e=>e.user_id===t&&"org_admin"===e.user_role)):[],sY=({teams:e,searchParams:s,accessToken:a,setTeams:r,userID:n,userRole:o,organizations:d,premiumUser:c=!1})=>{let v,w,C,T;console.log(`organizations: ${JSON.stringify(d)}`);let{data:P}=(0,sw.useOrganizations)(),[L,A]=(0,i.useState)(""),[M,D]=(0,i.useState)(null),[E,O]=(0,i.useState)(null),[R,z]=(0,i.useState)(!1),[q,U]=(0,i.useState)({team_id:"",team_alias:"",organization_id:"",sort_by:"created_at",sort_order:"desc"});(0,i.useEffect)(()=>{console.log(`inside useeffect - ${L}`),a&&(0,eG.fetchTeams)(a,n,o,M,r),e7()},[L]);let[H]=S.Form.useForm(),[V]=S.Form.useForm(),{Title:K,Paragraph:W}=sR.Typography,[Q,Y]=(0,i.useState)(""),[J,X]=(0,i.useState)(!1),[Z,ee]=(0,i.useState)(null),[et,es]=(0,i.useState)(null),[ea,el]=(0,i.useState)(!1),[er,ei]=(0,i.useState)(!1),[en,eo]=(0,i.useState)(!1),[ed,ec]=(0,i.useState)(!1),[em,eu]=(0,i.useState)([]),[ex,ep]=(0,i.useState)(!1),[eh,eg]=(0,i.useState)(null),[ey,ej]=(0,i.useState)([]),[e_,ev]=(0,i.useState)({}),[eN,ew]=(0,i.useState)(!1),[eC,eL]=(0,i.useState)([]),[eA,eM]=(0,i.useState)([]),[eD,eE]=(0,i.useState)({}),[eO,eR]=(0,i.useState)([]),[e$,eU]=(0,i.useState)([]),[eH,eV]=(0,i.useState)(!1),[eK,eZ]=(0,i.useState)({}),[e0,e1]=(0,i.useState)(null),[e2,e4]=(0,i.useState)(0);(0,i.useEffect)(()=>{let e;console.log(`currentOrgForCreateTeam: ${E}`);let t=(e=[],E&&E.models.length>0?(console.log(`organization.models: ${E.models}`),e=E.models):e=em,(0,$.unfurlWildcardModelsInList)(e,em));console.log(`models: ${t}`),ej(t),H.setFieldValue("models",[])},[E,em]),(0,i.useEffect)(()=>{if(er){let e=sQ(o,n,d);if(1===e.length){let t=e[0];H.setFieldValue("organization_id",t.organization_id),O(t)}else H.setFieldValue("organization_id",M?.organization_id||null),O(M)}},[er,o,n,d,M]),(0,i.useEffect)(()=>{let e=async()=>{try{if(null==a)return;let e=(await (0,l.getPoliciesList)(a)).policies.map(e=>e.policy_name);eM(e)}catch(e){console.error("Failed to fetch policies:",e)}};(async()=>{try{if(null==a)return;let e=(await (0,l.getGuardrailsList)(a)).guardrails.map(e=>e.guardrail_name);eL(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})(),e()},[a]);let e5=async()=>{try{if(null==a)return;let e=await (0,l.fetchMCPAccessGroups)(a);eU(e)}catch(e){console.error("Failed to fetch MCP access groups:",e)}};(0,i.useEffect)(()=>{e5()},[a]),(0,i.useEffect)(()=>{e&&ev(e.reduce((e,t)=>(e[t.team_id]={keys:t.keys||[],team_info:{members_with_roles:t.members_with_roles||[]}},e),{}))},[e]);let e6=async e=>{eg(e),ep(!0)},e3=async()=>{if(null!=eh&&null!=e&&null!=a)try{ew(!0),await (0,l.teamDeleteCall)(a,eh.team_id),await (0,eG.fetchTeams)(a,n,o,M,r),ez.default.success("Team deleted successfully")}catch(e){ez.default.fromBackend("Error deleting the team: "+e)}finally{ew(!1),ep(!1),eg(null)}};(0,i.useEffect)(()=>{(async()=>{try{if(null===n||null===o||null===a)return;let e=await (0,$.fetchAvailableModelsForTeamOrKey)(n,o,a);e&&eu(e)}catch(e){console.error("Error fetching user models:",e)}})()},[a,n,o,e]);let e8=async t=>{try{if(console.log(`formValues: ${JSON.stringify(t)}`),null!=a){let s=t?.team_alias,i=e?.map(e=>e.team_alias)??[],n=t?.organization_id||M?.organization_id;if(""===n||"string"!=typeof n?t.organization_id=null:t.organization_id=n.trim(),i.includes(s))throw Error(`Team alias ${s} already exists, please pick another alias`);if(ez.default.info("Creating Team"),eO.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:eO.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(eK).length>0&&(t.model_aliases=eK),e0?.router_settings&&Object.values(e0.router_settings).some(e=>null!=e&&""!==e)&&(t.router_settings=e0.router_settings);let o=await (0,l.teamCreateCall)(a,t);null!==e?r([...e,o]):r([o]),console.log(`response for team create call: ${o}`),ez.default.success("Team created"),H.resetFields(),eR([]),eZ({}),e1(null),e4(e=>e+1),ei(!1)}}catch(e){console.error("Error creating the team:",e),ez.default.fromBackend("Error creating the team: "+e)}},e7=()=>{A(new Date().toLocaleString())},e9=(e,t)=>{let s={...q,[e]:t};U(s),a&&(0,l.v2TeamListCall)(a,s.organization_id||null,null,s.team_id||null,s.team_alias||null).then(e=>{e&&e.teams&&r(e.teams)}).catch(e=>{console.error("Error fetching teams:",e)})};return(0,t.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:(0,t.jsx)(t6.Grid,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,t.jsxs)(t5.Col,{numColSpan:1,className:"flex flex-col gap-2",children:[sW(o,n,d)&&(0,t.jsx)(m.Button,{className:"w-fit",onClick:()=>ei(!0),children:"+ Create New Team"}),et?(0,t.jsx)(sC.default,{teamId:et,onUpdate:e=>{r(t=>{if(null==t)return t;let s=t.map(t=>e.team_id===t.team_id?(0,eB.updateExistingKeys)(t,e):t);return a&&(0,eG.fetchTeams)(a,n,o,M,r),s})},onClose:()=>{es(null),el(!1)},accessToken:a,is_team_admin:(e=>{if(null==e||null==e.members_with_roles)return!1;for(let t=0;t