1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["static/js/MonacoEditorInworld.SJq08rdx.js","static/js/vendor-core.6lta8LCj.js","static/js/vendor-monaco.BY-XW2OX.js","static/css/vendor-monaco.BCAKnara.css","static/js/bootstrap.Yl9dpo2n.js","static/js/vendor-mui-x.CmnfcHjQ.js","static/js/vendor-firebase.dbYXL2Q0.js","static/css/bootstrap.DSk3wTEy.css","static/css/MonacoEditorInworld.ChdngT_x.css","static/js/MonacoEditorYaml.FwpjT1aw.js","static/js/MonacoEditorJson.CAJuT6p2.js"])))=>i.map(i=>d[i]); 2import{j as e,a as l,W as qt,_ as bn}from"./vendor-core.6lta8LCj.js";import{u as vn,a as kt,s as Fn,K as Vn,P as yn,D as jn,c as Cn,S as In,h as pr,d as Sn,C as wn,e as mr,v as Un}from"./utilities.esm.BVvU8PSu.js";import{B as p,R as X,a0 as fe,b as D,c as A,aA as pn,F as _,aM as Jt,cN as it,S as C,k as xr,j as hr,e5 as Tt,ai as $e,_ as Hn,J as Jn,H as Xt,z as gr,aj as St,af as nt,cF as mn,cG as Ft,L as fr,az as br,e6 as vr,cP as yr,cO as Rn,aT as Kt,a1 as jr,I as Ze,a as et,bL as Cr,e7 as Ir,Q as Sr,as as Be,au as Fe,at as Ve,dM as Vt,dQ as xn}from"./bootstrap.Yl9dpo2n.js";import{t as Kn,l as xt,g as ze,C as ke,m as Gn,n as Yn,o as qn,q as hn,f as wr,w as kr,L as Tr,F as Rr}from"./App.DVmysEmP.js";import{u as Mr}from"./llmService.CJ0clZoM.js";import{d as Ge,S as tt,e as Er,c as Ar,a as Dr,b as $r,f as zr}from"./smartRouter.BP9cn_gE.js";import{D as Lr}from"./DirtyFormConfirmation.BPNvcDSj.js";import{a5 as Xn,x as Le,s as _r,y as f,aN as ct,aS as at,a7 as se,ae as Ce,ag as ve,bF as Or,aO as Wr,a6 as Te,ah as Pr,aj as kn,c as ht,aI as st,aQ as Qn,aL as rt,aM as He,bT as Zn,bI as De,b7 as Ue,bU as er,P as tr,ao as Nr,aT as Br,b4 as Fr,b5 as Vr,b6 as nn,aJ as Ur,b0 as Hr,aU as Ut,b1 as Mn,aW as Jr,aX as En}from"./vendor-mui-x.CmnfcHjQ.js";import{L as nr}from"./LightCodeEditor.D34V_3nv.js";import{S as Kr}from"./SnippetWrapper.CzNs_vv5.js";import{S as lt}from"./Slider.DKbSeTyH.js";import{l as U}from"./vendor-monaco.BY-XW2OX.js";import{CodeSnippetButton as Gr}from"./CodeSnippetButton.Ds1-yLOk.js";import{g as Rt}from"./voiceTagColors.B7cdZCgY.js";import{g as mt}from"./providerLogos.CKA9kfSK.js";import{g as ut,c as Yr,d as Ot,a as Wt,v as rn,t as rr,b as An,w as qr}from"./routerFormUtils.fSE7KH-B.js";import{P as dt,c as Dn,d as on}from"./ProviderPile.B3e76E_5.js";import{I as Xr}from"./InworldTable.Bg1TNXf6.js";import{k as Qr,u as Zr,l as jt,m as eo,e as to,h as no,n as ro,M as ot,o as gn}from"./routerMetrics.CCqQxdf-.js";import{a as oo,N as so}from"./NewMetricDialog.DvNyjl-C.js";import{b as io,c as Ct,d as ao}from"./TableRow.DHrqjvOH.js";import{P as or}from"./PickerDetails.Dz0X-toH.js";import{P as lo,a as co,b as uo,c as po}from"./PickerPopover.t-yVLseZ.js";import{T as Pt,f as mo}from"./modelSearch.BnPIeKUI.js";import{g as xo,c as ho,e as $n,d as go,f as zn}from"./constants.p722zpec.js";import"./vendor-firebase.dbYXL2Q0.js";import"./json.Vo5Fm4gT.js";import"./unsupportedIterableToArray.BlAcjINT.js";import"./defineProperty.DwNX8CmR.js";import"./IntegrateDialog.Cp34FTAH.js";import"./useRuntimeApiKeysManager.CpyotMBT.js";import"./integrateCodeGeneration.DREkKIeG.js";import"./types.CrUXJ4kA.js";import"./RadioGroup.2o-9YZiq.js";import"./ModelProviderLogos.AV43A1Lq.js";import"./table.JTfPwsOB.js";import"./useQueries.AyQcqfc2.js";import"./query_service.pb.DHkdEcVX.js";const fo=_r("svg")({position:"absolute"}),bo=({sx:t,children:n,onEdit:r,isLoading:s})=>e.jsxs(p,{component:"div",sx:{position:"relative",overflow:"hidden",borderRadius:X.md,border:"1px solid",borderColor:a=>a.palette.divider,"&::before":{content:'""',display:"block",position:"absolute",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",background:a=>Le(a.palette.background.default,.5),zIndex:1}},children:[e.jsx(p,{"aria-label":"Edit button",component:"div",onClick:()=>r==null?void 0:r(!0),sx:{display:"flex",alignItems:"center",justifyContent:"center",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",height:"100%",width:"100%",cursor:"pointer",zIndex:2,"&:hover":{"& .MuiButton-root":{transform:"scale(1.1)"}}},children:e.jsx(fe,{"aria-label":"Edit",startIcon:e.jsx(D,{icon:A.faPen}),size:"medium",onClick:()=>r==null?void 0:r(!0),sx:{transition:"all 0.3s "},children:"Edit"})}
2),e.jsx(p,{component:"div",sx:{filter:"url(#grayscale)",...t},children:n}),e.jsx(fo,{xmlns:"http://www.w3.org/2000/svg",version:"1.1",width:"0",height:"0",children:e.jsx("defs",{children:e.jsx("filter",{id:"grayscale",children:e.jsx("feColorMatrix",{type:"saturate",values:"0"})})})}),s&&e.jsx(p,{component:"div",sx:{width:"100%",height:"100%",position:"absolute",top:"0",zIndex:10,backgroundColor:a=>Le(a.palette.background.default,.5),display:"flex",justifyContent:"center",alignItems:"center"},children:e.jsx(Xn,{})})]}),sn=JSON.stringify([{role:"system",content:"You are a helpful assistant named {{character_name}}.",compression:{aggressiveness:.7}},{role:"user",content:"Hello!"}],null,2),vo=t=>{if(!t.trim())return null;try{const n=JSON.parse(t);if(!Array.isArray(n))return'Must be a JSON array â e.g. [{ "role": "system", "content": "..." }]';if(n.length===0)return"Array cannot be empty â add at least one message object";const r=n.findIndex(s=>!s||typeof s!="object"||!s.role);return r!==-1?`Item at index ${r} is missing the required "role" field`:null}catch(n){return"Invalid JSON â check for missing quotes, commas, or brackets"}},yo=({open:t,initialValue:n,onApply:r,onCancel:s})=>{const[a,i]=l.useState(n),[h,m]=l.useState(null),x=a.trim()==="",c=l.useRef(null);l.useEffect(()=>{t&&(i(n),m(null))},[t,n]);const v=l.useCallback(()=>{const I=vo(a);if(I){m(I);return}m(null),r(a)},[a,r]),y=l.useCallback(()=>{var E;i(sn);const I=(E=c.current)==null?void 0:E.querySelector(".light-code-editor-textarea");I==null||I.focus()},[]);return e.jsx(pn,{controlled:!0,open:t,onClose:s,size:"lg",title:"Edit prompt template",transitionDuration:{enter:225,exit:0},slotProps:{paper:{sx:{height:"100%","& .MuiDialogContent-root":{display:"flex",flexDirection:"column",minHeight:0,overflow:"hidden"}}}},primary:{label:"Apply",ariaLabel:"Apply message template",preventAutoClose:!0,onClick:v},secondary:{ariaLabel:"Cancel message template editor",preventAutoClose:!0,onClick:s},children:e.jsxs(p,{component:"div",sx:{display:"grid",gridTemplateColumns:"calc(100% - 20rem - 16px) 20rem",gridTemplateRows:"1fr",alignItems:"stretch",gap:2,flex:1,minHeight:0,py:1},children:[e.jsxs(p,{component:"div",sx:{minWidth:0,display:"flex",flexDirection:"column"},children:[e.jsxs(p,{ref:c,component:"div",sx:{border:"1px solid",borderColor:h?"error.main":"divider",borderRadius:X.md,overflow:"hidden",position:"relative",flex:1,display:"flex",flexDirection:"column"},children:[e.jsx(nr,{value:a,onValueChange:i,height:"100%"}),x&&e.jsx(p,{component:"div",sx:{position:"absolute",top:"8px",left:"8px",pointerEvents:"none",color:"text.disabled",fontFamily:Jt.mono,fontSize:_.md,lineHeight:"1.5",whiteSpace:"pre",userSelect:"none"},children:sn}),e.jsx(fe,{"aria-label":"Insert sample prompt",size:"small",onClick:y,sx:{position:"absolute",bottom:"0.5rem",right:"0.5rem",minHeight:"unset",opacity:.85,"&:hover":{opacity:1}},children:"Insert sample prompt"})]}),h&&e.jsx(Kn,{severity:"error",sx:{mt:1},children:h})]}),e.jsxs(p,{component:"div",sx:{display:"flex",flexDirection:"column",gap:1.5,overflowY:"auto",minHeight:0},children:[e.jsx(f,{variant:"body1",sx:{fontWeight:600},children:"Edit prompt template"}),e.jsx(f,{variant:"body1",children:"Prompt template used by default with all routes in this router. Can be overridden by a variant-specific template."}),e.jsx(f,{variant:"body1",sx:{color:"text.secondary"},children:"Users can specify variables that they can then pass in when they make their API call"}),e.jsx(f,{variant:"body1",sx:{color:"text.secondary"},children:"Messages sent in the API call then get appended to the prompt template"}),e.jsx(Kr,{title:"Sample prompt template",content:sn,language:"json"}),e.jsx(f,{variant:"body1",sx:{color:"text.secondary"},children:'ð¡ Add "compression" field to any message to reduce tokens. See sample above.'}),e.jsx(ct,{})]})]})})},jo=({fieldName:t})=>{const{setValue:n}=xt(),r=ze({name:`${t}.enabled`});return e.jsxs(p,{component:"div","aria-label":r?void 0:"Enable Prompt Compression",onClick:r?void 0:()=>n(`${t}.enabled`,!0,{shouldDirty:!0}),sx:{border:`${r?"solid":"dashed"} 1px`,borderColor:"divider",borderRadius:X.md,minHeight:"3rem",px:"0.5rem",py:r?"0.5rem":0,display:"flex",flexDirection:"column",justifyContent:"center",backgroundColor:"transparent",curs
2or:r?"default":"pointer","&:hover":r?void 0:{borderColor:it}},children:[e.jsxs(C,{direction:"row",sx:{alignItems:"center",gap:1,mb:r?1:0},children:[e.jsx(at,{size:"small",checked:!!r,onChange:s=>{s.stopPropagation(),n(`${t}.enabled`,s.target.checked,{shouldDirty:!0})},sx:{p:.25,flexShrink:0},slotProps:{input:{"aria-label":"Enable Prompt Compression"}}}),e.jsx(se,{title:"Compress long message templates before sending to the LLM to reduce token usage. Applies to all templates in this variant.",placement:"right",arrow:!0,children:e.jsx(f,{variant:"body2",sx:{userSelect:"none",color:"text.primary"},children:"Prompt Compression"})})]}),r&&e.jsx(ke,{name:`${t}.aggressiveness`,render:({field:s})=>{var a,i;return e.jsxs(C,{direction:"row",sx:{alignItems:"center",gap:1,border:"solid 1px",borderColor:"divider",borderRadius:X.md,height:"3rem",px:"0.5rem"},children:[e.jsx(f,{variant:"body2",sx:{minWidth:"7.5rem",color:"text.primary",userSelect:"none",flexShrink:0,"@container (max-width: 700px)":{minWidth:0,flex:1}},children:"Aggressiveness"}),e.jsx(p,{component:"div",sx:{display:"flex",flex:1,minWidth:"2rem",alignItems:"center","@container (max-width: 700px)":{display:"none"}},children:e.jsx(lt,{size:"small",min:0,max:1,step:.1,value:(a=s.value)!=null?a:.5,onChange:(h,m)=>s.onChange(m),"aria-label":"Compression aggressiveness"})}),e.jsx(Ce,{size:"small",type:"number",value:(i=s.value)!=null?i:.5,onChange:h=>{const m=parseFloat(h.target.value);isNaN(m)||s.onChange(Math.min(1,Math.max(0,m)))},slotProps:{htmlInput:{min:0,max:1,step:.1,"aria-label":"Aggressiveness value"}},sx:{width:"4.5rem",flexShrink:0,"@container (max-width: 700px)":{width:"3.5rem"},"& .MuiInputBase-root":{height:"2rem"},"& .MuiInputBase-input":{textAlign:"right",py:"0.25rem",px:1,fontSize:_.md,MozAppearance:"textfield","&::-webkit-outer-spin-button, &::-webkit-inner-spin-button":{WebkitAppearance:"none",margin:0}}}})]})}})]})},Ln=({name:t,label:n,min:r,max:s,defaultValue:a})=>e.jsx(ke,{name:t,render:({field:i})=>{var h,m;return e.jsxs(C,{direction:"row",sx:{alignItems:"center",gap:1,border:"solid 1px",borderColor:"divider",borderRadius:X.md,height:"3rem",px:"0.5rem"},children:[e.jsx(f,{variant:"body2",sx:{minWidth:"7.5rem",color:"text.primary",userSelect:"none",flexShrink:0,"@container (max-width: 700px)":{minWidth:0,flex:1}},children:n}),e.jsx(p,{component:"div",sx:{display:"flex",flex:1,minWidth:"2rem",alignItems:"center","@container (max-width: 700px)":{display:"none"}},children:e.jsx(lt,{size:"small",min:r,max:s,step:1,value:(h=i.value)!=null?h:a,onChange:(x,c)=>i.onChange(c),"aria-label":n})}),e.jsx(Ce,{size:"small",type:"number",value:(m=i.value)!=null?m:a,onChange:x=>{const c=parseInt(x.target.value,10);isNaN(c)||i.onChange(Math.min(s,Math.max(r,c)))},slotProps:{htmlInput:{min:r,max:s,step:1,"aria-label":`${n} value`}},sx:{width:"4.5rem",flexShrink:0,"@container (max-width: 700px)":{width:"3.5rem"},"& .MuiInputBase-root":{height:"2rem"},"& .MuiInputBase-input":{textAlign:"right",py:"0.25rem",px:1,fontSize:_.md,MozAppearance:"textfield","&::-webkit-outer-spin-button, &::-webkit-inner-spin-button":{WebkitAppearance:"none",margin:0}}}})]})}}),Co=({fieldName:t})=>{const{setValue:n}=xt(),r=ze({name:`${t}.enabled`});return e.jsxs(p,{component:"div","aria-label":r?void 0:"Enable Web Search",onClick:r?void 0:()=>n(`${t}.enabled`,!0,{shouldDirty:!0}),sx:{border:`${r?"solid":"dashed"} 1px`,borderColor:"divider",borderRadius:X.md,minHeight:"3rem",px:"0.5rem",py:r?"0.5rem":0,display:"flex",flexDirection:"column",justifyContent:"center",backgroundColor:"transparent",cursor:r?"default":"pointer","&:hover":r?void 0:{borderColor:it}},children:[e.jsxs(C,{direction:"row",sx:{alignItems:"center",gap:1,mb:r?1:0},children:[e.jsx(at,{size:"small",checked:!!r,onChange:s=>{s.stopPropagation(),n(`${t}.enabled`,s.target.checked,{shouldDirty:!0})},sx:{p:.25,flexShrink:0},slotProps:{input:{"aria-label":"Enable Web Search"}}}),e.jsx(se,{title:"Route requests through a web search engine before sending to the model. Only tool-based search is available at the router level.",placement:"right",arrow:!0,children:e.jsx(f,{variant:"body2",sx:{userSelect:"none",color:"text.primary"},children:"Web Search"})})]}),r&&e.jsxs(C,{spacing:1,sx:{mt:.5},children:[e.jsx(ke,{name:`${t}.engine`,render:({field:s})=>e.jsxs(Ce,{select:!0,size:"small",fullWidth:!0,value:s.value||"exa",onChange:s.onChange,"aria-label":"Web search engine",sx:{"& .MuiInputBase-root":{height:"2rem"},"& .MuiSelect-select":{py:"0.25rem",fontSize:_.md}},children:[e.jsx(ve,{value:"exa","aria-label":"Exa",children:"Exa"}),e.jsx(ve,{value:"google","aria-label":"Google",children:"Google"}),e.jsx(ve,{value:"brave","aria-label":"Brave",children:"Brave"}),e.jsx(ve,{value:"native","aria-label":"Native (provider built-in)",children:"Native (provider built-in)"})]})}),e.jsx(Ln,{name:`${t}.maxResults`,label:"Max Results",min:1,max:20,defaultValue:3}),e.jsx(Ln,{name:`${t}.maxSteps`,label:"Max Steps",min:1,max:5,defaultValue:1})]})]})},_n='{"stopSequences":[],"logitBias":[]}',Io=[{key:"temperature",label:"Temperature",description:"Sampling temperature between 0 and 2. Higher values make output more random.",min:0,max:2,step:.01,defaultValue:1},{key:"topP",label:"Top P",description:"Nucleus sampling parameter. Must be greater than 0. Lower values focus the model on high-probability tokens.",min:.01,max:1,step:.
201,defaultValue:1},{key:"maxTokens",label:"Max Tokens",description:"Maximum number of tokens to generate in the response.",min:1,max:32768,step:1,defaultValue:1e3},{key:"repetitionPenalty",label:"Repetition Penalty",description:"Values > 1 discourage repetition; values < 1 encourage it. Neutral = 1.0.",min:.1,max:2,step:.01,defaultValue:1},{key:"frequencyPenalty",label:"Frequency Penalty",description:"Penalizes tokens based on frequency in the text. Range: â2 to 2.",min:-2,max:2,step:.01,defaultValue:0},{key:"presencePenalty",label:"Presence Penalty",description:"Penalizes tokens based on presence in the text. Range: â2 to 2.",min:-2,max:2,step:.01,defaultValue:0},{key:"seed",label:"Seed",description:"Random seed for reproducible generation. The same seed with the same prompt produces the same output.",min:0,max:2147483647,step:1,defaultValue:0,noSlider:!0}],So=[{key:"reasoning.effort",label:"Reasoning Effort",description:"Controls how much reasoning effort the model uses. Provider/model-specific â may not be supported by all models.",options:[{value:Ge.EFFORT_NONE,label:"None"},{value:Ge.EFFORT_MINIMAL,label:"Minimal"},{value:Ge.EFFORT_LOW,label:"Low"},{value:Ge.EFFORT_MEDIUM,label:"Medium"},{value:Ge.EFFORT_HIGH,label:"High"},{value:Ge.EFFORT_XHIGH,label:"xHigh"},{value:Ge.EFFORT_MAX,label:"Max"}],defaultValue:Ge.EFFORT_MEDIUM}],On=(t,n)=>{if(!n.includes("."))return t[n];const[r,s]=n.split("."),a=t[r];if(a&&typeof a=="object")return a[s]},wo=(t,n,r)=>{var h;const s={...t};if(!n.includes("."))return r===void 0?delete s[n]:s[n]=r,s;const[a,i]=n.split(".");if(r===void 0){const m=s[a];if(m&&typeof m=="object"){const x={...m};delete x[i],Object.keys(x).length===0?delete s[a]:s[a]=x}}else s[a]={...(h=s[a])!=null?h:{},[i]:r};return s},ko=({def:t,checked:n,value:r,onToggle:s,onChange:a})=>{const i=t.key==="maxTokens"||t.key==="seed",h=m=>{const x=i?parseInt(m.target.value,10):parseFloat(m.target.value);isNaN(x)||a(Math.min(t.max,Math.max(t.min,x)))};return e.jsxs(C,{direction:"row","aria-label":n?void 0:`Enable ${t.label}`,onClick:n?void 0:()=>s(!0),sx:{alignItems:"center",gap:1,border:`${n?"solid":"dashed"} 1px`,borderColor:"divider",borderRadius:X.md,height:"3rem",px:"0.5rem",cursor:n?"default":"pointer","&:hover":n?void 0:{borderColor:it}},children:[e.jsx(at,{size:"small",checked:n,onChange:m=>{m.stopPropagation(),s(m.target.checked)},sx:{p:.25,flexShrink:0},slotProps:{input:{"aria-label":`Enable ${t.label}`}}}),e.jsx(se,{title:t.description,placement:"right",arrow:!0,children:e.jsx(f,{variant:"body2",sx:{minWidth:"7.5rem",color:"text.primary",userSelect:"none",flexShrink:0,"@container (max-width: 700px)":{minWidth:0,flex:1}},children:t.label})}),t.noSlider?e.jsx(p,{component:"div",sx:{flex:1}}):e.jsx(p,{component:"div",sx:{display:"flex",flex:1,minWidth:"3rem",alignItems:"center","@container (max-width: 700px)":{display:"none"}},children:e.jsx(lt,{size:"small",value:r,min:t.min,max:t.max,step:t.step,disabled:!n,onChange:(m,x)=>a(x),"aria-label":t.label})}),e.jsx(Ce,{size:"small",type:"number",value:r,onChange:h,disabled:!n,slotProps:{htmlInput:{min:t.min,max:t.max,step:t.step,"aria-label":`${t.label} value`}},sx:[Tt,{width:"4.5rem",flexShrink:0,"@container (max-width: 700px)":{width:"3.5rem"},"& .MuiInputBase-root":{height:"2rem"},"& .MuiInputBase-input":{textAlign:"right",py:"0.25rem",px:1,fontSize:_.md,MozAppearance:"textfield","&::-webkit-outer-spin-button, &::-webkit-inner-spin-button":{WebkitAppearance:"none",margin:0}}}]})]})},To=({def:t,checked:n,value:r,onToggle:s,onChange:a})=>e.jsxs(C,{direction:"row","aria-label":n?void 0:`Enable ${t.label}`,onClick:n?void 0:()=>s(!0),sx:{alignItems:"center",gap:1,border:`${n?"solid":"dashed"} 1px`,borderColor:"divider",borderRadius:X.md,height:"3rem",px:"0.5rem",backgroundColor:"transparent",cursor:n?"default":"pointer","&:hover":n?void 0:{borderColor:it}},children:[e.jsx(at,{size:"small",checked:n,onChange:i=>{i.stopPropagation(),s(i.target.checked)},sx:{p:.25,flexShrink:0},slotProps:{input:{"aria-label":`Enable ${t.label}`}}}),e.jsx(se,{title:t.description,placement:"right",arrow:!0,children:e.jsx(f,{variant:"body2",sx:{minWidth:"7.5rem",color:"text.primary",userSelect:"none",flexShrink:0,"@container (max-width: 700px)":{minWidth:0,flex:1}},children:t.label})}),e.jsx(p,{component:"div",sx:{flex:1,"@container (max-width: 700px)":{display:"none"}}}),e.jsx(Or,{size:"small",sx:{minWidth:110,flexShrink:0,"@container (max-width: 700px)":{minWidth:90}},children:e.jsx(Wr,{value:r,onChange:i=>a(i.target.value),disabled:!n,inputProps:{"aria-label":`${t.label} value`},sx:[Tt,{fontSize:_.md,height:"2rem","& .MuiSelect-select":{py:"0.25rem"}}],children:t.options.map(i=>e.jsx(ve,{value:i.value,"aria-label":i.label,children:i.label},i.value))})})]}),Ro=({items:t,onChange:n})=>{const r=(s,a,i)=>n(t.map((h,m)=>m===s?{...h,[a]:i}:h));return e.jsxs(C,{sx:{gap:1},children:[t.map((s,a)=>{var i,h,m;return e.jsxs(C,{direction:"row",sx:{gap:1,alignItems:"center"},children:[e.jsx(Ce,{size:"small",placeholder:"Token ID",value:(i=s.tokenId)!=null?i:"",onCh
2ange:x=>r(a,"tokenId",x.target.value),slotProps:{htmlInput:{"aria-label":"Token ID"}},sx:{width:110,"& .MuiInputBase-input":{py:.5,px:1,fontSize:_.md}}}),e.jsx(lt,{size:"small",value:(h=s.biasValue)!=null?h:0,min:-100,max:100,step:1,onChange:(x,c)=>r(a,"biasValue",c),"aria-label":"Bias value",sx:{flex:1}}),e.jsx(f,{variant:"caption",sx:{width:32,textAlign:"right",flexShrink:0},children:(m=s.biasValue)!=null?m:0}),e.jsx(Te,{size:"small",onClick:()=>n(t.filter((x,c)=>c!==a)),"aria-label":"Remove logit bias entry",children:e.jsx(D,{icon:A.faTrash,size:"sm"})})]},a)}),e.jsx(fe,{intent:"ghost",size:"small",startIcon:e.jsx(D,{icon:A.faPlus}),onClick:()=>n([...t,{tokenId:"",biasValue:0}]),"aria-label":"Add logit bias entry",sx:{alignSelf:"flex-start"},children:"Add token"})]})},Mo=({fieldName:t,defaultsFieldName:n,webSearchFieldName:r,compressionFieldName:s,fallbackFieldName:a})=>{var g,ce,de,Q;const i=xr(hr.STUDIO_V2_ROUTER_TTFT_TIMEOUT),{setValue:h}=xt(),m=ze({name:t}),x=ze({name:n!=null?n:t}),c=l.useMemo(()=>{if(!n||!x)return{};try{const R=JSON.parse(x);if(R&&typeof R=="object"&&!Array.isArray(R))return R}catch(R){}return{}},[n,x]),v=l.useMemo(()=>{if(!m&&n)return c;if(!m)return{};try{const R=JSON.parse(m);if(R&&typeof R=="object"&&!Array.isArray(R))return R}catch(R){}return{}},[m,n,c]),y=!m&&!!n,I=l.useCallback((R,F)=>{const te=y?{...c}:v,ae=wo(te,R,F),J=Object.keys(ae).length>0;h(t,J?JSON.stringify(ae,null,2):n?_n:"",{shouldDirty:!0})},[v,c,y,t,n,h]),E=(g=v.logitBias)!=null?g:[],V=l.useCallback(R=>{const F=y?{...c}:{...v};R.length===0?delete F.logitBias:F.logitBias=R;const te=Object.keys(F).length>0;h(t,te?JSON.stringify(F,null,2):n?_n:"",{shouldDirty:!0})},[v,c,y,t,n,h]),H=E.length>0,M=ze({name:a?`${a}.ttftTimeoutEnabled`:""}),T=ze({name:a?`${a}.ttftTimeoutMs`:""}),N=(ce=a==null?void 0:a.replace(/\.fallback$/,""))!=null?ce:"",ne=ze({name:N?`${N}.modelSelection.models`:""}),z=((Q=(de=ne==null?void 0:ne.filter(R=>R==null?void 0:R.model))==null?void 0:de.length)!=null?Q:0)>0,ee=l.useCallback(R=>{a&&(h(`${a}.ttftTimeoutEnabled`,R,{shouldDirty:!0}),R&&!T&&h(`${a}.ttftTimeoutMs`,1e3,{shouldDirty:!0}))},[a,h,T]),pe=l.useCallback(R=>{if(!a)return;const F=Math.min(5e3,Math.max(300,R));h(`${a}.ttftTimeoutMs`,F,{shouldDirty:!0})},[a,h]);return e.jsx(p,{component:"div",sx:{containerType:"inline-size"},children:e.jsx(p,{component:"div",sx:{opacity:1},children:e.jsxs(p,{component:"div",sx:{display:"grid",gridTemplateColumns:"repeat(2, 1fr)",gap:"0.375rem","@container (max-width: 700px)":{gridTemplateColumns:"1fr"}},children:[Io.map(R=>{const F=On(v,R.key),te=F!==void 0;return e.jsx(p,{component:"div",children:e.jsx(ko,{def:R,checked:te,value:te?F:R.defaultValue,onToggle:ae=>I(R.key,ae?R.defaultValue:void 0),onChange:ae=>I(R.key,ae)})},R.key)}),So.map(R=>{const F=On(v,R.key),te=F!==void 0;return e.jsx(p,{component:"div",children:e.jsx(To,{def:R,checked:te,value:te?F:R.defaultValue,onToggle:ae=>I(R.key,ae?R.defaultValue:void 0),onChange:ae=>I(R.key,ae)})},R.key)}),e.jsx(p,{component:"div",sx:{gridColumn:a?"1":"1 / -1"},children:e.jsxs(p,{component:"div","aria-label":H?void 0:"Enable Logit Bias",onClick:H?void 0:()=>V([{tokenId:"",biasValue:0}]),sx:{border:`${H?"solid":"dashed"} 1px`,borderColor:"divider",borderRadius:X.md,minHeight:"3rem",px:"0.5rem",py:H?"0.5rem":0,display:"flex",flexDirection:"column",justifyContent:"center",backgroundColor:"transparent",cursor:H?"default":"pointer","&:hover":H?void 0:{borderColor:it}},children:[e.jsxs(C,{direction:"row",sx:{alignItems:"center",gap:1,mb:H?1:0},children:[e.jsx(at,{size:"small",checked:H,onChange:R=>{R.stopPropagation(),V(R.target.checked?[{tokenId:"",biasValue:0}]:[])},sx:{p:.25,flexShrink:0},slotProps:{input:{"aria-label":"Enable Logit Bias"}}}),e.jsx(se,{title:"Modifies the likelihood of specific tokens appearing in the completion. Bias values range from â100 to 100.",placement:"right",arrow:!0,children:e.jsx(f,{variant:"body2",sx:{userSelect:"none",color:"text.primary"},children:"Logit Bias"})})]}),H&&e.jsx(Ro,{items:E,onChange:V})]})}),i&&a&&e.jsx(p,{component:"div",sx:{gridColumn:"2","@container (max-width: 700px)":{gridColumn:"1"}},children:e.jsxs(C,{direction:"row","aria-label":M?void 0:"Enable TTFT Timeout",onClick:!M&&z?()=>ee(!0):void 0,sx:{alignItems:"center",gap:1,border:`${M?"solid":"dashed"} 1px`,borderColor:"divider",borderRadius:X.md,height:"3rem",px:"0.5rem",cursor:!M&&z?"pointer":"default",opacity:z?1:.5,"&:hover":!M&&z?{borderColor:it}:void 0},children:[e.jsx(at,{size:"small",checked:!!M,disabled:!z,onChange:R=>{R.stopPropagation(),ee(R.target.checked)},sx:{p:.25,flexShrink:0},slotProps:{input:{"aria-label":"Enable TTFT Timeout"}}}),e.jsx(se,{title:z?"Time to first token timeout. If the primary model doesn't return the first token within this threshold, the request falls back to the next model.":"Time to first token timeout. Add fallback models to enable TTFT timeout.",placement:"right",arrow:!0,children:e.jsx(f,{variant:"body2",sx:{minWidth:"7.5rem",color:"text.primary",userSelect:"none",flexShrink:0,"@container (max-width: 700px)":{minWidth:0,flex:1}},children:"TTFT Timeout (ms)"})}
2),e.jsx(p,{component:"div",sx:{display:"flex",flex:1,minWidth:"3rem",alignItems:"center","@container (max-width: 700px)":{display:"none"}},children:e.jsx(lt,{size:"small",value:T!=null?T:1e3,min:300,max:5e3,step:100,disabled:!M,onChange:(R,F)=>pe(F),"aria-label":"TTFT Timeout"})}),e.jsx(Ce,{size:"small",type:"number",value:T!=null?T:1e3,onChange:R=>{const F=parseInt(R.target.value,10);isNaN(F)||pe(F)},disabled:!M,slotProps:{htmlInput:{min:300,max:5e3,step:100,"aria-label":"TTFT Timeout value"}},sx:[Tt,{width:"4.5rem",flexShrink:0,"@container (max-width: 700px)":{width:"3.5rem"},"& .MuiInputBase-root":{height:"2rem"},"& .MuiInputBase-input":{textAlign:"right",py:"0.25rem",px:1,fontSize:_.md,MozAppearance:"textfield","&::-webkit-outer-spin-button, &::-webkit-inner-spin-button":{WebkitAppearance:"none",margin:0}}}]})]})}),s&&e.jsx(p,{component:"div",children:e.jsx(jo,{fieldName:s})}),r&&e.jsx(p,{component:"div",children:e.jsx(Co,{fieldName:r})})]})})})},sr=({messageTemplatesFieldName:t,textGenerationConfigFieldName:n,defaultsTextGenerationConfigFieldName:r,webSearchFieldName:s,compressionFieldName:a,fallbackFieldName:i,title:h="Advanced"})=>{const{setValue:m}=xt(),x=ze({name:t}),c=ze({name:n}),v=ze({name:r!=null?r:n}),[y,I]=l.useState(!1),[E,V]=l.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(Gn,{disableGutters:!0,elevation:0,expanded:E,onChange:(H,M)=>V(M),sx:H=>({"&.MuiAccordion-root.MuiPaper-root":{borderRadius:X.md},border:"1px solid",borderColor:"divider",overflow:"clip","&:before":{display:"none"}}),children:[e.jsx(Yn,{expandIcon:e.jsx(D,{icon:A.faChevronDown,size:"base",style:{flexShrink:0}}),sx:H=>({borderBottom:E?"1px solid":"none",borderColor:"divider",minHeight:"2.5rem","& .MuiAccordionSummary-content":{my:.75,minWidth:0,overflow:"hidden"},backgroundColor:H.palette.action.hover,"&:hover":{backgroundColor:H.palette.action.hover}}),children:e.jsx(p,{component:"div",sx:{display:"flex",alignItems:"center",width:"100%",minWidth:0,gap:.75},children:e.jsx(f,{variant:"body2",sx:{color:"text.secondary",flexShrink:0},children:h})})}),e.jsxs(qn,{sx:{padding:"1rem"},children:[e.jsx($e,{label:"Prompt template",children:x?e.jsx(bo,{onEdit:()=>I(!0),children:e.jsx(nr,{value:x,height:150,readOnly:!0})}):e.jsxs(Pr,{onClick:()=>I(!0),"aria-label":"Add prompt template",sx:H=>({width:"100%",border:"1px dashed",borderColor:H.palette.divider,borderRadius:X.md,py:1.5,display:"flex",alignItems:"center",justifyContent:"center",gap:.75,color:"text.secondary","&:hover":{borderColor:it,color:"text.primary",backgroundColor:"action.hover"}}),children:[e.jsx(D,{icon:A.faPlus,size:"xs"}),e.jsx(f,{variant:"body2",children:"Add prompt template"})]})}),e.jsx(ct,{sx:{my:1.5}}),e.jsx($e,{label:"Advanced model configurations",customRightSlot:r&&v&&(c?e.jsx(fe,{intent:"ghost",size:"small",startIcon:e.jsx(D,{icon:A.faRotateLeft,style:{fontSize:_.xs}}),onClick:()=>m(n,"",{shouldDirty:!0}),"aria-label":"Reset to default configuration",sx:{ml:"auto",textTransform:"none",fontSize:_.sm,py:0,minHeight:0},children:"Reset to default"}):e.jsx(f,{variant:"caption",sx:{color:"text.disabled",ml:"auto",fontStyle:"italic"},children:"Inherited from default"})),children:e.jsx(Mo,{fieldName:n,defaultsFieldName:r,webSearchFieldName:s,compressionFieldName:a,fallbackFieldName:i})})]})]}),e.jsx(yo,{open:y,initialValue:x!=null?x:"",onApply:H=>{m(t,H,{shouldDirty:!0}),I(!1)},onCancel:()=>I(!1)})]})},Eo=qt.lazy(()=>bn(()=>import("./MonacoEditorInworld.SJq08rdx.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(t=>({default:t.MonacoEditorInworld})));qt.lazy(()=>bn(()=>import("./MonacoEditorYaml.FwpjT1aw.js"),__vite__mapDeps([9,1,2,3,0,4,5,6,7,8])).then(t=>({default:t.MonacoEditorYaml})));qt.lazy(()=>bn(()=>import("./MonacoEditorJson.CAJuT6p2.js"),__vite__mapDeps([10,1,0,2,3,4,5,6,7,8])).then(t=>({default:t.MonacoEditorJson})));const Ao=e.jsx(Xn,{size:24}),Do=t=>e.jsx(l.Suspense,{fallback:Ao,children:e.jsx(Eo,{...t})}),$o=[{label:"Premium users",value:'tier == "premium"'},{label:"Premium users from US",value:'tier == "premium" && country == "us"'},{label:"Users with score between 80 and 100",value:"score >= 80 && score <= 100"},{label:"Users in enterprise segment",value:'user_segment.contains("enterprise")'}
2,{label:"Message starts with /hard",value:"messages.last().content.matches('^/hard(\\\\s|$)')"}],zo=({value:t,onChange:n,error:r,handleEditorWillMount:s})=>{const[a,i]=l.useState(null),h=!!a,m=l.useCallback(v=>{i(v.currentTarget)},[]),x=l.useCallback(()=>{i(null)},[]),c=l.useCallback(v=>{v&&(n(v),x())},[n,x]);return e.jsx(p,{component:"div",sx:{width:"100%"},children:e.jsxs(p,{component:"div",sx:{border:"1px solid",borderColor:"divider",borderRadius:1,overflow:"hidden",p:"1rem",containerType:"inline-size",containerName:"cel-editor",backgroundColor:v=>v.palette.background.paper},children:[e.jsxs(p,{component:"div",sx:v=>({display:"flex",alignItems:"center",justifyContent:"space-between",mb:"0.5rem","@container cel-editor (max-width: 560px)":{flexDirection:"column-reverse",alignItems:"flex-start",gap:"0.5rem"}}),children:[e.jsx(f,{variant:"body2",sx:{fontWeight:600,color:"text.secondary",whiteSpace:"nowrap"},children:"Common expression language"}),e.jsxs(C,{direction:"row",spacing:1,sx:{"@container cel-editor (max-width: 560px)":{width:"100%",justifyContent:"flex-start"}},children:[e.jsx(fe,{intent:"secondary","aria-label":"Open documentation",size:"small",component:"a",href:`${Hn}/docs/router/routing-strategies/conditional-routing`,target:"_blank",rel:"noopener noreferrer",children:"Documentation"}),e.jsx(fe,{intent:"secondary","aria-label":"Insert example",size:"small",endIcon:e.jsx(D,{icon:A.faChevronDown}),onClick:m,sx:{whiteSpace:"nowrap"},children:"Insert example"}),e.jsx(kn,{anchorEl:a,open:h,className:"inworld-text-field-menu",onClose:x,slotProps:{paper:{sx:{minWidth:a==null?void 0:a.offsetWidth}}},children:$o.map(v=>e.jsx(ve,{"aria-label":`Insert example ${v.label}`,onClick:()=>c(v.value),children:v.label},v.label))})]})]}),e.jsx(p,{component:"div",sx:{borderRadius:X.md,overflow:"hidden",border:v=>`1px solid ${v.palette.divider}`},children:e.jsx(Do,{height:120,language:"cel",value:t,onChange:n,editorWillMount:s,options:{minimap:{enabled:!1},folding:!1,wordWrap:"on",scrollBeyondLastLine:!1,renderLineHighlight:"none",overviewRulerLanes:0,hideCursorInOverviewRuler:!0,padding:{top:8},scrollbar:{vertical:"auto",horizontal:"hidden"}}})}),(r==null?void 0:r.message)&&e.jsx(p,{component:"div",sx:{mt:.5,color:"error.main",fontSize:_.sm},children:r.message})]})})},Lo={defaultToken:"",tokenPostfix:".cel",keywords:["true","false","null","in"],typeKeywords:["bool","bytes","double","duration","dyn","int","list","map","null_type","string","timestamp","type","uint"],operators:["!","!=","%","&&","*","+","-",".","/","<","<=","==",">",">=","?",":","||"],builtinFunctions:["size","type","has","all","exists","exists_one","map","filter","contains","startsWith","endsWith","matches","int","uint","double","string","bytes","bool","timestamp","duration","dyn","getDate","getDayOfMonth","getDayOfWeek","getDayOfYear","getFullYear","getHours","getMilliseconds","getMinutes","getMonth","getSeconds"],brackets:[{open:"{",close:"}",token:"delimiter.curly"},{open:"[",close:"]",token:"delimiter.bracket"},{open:"(",close:")",token:"delimiter.parenthesis"}],tokenizer:{root:[{include:"@whitespace"},[/\/\/.*$/,"comment"],[/[{}()[\]]/,"@brackets"],[/[<>](?!@symbols)/,"operator"],[/@symbols/,{cases:{"@operators":"operator","@default":""}}],[/\d*\.\d+([eE][-+]?\d+)?/,"number.float"],[/0[xX][0-9a-fA-F]+[uU]?/,"number.hex"],[/\d+[uU]?/,"number"],[/"([^"\\]|\\.)*$/,"string.invalid"],[/'([^'\\]|\\.)*$/,"string.invalid"],[/"/,"string","@string_double"],[/'/,"string","@string_single"],[/[rR]"/,"string","@string_raw_double"],[/[rR]'/,"string","@string_raw_single"],[/[bB]"/,"string","@string_double"],[/[bB]'/,"string","@string_single"],[/[a-zA-Z_]\w*/,{cases:{"@keywords":"keyword","@typeKeywords":"type.identifier","@builtinFunctions":"predefined","@default":"identifier"}}],[/[;,.]/,"delimiter"]],comment:[[/[^/*]+/,"comment"],[/\/\/.*$/,"comment"]],string_double:[[/[^\\"]+/,"string"],[/\\./,"string.escape"],[/"/,"string","@pop"]],string_single:[[/[^\\']+/,"string"],[/\\./,"string.escape"],[/'/,"string","@pop"]],string_raw_double:[[/[^"]+/,"string"],[/"/,"string","@pop"]],string_raw_single:[[/[^']+/,"string"],[/'/,"string","@pop"]],whitespace:[[/[ \t\r\n]+/,"white"]]},symbols:/[=><!~?:&|+\-*/^%]+/},_o=[{label:"true",kind:U.CompletionItemKind.Keyword,insertText:"true"},{label:"false",kind:U.CompletionItemKind.Keyword,insertText:"false"},{label:"null",kind:U.CompletionItemKind.Keyword,insertText:"null"},{label:"in",kind:U.CompletionItemKind.Keyword,insertText:"in"},{label:"size",kind:U.CompletionItemKind.Function,insertText:"size(${1:value})",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Returns the size of a string, bytes, list, or map"},{label:"has",kind:U.CompletionItemKind.Function,insertText:"has(${1:field})",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Tests whether a field is available"},{label:"type",kind:U.CompletionItemKind.Function,insertText:"type(${1:value})",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Returns the type of a value"},{label:"contains",kind:U.CompletionItemKind.Function,insertText:"contains(${1:substring})",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Tests whether a string contains a substring"},{label:"startsWith",kind:U.CompletionItemKind.Function,insertText:"startsWith(${1:prefix})",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Tests whether a string starts with a prefix"},{label:"endsWith",kind:U.CompletionItemKind.Function,insertText:"endsWith(${1:suffix})",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Tests whether a string ends with a suffix"},{label:"matches",kind:U.CompletionItemKind.Function,insertText:"matches(${1:regex}
2)",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Tests whether a string matches a regular expression"},{label:"all",kind:U.CompletionItemKind.Function,insertText:"all(${1:list}, ${2:x}, ${3:predicate})",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Tests whether a predicate holds for all elements of a list"},{label:"exists",kind:U.CompletionItemKind.Function,insertText:"exists(${1:list}, ${2:x}, ${3:predicate})",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Tests whether a predicate holds for any element of a list"},{label:"filter",kind:U.CompletionItemKind.Function,insertText:"filter(${1:list}, ${2:x}, ${3:predicate})",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Returns elements for which a predicate holds"},{label:"map",kind:U.CompletionItemKind.Function,insertText:"map(${1:list}, ${2:x}, ${3:transform})",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Applies a function to each element of a list"},{label:"int",kind:U.CompletionItemKind.Function,insertText:"int(${1:value})",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Converts a value to int"},{label:"uint",kind:U.CompletionItemKind.Function,insertText:"uint(${1:value})",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Converts a value to unsigned int"},{label:"double",kind:U.CompletionItemKind.Function,insertText:"double(${1:value})",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Converts a value to double"},{label:"string",kind:U.CompletionItemKind.Function,insertText:"string(${1:value})",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Converts a value to string"},{label:"timestamp",kind:U.CompletionItemKind.Function,insertText:"timestamp(${1:value})",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Converts a value to timestamp"},{label:"duration",kind:U.CompletionItemKind.Function,insertText:"duration(${1:value})",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Converts a value to duration"},{label:"ternary",kind:U.CompletionItemKind.Snippet,insertText:"${1:condition} ? ${2:true_value} : ${3:false_value}",insertTextRules:U.CompletionItemInsertTextRule.InsertAsSnippet,documentation:"Ternary conditional expression"}],Oo={provideCompletionItems:(t,n)=>{const r=t.getWordUntilPosition(n),s={startLineNumber:n.lineNumber,endLineNumber:n.lineNumber,startColumn:r.startColumn,endColumn:r.endColumn};return{suggestions:_o.map(i=>({...i,range:s}))}}},We="2.5rem",an=3,Wo=({weightedVariant:t,variantIndex:n})=>{var y,I;const{palette:r}=ht(),{variant:s,weight:a}=t,i=Rt(n,r.tints),h=ut(n),m=s.isAutoModel,x=m?null:s.modelId,c=((I=(y=s.modelSelection)==null?void 0:y.models)!=null?I:[]).map(E=>E.model),v=m?c:[];return e.jsxs(C,{direction:"row",spacing:1,sx:{alignItems:"center"},children:[e.jsx(p,{component:"span",sx:{backgroundColor:i.backgroundColor,color:i.color,fontWeight:700,fontSize:_.xs,width:"1.25rem",height:"1.25rem",borderRadius:X.sm,flexShrink:0,display:"inline-flex",alignItems:"center",justifyContent:"center",lineHeight:1},children:h}),e.jsx(p,{component:"div",sx:{flex:1,minWidth:0},children:m?e.jsxs(C,{direction:"row",spacing:.5,sx:{alignItems:"center"},children:[e.jsxs(p,{component:"div",sx:{display:"flex",alignItems:"center",gap:"0.25rem",color:"text.secondary"},children:[mt("auto",12),e.jsx(f,{variant:"caption",sx:{color:"text.secondary"},children:"Auto"})]}),v.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(f,{variant:"caption",sx:{color:"text.disabled"},children:"·"}),e.jsx(dt,{models:v,iconSize:10,bubbleSize:"1.25rem",max:4,deduplicateByProvider:!1})]})]}):e.jsxs(C,{direction:"row",spacing:.5,sx:{alignItems:"center"},children:[x&&e.jsxs(e.Fragment,{children:[e.jsx(dt,{models:[x],iconSize:10,bubbleSize:"1.25rem",max:1,deduplicateByProvider:!1}),e.jsx(f,{variant:"caption",sx:{color:"text.primary",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x})]}),!x&&e.jsx(f,{variant:"caption",sx:{color:"text.disabled"},children:"No model"})]})}),e.jsxs(f,{variant:"caption",sx:{color:"text.secondary",fontWeight:600,flexShrink:0,minWidth:"2.5rem",textAlign:"right"},children:[a,"%"]})]})},ir=({isSelected:t,routeName:n,isDefault:r,index:s,onClick:a,variantIds:i=[],variants:h=[],dragHandleProps:m})=>{const x=ht(),c=i.slice(0,an),v=i.length-an,y=l.useRef(null),[I,E]=l.useState(!1),V=()=>{h.length>0&&E(!0)},H=()=>E(!1),M=T=>{T.stopPropagation()};
2return e.jsxs(e.Fragment,{children:[e.jsxs(p,{ref:y,component:"div","aria-label":`Select route ${n}`,sx:T=>({borderRadius:X.md,padding:"0.5rem",paddingLeft:r?"0.5rem":"0.75rem",display:"flex",height:We,flexDirection:"row",alignItems:"center",gap:"0.5rem",backgroundColor:t?T.palette.primary.main:T.palette.background.paper,color:t?T.palette.primary.contrastText:"text.primary",width:"100%",position:"relative",boxShadow:N=>`0 0 0 0.5px ${N.palette.divider}`,"&:hover":{cursor:"pointer",backgroundColor:t?T.palette.primary.main:T.palette.background.default},"@container routes-section (max-width: 720px)":{width:"100%"}}),onClick:()=>a(s),onMouseEnter:V,onMouseLeave:H,children:[m&&e.jsx(p,{ref:m.setActivatorNodeRef,component:"span",...m.attributes,...m.listeners,onClick:T=>T.stopPropagation(),"aria-label":"Drag to reorder",sx:T=>({cursor:m.isDragging?"grabbing":"grab",color:t?Le(T.palette.primary.contrastText,.5):T.palette.text.disabled,display:"flex",alignItems:"center",flexShrink:0,ml:"-0.125rem",mr:"-0.125rem",touchAction:"none","&:hover":{color:t?Le(T.palette.primary.contrastText,.85):T.palette.text.secondary}}),children:e.jsx(D,{icon:A.faGripDotsVertical,size:"md"})}),r?e.jsx(p,{component:"div",sx:{flexShrink:0},children:e.jsx(se,{title:"Any requests that fail to meet the conditions above",children:e.jsx(st,{label:"Default",color:"secondary",size:"small",sx:T=>({"& .MuiChip-label":{fontWeight:600,fontSize:_.xs},color:t?T.palette.primary.contrastText:T.palette.text.primary,backgroundColor:t?Le(T.palette.primary.contrastText,.2):T.palette.background.surface.main})})})}):e.jsx(f,{sx:[{fontSize:_.sm,fontWeight:600},T=>({color:t?T.palette.primary.contrastText:"text.secondary"})],children:s+1}),e.jsx(f,{variant:"h6",sx:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",lineHeight:1},children:n}),i.length>0&&e.jsxs(p,{component:"div",sx:{display:"flex",ml:"auto",flexShrink:0},onMouseEnter:M,children:[c.map((T,N)=>{const ne=Rt(N,x.palette.tints);return e.jsx(p,{component:"span",sx:z=>({backgroundColor:t?z.palette.primary.dark:ne.backgroundColor,color:t?z.palette.primary.contrastText:ne.color,fontWeight:600,fontSize:_.xs,width:"1.125rem",height:"1.125rem",borderRadius:X.sm,flexShrink:0,display:"inline-flex",alignItems:"center",justifyContent:"center",border:"1px solid ",borderColor:t?z.palette.primary.light:z.palette.background.paper,ml:N>0?"-0.25rem":0,zIndex:N,lineHeight:1}),children:ut(N)},N)}),v>0&&e.jsxs(p,{component:"span",sx:T=>({fontWeight:600,fontSize:_.xs,width:"1.125rem",height:"1.125rem",borderRadius:X.sm,flexShrink:0,display:"inline-flex",alignItems:"center",justifyContent:"center",border:"1px solid",borderColor:t?T.palette.primary.light:T.palette.background.paper,backgroundColor:t?T.palette.primary.dark:T.palette.background.default,color:t?T.palette.primary.contrastText:T.palette.text.secondary,ml:"-0.25rem",zIndex:an,lineHeight:1}),children:["+",v]})]})]}),h.length>0&&e.jsx(Qn,{open:I,anchorEl:y.current,onClose:()=>E(!1),anchorOrigin:{vertical:"center",horizontal:"right"},transformOrigin:{vertical:"center",horizontal:"left"},disableRestoreFocus:!0,disableScrollLock:!0,sx:{pointerEvents:"none"},slotProps:{paper:{sx:{pointerEvents:"none",ml:.5,minWidth:"16rem",maxWidth:"22rem",p:1.5,borderRadius:X.md}}},children:e.jsxs(C,{spacing:.75,children:[e.jsx(f,{variant:"caption",sx:{color:"text.secondary",fontWeight:600,mb:.25},children:n}),e.jsx(ct,{}),h.map((T,N)=>e.jsx(Wo,{weightedVariant:T,variantIndex:N},N))]})})]})},Po=({error:t})=>{var a;const n=Jn(),{workspace:r}=Xt(),s=(a=t==null?void 0:t.message)!=null?a:"Router not found";return e.jsxs(C,{spacing:2,sx:{alignItems:"center",justifyContent:"center",height:"100%"},children:[e.jsx(f,{variant:"h5",children:s}),e.jsx(fe,{"aria-label":"Back to routers",onClick:()=>n(`/workspaces/${r}/routers`),children:"Back to routers"})]})},It="2.5rem",fn=(t,n)=>t===n||t.endsWith(`/${n}`),ln=(t,n)=>{var r;try{const s=JSON.parse((r=t.dataJson)!=null?r:"{}");return(Array.isArray(s.routers)?s.routers:[]).some(i=>fn(i,n))}catch(s){return!1}},Wn=(t,n)=>{if(n==="neutral")return null;const r=t.map((i,h)=>i!==void 0?{v:i,i:h}:null).filter(i=>i!==null);if(r.length<2)return null;const s=r.reduce((i,h)=>n==="lower"?h.v<i.v?h:i:h.v>i.v?h:i);return r.filter(i=>i.v===s.v).length>1?null:s.i},Ht=[{label:"1d",ms:1440*60*1e3},{label:"7d",ms:10080*60*1e3},{label:"30d",ms:720*60*60*1e3}],ar="7d",cn=Ht.find(t=>t.label===ar).ms,No=[{label:"Since",value:"since"},{label:"Between",value:"between"}],Nt=t=>Ue(t).format("MMM D, YYYY"),dn=t=>Ue(t).format("MM/DD/YYYY"),pt=t=>{const n=new Date(t);return n.setHours(0,0,0,0),n},Bo=({anchorEl:t,open:n,mode:r,sinceDate:s,betweenStart:a,betweenEnd:i,onModeChange:h,onSinceDateChange:m,onBetweenStartChange:x,onBetweenEndChange:c,onCancel:v,onApply:y})=>{const I=l.useMemo(()=>new Date,[]);return e.jsx(er,{open:n,anchorEl:t,placement:"bottom-start",style:{zIndex:1300}
2,children:e.jsx(tr,{elevation:8,sx:{display:"flex",flexDirection:"column",borderRadius:2,overflow:"hidden",mt:.5,maxWidth:"95vw"},children:e.jsxs(p,{component:"div",sx:{p:2,minWidth:{xs:0,sm:340},width:"100%"},children:[e.jsx(mn,{value:r,exclusive:!0,onChange:(E,V)=>V&&h(V),size:"small","aria-label":"Date mode",sx:{mb:1.5},children:No.map(({label:E,value:V})=>e.jsx(Ft,{value:V,disableRipple:!0,sx:{px:2},children:E},V))}),r==="since"&&e.jsxs(p,{component:"div",sx:{display:"flex",alignItems:"center",gap:1,mb:1},children:[e.jsx(Ce,{size:"small",value:dn(s),slotProps:{input:{readOnly:!0}},sx:{width:140}}),e.jsx(f,{variant:"body2",sx:{color:"text.secondary"},children:"to today"})]}),r==="between"&&e.jsxs(p,{component:"div",sx:{display:"flex",alignItems:"center",gap:1,mb:1},children:[e.jsx(Ce,{size:"small",value:dn(a),slotProps:{input:{readOnly:!0}},sx:{width:140}}),e.jsx(f,{variant:"body2",sx:{color:"text.secondary"},children:"to"}),e.jsx(Ce,{size:"small",value:dn(i),slotProps:{input:{readOnly:!0}},sx:{width:140}})]}),e.jsxs(Fr,{dateAdapter:Vr,children:[r==="since"&&e.jsx(nn,{value:Ue(s),maxDate:Ue(I),onChange:E=>E&&m(pt(E.toDate())),sx:{width:"100%","& .MuiPickersDay-root":{"&.Mui-selected, &.Mui-selected:hover, &.Mui-selected:focus":{color:"primary.contrastText"}}}}),r==="between"&&e.jsxs(p,{component:"div",sx:{display:"flex",flexDirection:{xs:"column",md:"row"},gap:1},children:[e.jsxs(p,{component:"div",children:[e.jsx(f,{variant:"caption",sx:{color:"text.secondary",mb:.5,display:"block"},children:"Start"}),e.jsx(nn,{value:Ue(a),maxDate:Ue(i),onChange:E=>E&&x(pt(E.toDate())),sx:{"& .MuiPickersDay-root":{"&.Mui-selected, &.Mui-selected:hover, &.Mui-selected:focus":{color:"primary.contrastText"}}}})]}),e.jsxs(p,{component:"div",children:[e.jsx(f,{variant:"caption",sx:{color:"text.secondary",mb:.5,display:"block"},children:"End"}),e.jsx(nn,{value:Ue(i),minDate:Ue(a),maxDate:Ue(I),onChange:E=>E&&c(pt(E.toDate())),sx:{"& .MuiPickersDay-root":{"&.Mui-selected, &.Mui-selected:hover, &.Mui-selected:focus":{color:"primary.contrastText"}}}})]})]})]}),e.jsxs(e.Fragment,{children:[e.jsx(ct,{sx:{my:1}}),e.jsxs(p,{component:"div",sx:{display:"flex",justifyContent:"flex-end",gap:1},children:[e.jsx(fe,{intent:"ghost",size:"small","aria-label":"Cancel",onClick:v,children:"Cancel"}),e.jsx(fe,{size:"small","aria-label":"Apply",onClick:y,children:"Apply"})]})]})]})})})},Fo=({routes:t,selectedRouteIds:n,onToggleRoute:r})=>{const[s,a]=l.useState(!1),i=l.useRef(null),h=l.useCallback(()=>a(c=>!c),[]),m=l.useCallback(()=>a(!1),[]),x=l.useMemo(()=>{const c=n.size;if(c===0)return"No routes selected";if(c===1){const v=Array.from(n)[0],y=t.find(I=>I.routeId===v);return y!=null&&y.isDefault?`${v} (default)`:v}return`${c} routes selected`},[t,n]);return e.jsxs(e.Fragment,{children:[e.jsx(fe,{intent:"ghost",ref:i,size:"small","aria-label":"Select routes",onClick:h,endIcon:e.jsx(D,{icon:A.faChevronDown}),startIcon:e.jsx(D,{icon:A.faSplit}),sx:{textTransform:"none",color:"text.primary",fontWeight:500,fontSize:_.md,border:"1px solid",borderColor:"divider",borderRadius:1,px:1.5,height:It,whiteSpace:"nowrap",backgroundColor:"background.paper","& .MuiButton-endIcon":{ml:"auto"}},children:x}),s&&e.jsx(Zn,{onClickAway:m,children:e.jsx(er,{open:s,anchorEl:i.current,placement:"bottom-start",style:{zIndex:1300},children:e.jsx(tr,{elevation:8,sx:{borderRadius:2,overflow:"hidden",mt:.5,minWidth:240},children:e.jsxs(Nr,{disablePadding:!0,sx:{py:.5},children:[t.map(c=>e.jsxs(Br,{dense:!0,"aria-label":`Toggle route ${c.routeId}`,onClick:()=>r(c.routeId),sx:{py:.25},children:[e.jsx(rt,{sx:{minWidth:36},children:e.jsx(at,{edge:"start",checked:n.has(c.routeId),disableRipple:!0,size:"small"})}),e.jsx(He,{primary:c.isDefault?`${c.routeId} (default)`:c.routeId,slotProps:{primary:{variant:"body2",noWrap:!0}}})]},c.routeId)),t.length===0&&e.jsx(f,{variant:"body2",sx:{color:"text.secondary",px:2,py:1},children:"No routes available"})]})})})})]})},Vo="router-metrics-connect-banner-dismissed",Uo=({onDismiss:t})=>{const{workspace:n}=Xt();return e.jsxs(Kn,{severity:"success",sx:{mb:"0.5rem"},action:e.jsx(Te,{"aria-label":"Dismiss banner",onClick:t,size:"small",color:"inherit",children:e.jsx(D,{icon:A.faClose,size:"sm"})}),children:["Connect to your data sources to see how your router impacts your KPIs."," ",e.jsx(fr,{to:`/workspaces
2/${n!=null?n:""}/router-metrics`,component:br,"aria-label":"Connect your data",underline:"always",color:"inherit",sx:{fontWeight:600,fontSize:"inherit",verticalAlign:"baseline",cursor:"pointer"},children:"Connect your data"})]})},lr=1e4,Ho=new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}),cr=new Intl.NumberFormat("en-US",{maximumFractionDigits:0}),Jo=t=>Math.abs(t)<lr?cr.format(Math.round(t)):Ho.format(t),Ko=(t,n)=>{switch(n){case ot.COST:return vr(t);case ot.COMPACT_NUMBER:return Jo(t);case ot.WHOLE_NUMBER:return Math.round(t);case ot.FOUR_DECIMAL_PLACES:return Math.round(t*1e4)/1e4;default:return t}},Go=(t,n)=>n===ot.COMPACT_NUMBER&&Math.abs(t)>=lr?cr.format(Math.round(t)):void 0,Bt=({data:t,isLoading:n,isError:r,isWinner:s,formatType:a})=>{const i=ht(),h=gn(t),m=i.palette.success.dark;return e.jsx(f,{variant:"body2",sx:{fontWeight:s?600:400,color:s?m:void 0,display:"flex",alignItems:"center",gap:.5},children:n?e.jsx(Ur,{variant:"text",width:40}):r?"â":h!==void 0?e.jsxs(e.Fragment,{children:[(()=>{const x=Go(h,a),c=Ko(h,a);return x?e.jsx(se,{title:x,placement:"top",children:e.jsx("span",{children:c})}):c})(),s&&e.jsx(st,{label:"Leading",size:"small",sx:x=>({"&.MuiChip-colorDefault":{backgroundColor:"transparent"},color:x.palette.primary.main,border:`1px solid ${x.palette.primary.main}`,ml:"auto",height:"1.125rem",fontSize:_.xs,fontWeight:600,letterSpacing:"0.04em","& .MuiChip-label":{px:"0.375rem"}})})]}):"â"})},Yo=({routerId:t,routes:n=[]})=>{var ft,bt,vt;const{workspace:r}=Xt(),s=ht(),[a,i]=l.useState(null),[h,m]=l.useState(!1),x=l.useMemo(()=>Qr(),[]),{data:c,isLoading:v}=Zr({workspace:r!=null?r:"",pageSize:100,pageToken:""}),y=((bt=(ft=c==null?void 0:c.aiIntegrations)==null?void 0:ft.length)!=null?bt:0)>0&&((vt=c==null?void 0:c.aiIntegrations)==null?void 0:vt.some(d=>{var S,w;if(!d.dataJson)return!1;try{const o=JSON.parse(d.dataJson);return o.enabled_import||o.enabled_export||((S=o.importConfig)==null?void 0:S.enabled)||((w=o.exportConfig)==null?void 0:w.enabled)}catch(o){return console.error("Failed to parse integration dataJson:",o),!1}})),{value:I,setValue:E,isLoading:V}=gr(Vo),M=!V&&!v&&!y&&!(I==="true"),T=l.useCallback(()=>{E("true")},[E]),[N,ne]=l.useState(ar),[z,ee]=l.useState("since"),[pe,g]=l.useState(()=>pt(new Date(Date.now()-cn))),[ce,de]=l.useState(()=>pt(new Date(Date.now()-cn))),[Q,R]=l.useState(()=>pt(new Date)),[F,te]=l.useState("since"),[ae,J]=l.useState(pe),[Z,ie]=l.useState(ce),[ye,Me]=l.useState(Q),[_e,we]=l.useState(!1),me=l.useRef(null),{start:Pe,end:Ye}=l.useMemo(()=>{var S;const d=Date.now();if(N){const w=Ht.find(o=>o.label===N);return{start:d-((S=w==null?void 0:w.ms)!=null?S:cn),end:d}}return z==="since"?{start:pe.getTime(),end:d}:{start:ce.getTime(),end:Q.getTime()}},[N,z,pe,ce,Q]),qe=l.useCallback((d,S)=>{S&&(ne(S),we(!1))},[]),Ie=l.useCallback(()=>{te(z),J(pe),ie(ce),Me(Q),we(!0)},[z,pe,ce,Q]),be=l.useCallback(()=>we(!1),[]),B=l.useCallback(()=>{ee(F),g(ae),de(Z),R(ye),ne(null),we(!1)},[F,ae,Z,ye]),je=l.useMemo(()=>{var d;if(N){const S=Ht.find(w=>w.label===N);return`Since ${Nt(Date.now()-((d=S==null?void 0:S.ms)!=null?d:0))}`}return z==="since"?`Since ${Nt(pe.getTime())}`:`${Nt(ce.getTime())} â ${Nt(Q.getTime())}`},[N,z,pe,ce,Q]),[Ne,Je]=l.useState(new Set),Ke=l.useRef(!1);l.useEffect(()=>{!Ke.current&&n.length>0&&(Ke.current=!0,Je(new Set(n.map(d=>d.routeId))))},[n]);const Xe=l.useCallback(d=>{Je(S=>{const w=new Set(S);return w.has(d)?w.delete(d):w.add(d),w})},[]),b=l.useMemo(()=>n.filter(d=>Ne.has(d.routeId)),[n,Ne]),[K,G]=l.useState(jt.ROUTE),W=l.useCallback((d,S)=>{S&&G(S)},[]),Y=l.useMemo(()=>K===jt.ROUTE?b.map(d=>({key:d.routeId,primaryLabel:d.routeId,additionalFilters:[{key:"route_id",value:d.routeId}]})):K===jt.ROUTE_AND_VARIANT?b.flatMap(d=>d.variantIds.map((S,w)=>({key:`${d.routeId}/${S}`,primaryLabel:S,secondaryLabel:`route: ${d.routeId}`,variantIndex:w,additionalFilters:[{key:"route_id",value:d.routeId},{key:"variant_id",value:S}]}))):[],[K,b]),xe=eo({start:Pe,end:Ye,routerId:t,columns:Y,metricsGroupBy:K,enabled:Y.length>0}),{data:P}=to({workspace:r!=null?r:"",enabled:!!r}),re=l.useMemo(()=>`routers/${t}`,[t]),Se=l.useMemo(()=>{var S;const d=new Set;
2return(S=c==null?void 0:c.aiIntegrations)==null||S.forEach(w=>{var o,u,j;try{if((u=JSON.parse((o=w.dataJson)!=null?o:"{}").importConfig)!=null&&u.enabled){const $=(j=w.name)==null?void 0:j.split("/integrations/")[1];$&&d.add($)}}catch(k){}}),d},[c]),he=l.useMemo(()=>{var S;return((S=P==null?void 0:P.metrics)!=null?S:[]).filter(w=>{var o,u;if(!ln(w,re))return!1;try{const k=(u=JSON.parse((o=w.dataJson)!=null?o:"{}").event)==null?void 0:u.source;return k?Se.has(k):!1}catch(j){return!1}})},[P==null?void 0:P.metrics,re,Se]),oe=no({workspace:r!=null?r:"",onSuccess:()=>{i(null)},onError:d=>{nt(`Failed to update metric: ${d.message}`)}}),Re=l.useMemo(()=>{var S;return((S=P==null?void 0:P.metrics)!=null?S:[]).filter(w=>{var o,u;if(ln(w,re))return!1;try{const k=(u=JSON.parse((o=w.dataJson)!=null?o:"{}").event)==null?void 0:u.source;return k?Se.has(k):!1}catch(j){return!1}})},[P==null?void 0:P.metrics,re,Se]),Oe=l.useCallback(d=>{var S,w,o,u,j,k;try{return(u=(o=JSON.parse((S=d.dataJson)!=null?S:"{}").displayName)!=null?o:(w=d.name)==null?void 0:w.split("/").pop())!=null?u:"Unknown"}catch($){return(k=(j=d.name)==null?void 0:j.split("/").pop())!=null?k:"Unknown"}},[]),Qe=l.useCallback(d=>{var S,w;try{return(w=JSON.parse((S=d.dataJson)!=null?S:"{}").event)==null?void 0:w.source}catch(o){return}},[]),Qt=l.useCallback(d=>{var S,w;try{return(w=JSON.parse((S=d.dataJson)!=null?S:"{}").description)!=null?w:""}catch(o){return""}},[]),gt=l.useMemo(()=>new Map(oo.map(d=>[d.id,d.logo])),[]),Mt=l.useCallback(d=>{if(!d)return null;const S=gt.get(d);return S?e.jsx(p,{component:"span",sx:{display:"inline-flex",alignItems:"center",flexShrink:0,width:20,height:20,"& svg":{width:"100%",height:"100%"}},children:e.jsx(S,{})}):null},[gt]),Et=l.useCallback(d=>{var S;try{if(ln(d,re))return;const w=JSON.parse((S=d.dataJson)!=null?S:"{}"),u=[...(Array.isArray(w.routers)?w.routers:[]).filter(k=>!fn(k,re)),re],j={...w,routers:u};oe.mutate({metric:{name:d.name,dataJson:JSON.stringify(j)}},{onSuccess:()=>{St("External metric added to router")}})}catch(w){nt("Failed to parse metric data")}},[re,oe]),At=l.useCallback(d=>{var S;try{const w=JSON.parse((S=d.dataJson)!=null?S:"{}"),o=Array.isArray(w.routers)?w.routers:[],u=o.filter(k=>!fn(k,re));if(u.length===o.length)return;const j={...w,routers:u};oe.mutate({metric:{name:d.name,dataJson:JSON.stringify(j)}},{onSuccess:()=>{St("External metric removed from router")}})}catch(w){nt("Failed to parse metric data")}},[re,oe]),Zt=l.useCallback(()=>{i(null),m(!0)},[]),en=l.useCallback(d=>{var S,w,o,u,j,k;try{return(u=(o=JSON.parse((S=d.dataJson)!=null?S:"{}").displayName)!=null?o:(w=d.name)==null?void 0:w.split("/").pop())!=null?u:"Unknown"}catch($){return(k=(j=d.name)==null?void 0:j.split("/").pop())!=null?k:"Unknown"}},[]),Dt=l.useCallback(d=>{var S,w;try{return(w=JSON.parse((S=d.dataJson)!=null?S:"{}").description)!=null?w:""}catch(o){return""}},[]),tn=ro({metrics:he,start:Pe,end:Ye,routerId:t,columns:Y,enabled:!!r&&he.length>0&&(Y.length>0||!!t)}),$t=l.useCallback(d=>{var S;try{const w=JSON.parse((S=d.dataJson)!=null?S:"{}");if(Object.values(ot).includes(w.formatType))return w.formatType}catch(w){}return ot.FOUR_DECIMAL_PLACES},[]),zt=l.useCallback(d=>{var S;try{const o=JSON.parse((S=d.dataJson)!=null?S:"{}").targetDirection;if(o==="increase")return"higher";if(o==="decrease")return"lower"}catch(w){}return"neutral"},[]);return e.jsxs(p,{component:"div",children:[M&&e.jsx(Uo,{onDismiss:T}),e.jsxs(p,{component:"div",sx:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:1,mb:"0.5rem",containerType:"inline-size",containerName:"metrics-toolbar"},children:[e.jsxs(mn,{value:K,exclusive:!0,onChange:W,size:"small","aria-label":"Group by",variant:"primary",sx:{height:It,gap:"0.25rem",backgroundColor:"transparent"},children:[e.jsx(Ft,{value:jt.ROUTE,disableRipple:!0,sx:{px:2,height:"100%"},children:"By route"}),n.some(d=>d.variantIds.length>0)&&e.jsx(Ft,{value:jt.ROUTE_AND_VARIANT,disableRipple:!0,sx:{px:2,height:"100%"},children:"By variant"})]}),e.jsxs(C,{direction:"row",spacing:.75,sx:{alignItems:"center",ml:"auto",flexWrap:"wrap",gap:.75,"@container metrics-toolbar (max-width: 720px)":{width:"100%","& > *":{flex:"1 1 100%"}}},children:[n.length>0&&e.jsx(Fo,{routes:n,selectedRouteIds:Ne,onToggleRoute:Xe}),e.jsx(fe,{intent:"ghost",ref:me,size:"small","aria-label":"Select date range",onClick:Ie,startIcon:e.jsx(D,{icon:A.faCalendar}),endIcon:e.jsx(D,{icon:A.faChevronDown}),sx:{textTransform:"none",color:"text.primary",fontWeight:500,fontSize:_.md,border:"1px solid",borderColor:"divider",backgroundColor:"background.paper",borderRadius:1,px:1.5,height:It,whiteSpace:"nowrap","& .MuiButton-endIcon":{ml:"auto"}},children:je}),e.jsx(mn,{variant:"primary",sx:{height:It,"@container metrics-toolbar (max-width: 720px)":{flex:"1 1 100%","& .MuiToggleButtonGroup-grouped":{flex:1}}},value:N,exclusive:!0,onChange:qe,size:"small",bgColor:"transparent","aria-label":"Time range",children:Ht.map(({label:d})=>e.jsx(Ft,{value:d,disableRipple:!0,sx:{px:2,height:"100%"},children:d},d))}),e.jsx(fe,{intent:"ghost",size:"small","aria-label":"Add metric","aria-haspopup":"menu","aria-expanded":!!a,startIcon:e.jsx(D,{icon:A.faPlus}),endIcon:e.jsx(D,{icon:A.faChevronDown}),onClick:d=>i(a?null:d.currentTarget),sx:{textTransform:"none",color:"text.primary",fontWeight:500,fontSize:_.md,border:"1px solid",borderColor:"divider",backgroundColor:"background.paper",borderRadius:1,px:1.5,height:It,whiteSpace:"nowrap"},children:"Add metric"}),e.jsxs(kn,{anchorEl:a,open:!!a,onClose:()=>i(null),anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},slotProps:{paper:{sx:{maxHeight:320,minWidth:240}}},children:[Re.map(d=>e.jsxs(ve,{"aria-label":`Add ${Oe(d)} to router`,onClick:()=>Et(d),disabled:oe.isLoading,children:[e.jsx(rt,{sx:{minWidth:36}
2,children:Mt(Qe(d))}),e.jsx(He,{primary:Oe(d),secondary:Qt(d)||void 0,slotProps:{primary:{variant:"body2",sx:{fontWeight:500}},secondary:{variant:"caption"}}})]},d.name)),Re.length===0&&e.jsx(ve,{disabled:!0,children:e.jsx(He,{primary:"No metrics available",secondary:"Create a custom metric to add",slotProps:{primary:{variant:"body2"},secondary:{variant:"caption"}}})}),e.jsx(ct,{sx:{marginTop:0,marginBottom:0}}),e.jsxs(ve,{"aria-label":"Create new metric",onClick:Zt,children:[e.jsx(rt,{children:e.jsx(D,{icon:A.faPlus,style:{fontSize:_.sm}})}),e.jsx(He,{primary:"Create new metric",slotProps:{primary:{variant:"body2",sx:{fontWeight:500}}}})]})]})]})]}),_e&&e.jsx(Zn,{onClickAway:be,children:e.jsx(p,{component:"div",children:e.jsx(Bo,{anchorEl:me.current,open:_e,mode:F,sinceDate:ae,betweenStart:Z,betweenEnd:ye,onModeChange:te,onSinceDateChange:J,onBetweenStartChange:ie,onBetweenEndChange:Me,onCancel:be,onApply:B})})}),e.jsxs(Xr,{variant:"data",sx:{minWidth:400},children:[e.jsx(io,{children:e.jsxs(Ct,{children:[e.jsx(De,{sx:{position:"sticky",left:0,backgroundColor:"background.surface.main",zIndex:1,minWidth:180},children:"Metric"}),Y.length>0?Y.map(d=>{const S=d.variantIndex!==void 0,w=S?Rt(d.variantIndex,s.palette.tints):null;return e.jsxs(De,{children:[e.jsxs(C,{direction:"row",spacing:.75,sx:{alignItems:"center"},children:[S&&w&&e.jsx(p,{component:"span",sx:{backgroundColor:w.backgroundColor,color:w.color,fontWeight:700,fontSize:_.xs,width:"1.25rem",height:"1.25rem",borderRadius:X.sm,flexShrink:0,display:"inline-flex",alignItems:"center",justifyContent:"center",lineHeight:1},children:ut(d.variantIndex)}),e.jsx("span",{children:d.primaryLabel})]}),d.secondaryLabel&&e.jsx(f,{variant:"caption",component:"div",sx:{color:"text.disabled"},children:d.secondaryLabel})]},d.key)}):e.jsx(De,{children:t})]})}),e.jsxs(ao,{children:[x.map((d,S)=>{var k,$,L,O;const w=(k=xe[S])!=null?k:[],o=S>0?x[S-1].section:void 0,u=d.section!==o,j=Math.max(Y.length,1)+1;return e.jsxs(qt.Fragment,{children:[u&&e.jsx(Ct,{children:e.jsx(De,{colSpan:j,sx:{position:"sticky",left:0,backgroundColor:"background.paper",zIndex:1,py:.75,borderBottom:"none",...S>0&&{borderTop:"1px solid",borderColor:"divider"}},children:e.jsx(f,{variant:"caption",sx:{fontWeight:700,textTransform:"uppercase",letterSpacing:"0.05em",color:"text.secondary"},children:d.section})})}),e.jsxs(Ct,{children:[e.jsx(De,{sx:{position:"sticky",left:0,backgroundColor:"background.paper",zIndex:1},children:e.jsxs(C,{direction:"row",spacing:.75,sx:{alignItems:"center"},children:[e.jsx(f,{variant:"body2",sx:{display:"flex",alignItems:"center",gap:1},children:d.widget.title}),e.jsx(se,{title:d.widget.description,placement:"right",children:e.jsx(Te,{"aria-label":`Info: ${d.widget.description}`,size:"small",sx:{color:"text.secondary",width:"1.5rem",height:"1.5rem",borderRadius:X.sm,p:0},children:e.jsx(D,{icon:A.faInfoCircle,style:{height:"0.75rem",width:"0.75rem"}})})})]})}),Y.length>0?(()=>{const q=w.every(le=>le==null?void 0:le.isSuccess),ue=w.map(le=>gn(le==null?void 0:le.data)),ge=q&&d.winCondition?Wn(ue,d.winCondition):null;return Y.map((le,Lt)=>{var Tn;const{data:Ee,isLoading:_t,isError:Ae}=(Tn=w[Lt])!=null?Tn:{},yt=ge===Lt;return e.jsx(De,{sx:{backgroundColor:yt?s.palette.success.light:void 0},children:e.jsx(Bt,{data:Ee,isLoading:!!_t,isError:!!Ae,isWinner:yt,formatType:d.formatType})},le.key)})})():e.jsx(De,{children:e.jsx(Bt,{data:($=w[0])==null?void 0:$.data,isLoading:!!((L=w[0])!=null&&L.isLoading),isError:!!((O=w[0])!=null&&O.isError),formatType:d.formatType})})]})]},d.widget.id)}),he.length>0&&e.jsx(Ct,{children:e.jsx(De,{colSpan:Math.max(Y.length,1)+1,sx:{position:"sticky",left:0,backgroundColor:"background.paper",zIndex:1,py:.75,borderTop:"1px solid",borderColor:"divider",borderBottom:"none"},children:e.jsx(f,{variant:"caption",sx:{fontWeight:700,textTransform:"uppercase",letterSpacing:"0.05em",color:"text.secondary"},children:"Custom Metrics"})})}),he.map((d,S)=>{var L,O,q,ue;const w=en(d),o=Dt(d),u=Qe(d),j=(L=tn[S])!=null?L:[],k=$t(d),$=zt(d);return e.jsxs(Ct,{children:[e.jsx(De,{sx:{position:"sticky",left:0,backgroundColor:"background.paper",zIndex:1},children:e.jsxs(C,{direction:"row",spacing:.75,sx:{alignItems:"center"}
2,children:[Mt(u),e.jsx(f,{variant:"body2",sx:{display:"flex",alignItems:"center",gap:1},children:w}),o&&e.jsx(se,{title:o,placement:"right",children:e.jsx(Te,{"aria-label":`Info: ${o}`,size:"small",sx:{color:"text.secondary",width:"1.5rem",height:"1.5rem",borderRadius:X.sm,p:0},children:e.jsx(D,{icon:A.faInfoCircle,style:{height:"0.75rem",width:"0.75rem"}})})}),e.jsx(se,{title:"Remove metric from router",placement:"right",children:e.jsx(Te,{"aria-label":`Remove ${w} from router`,size:"small",onClick:()=>At(d),disabled:oe.isLoading,sx:{color:"text.secondary",width:"1.5rem",height:"1.5rem",borderRadius:X.sm,p:0,"&:hover":{color:"error.main"}},children:e.jsx(D,{icon:A.faTrash,style:{height:"0.75rem",width:"0.75rem"}})})})]})}),Y.length>0?(()=>{const ge=j.every(Ee=>Ee==null?void 0:Ee.isSuccess),le=j.map(Ee=>gn(Ee==null?void 0:Ee.data)),Lt=ge&&$!=="neutral"?Wn(le,$):null;return Y.map((Ee,_t)=>{const Ae=j[_t],yt=Lt===_t;return e.jsx(De,{sx:{backgroundColor:yt?s.palette.success.light:void 0},children:e.jsx(Bt,{data:Ae==null?void 0:Ae.data,isLoading:!!(Ae!=null&&Ae.isLoading),isError:!!(Ae!=null&&Ae.isError),isWinner:yt,formatType:k})},Ee.key)})})():e.jsx(De,{children:e.jsx(Bt,{data:(O=j[0])==null?void 0:O.data,isLoading:!!((q=j[0])!=null&&q.isLoading),isError:!!((ue=j[0])!=null&&ue.isError),formatType:k})})]},d.name)})]})]}),r&&e.jsx(so,{open:h,onClose:()=>m(!1),workspace:r,integrationsResponse:c,routerToAssociate:re})]})},dr=(t,n=[])=>{if(!t||typeof t!="object")return[];if("message"in t&&typeof t.message=="string")return[{label:n.join(" â "),message:t.message}];const r=[];for(const[s,a]of Object.entries(t))s==="type"||s==="ref"||s==="types"||r.push(...dr(a,[...n,s]));return r},qo=(t,n,r)=>{var h,m;const s={displayName:"Name",name:"ID",routeId:"Route ID",celExpression:"Condition",variantId:"Variant ID",weight:"Weight",modelId:"Model",textGenerationConfig:"Config",messageTemplates:"Message Template",defaults:"Defaults"},a=t.split(" â "),i=[];for(let x=0;x<a.length;x++){const c=a[x],v=Number(c);if(isNaN(v))c==="defaultRoute"?i.push(r||"Default Route"):c==="route"||c==="variant"||c==="condition"||i.push((m=s[c])!=null?m:c);else{const y=a[x-1];y==="routes"?i.push(((h=n[v])==null?void 0:h.route.routeId)||`Route ${v+1}`):y==="variants"?i.push(`Variant ${"ABCDEFGHIJKLMNOPQRSTUVWXYZ"[v%26]}`):i.push(`#${v+1}`)}}return i.join(" â ")},Xo=({errors:t,watchedRoutes:n,defaultRouteId:r,hasSubmitAttempted:s,rootRef:a})=>{if(!s)return null;const i=dr(t);if(i.length===0)return null;const h=i.map(({label:m,message:x})=>({label:qo(m,n,r),message:x}));return e.jsxs(p,{component:"div",className:"ValidationErrorPanel",ref:a,sx:{mb:"1.5rem",scrollMarginTop:"1rem",p:"0.75rem 1rem",borderRadius:X.md,border:m=>`1px solid ${m.palette.error.main}`,backgroundColor:m=>Le(m.palette.error.main,.08)},children:[e.jsx(f,{variant:"body2",color:"error",sx:{fontWeight:600,mb:.5},children:"Please fix the following before saving:"}),h.map(({label:m,message:x},c)=>e.jsxs(f,{variant:"body2",color:"error",sx:{display:"flex",gap:"0.25rem"},children:[e.jsx("span",{children:"â¢"}),e.jsxs("span",{children:[e.jsxs("strong",{children:[m,":"]})," ",x]})]},c))]})},Gt="auto",Qo=({model:t})=>{var h,m,x,c,v;const n=t.model.split("/").pop()||t.model,r=y=>{const I=y*1e6;return I<.01?`$${I.toFixed(4)}`:`$${I.toFixed(2)}`},s=(h=t.spec)!=null&&h.capabilities?Object.entries(t.spec.capabilities).filter(([,y])=>y).map(([y])=>y):[],a=(x=(m=t.spec)==null?void 0:m.inputModalities)!=null?x:[],i=(v=(c=t.spec)==null?void 0:c.outputModalities)!=null?v:[];return e.jsx(or,{width:"20rem",children:e.jsxs(C,{spacing:2,children:[e.jsxs(p,{component:"div",children:[e.jsxs(C,{direction:"row",spacing:1,sx:{alignItems:"center",mb:.5},children:[mt(`${t.provider}/${t.model}`,20),e.jsx(f,{variant:"h5",component:"h6",children:n})]}),e.jsxs(C,{direction:"row",spacing:.5,sx:{alignItems:"center"},children:[e.jsx(f,{variant:"caption",component:"p",sx:{color:"text.secondary"},children:t.model}),e.jsx(Kt,{copy:t.model,tooltip:"Copy model ID",iconButtonProps:{size:"small",sx:{p:.25}}})]}),t.modelCreator&&e.jsxs(f,{variant:"caption",component:"p",sx:{color:"text.secondary",mt:.5},children:["by ",t.modelCreator]})]}),t.pricing&&e.jsx(p,{component:"div",children:e.jsxs(C,{spacing:.5,children:[e.jsxs(C,{direction:"row",sx:{justifyContent:"space-between",alignItems:"center"},children:[e.jsx(f,{variant:"body2",sx:{color:"text.secondary"},children:"Input ($/1M tokens)"}),e.jsx(f,{variant:"body2",sx:{fontWeight:500},children:r(t.pricing.promptToken)})]}),e.jsxs(C,{direction:"row",sx:{justifyContent:"space-between",alignItems:"center"},children:[e.jsx(f,{variant:"body2",sx:{color:"text.secondary"},children:"Output ($/1M tokens)"}),e.jsx(f,{variant:"body2",sx:{fontWeight:500},children:r(t.pricing.completionToken)})]}),t.pricing.promptCacheReadToken!=null&&e.jsxs(C,{direction:"row",sx:{justifyContent:"space-between",alignItems:"center"},children:[e.jsx(f,{variant:"body2",sx:{color:"text.secondary"},children:"Cache read ($/1M tokens)"}),e.jsx(f,{variant:"body2",sx:{fontWeight:500},children:r(t.pricing.promptCacheReadToken)})]}),t.pricing.promptCacheWriteToken!=null&&e.jsxs(C,{direction:"row",sx:{justifyContent:"space-between",alignItems:"center"},children:[e.jsx(f,{variant:"body2",sx:{color:"text.secondary"},children:"Cache write ($/1M tokens)"}),e.jsx(f,{variant:"body2",sx:{fontWeight:500},children:r(t.pricing.promptCacheWriteToken)})]})]})}),t.spec&&(t.spec.contextLength!==void 0||t.spec.maxCompletionTokens!==void 0)&&e.jsx(p,{component:"div",children:e.jsxs(C,{spacing:.5,children:[t.spec.contextLength!==void 0&&e.jsxs(C,{direction:"row",sx:{justifyContent:"space-between",alignItems:"center"},children:[e.jsx(f,{variant:"body2",sx:{color:"text.secondary"},children:"Context length"}),e.jsx(f,{variant:"body2",sx:{fontWeight:500},children:Pn(t.spec.contextLength)})]}),t.spec.maxCompletionTokens!==void 0&&e.jsxs(C,{direction:"row",sx:{justifyContent:"space-between",alignItems:"center"},children:[e.jsx(f,{variant:"body2",sx:{color:"text.secondary"},children:"Max output tokens"}),e.jsx(f,{variant:"body2",sx:{fontWeight:500},children:Pn(t.spec.maxCompletionTokens)})]})]})}),s.length>0&&e.jsxs(p,{component:"div",children:[e.jsx(f,{variant:"body2",sx:{color:"text.secondary",mb:.5},children:"Capabilities"}),e.jsx(C,{direction:"row",sx:{flexWrap:"wrap",gap:.5},children:s.map(y=>{const I=go(y);return e.jsx(st,{label:e.jsxs(C,{direction:"row",spacing:.5,sx:{alignItems:"center"},children:[I&&e.jsx(D,{icon:I,style:{height:"0.625rem",width:"0.625rem"}}),e.jsx("span",{children:ho(y)})]}
2),size:"small",sx:{fontSize:_.sm,height:"22px","& .MuiChip-label":{px:.75}}},y)})})]}),a.length>0&&e.jsxs(p,{component:"div",children:[e.jsx(f,{variant:"body2",sx:{color:"text.secondary",mb:.5},children:"Input modalities"}),e.jsx(C,{direction:"row",sx:{flexWrap:"wrap",gap:.5},children:a.map(y=>{const I=zn(y);return e.jsx(st,{label:e.jsxs(C,{direction:"row",spacing:.5,sx:{alignItems:"center"},children:[I&&e.jsx(D,{icon:I,style:{height:"0.625rem",width:"0.625rem"}}),e.jsx("span",{children:$n(y)})]}),size:"small",sx:{fontSize:_.sm,height:"22px","& .MuiChip-label":{px:.75}}},y)})})]}),i.length>0&&e.jsxs(p,{component:"div",children:[e.jsx(f,{variant:"body2",sx:{color:"text.secondary",mb:.5},children:"Output modalities"}),e.jsx(C,{direction:"row",sx:{flexWrap:"wrap",gap:.5},children:i.map(y=>{const I=zn(y);return e.jsx(st,{label:e.jsxs(C,{direction:"row",spacing:.5,sx:{alignItems:"center"},children:[I&&e.jsx(D,{icon:I,style:{height:"0.625rem",width:"0.625rem"}}),e.jsx("span",{children:$n(y)})]}),size:"small",sx:{fontSize:_.sm,height:"22px","& .MuiChip-label":{px:.75}}},y)})})]})]})})},Zo=()=>e.jsx(or,{width:"20rem",children:e.jsxs(C,{spacing:2,children:[e.jsxs(p,{component:"div",children:[e.jsxs(C,{direction:"row",spacing:1,sx:{alignItems:"center",mb:1},children:[e.jsx(D,{icon:A.faBoltAuto,size:"base"}),e.jsx(f,{variant:"h5",component:"h6",children:"Auto"})]}),e.jsx(f,{variant:"body2",sx:{color:"text.secondary"},children:"The router automatically selects the best model for each request based on your selected optimization criteria."})]}),e.jsx(ct,{}),e.jsxs(p,{component:"div",children:[e.jsx(f,{variant:"body2",sx:{fontWeight:600,mb:.5},children:"When to use"}),e.jsx(f,{variant:"body2",sx:{color:"text.secondary"},children:"Optimal when you have no specific provider or model version requirements or you want the system to automatically adapt as new models become available."})]})]})}),Pn=t=>t>=1e6?`${(t/1e6).toFixed(0)}M`:t>=1e3?`${(t/1e3).toFixed(0)}k`:t.toString(),wt=({models:t,value:n,onChange:r,disabled:s=!1,placeholder:a="Select model",allowAuto:i=!1,renderTrigger:h})=>{var te,ae;const[m,x]=l.useState(null),[c,v]=l.useState(""),[y,I]=l.useState(null),[E,V]=l.useState(null),H=l.useRef(null),M=i&&n===Gt,T=!!m,N=T?"llm-selector-popover":void 0,ne=l.useCallback(J=>{s||(x(J.currentTarget),setTimeout(()=>{var Z;return(Z=H.current)==null?void 0:Z.focus()},100))},[s]),z=l.useCallback(()=>{x(null),v(""),V(null)},[]),ee=l.useCallback(J=>{r(J),z()},[r,z]),pe=l.useMemo(()=>{const J=new Set,Z=[];for(const ie of t){if(!ie.isSupported||!ie.modelCreator)continue;const ye=ie.modelCreator;J.has(ye)||(J.add(ye),Z.push({id:ye,label:ye}))}return Z.sort((ie,ye)=>{const Me=Pt.indexOf(ie.id),_e=Pt.indexOf(ye.id),we=Me===-1?Pt.length:Me,me=_e===-1?Pt.length:_e;return we!==me?we-me:ie.label.localeCompare(ye.label)}),Z.map(ie=>({...ie,icon:xo(ie.id)}))},[t]),g=(ae=y!=null?y:(te=pe[0])==null?void 0:te.id)!=null?ae:"",ce=l.useMemo(()=>{const J=t.filter(Z=>!Z.isSupported||!Z.modelCreator?!1:c!==""||!g||Z.modelCreator===g);return mo(J,c)},[t,c,g]),de=l.useMemo(()=>E!==null?E:i?{type:"auto"}:ce.length>0?{type:"model",model:ce[0]}:null,[E,i,ce]),Q=l.useMemo(()=>{if(!n)return null;const J=t.find(Z=>`${Z.provider}/${Z.model}`===n);return J||(n.includes("/")?null:t.find(Z=>Z.model===n)||null)},[t,n]),R=M?"Auto":Q?`${Q.provider}/${Q.model}`:n||void 0,F=e.jsx(yr,{onClick:ne,open:T,disabled:s,placeholder:a,icon:M?e.jsx(D,{icon:A.faBoltAuto,size:"base"}):R?mt(R,20):void 0,label:R,ariaLabel:R?`Selected: ${R}`:a});return e.jsxs(e.Fragment,{children:[h?h({onClick:ne,open:T}):F,e.jsxs(lo,{id:N,open:T,anchorEl:m,onClose:z,title:"Select model",closeAriaLabel:"Close",filters:e.jsx(po,{filters:pe,activeId:g,onChange:I}),children:[e.jsxs(co,{ariaLabel:"Available models",search:{value:c,onChange:v,placeholder:"Search models...",inputRef:H},children:[i&&e.jsxs(e.Fragment,{children:[e.jsxs(Rn,{"aria-label":"Select Auto model",selected:M,onClick:()=>ee(Gt),onMouseEnter:()=>V({type:"auto"}),onFocus:()=>V({type:"auto"}),sx:{mt:"0.25rem"},children:[e.jsx(D,{icon:A.faBoltAuto,style:{fontSize:_.base}}),e.jsx(f,{variant:"body2",sx:{fontWeight:M?600:400,lineHeight:1.2},children:"Auto"})]}
2),e.jsx(ct,{sx:{my:"0.125rem"}})]}),ce.length===0?e.jsx(uo,{children:"No models found"}):ce.map(J=>{const Z=`${J.provider}/${J.model}`,ie=Z===n;return e.jsxs(Rn,{"aria-label":`Select ${Z}`,selected:ie,onClick:()=>ee(Z),onMouseEnter:()=>V({type:"model",model:J}),onFocus:()=>V({type:"model",model:J}),children:[mt(Z,20),e.jsx(f,{variant:"body2",sx:{fontWeight:ie?600:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Z})]},Z)})]}),(de==null?void 0:de.type)==="auto"&&e.jsx(Zo,{}),(de==null?void 0:de.type)==="model"&&e.jsx(Qo,{model:de.model})]})]})},Yt=[{value:tt.SORT_METRIC_INTELLIGENCE,label:"Intelligence",icon:A.faBrain,description:"Overall intelligence of the model based on the Artificial Analysis Intelligence Index"},{value:tt.SORT_METRIC_PRICE,label:"Cost",icon:A.faCoins,description:"Publicly listed token pricing of the model, based on adding input and output token pricing"},{value:tt.SORT_METRIC_LATENCY,label:"Latency",icon:A.faBolt,description:"Median time to first token"},{value:tt.SORT_METRIC_THROUGHPUT,label:"Throughput",description:"Median output tokens per second",icon:A.faGaugeHigh},{value:tt.SORT_METRIC_MATH,label:"Math",description:"Math capabilities of the model based on the MATH-500 benchmark",icon:A.faCalculator},{value:tt.SORT_METRIC_CODING,label:"Coding",description:"Coding capabilities of the model based on the LiveCodeBench benchmark",icon:A.faCode}],es=["First","Second"],ts=({providers:t,selectedValue:n,onSelect:r})=>e.jsx(e.Fragment,{children:t.map(s=>e.jsx(ve,{selected:s===n,onClick:()=>r(s),"aria-label":`Select ${s}`,children:e.jsxs(C,{direction:"row",spacing:1,sx:{alignItems:"center"},children:[mt(`${s}/`,16),e.jsx("span",{children:s.charAt(0).toUpperCase()+s.slice(1)})]})},s))}),ns=({id:t,sort:n,index:r,onRemove:s,showOrdinal:a=!0})=>{var I,E,V,H;const{attributes:i,listeners:h,setNodeRef:m,transform:x,transition:c,isDragging:v}=Sn({id:t}),y=Yt.find(M=>M.value===n.metric);return e.jsx(p,{component:"div",ref:m,style:{transform:wn.Transform.toString(x),transition:c,opacity:v?.5:1},sx:{display:"inline-flex",cursor:"grab"},onMouseDown:M=>M.stopPropagation(),...i,...h,children:e.jsx(st,{size:"small",label:a?`${(I=es[r])!=null?I:String(r+1)}: ${(E=y==null?void 0:y.label)!=null?E:String(n.metric)}`:(V=y==null?void 0:y.label)!=null?V:String(n.metric),icon:e.jsx(D,{icon:(H=y==null?void 0:y.icon)!=null?H:A.faBrain,style:{height:"1rem",width:"1rem"}}),onDelete:M=>{M.stopPropagation(),s(r)},sx:{cursor:"grab",fontSize:_.md,pointerEvents:"none",borderRadius:X.md,"& .MuiChip-deleteIcon":{pointerEvents:"auto",cursor:"pointer"}}})})},rs=({id:t,children:n})=>{const{attributes:r,listeners:s,setNodeRef:a,setActivatorNodeRef:i,transform:h,transition:m,isDragging:x}=Sn({id:t}),c=e.jsx(p,{component:"span",ref:i,...r,...s,sx:{cursor:x?"grabbing":"grab",color:"text.disabled",display:"flex",alignItems:"center",flexShrink:0,touchAction:"none","&:hover":{color:"text.secondary"}},children:e.jsx(D,{icon:A.faGripDotsVertical,size:"md"})});
2return e.jsx(p,{component:"div",ref:a,style:{transform:wn.Transform.toString(h),transition:m,opacity:x?.5:1},children:n(c)})},ur=({label:t,description:n,endIcon:r,sx:s,...a})=>e.jsxs(fe,{intent:"ghost","aria-label":t,disableRipple:!0,sx:[{display:"flex",flexDirection:"row",alignItems:n?"flex-start":"center",justifyContent:"space-between",gap:1,width:"100%",height:n?"auto":We,minHeight:"unset",backgroundColor:"transparent",p:"0.75rem",borderRadius:X.md,border:i=>`1px dashed ${i.palette.divider}`,textAlign:"left","&.Mui-disabled":{cursor:"not-allowed"},"&:hover":{backgroundColor:i=>i.palette.background.surface.main,borderColor:i=>i.palette.text.secondary},"&:focus-visible":{outline:i=>`2px solid ${i.palette.primary.main}`,outlineOffset:2}},...Array.isArray(s)?s:s?[s]:[]],...a,children:[e.jsxs(p,{component:"div",children:[e.jsx(f,{variant:"body2",sx:{lineHeight:1.4,color:"inherit"},children:t}),n&&e.jsx(f,{variant:"caption",sx:{display:"block",color:"inherit",opacity:.7,lineHeight:1.3,mt:.25},children:n})]}),r!=null?r:e.jsx(D,{icon:A.faPlus,style:{fontSize:_.sm,flexShrink:0,marginTop:n?2:0}})]}),un=({label:t,description:n,llmModels:r,onModelSelect:s,allowAuto:a=!1,disabled:i=!1})=>e.jsx(wt,{models:r,allowAuto:a,onChange:s,renderTrigger:({onClick:h})=>e.jsx(ur,{label:t,description:n,onClick:h,disabled:i})}),os=({label:t,description:n,availableProviders:r,excludedProviders:s,onProviderSelect:a,disabled:i=!1})=>{const[h,m]=l.useState(null),x=!!h,c=E=>{m(E.currentTarget)},v=()=>{m(null)},y=E=>{a(E),v()},I=r.filter(E=>!s.includes(E));return e.jsxs(e.Fragment,{children:[e.jsx(ur,{label:t,description:n,onClick:c,disabled:i}),e.jsx(Qn,{open:x,anchorEl:h,className:"inworld-text-field-menu",onClose:v,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},slotProps:{paper:{className:"inworld-text-field-menu",sx:{minWidth:"12rem",maxHeight:"300px",borderRadius:X.md}}},children:e.jsx(Hr,{children:I.length===0?e.jsx(ve,{disabled:!0,"aria-label":"All providers restricted",children:e.jsx(f,{variant:"body2",sx:{color:"text.secondary"},children:"All providers restricted"})}):e.jsx(ts,{providers:I,onSelect:y})})})]})},Nn=({value:t,onChange:n,label:r="Optimize for",maxSelections:s=2})=>{const a=t||[],i=a.map(M=>M.metric),h=a.map((M,T)=>`sort-chip-${T}-${M.metric}`),[m,x]=l.useState(!1),c=s>1,v=vn(kt(yn,{activationConstraint:{distance:5}}),kt(Vn,{coordinateGetter:Fn})),y=M=>{const{active:T,over:N}=M;if(N&&T.id!==N.id){const ne=h.indexOf(T.id),z=h.indexOf(N.id);n(mr(a,ne,z))}},I=M=>{const T=M.slice(0,s),N=T.map(ne=>{const z=a.find(ee=>ee.metric===ne);return z!=null?z:{metric:ne}});n(N),T.length>=s&&x(!1)},E=M=>{n(a.filter((T,N)=>N!==M))},V=i,H=e.jsx(jn,{sensors:v,collisionDetection:Cn,onDragEnd:y,children:e.jsx(In,{items:h,strategy:pr,children:e.jsx(Ce,{select:!0,fullWidth:!0,size:"small",className:"inworld-text-field",value:V,onChange:M=>{const T=M.target.value;I(T)},sx:{minWidth:0,"& .MuiInputBase-root":{height:"auto",minHeight:"2.25rem",flexWrap:"nowrap",alignItems:"center",py:"4px"},"& .MuiSelect-select":{pl:"0.5rem"},"& .MuiInputBase-input":{display:"flex",flexDirection:"row",alignItems:"center",py:0,minWidth:0,overflow:"hidden"}},slotProps:{select:{multiple:!0,displayEmpty:!0,open:m,onOpen:()=>x(!0),onClose:()=>x(!1),MenuProps:{className:"inworld-text-field-menu"},renderValue:M=>(Array.isArray(M)?M:[]).length===0?e.jsx(f,{variant:"body2",component:"span",sx:{color:"text.disabled"},children:"Default"}):e.jsx(p,{component:"div",sx:{display:"flex",flexDirection:"row",flexWrap:"nowrap",gap:.5,alignItems:"center"},children:a.map((N,ne)=>{var z;return e.jsx(ns,{id:(z=h[ne])!=null?z:`sort-chip-${ne}`,sort:N,index:ne,onRemove:E,showOrdinal:c},h[ne])})})}},children:Yt.map(M=>e.jsxs(ve,{value:M.value,disabled:i.length>=s&&!i.includes(M.value),sx:{display:"flex",gap:1},"aria-label":`Sort by ${M.label}`,children:[e.jsx(D,{icon:M.icon,style:{height:"1rem",width:"1rem"}}),e.jsxs(C,{direction:"column",spacing:0,children:[e.jsx(f,{variant:"body2",sx:{color:"text.primary"},children:M.label}),e.jsx(f,{variant:"body2",sx:{color:"text.secondary"},children:M.description})]})]},M.value))})})});return e.jsx($e,{label:r,infoHelperProps:{tooltip:"Selects the optimization criteria for ordering fallback models. When set to Default, models are tried in the order shown above.",size:"small"},children:H})},ss=[{metric:tt.SORT_METRIC_INTELLIGENCE}],is=({index:t,basePath:n,entryModel:r,llmModels:s,dragHandle:a,onRemove:i})=>{const{setValue:h}=xt();return e.jsxs(C,{direction:"row",spacing:1,sx:{alignItems:"start"}
2,children:[a&&e.jsx(p,{component:"div",sx:{display:"flex",alignItems:"center",height:We},children:a}),e.jsx(p,{component:"div",sx:{flex:1,display:"grid",gridTemplateColumns:"minmax(0, 1fr)",gap:1},children:e.jsx(wt,{models:s,value:r,onChange:m=>{h(`${n}.variant.modelSelection.models.${t}.model`,m)},placeholder:"Select a model"})}),e.jsx(se,{title:"Remove fallback model",children:e.jsx(Te,{"aria-label":"Remove fallback model",size:"small",onClick:i,sx:{color:"text.secondary",height:We},children:e.jsx(D,{icon:A.faXmark,style:{height:"1rem",width:"1rem"}})})})]})},as=({basePath:t,onDelete:n,canDelete:r,variantLetter:s,variantIndex:a,llmModels:i,isDistributionCustom:h,isDistributionError:m,onResetDistribution:x,siblingVariants:c,stickyTopOffset:v})=>{var je,Ne,Je,Ke,Xe;const{control:y,setValue:I,watch:E}=xt(),V=ht(),H=Rt(a,V.palette.tints),[M,T]=l.useState(!0),[N,ne]=l.useState(!1),z=c.length<=1,ee=()=>ne(!0),pe=b=>{b.currentTarget.contains(b.relatedTarget)||ne(!1)},g=(()=>{if(c.length<=1)return"";const b=c.reduce((G,W)=>G+W.weight,0),K=b!==100;return e.jsxs(C,{spacing:.5,children:[c.map(G=>{const W="ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(G.letter),Y=Rt(W,V.palette.tints);return e.jsxs(C,{direction:"row",spacing:.75,sx:{alignItems:"center",opacity:G.isCurrent?1:.7},children:[e.jsx(p,{component:"span",sx:{backgroundColor:Y.backgroundColor,color:Y.color,fontWeight:700,fontSize:_.xs,width:"1.125rem",height:"1.125rem",borderRadius:X.sm,flexShrink:0,display:"inline-flex",alignItems:"center",justifyContent:"center",lineHeight:1},children:G.letter}),e.jsxs(f,{variant:"caption",sx:{fontWeight:G.isCurrent?700:400},children:[G.weight,"%"]})]},G.letter)}),e.jsxs(C,{direction:"row",spacing:.75,sx:{alignItems:"center",borderTop:G=>`1px solid ${Le(G.palette.background.paper,.15)}`,pt:.5,mt:.25},children:[e.jsx(p,{component:"span",sx:{width:"1.125rem",height:"1.125rem",borderRadius:X.sm,flexShrink:0,display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:_.sm,fontWeight:700,lineHeight:1,opacity:.5,border:G=>`1px solid ${Le(G.palette.background.paper,.3)}`},children:"Σ"}),e.jsxs(f,{variant:"caption",sx:{fontWeight:700,color:K?"error.main":"inherit"},children:[b,"%"]})]})]})})(),ce=ze({control:y,name:`${t}.variant.variantId`}),de=(je=E(`${t}.variant.isAutoModel`))!=null?je:!0,Q=(Ne=E(`${t}.variant.modelSelection.models`))!=null?Ne:[],R=(Je=E(`${t}.variant.modelSelection.sort`))!=null?Je:ss,F=(Ke=E(`${t}.variant.modelId`))!=null?Ke:"",te=(Xe=E(`${t}.variant.modelSelection.ignore`))!=null?Xe:[],ae=l.useMemo(()=>!Array.isArray(R)||R.length===0?[]:R.flatMap(b=>{const K=Yt.find(G=>G.value===(b==null?void 0:b.metric));return K?[{label:K.label,icon:K.icon,isDescending:(b==null?void 0:b.direction)===Er.SORT_DIRECTION_DESCENDING}]:[]}),[R]),{fields:J,append:Z,remove:ie,move:ye}=hn({control:y,name:`${t}.variant.modelSelection.models`}),{fields:Me,append:_e,remove:we}=hn({control:y,name:`${t}.variant.modelSelection.ignore`}),me=vn(kt(yn,{activationConstraint:{distance:5}}),kt(Vn,{coordinateGetter:Fn})),Pe=J.map(b=>b.id),Ye=b=>{const{active:K,over:G}=b;if(G&&K.id!==G.id){const W=Pe.indexOf(K.id),Y=Pe.indexOf(G.id);ye(W,Y)}},qe=l.useMemo(()=>{const b=new Set(i.filter(K=>K.isSupported).map(K=>K.provider.toLowerCase()));return Array.from(b).sort()},[i]),Ie=l.useRef(null),[be,B]=l.useState(!1);return l.useEffect(()=>{const b=Ie.current;if(!b)return;const G=(xe=>{let P=xe.parentElement;for(;P;){const{overflowY:re}=window.getComputedStyle(P);if(re==="auto"||re==="scroll")return P;P=P.parentElement}return null})(b),W=v?`-${v}`:"-72px",Y=new IntersectionObserver(([xe])=>B(!xe.isIntersecting),{root:G,threshold:0,rootMargin:`${W} 0px 0px 0px`});return Y.observe(b),()=>Y.disconnect()},[v]),e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:Ie,style:{height:0,pointerEvents:"none"}}),e.jsxs(Gn,{expanded:M,onChange:()=>T(!M),disableGutters:!0,elevation:0,sx:{mt:0,"&.MuiAccordion-root.MuiPaper-root":{mb:"1rem",borderRadius:X.md},border:b=>`1px solid ${m&&!M?b.palette.error.main:b.palette.divider}`,"&:before":{display:"none"},backgroundColor:b=>m&&!M?Le(b.palette.error.main,.05):void 0,overflow:"clip"},children:[e.jsx(Yn,{sx:{height:"3rem",containerType:"inline-size",containerName:"variant-header",position:"sticky",top:"-1.5rem",zIndex:2,backgroundColor:b=>m&&!M?Le(b.palette.error.main,.05):b.palette.background.paper,borderBottom:b=>`1px solid ${M?b.palette.divider:"transparent"}`,boxShadow:be?jr.md:"none",transition:"background-color 0.15s ease, box-shadow 0.15s ease","& .MuiAccordionSummary-content":{margin:"0.75rem 0"}}
2,children:e.jsxs(p,{component:"div",sx:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",alignItems:"center",width:"100%",columnGap:1,"@container variant-header (max-width: 500px)":{gridTemplateColumns:"1fr auto"}},children:[e.jsxs(C,{direction:"row",spacing:1,sx:{alignItems:"center",minWidth:0,overflow:"hidden","@container variant-header (max-width: 280px)":{gap:.5}},children:[e.jsx(D,{icon:M?A.faChevronDown:A.faChevronRight,style:{height:"1rem",width:"1rem",flexShrink:0}}),e.jsx(p,{component:"div",sx:{backgroundColor:H.backgroundColor,color:H.color,fontWeight:600,fontSize:_.sm,width:"1.25rem",height:"1.25rem",borderRadius:X.sm,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:s}),e.jsx(f,{variant:"h6",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap","@container variant-header (max-width: 280px)":{fontSize:_.md}},children:M?"Edit variant":ce||"Edit variant"}),!M&&ce&&e.jsx(Kt,{copy:ce,tooltip:"Copy ID",iconButtonProps:{sx:{flexShrink:0,[et]:Ze.md}}})]}),e.jsx(p,{component:"div",sx:{minWidth:0,overflow:"hidden",display:"flex",alignItems:"center",pl:1.5,"@container variant-header (max-width: 500px)":{display:"none"}},children:!M&&e.jsx(C,{direction:"row",spacing:1,sx:{alignItems:"center",flexWrap:"nowrap"},children:de?e.jsxs(e.Fragment,{children:[e.jsx(dt,{models:["auto"],iconSize:13,bubbleSize:"1.5rem"}),((Q==null?void 0:Q.length)>0||te.length>0)&&e.jsx(dt,{models:[...Q.map(b=>b.model),...te],bannedModels:te,iconSize:13,bubbleSize:"1.5rem"}),ae.map(b=>e.jsx(st,{color:"secondary",label:e.jsxs(C,{direction:"row",spacing:.5,sx:{alignItems:"center"},children:[e.jsx(D,{icon:b.isDescending?A.faArrowDownWideShort:A.faArrowUpShortWide,style:{fontSize:_.xs}}),e.jsx("span",{children:b.label}),e.jsx(D,{icon:b.icon,style:{fontSize:_.xs}})]}),size:"small",sx:{flexShrink:0,borderRadius:X.sm,height:"1.375rem","& .MuiChip-label":{fontSize:_.md,px:.75}}},b.label))]}):e.jsxs(e.Fragment,{children:[F&&e.jsx(dt,{models:[F],iconSize:13,bubbleSize:"1.5rem",deduplicateByProvider:!1}),((Q==null?void 0:Q.length)>0||te.length>0)&&e.jsx(dt,{models:[...Q.map(b=>b.model),...te],bannedModels:te,iconSize:13,bubbleSize:"1.5rem"})]})})}),e.jsxs(C,{direction:"row",sx:{alignItems:"center",justifyContent:"flex-end",gap:.5},children:[!M&&e.jsx(ke,{name:`${t}.weight`,control:y,defaultValue:0,render:({field:b})=>{var G;const K=(G=b.value)!=null?G:0;return e.jsx(se,{open:z?void 0:N&&c.length>1,placement:"top",disableHoverListener:!z,disableFocusListener:!z,disableTouchListener:!z,title:z?"Add another variant to adjust traffic distribution":g,children:e.jsxs(C,{"aria-label":"Weight percentage",direction:"row",onClick:W=>W.stopPropagation(),onFocus:ee,onBlur:pe,sx:{alignItems:"center",gap:"0.75rem",flexShrink:0,"@container variant-header (max-width: 600px)":{display:"none"}},children:[e.jsx(lt,{value:K,onChange:(W,Y)=>b.onChange(Y),disabled:z,min:0,max:100,sx:{width:"80px","& .MuiSlider-thumb":{width:"0.75rem",height:"0.75rem",backgroundColor:"text.accent"},"& .MuiSlider-track":{backgroundColor:"text.accent",border:"none"},"& .MuiSlider-rail":{backgroundColor:W=>W.palette.divider}}}),e.jsx(Ce,{type:"number",disabled:z,value:K,onChange:W=>{const Y=W.target.value;if(!/^\d*$/.test(Y))return;const xe=parseInt(Y,10);Y===""?b.onChange(0):!isNaN(xe)&&xe>=0&&xe<=100&&b.onChange(xe)},onKeyDown:W=>{["e","E","+","-","."].includes(W.key)&&W.preventDefault()},size:"small",slotProps:{input:{endAdornment:e.jsx(Ut,{position:"end",children:"%"})},htmlInput:{inputMode:"numeric",pattern:"[0-9]*",style:{textAlign:"right"}}},sx:[Tt,{width:"4rem","& .MuiInputBase-input":{fontSize:_.md,padding:"0.25rem 0.375rem",MozAppearance:"textfield","&::-webkit-outer-spin-button, &::-webkit-inner-spin-button":{WebkitAppearance:"none",margin:0}},"& .MuiInputAdornment-root":{ml:0,"& .MuiTypography-root":{fontSize:_.md}}}]}),h&&e.jsx(se,{title:"Reset to even distribution",children:e.jsx(Te,{"aria-label":"Reset to even distribution",size:"small",onClick:W=>{W.stopPropagation(),x()},sx:{p:"2px",color:m?"error.main":"inherit",[et]:Ze.sm},children:e.jsx(D,{icon:A.faRotateLeft})})})]})})}}),r&&e.jsx(se,{title:"Delete variant",children:e.jsx(Te,{"aria-label":"Delete variant",size:"small",onClick:b=>{b.stopPropagation(),n()},sx:{[et]:Ze.md},children:e.jsx(D,{icon:A.faTrash,style:{height:"1rem",width:"1rem"}})})})]})]})}),e.jsx(qn,{sx:{p:2,containerType:"inline-size",containerName:"variant"}
2,children:e.jsxs(C,{children:[e.jsxs(p,{component:"div",sx:{display:"flex",flexDirection:"row",mb:"1.5rem",gap:2,flexWrap:"wrap","@container variant (max-width: 480px)":{flexDirection:"column",gap:2}},children:[e.jsx(p,{component:"div",sx:{flex:1,minWidth:"200px","@container variant (max-width: 480px)":{minWidth:"100%"}},children:e.jsx(ke,{name:`${t}.variant.variantId`,control:y,render:({field:b})=>e.jsx($e,{label:"ID",sx:{width:"100%"},children:e.jsx(Ce,{...b,variant:"outlined",className:"inworld-text-field",size:"small",fullWidth:!0,sx:{"& .MuiInputBase-input":{fontSize:_.md},"& .MuiInputAdornment-root":{ml:"unset",mr:"-0.5rem"}},slotProps:{input:{endAdornment:e.jsx(Ut,{position:"end",children:e.jsx(Kt,{copy:b.value,tooltip:"Copy ID",iconButtonProps:{size:"small",sx:{borderRadius:X.sm,[et]:Ze.md}}})})}}})})})}),e.jsx(p,{component:"div",sx:{flex:1,minWidth:"200px","@container variant (max-width: 480px)":{minWidth:"100%"}},children:e.jsx($e,{label:"Traffic",infoHelperProps:{tooltip:"The percent of requests for this route sent to this variant"},customRightSlot:e.jsxs(C,{direction:"row",spacing:.25,sx:{alignItems:"center",ml:"auto"},children:[h&&e.jsx(se,{title:"Reset to even distribution",placement:"top",children:e.jsx(fe,{intent:"ghost","aria-label":"Reset to even distribution",size:"small",onClick:x,startIcon:e.jsx(D,{icon:A.faRotateLeft}),sx:{fontSize:_.md,color:"text.secondary",[et]:Ze.sm},children:"Reset"})}),m&&e.jsx(se,{title:"Traffic across all variants must add up to 100%",placement:"top",children:e.jsx(p,{component:"span",sx:{display:"flex",alignItems:"center",color:"error.main",[et]:Ze.sm},children:e.jsx(D,{icon:A.faCircleExclamation})})})]}),children:e.jsx(ke,{name:`${t}.weight`,control:y,defaultValue:0,render:({field:b})=>{var G;const K=(G=b.value)!=null?G:0;return e.jsx(se,{open:z?void 0:N&&c.length>1,placement:"top",disableHoverListener:!z,disableFocusListener:!z,disableTouchListener:!z,title:z?"Add another variant to adjust traffic distribution":g,children:e.jsxs(C,{direction:"row",spacing:2,onFocus:ee,onBlur:pe,sx:{alignItems:"center",boxSizing:"border-box",height:Ir,px:"0.75rem",borderRadius:Cr.borderRadius,border:W=>`1px solid ${m?W.palette.error.main:W.palette.divider}`,backgroundColor:W=>m?Le(W.palette.error.main,.05):W.palette.background.paper,"@container variant (max-width: 320px)":{flexDirection:"column",alignItems:"stretch",gap:"0.5rem",height:"auto",py:"0.5rem"}},children:[e.jsx(lt,{value:K,onChange:(W,Y)=>b.onChange(Y),disabled:z,min:0,max:100,sx:{"& .MuiSlider-thumb":{width:16,height:16,backgroundColor:"text.accent"},"& .MuiSlider-track":{backgroundColor:"text.accent",border:"none"},"& .MuiSlider-rail":{backgroundColor:W=>W.palette.divider}}}),e.jsx(Ce,{value:K,disabled:z,onChange:W=>{const Y=W.target.value;if(!/^\d*$/.test(Y))return;const xe=parseInt(Y,10);Y===""?b.onChange(0):!isNaN(xe)&&xe>=0&&xe<=100&&b.onChange(xe)},onKeyDown:W=>{["e","E","+","-","."].includes(W.key)&&W.preventDefault()},size:"small",slotProps:{input:{endAdornment:e.jsx(Ut,{position:"end",children:"%"})},htmlInput:{inputMode:"numeric",pattern:"[0-9]*",style:{textAlign:"right"}}},sx:[Tt,{width:"5rem",minWidth:"5rem",maxWidth:"5rem",flexShrink:0,"& .MuiInputBase-root":{height:"1.75rem"},"& .MuiInputBase-input":{fontSize:_.md,padding:"0.25rem 0.5rem"}}]})]})})}})})})]}),e.jsxs(p,{component:"div",sx:{display:"grid",mb:"1.5rem",gridTemplateColumns:de?"minmax(0, 1fr) minmax(0, 1fr)":"1fr",gap:2,alignItems:"start"},children:[e.jsx($e,{label:"Model",children:e.jsx(wt,{models:i,value:de?Gt:F,onChange:b=>{b===Gt?(I(`${t}.variant.isAutoModel`,!0),I(`${t}.variant.modelId`,"")):(I(`${t}.variant.isAutoModel`,!1),I(`${t}.variant.modelId`,b))},allowAuto:!0,placeholder:"Select a model"})}),de&&e.jsx(p,{component:"div",sx:{minWidth:0},children:e.jsx(ke,{name:`${t}.variant.modelSelection.sort`,control:y,defaultValue:[],render:({field:b})=>e.jsx(Nn,{value:b.value,onChange:b.onChange})})})]}),de&&(()=>{const b=Q==null?void 0:Q.some(P=>!!P.model),K=Me.length>0,G=b||K,W=e.jsx(se,{title:K?"Remove all restrictions to add specific models":"",disableHoverListener:!K,children:e.jsx("span",{children:e.jsx(un,{label:"Add model",description:"Select desired models to be used",llmModels:i,disabled:K,onModelSelect:P=>{Z({model:P}),I(`${t}.variant.modelSelection.ignore`,[])}})})}),Y=e.jsx(se,{title:b?"Remove all models to add restrictions":"",disableHoverListener:!b,children:e.jsx("span",{children:e.jsx(un,{label:"Add model restriction",description:"Exclude a specific model",llmModels:i,disabled:b,onModelSelect:P=>{_e(P)}})})}),xe=e.jsx(se,{title:b?"Remove all models to add restrictions":"",disableHoverListener:!b,children:e.jsx("span",{children:e.jsx(os,{label:"Add provider restriction",description:"Exclude all models from a provider",availableProviders:qe,excludedProviders:(te||[]).filter(P=>P&&!P.includes("/")),disabled:b,onProviderSelect:P=>{_e(P)}})})});return e.jsx($e,{label:"Model list",infoHelperProps:{tooltip:"The set of models that can be selected based on the optimization criteria. If none are specified here, all available models are considered.",size:"small"},customRightSlot:G?e.jsx(fe,{intent:"ghost",size:"small","aria-label":"Clear all model list",onClick:()=>{I(`${t}.variant.modelSelection.models`,[]),I(`${t}.variant.modelSelection.ignore`,[])},sx:{ml:"auto",fontSize:_.md,py:0,minWidth:"unset"}
2,children:"Clear all"}):null,children:G?e.jsxs(C,{spacing:1.5,sx:{containerType:"inline-size"},children:[e.jsx(p,{component:"div",sx:{border:P=>`1px solid ${P.palette.divider}`,borderRadius:X.md,p:1.5},children:e.jsxs(C,{spacing:1.5,children:[b&&e.jsxs(e.Fragment,{children:[e.jsx(f,{variant:"body2",children:(()=>{var he;const P=R==null?void 0:R.filter(oe=>oe==null?void 0:oe.metric);if(!P||P.length===0)return"Use these models";const re=P.map(oe=>{var Re,Oe;return(Oe=(Re=Yt.find(Qe=>Qe.value===oe.metric))==null?void 0:Re.label)!=null?Oe:oe.metric});return`Use these models, sorted by ${(re.length===1?(he=re[0])!=null?he:"":re.map((oe,Re)=>Re===0?oe!=null?oe:"":`then ${(oe!=null?oe:"").toLowerCase()}`).join(", ")).toLowerCase()}`})()}),J.map((P,re)=>{const Se=Q==null?void 0:Q[re],he=(Se==null?void 0:Se.model)||"";return e.jsxs(C,{direction:"row",spacing:1,sx:{alignItems:"start"},children:[e.jsx(p,{component:"div",sx:{flex:1,display:"grid",gridTemplateColumns:"minmax(0, 1fr)",gap:1},children:e.jsx(wt,{models:i,value:he,onChange:oe=>{I(`${t}.variant.modelSelection.models.${re}.model`,oe),oe&&I(`${t}.variant.modelSelection.ignore`,[])},placeholder:"Select a model"})}),e.jsx(se,{title:"Remove model",children:e.jsx(Te,{"aria-label":"Remove model from pool",size:"small",onClick:()=>ie(re),sx:{color:"text.secondary",height:We},children:e.jsx(D,{icon:A.faXmark,style:{height:"1rem",width:"1rem"}})})})]},P.id)})]}),K&&e.jsxs(e.Fragment,{children:[e.jsx(f,{variant:"body2",children:"Don't use these models/providers"}),Me.map((P,re)=>e.jsx(ke,{name:`${t}.variant.modelSelection.ignore.${re}`,control:y,render:({field:Se})=>{const he=Se.value||"",oe=!he.includes("/")&&qe.includes(he),Re=e.jsx(D,{icon:A.faBan,style:{marginRight:"0.25rem",fontSize:_.base,color:"inherit",flexShrink:0}});return oe?e.jsxs(C,{direction:"row",spacing:1,sx:{alignItems:"start"},children:[e.jsxs(C,{direction:"row",spacing:.5,sx:{alignItems:"center",flex:1,height:We},children:[Re,mt(`${he}/`,16),e.jsx(f,{variant:"body2",children:he.charAt(0).toUpperCase()+he.slice(1)})]}),e.jsx(se,{title:"Remove provider restriction",children:e.jsx(Te,{"aria-label":"Remove provider restriction",size:"small",onClick:()=>we(re),sx:{color:"text.secondary",height:We},children:e.jsx(D,{icon:A.faXmark,style:{height:"1rem",width:"1rem"}})})})]}):e.jsxs(C,{direction:"row",spacing:1,sx:{alignItems:"start"},children:[e.jsxs(C,{direction:"row",spacing:0,sx:{alignItems:"center",flex:1},children:[e.jsx(p,{component:"span",sx:{display:"flex",alignItems:"center",height:We,flexShrink:0,mr:.5},children:Re}),e.jsx(p,{component:"div",sx:{flex:1,minWidth:0},children:e.jsx(wt,{models:i,value:he,onChange:Oe=>{Se.onChange(Oe),Oe&&I(`${t}.variant.modelSelection.models`,[])},placeholder:"Select a model"})})]}),e.jsx(se,{title:"Remove model restriction",children:e.jsx(Te,{"aria-label":"Remove model restriction",size:"small",onClick:()=>we(re),sx:{color:"text.secondary",height:We},children:e.jsx(D,{icon:A.faXmark,style:{height:"1rem",width:"1rem"}})})})]})}},P.id))]})]})}),e.jsxs(p,{component:"div",sx:{display:"flex",flexDirection:"row",alignItems:"stretch",gap:1,mb:1.5,"& > span":{flex:1,minWidth:0,display:"flex",flexDirection:"column"},"& > span > button":{height:"100%"},"@container (max-width: 500px)":{flexDirection:"column","& > span":{flex:"none",width:"100%"},"& > span > button":{height:"auto"}}},children:[W,Y,xe]})]}):e.jsxs(p,{component:"div",sx:{border:P=>`1px solid ${P.palette.divider}`,borderRadius:X.md,p:2,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",containerType:"inline-size"},children:[e.jsx(f,{variant:"body1",sx:{fontWeight:600,mb:"0.5rem",textAlign:"center"},children:"Define model list"}),e.jsx(f,{variant:"body2",sx:{color:"text.secondary",textAlign:"center",mb:"1.5rem",maxWidth:"20rem"},children:"The set of models that can be selected based on the optimization criteria. If none are specified here, all available models are considered."}),e.jsxs(p,{component:"div",sx:{width:"100%",display:"flex",flexDirection:"row",alignItems:"stretch",gap:1,"& > span":{flex:1,minWidth:0,display:"flex",flexDirection:"column"},"& > span > button":{height:"100%"},"@container (max-width: 500px)":{flexDirection:"column","& > span":{flex:"none",width:"100%"},"& > span > button":{height:"auto"}}},children:[W,Y,xe]})]})})})(),!de&&e.jsxs(C,{spacing:1.5,children:[e.jsx($e,{label:"Model fallbacks",infoHelperProps:{tooltip:"If the primary model fails, the router tries these models in order. Leave empty to surface an error instead of falling back.",size:"small"},children:e.jsxs(C,{spacing:J.length>0?1.5:0,children:[J.length>0&&e.jsx(jn,{sensors:me,collisionDetection:Cn,onDragEnd:Ye,children:e.jsx(In,{items:Pe,strategy:Un,children:e.jsx(C,{spacing:1.5,children:J.map((b,K)=>e.jsx(rs,{id:b.id,children:G=>{var W;return e.jsx(is,{index:K,basePath:t,entryModel:((W=Q==null?void 0:Q[K])==null?void 0:W.model)||"",llmModels:i,dragHandle:G,onRemove:()=>ie(K)})}},b.id))})})}),e.jsx(un,{allowAuto:!1,label:"Add fallback model",llmModels:i,onModelSelect:b=>{Z({model:b})}})]})}),J.length>=2&&e.jsx(ke,{name:`${t}.variant.modelSelection.sort`,control:y,defaultValue:[],render:({field:b})=>e.jsx(Nn,{label:"Sort by",value:b.value,onChange:b.onChange,maxSelections:1})})]}),e.jsx(p,{component:"div",sx:{mt:"1rem"},children:e.jsx(sr,{title:"Advanced variant settings",messageTemplatesFieldName:`${t}.variant.messageTemplates`,textGenerationConfigFieldName:`${t}.variant.textGenerationConfig`,defaultsTextGenerationConfigFieldName:"defaults.textGenerationConfig",webSearchFieldName:`${t}.variant.webSearch`,compressionFieldName:`${t}.variant.compression`,fallbackFieldName:`${t}.variant.fallback`})})]})})]})]})},ls=t=>{t.languages.getLanguages().some(({id:n})=>n==="cel")||(t.languages.register({id:"cel"}
2),t.languages.setMonarchTokensProvider("cel",Lo),t.languages.registerCompletionItemProvider("cel",Oo))},Bn=({errors:t,watchedRoutes:n,defaultRoute:r,hasSubmitAttempted:s,validationPanelRef:a,control:i,isEditMode:h,setValue:m})=>e.jsxs(p,{component:"div",sx:{pb:"2.5rem",maxWidth:Vt.page,mx:"auto",px:"1.5rem",pt:"1.5rem"},children:[e.jsx(Xo,{errors:t,watchedRoutes:n,defaultRouteId:r.routeId,hasSubmitAttempted:s,rootRef:a}),e.jsxs(p,{component:"div",sx:{display:"flex",flexDirection:"row",alignItems:"flex-start",gap:2,flexWrap:"wrap"},children:[e.jsx(ke,{name:"displayName",control:i,rules:{required:{value:!0,message:"Display name cannot be empty"},validate:x=>(x==null?void 0:x.trim().length)>0||"Display name cannot be empty"},render:({field:x,fieldState:{error:c}})=>e.jsx($e,{sx:{flex:1,minWidth:"12rem"},label:"Name",children:e.jsx(Ce,{...x,onChange:v=>{x.onChange(v),h||m("name",rr(v.target.value),{shouldValidate:!1,shouldDirty:!0})},variant:"outlined",className:"inworld-text-field",size:"small",placeholder:"Eg. A/B Test",sx:{"& .MuiInputBase-input":{fontSize:_.base}},fullWidth:!0,error:!!c,helperText:c!=null&&c.message?e.jsx(xn,{errors:[c.message]}):null})})}),e.jsx(ke,{name:"name",control:i,rules:{required:{value:!0,message:"ID cannot be empty"},validate:x=>{if(h)return!0;if(!x)return"ID cannot be empty";const c=x==null?void 0:x.trim();return c.length===0?"ID cannot be empty":c==="new"?'ID cannot be "new"':/^[a-z0-9_-]{1,61}$/.test(c)?!0:"ID must be 1-61 characters and contain only lowercase letters, numbers, underscores, and hyphens"}},render:({field:x,fieldState:{error:c}})=>e.jsx($e,{sx:{flex:1,minWidth:"12rem"},label:"ID",children:e.jsx(Ce,{...x,variant:"outlined",className:"inworld-text-field",size:"small",placeholder:"Router name",sx:{"& .MuiInputBase-input":{fontSize:_.base,fontFamily:h?Jt.mono:Jt.functional},"& .MuiInputAdornment-positionEnd, & .MuiInputAdornment-positionEnd *":{cursor:"pointer",pointerEvents:"auto"},"&.inworld-text-field .MuiInputBase-root .MuiInputAdornment-positionEnd":{marginLeft:0,marginRight:"-0.5rem"}},fullWidth:!0,disabled:h,error:!!c,helperText:c!=null&&c.message?e.jsx(xn,{errors:[c.message]}):null,slotProps:{input:{endAdornment:h?e.jsx(Ut,{position:"end",children:e.jsx(Kt,{copy:qr(x.value),tooltip:"Copy ID",iconButtonProps:{size:"small",style:{cursor:"pointer",pointerEvents:"auto"},sx:{[et]:Ze.sm}}})}):void 0}}})})})]}),e.jsx(p,{component:"div",sx:{mt:"1rem"},children:e.jsx(sr,{title:"Advanced router settings",messageTemplatesFieldName:"defaults.messageTemplates",textGenerationConfigFieldName:"defaults.textGenerationConfig"})})]}),cs=({field:t,index:n,isSelected:r,routeName:s,variantIds:a,variants:i,onClick:h})=>{const{attributes:m,listeners:x,setNodeRef:c,setActivatorNodeRef:v,transform:y,transition:I,isDragging:E}=Sn({id:t.id});return e.jsx(p,{ref:c,component:"div",sx:{transform:wn.Transform.toString(y),transition:I,opacity:E?.4:1},children:e.jsx(ir,{index:n,isSelected:r,routeName:s,variantIds:a,variants:i,onClick:h,dragHandleProps:{setActivatorNodeRef:v,attributes:m,listeners:x,isDragging:E}})})},ds=({selectedRouteIndex:t,defaultRoute:n,watchedRoutes:r,routeFields:s,handleRouteClick:a,handleAddRoute:i,onDragEnd:h})=>{var x,c;const m=vn(kt(yn,{activationConstraint:{distance:4}}));return e.jsxs(C,{direction:"column",className:"routes-sidebar",spacing:1,sx:{alignSelf:"flex-start",position:"sticky",top:"1.5rem",width:"18rem"},children:[e.jsx(C,{direction:"row",sx:{alignItems:"center",minHeight:"2rem"},children:e.jsx(f,{variant:"body1",sx:{fontWeight:600},children:"Routes"})}),e.jsxs(C,{direction:"column",spacing:1,children:[e.jsx(fe,{intent:"secondary","aria-label":"Add conditional route",size:"small",sx:v=>({display:"flex",justifyContent:"space-between",height:We,backgroundColor:"transparent","&:hover":{backgroundColor:v.palette.background.surface.main},"@container routes-section (max-width: 720px)":{width:"100%"}}),endIcon:e.jsx(D,{icon:A.faPlus}),onClick:i,children:"Add conditional route"}),e.jsx(jn,{sensors:m,collisionDetection:Cn,onDragEnd:h,children:e.jsx(In,{items:s.map(v=>v.id),strategy:Un,children:s.map((v,y)=>{var I,E,V,H,M;return e.jsx(cs,{field:v,index:y,isSelected:t===y,routeName:((I=r[y])==null?void 0:I.route.routeId)||"",variantIds:((V=(E=r[y])==null?void 0:E.route.variants)!=null?V:[]).map(T=>{var N;return(N=T.variant)==null?void 0:N.variantId}).filter(T=>!!T),variants:(M=(H=r[y])==null?void 0:H.route.variants)!=null?M:[],onClick:a},v.id)})})}),e.jsx(ir,{index:-1,isSelected:t===-1,routeName:n.routeId,isDefault:!0,variantIds:((x=n.variants)!=null?x:[]).map(v=>{var y;return(y=v.variant)==null?void 0:y.variantId}).filter(v=>!!v),variants:(c=n.variants)!=null?c:[],onClick:a},"default-route")]}),e.jsx(f,{variant:"body2",sx:{color:"text.secondary",mb:"2rem"},children:"Routes are evaluated top to bottom and the first route whose conditions match is used. If none match, the Default route applies."})]})},Ys=()=>{var $t,zt,ft,bt,vt,d,S,w;const t=ht(),{workspace:n,routerId:r}=Xt(),s=Jn(),a=Sr(),i=!!r,h=i,[m,x]=l.useState((($t=a.state)==null?void 0:$t.openTab)||"configuration"),[c,v]=l.useState(!1),[y,I]=l.useState(!1),[E,V]=l.useState(null),H=l.useRef(null),M=l.useRef(null),[T,N]=l.useState(!1);l.useLayoutEffect(()=>{var j;const o=(j=H.current)==null?void 0:j.closest(".enhanced-page-header");if(!o)return;N(o.clientWidth<960);const u=new ResizeObserver(([k])=>{N(k.contentRect.width<960)});return u.observe(o),()=>u.disconnect()},[]);const{isLoading:ne,mutate:z}=Ar(n!=null?n:"",()=>
2{St("Router has been deleted"),s(`/workspaces/${n}/routers`)},o=>{nt(`Failed to delete router. ${o==null?void 0:o.message}`)}),{data:ee}=Mr(n!=null?n:"",o=>{nt("Failed to fetch LLM models",o.message)}),pe=l.useRef(ee);pe.current=ee;const{data:g,isLoading:ce,error:de}=Dr(n!=null?n:"",r?`routers/${r}`:""),Q=l.useMemo(()=>{var u,j,k,$,L;if(!g)return[];const o=[];for(const O of(u=g.routes)!=null?u:[])(j=O.route)!=null&&j.routeId&&o.push({routeId:O.route.routeId,isDefault:!1,variantIds:((k=O.route.variants)!=null?k:[]).map(q=>{var ue;return(ue=q.variant)==null?void 0:ue.variantId}).filter(q=>!!q)});return($=g.defaultRoute)!=null&&$.routeId&&o.push({routeId:g.defaultRoute.routeId,isDefault:!0,variantIds:((L=g.defaultRoute.variants)!=null?L:[]).map(O=>{var q;return(q=O.variant)==null?void 0:q.variantId}).filter(O=>!!O)}),o},[g]),R=l.useRef(i||(zt=a.state)==null?void 0:zt.preset),F=wr({mode:"onChange",defaultValues:(ft=R.current)!=null?ft:Dn}),{control:te,handleSubmit:ae,reset:J,watch:Z,getValues:ie,setError:ye,setValue:
2Me,formState:{isDirty:_e,errors:we}}=F,{fields:me,append:Pe,remove:Ye,move:qe}=hn({control:te,name:"routes"}),Ie=Z("defaultRoute"),be=Z("routes"),[B,je]=l.useState(-1),[Ne,Je]=l.useState(!1),[Ke,Xe]=l.useState(0),b=l.useRef(null);l.useEffect(()=>{var o;Ke!==0&&((o=b.current)==null||o.scrollIntoView({behavior:"smooth",block:"start"}))},[Ke]);const K=l.useRef(!1),G=l.useRef(void 0),W=l.useCallback(o=>{je(o)},[]),Y=l.useCallback(o=>{const{active:u,over:j}=o;if(!j||u.id===j.id)return;const k=me.findIndex(L=>L.id===u.id),$=me.findIndex(L=>L.id===j.id);k===-1||$===-1||(qe(k,$),je(L=>{if(L===k)return $;const O=Math.min(k,$),q=Math.max(k,$);return L<O||L>q?L:k<$?L-1:L+1}))},[qe,me]),xe=l.useCallback(()=>{const o=be.map(j=>j.route.routeId),u={route:{routeId:Yr(o),variants:[on]},condition:{celExpression:""}};Pe(u),je(me.length)},[Pe,me.length,be]),P=l.useCallback(()=>{var O;const o=B===-1?Ie.variants||[]:((O=be[B])==null?void 0:O.route.variants)||[],u=ut(o.length),j={...on,variant:{...on.variant,variantId:`variant-${u.toLowerCase()}`},weight:0},k=[...o,j],$=Ot(k.length),L=k.map((q,ue)=>({...q,weight:$[ue]}));B===-1?F.setValue("defaultRoute.variants",L):F.setValue(`routes.${B}.route.variants`,L)},[B,Ie.variants,be,F]),re=l.useCallback(o=>{var L;const j=(B===-1?Ie.variants||[]:((L=be[B])==null?void 0:L.route.variants)||[]).filter((O,q)=>q!==o),k=Ot(j.length),$=j.map((O,q)=>({...O,weight:k[q]}));B===-1?F.setValue("defaultRoute.variants",$):F.setValue(`routes.${B}.route.variants`,$)},[B,Ie.variants,be,F]),Se=l.useCallback(()=>{var k;const o=B===-1?Ie.variants||[]:((k=be[B])==null?void 0:k.route.variants)||[],u=Ot(o.length),j=o.map(($,L)=>({...$,weight:u[L]}));B===-1?F.setValue("defaultRoute.variants",j):F.setValue(`routes.${B}.route.variants`,j)},[B,Ie.variants,be,F]);l.useEffect(()=>{var o,u;g&&G.current!==g.name?(G.current=g.name,J(Wt(g,(o=pe.current)!=null?o:[])),(u=g.routes)!=null&&u.length?je(0):je(-1)):!g&&G.current&&(G.current=void 0,J(Dn),je(-1))},[g,J]),l.useEffect(()=>{if(!(ee!=null&&ee.length)||!g)return;const o=ie(),u=o.defaultRoute.variants.some(k=>k.variant.modelId&&!k.variant.modelId.includes("/")&&!k.variant.isAutoModel),j=o.routes.some(k=>k.route.variants.some($=>$.variant.modelId&&!$.variant.modelId.includes("/")&&!$.variant.isAutoModel));(u||j)&&J(Wt(g,ee))},[ee,g,ie,J]);const he=l.useRef(!1);l.useEffect(()=>{var j,k;if(he.current)return;let o=(j=a.state)==null?void 0:j.preset;const u=!!R.current;if(!o){const $=new URLSearchParams(window.location.search),L=$.get("duplicateState");if(L){try{const q=sessionStorage.getItem(L);q&&(o=JSON.parse(q).preset,sessionStorage.removeItem(L))}catch(q){}$.delete("duplicateState");const O=$.toString().length>0?`${a.pathname}?${$.toString()}`:a.pathname;s(O,{replace:!0,state:{}})}}o&&!i&&(he.current=!0,u||J(o),o.routes&&o.routes.length>0&&je(0),(k=a.state)!=null&&k.preset&&s(a.pathname,{replace:!0,state:{}}))},[a.state,i,J,s,a.pathname]),l.useEffect(()=>{var u;(u=a.state)!=null&&u.justCreated&&(I(!0),s(a.pathname,{replace:!0,state:{}}))},[a.state,s,a.pathname]);const oe=l.useCallback((o,u)=>{var $;const j=u==null?void 0:u.details,k=[];if(j&&Array.isArray(j))for(const L of j){const O=L;($=O==null?void 0:O.fieldViolations)!=null&&$.length&&k.push(O)}if(k.length===0){nt(`${o}: ${u.message}`);return}nt(e.jsxs(e.Fragment,{children:[e.jsx(f,{variant:"h6",children:o}),e.jsx(f,{variant:"body2",children:u.message}),k.map((L,O)=>{var q;return e.jsxs(p,{component:"div",sx:{mt:1},children:[L.message&&e.jsx(Mn,{error:!0,children:L.message}),(q=L.fieldViolations)==null?void 0:q.map((ue,ge)=>e.jsxs(Mn,{sx:{color:"text.primary"},children:["â¢",ue.field,": ",ue.description]},`violation_${ue.field}_${ge}`))]},`detail-${O}`)})]}),{id:"router-error",duration:1e4})},[]),Re=l.useCallback(o=>{var j;St("Router created successfully"),K.current=!0;const u=(j=o.name)==null?void 0:j.replace("routers/","");u&&n&&s(`/workspaces/${n}/routers/${u}`,{replace:!0,state:{justCreated:!0}})},[s,n]),Oe=l.useCallback(o=>{var L;St("Router updated successfully");const u=ie(),j=Wt(o,(L=pe.current)!=null?L:[]),k=(O,q)=>{const ue=new Map(q.map(ge=>[ge.variant.variantId,ge.variant.textGenerationConfig]));return O.map(ge=>{var le;return{...ge,variant:{...ge.variant,textGenerationConfig:(le=ue.get(ge.variant.variantId))!=null?le:ge.variant.textGenerationConfig}}})};j.defaults.textGenerationConfig=u.defaults.textGenerationConfig,j.defaultRoute.variants=k(j.defaultRoute.variants,u.defaultRoute.variants);const $=new Map(j.routes.map(O=>[O.route.routeId,O]));j.routes=u.routes.map(O=>{const q=$.get(O.route.routeId);return q?{...q,route:{...q.route,variants:k(q.route.variants,O.route.variants)}}:O}),J(j),Je(!1)},[J,ie]),{mutate:Qe,isLoading:Qt}=$r(n!=null?n:"",Re,o=>{var u;Be(Ve.ROUTERS_SAVE_ERROR,Fe.Routers,{error:(u=o==null?void 0:o.message)!=null?u:"Unknown error",action:"Create"}),oe("Failed to create router",o)}),{mutate:gt,isLoading:Mt}=zr(n!=null?n:"",Oe,o=>{var u;Be(Ve.ROUTERS_SAVE_ERROR,Fe.Routers,{error:(u=o==null?void 0:o.message)!=null?u:"Unknown error",action:"Edit"}),oe("Failed to save router",o)}),Et=Qt||Mt,At=l.useCallback(o=>{var k,$;const u=o.routes.findIndex(L=>rn(L.condition.celExpression)!==!0);if(u!==-1){ye(`routes.${u}.condition.celExpression`,{message:rn(o.routes[u].condition.celExpression)}),je(u),x("configuration"),Xe(L=>L+1);return}const j=i?($=(k=g==null?void 0:g.name)==null?void 0:k.replace("routers/",""))!=null?$:"":rr(o.displayName);Be(Ve.ROUTERS_CLICKED_SAVE,Fe.Routers,{routerId:j,action:i?"Edit":"Create",fromPreset:he.current}),i&&(g!=null&&g.name)?gt({router:An(o,g.name,ee!=null?ee:[])}):Qe(An(o,void 0,ee!=null?ee:[]))},[i,g==null?void 0:g.name,Qe,gt,ye,ee]),Zt=l.useCallback(()=>{Je(!0),ae(At,()=>{x("configuration"),Xe(o=>o+1)})()},[ae,At]),en=l.useCallback(o=>{Ye(o),B===o?o<me.length-1?je(o):je(-1):B>o&&je(B-1)},[Ye,B,me.length]),Dt=e.jsx(p,{component:"div",sx:{mt:"0",minHeight:"100%",containerType:"inline-size",containerName:"routes-section",backgroundColor:`color-mix(in srgb, ${t.palette.background.default} 50%, transparent)`,borderTop:o=>`solid 1px ${o.palette.divider}`},children:e.jsxs(p,{component:"div",sx:o=>
2({display:"flex",flexDirection:"row",alignItems:"flex-start",gap:4,maxWidth:Vt.page,px:"1.5rem",pt:{xs:2,sm:3},pb:"1.5rem",mx:"auto",[o.breakpoints.down("md")]:{flexDirection:"column",gap:3,".routes-sidebar":{position:"relative",top:0,marginBottom:"2rem"}},"@container routes-section (max-width: 720px)":{flexDirection:"column",gap:3,".routes-sidebar":{position:"relative",top:0,marginBottom:"2rem"}}}),children:[e.jsx(ds,{selectedRouteIndex:B,defaultRoute:Ie,watchedRoutes:be,routeFields:me,handleRouteClick:W,handleAddRoute:xe,onDragEnd:Y}),e.jsxs(C,{direction:"column",spacing:1,sx:{flex:1,minWidth:0,width:"100%"},children:[e.jsxs(C,{direction:"row",sx:{alignItems:"center",justifyContent:"space-between",minHeight:"2rem"},children:[e.jsx(f,{variant:"body1",sx:{fontWeight:600},children:B===-1?"Edit default route":"Edit conditional route"}),B!==-1&&e.jsx(se,{title:"Delete route",children:e.jsx(Te,{"aria-label":"Delete route",size:"small",onClick:()=>en(B),children:e.jsx(D,{icon:A.faTrash,style:{height:"1rem",width:"1rem"}})})})]}),e.jsx(p,{component:"div",sx:{"@keyframes routeEditorFadeIn":{from:{opacity:0,transform:"translateY(6px)"},to:{opacity:1,transform:"translateY(0)"}},animation:"routeEditorFadeIn 0.05s ease-out"},children:e.jsxs(p,{component:"div",sx:{display:"flex",flexDirection:"column"},children:[e.jsx(p,{component:"div",sx:{pb:1},children:e.jsx(ke,{name:B===-1?"defaultRoute.routeId":`routes.${B}.route.routeId`,control:te,rules:{validate:o=>!o||o.trim().length===0?"ID cannot be empty":/^[a-z0-9_-]+$/.test(o)?o.length>61?"ID must be 61 characters or fewer":!0:"Only lowercase letters, digits, underscores, and hyphens are allowed"},render:({field:o,fieldState:{error:u}})=>e.jsx($e,{sx:{mt:"1rem",width:"100%","& .MuiFormLabel-root .MuiTypography-root":{fontWeight:600,color:t.palette.text.primary}},label:"Route ID",infoHelperProps:{tooltip:"Unique identifier used to reference route. Must only contain lowercase letters, numbers, hyphens, or underscores."},children:e.jsx(Ce,{...o,onChange:j=>{const k=j.target.value.toLowerCase().replace(/[^a-z0-9_-]/g,"").slice(0,61);o.onChange(k)},variant:"outlined",className:"inworld-text-field",size:"small",placeholder:"Route ID",slotProps:{htmlInput:{maxLength:61}},fullWidth:!0,error:!!u,helperText:u!=null&&u.message?e.jsx(xn,{errors:[u.message]}):null})})},B===-1?"default-route":(bt=me[B])==null?void 0:bt.id)}),B!==-1&&e.jsxs(e.Fragment,{children:[e.jsx(C,{direction:"column",spacing:0,sx:{mt:"1rem",mb:"0.5rem"},children:e.jsx(f,{variant:"h6",sx:{mb:0},children:"Conditions"})}),e.jsx(ke,{name:`routes.${B}.condition.celExpression`,control:te,rules:{validate:rn},render:({field:{onChange:o,value:u},fieldState:{error:j}})=>{var k;return e.jsx(zo,{value:u,onChange:o,error:j,handleEditorWillMount:ls},`cel-editor-${(k=me[B])==null?void 0:k.id}`)}},`condition-${(vt=me[B])==null?void 0:vt.id}`)]}),e.jsx(f,{variant:"h6",sx:{mt:"2rem"},children:"Variants"}),e.jsx(f,{variant:"body2",sx:{color:"text.secondary",mb:"0.5rem"},children:"Variants split traffic within this route. Use one variant for simple routing, or multiple to run an A/B test."}),e.jsx(C,{children:(B===-1?Ie.variants:((d=be[B])==null?void 0:d.route.variants)||[]).map((o,u,j)=>{var q;const k=Ot(j.length),$=j.reduce((ue,ge)=>{var le;return ue+((le=ge.weight)!=null?le:0)},0),L=j.some((ue,ge)=>{var le;return((le=ue.weight)!=null?le:0)!==k[ge]}),O=$!==100;return e.jsx(as,{variantIndex:u,basePath:B===-1?`defaultRoute.variants.${u}`:`routes.${B}.route.variants.${u}`,onDelete:()=>re(u),canDelete:j.length>1,variantLetter:ut(u),siblingVariants:j.map((ue,ge)=>{var le;return{letter:ut(ge),weight:(le=ue.weight)!=null?le:0,isCurrent:ge===u}}),llmModels:ee!=null?ee:[],isDistributionCustom:L,isDistributionError:O,onResetDistribution:Se,stickyTopOffset:"0px"},`variant-${B===-1?"default":(q=me[B])==null?void 0:q.id}-${u}`)})}),e.jsx(fe,{intent:"secondary","aria-label":"Add variant",startIcon:e.jsx(D,{icon:A.faPlus}),onClick:P,sx:{maxWidth:"10rem",width:"fit-content"},children:"Add variant"})]})},B)]})]})}),tn=e.jsx(e.Fragment,{children:h?e.jsxs(e.Fragment,{children:[e.jsxs(p,{component:"div",sx:{maxWidth:Vt.page,mx:"auto",px:"1.5rem",pt:"1.5rem"},children:[e.jsx(C,{direction:"row",sx:{alignItems:"center",justifyContent:"space-between"},children:e.jsx(f,{variant:"h1",component:"h2",sx:{mb:2,fontFamily:Jt.display,fontWeight:400},children:i?(S=g==null?void 0:g.displayName)!=null?S:"":"Create router"})}),e.jsx(C,{direction:"row",spacing:2,sx:{alignItems:"center"},children:e.jsxs(Jr,{value:m,onChange:(o,u)=>x(u),color:"secondary","aria-label":"Router tabs",sx:{height:"2.5rem",minHeight:"unset","& .MuiTabs-flexContainer":{gap:"0.5rem"},"& .MuiTab-root":{fontSize:_.md,borderRadius:X.md,fontWeight:500,px:"0.25rem",minWidth:"unset",minHeight:"unset",height:"2.5rem",color:"text.secondary","&.Mu
2i-selected":{color:"text.primary"}}},children:[e.jsx(En,{disableRipple:!0,value:"configuration",label:"Configuration",id:"router-tab-configuration","aria-controls":"router-tabpanel-configuration"}),e.jsx(En,{disableRipple:!0,value:"metrics",label:"Metrics",id:"router-tab-metrics","aria-controls":"router-tabpanel-metrics"})]})})]}),e.jsxs(p,{component:"div",role:"tabpanel",id:"router-tabpanel-configuration","aria-labelledby":"router-tab-configuration",hidden:m!=="configuration",children:[e.jsx(Bn,{errors:we,watchedRoutes:be,defaultRoute:Ie,hasSubmitAttempted:Ne,validationPanelRef:b,control:te,isEditMode:i,setValue:Me}),Dt]}),e.jsx(p,{component:"div",role:"tabpanel",id:"router-tabpanel-metrics","aria-labelledby":"router-tab-metrics",hidden:m!=="metrics",sx:o=>({minHeight:"100%",backgroundColor:o.palette.background.paper,borderTop:"1px solid",borderColor:"divider"}),children:m==="metrics"&&e.jsx(p,{component:"div",sx:{p:"1.5rem",pt:"0.5rem",maxWidth:Vt.page,mx:"auto"},children:r?e.jsx(Yo,{routerId:r,routes:Q}):e.jsx(kr,{icon:null,density:"compact",title:"No router found"})})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Bn,{errors:we,watchedRoutes:be,defaultRoute:Ie,hasSubmitAttempted:Ne,validationPanelRef:b,control:te,isEditMode:i,setValue:Me}),Dt]})});return e.jsx(Tr,{disablePadding:!0,customWrapperSX:{height:"100%",backgroundColor:o=>o.palette.background.paper,px:0,pb:0,pt:0},EnhancedPageHeaderProps:{noColumnStack:!0,breadcrumbs:[{label:"Routers",href:`/workspaces/${n}/routers`},{label:i?(w=g==null?void 0:g.displayName)!=null?w:"":"Create router"}],sx:{minHeight:"4.5rem",alignItems:"center","& > div":{alignItems:"center",rowGap:0},"& h1":{maxWidth:{xs:"10rem",sm:"20rem",md:"none"}},[t.breakpoints.down("sm")]:{"& .page-header-column > div > div:first-of-type > div:first-of-type":{flexShrink:0}}},primaryAction:e.jsxs(e.Fragment,{children:[e.jsx(pn,{size:"xs",open:c,onClose:()=>v(!1),title:"Delete router",controlled:!0,headerIcon:e.jsx(p,{component:"span",sx:{display:"inline-flex",color:"warning.main"},children:e.jsx(D,{icon:A.faTriangleExclamation})}),primary:{label:"Delete",loading:ne,onClick:()=>{g!=null&&g.name&&(Be(Ve.ROUTERS_CLICKED_DELETE,Fe.Routers,{routerId:g.name.replace("routers/","")}),z(g.name)),v(!1)}},secondary:{label:"Cancel",onClick:()=>v(!1)},children:e.jsx(f,{component:"pre",sx:{py:2,whiteSpace:"pre-wrap"},children:`You are about to delete the "${(g==null?void 0:g.displayName)||r}" router. This action cannot be undone. Are you sure you want to proceed?`})}),e.jsx(pn,{size:"xs",open:y,onClose:()=>I(!1),title:"Your router is ready to test",controlled:!0,primary:{label:"Test in Playground",onClick:()=>{var o,u;Be(Ve.ROUTERS_CLICKED_TEST_IN_PLAYGROUND,Fe.Routers,{routerId:(u=(o=g==null?void 0:g.name)==null?void 0:o.replace("routers/",""))!=null?u:""}),I(!1),s(`/workspaces/${n}/llm-playground`,{state:{routerName:g==null?void 0:g.name,routerDisplayName:g==null?void 0:g.displayName}})}},secondary:{label:"I'll do it later",onClick:()=>{var o,u;Be(Ve.ROUTERS_CLICKED_ILL_DO_IT_LATER,Fe.Routers,{routerId:(u=(o=g==null?void 0:g.name)==null?void 0:o.replace("routers/",""))!=null?u:""}),I(!1)}},children:e.jsx(f,{component:"p",sx:{py:2},children:`Try out your "${(g==null?void 0:g.displayName)||r}" router in the LLM Playground to see how it routes requests across your configured models.`})}),e.jsxs(C,{ref:H,direction:"row",spacing:1,sx:{alignItems:"center"},children:[i&&(g==null?void 0:g.name)&&e.jsxs(e.Fragment,{children:[e.jsx(Te,{"aria-label":"More options",onClick:o=>V(o.currentTarget),size:"small",children:e.jsx(D,{icon:A.faEllipsisVertical})}),e.jsxs(kn,{anchorEl:E,open:!!E,className:"inworld-text-field-menu",onClose:()=>V(null),children:[T&&e.jsxs(ve,{"aria-label":"Integrate",onClick:()=>{var o;V(null),(o=M.current)==null||o.click()},children:[e.jsx(rt,{children:e.jsx(D,{icon:A.faCode})}),e.jsx(He,{children:"Integrate"})]}),T&&e.jsxs(ve,{"aria-label":"Test in Playground",onClick:()=>{var o,u;V(null),Be(Ve.ROUTERS_CLICKED_TEST_IN_PLAYGROUND,Fe.Routers,{routerId:(u=(o=g==null?void 0:g.name)==null?void 0:o.replace("routers/",""))!=null?u:""}
2),s(`/workspaces/${n}/llm-playground`,{state:{routerName:g==null?void 0:g.name,routerDisplayName:g==null?void 0:g.displayName}})},children:[e.jsx(rt,{children:e.jsx(D,{icon:A.faFlask})}),e.jsx(He,{children:"Test in Playground"})]}),e.jsxs(ve,{"aria-label":"Duplicate router",onClick:()=>{var o,u,j;if(V(null),g){const k=(u=(o=g.name)==null?void 0:o.replace("routers/",""))!=null?u:"";Be(Ve.ROUTERS_CLICKED_DUPLICATE,Fe.Routers,{routerId:k});const $=Wt(g,(j=pe.current)!=null?j:[]),L=`/workspaces/${n}/routers/new`,O=`duplicate_router_${Date.now()}`;sessionStorage.setItem(O,JSON.stringify({preset:{...$,displayName:`Copy of ${$.displayName}`,name:""}})),window.open(`${L}?duplicateState=${O}`,"_blank")}},children:[e.jsx(D,{icon:A.faCopy}),e.jsx(He,{children:"Duplicate router"})]}),e.jsxs(ve,{"aria-label":"Router docs",component:"a",href:`${Hn}/docs/router/introduction`,target:"_blank",rel:"noopener noreferrer",onClick:()=>V(null),children:[e.jsx(rt,{children:e.jsx(D,{icon:A.faBook})}),e.jsx(He,{children:"Router docs"})]}),e.jsxs(ve,{"aria-label":"Delete router",onClick:()=>{V(null),v(!0)},disabled:Et||ne,children:[e.jsx(rt,{children:e.jsx(D,{icon:A.faTrash})}),e.jsx(He,{children:"Delete router"})]})]})]}),i&&(g==null?void 0:g.name)&&e.jsx(p,{component:"div",sx:T?{width:0,overflow:"hidden",opacity:0}:void 0,children:e.jsx(Gr,{routerName:g.name,defaults:g.defaults,defaultRoute:g.defaultRoute,routes:g.routes,showLabel:!0,buttonProps:{ref:M,intent:"secondary"}})}),i&&(g==null?void 0:g.name)&&!T&&e.jsx(fe,{intent:"secondary","aria-label":"Test in Playground",startIcon:e.jsx(D,{icon:A.faFlask}),onClick:()=>{var o,u;Be(Ve.ROUTERS_CLICKED_TEST_IN_PLAYGROUND,Fe.Routers,{routerId:(u=(o=g.name)==null?void 0:o.replace("routers/",""))!=null?u:""}),s(`/workspaces/${n}/llm-playground`,{state:{routerName:g.name,routerDisplayName:g.displayName}})},children:"Test in Playground"}),!(i&&!g)&&e.jsx(fe,{"aria-label":i?"Save router":"Create router",disabled:Et,onClick:Zt,children:"Save"})]})]})},children:ce?e.jsx(p,{component:"div",sx:{p:3},children:e.jsx(f,{children:"Loading router..."})}):de?e.jsx(Po,{error:de}):e.jsxs(Rr,{...F,children:[e.jsx(Lr,{isDirtyOverride:()=>_e&&!K.current}),tn]})})};export{Ys as RouterDetailsPage};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.