import{X as k,r as h,a4 as $e,j as e,O as v,ai as S,dc as je,as as N,bE as Pt,N as b,dd as Et,am as ae,de as ve,p as B,ar as U,R as P,d0 as ie,bm as he,a6 as xe,df as lt,D as Fe,dg as rt,C as W,dh as R,a3 as ee,di as ct,dj as De,b5 as Z,dk as fe,T as se,d2 as ge,c7 as Dt,bL as Q,q as le,s as ye,t as $,c_ as ce,dl as dt,V as M,dm as Vt,bK as de,dn as ut,bx as Ge,dp as _e,e as $t,I as pt,dq as Ft,dr as Ot,ds as Rt,cd as gt,aM as Nt,F as qt,aL as mt,b1 as ht,dt as Bt,aw as q,du as zt,aO as Wt,aP as Ae,ao as Oe,ag as Y,cx as Kt,aR as xt,aS as Ut,aj as Ht,aN as ft,aT as Gt,dv as we,ax as Se,c2 as bt,dw as be,dx as re,bY as me,da as Qt,dy as Jt,dz as Re,b3 as Yt,l as J,bR as Me,Q as Xt,dA as Zt,a2 as V,dB as es,bS as ts,c3 as ss,dC as as,at as jt,au as ns,aq as os,w as Qe,dD as is,dE as ls,dF as rs,ak as Je,dG as cs,dH as ds,dI as us,dJ as ps,f as Ye,dK as gs,dL as ms,a7 as hs,br as xs,a5 as fs,J as bs,dM as js,dN as vs,b6 as Ie,ce as ys,dO as _s,bM as ws,aK as Ss,bt as Ts,bN as Cs,bP as ks,dP as As,dQ as Ms,dR as Is,dS as Ls,be as Ps,bd as Es}from"./index-BLPf7Sv2.js";import{A as Ds}from"./index-DbFmShiq.js";import{C as Vs}from"./ChatPlaceholder-CbJiuHNx.js";import{T as $s}from"./TryAgent-BGCyvyP3.js";import{u as Fs,a as Os}from"./use-get-agent-versions-OXHyhu4_.js";import{a as Rs}from"./use-full-view-BmMw2SH8.js";import{i as Ns}from"./json-BFYCgnm2.js";import{a as D}from"./translations-8IvuaW6e.js";import{b as vt,h as Te,C as qs,A as Bs,t as pe,c as Xe,d as Ve,e as Ze,f as zs}from"./AddAgentsModal-Br8lVdit.js";import{G as Ws,u as Ks}from"./GenerateWithAI-CqPdBJl0.js";import{V as Us}from"./VersionSelectorBox-C3N1pEqJ.js";const O=({cardTitle:t,popoverTitle:s,popoverContent:a,popoverPosition:n,ariaLabel:l="right",showDocumentation:i=!0,sx:u,id:m=`tooltip-${Math.random().toString(36).substr(2,9)}`})=>{const o=k("agents",D),[d,r]=h.useState(!1),g=h.useRef(null),c=!!a,p=()=>{r(!1),g.current?.focus()},w=$e(),y=()=>{r(!0),setTimeout(()=>{const _=document.getElementById(`tooltip-${m}`);_&&_.focus()},100)},j=_=>{_.key==="Escape"&&p()};return e.jsxs(v,{ref:g,alignItems:"center",flexWrap:"nowrap",children:[e.jsx(S,{autoFocus:!0,appearance:"body2",mr:3,id:`card-title-${m}`,children:t}),c&&e.jsx(je,{sx:u,position:n,clickable:!0,isOpen:d,tabIndex:-1,role:"tooltip","aria-expanded":d,setIsOpen:r,globalCloseEvents:{clickOutsideAnchor:!0,escape:!0,resize:!0,scroll:!0},text:e.jsxs(b,{role:"dialog","aria-modal":"false","aria-labelledby":`popover-title-${m}`,tabIndex:-1,children:[!!s&&e.jsxs(v,{mb:1,justifyContent:"space-between",alignItems:"baseline",flexWrap:"nowrap",gap:!0,children:[e.jsx(b,{children:e.jsx(S,{"aria-hidden":!0,id:`popover-title-${m}`,"aria-label":s,appearance:"body2",weight:"medium",children:s})}),e.jsx(b,{children:e.jsx(Et,{color:"inverse.contrastText",onClick:p,"aria-label":o.global.closePopover,tabIndex:0})})]}),e.jsx(S,{appearance:"microtext1",colorScheme:"inverse.contrastText",align:"justify",children:a}),i&&e.jsx(v,{mt:3,justifyContent:"end",children:e.jsx(ae,{size:"sm",as:"a",colorScheme:"light.500",href:`${w}/${vt}`,target:"_blank",children:o.agents.viewDocumentationButton})})]}),children:e.jsx(N,{type:"button",sx:{cursor:"pointer",p:0},bg:"light.500",appearance:"circle",size:"xs","aria-label":l||t,"aria-haspopup":"dialog","aria-controls":`tooltip-${m}`,onClick:y,onKeyDown:j,"aria-expanded":d,children:e.jsx(Pt,{})})})]})},Hs=B(U)` position: relative; padding: 8px; `,Gs=()=>{const t=k("agents",D);return e.jsx(Hs,{children:e.jsxs(v,{justifyContent:"space-between",children:[e.jsx(O,{cardTitle:t.agents.advanced,popoverTitle:t.agents.advanced,popoverContent:t.agents.advancedPopover,ariaLabel:t.agents.advancedSettingsDetails}),e.jsx(N,{type:"button",title:t.agents.advanced,"data-test-hint":"buttonConfigAdvanced","aria-label":t.agents.advanced,onClick:()=>Te("advanced-settings"),appearance:"square",children:e.jsx(ve,{})})]})})},Le=({cardTitle:t,popoverContent:s,options:a,value:n,onChange:l,ariaLabel:i,children:u,disabled:m=!1,disabledTooltip:o,showDocumentation:d=!1})=>{const[r,g]=h.useState(!1),c=h.useMemo(()=>a.find(j=>j.value===n),[a,n]),p=()=>{g(!1)},w=()=>{g(!0)},y=async(j,_)=>{await l(j,_),p()};return e.jsxs(U,{sx:{border:"none",padding:"0.5rem"},children:[e.jsxs(P,{justifyContent:"space-between",gap:"4px",style:{position:"static"},children:[e.jsx(v,{sx:{maxWidth:"60%"},children:e.jsx(O,{cardTitle:t,popoverContent:s,showDocumentation:d})}),e.jsxs(P,{alignItems:"center",justifyContent:"end",style:{position:"static",flex:1},children:[e.jsx(ie,{disabled:!m,content:o,children:e.jsx(P,{children:e.jsx(he,{appearance:"contained",colorScheme:"light",size:"sm",disabled:m,onClick:w,"aria-label":i,"aria-expanded":r,sx:{display:"grid"},children:e.jsxs(P,{style:{overflow:"hidden"},children:[e.jsx(b,{sx:{overflow:"hidden",textOverflow:"ellipsis"},pr:3,children:e.jsx(S,{nowrapEllipsis:!0,appearance:"microtext1",weight:"medium",children:c?.title||String(n)})}),e.jsx(xe,{icon:"Select"})]})})})}),e.jsx(lt,{visible:r,onClose:p,sx:{position:"absolute",top:"100%",left:"0",background:"light.300",border:"1px solid light.600",zIndex:999},children:a.map((j,_)=>e.jsxs("div",{children:[e.jsx(Qs,{option:j,isSelected:j.value===n,onSelect:y}),_{a(t.value,t)};return e.jsx(rt,{sx:{cursor:"pointer"},onClick:n,children:e.jsxs(W,{children:[e.jsxs(P,{alignItems:"center",gap:"4px",children:[e.jsx(P,{w:18,children:s&&e.jsx(xe,{icon:"Check",size:"sm"})}),e.jsx(S,{nowrapEllipsis:!0,weight:"medium",children:t.title}),t.icon&&e.jsx(xe,{...t.icon})]}),t.description&&e.jsx(S,{nowrapEllipsis:!0,colorScheme:"light.700",pl:"18px",style:{whiteSpace:"pre-line"},children:t.description})]})})}const Js=()=>{const t=k("agents",ea),s=R(),a="structured_output",[n,l]=h.useState(!1),[i,u]=h.useState(!1);h.useEffect(()=>{l(!!s.values[a])},[!!s.values[a]]);const m=c=>{s.setFieldValue(a,c?et:null),l(!n)},{model_id:o}=s.values,[d,r]=ee.getModel.useStatefulQuery({modelId:o||""},{enabled:!!o});h.useEffect(()=>{if(d){const c=!!d?.model_configuration?.usage_params?.enabled_structured_outputs;u(c),s.values.enabled_structured_outputs!==c&&s.setFieldValue("enabled_structured_outputs",c),!c&&s.values[a]!==null&&s.setFieldValue(a,null)}},[d]);const g=n;return e.jsx(ct,{loading:r,children:e.jsx(b,{w:12,children:e.jsxs(U,{sx:{border:"none",padding:"0.5rem"},children:[e.jsxs(De,{as:v,justifyContent:"space-between",children:[e.jsxs(v,{sx:{gap:"8px"},children:[e.jsx(O,{cardTitle:t.agents.cardTitle,popoverTitle:t.agents.popoverTitle,popoverContent:t.agents.popoverContent,popoverPosition:"bottom-start"}),e.jsx(Z,{palette:"cyan",appearance:"square",children:"Beta"})]}),e.jsx(fe,{checked:g,onChange:({target:c})=>m(c.checked),"data-test-hint":"buttonSwitch","aria-label":t.global.toggle,disabled:!i}),!i&&e.jsx(P,{mt:3,children:e.jsx(se,{color:"light.700",children:t.agents.disabledText})})]}),e.jsxs(ge,{sx:{visibility:g?"visible":"hidden",opacity:g?1:0,maxHeight:g?"500px":"0px",transition:"opacity 0.5s ease, max-height 0.3s ease-in-out, visibility 0.3s"},children:[e.jsx(Dt,{size:"sm",appearance:"flat",alignment:"start","aria-label":t.agents.examples,options:[{text:t.agents.mathStepByStep,onClick(){s.setFieldValue(a,et)}},{text:t.agents.userProfileParsing,onClick(){s.setFieldValue(a,Ys)}},{text:t.agents.orderParsing,onClick(){s.setFieldValue(a,Xs)}},{text:t.agents.projectParsing,onClick(){s.setFieldValue(a,Zs)}}],children:t.agents.examples}),e.jsx(Q,{fieldType:"code-editor",name:`${a}`,language:"json",required:!0})]})]})})})},et=`{ "name": "example_math_step_by_step", "description": "Solves a math equation step by step", "schema": { "type": "object", "properties": { "steps": { "type": "array", "items": { "type": "object", "properties": { "explanation": { "type": "string" }, "output": { "type": "string" } }, "required": ["explanation", "output"], "additionalProperties": false } }, "final_answer": { "type": "string" } }, "required": ["steps", "final_answer"], "additionalProperties": false } }`,Ys=` { "title": "UserProfile", "type": "object", "properties": { "id": { "type": "integer", "title": "User ID" }, "name": { "type": "string", "title": "User Name" }, "email": { "type": "string", "title": "Email Address", "format": "email" }, "phone": { "type": "string", "title": "Phone Number" }, "age": { "type": "integer", "title": "Age", "minimum": 0 } }, "required": [ "id", "name", "email", "phone", "age" ] } `,Xs=`{ "title": "Order", "type": "object", "properties": { "order_id": { "type": "integer", "title": "Order ID" }, "customer": { "$ref": "#/definitions/Customer" }, "items": { "type": "array", "items": { "$ref": "#/definitions/Item" } } }, "required": ["order_id", "customer", "items"], "definitions": { "Customer": { "type": "object", "properties": { "id": { "type": "integer", "title": "Customer ID" }, "name": { "type": "string", "title": "Customer Name" } }, "required": ["id", "name"] }, "Item": { "type": "object", "properties": { "item_id": { "type": "integer", "title": "Item ID" }, "description": { "type": "string", "title": "Item Description" }, "quantity": { "type": "integer", "title": "Quantity", "minimum": 1 } }, "required": ["item_id", "description", "quantity"] } } } `,Zs=` { "title": "Project", "type": "object", "properties": { "project_id": { "type": "integer", "title": "Project ID" }, "name": { "type": "string", "title": "Project Name" }, "owner": { "$ref": "#/definitions/User" }, "tasks": { "type": "array", "items": { "$ref": "#/definitions/Task" } }, "status": { "type": "string", "title": "Project Status", "enum": ["pending", "in_progress", "completed"] }, "deadline": { "type": "string", "title": "Deadline", "format": "date-time" } }, "required": ["project_id", "name", "owner", "tasks", "status"], "definitions": { "User": { "type": "object", "properties": { "user_id": { "type": "integer", "title": "User ID" }, "username": { "type": "string", "title": "Username" }, "email": { "type": "string", "title": "Email Address", "format": "email" } }, "required": ["user_id", "username", "email"] }, "Task": { "type": "object", "properties": { "task_id": { "type": "integer", "title": "Task ID" }, "description": { "type": "string", "title": "Task Description" }, "completed": { "type": "boolean", "title": "Is Completed" } }, "required": ["task_id", "description"] } } } `,ea={en:{cardTitle:"Structure output",popoverTitle:"Structured Outputs",popoverContent:"Structured Outputs ensures that AI responses follow a specific and valid JSON Schema format. This prevents errors, improves reliability, and simplifies the use of structured data in applications. When enabled, all AI responses adhere to the format defined by the chosen schema. For more information, refer to the documentation.",examples:"Examples",mathStepByStep:"Math Step-by-Step",userProfileParsing:"User Profile Parsing",enterCode:"Enter your Python code below and click 'Generate' to convert it into a JSON Schema",generate:"Generate",orderParsing:"Order Parsing",projectParsing:"Project Parsing",disabledText:'The "Output Structure" feature is not available in the current default LLM. Modify the default LLM to enable this feature.'},pt:{cardTitle:"Estruturar saída",popoverTitle:"Saídas Estruturadas",popoverContent:"As Saídas Estruturadas garantem que as respostas da IA sigam um formato específico e válido de Esquema JSON. Isso previne erros, melhora a confiabilidade e simplifica o uso de dados estruturados em aplicações. Quando ativado, todas as respostas da IA aderem ao formato definido pelo esquema escolhido. Para mais informações, consulte a documentação.",examples:"Exemplos",mathStepByStep:"Math Step-by-Step",userProfileParsing:"User Profile Parsing",enterCode:"Insira seu código Python abaixo e clique em 'Gerar' para convertê-lo em um JSON Schema",generate:"Gerar",orderParsing:"Order Parsing",projectParsing:"Project Parsing",disabledText:'O recurso "Estrutura de saída" não está disponível no LLM padrão atual. Modifique o LLM padrão para habilitar esse recurso.'}},ta=()=>{const t=R(),s=le(yt),a=le(D),n={buffer:{value:"buffer",title:s.bufferTitle,description:s.bufferDescription},summary:{value:"summary",title:s.summaryTitle,description:s.summaryDescription},vector:{value:"vector",title:s.vectorTitle,description:s.vectorDescription}},l={simple:{value:"simple",title:s.plannerTypeSimpleTitle,description:s.plannerTypeSimpleDescription,icon:{icon:"Lightning",group:"fill"}},tool_oriented:{value:"tool_oriented",title:s.plannerTypeToolOrientedTitle,description:s.plannerTypeToolOrientedDescription,icon:{icon:"BorderRadius",group:"outline"}}},i={autonomous:{value:"autonomous",title:s.autonomousModelTitle,description:s.autonomousModelDescription},plan_approval:{value:"plan_approval",title:s.planApprovalTitle,description:s.planApprovalDescription},plan_and_critical_approval:{value:"plan_and_critical_approval",title:s.planAndCriticalToolsApprovalTitle,description:s.planAndCriticalToolsApprovalDescription}},u=o=>{t.setFieldValue("planner_type",o),o==="simple"?(t.setFieldValue("mode","autonomous"),t.setFieldValue("max_llm_interactions",50)):t.setFieldValue("max_llm_interactions",void 0)},m=t.values.planner_type==="simple";return e.jsxs(e.Fragment,{children:[e.jsxs(P,{justifyContent:"space-between",mb:8,children:[e.jsx(S,{children:s.advancedSettings}),e.jsx(ye,{icon:"Times",onClick:()=>Te("advanced-settings"),"aria-label":s.close})]}),e.jsxs(W,{gap:"12px",children:[e.jsx(U,{sx:{border:"none",padding:"0.5rem"},children:e.jsxs(P,{alignItems:"center",justifyContent:"space-between",children:[e.jsx(S,{"aria-hidden":"true",children:a.conversationalMode}),e.jsx(fe,{checked:t?.values?.type,onChange:({target:o})=>{t.setFieldValue("type",o.checked)},"aria-label":a.conversationalMode})]})}),e.jsx(Le,{value:t.values.planner_type,onChange:u,cardTitle:s.plannerTypeTitle,popoverContent:s.plannerTypeTitle,options:Object.values(l),ariaLabel:s.plannerTypeTitle,children:t.values.planner_type==="simple"&&e.jsx(sa,{})}),e.jsx(Le,{value:t.values.mode,onChange:o=>{t.setFieldValue("mode",o)},cardTitle:s.autonomyMode,popoverContent:s.autonomyModePopoverContent,options:Object.values(i),disabled:m,disabledTooltip:s.modeDisabled,ariaLabel:s.autonomyMode}),e.jsx(Le,{value:t.values.memory,onChange:o=>{t.setFieldValue("memory",o)},cardTitle:s.memory,popoverContent:s.memory,options:Object.values(n),ariaLabel:s.memory}),e.jsx(Js,{})]})]})},sa=()=>{const t=le(yt);return e.jsxs(P,{justifyContent:"space-between",mt:3,gap:"8px",children:[e.jsx(S,{colorScheme:"light.700",children:e.jsx(O,{cardTitle:t.maxInteractionsLabel,popoverContent:t.maxInteractionsPopover,popoverPosition:"top",showDocumentation:!1})}),e.jsx(P,{children:e.jsx(Q,{sxInput:{height:30},fieldType:"input",type:"number",name:"max_llm_interactions"})})]})},yt={en:{autonomyMode:"Autonomy Mode",advancedSettings:"Advanced Settings",planApprovalTitle:"Plan Approval Mode",planApprovalDescription:"The agent generates the plan, requests user approval for the complete plan, and upon approval, automatically executes all steps and tools.",autonomousModelTitle:"Autonomous Mode",autonomousModelDescription:"The agent automatically executes the entire plan and tools without user intervention.",modeDisabled:"It is not possible to change the autonomy mode because the Planner is set to Simple and it necessarily uses Autonomous Mode.",planAndCriticalToolsApprovalTitle:"Plan & Critical Tools Approval Mode",planAndCriticalToolsApprovalDescription:"User approves both the plan and critical tool usage before execution (POST, PUT and DELETE).",memory:"Chat Memory Management",bufferTitle:"Buffer Memory",bufferDescription:"Stores only the most recent interactions in the conversation.",vectorTitle:"Vectorized Memory",vectorDescription:"Uses vectors to retrieve relevant information from large conversational datasets.",summaryTitle:"Summary Memory",summaryDescription:"Keeps a condensed summary of previous conversations",plannerTypeTitle:"Planner type",plannerTypeSimpleTitle:"Simple - Fast - Smart",plannerTypeSimpleDescription:"This mode operates without planning. It automatically executes the necessary tools without reasoning or breaking down the user's request, making it faster and ideal for agents with a single tool.",plannerTypeToolOrientedTitle:"Tool-Oriented - Smarter",plannerTypeToolOrientedDescription:"The planner will specify which tools to use at each step, based on those available in the agent. It is suitable for tool-oriented scenarios.",maxInteractionsLabel:"Maximum Number of Interactions",maxInteractionsPopover:"Set the maximum number of cycles (loops) the agent can execute in React mode. Ideal values range from 5 to 50, balancing efficiency and depth of reasoning. Very low limits may interrupt complex flows; very high values may result in unnecessary executions.",close:"Close"},pt:{autonomyMode:"Modo de Autonomia",advancedSettings:"Configurações Avançadas",planApprovalTitle:"Modo de Aprovação do Plano",planApprovalDescription:"O agente gera o plano, solicita a aprovação do usuário para o plano completo e, após a aprovação, executa automaticamente todas as etapas e ferramentas.",autonomousModelTitle:"Modo Autônomo",autonomousModelDescription:"O agente executa automaticamente todo o plano e as ferramentas sem intervenção do usuário.",modeDisabled:"Não é possível alterar o modo de autonomia, pois o Planner está definido como Simple e ele utiliza obrigatoriamente o Modo Autônomo.",planAndCriticalToolsApprovalTitle:"Modo de Aprovação do Plano e das Ferramentas Críticas",planAndCriticalToolsApprovalDescription:"O usuário aprova o plano e o uso das ferramentas críticas antes da execução (POST, PUT e DELETE).",memory:"Gerenciamento de memória do chat",bufferTitle:"Memória em Buffer",bufferDescription:"Armazena apenas as interações mais recentes na conversa.",vectorTitle:"Memória Vetorizada",vectorDescription:"Utiliza vetores para recuperar informações relevantes de grandes conjuntos de dados conversacionais.",summaryTitle:"Memória de Sumário",summaryDescription:"Mantém um resumo condensado das conversas anteriores",plannerTypeTitle:"Tipo do planejamento",plannerTypeSimpleTitle:"Simples - Rápido - Inteligente",plannerTypeSimpleDescription:"Este modo opera sem planejamento. Executa automaticamente as ferramentas necessárias sem raciocinar ou dividir a solicitação do usuário, tornando-o mais rápido e ideal para agentes com uma única ferramenta.",plannerTypeToolOrientedTitle:"Orientado por Ferramentas - Mais Inteligente",plannerTypeToolOrientedDescription:"O planejador especificará quais ferramentas usar em cada etapa, com base nas disponíveis no agente. É adequado para cenários orientados ao uso de ferramentas.",maxInteractionsLabel:"Quantidade Máxima de Interação",maxInteractionsPopover:"Defina o número máximo de ciclos (loops) que o agente pode executar no modo ReAct. Valores ideais variam entre 5 e 50, equilibrando eficiência e profundidade do raciocínio. Limites muito baixos podem interromper fluxos complexos; valores muito altos podem gerar execuções desnecessárias.",close:"Fechar"}},ne={divider:{borderRight:"1px solid light.500"},formContent:{".image-preview":{borderRadius:"50%"},height:"100%"}},aa=B(b)` height: 100vh; width: 100vw; `,na=B.div` width: 100%; height: 100%; background: ${$.color.light[300]}; position: fixed; top: 0; left: 0; right: 0; `,oa=B.div` position: absolute; top: 0; width:100%; height: 56px; border-bottom: 1px solid ${$.color.light[600]}; background: ${$.color.light[400]}; z-index: 10; cursor: default; `,ia=B.div` position: fixed; width: 32vw; max-width: 410px; background: ${$.color.light[400]}; bottom: 30px; z-index: 1; box-shadow: 4px 4px 48px #000; border-radius: 4px; padding: 14px 18px; `;B.div` display: flex; height: 100%; overflow: 'auto'; form > div:first-of-type { height: 100%; } form > div > div:nth-of-type(3) { height: 100%; } textarea { position: relative; } `;const la=B.div` display: flex; gap: '8px'; align-items: center; background-color: ${$.color.warning[500]}; padding: 8px 16px; margin: 12px 12px 0px; z-index: 1; &, a { color: ${$.color.warning.contrastText}; } a { text-decoration: underline; } button:hover { background-color: ${$.color.light[600]}; } `,ra=({data:t,onChangeValue:s})=>{const a=k("agents",D),n=k("global",ce),[l,i]=h.useState(!0);return e.jsxs(aa,{bg:"inverse.contrastText","aria-expanded":l,children:[e.jsxs(v,{justifyContent:"space-between",bg:"light.300",sx:{height:"56px",borderBottom:"1px solid light.500"},alignItems:"center",px:7,children:[e.jsx(S,{as:"h2",appearance:"body2",children:a.agents.instructions}),e.jsx(N,{onClick:()=>{M.closeModal(),i(!1)},"aria-label":a.agents.instructionsModal,"aria-expanded":l,children:e.jsx(dt,{})})]}),e.jsx(Vt,{height:"calc(100vh - 136px)",resize:!1,onInput:s,name:"system_prompt",defaultValue:t,"aria-label":a.agents.instructions}),e.jsx(v,{bg:"light.300",sx:{height:"64px",borderTop:"1px solid light.500"},alignItems:"center",justifyContent:"end",pr:7,children:e.jsx(de,{appearance:"flat-outline",onClick:()=>M.closeModal(),children:n.global.close})})]})},ca={width:100,height:100},da=80,ua="01KCP9ND02DCMBAMHN0VPAMAYV",pa=B.div` max-width: 18vw; min-width: 120px; @media (max-width: 1640px) { max-width: 13vw; } `,ga=({isUpdate:t,versions:s,initialVersion:a,draftVersion:n,route:l,recommendedVersion:i})=>{const u=k("agents",D),m=k("form",ut),o=R(),d=o.values.id||"",[r,g]=h.useState(o.values.slug||Ge()),{getOption:c}=Fs(),[p,w]=h.useState(c(a,i===a)),[y,j]=ee.sendAgentMessage.useMutation(),{flagEnabled:_}=_e("ENABLE_VERSION_CONTENT_AI"),f=!!n.current,I=()=>{M.showCustomModal(e.jsx(ra,{data:o.values.system_prompt||"",onChangeValue:C=>o.setFieldValue("system_prompt",C.target.value)}),{size:"fit-content"})},A=async C=>{const K=(await y({agentId:ua,chatRequest:{user_prompt:C,streaming:!1,stackspot_knowledge:!1}}))?.message?.replace(/^```python\n|```$/g,"");o.setFieldValue("system_prompt",K)},x=C=>{C&&w(C),l.$go({version:C?.value},{mergeSearchParameters:!0})};return e.jsxs(e.Fragment,{children:[e.jsx(b,{children:e.jsx(v,{flexWrap:"nowrap",justifyContent:"space-between",children:t?e.jsxs(P,{w:"100%",justifyContent:"space-between",style:{marginBlock:5},children:[e.jsxs(P,{w:"50%",gap:"8px",children:[e.jsx(P,{children:o.values.avatar?e.jsx($t,{size:"sm",image:o.values.avatar||""}):e.jsx(pt,{icon:"Agent",appearance:"circle",colorScheme:"light",size:"lg"})}),e.jsx(pa,{children:e.jsx(ie,{content:o.values.name,children:e.jsx(S,{appearance:"h3",nowrapEllipsis:!0,children:o.values.name})})})]}),_&&s&&e.jsxs(P,{justifyContent:"end",mr:5,w:"50%",children:[e.jsx(Us,{style:{marginRight:"12px"},children:e.jsx(Ft,{value:f?c(n.current):p,onChange:x,className:"version-selector",options:f?[c(n.current)]:s,renderLabel:C=>C?.label??"",renderKey:C=>C.value,disabled:f})}),e.jsx(ie,{content:f?u.agents.notPublished:u.agents.published,style:{minWidth:"10px"},children:e.jsx(S,{nowrapEllipsis:!0,children:f?u.agents.notPublished:u.agents.published})}),e.jsx(Ot,{colorScheme:f?"inverse":"success"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(b,{mr:"8px",children:e.jsx(Q,{fieldType:"image-upload",name:"avatar",hasDescription:!1,maxDimensions:ca,onChange:(C,F)=>{Rt.includes(F)&&M.showToaster({type:"error",message:m.form[F]})}})}),e.jsx(b,{w:12,children:e.jsxs(v,{children:[e.jsx(b,{w:12,children:e.jsx(Q,{fieldType:"input",type:"text",id:"name",name:"name",text:"agentName",placeholder:"agentNamePlaceholder",required:!0,onChange:(C,F)=>{if(d)C.setFieldValue("name",F);else{const K=C.values.slug,H=`${gt(F)}`,Ce=da-(r.length+1),X=H.substring(0,Ce);if(K.startsWith(r))C.setFieldValue("slug",`${F?r+"-"+X:r}`);else{const ue=Ge();g(ue),C.setFieldValue("slug",`${ue}-${X}`)}}}})}),e.jsx(b,{w:12,children:e.jsx(Q,{fieldType:"slug",type:"text",id:"slug",name:"slug",required:!0,disabled:!!d,prefix:e.jsx(S,{nowrapEllipsis:!0,sx:{maxWidth:window.innerWidth>1400?"12vw":"6vw"},children:"ai.stackspot.com/agents/"})})})]})})]})})}),e.jsx(b,{sx:{height:"100%",pt:3},children:e.jsx(v,{sx:{height:"100%"},children:e.jsxs(b,{w:12,sx:{position:"relative"},children:[e.jsx(Q,{fieldType:"textarea",id:"system_prompt",name:"system_prompt",text:"agentSystemPrompt",placeholder:"agentPlaceholder",resize:!1,infoTooltip:u.agents.agentTooltip,minHeight:"100px",height:"100%",customStyle:{flexDirection:"column",width:"100%",height:"100%",position:"relative"},afterAddon:e.jsx(N,{sx:{position:"absolute",right:"5px",bottom:"5px"},onClick:I,"data-test-hint":"buttonExpandPrompt","aria-label":`${u.agents.expande} ${u.agents.instructionsModal}`,children:e.jsx(dt,{})})}),e.jsx(v,{sx:{position:"absolute",top:"-5px",right:"0px"},children:e.jsx(Ws,{onClick:A,isLoading:j,title:u.agents.popoverAgentSuggestionTitle,description:u.agents.popoverAgentSuggestionDescription,placeHolder:u.agents.popoverAgentSuggestionPlaceholder,customStyle:{right:0,left:"auto",transform:"translateX(0)",maxWidth:"90vw",top:"80%"}})})]})})})]})},ma=({tabIndex:t,setFieldValue:s,values:a,visibilityLevel:n})=>{const[l,i]=h.useState(t||0),u=k("menu",Nt),m=k("agents",D),o=qt(),d=n?.toLowerCase()==="account",[r,g]=h.useState(d?"account":"personal"),{params:c}=mt(),p=c.spotId,w=!!p,{knowledgeSourcesList:y,isFetching:j,error:_,filter:f,setFilter:I,fetchNextPage:A,hasNextPage:x}=Ks({visibility:r,spotId:p}),C=!d&&!w,F=!o&&!w,K=w;return e.jsxs(e.Fragment,{children:[e.jsx(b,{children:e.jsx(ae,{colorScheme:"inverse",size:"md",children:e.jsx(ht,{target:"_blank",sx:{textDecoration:"none"},href:`${Bt}/knowledge-sources?mode=create`,children:e.jsxs(v,{alignItems:"center",children:[e.jsx(S,{colorScheme:"inverse.contrastText",mr:3,children:m.agents.createKS}),e.jsx(q,{colorIcon:"inverse.contrastText",children:e.jsx(zt,{})})]})})})}),e.jsxs(Wt,{activeIndex:l,onChange:H=>{i(H),g(H===0?"personal":"account")},children:[C?e.jsx(Ae,{title:u.menu.personal,children:e.jsx(Pe,{isFetching:j,error:_,setFilter:I,values:a,setFieldValue:s,filter:f,knowledgeSourcesList:y,fetchNextPage:A,hasNextPage:x})}):null,F?e.jsx(Ae,{title:u.menu.account,children:e.jsx(Pe,{isFetching:j,values:a,error:_,setFilter:I,setFieldValue:s,filter:f,knowledgeSourcesList:y,fetchNextPage:A,hasNextPage:x})}):null,K?e.jsx(Ae,{title:"Spot",children:e.jsx(Pe,{isFetching:j,values:a,error:_,setFilter:I,setFieldValue:s,filter:f,knowledgeSourcesList:y,fetchNextPage:A,hasNextPage:x})}):null]})]})},Pe=({isFetching:t,error:s,setFilter:a,knowledgeSourcesList:n,filter:l,setFieldValue:i,values:u,fetchNextPage:m,hasNextPage:o})=>{const d=k("agents",D),[r,g]=h.useState(u.knowledge_sources_config?.knowledge_sources||[]),c=(w,y)=>{const j=w.currentTarget.checked;g(_=>j?[..._,y]:_.filter(f=>f!==y))},p=()=>{ft.knowledgeSourcesV2.invalidate()};return e.jsxs(e.Fragment,{children:[e.jsx(Oe,{onChange:a,placeholder:d.agents.filterPlaceholder}),e.jsxs(Y,{loading:t,error:s,children:[e.jsx(v,{flexWrap:"nowrap",children:e.jsx(ae,{colorScheme:"light",sx:{ml:"4px"},onClick:p,children:e.jsxs(v,{alignItems:"center",flexWrap:"nowrap",sx:{gap:"8px"},children:[d.agents.updateList,e.jsx(q,{children:e.jsx(Kt,{})})]})})}),e.jsx(qs,{searchText:l,listLength:n.length,titleAs:"h3",children:n?.length?e.jsx(b,{mt:7,sx:{maxHeight:"calc(100vh - 350px)",overflowY:"auto"},id:"ks-infinite-scroll",children:e.jsx(xt,{dataLength:n.length,next:m,hasMore:!!o,loader:e.jsx(e.Fragment,{}),scrollableTarget:"ks-infinite-scroll",style:{overflow:"visible"},children:n.map(w=>e.jsx(ha,{type:w.type,name:w.name,objectsQuantity:w.object_count,selectedItems:r,onChangeCheckbox:c,id:w.id},w.id))})}):e.jsx(Ut,{title:d.agents.addKnowledgeSourceEmptyListTitle,description:d.agents.addKnowledgeSourceEmptyListDescription,img:e.jsx(Ht,{src:"/assets/svg/icons/placeholder-generic.svg",width:184,height:104}),fullWidth:!0,sxCard:{marginTop:"7"},titleAs:"h3"})}),!!n?.length&&e.jsx(v,{pt:"5",children:e.jsx(de,{onClick:()=>{i("knowledge_sources_config.knowledge_sources",r),M.closeRightPanel()},children:d.global.add})})]})]})},ha=({type:t,name:s,id:a,objectsQuantity:n,onChangeCheckbox:l,selectedItems:i})=>{const u=i.includes(a),m=`knowledge_source-${a}`,o=h.useRef(null),d=k("agents",D);return e.jsxs(v,{as:"label",htmlFor:m,sx:{height:"48px",borderRadius:"4px"},bg:"light.400",my:3,p:4,alignItems:"center",justifyContent:"space-between","aria-checked":u,children:[e.jsxs(v,{alignItems:"center",gap:!0,flexWrap:"nowrap",children:[e.jsx(b,{sx:{borderRadius:"4px",position:"relative",cursor:"pointer",":focus-within":{outline:"2px solid currentColor",outlineOffset:"2px"}},onKeyDown:r=>{if(r.key==="Enter"||r.key===" "){r.preventDefault();const g=r.currentTarget.querySelector('input[type="checkbox"]');g&&g.click()}},children:e.jsx(Gt,{ref:o,id:m,name:"knowledge_source",checked:u,onChange:r=>l(r,a)})}),e.jsx(b,{children:e.jsx(Z,{palette:"gray",appearance:"square",children:t})}),e.jsx(b,{w:12,children:e.jsx(S,{as:"h4",appearance:"h6",nowrapEllipsis:!0,style:{maxWidth:"380px"},children:s})})]}),e.jsxs("span",{children:[e.jsxs("span",{style:{position:"absolute",left:"-9999px",width:"1px",height:"1px",overflow:"hidden",clip:"rect(1px,1px,1px,1px)"},children:[d.agents.totalObjects,": ",n]}),e.jsx(Z,{"aria-hidden":"true",palette:"gray",appearance:"square",children:n})]})]})};function tt(t,s,a){return!(!t||!s||a)}function xa(t,s,a,n,l,i){return tt(t,a,l)||tt(s,n,i)}const oe=(t,s,a,n,l,i,u)=>({label:t?`${t.model_configuration.provider.name} - ${t.display_name}`:"",value:t?.id,checked:!!s?.find(m=>m.model_id===t?.id),disabled:a===t?.id||xa(n,l,i,u,t?.model_configuration.usage_params?.enabled_structured_outputs,t?.model_configuration.usage_params?.enabled_tools),labelObject:{title:t?.display_name,description:t?.display_name,img:t?.model_configuration.provider.provider_type}}),fa=["settings-advanced","llm-settings","ks-settings"],_t=t=>{fa.forEach(s=>{s!==t&&document.getElementById(s)?.classList.add("hidden")}),document.getElementById(t)?.classList.toggle("hidden")},ba=({tabIndex:t,visibilityLevel:s})=>{const[a,n]=h.useState(!1),l=k("agents",D),i=k("global",ce),[u,m]=h.useState({left:void 0}),o=h.useRef(null),d=R(),r="knowledge_sources_config.knowledge_sources",g=d.values.knowledge_sources_config?.knowledge_sources||[],c=h.useMemo(()=>(d.values.knowledge_sources_details?g.filter(x=>!d.values?.knowledge_sources_details?.some(C=>C.id===x)):g)||[],[d.values.knowledge_sources_details,g]),[p,,,{isLoading:w}]=ft.listKnowledgeSourcesDataByIds.useStatefulQuery({knowledgeSourceSearchRequest:{ids:c}},{enabled:(!d.values.knowledge_sources_details||d.values.knowledge_sources_details.length!==g.length)&&!!g?.length}),y=h.useMemo(()=>d.values.knowledge_sources_details?d.values.knowledge_sources_details.filter(x=>g.some(C=>x.id===C)):[],[d.values.knowledge_sources_details,g]),j=x=>["snippet","api","event","custom","project_file","memory"].includes(x),_=x=>["public","private","internal"].includes(x),f=y.map(x=>({...x,type:j(x.type)?x.type:"custom",visibility_level:_(x.visibility_level)?x.visibility_level:"personal",use_only:x.use_only??!1,creator:x.creator??""})),I=p?p.concat(f):f,A=()=>{M.showRightPanel({title:l.agents.addKnowledgeSourceModalTitle,subtitle:l.agents.addKnowledgeSourceModalSubtitle,children:e.jsx(ma,{visibilityLevel:s,tabIndex:t,setFieldValue:d.setFieldValue,values:d.values}),style:{background:`${$.color.light[300]}`}})};return h.useEffect(()=>{if(a&&o.current){const x=o.current.getBoundingClientRect();m({left:x.right+8})}},[a]),e.jsx(b,{w:12,children:e.jsxs(U,{sx:{p:3},children:[e.jsxs(v,{justifyContent:"space-between",alignItems:"center",children:[e.jsx(O,{cardTitle:"Knowledge sources",popoverTitle:"Knowledge sources",popoverContent:l.agents.knowledgeSourcesPopoverDescription,ariaLabel:l.agents.knowledgeSourcesDetails}),e.jsxs(v,{alignItems:"center",children:[e.jsxs(b,{sx:{position:"relative"},mr:3,children:[e.jsx(N,{ref:o,sx:{bg:"light.500"},appearance:"square",size:"sm",onClick:()=>_t("ks-settings"),type:"button","data-test-hint":"buttonConfigKnowledgeSources","aria-label":l.agents.searchKnowledgeSourceConfiguration,children:e.jsx(ve,{})}),e.jsx(ja,{menuOpen:a&&!!u.left,setMenuOpen:n,style:{left:`${u.left}px`}})]}),e.jsxs(we,{sx:{height:"24px"},colorScheme:"inverse",type:"button",onClick:A,"data-test-hint":"buttonAddKnowledSources","aria-label":`${i.global.add} ${l.agents.knowledgeSourcesPopoverDescription}`,children:[e.jsx(q,{colorIcon:"inverse.contrastText",size:"xs",mr:2,children:e.jsx(Se,{})}),e.jsx(S,{appearance:"microtext1",weight:"medium",children:i.global.add})]})]})]}),w?e.jsx(bt,{height:"32px"}):e.jsx(e.Fragment,{children:!!I?.length&&e.jsx(v,{mt:3,sx:{gap:"4px"},children:I?.map((x,C)=>e.jsx(Z,{palette:"purple",appearance:"square",afterElement:e.jsx(N,{size:"xs",appearance:"square",colorIcon:"purple.800","data-test-hint":`RemoveKnowledgeBadgeButton-${C+1}`,"aria-label":`${l.global.remove} ${x.name}`,onClick:()=>d.setFieldValue(r,g?.filter(F=>F!==x.id)),children:e.jsx(be,{})}),children:x.name},`${x}-${C}`))})})]})})},ja=({menuOpen:t,setMenuOpen:s,style:a})=>{const{values:n,setFieldValue:l}=R(),i=h.useRef(null),u=k("agents",D),m=d=>{i.current&&!i.current.contains(d.target)&&s(!1)},o=()=>{s(!1),l("knowledge_sources_config.max_number_of_kos",4),l("knowledge_sources_config.relevancy_threshold",40),l("knowledge_sources_config.knowledge_sources",n?.knowledge_sources_config?.knowledge_sources||[])};return h.useEffect(()=>{const d=r=>m(r);return t?(document.addEventListener("mousedown",d),i?.current?.focus()):document.removeEventListener("mousedown",d),()=>{document.removeEventListener("mousedown",d)}},[t]),t&&e.jsx(ia,{style:a,ref:i,role:"menu","aria-modal":"true","aria-label":u.agents.searchKnowledgeSourceConfiguration,tabIndex:0,children:e.jsxs(v,{gap:!0,flexDirection:"column",children:[e.jsxs(b,{w:12,children:[e.jsx(O,{cardTitle:u.agents.maxNumberOfKos,popoverTitle:u.agents.maxNumberOfKos,popoverContent:u.agents.maxNumberofKosPopover}),e.jsx(re,{name:"knowledge_sources_config.max_number_of_kos",showValue:!0,min:1,max:20,step:"1",onChange:d=>l("knowledge_sources_config.max_number_of_kos",d),ariaLabel:u.agents.maxNumberOfKos})]}),e.jsxs(b,{w:12,children:[e.jsx(O,{cardTitle:u.agents.relevanceThreshold,popoverTitle:u.agents.relevanceThreshold,popoverContent:u.agents.relevanceThresholdPopover}),e.jsx(re,{showValueAsPercentage:!0,showValue:!0,name:"knowledge_sources_config.relevancy_threshold",step:"1",ariaLabel:u.agents.relevanceThreshold})]}),e.jsx(b,{children:e.jsx(me,{})}),e.jsx(b,{children:e.jsx(v,{justifyContent:"end",children:e.jsx(ae,{size:"sm",colorScheme:"primary",onClick:()=>o(),type:"button","data-test-hint":"buttonResetConfig",children:u.agents.resetConfiguration})})})]})})},va=()=>{const{values:t,setFieldValue:s}=R(),a=k("agents",D),n=()=>{s("knowledge_sources_config.max_number_of_kos",4),s("knowledge_sources_config.relevancy_threshold",40),s("knowledge_sources_config.knowledge_sources",t?.knowledge_sources_config?.knowledge_sources||[])};return e.jsxs(W,{children:[e.jsxs(P,{justifyContent:"space-between",mb:5,children:[e.jsx(se,{children:a.agents.knowledgeSourcesSettings}),e.jsx(ye,{icon:"Times",onClick:()=>_t("ks-settings")})]}),e.jsxs(Qt,{gap:"12px",p:3,bgLevel:400,children:[e.jsxs(W,{w:"100%",children:[e.jsx(O,{cardTitle:a.agents.maxNumberOfKos,popoverTitle:a.agents.maxNumberOfKos,popoverContent:a.agents.maxNumberofKosPopover}),e.jsx(re,{name:"knowledge_sources_config.max_number_of_kos",showValue:!0,min:1,max:20,step:"1",onChange:l=>s("knowledge_sources_config.max_number_of_kos",l),ariaLabel:a.agents.maxNumberOfKos})]}),e.jsxs(W,{w:"100%",children:[e.jsx(O,{cardTitle:a.agents.relevanceThreshold,popoverTitle:a.agents.relevanceThreshold,popoverContent:a.agents.relevanceThresholdPopover}),e.jsx(re,{showValueAsPercentage:!0,showValue:!0,name:"knowledge_sources_config.relevancy_threshold",step:"1",ariaLabel:a.agents.relevanceThreshold})]}),e.jsx(P,{children:e.jsx(Fe,{})}),e.jsx(P,{justifyContent:"end",children:e.jsx(ae,{size:"sm",colorScheme:"primary",onClick:()=>n(),type:"button","data-test-hint":"buttonResetConfig",children:a.agents.resetConfiguration})})]})]})},ya={openai:"OpenAI",bedrock:"AWSBedrock",azure:"Azure",stackspot:"StackSpot",gemini:"Gemini",deepseek:"DeepSeek",anthropic:"Anthropic"},_a={xs:{width:"16px",height:"16px"},md:{width:"24px",height:"24px"},lg:{width:"32px",height:"32px"}},Ne=({providerType:t="stackspot",size:s="xs"})=>e.jsx(b,{sx:_a[s],mr:3,children:e.jsx(pt,{appearance:"square",group:t==="stackspot"?"outline":"social",icon:ya[t]})}),wa=({providerName:t,providerType:s,providerModel:a})=>{const{overflow:n,ref:l}=Jt(),i=!n,u=t&&a?[t,a].join(" - "):"";return e.jsx(je,{hidden:i,text:u,position:"right",children:e.jsx(b,{children:e.jsxs(v,{bg:"light.600",flexWrap:"nowrap",sx:{gap:"4px",p:"4px",pr:3,borderRadius:"2px"},children:[e.jsx(Ne,{providerType:s}),e.jsx(b,{sx:{maxWidth:"200px"},children:e.jsx(S,{ref:l,nowrapEllipsis:!0,appearance:"microtext1",weight:"medium",children:u},gt(u))})]})})})},Sa=()=>{const t=k("agents",D),a=R().values.model_id||"",[n,,l,{isLoading:i}]=ee.getModel.useStatefulQuery({modelId:a},{enabled:!!a});return e.jsx(Y,{loading:i,error:l,children:e.jsx(b,{w:12,children:e.jsx(U,{sx:{p:3},children:e.jsxs(v,{justifyContent:"space-between",children:[e.jsx(O,{cardTitle:t.agents.llm,popoverTitle:t.agents.llmPopoverTitle,popoverContent:t.agents.llmPopoverContent,ariaLabel:t.agents.llmDetails}),e.jsxs(v,{alignItems:"center",sx:{gap:"8px"},children:[e.jsx(N,{onClick:()=>Te("llm-settings"),type:"button",bg:"light.400",appearance:"square",size:"sm","data-test-hint":"ConfigLLM","aria-label":t.agents.llmConfiguration,children:e.jsx(ve,{})}),n&&e.jsx(wa,{providerName:n?.model_configuration.provider.name,providerModel:n?.display_name,providerType:n?.model_configuration.provider.provider_type})]})]})})})})},Ta=()=>{const t=k("model",wt),s=R(),[a,n]=ee.listModels.useStatefulQuery({pageSize:999,active:!0}),[l,i]=h.useState(!1),u=h.useCallback(y=>{s.setFieldValue("model_id",y.id),s.setFieldValue("model_name",y.model_configuration.model_name),s.setFieldValue("llm_settings",null),s.setFieldValue("enabled_tools",y.model_configuration.usage_params?.enabled_tools),s.setFieldValue("enabled_structured_outputs",y.model_configuration.usage_params?.enabled_structured_outputs)},[s]);h.useEffect(()=>{if(a&&!s.values.model_id){const y=a?.items?.find(j=>j.resources.some(_=>_.is_default&&_.name==="agents"));u(y??a?.items?.[0])}},[a,s.values.model_id,u]);function m(y,j){if(y){const _=s.values.available_llm_models;_?.push({model_id:j.id,model_name:j.display_name,is_default:!1}),s.setFieldValue("available_llm_models",_)}else{const _=s.values.available_llm_models?.filter(f=>f.model_id!==j.id);s.setFieldValue("available_llm_models",_)}}const o=s.values.available_llm_models,d=s.values.model_id,r=s.values.enabled_structured_outputs,g=s.values.enabled_tools,c=!!s.values.structured_output,p=!!s.values.tools?.length||!!s.values.sub_agents_ids?.length;h.useEffect(()=>{l&&i(!1)},[d]);const w=y=>{if(y){const j=a?.items?.reduce((_,f)=>{const I=oe(f,o,d,r,g,c,p);return(!I.disabled||I.checked)&&_.push({model_id:f.id,model_name:f.display_name,is_default:!1}),_},[]);s.setFieldValue("available_llm_models",j)}else{const j=a?.items?.reduce((_,f)=>{const I=oe(f,o,d,r,g,c,p);return I.disabled&&I.checked&&_.push({model_id:f.id,model_name:f.display_name,is_default:!1}),_},[]);s.setFieldValue("available_llm_models",j)}i(y)};return e.jsxs(Re,{header:Ca,appearance:"card",style:{backgroundColor:$.color.light[400],padding:12},maxHeight:400,children:[e.jsx(b,{sx:{py:4},children:e.jsx(S,{appearance:"body2",colorScheme:"light.700",children:t.model.description})}),e.jsx(Y,{loading:n,children:e.jsxs(b,{children:[e.jsxs(P,{alignItems:"center",justifyContent:"space-between",bg:"light.300",p:"4px 12px",children:[e.jsx(S,{children:t.model.selectAll}),e.jsx(fe,{onChange:y=>w(y.target.checked),checked:l})]}),e.jsx(Fe,{}),a?.items?.map(y=>{const j=oe(y,o,d,r,g,c,p),_=s.values.available_llm_models?.some(f=>f.model_id===y.id);return j.checked&&_&&j.disabled&&y.id!==d&&m(!1,y),e.jsxs(b,{bg:"light.300",px:4,py:2,w:12,children:[e.jsxs(v,{alignItems:"center",justifyContent:"space-between",flexWrap:"nowrap",children:[e.jsx(b,{children:e.jsx(ka,{label:j.label,img:j.labelObject.img})}),e.jsx(b,{children:e.jsx(fe,{onChange:f=>m(f.target.checked,y),disabled:j.disabled,checked:j.disabled&&!j.checked?!1:j.checked})})]}),j.disabled&&y.id!==s.values.model_id&&e.jsx(b,{children:e.jsx(S,{colorScheme:"light.700",appearance:"body2",children:t.model.disabledModel})})]},y.id)})]})})]})},Ca=t=>{const s=k("model",wt);return e.jsxs(v,{justifyContent:"space-between",children:[e.jsx(O,{cardTitle:s.model.title,popoverContent:s.model.popover,showDocumentation:!1}),t]})},ka=({img:t,label:s})=>e.jsxs(v,{alignItems:"center",flexWrap:"nowrap",sx:{gap:"5px"},children:[e.jsx(b,{children:e.jsx(Ne,{providerType:t,size:"md"})}),e.jsx(b,{sx:{maxWidth:"300px"},children:e.jsx(ie,{content:s,children:e.jsx(S,{nowrapEllipsis:!0,children:s})})})]}),wt={en:{title:"Manage LLMs available for this agent",popover:"Enable or disable the available LLMs. Disabled LLMs cannot be used in chats with this agent.",description:"Select the LLMs you want to keep available for this agent. Uncheck those you don't want in the chat. Only models with the same functionality as the default agent will be available in the chat. For more details, consult the documentation.",disabledModel:"This LLM has been disabled because the agent has an Output Structure, Multi-agents, or Tools linked to it.",selectAll:"Select All"},pt:{title:"Gerencie os LLMs disponíveis para este agente",popover:"Ative ou desative os LLMs disponíveis. LLMs desativados não poderão ser usados em chats com este agente.",description:"Selecione os LLMs que você deseja manter disponíveis para este agente. Desmarque aqueles que você não quer no chat. Somente modelos com a mesma funcionalidade do agente padrão estarão disponíveis no chat. Para mais detalhes, consulte a documentação.",disabledModel:"Esta LLM foi desativada porque o agente possui uma Estrutura de saída, Multi-agentes ou Tools vinculadas.",selectAll:"Selecionar todos"}},Aa=(t,s)=>{const a={};return t.forEach(n=>{n.exclusive_group&&(a[n.exclusive_group]||(a[n.exclusive_group]=[]),a[n.exclusive_group].push({...n,label:s[n.name]}))}),a},st=(t,s)=>t.filter(a=>!a.exclusive_group).map(a=>({...a,label:s[a.name]})),Ma=()=>{const t=k("settings",St),s=R(),{model_id:a}=s.values,[n,l]=ee.getModel.useStatefulQuery({modelId:a||""},{enabled:!!a}),i=n?.model_configuration?.usage_params?.parameters||[],u=n?.model_configuration?.usage_params?.has_groups;h.useEffect(()=>{n&&s.setFieldValue("enabled_tools",!!n?.model_configuration?.usage_params?.enabled_tools)},[n]);const m=h.useMemo(()=>{if(u){const r=Aa(i,t.settings),g=st(i,t.settings);return[...Object.entries(r).map(([c,p])=>({group:c,items:p})),...g]}return st(i,t.settings)},[t,i,u]);h.useEffect(()=>{if(!n)return;const r={};if(u){const g=i.filter(c=>c.exclusive_group).reduce((c,p)=>(c[p.exclusive_group]||(c[p.exclusive_group]=[]),c[p.exclusive_group].push(p),c),{});Object.values(g).forEach(c=>{const p=c.find(w=>w.priority_parameter===!0);p&&(r[p.name]=p.default??void 0)}),i.filter(c=>!c.exclusive_group).forEach(c=>{r[c.name]=c.default??void 0})}else i.forEach(g=>{r[g.name]=g.default??void 0});s.setFieldValue("llm_settings",r)},[n]);const o=h.useCallback(r=>{const g=i.find(w=>w.name===r);if(!g)return;const c=g.exclusive_group,p={...s.values.llm_settings};c&&i.filter(w=>w.exclusive_group===c).forEach(w=>{delete p[w.name]}),p[r]=g.default??void 0,s.setFieldValue("llm_settings",p)},[i,s]),d=h.useCallback(r=>{const g=i.find(c=>c.name===r);return g?.exclusive_group?i.filter(c=>c.exclusive_group===g.exclusive_group&&c.name!==r).filter(c=>s.values.llm_settings?.[c.name]!==void 0).map(c=>c.label||c.name):[]},[i,s.values.llm_settings]);return!m.length&&!l?null:e.jsx(e.Fragment,{children:e.jsx(Y,{loading:l,children:e.jsx(b,{w:12,children:m.map((r,g)=>"group"in r?e.jsxs(b,{children:[e.jsx(ge,{children:r.items.map((c,p)=>e.jsxs(b,{children:[e.jsx(De,{as:v,justifyContent:"space-between",children:e.jsx(O,{cardTitle:c.label||c.name})}),e.jsxs(ge,{children:[(c.type==="float"||c.type==="int")&&e.jsx(nt,{...c,onChangeSwitch:w=>o(w.split(".")[1]),showSwitch:!0,isSwitchChecked:J.has(s.values.llm_settings,c.name),disabled:!J.has(s.values.llm_settings,c.name),isDisabledBy:Yt(t.settings.disabledByMutualExclusivity,d(c.name))}),c.type==="list"&&e.jsx(at,{...c})]}),p{const s=k("settings",St),a=h.useMemo(()=>t.options.map(o=>({label:s.settings[o]||o,value:o})),[t.options,s]),n="llm_settings."+t.name,l=a.find(o=>o.value===t.default),i=o=>e.jsx(Me.SingleValue,{...o,children:e.jsx("span",{"data-test-hint":`select-single-value-${o.data.label}`,children:o.children})}),u=o=>e.jsx(Me.IndicatorsContainer,{...o,innerProps:{...o.innerProps,"data-test-hint":`select-single-value-${Array.isArray(o.selectProps.value)?o.selectProps.value.map(d=>d.label).join("-"):o.selectProps.value?.label||""}`},children:o.children}),m=o=>e.jsx(Me.Menu,{...o,innerProps:{...o.innerProps,"data-test-hint":`select-menu-${Array.isArray(o.selectProps.value)?o.selectProps.value.map(d=>d.label).join("-"):o.selectProps.value?.label||""}`},children:o.children});return e.jsx(Q,{fieldType:"select",id:`selectForm-${n}`,name:n,defaultValue:l,options:a,"aria-label":s.eval(s.global.selectAtLeastOne,{suffix:s.settings.value}),required:t.required,components:{SingleValue:i,IndicatorsContainer:u,Menu:m}})},nt=t=>{const s=R(),a="llm_settings."+t.name;return e.jsx(re,{name:a,showValue:!0,min:t.min,max:t.max,step:t.type==="float"?"0.1":"1",defaultValue:t.default,onChange:n=>{s.setFieldValue(a,t.type==="float"?parseFloat(n.toString()):parseInt(n.toString()))},disabled:t.disabled,showSwitch:t.showSwitch,onChangeSwitch:t.onChangeSwitch,isSwitchChecked:t.isSwitchChecked,isDisabledBy:t.isDisabledBy})},St={en:{temperature:"Temperature",topP:"Top P",top_p:"Top P",topK:"Top K",top_k:"Top K",frequency_penalty:"Frequency penalty",presence_penalty:"Presence penalty",reasoning_effort:"Reasoning Effort",verbosity:"Verbosity",none:"None",minimal:"Minimal",low:"Low",medium:"Medium",high:"High",disabledByMutualExclusivity:"Disabled due to mutual exclusivity with $0. Use the toggle above to enable",value:"value"},pt:{temperature:"Temperatura",topP:"Top P",top_p:"Top P",topK:"Top K",top_k:"Top K",frequency_penalty:"Penalidade de frequência",presence_penalty:"Penalidade de presença",reasoning_effort:"Esforço de raciocínio",verbosity:"Verbosidade",none:"Nenhum",minimal:"Mínimo",low:"Baixo",medium:"Médio",high:"Alto",disabledByMutualExclusivity:"Desabilitado devido à exclusividade mútua com $0. Use o toggle acima para ativar.",value:"valor"}},Ia=()=>{const t=k("model",Pa),s=R(),[a,n]=h.useState(!1),[l,i]=ee.listModels.useStatefulQuery({pageSize:999,active:!0});function u(r){s.setFieldValue("model_id",r.id),s.setFieldValue("model_name",r.model_configuration.model_name),s.setFieldValue("llm_settings",null),s.setFieldValue("enabled_tools",r.model_configuration.usage_params?.enabled_tools),s.setFieldValue("enabled_structured_outputs",r.model_configuration.usage_params?.enabled_structured_outputs),s.setFieldValue("available_llm_models",[{model_id:r.id||"",model_name:r.model_configuration.model_name||"",is_default:!0}])}const m=async r=>{const g=s.values.enabled_tools&&(!!s.values.tools||!!s.values.sub_agents_ids)&&!r.model_configuration.usage_params?.enabled_tools,c=s.values.enabled_structured_outputs&&!!s.values.structured_output&&!r.model_configuration.usage_params?.enabled_structured_outputs;g||c?await M.confirm({title:t.model.confirmModalTitle,children:t.model.confirmModalDescription,confirm:t.model.confirm,cancel:t.model.cancel})&&u(r):u(r),n(!1)};h.useEffect(()=>{if(l?.items&&!s.values.model_id){const r=l?.items.find(g=>g.resources.some(c=>c.is_default&&c.name==="agents"));m(r??l?.items[0])}},[l,s.values.model_id,m]);const o=h.useMemo(()=>{const r=l?.items?.find(g=>g.id===s.values.model_id);return oe(r)},[l,s.values.model_id]),d=r=>e.jsxs(v,{justifyContent:"space-between",children:[e.jsx(O,{cardTitle:t.model.defaultLLM,popoverContent:t.model.defaultLLMPopover,showDocumentation:!1}),e.jsxs(v,{alignItems:"center",children:[e.jsxs(he,{sx:{marginRight:5},appearance:"contained",colorScheme:"light",size:"sm",onClick:()=>n(!0),"aria-label":t.model.defaultLLM,children:[o.label&&e.jsx(b,{sx:{maxWidth:"200px"},pr:3,children:e.jsx(S,{nowrapEllipsis:!0,appearance:"microtext1",weight:"medium",children:o.label})}),e.jsx(q,{size:"xs",children:i?e.jsx(Xt,{}):e.jsx(Zt,{})})]}),e.jsx(lt,{visible:a,onClose:()=>n(!1),sx:{position:"absolute",top:"40px",left:"-25%",width:"200px",background:"light.300",border:"1px solid light.600",zIndex:999},children:l?.items?.map(g=>{const c=oe(g);return e.jsx(rt,{sx:{cursor:"pointer"},onClick:()=>m(g),children:e.jsx(La,{img:c.labelObject.img,label:c.label})},g.id)})}),r]})]});return e.jsx(Re,{header:d,appearance:"card",style:{backgroundColor:$.color.light[400],padding:12},children:e.jsx(Ma,{})})},La=({img:t,label:s})=>e.jsxs(v,{alignItems:"center",children:[e.jsx(Ne,{providerType:t,size:"md"}),e.jsx(b,{sx:{maxWidth:"140px"},children:e.jsx(ie,{content:s,children:e.jsx(S,{nowrapEllipsis:!0,children:s})})})]}),Pa={en:{defaultLLM:"Default LLM",defaultLLMPopover:"Choose the LLM that will be used by default when starting a new chat with this agent.",advancedSettings:"Advanced LLM settings",confirm:"Confirm",cancel:"Cancel",confirmModalTitle:"Are you sure you want to change the LLM?",confirmModalDescription:"By changing this LLM, the Tools, Multi-agent, and Structured Responses settings will be removed. Are you sure you want to proceed?"},pt:{defaultLLM:"LLM Padrão",defaultLLMPopover:"Escolha o LLM que será usado por padrão ao iniciar um novo chat com este agente.",advancedSettings:"Configurações avançadas do LLM",confirm:"Confirmar",cancel:"Descartar",confirmModalTitle:"Tem certeza que deseja modificar a LLM?",confirmModalDescription:"Ao modificar essa LLM, as configurações de Tools, Multi-agentes e Respostas Estruturados serão removidas. Tem certeza de que deseja prosseguir?"}},Ea=()=>{const t=k("agents",D);return e.jsxs(W,{children:[e.jsxs(P,{justifyContent:"space-between",mb:5,children:[e.jsx(S,{children:t.agents.llmConfiguration}),e.jsx(ye,{icon:"Times",onClick:()=>Te("llm-settings")})]}),e.jsxs(W,{gap:12,children:[e.jsx(Ia,{}),e.jsx(Ta,{})]})]})},Da=({agentId:t,spotId:s})=>{const a=k("agents",D),n=$e(),l=k("global",ce),i=R(),u=i.values.sub_agents_ids,m=!!s,o="sub_agents_ids",[d,,,{isLoading:r}]=V.agentsByIdsV2.useStatefulQuery({searchAgentsRequestV2:{agents:u??[]}},{enabled:!!i.values.sub_agents_ids?.length}),g=async p=>{i.setFieldValue(o,p),M.closeRightPanel()},c=()=>{M.showRightPanel({title:a.agents.multiAgent,children:e.jsx(Bs,{spotId:s,onSave:g,addEmptyListTitle:a.agents.noAgentAddedToAgent,alreadySelectedItems:u,listTabsAgent:m?["workspace"]:["personal","account","shared"],onConfirmText:a.global.save,"data-test-hint":"buttonSaveMultiAgents","aria-label":a.agents.save,agentId:t,title:e.jsxs(S,{colorScheme:"light.700",appearance:"body2",children:[a.agents.addMultiAgentModalSubtitle,e.jsxs(ht,{target:"_blank",colorScheme:"light.700",href:`${n}/agents/create-agents#step-6-add-multi-agent`,children:[a.global.documentation,"."]})]})}),style:{background:`${$.color.light[300]}`,overflow:"hidden"}})};return e.jsx(b,{w:12,children:e.jsxs(U,{sx:{padding:3},children:[e.jsxs(v,{justifyContent:"space-between",alignItems:"center",flexWrap:"nowrap",children:[e.jsx(b,{children:e.jsx(v,{style:{gap:"8px"},alignItems:"center",flexWrap:"nowrap",children:e.jsx(O,{cardTitle:a.agents.multiAgent,popoverTitle:a.agents.multiAgent,popoverContent:a.agents.multiAgentPopoverDescription,popoverPosition:"right",ariaLabel:a.agents.multiAgentDetails})})}),e.jsx(b,{children:e.jsx(je,{hidden:i.values.enabled_tools,text:a.agents.toolsDisabledPopoverDescription,place:"top",children:e.jsxs(we,{size:"sm",colorScheme:"inverse",type:"button",onClick:c,"data-test-hint":"buttonMultiAgent","aria-label":`${l.global.add} ${a.agents.knowledgeSourcesPopoverDescription}`,disabled:!i.values.enabled_tools,children:[e.jsx(q,{colorIcon:"inverse.contrastText",size:"xs",mr:2,children:e.jsx(Se,{})}),e.jsx(S,{appearance:"microtext1",weight:"medium",children:l.global.add})]})})})]}),e.jsx(v,{children:r?e.jsx(bt,{height:"34px"}):e.jsx(e.Fragment,{children:!!d?.length&&i.values.enabled_tools&&e.jsx(v,{mt:3,sx:{gap:"4px"},children:d.map((p,w)=>e.jsx(Z,{palette:"gray",afterElement:e.jsx(N,{colorIcon:"gray.900",appearance:"circle","aria-label":a.agents.multiAgentRemove,title:a.agents.multiAgentRemove,"data-test-hint":`RemoveMultiAgentBadgeButton-${w+1}`,onClick:()=>i.setFieldValue(o,u?.filter(y=>y.agent_core_id!==p.id)),children:e.jsx(be,{})}),beforeElement:e.jsx(es,{size:"xxs",sx:{ml:"-3px",border:`2px solid ${$.color.gray[50]}`},children:p.avatar?e.jsx(ts,{name:p.name,imageSrc:p.avatar,style:{height:"24px"}}):e.jsx(q,{size:"md",color:"gray",appearance:"circle",children:e.jsx(ss,{})})}),children:p.name},p.id))})})})]})})},Va=({onGoBack:t,agentId:s,isLoading:a,handleSubmit:n,isEnableVersionContent:l})=>{const i=k("agents",D);return e.jsxs(b,{children:[e.jsx(S,{colorScheme:"light.700",children:l?i.agents.saveBeforeLeavingModalDescriptionVersion:i.eval(i.agents.saveBeforeLeavingModalDescription,{suffix:s?i.agents.editing:i.agents.creation})}),e.jsxs(v,{mt:6,justifyContent:"end",sx:{gap:"12px"},children:[e.jsx(ae,{appearance:"outlined",colorScheme:"inverse",size:"md",onClick:()=>{M.closeModal(),t()},children:i.agents.discard}),e.jsx(de,{size:"md",onClick:n,isLoading:a,children:e.jsx(S,{weight:"medium",children:i.agents.saveChanges})})]})]})},$a=()=>{const t=k("agents",D),s=k("global",ce),a=R(),n=a.values.suggested_prompts||[];return e.jsx(b,{w:12,children:e.jsx(as,{name:"suggested_prompts",children:({remove:l,push:i})=>e.jsxs(U,{sx:{p:3},children:[e.jsxs(v,{justifyContent:"space-between",alignItems:"center",children:[e.jsx(v,{alignItems:"center",children:e.jsx(O,{cardTitle:t.agents.suggestedPrompts,popoverTitle:t.agents.suggestedPrompts,popoverContent:t.agents.suggestedPromptsTooltip,showDocumentation:!1,ariaLabel:t.agents.suggestedPromptsDetails})}),e.jsxs(we,{size:"sm",colorScheme:"inverse",onClick:()=>i(""),type:"button",disabled:n?.length>=4,"data-test-hint":"buttonAddSuggested","aria-label":`${s.global.add} ${t.agents.suggestedPrompts}`,children:[e.jsx(q,{colorIcon:"inverse.contrastText",size:"xs",mr:2,children:e.jsx(Se,{})}),e.jsx(S,{appearance:"microtext1",weight:"medium",children:s.global.add})]})]}),!!n?.length&&e.jsx(b,{mt:4,children:n?.map((u,m)=>e.jsx(Q,{"aria-label":"Prompt",fieldType:"input",name:`suggested_prompts.${m}`,required:!0,autoFocus:!0,suffix:e.jsx(N,{type:"button",onClick:()=>{l(m)},"data-test-hint":`removeButtonSuggested-${m+1}`,"aria-label":`${t.global.remove} "${a.values.suggested_prompts?.[m]||""}"`,children:e.jsx(jt,{})})},m))})]})})})};function Fa({spotId:t}){const s=!!t,[a=[],n,l]=V.tools.useStatefulQuery({}),[i=[],u,m]=ns.getToolkitsFromWorkspaceAi.useStatefulQuery({workspaceId:t??""},{enabled:!!t}),[o=[],d,r,{fetchNextPage:g,hasNextPage:c}]=V.toolkitsV2.useStatefulInfiniteQuery({size:20,page:1});return[h.useMemo(()=>s?[...a.map(pe),...i.map(pe)]:[...a.map(pe),...(o??[]).map(pe)],[a,o,i]),n||d,l??r,u??m,g,c]}function Oa(t){const[s,,a,{isLoading:n}]=V.toolkitById.useStatefulQuery({toolkitId:t.id},{enabled:!t.builtIn}),l=h.useMemo(()=>t.builtIn?t.tools.map(i=>Xe(i)):s?.tools.map(i=>Xe(i,t.id)),[t,s]);return t.builtIn?[l,!1,void 0]:[l,n,a]}const Tt=B.ul` list-style: none; margin: 20px 0; padding: 0; display: flex; flex-direction: column; gap: 10px; flex: 1; overflow: auto; .content { padding: 20px; display: flex; &.vertical { gap: 10px; flex-direction: column; } &.horizontal { gap: 20px; align-items: center; } } li { border-radius: 8px; background-color: ${$.color.light[400]}; transition: background-color 0.3s; display: flex; flex-direction: column; & > button { border: none; cursor: pointer; background-color: transparent; color: inherit; text-align: left; } &:hover { background-color: ${$.color.light[500]}; .arrow { opacity: 1; } } .toolkit-icon { width: 32px; height: 32px; border-radius: 8px; background-color: ${$.color.light[500]}; display: flex; align-items: center; justify-content: center; } .arrow { opacity: 0.5; transition: opacity 0.3s; } label { display: flex; flex-direction: row; gap: 10px; } .title { flex: 1; } } `,Ra=B(os)` overflow: auto; height: 80vh; `,Ct=B.div` margin: 60px; text-align: center; color: ${$.color.light[700]}; `,Na=({onSelect:t})=>{const s=k("agents",D),{params:a}=mt(),n=a.spotId,[l=[],i,u,m,o]=Fa({spotId:n}),[d,r]=h.useState(""),g=h.useMemo(()=>d?l.filter(p=>p.name.toLocaleLowerCase().includes(d.toLocaleLowerCase())):l,[d,l]),c=h.useMemo(()=>g.map(p=>e.jsx("li",{children:e.jsxs("button",{onClick:()=>t(p),className:"content horizontal",children:[p.image?e.jsx("img",{src:p.image,className:"toolkit-icon"}):e.jsx(q,{className:"toolkit-icon",children:e.jsx(ve,{})}),e.jsx(S,{appearance:"body1",className:"title",children:p.name}),p.type==="mcp"?e.jsx(Qe,{colorPalette:"gray",children:"MCP"}):e.jsx(Qe,{colorPalette:"purple",children:s.global.webRequest}),e.jsx(q,{className:"arrow",children:e.jsx(is,{})})]})},p.id)),[g]);return e.jsxs(Y,{loading:i,error:u,children:[e.jsx(Oe,{onChange:r}),c.length?e.jsx(Ra,{children:e.jsx(b,{mt:7,sx:{maxHeight:"calc(100vh - 350px)",overflowY:"auto"},id:"toolkit-infinite-scroll",children:e.jsx(xt,{dataLength:g.length,next:m,hasMore:!!o,loader:e.jsx(e.Fragment,{}),scrollableTarget:"toolkit-infinite-scroll",children:e.jsx(Tt,{children:c})})})}):e.jsx(Ct,{children:e.jsx(S,{children:l.length?s.agents.noFilteredToolkits:s.agents.noTools})})]})},qa=({onChange:t,value:s,toolkit:a})=>{const n=k("agents",D),[l=[],i,u]=Oa(a),[m,o]=h.useState(s),[d,r]=h.useState(""),g=()=>{const f=s.map(A=>A.id);return l.every(A=>f.includes(A.id))},[c,p]=h.useState(g),w=()=>{const f=[...s,...l],I=Array.from(new Map(f.map(A=>[A.id,A])).values());o(I),p(!0)},y=()=>{const f=new Set(l.map(A=>A.id)),I=s.filter(A=>!f.has(A.id));o(I),p(!1)},j=h.useMemo(()=>d?l.filter(f=>f.name.toLocaleLowerCase().includes(d.toLocaleLowerCase())):l,[d,l]),_=h.useMemo(()=>j.map(f=>{const I=m.some(A=>A.id===f.id);return e.jsx("li",{children:e.jsxs(ls,{children:[e.jsxs(rs,{children:[e.jsxs(v,{alignItems:"center",children:[e.jsx(Je,{id:`checkbox-tool-${f.id}`,name:`checkbox-tool-${f.id}`,"data-test-hint":`checkbox-tool-${f.id}`,checked:I,onChange:()=>o(I?m.filter(A=>A.id!==f.id):[...m,f]),onClick:A=>A.stopPropagation()}),e.jsx(b,{sx:{maxWidth:"450px"},children:e.jsx(S,{nowrapEllipsis:!0,ml:3,appearance:"body1",children:f.name})})]}),e.jsx(cs,{})]}),e.jsx(ds,{children:f.description&&e.jsx("section",{id:`tool-description-section-${f.id}`,"data-test-hint":`tool-description-section-${f.id}`,"data-tool-id":f.id,children:e.jsx(S,{id:`tool-description-${f.id}`,"data-test-hint":`tool-description-${f.id}`,colorScheme:"light.700",children:f.description})})})]})},f.id)}),[j,m]);return e.jsxs(Y,{loading:i,error:u,children:[e.jsx(Oe,{onChange:r}),e.jsxs(he,{size:"sm",onClick:()=>c?y():w(),style:{alignSelf:"end",marginTop:"20px",position:"relative",paddingLeft:"28px",lineHeight:"12px"},colorScheme:"light",children:[e.jsx(Je,{tabIndex:-1,checked:c,style:{transform:"scale(0.6)",position:"absolute",left:0}}),c?n.global.uncheckAll:n.global.checkAll]}),_.length?e.jsx(Tt,{children:_}):e.jsx(Ct,{children:e.jsx(S,{children:n.agents.noFilteredTools})}),e.jsx(he,{onClick:()=>t(m),style:{alignSelf:"start"},"data-test-hint":"AddUtilitiesButton","aria-label":n.agents.addToolsModalSubtitle,children:n.global.add})]})},Ba=({toolkit:t,onSubmit:s})=>{const a=le(za),[n,l]=h.useState(""),[i,u,m]=V.mcpTools.useStatefulQuery({toolkitId:t.id}),o=h.useMemo(()=>i?.tools?.filter(d=>d.function.name.toLocaleLowerCase().includes(n.toLocaleLowerCase())).map(d=>e.jsx(Re,{header:e.jsxs(P,{gap:10,children:[e.jsx(us,{appearance:"square",children:e.jsx(ps,{src:t.image,fallback:e.jsx(Ye,{icon:"Cog"})})}),d.function.name]}),appearance:"card",children:e.jsx(se,{color:"light.700",children:d.function.description})},d.function.name)),[i?.tools,n]);return e.jsx(ct,{loading:u,error:m,children:e.jsxs(W,{gap:16,flex:1,style:{overflow:"hidden"},children:[e.jsxs(gs,{fullWidth:!0,children:[e.jsx(Ye,{icon:"Filter"}),e.jsx(ms,{type:"search",value:n,onChange:l,placeholder:a.filterTools})]}),e.jsx(se,{children:a.toolName}),!!o?.length&&e.jsx(W,{gap:4,flex:1,style:{overflow:"auto"},children:o}),o?.length===0&&e.jsx(se,{align:"center",color:"light.700",appearance:"microtext1",children:n?a.badSearch:a.noTools}),e.jsx(hs,{style:{alignSelf:"start"},onClick:s,children:a.add})]})})},za={en:{filterTools:"Filter tools",toolName:"Tool name",add:"Add",noTools:"This MCP toolkit doesn't have any tools.",badSearch:"Your search yield no results"},pt:{filterTools:"Filtrar tools",toolName:"Nome da Tool",add:"Adicionar",noTools:"Este Toolkit MCP não possui tools.",badSearch:"A busca não produziu resultados"}},Wa=()=>{const t=k("agents",D),s=k("global",ce),a=R(),n=a.getFieldProps("tools"),l=a.values.tools??[],i=a.values.mcpToolkits??[],u=!!a.values.enabled_tools,m=()=>{M.showRightPanel({title:t.agents.tools,subtitle:t.agents.addToolsModalSubtitle,stack:!0,children:e.jsx(Na,{onSelect:o=>{M.showRightPanel(o.type==="mcp"?{title:o.name,subtitle:t.agents.selectMCPTool,stack:!0,style:{overflow:"hidden"},children:e.jsx(Ba,{toolkit:o,onSubmit:()=>{a.setFieldValue("mcpToolkits",J.uniqBy([...i??[],o],"id")),M.closeRightPanel()}})}:{title:o.name,subtitle:t.agents.selectTool,stack:!0,children:e.jsx(qa,{toolkit:o,value:l,onChange:d=>{a.setFieldValue("tools",d),M.closeRightPanel()}}),style:{background:`${$.color.light[300]}`,overflow:"hidden"}})}}),style:{background:`${$.color.light[300]}`}})};return e.jsx(b,{w:12,children:e.jsxs(U,{sx:{padding:3},children:[e.jsxs(v,{justifyContent:"space-between",alignItems:"center",flexWrap:"nowrap",children:[e.jsx(b,{children:e.jsx(v,{style:{gap:"8px"},alignItems:"center",flexWrap:"nowrap",children:e.jsx(O,{cardTitle:t.agents.tools,popoverTitle:t.agents.tools,popoverContent:t.agents.toolsPopoverDescription,popoverPosition:"right",ariaLabel:t.agents.toolsDetails})})}),e.jsx(b,{children:e.jsx(je,{hidden:u,text:t.agents.toolsDisabledPopoverDescription,place:"top",children:e.jsxs(we,{size:"sm",colorScheme:"inverse",type:"button",onClick:m,"data-test-hint":"buttonTools","aria-label":`${s.global.add} ${t.agents.knowledgeSourcesPopoverDescription}`,disabled:!a.values.enabled_tools,children:[e.jsx(q,{colorIcon:"inverse.contrastText",size:"xs",mr:2,children:e.jsx(Se,{})}),e.jsx(S,{appearance:"microtext1",weight:"medium",children:s.global.add})]})})})]}),(!!l?.length||!!i?.length)&&u&&e.jsxs(v,{mt:5,flexWrap:"wrap",sx:{overflow:"auto",maxHeight:"200px"},children:[l?.map((o,d)=>e.jsx(b,{mb:2,children:e.jsx(Z,{palette:"orange",appearance:"square",afterElement:e.jsx(N,{appearance:"square",colorIcon:"orange.800",size:"xs",type:"button","data-test-hint":`RemoveToolsBadgeButton-${d+1}`,"aria-label":t.agents.tooltipRemove,onClick:()=>{a.setFieldValue("tools",n.value?.filter(r=>r.id!==o.id))},children:e.jsx(be,{})}),children:e.jsx(S,{nowrapEllipsis:!0,mr:1,sx:{whiteSpace:"pre-wrap"},children:o.name})})},o.id)),i?.map((o,d)=>e.jsx(b,{mb:2,children:e.jsx(Z,{palette:"gray",appearance:"square",afterElement:e.jsx(N,{appearance:"square",colorIcon:"gray.800",size:"xs",type:"button","data-test-hint":`RemoveMcpToolkitBadgeButton-${d+1}`,"aria-label":t.agents.tooltipRemove,onClick:()=>{a.setFieldValue("mcpToolkits",i.filter(r=>r.id!==o.id))},children:e.jsx(be,{})}),children:e.jsx(S,{nowrapEllipsis:!0,mr:1,sx:{whiteSpace:"pre-wrap"},children:o.name})})},o.id))]})]})})},Ka=({enabled:t=!0,debounceMs:s=2e3,onSave:a})=>{const n=R(),l=h.useRef(!0),i=h.useCallback(J.debounce(async u=>{await a(u)},s),[a,s]);h.useEffect(()=>{if(l.current){l.current=!1;return}return t&&n&&n.dirty&&n.isValid&&i(n.values),()=>{i.cancel()}},[n?.values,n?.dirty,n?.isValid,t,i])},kt=({id:t,agentData:s,draftVersion:a,version:n,shouldShowLoading:l,agent:i})=>{const[u]=V.updateAgentV2.useMutation(),[m]=V.createAgentVersion.useMutation(),[o,d]=h.useState(0),[r,g]=h.useState(),c=le(Ha),p=_e("ENABLE_VERSION_CONTENT_AI"),w=async()=>t?(await m({agentCoreId:t,createVersionRequest:{base_version_number:n}})).version.version_number:void 0;return{onEditAgent:async(j,_)=>{if(!t||!i)return;p.flagEnabled&&!a.current&&(a.current=await w());const f=s(j),I=Ve(i,f),A=p.flagEnabled?_??"draft":"published",x={...f,sub_agents_ids:f.sub_agents_ids??[],status:A,planner_type:f.planner_type},C=J.isEqual(x,r);if(r?!C:I)if(o<2)try{await u({agentId:t,updateAgentRequestV2:x}),d(0),g(x),l.current=!1}catch(K){if(d(H=>H+1),_==="published")throw K}else M.showToaster({message:c.titleError,type:"error"})}}},Ua=({enabled:t,...s})=>{const{onEditAgent:a}=kt(s);return Ka({enabled:t,onSave:a}),null},Ha={en:{titleError:"An error happened while trying to auto save your agent"},pt:{titleError:"Ocorreu um erro ao salvar seu agente"}},ot=20,Ga=B(Ds)` border-radius: 4px; border: 1px solid ${$.color.light[500]}; `,Qa={workspace:!1,knowledgeSource:!1,agent:!1,stack:!1,chatHistory:!1},At={height:"calc(100vh - 45px)",overflow:"scroll"},it={form:7,"try-agent":12},Ja=()=>{const t=k("agents",D),[s,a]=h.useState(!1),n=l=>{a(l),l?localStorage.setItem("showAgentModalInfoVersion","false"):localStorage.removeItem("showAgentModalInfoVersion")};return e.jsxs(W,{children:[e.jsx(S,{colorScheme:"light.700",children:t.agents.modalVersionsDescription1}),e.jsx(S,{colorScheme:"light.700",style:{fontWeight:"700"},children:t.agents.modalVersionsDescription2}),e.jsxs(P,{justifyContent:"space-between",mt:"32px",children:[e.jsx(P,{children:e.jsx(Ls,{value:s,onChange:n,children:t.agents.doNotShowAgain})}),e.jsx(de,{onClick:()=>M.closeModal(),children:t.agents.buttonCreateNewVersion})]})]})},dn=({onGoBack:t,route:s,id:a,tabIndex:n,randomAvatar:l,workspaceId:i,version:u})=>{Rs();const m=h.useRef(),o=k("agents",D),r=!!a?80:60,g=h.useMemo(()=>new xs({features:Qa,interceptors:[(...T)=>m.current?.(...T)]}),[]),c=h.useRef(!0),p=h.useRef(!1),w=h.useRef(!1),[y,,j,{isLoading:_}]=V.createAgentV2.useAllowed(),[f,,,{isLoading:I}]=V.updateAgentV2.useAllowed({agentId:a},{enabled:!!a}),A=h.useRef(),[x,,C,{isLoading:F}]=V.agentV2.useStatefulQuery({agentCoreId:a,versionNumber:A.current??u},{enabled:!!a}),{versions:K,recommendedVersion:H,isLoading:Ce}=Os(a),[X]=ee.getModel.useStatefulQuery({modelId:x?.version?.model_id??""},{enabled:!!x?.version?.model_id}),[ue]=fs.searchKnowledgeSources.useStatefulQuery({searchKnowledgeSourcesRequest:{knowledge_source_ids:x?.version?.knowledge_sources_config?.knowledge_sources??[]}},{enabled:!!x?.version?.knowledge_sources_config?.knowledge_sources?.length}),[qe,Be]=V.createAgentV2.useMutation(),te=T=>({...T,type:T.type?"CONVERSATIONAL":"SINGLE_ANSWER",name:T.name??"",slug:T.slug,system_prompt:T.system_prompt,suggested_prompts:T.suggested_prompts?.filter(L=>L.trim()),avatar:T.avatar,model_id:T.model_id,model_name:T.model_name,structured_output:T.enabled_structured_outputs&&T.structured_output?JSON.parse(T.structured_output):null,llm_settings:T.llm_settings,knowledge_sources_config:T.knowledge_sources_config?{...T.knowledge_sources_config,similarity_function:T?.knowledge_sources_config?.similarity_function}:T.knowledge_sources_config,builtin_tools_ids:T.enabled_tools?T.tools?.filter(L=>L.builtIn).map(L=>L.id):[],custom_tools:(()=>{if(!T.enabled_tools)return[];const L=J.groupBy(T.tools?.filter(z=>!z.builtIn),"toolkitId");return Object.keys(L).map(z=>({toolkit_id:z,tools_ids:L[z].map(G=>G.id)}))})(),mcp_toolkit_ids:T.mcpToolkits?.map(L=>L.id),available_models_ids:T.available_llm_models?.flatMap(L=>L.model_id),mode:T.mode}),{onEditAgent:ze}=kt({id:a,agentData:te,draftVersion:A,version:u??x?.version?.version_number,shouldShowLoading:c,agent:x}),[We,Ke]=h.useState();h.useEffect(()=>{I||_||(!a&&!y||a&&!f)&&bs.agents.$go()},[y]);const Mt=x?.visibility_level,ke=h.useMemo(()=>{const T=x?Ze(x,X):zs;return{...T,avatar:T.avatar||l}},[x,X,l]),It=js({avatar:_s().nullable(),name:Ie().trim().required("nameIsRequired").max(r,`max${r}Characters`).min(3,"min3Characters"),slug:ys(r),system_prompt:Ie().max(32e3,"max32000Characters"),structured_output:Ie().nullable().test("invalidJson","invalidJson",T=>T===null?!0:Ns(T)),max_llm_interactions:vs().min(1,"min1").max(50,"max50").nullable()}),E=ws({initialValues:ke,onSubmit:()=>{},enableReinitialize:!1,validationSchema:It}),Ue=h.useCallback(async()=>{c.current=!1,p.current=!0;const T=await E.validateForm();if(J.isEmpty(T))try{let L=a;if(a?(await ze(E.values,"published"),await V.listAgentVersions.invalidate({agentCoreId:a}),await V.agentV2.invalidate({agentCoreId:a})):(L=(await qe({newAgentRequestV2:te(E.values)})).id,await V.agentsMultipleFilters.invalidate(),await V.agents.invalidate(),s.$go({id:L,version:1}),M.showToaster({type:"success",title:o.agents.toastCreateAgentSuccessTitle,message:o.agents.toastCreateAgentSuccessMessage})),!L)return;let z={id:L,label:E.values?.name||""};try{const G=await V.agentV2.query({agentCoreId:L});z={id:L,label:G.name,image:G.avatar}}catch{}return z}catch(L){const z=Ss({error:L,prefix:o.agents.toastCreateAgentError});M.showToaster({type:"error",message:z})}E.setTouched(T)},[E.values,a]),He=_e("ENABLE_VERSION_CONTENT_AI")?.flagEnabled;h.useEffect(()=>{const T=localStorage.getItem("showAgentModalInfoVersion");a&&He&&T!=="false"&&M.showModal({size:"small",title:o.agents.modalVersionsTitle,onClose:()=>M.closeModal(),children:e.jsx(Ja,{})})},[He]),h.useEffect(()=>{x&&!w.current&&(w.current=!0,E.setValues(Ze(x,X)))},[x,X]),h.useEffect(()=>{w.current=!1},[a,u]),h.useEffect(()=>{!E.values.enabled_tools&&E.values.tools?.length&&(E.values.tools=[]),Ke((E.values.tools||[])?.length+(E.values.sub_agents_ids||[]).length>ot),m.current=async(T,L)=>{if(T.getValue().agentType!=="user"||!x||!Ve({...x,tools:ke.tools},te(E.values)))return;const z=await M.confirm({title:o.agents.saveAndTryModalTitle,subtitle:o.agents.saveAndTryModalDescription,confirm:o.agents.confirmSaveAgent,children:void 0});let G;if(z&&(L.set("isLoading",!0),G=await Ue()),G)L.set("agent",{...G,builtIn:!1});else return L.set("nextMessage",J.last(L.getMessages())?.getValue().content),L.popMessage(),L.set("isLoading",!1),!1}},[E.values,ke]);const Lt=$e();return e.jsx(Ts,{value:g,children:e.jsx(Y,{loading:Ce,error:j,children:e.jsx(na,{children:e.jsxs(Cs,{value:E,children:[e.jsx(Ua,{id:a,enabled:!!a,agentData:te,draftVersion:A,version:u??x?.version?.version_number,shouldShowLoading:c,agent:x}),e.jsx(Ya,{route:s,lastUpdated:x?.version?.created_at??void 0,formData:()=>te(E.values),formValues:E.values,name:E?.values?.name??"",validateForm:E.validateForm,setTouched:E?.setTouched,agentId:a,onEditAgent:ze,hasChanged:()=>!x||Ve(x,te(E.values)),onGoBack:()=>t(p.current?void 0:A.current),hasPublished:p.current,createAgent:qe,isCreatingAgent:Be}),e.jsx(Y,{loading:F&&c.current,error:C,children:e.jsxs(v,{mt:"56px",w:12,flexWrap:"nowrap",children:[e.jsx(b,{id:"agent-information",w:it.form,sx:At,children:e.jsxs(v,{p:4,flexDirection:"column",flexWrap:"nowrap",w:12,sx:{...ne.formContent,...ne.divider,gap:"8px"},children:[e.jsx(ga,{isUpdate:!!x?.id,versions:K,initialVersion:u,draftVersion:A,route:s,recommendedVersion:H}),e.jsx(ks,{}),e.jsx(Ga,{startExpanded:!0,padding:"16px 16px 8px 16px",children:{header:e.jsx(S,{mb:"3",sx:{fontWeight:500},children:o.agents.optionalSettings}),content:e.jsxs(v,{flexDirection:"column",flexWrap:"nowrap",w:12,p:"0 5 5 5",sx:{...ne.formContent,...ne.divider,gap:"8px"},children:[e.jsx(Sa,{}),e.jsx(Wa,{}),e.jsx(Da,{spotId:i,agentId:a}),e.jsx(ba,{tabIndex:Number(n),visibilityLevel:Mt}),e.jsx($a,{}),e.jsx(Gs,{})]})}})]})}),e.jsx(Ee,{id:"llm-settings",children:e.jsx(Ea,{})}),e.jsx(Ee,{id:"ks-settings",children:e.jsx(va,{})}),e.jsx(Ee,{id:"advanced-settings",children:e.jsx(ta,{})}),e.jsxs(b,{id:"try-agent",w:it["try-agent"],children:[We&&e.jsxs(la,{children:[e.jsx(q,{colorIcon:"warning.contrastText",children:e.jsx(As,{})}),e.jsxs("div",{style:{flex:1},children:[o.agents.tooManyTools1.replace("$0",`${(E.values.tools?.length||0)+(E.values.sub_agents_ids?.length||0)}`).replace("$1",`${ot}`)," ",e.jsx("a",{href:`${Lt}/${vt}`,target:"_blank",rel:"noreferrer",children:o.global.documentation})," ",o.agents.tooManyTools2]}),e.jsx(N,{appearance:"circle",colorIcon:"warning.contrastText",onClick:()=>Ke(!1),children:e.jsx(jt,{})})]}),e.jsxs(b,{p:4,sx:{width:"100%",height:We?"calc(100% - 60px)":"99%"},children:[e.jsx($s,{agent:x,agentKs:ue}),!x&&e.jsxs(Vs,{avatar:e.jsx(q,{children:e.jsx(Is,{})}),title:o.agents.newAgent,style:{position:"absolute",inset:0},children:[e.jsx(S,{children:o.agents.newAgentDescription}),e.jsx(Ms,{disabled:Be,appearance:"contrast",onClick:Ue,children:o.agents.save})]})]})]})]})})]})})})})},Ya=({route:t,formData:s,formValues:a,agentId:n,validateForm:l,setTouched:i,hasChanged:u,onGoBack:m,lastUpdated:o,hasPublished:d,isCreatingAgent:r,createAgent:g,onEditAgent:c})=>{const p=k("agents",D),w=k("form",ut),y=_e("ENABLE_VERSION_CONTENT_AI")?.flagEnabled,{formatDateWithTime:j}=Ps(),_=r,f=async()=>{const x=await l();if(x&&Object.keys(x).length>0){i(x),M.closeModal();return}try{if(n)await c(a,"published"),await V.listAgentVersions.invalidate({agentCoreId:n}),await V.agentV2.invalidate({agentCoreId:n}),t.$parent.agent.$go({agentId:n}),M.showToaster({type:"success",message:p.agents.toastUpdateAgentSuccess});else{const{id:C}=await g({newAgentRequestV2:s()});t.$parent.agent.$go({agentId:C}),M.showToaster({type:"success",title:p.agents.toastCreateAgentSuccessTitle,message:p.agents.toastCreateAgentSuccessMessage})}await V.agentsMultipleFilters.invalidate(),await V.agents.invalidate(),M.closeModal()}catch(C){const F=C instanceof Es?C?.translate():p.agents.toastCreateAgentError;M.showToaster({type:"error",message:typeof F=="string"?F:p.agents.toastCreateAgentError})}},I=()=>{u()?M.showModal({size:"small",title:y?p.agents.saveBeforeLeavingModalTitleVersion:p.agents.saveBeforeLeavingModalTitle,onClose:()=>M.closeModal(),children:e.jsx(Va,{onGoBack:m,isLoading:_??!1,handleSubmit:f,agentId:n,isEnableVersionContent:y})}):m()},A=async()=>{if(u()){const x=await l();if(x&&Object.keys(x).length>0)return i(x),x.slug&&x.slug==="slugMatches"&&n&&M.showToaster({type:"error",title:p.agents.toastCreateAgentError,message:w.form.slugInvalid}),null;f()}else m()};return e.jsx(oa,{children:e.jsxs(P,{justifyContent:"space-between",alignItems:"center",style:{height:"56px",marginInline:7},children:[e.jsxs(P,{alignItems:"center",children:[e.jsx(ye,{icon:"ArrowLeft",style:{marginInline:"4px"},"aria-label":p.agents.back,size:"md",onClick:()=>d?m():I()}),e.jsx(S,{ml:2,appearance:"body2",children:p.agents.back})]}),e.jsxs(P,{gap:"16px",children:[e.jsxs(P,{children:[e.jsx(xe,{icon:"Check"}),e.jsx(se,{children:j(o)})]}),e.jsx(de,{appearance:"primary",disabled:_,onClick:A,isLoading:_,"data-test-hint":"agent-confirm-button",children:y&&n?p.agents.createNewVersion:p.agents.finish})]})]})})},Ee=({children:t,id:s})=>e.jsx(b,{id:s,w:8,sx:At,className:"hidden",children:e.jsx(b,{p:4,sx:{width:"100%",height:"100%",...ne.divider},children:t})});export{dn as C};