@heroui/agent 0.2.0-beta.11 → 0.2.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +0,0 @@
1
- "use client";import{a as Oo,b as Do,c as Ho}from"./chunk-MXLGM4WV.js";import{a as Ha,c as bn}from"./chunk-S6OIAJSC.js";import{a as me}from"./chunk-CR3H7AVI.js";import{A as vn,B as La,b as Ca,c as Vn,e as Aa,f as Ta,g as Eo,h as Po,k as Ea,l as Pa,m as $n,n as Ia,o as xa,p as Na,q as No,r as ka,s as _a,t as Oa,u as Da,v as Tr,w as ko,x as Rr,y as Mr,z as _o}from"./chunk-TV4IIQ5G.js";import{a as Io}from"./chunk-6ZJJN322.js";import{b as ba,c as Ar,d as Sa}from"./chunk-64RI74L5.js";import{c as Ra,d as Ma,e as xo,f as wa}from"./chunk-OA3TG5CS.js";import{a as Ua,b as Ba,c as Fa,d as Lo}from"./chunk-7KCGPNEN.js";import"./chunk-2XBFFSW2.js";import{a as Bo,b as $a,c as Ka,d as wr}from"./chunk-RNNGE7KM.js";import{a as Va,b as Uo}from"./chunk-PZJ4NC3J.js";import{useAgentChat as _g}from"@cloudflare/ai-chat/react";import{ArrowUp as Og,ArrowUpRight as Dg,Microphone as Uc,Plus as Bc,StopFill as Oc,Xmark as Lg}from"@gravity-ui/icons";function Rt(e){return!!(e&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e))}function Fo(e,t){return e===null?null:typeof e=="string"?Rt(e)?e:null:Rt(t)?t:null}var Er=30,Ga=52;function Vo(e){try{let t=JSON.parse(localStorage.getItem(e)??"[]");return Pr(t)}catch{return[]}}function Pr(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object"&&"id"in t&&typeof t.id=="string"&&Rt(t.id)&&"title"in t&&typeof t.title=="string"&&"updatedAt"in t&&typeof t.updatedAt=="number")).sort((t,n)=>n.updatedAt-t.updatedAt).slice(0,Er):[]}function $o(e,t){let n=new Map(e.map(r=>[r.id,r]));for(let r of t){let o=n.get(r.id);(!o||r.updatedAt>=o.updatedAt)&&n.set(r.id,r)}return[...n.values()].sort((r,o)=>o.updatedAt-r.updatedAt).slice(0,Er)}function Nt(e,t){localStorage.setItem(e,JSON.stringify(t.slice(0,Er)))}function Kn(e,t,n,r,{replaceTitle:o=!1}={}){if(!n)return e;let s=e.find(d=>d.id===t);return[{id:t,title:o?n:s?.title??n,updatedAt:r},...e.filter(d=>d.id!==t)].sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,Er)}function Ir(e){let t=e?.find(r=>r.role==="user"),n=t?.parts.filter(r=>r.type==="text").map(r=>r.text??"").join(" ");return n?.trim()?Go(n):t?"Attachment":null}function Ko(e,t){return e?Go(e):t[0]?.name||"Attachment"}function Go(e){let t=e.replace(/\s+/g," ").trim();return t.length>Ga?`${t.slice(0,Ga-1).trimEnd()}\u2026`:t}function qo(e){let t=new Date;t.setHours(0,0,0,0);let n=t.getTime(),r=n-8640*60*1e3,o=[{items:[],label:"Today"},{items:[],label:"Previous 7 days"},{items:[],label:"Older"}];for(let s of e)s.updatedAt>=n?o[0].items.push(s):s.updatedAt>=r?o[1].items.push(s):o[2].items.push(s);return o.filter(s=>s.items.length>0)}import{Disclosure as Sn}from"@heroui/react";import{jsx as Fe,jsxs as en}from"react/jsx-runtime";function vu(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase().replace(/^\w/,t=>t.toUpperCase())}function bu(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=Object.entries(e);return t.length===0||t.some(([,n])=>typeof n=="object")?null:t.map(([n,r])=>[vu(n),String(r)])}function qa({approveLabel:e="Allow",className:t,denyLabel:n="Deny",hint:r="Waiting for your approval",icon:o,input:s,onApprove:i,onDeny:d,title:l,...c}){let m=bu(s),p=s!=null&&(typeof s!="object"||Object.keys(s).length>0);return en("section",{"aria-label":l,className:me("aui-approval",t),"data-slot":"agent-ui-approval",...c,children:[en("div",{className:"aui-approval__heading","data-slot":"agent-ui-approval-heading",children:[o?Fe("span",{"aria-hidden":!0,className:"aui-approval__icon","data-slot":"agent-ui-approval-icon",children:o}):null,en("div",{className:"aui-approval__heading-text",children:[Fe("strong",{className:"aui-approval__title",children:l}),r?Fe("span",{className:"aui-approval__hint",children:r}):null]})]}),p?en(Sn,{defaultExpanded:!0,className:"aui-approval__disclosure",children:[Fe(Sn.Heading,{children:en(Sn.Trigger,{className:"aui-approval__disclosure-trigger",children:["Review action details",Fe(Sn.Indicator,{})]})}),Fe(Sn.Content,{children:Fe(Sn.Body,{children:m?Fe("dl",{className:"aui-approval__details","data-slot":"agent-ui-approval-details",children:m.map(([S,u])=>en("div",{className:"aui-approval__detail",children:[Fe("dt",{children:S}),Fe("dd",{children:u})]},S))}):Fe("pre",{className:"aui-approval__pre",children:JSON.stringify(s,null,2)})})})]}):null,en("div",{className:"aui-approval__actions","data-slot":"agent-ui-approval-actions",children:[Fe(Oo,{size:"md",variant:"tertiary",onClick:d,children:n}),Fe(Oo,{size:"md",variant:"primary",onClick:i,children:e})]})]})}import{Description as Mu,Label as wu,ListBox as Qo,Select as qn}from"@heroui/react";import{useCallback as Eu,useEffect as Pu,useRef as za,useState as Wa}from"react";import{useId as Su}from"react";import{jsx as q,jsxs as Gn}from"react/jsx-runtime";function Qa({className:e,provider:t}){let n=t?.toLowerCase();return n==="openai"?q(Cu,{className:e,"data-provider":"openai"}):n==="google"?q(Au,{className:e,"data-provider":"google"}):n==="anthropic"?q(Tu,{className:e,"data-provider":"anthropic"}):n==="moonshot ai"?q(Ru,{className:e,"data-provider":"moonshot-ai"}):null}function Cu(e){return q("svg",{"aria-hidden":"true",fill:"currentColor",focusable:"false",role:"presentation",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",...e,children:q("path",{d:"M22.282 9.821a5.985 5.985 0 0 0-.516-4.911 6.046 6.046 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.182a5.985 5.985 0 0 0-3.998 2.9 6.046 6.046 0 0 0 .743 7.096 5.98 5.98 0 0 0 .511 4.911 6.051 6.051 0 0 0 6.515 2.9A5.985 5.985 0 0 0 13.26 24a6.056 6.056 0 0 0 5.772-4.206 5.99 5.99 0 0 0 3.997-2.9 6.056 6.056 0 0 0-.747-7.073m-9.022 12.608a4.476 4.476 0 0 1-2.877-1.041l.142-.08 4.778-2.758a.795.795 0 0 0 .393-.682v-6.737l2.02 1.169a.07.07 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494M3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085 4.783 2.758a.77.77 0 0 0 .781 0l5.843-3.368v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.141-1.646M2.341 7.896a4.485 4.485 0 0 1 2.365-1.973V11.6a.766.766 0 0 0 .388.677l5.814 3.354-2.02 1.169a.08.08 0 0 1-.071 0l-4.83-2.787A4.504 4.504 0 0 1 2.34 7.872zm16.596 3.856-5.833-3.388L15.119 7.2a.08.08 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.104v-5.677a.79.79 0 0 0-.407-.667m2.011-3.023-.142-.085-4.773-2.782a.776.776 0 0 0-.786 0L9.409 9.23V6.897a.07.07 0 0 1 .028-.061l4.83-2.787a4.499 4.499 0 0 1 6.68 4.66zM8.307 12.863l-2.02-1.164a.08.08 0 0 1-.038-.056V6.074a4.499 4.499 0 0 1 7.376-3.453l-.142.08-4.778 2.758a.795.795 0 0 0-.393.682zm1.098-2.365 2.602-1.5 2.607 1.5v2.999l-2.598 1.5-2.607-1.5Z"})})}function Au(e){let t=Su().replace(/:/g,""),n=`${t}-gemini-shape`,r=`${t}-gemini-mask`,o=`${t}-gemini-yellow-blur`,s=`${t}-gemini-red-blur`,i=`${t}-gemini-green-blur`,d=`${t}-gemini-blue-blur`,l=`${t}-gemini-gold-blur`,c=`${t}-gemini-cyan-blur`,m=`${t}-gemini-violet-blur`,p=`${t}-gemini-coral-blur`,S=`${t}-gemini-lemon-blur`;return Gn("svg",{"aria-hidden":"true",fill:"none",focusable:"false",role:"presentation",viewBox:"0 0 32 32",xmlns:"http://www.w3.org/2000/svg",...e,children:[q("path",{d:"M0 0h32v32H0z",fill:"none"}),q("defs",{children:q("path",{d:"M57.067 28.61q-7.396-3.184-12.945-8.732q-5.547-5.546-8.732-12.944a38.4 38.4 0 0 1-1.97-5.824A1.464 1.464 0 0 0 32 .001c-.671 0-1.255.458-1.419 1.11a38.4 38.4 0 0 1-1.971 5.823q-3.186 7.397-8.732 12.944q-5.548 5.548-12.945 8.732a38.4 38.4 0 0 1-5.824 1.972A1.464 1.464 0 0 0 0 32c0 .67.458 1.255 1.11 1.418a38.4 38.4 0 0 1 5.823 1.972q7.396 3.184 12.945 8.732q5.55 5.546 8.732 12.944a38.4 38.4 0 0 1 1.971 5.824c.164.65.749 1.11 1.419 1.11s1.255-.458 1.419-1.11a38.4 38.4 0 0 1 1.971-5.823q3.185-7.395 8.732-12.944q5.548-5.548 12.945-8.732a38.4 38.4 0 0 1 5.824-1.972A1.464 1.464 0 0 0 64 32.001c0-.672-.458-1.255-1.11-1.42a38.4 38.4 0 0 1-5.823-1.97",fill:"#fff",id:n})}),Gn("g",{fill:"none",children:[Gn("g",{mask:`url(#${r})`,transform:"translate(2 2)scale(.4375)",children:[q("use",{href:`#${n}`}),q("g",{filter:`url(#${o})`,children:q("ellipse",{cx:"14.208",cy:"16.716",fill:"#ffe432",rx:"14.208",ry:"16.716",transform:"rotate(19.552 -43.96 -16.268)"})}),q("g",{filter:`url(#${s})`,children:q("ellipse",{cx:"27.054",cy:"2.551",fill:"#fc413d",rx:"18.394",ry:"18.799"})}),q("g",{filter:`url(#${i})`,children:q("ellipse",{cx:"19.224",cy:"24.904",fill:"#00b95c",rx:"19.224",ry:"24.904",transform:"rotate(-2.799 667.58 51.694)"})}),q("g",{filter:`url(#${i})`,children:q("ellipse",{cx:"18.843",cy:"20.744",fill:"#00b95c",rx:"18.843",ry:"20.744",transform:"rotate(-31.317 81.174 36.482)"})}),q("g",{filter:`url(#${d})`,children:q("ellipse",{cx:"66.462",cy:"24.977",fill:"#3186ff",rx:"18.093",ry:"17.423"})}),q("g",{filter:`url(#${l})`,children:q("ellipse",{cx:"20.929",cy:"22.075",fill:"#fbbc04",rx:"20.929",ry:"22.075",transform:"rotate(37.251 9.618 -7.898)"})}),q("g",{filter:`url(#${c})`,children:q("ellipse",{cx:"24.131",cy:"22.292",fill:"#3186ff",rx:"24.131",ry:"22.292",transform:"rotate(34.51 19.317 63.957)"})}),q("g",{filter:`url(#${m})`,children:q("path",{d:"M54.226-2.304c2.794 3.799-.797 11.184-8.02 16.497c-7.222 5.312-15.342 6.539-18.136 2.74S28.866 5.75 36.09.436c7.223-5.312 15.343-6.539 18.136-2.74",fill:"#749bff"})}),q("g",{filter:`url(#${p})`,children:q("ellipse",{cx:"27.585",cy:"17.148",fill:"#fc413d",rx:"27.585",ry:"17.148",transform:"rotate(-42.847 5.973 20.37)"})}),q("g",{filter:`url(#${S})`,children:q("ellipse",{cx:"14.782",cy:"8.596",fill:"#ffee48",rx:"14.782",ry:"8.596",transform:"rotate(35.592 -44.338 25.191)"})})]}),Gn("defs",{children:[q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"42.756",id:o,width:"38.868",x:"-19.618",y:"12.903",children:q("feGaussianBlur",{stdDeviation:"2.46"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"85.162",id:s,width:"84.353",x:"-15.122",y:"-40.03",children:q("feGaussianBlur",{stdDeviation:"11.891"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"90.22",id:i,width:"78.916",x:"-20.768",y:"11.483",children:q("feGaussianBlur",{stdDeviation:"10.109"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"73.27",id:d,width:"74.611",x:"29.156",y:"-11.658",children:q("feGaussianBlur",{stdDeviation:"9.606"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"78.151",id:l,width:"77.538",x:"-38.291",y:"-16.269",children:q("feGaussianBlur",{stdDeviation:"8.706"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"76.898",id:c,width:"78.218",x:"7.78",y:"-6.098",children:q("feGaussianBlur",{stdDeviation:"7.775"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"51.479",id:m,width:"55.879",x:"13.208",y:"-18.425",children:q("feGaussianBlur",{stdDeviation:"6.957"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"68.674",id:p,width:"70.203",x:"-15.474",y:"-31.027",children:q("feGaussianBlur",{stdDeviation:"5.876"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"51.261",id:S,width:"55.137",x:"-14.173",y:"20.474",children:q("feGaussianBlur",{stdDeviation:"7.273"})}),q("mask",{height:"64",id:r,maskUnits:"userSpaceOnUse",width:"64",x:"0",y:"0",children:q("use",{href:`#${n}`})})]})]})]})}function Tu(e){return q("svg",{"aria-hidden":"true",fill:"none",focusable:"false",role:"presentation",viewBox:"0 0 256 257",xmlns:"http://www.w3.org/2000/svg",...e,children:q("path",{d:"m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0l10.63 1.426 4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999z",fill:"#d97757"})})}function Ru(e){return Gn("svg",{"aria-hidden":"true",clipRule:"evenodd",fillRule:"evenodd",focusable:"false",role:"presentation",strokeLinejoin:"round",strokeMiterlimit:2,viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",...e,children:[q("path",{d:"M503 114.333v280c0 60.711-49.29 110-110 110H113c-60.711 0-110-49.289-110-110v-280c0-60.71 49.289-110 110-110h280c60.71 0 110 49.29 110 110z"}),q("path",{d:"M342.065 189.759c1.886-2.42 3.541-4.63 5.289-6.77.81-1.007.74-1.771-.046-2.824-7.58-9.965-8.298-21.028-3.935-32.254 3.275-8.448 10.52-12.406 19.373-13.25 5.52-.521 10.936.046 15.959 2.73 6.596 3.53 10.438 8.912 11.688 16.341.995 5.926.81 11.712-.868 17.452-2.974 10.161-10.277 15.427-20.287 16.758-8.31 1.11-16.734 1.25-25.113 1.817-.648.046-1.308 0-2.06 0z",fill:"#027aff"}),q("path",{d:"M321.512 144.254h-50.064l-39.637 90.384h-56.036v-89.99H131v232.868h44.787v-98.103h78.973c13.598 0 26.015-7.927 31.744-20.252v118.355h44.787v-98.103c0-23.342-18.239-42.97-41.523-44.671v-.116h-24.593a45.577 45.577 0 0026.884-24.534l29.453-65.838z",fill:"#fff"})]})}import{jsx as gt,jsxs as Qn}from"react/jsx-runtime";function Iu({description:e,provider:t}){return t?e?`${t} \xB7 ${e}`:t:e}function xr({"aria-label":e="AI model",className:t,isDisabled:n=!1,onChange:r,options:o,placement:s="top start",value:i}){let[d,l]=Wa(!1),[c,m]=Wa(),p=za(0),S=za(null),u=n||o.length===0,h=o.find(A=>A.id===i),x=Eu(A=>{S.current=A,A?.setAttribute("aria-keyshortcuts","Control+Shift+M"),m(bn(A))},[]),w=A=>{!A&&Date.now()-p.current<350||l(A)};return Pu(()=>{if(u)return;let A=O=>{O.defaultPrevented||O.isComposing||O.repeat||!O.ctrlKey||!O.shiftKey||O.altKey||O.metaKey||O.key.toLowerCase()!=="m"||(O.preventDefault(),S.current?.focus(),l(!0))};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[u]),Qn(qn,{"aria-label":e,className:me("aui-model-picker",t),isDisabled:u,isOpen:d,value:i,onOpenChange:w,onChange:A=>{A!=null&&r(A),l(!1)},children:[Qn(qn.Trigger,{ref:x,className:"aui-model-picker__trigger","data-shortcut":"\u2303\u21E7M","data-slot":"agent-ui-model-picker-trigger","data-tooltip":"Select model",onPointerDown:()=>{p.current=Date.now()},children:[gt(qn.Value,{className:"aui-model-picker__value",children:h?.label??i}),gt(qn.Indicator,{className:"aui-model-picker__indicator"}),Qn("span",{"aria-hidden":"true",className:"aui-picker-tooltip",children:[gt("span",{children:"Select model"}),gt("kbd",{className:"aui-picker-tooltip__shortcut",children:"\u2303\u21E7M"})]})]}),gt(qn.Popover,{className:"aui-model-picker__popover",placement:s,UNSTABLE_portalContainer:c,children:gt(Qo,{"aria-label":`${e} options`,className:"aui-model-picker__list",children:o.map(A=>{let O=Iu(A);return Qn(Qo.Item,{className:"aui-model-picker__option","data-description":O,id:A.id,textValue:A.label,children:[gt(Qa,{className:"aui-model-picker__option-icon",provider:A.provider}),Qn("span",{className:"aui-model-picker__option-copy",children:[gt(wu,{className:"aui-model-picker__option-label",children:A.label}),O?gt(Mu,{className:"aui-model-picker__option-description",title:O,children:O}):null]}),gt(Qo.ItemIndicator,{className:"aui-model-picker__option-indicator"})]},A.id)})})})]})}import{Hand as xu,LockOpen as Nu,ShieldCheck as Ja}from"@gravity-ui/icons";import{Description as ku,Label as _u,ListBox as zo,Select as zn}from"@heroui/react";import{useCallback as Ou,useEffect as Du,useRef as ja,useState as Ya}from"react";import{jsx as rt,jsxs as Wn}from"react/jsx-runtime";var Xa=[{description:"Ask before every client tool action.",icon:xu,id:"ask",label:"Ask for approval"},{description:"Only ask for actions marked as needing approval.",icon:Ja,id:"auto",label:"Approve for me"},{description:"Run client tools without asking for approval.",icon:Nu,id:"full",label:"Full access"}];function Nr({"aria-label":e="Tool permissions",className:t,isDisabled:n=!1,onChange:r,value:o}){let[s,i]=Ya(!1),[d,l]=Ya(),c=ja(0),m=ja(null),p=Xa.find(h=>h.id===o),S=Ou(h=>{m.current=h,h?.setAttribute("aria-keyshortcuts","Control+Shift+P"),l(bn(h))},[]),u=h=>{!h&&Date.now()-c.current<350||i(h)};return Du(()=>{if(n)return;let h=x=>{x.defaultPrevented||x.isComposing||x.repeat||!x.ctrlKey||!x.shiftKey||x.altKey||x.metaKey||x.key.toLowerCase()!=="p"||(x.preventDefault(),m.current?.focus(),i(!0))};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[n]),Wn(zn,{"aria-label":e,className:me("aui-permission-picker",t),"data-tone":o==="full"?"warning":void 0,isDisabled:n,isOpen:s,value:o,onOpenChange:u,onChange:h=>{h!=null&&r(h),i(!1)},children:[Wn(zn.Trigger,{ref:S,className:"aui-permission-picker__trigger","data-shortcut":"\u2303\u21E7P","data-slot":"agent-ui-permission-picker-trigger","data-tooltip":"Change permissions",onPointerDown:()=>{c.current=Date.now()},children:[rt(Ja,{"aria-hidden":"true",className:"aui-permission-picker__trigger-icon"}),rt(zn.Value,{className:"aui-permission-picker__value",children:p?.label??o}),rt(zn.Indicator,{className:"aui-permission-picker__indicator"}),Wn("span",{"aria-hidden":"true",className:"aui-picker-tooltip",children:[rt("span",{children:"Change permissions"}),rt("kbd",{className:"aui-picker-tooltip__shortcut",children:"\u2303\u21E7P"})]})]}),rt(zn.Popover,{className:"aui-permission-picker__popover",placement:"top start",UNSTABLE_portalContainer:d,children:rt(zo,{"aria-label":`${e} options`,className:"aui-permission-picker__list",children:Xa.map(h=>{let x=h.icon;return Wn(zo.Item,{className:"aui-permission-picker__option","data-description":h.description,"data-tone":h.id==="full"?"warning":void 0,id:h.id,textValue:h.label,children:[rt(x,{"aria-hidden":"true",className:"aui-permission-picker__option-icon"}),Wn("span",{className:"aui-permission-picker__option-copy",children:[rt(_u,{className:"aui-permission-picker__option-label",children:h.label}),rt(ku,{className:"aui-permission-picker__option-description",title:h.description,children:h.description})]}),rt(zo.ItemIndicator,{className:"aui-permission-picker__option-indicator"})]},h.id)})})})]})}import{useEffect as Wo,useRef as Cn}from"react";import{jsx as ei}from"react/jsx-runtime";var Lu=40,Za=2;function kr(e,t,n){return Math.min(n,Math.max(t,e))}function Hu(e){let t=kr(Math.round(e),32,32768);return 2**Math.round(Math.log2(t))}function Uu(e){return e instanceof Error?e:new Error("Unable to access the microphone.")}function Bu(){let e=window;return e.AudioContext??e.webkitAudioContext}function Fu(e){e?.getTracks().forEach(t=>t.stop())}function Vu(e){if(!(!e||e.state==="closed"))try{e.close().catch(()=>{})}catch{}}function $u(e,t,n,r,o){let s=Math.min(r/2,o/2);if(typeof e.roundRect!="function"){e.fillRect(t,n,r,o);return}e.beginPath(),e.roundRect(t,n,r,o,s),e.fill()}function jo({active:e=!1,"aria-label":t,barGap:n=2,barWidth:r=2,className:o,deviceId:s,fadeEdges:i=!0,fadeWidth:d=20,fftSize:l=256,height:c=Lu,onError:m,onStreamEnd:p,onStreamReady:S,role:u,sensitivity:h=1.15,smoothingTimeConstant:x=.82,stream:w,style:A,...O}){let _=Cn(null),N=Cn({onError:m,onStreamEnd:p,onStreamReady:S}),L=Cn(null),$=Cn(null),X=Cn(null),b=Cn([]);Wo(()=>{N.current={onError:m,onStreamEnd:p,onStreamReady:S}},[m,p,S]),Wo(()=>{if(!e||w===null){_.current=null;return}let M,T=!1,P=!1,z=!1,ie=w===void 0,j,F=w,K=Se=>{try{j?.disconnect()}catch{}j=void 0,_.current?.context===M&&(_.current=null),Vu(M),M=void 0,ie&&Fu(F),F=void 0,Se&&P&&!z&&(z=!0,N.current.onStreamEnd?.())};return(async()=>{try{let Se=Bu();if(!Se)throw new Error("Live audio analysis is not supported in this browser.");if(!F){if(!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone capture is not supported in this browser.");F=await navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,...s?{deviceId:{exact:s}}:{},echoCancellation:!0,noiseSuppression:!0}})}if(T){K(!1);return}M=new Se;let H=M.createAnalyser();if(H.fftSize=Hu(l),H.smoothingTimeConstant=kr(x,0,1),j=M.createMediaStreamSource(F),j.connect(H),M.state==="suspended"&&await M.resume(),T){K(!1);return}_.current=H,X.current=new Uint8Array(H.frequencyBinCount),P=!0,N.current.onStreamReady?.(F)}catch(Se){K(!1),T||N.current.onError?.(Uu(Se))}})(),()=>{T=!0,K(!0)}},[e,s,l,w,x]),Wo(()=>{let M=L.current,T=$.current;if(!M||!T)return;let P=M.getContext("2d");if(!P)return;let z=0,ie=getComputedStyle(M).color||"#000",j=0,F=0,K=0,ye=D=>{if(K<=0||F<=0)return;D-j>500&&(ie=getComputedStyle(M).color||ie,j=D),P.clearRect(0,0,K,F),P.fillStyle=ie;let k=Math.max(1,r),Y=Math.max(0,n),re=k+Y,oe=Math.max(1,Math.floor((K+Y)/re)),Me=Math.ceil(oe/2),Ge=_.current;b.current.length!==Me&&(b.current=Array.from({length:Me},()=>0));let at=b.current;if(e&&Ge){let pe=X.current;(!pe||pe.length!==Ge.frequencyBinCount)&&(pe=new Uint8Array(Ge.frequencyBinCount),X.current=pe),Ge.getByteFrequencyData(pe);let Oe=Math.max(1,Math.floor(pe.length*.025)),vt=Math.max(Oe+1,Math.floor(pe.length*.46)),it=kr(h,0,4);for(let ge=0;ge<Me;ge+=1){let Et=Me<=1?0:ge/(Me-1),Kt=Math.min(pe.length-1,Math.round(Oe+Et*(vt-Oe))),Pt=Math.pow((pe[Kt]??0)/255*it,.72);at[ge]=kr((at[ge]??0)*.56+Pt*.44,0,1)}}else at.fill(0);let un=Math.max(Za,F*.84),xn=F/2,wt=oe*k+(oe-1)*Y,Je=(K-wt)/2;for(let pe=0;pe<oe;pe+=1){let Oe=Me-1-Math.min(pe,oe-1-pe),vt=e?at[Oe]??0:0,it=Math.max(Za,vt*un),ge=Je+pe*re,Et=xn-it/2;P.globalAlpha=e?.38+vt*.62:.2,$u(P,ge,Et,k,it)}P.globalAlpha=1},Se=()=>{let D=T.getBoundingClientRect(),k=Math.max(1,window.devicePixelRatio||1),Y=getComputedStyle(M).color||ie;K=Math.max(0,D.width),F=Math.max(0,D.height),M.width=Math.max(1,Math.round(K*k)),M.height=Math.max(1,Math.round(F*k)),M.style.width=`${K}px`,M.style.height=`${F}px`,P.setTransform(k,0,0,k,0,0),ie=Y,ye(performance.now())},H=D=>{ye(D),z=requestAnimationFrame(H)};Se();let B;return typeof ResizeObserver>"u"?window.addEventListener("resize",Se):(B=new ResizeObserver(Se),B.observe(T)),e&&(z=requestAnimationFrame(H)),()=>{z&&cancelAnimationFrame(z),B?.disconnect(),window.removeEventListener("resize",Se)}},[e,n,r,h]);let f=typeof c=="number"?`${Math.max(1,c)}px`:c,v={...A,height:f},R=`${Math.max(0,d)}px`,y=`linear-gradient(90deg, transparent 0, #000 min(${R}, 20%), #000 calc(100% - min(${R}, 20%)), transparent 100%)`;return ei("div",{...O,ref:$,"aria-label":t??(e?"Live microphone waveform":"Microphone waveform"),className:me("aui-voice-live-waveform",o),"data-active":e||void 0,"data-fade-edges":i||void 0,"data-slot":"agent-ui-voice-live-waveform",role:u??"img",style:v,children:ei("canvas",{ref:L,"aria-hidden":"true",className:"aui-voice-live-waveform__canvas",style:i?{WebkitMaskImage:y,maskImage:y}:void 0})})}import{useCallback as Ve,useEffect as ti,useRef as $e,useState as _r,useSyncExternalStore as Ku}from"react";var Lr={"audio-capture":"No microphone was found. Check your audio input and try again.","bad-grammar":"Speech recognition could not understand the requested grammar.",language:"Speech recognition is not available for this language.","language-not-supported":"Speech recognition is not available for this language.",network:"Speech recognition lost its network connection. Try again.","no-speech":"No speech was detected. Try again when you are ready.","not-allowed":"Voice dictation was blocked. Check microphone and speech recognition permissions and try again.","service-not-allowed":"Speech recognition is blocked by your browser settings."},ri="Microphone access is blocked for this page. Allow microphone access and try again.",Gu="Microphone access is enabled, but speech recognition is blocked in this browser or embedded preview.",Xo="Voice dictation is not supported in this browser.",oi="Voice recording stopped unexpectedly. Try again.",qu=["audio/webm;codecs=opus","audio/mp4","audio/webm","audio/ogg;codecs=opus"],Qu=/\s+/g;function Dr(e,t){let n=t.trim().replace(Qu," ");return n?!e||/\s$/.test(e)||/^[,.;:!?)]/.test(n)?`${e}${n}`:`${e} ${n}`:e}function Hr(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0,n=t%60,r=Math.floor(t/60),o=r%60,s=Math.floor(r/60),i=String(n).padStart(2,"0");return s>0?`${s}:${String(o).padStart(2,"0")}:${i}`:`${o}:${i}`}function Jo(e,t,n="unknown"){if(e==="not-allowed"){if(n==="denied")return ri;if(n==="granted")return Gu}return Lr[e]??(t?.trim()||"Voice dictation stopped unexpectedly.")}async function zu(){if(typeof navigator>"u"||!navigator.permissions?.query)return"unknown";try{return(await navigator.permissions.query({name:"microphone"})).state}catch{return"unknown"}}function si(){if(typeof window>"u")return;let e=window;return e.SpeechRecognition??e.webkitSpeechRecognition}function Wu(){return!!si()}function ni(){return typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof MediaRecorder<"u"}function ju(){if(!(typeof MediaRecorder>"u"||typeof MediaRecorder.isTypeSupported!="function"))return qu.find(e=>MediaRecorder.isTypeSupported(e))}function Or(e){e?.getTracks().forEach(t=>t.stop())}function Yo(e){if(typeof DOMException<"u"&&e instanceof DOMException){if(e.name==="NotAllowedError"||e.name==="SecurityError")return ri;if(e.name==="NotFoundError"||e.name==="DevicesNotFoundError")return Lr["audio-capture"]}return e instanceof Error&&e.message.trim()?e.message:"Microphone access could not be started."}function Yu(e){return e.error??new Error(oi)}function Xu(){return()=>{}}function Zo({language:e,onValueChange:t,transcribe:n,value:r}){let[o,s]=_r("idle"),[i,d]=_r(0),[l,c]=_r(null),[m,p]=_r(null),S=Ve(()=>n?ni():Wu(),[n]),u=Ku(Xu,S,()=>!1),h=$e("idle"),x=$e(r),w=$e(null),A=$e(e),O=$e(t),_=$e(null),N=$e(null),L=$e(0),$=$e(0),X=$e(n),b=$e(null),f=$e(new Map),v=$e(r);ti(()=>{A.current=e,O.current=t,X.current=n,v.current=r},[e,t,n,r]);let R=Ve(H=>{h.current=H,s(H)},[]),y=Ve(()=>{w.current!==null&&(clearInterval(w.current),w.current=null)},[]),M=Ve(()=>{y(),$.current=Date.now(),d(0),w.current=setInterval(()=>{d(Math.floor((Date.now()-$.current)/1e3))},250)},[y]),T=Ve(H=>{H.onend=null,H.onerror=null,H.onresult=null,H.onstart=null},[]),P=Ve(H=>{H.ondataavailable=null,H.onerror=null,H.onstop=null},[]),z=Ve((H,B)=>{if(P(H.recorder),B&&H.recorder.state!=="inactive")try{H.recorder.stop()}catch{}Or(H.stream)},[P]),ie=Ve(async H=>{if(L.current!==H.session||_.current!==H){z(H,!1);return}_.current=null,P(H.recorder),Or(H.stream),p(null),y(),R("transcribing");let B=H.recorder.mimeType||H.chunks[0]?.type||"audio/webm",D=new Blob(H.chunks,{type:B}),k=X.current;if(!k||D.size===0){R("idle"),c(D.size===0?Lr["no-speech"]:oi);return}let Y=new AbortController;b.current=Y;try{let re=await k(D,{...A.current?{language:A.current}:{},signal:Y.signal});if(L.current!==H.session||Y.signal.aborted)return;if(!re.trim()){c(Lr["no-speech"]);return}O.current(Dr(x.current,re)),c(null)}catch(re){if(L.current!==H.session||Y.signal.aborted)return;c(re instanceof Error&&re.message.trim()?re.message:"Voice transcription could not be completed. Try again.")}finally{b.current===Y&&(b.current=null),L.current===H.session&&R("idle")}},[P,z,y,R]),j=Ve(()=>{L.current+=1,y(),b.current?.abort(),b.current=null,c(null),p(null),R("idle");let H=_.current,B=N.current;if(_.current=null,N.current=null,f.current.clear(),H&&z(H,!0),!!B){T(B);try{B.abort()}catch{}}},[T,z,y,R]),F=Ve(()=>{if(h.current==="transcribing"){j();return}let H=_.current;if(H){y(),R("transcribing");try{H.recorder.stop()}catch(D){L.current+=1,_.current=null,z(H,!1),p(null),R("idle"),c(D instanceof Error?D.message:"Voice recording could not be stopped cleanly.")}return}if(h.current==="recording"){j();return}let B=N.current;if(B){y();try{B.stop()}catch(D){R("idle"),L.current+=1,N.current=null,f.current.clear(),T(B);try{B.abort()}catch{}c(D instanceof Error?D.message:"Voice dictation could not be stopped cleanly.")}}},[j,T,z,y,R]),K=Ve(async()=>{if(!ni()){c(Xo);return}let H=L.current+1;L.current=H,x.current=v.current,c(null),d(0),p(null),R("recording");let B;try{B=await navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0}})}catch(Y){if(L.current!==H)return;R("idle"),c(Yo(Y));return}if(L.current!==H){Or(B);return}let D;try{let Y=ju();D=Y?new MediaRecorder(B,{mimeType:Y}):new MediaRecorder(B)}catch(Y){if(Or(B),L.current!==H)return;R("idle"),c(Yo(Y));return}let k={chunks:[],recorder:D,session:H,stream:B};D.ondataavailable=Y=>{Y.data.size>0&&k.chunks.push(Y.data)},D.onerror=Y=>{L.current!==H||_.current!==k||(L.current+=1,_.current=null,y(),z(k,!0),p(null),R("idle"),c(Yu(Y).message))},D.onstop=()=>{ie(k)},_.current=k,p(B);try{D.start(1e3),M()}catch(Y){L.current+=1,_.current=null,z(k,!1),p(null),R("idle"),c(Yo(Y))}},[z,ie,M,y,R]),ye=Ve(()=>{let H=si();if(!H){c(Xo);return}let B;try{B=new H}catch(k){c(k instanceof Error?k.message:"Voice dictation could not be started.");return}let D=L.current+1;L.current=D,x.current=v.current,f.current=new Map,B.continuous=!0,B.interimResults=!0,B.maxAlternatives=1,A.current&&(B.lang=A.current),B.onstart=()=>{L.current===D&&(R("recognizing"),M())},B.onresult=k=>{if(L.current!==D)return;let Y=Math.max(0,k.resultIndex);for(let oe of f.current.keys())oe>=Y&&f.current.delete(oe);for(let oe=Y;oe<k.results.length;oe+=1){let Ge=k.results[oe]?.[0]?.transcript;typeof Ge=="string"&&f.current.set(oe,Ge)}let re=Array.from(f.current.entries()).sort(([oe],[Me])=>oe-Me).map(([,oe])=>oe).reduce(Dr,"");O.current(Dr(x.current,re))},B.onerror=k=>{if(L.current!==D)return;y(),R("idle"),f.current.clear(),L.current+=1;let Y=L.current;k.error!=="aborted"&&(k.error==="not-allowed"?zu().then(re=>{L.current===Y&&c(Jo(k.error,k.message,re))}):c(Jo(k.error,k.message))),N.current===B&&(N.current=null,T(B))},B.onend=()=>{L.current===D&&(y(),R("idle"),N.current===B&&(N.current=null,T(B)))},N.current=B,c(null),d(0),R("recognizing");try{B.start()}catch(k){T(B),N.current=null,y(),R("idle"),c(k instanceof Error?k.message:"Voice dictation could not be started.")}},[T,M,y,R]),Se=Ve(()=>{h.current!=="idle"||N.current||_.current||b.current||(X.current?K():ye())},[ye,K]);return ti(()=>()=>{L.current+=1,y(),b.current?.abort(),b.current=null;let H=_.current,B=N.current;if(_.current=null,N.current=null,H&&z(H,!0),!!B){T(B);try{B.abort()}catch{}}},[T,z,y]),{cancel:j,elapsedSeconds:i,error:l,isActive:o!=="idle",isRecording:o==="recording",isSupported:u,isTranscribing:o==="transcribing",start:Se,stop:F,stream:m}}import{Spinner as Hg}from"@heroui/react/spinner";import{isTerminalCloseEvent as Ug}from"agents/client";import{useAgent as Bg}from"agents/react";import{Suspense as Fg,useCallback as W,useEffect as be,useEffectEvent as Vt,useId as Vg,useLayoutEffect as $t,useMemo as Ae,useRef as ce,useState as ee}from"react";import{z as te}from"zod";var We="0.2.0-beta.11";var Ju=te.enum(["light","dark","system"]),Zu=te.enum(["outline","plain","surface","surface-secondary"]),ed=new Set(["[object object]","0","anonymous","distinct_id","distinctid","email","false","guest","id","nan","none","not_authenticated","null","true","undefined"]),es=te.string().trim().min(1).max(200).refine(e=>!ed.has(e.toLowerCase()),{message:"Identity id is reserved"}),td=te.discriminatedUnion("type",[te.object({id:es,type:te.literal("anonymous")}),te.object({id:es,type:te.literal("user")})]),nd=te.object({avatarUrl:te.string().trim().pipe(te.url()).optional(),email:te.string().trim().max(320).pipe(te.email()).optional(),name:te.string().trim().max(120).optional()}),$f=te.object({anonymousId:es.optional(),identity:td,profile:nd.optional()}),Kf=te.object({expiresAt:te.number().int().positive(),token:te.string().trim().min(1)}),Gf=te.object({agentId:te.string().trim().min(1).max(100),apiKeyId:te.string().trim().min(1).max(100),aud:te.literal("heroui-agent"),exp:te.number().int().positive(),iat:te.number().int().positive(),iss:te.literal("https://api.heroui.com"),jti:te.uuid(),protocolVersion:te.literal(6),sub:te.string().trim().min(1).max(200)});var Ur=te.object({agentId:te.string(),minimumProtocolVersion:te.literal(6),name:te.string().trim().min(1).max(120),protocolVersion:te.literal(6),sdkVersion:te.string().default(We),suggestedPrompts:te.array(te.string().trim().min(1).max(160)).max(5),surfaceVariant:Zu.default("plain"),theme:Ju});var rd="understanding your request";function od(e){let t=e.replace(/\r\n?/g,`
2
- `).trim();if(!t)return null;if(t.length<=1600)return t;let n=t.slice(0,1601),r=n.lastIndexOf(" "),o=r>=1600*.8?r:1600;return`${n.slice(0,o).trimEnd()}\u2026`}function sd(e){let t=e.replace(/\[([^\]]+)\]\([^\s)]+\)/g,"$1").replace(/[*_`~]/g,"").replace(/\s+/g," ").replace(/[.…!?:;,|—–-]+$/u,"").trim();return!t||t.length>80?null:t.replace(/^\p{Ll}/u,n=>n.toLocaleUpperCase())}function ad(e,t){let n=e.replace(/\r\n?/g,`
3
- `).trim();if(!n)return null;let r=/^#{1,6}\s+([^\n]+)\n+([\s\S]+)$/u.exec(n),o=/^(?:\*\*([^*\n]+)\*\*|__([^_\n]+)__)([\s\S]+)$/u.exec(n),s=r?.[1]??o?.[1]??o?.[2],i=r?.[2]??o?.[3],d=s?sd(s):null,l=i?.replace(/^\s*(?:[|:—–-]\s*)?/u,"").trim(),c=od(d&&l?l:n);return c?{detail:c,label:d??(t===0?"Thinking through your request":"Thinking through the next step")}:null}function id(e){if(!e.input||typeof e.input!="object"||Array.isArray(e.input))return null;let t=e.input.query;if(typeof t!="string")return null;let n=t.replace(/\s+/g," ").trim();return!n||n.length>300?null:n}function ts(e){return e.toLocaleLowerCase().replace(/[.…]+$/u,"").trim()}function ld(e,t){return t!=="accepted"&&t!=="preparing"?!1:ts(e)===rd}function ai(e){return e.type==="dynamic-tool"&&e.toolName?e.toolName:e.type.startsWith("tool-")?e.type.slice(5):null}function ii(e){return e==="renderComponent"||e==="composeUI"}var cd={ai:"AI",api:"API",crm:"CRM",csv:"CSV",id:"ID",mcp:"MCP",sql:"SQL",ui:"UI",url:"URL"};function ud(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").trim().split(/\s+/).map((n,r)=>{let o=cd[n.toLowerCase()];return o||(r===0?n.replace(/^\w/,s=>s.toUpperCase()):n)}).join(" ")}function Br(e){let t=e.toLowerCase();return/search|find|look up|research/.test(t)?"search":/web|source|browse|url/.test(t)?"browse":/code|sandbox|python|script|compute/.test(t)?"code":/chart|graph|visual|plot/.test(t)?"chart":/data|query|load|fetch|metric|table|account/.test(t)?"data":"thinking"}function li(e,t){if(!t.hasContent)return!1;let n=e.reduce((r,o)=>Math.max(r,o.messagePartIndex??-1),-1);return t.latestContentPartIndex>=n}function ns(e,t,n={}){if(e.role!=="assistant")return[];let r=[],o=new Set,s=0,i;for(let[l,c]of e.parts.entries()){if(c.type==="reasoning"){let N=ad(c.text,s);if(!N)continue;r.push({active:n.isStreaming===!0&&c.state!=="done",detail:N.detail,detailVisibility:"always",id:`${e.id}-reasoning-${l}`,kind:"thinking",label:N.label,messagePartIndex:l,stateKnown:c.state!==void 0,...r.length===0&&i?{title:i}:{}}),s+=1;continue}if(c.type==="data-activity"){let N=c.data.label.trim(),L=c.data.title?.trim();if(L&&!i){i=L;let $=r[0];$&&!$.title&&(r[0]={...$,title:L})}if(ld(N,c.data.stage)||L&&ts(N)===ts(L))continue;if(N&&o.has(N)){let $=r.findIndex(b=>b.label===N),X=r[$];L&&X&&!X.title&&(r[$]={...X,title:L})}else N&&(o.add(N),r.push({active:!1,detail:c.data.detail,id:c.id??`${e.id}-activity-${l}`,kind:c.data.kind??Br(N),label:N,messagePartIndex:l,sources:c.data.sources,stateKnown:!1,...L||r.length===0&&i?{title:L??i}:{}}));continue}let m=ai(c);if(!m)continue;let p=c,S=ii(m),u=S&&e.parts.slice(l+1).some(N=>{let L=ai(N);return L!==null&&ii(L)&&N.state==="output-available"});if(S&&p.state==="output-error"&&(n.isStreaming||u))continue;let h=m==="searchWeb"?id(p):null,x=S?"Building your data view":m==="executeSandbox"?"Analyzing your data":m==="getComponentSchema"?"Preparing your data view":h?`Searching the web for \u201C${h}\u201D`:t.get(m)?.displayName??ud(m),A=p.state==="output-denied"||!!(p.output&&typeof p.output=="object"&&"rejected"in p.output&&p.output.rejected)?h?`Skipped web search for \u201C${h}\u201D`:`Skipped ${x}`:p.state==="output-error"?h?`Couldn\u2019t search the web for \u201C${h}\u201D`:`Couldn\u2019t complete ${x}`:x,O=["input-available","input-streaming","approval-requested","approval-responded"].includes(p.state),_=r.findIndex(N=>N.label===A);if(_>=0){let N=r[_];N&&(r[_]={...N,active:O,messagePartIndex:l,stateKnown:!0,...!N.title&&i?{title:i}:{}});continue}o.add(A),r.push({active:O,id:p.toolCallId||`${e.id}-tool-${l}`,kind:S?"chart":m==="executeSandbox"?"code":m==="getComponentSchema"?"thinking":Br(A),label:A,messagePartIndex:l,stateKnown:!0,...r.length===0&&i?{title:i}:{}})}if(!n.isStreaming||r.length===0||r.some(l=>l.active))return r;let d=r.length-1;return r[d]?.stateKnown?r:r.map((l,c)=>({...l,active:c===d}))}var dd={accepted:"Thinking\u2026",generating:"Writing the answer\u2026",preparing:"Preparing the answer\u2026",recovering:"Recovering your answer\u2026","running-server-tool":"Running tools\u2026","waiting-client-tool":"Waiting for a browser action\u2026"},pd=new Set(["accepted","preparing","generating","waiting-client-tool","running-server-tool","recovering"]);function md(e){return e.type==="dynamic-tool"&&e.toolName?e.toolName:e.type.startsWith("tool-")?e.type.slice(5):null}function jn(e){return e?dd[e]:null}function ci({clientToolNames:e,isLocalPending:t,isRecovering:n,isStreaming:r,messages:o,status:s}){if(n)return"recovering";let i=o.findLast(d=>d.role==="assistant");if(i){for(let l=i.parts.length-1;l>=0;l-=1){let c=i.parts[l],m=md(c);if(m&&["input-streaming","input-available","approval-requested","approval-responded"].includes(c.state??""))return e.has(m)?"waiting-client-tool":"running-server-tool";if(c.type==="data-activity"||c.type==="data-progress"){let p=c.data?.stage;if(typeof p=="string"&&pd.has(p))return p}}let d=i.parts.some(l=>l.type==="text"&&l.text.trim().length>0||l.type==="data-component");if(r&&d)return"generating"}return r||s==="streaming"?"preparing":t||s==="submitted"?"accepted":null}import{ChartColumn as Od,CircleCheck as Dd,Code as Ld,Database as Hd,Globe as hi,Magnifier as Ud,Wrench as Bd}from"@gravity-ui/icons";import{Disclosure as je}from"@heroui/react";import{useEffect as yi,useRef as ss,useState as as}from"react";import{useEffect as fd,useState as hd}from"react";import{jsx as gd}from"react/jsx-runtime";function tn({children:e,className:t,...n}){return gd("span",{...n,className:`ha-shimmer${t?` ${t}`:""}`,children:e})}import{jsx as Fr,jsxs as vd}from"react/jsx-runtime";var yd=280;function Vr({animateOnMount:e=!0,children:t,className:n,...r}){let[o,s]=hd(()=>({current:{animate:e,id:0,text:t},previous:null}));o.current.text!==t&&s({current:{animate:!0,id:o.current.id+1,text:t},previous:o.current});let i=o.current.id,d=o.previous;return fd(()=>{if(!d)return;let l=window.setTimeout(()=>{s(c=>c.current.id===i?{...c,previous:null}:c)},yd);return()=>window.clearTimeout(l)},[i,d]),vd("span",{...r,"aria-label":r["aria-label"]??t,className:`ha-status-text${n?` ${n}`:""}`,"data-slot":"animated-text",children:[Fr("span",{"aria-hidden":"true","data-slot":"animated-text-value",className:o.current.animate?"ha-status-text__value ha-status-text__value--animated":"ha-status-text__value",children:Fr(tn,{children:o.current.text})},o.current.id),o.previous?Fr("span",{"aria-hidden":"true",className:"ha-status-text__value ha-status-text__value--exiting","data-slot":"animated-text-previous-value",children:Fr(tn,{children:o.previous.text})},o.previous.id):null]})}import{Code as bd,Heading as An,Link as Sd,Paragraph as Cd,Separator as Ad,Table as kt}from"@heroui/react";import{Children as ui,Suspense as di,isValidElement as pi,lazy as Td,memo as Rd,useMemo as Md}from"react";import{jsx as fe,jsxs as Nd}from"react/jsx-runtime";var wd=Td(()=>import("streamdown").then(e=>({default:e.Streamdown})));function Ed(e){return e?.match(/language-([^\s]+)/)?.[1]??"plaintext"}function Pd(e,t){return e?.find(n=>Array.isArray(n.language)?n.language.includes(t):n.language===t)}function rs(e){return ui.toArray(e?.props.children).filter(t=>pi(t))}function os(e,t){return ui.toArray(e).find(n=>pi(n)&&n.props.node?.tagName===t)}function Id({children:e}){let t=os(e,"thead"),n=os(e,"tbody"),r=os(t?.props.children,"tr"),o=rs(r),s=rs(n);return fe(kt,{"data-slot":"markdown-table",variant:"secondary",children:fe(kt.ScrollContainer,{children:Nd(kt.Content,{"aria-label":"Markdown table",children:[fe(kt.Header,{children:o.map((i,d)=>fe(kt.Column,{id:`column-${d}`,isRowHeader:d===0,children:i.props.children},String(i.key)))}),fe(kt.Body,{children:s.map((i,d)=>fe(kt.Row,{id:`row-${d}`,children:rs(i).map(l=>fe(kt.Cell,{children:l.props.children},String(l.key)))},String(i.key)))})]})})})}function xd(e,t){function n({children:o,className:s,node:i}){let d=Ed(s),l=String(o??"").replace(/\n$/,""),c=Pd(e?.renderers,d);if(c){let m=c.component,p=i?.properties?.metastring;return fe(di,{fallback:fe(Ho,{code:l,language:d}),children:fe(m,{code:l,isIncomplete:t,language:d,meta:typeof p=="string"?p:void 0})})}return fe(Ho,{code:l,language:d})}function r({children:o,className:s}){return fe(bd,{className:s,"data-slot":"markdown-inline-code",children:o})}return{a:({children:o,className:s,href:i})=>fe(Sd,{className:s,href:i,rel:"noreferrer",target:"_blank",children:o}),code:n,h1:({children:o,className:s})=>fe(An,{className:s,level:1,children:o}),h2:({children:o,className:s})=>fe(An,{className:s,level:2,children:o}),h3:({children:o,className:s})=>fe(An,{className:s,level:3,children:o}),h4:({children:o,className:s})=>fe(An,{className:s,level:4,children:o}),h5:({children:o,className:s})=>fe(An,{className:s,level:5,children:o}),h6:({children:o,className:s})=>fe(An,{className:s,level:6,children:o}),hr:({className:o})=>fe(Ad,{className:o,"data-slot":"markdown-separator",variant:"tertiary"}),inlineCode:r,p:({children:o,className:s})=>fe(Cd,{className:s,"data-slot":"markdown-paragraph",size:"sm",children:o}),table:Id}}var $r=Rd(function({animated:t=La,caret:n="block",children:r,isStreaming:o=!1,plugins:s}){let i=Md(()=>xd(s,o),[o,s]);return fe(di,{fallback:fe("div",{className:"ha-markdown","data-streaming":o?!0:void 0,children:fe("p",{children:r})}),children:fe("div",{className:"ha-markdown","data-streaming":o?!0:void 0,children:fe(wd,{normalizeHtmlIndentation:!0,parseIncompleteMarkdown:!0,animated:t,caret:o&&n!==!1?n:void 0,components:i,controls:!1,isAnimating:o,lineNumbers:!1,linkSafety:{enabled:!1},mode:o?"streaming":"static",plugins:s,children:r})})})});import{useEffect as kd}from"react";function _d(e,t=1){let n=e.scrollTop>t,r=e.scrollTop+e.clientHeight+t<e.scrollHeight;return n&&r?"both":n?"top":r?"bottom":"none"}function mi(e,t){delete e.dataset.topScroll,delete e.dataset.bottomScroll,delete e.dataset.topBottomScroll,t==="both"?e.dataset.topBottomScroll="true":t==="top"?e.dataset.topScroll="true":t==="bottom"&&(e.dataset.bottomScroll="true")}function nn(e,t=1){kd(()=>{let n=e.current;if(!n)return;let r=null,o=null,s=()=>{r!==null&&cancelAnimationFrame(r),r=requestAnimationFrame(()=>{r=null;let l=_d(n,t);l!==o&&(o=l,mi(n,l))})};s(),n.addEventListener("scroll",s,{passive:!0});let i=typeof ResizeObserver>"u"?null:new ResizeObserver(s),d=typeof MutationObserver>"u"?null:new MutationObserver(s);return i?.observe(n),d?.observe(n,{characterData:!0,childList:!0,subtree:!0}),()=>{n.removeEventListener("scroll",s),i?.disconnect(),d?.disconnect(),r!==null&&cancelAnimationFrame(r),mi(n,"none")}},[t,e])}import{jsx as ne,jsxs as ft}from"react/jsx-runtime";var Fd=24,Vd=160,$d=220;function vi(e,t,n,r){let o=ss(!0);yi(()=>{let s=e.current;if(!s)return;let i,d=!1,l=()=>{let h=s.scrollHeight-s.scrollTop-s.clientHeight;o.current=h<=Fd},c=()=>{d||l()},m=()=>{d=!1,window.clearTimeout(i),requestAnimationFrame(l)},p=()=>{if(!r||!n||!o.current)return;let h=typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,x=s.scrollHeight;if(typeof s.scrollTo!="function"){s.scrollTop=x;return}d=!h,s.scrollTo({behavior:h?"auto":"smooth",top:x}),window.clearTimeout(i),i=window.setTimeout(()=>{d=!1,l()},360)};s.addEventListener("scroll",c,{passive:!0}),s.addEventListener("pointerdown",m,{passive:!0}),s.addEventListener("touchstart",m,{passive:!0}),s.addEventListener("wheel",m,{passive:!0}),p();let S=s.firstElementChild,u=S&&typeof ResizeObserver<"u"?new ResizeObserver(p):null;return S&&u?.observe(S),()=>{s.removeEventListener("scroll",c),s.removeEventListener("pointerdown",m),s.removeEventListener("touchstart",m),s.removeEventListener("wheel",m),u?.disconnect(),window.clearTimeout(i)}},[t,r,n,e])}function Kd(e){let[t,n]=as(()=>({isStreaming:e,phase:e?"expanded":"collapsed"})),r=t.phase;return t.isStreaming!==e&&(r=e?"expanded":"fading",n({isStreaming:e,phase:r})),yi(()=>{if(e||r==="collapsed"||r==="expanded")return;let o=typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,s=o?"collapsed":r==="fading"?"collapsing":"collapsed",i=o?0:r==="fading"?Vd:$d,d=window.setTimeout(()=>{n(l=>l.isStreaming===e&&l.phase===r?{...l,phase:s}:l)},i);return()=>window.clearTimeout(d)},[e,r]),r}var Gd={browse:hi,chart:Od,code:Ld,data:Hd,search:Ud,thinking:Bd},gi="Working on your request";function Kr(e){return e.toLocaleLowerCase().replace(/\s+/g," ").replace(/[.…!?:;,]+$/u,"").trim()}function qd(e){let t=e.find(d=>d.title?.trim()),n=t?.title?.trim(),r=e.find(d=>Kr(d.label)!=="understanding your request")??e[0],o=t??r,s=o?.kind??Br(o?.label??n??""),i=new Set(e.map(d=>Kr(d.label)));return n&&!i.has(Kr(n))?{kind:s,title:n}:{kind:s,title:i.has(Kr(gi))?"Making progress":gi}}function fi({active:e}){return ft("span",{className:"ha-activity-icon","data-state":e?"active":"complete",children:[ne("span",{"aria-hidden":"true",className:"ha-activity-icon-state ha-activity-icon-state--active",children:ne("span",{className:"ha-activity-spinner"})}),ne("span",{"aria-hidden":"true",className:"ha-activity-icon-state ha-activity-icon-state--complete",children:ne(Dd,{})})]})}function bi({active:e,label:t}){return e?ne(Vr,{className:"ha-activity-step-label ha-progress-shimmer",children:t}):ne("span",{className:"ha-activity-step-label",children:t})}function Qd({detail:e,isDetailActive:t,isLabelActive:n,isTurnActive:r,label:o,markdownAnimation:s,markdownPlugins:i}){let[d,l]=as(()=>({isDetailActive:t,isExpanded:t})),c=d.isExpanded;d.isDetailActive!==t&&(c=t,l({isDetailActive:t,isExpanded:c}));let m=ss(null);return nn(m),vi(m,e,t&&r,c),ft(je,{className:"ha-activity-step-disclosure",isExpanded:c,onExpandedChange:p=>l({isDetailActive:t,isExpanded:p}),children:[ne(je.Heading,{children:ft(je.Trigger,{className:"ha-activity-step-trigger",children:[ne(bi,{active:n,label:o}),ne(je.Indicator,{className:"ha-activity-step-chevron"})]})}),ne(je.Content,{className:"ha-activity-step-disclosure-content",children:ne(je.Body,{className:"ha-activity-detail",children:ne("div",{ref:m,className:"ha-activity-detail-inner",children:ne($r,{animated:s,caret:!1,isStreaming:t?r:!1,plugins:i,children:e})})})})]})}function zd(e){let t=Math.max(1,Math.round(e/1e3)),n=Math.floor(t/3600),r=Math.floor(t%3600/60),o=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${o}s`:`${o}s`}function Gr({ariaLabel:e,label:t}){return ne("div",{className:"ha-progress ha-activity-status",children:ne(Vr,{"aria-label":e,className:"ha-progress-shimmer",role:"status",children:t})})}function Si({completedAt:e,defaultOpen:t=!1,hasResponseStarted:n=!1,isStreaming:r,items:o,markdownAnimation:s,markdownPlugins:i,startedAt:d}){let l=r&&!n,c=Kd(r),[m,p]=as(null),S=ss(null),u=o.findLastIndex(y=>y.active),h=o.length-1,x=l?u>=0?u:h:-1,w=o.map((y,M)=>({...y,active:M===x})),A=qd(w),O=m===null&&!t&&!r&&(c==="fading"||c==="collapsing"),N=m??(t||c==="expanded"||c==="fading"),L=m!==null||t?N?"expanded":"collapsed":c,$=d!==void 0&&e!==void 0&&!r?Math.max(0,e-d):null,X=$===null?"Activity":`Worked for ${zd($)}`,b=r||O?A.title:$===null?"Activity":X,f=A.kind,v=Gd[f],R=w.map(y=>`${y.id}:${y.active?1:0}:${y.detail??""}:${y.sources?.map(M=>M.label).join(",")}`).join("|");return nn(S),vi(S,R,r,N),ft(je,{className:"ha-activity","data-complete":r?void 0:"true","data-phase":L,isExpanded:N,onExpandedChange:p,children:[ne(je.Heading,{children:ft(je.Trigger,{className:"ha-activity-trigger",children:[ne("span",{"aria-hidden":"true",className:"ha-activity-summary-icon",children:ne("span",{children:ne(v,{})},f)}),r||O?ne(Vr,{className:"ha-activity-summary-label ha-progress ha-progress-shimmer",role:"status",children:b}):ne("span",{className:"ha-activity-summary-label ha-activity-summary-label--complete ha-progress",children:b}),ne(je.Indicator,{className:"ha-activity-chevron"})]})}),ne(je.Content,{className:"ha-activity-disclosure-content",children:ne(je.Body,{children:ne("div",{ref:S,className:"ha-activity-panel",children:ft("ol",{"aria-label":"Thinking steps",children:[w.map((y,M)=>ft("li",{"aria-current":y.active?"step":void 0,className:"ha-activity-item","data-active":y.active||void 0,"data-state":y.active?"active":"complete",children:[ne(fi,{active:y.active}),ft("div",{className:"ha-activity-content",children:[y.detail&&(y.active||y.detailVisibility==="always")?ne(Qd,{detail:y.detail,isDetailActive:l?o[M]?.active===!0:!1,isLabelActive:y.active,isTurnActive:r,label:y.label,markdownAnimation:s,markdownPlugins:i}):ne(bi,{active:y.active,label:y.label}),y.sources?.length?ne("span",{"aria-label":"Sources",className:"ha-activity-sources",children:y.sources.map(T=>ft("span",{className:"ha-activity-source",children:[ne(hi,{"aria-hidden":"true"}),T.label]},T.label))}):null]})]},y.id)),r?null:ft("li",{className:"ha-activity-item","data-complete":"true","data-state":"complete",children:[ne(fi,{active:!1}),ne("div",{className:"ha-activity-content",children:ne("span",{className:"ha-activity-step-label",children:"Final response ready"})})]})]})})})})]})}import{z as tp}from"zod";import{z as _t}from"zod";var Wd=["callMcpTool","composeUI","executeSandbox","getComponentSchema","renderComponent","searchKnowledge","searchMcpTools","searchWeb"],jd="mcp_",Yd=20,Xd=16*1024,Jd=_t.object({description:_t.string().trim().min(1).max(1e3),inputSchema:_t.record(_t.string(),_t.unknown()),name:_t.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).refine(e=>!Wd.includes(e)&&!e.toLowerCase().startsWith(jd),"Client tool name is reserved by the HeroUI Agent runtime"),needsApproval:_t.boolean().optional()}),Ci=_t.array(Jd).max(Yd).superRefine((e,t)=>{let n=new Set;for(let r of e)n.has(r.name)&&t.addIssue({code:"custom",message:`Duplicate client tool name: ${r.name}`}),n.add(r.name);new TextEncoder().encode(JSON.stringify(e)).byteLength>Xd&&t.addIssue({code:"custom",message:"Client tool manifest exceeds 16KB"})});import{z as Ye}from"zod";var Ai=Ye.object({excerpt:Ye.string().trim().min(1).max(2e3).optional(),locator:Ye.string().trim().min(1).max(160).optional(),sourceId:Ye.string().trim().min(1).max(120)}),Zd=Ye.string().trim().max(2048).refine(e=>{try{return["http:","https:"].includes(new URL(e).protocol)}catch{return!1}}),ep=Ye.union([Ai.extend({sourceType:Ye.literal("document"),title:Ye.string().trim().min(1).max(200)}),Ai.extend({sourceType:Ye.literal("url").optional(),title:Ye.string().trim().min(1).max(200).optional(),url:Zd})]),Ti=Ye.object({items:Ye.array(ep).min(1).max(16)});function np(e){return ba(e.parameters)?tp.toJSONSchema(e.parameters):e.parameters}function Ot(e){return Ci.parse(e.map(t=>({description:t.description,inputSchema:np(t),name:t.name,...t.needsApproval?{needsApproval:!0}:{}})))}var Tn=class extends Error{constructor(){super("The assistant configuration changed and must be bootstrapped again"),this.name="AgentRuntimeRevisionStaleError"}},Yn=class extends Error{retryable;status;constructor(t){super("Could not refresh the assistant connection"),this.name="AgentRuntimeTicketError",this.status=t,this.retryable=t===408||t===429||t>=500}},qr=class extends Error{code;status;constructor(t,n){super("Could not bootstrap the assistant conversation"),this.name="AgentConversationBootstrapError",this.code=n,this.status=t}},rp=250,op=2e3,wi=new Set(["CONVERSATION_LEASE_CONFLICT","SETTLEMENT_ACKNOWLEDGEMENT_PENDING"]),sp=15e3,Ri=3e4;function Ei(e){return e instanceof qr&&e.status===409&&wi.has(e.code)}function ap(e){return e===408||e===429||e>=500}function ip(e,t){if(!e)return null;let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.max(250,Math.ceil(n*1e3));let r=Date.parse(e);return Number.isFinite(r)?Math.max(250,r-t):null}function lp(e,t){return new Promise((n,r)=>{if(t.aborted){r(t.reason);return}let o=()=>{globalThis.clearTimeout(s),r(t.reason)},s=globalThis.setTimeout(()=>{t.removeEventListener("abort",o),n()},e);t.addEventListener("abort",o,{once:!0})})}function Pi(e){return{clientTools:Ot(e.tools),imageSearch:e.imageSearch,...e.composerDefaultModel?{modelId:e.composerDefaultModel}:{},newsSearch:e.newsSearch,webSearch:e.webSearch}}function Ii(e){return JSON.stringify(Pi(e))}function Qr(e,t=!1){return{Authorization:`Bearer ${e}`,...t?{"Content-Type":"application/json"}:{},"X-HeroUI-Agent-Protocol-Version":String(6),"X-HeroUI-Agent-SDK-Version":We}}async function Xn(e,t,n={}){let r=async()=>{let s=new Headers(n.headers);return s.set("Authorization",`Bearer ${await e.get()}`),s.set("X-HeroUI-Agent-Protocol-Version",String(6)),s.set("X-HeroUI-Agent-SDK-Version",We),fetch(t,{...n,headers:s})},o=await r();return o.status===401&&(e.clear(),o=await r()),o}function Mi(e){if(typeof e!="string"||!e)return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}var cp=/^sha256:[0-9a-f]{64}$/u;function xi(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.baseUrl!="string"||typeof t.path!="string"||typeof t.ticket!="string"||!t.baseUrl||!t.path||!t.ticket||!Mi(t.ticketExpiresAt)||!Mi(t.connectionExpiresAt)||typeof t.runtimeRevision!="string"||!cp.test(t.runtimeRevision))return null;try{let n=new URL(t.baseUrl);if(n.protocol!=="http:"&&n.protocol!=="https:")return null}catch{return null}return{baseUrl:t.baseUrl,connectionExpiresAt:t.connectionExpiresAt,path:t.path,runtimeRevision:t.runtimeRevision,ticket:t.ticket,ticketExpiresAt:t.ticketExpiresAt}}function up(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,n=t.conversation,r=xi(t.runtime);if(t.protocolVersion!==6||!n||typeof n!="object"||Array.isArray(n)||!r)return null;let o=n;return typeof o.id!="string"||typeof o.agentId!="string"||typeof o.projectId!="string"||!o.id||!o.agentId||!o.projectId||r.path!==`/v1/conversations/${encodeURIComponent(o.id)}/connect`?null:{conversation:{agentId:o.agentId,id:o.id,projectId:o.projectId},protocolVersion:6,runtime:r}}function dp(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return xi(t.runtime??t)}async function Ni(e,t,n){let r=new AbortController,o=Date.now()+Ri,s=globalThis.setTimeout(()=>r.abort(new Error("Assistant conversation bootstrap request timed out")),Ri),i=rp;try{for(;;){let d=await Xn(t,`${e.apiBaseUrl}/v1/conversations/${encodeURIComponent(n)}/bootstrap`,{body:JSON.stringify(Pi(e)),headers:{"Content-Type":"application/json"},method:"POST",signal:r.signal});if(!d.ok){let c=await d.json().catch(()=>null),m=typeof c?.code=="string"?c.code.toUpperCase():"";if(d.status===409&&wi.has(m))throw new qr(d.status,m);if(!ap(d.status))return null;let p=Date.now(),S=ip(d.headers.get("Retry-After"),p)??i;if(p+S>=o)return null;await lp(S,r.signal),i=Math.min(i*2,op);continue}let l=up(await d.json().catch(()=>null));return l?.conversation.id!==n||l?.conversation.agentId!==e.agentId?null:l}}finally{globalThis.clearTimeout(s)}}async function ki(e,t,n,r){let o=new AbortController,s=globalThis.setTimeout(()=>o.abort(new Error("Assistant connection ticket request timed out")),sp);try{let i=await Xn(t,`${e.apiBaseUrl}/v1/conversations/${encodeURIComponent(n)}/runtime-ticket`,{body:JSON.stringify({runtimeRevision:String(r)}),headers:{"Content-Type":"application/json"},method:"POST",signal:o.signal}),d=await i.json().catch(()=>null);if(!i.ok){let c=typeof d?.code=="string"?d.code.toUpperCase():"";throw i.status===409||c.includes("STALE")&&c.includes("REVISION")?new Tn:new Yn(i.status)}let l=dp(d);if(!l||l.runtimeRevision!==r||l.path!==`/v1/conversations/${encodeURIComponent(n)}/connect`)throw new Error("The assistant returned an invalid connection ticket");return l}finally{globalThis.clearTimeout(s)}}async function ke(e,t,n,r,o={}){try{await fetch(`${e.apiBaseUrl}/v1/agents/${encodeURIComponent(e.agentId)}/events`,{body:JSON.stringify({conversationId:n,event:r,properties:{...o,protocolVersion:6,sdkVersion:We}}),headers:Qr(await t.get(),!0),keepalive:!0,method:"POST"})}catch{}}function Rn(e,t=Eo){let n=new Set(t),o=e.filter(s=>Po(s.type)&&n.has(s.type.trim().toLowerCase())&&s.size>0&&s.size<=10485760).slice(0,5);return e.length>5?{error:`You can attach up to ${5} files at a time.`,files:o}:e.some(s=>!Po(s.type)||!n.has(s.type.trim().toLowerCase()))?{error:pp(t),files:o}:e.some(s=>s.size===0)?{error:"Empty files cannot be attached.",files:o}:e.some(s=>s.size>10485760)?{error:"Each attachment must be 10 MB or smaller.",files:o}:{error:null,files:o}}async function Oi({acceptedContentTypes:e=Eo,apiBaseUrl:t,conversationId:n,files:r,tokenManager:o}){if(r.length===0)return[];let s=Rn(r,e);if(s.error||s.files.length!==r.length)throw new Error(s.error??"One or more attachments are not supported.");return Promise.all(r.map(i=>mp({apiBaseUrl:t,conversationId:n,file:i,tokenManager:o})))}function pp(e){if(e.length===0)return"File attachments are disabled for this agent.";let t=e.map(o=>{let s=Ta[o];return s==="jpg"?"JPEG":s==="md"?"Markdown":s.toUpperCase()}),n=[...new Set(t)];return`Use ${n.length===1?n[0]:n.length===2?n.join(" or "):`${n.slice(0,-1).join(", ")}, or ${n.at(-1)}`} files.`}async function mp({apiBaseUrl:e,conversationId:t,file:n,tokenManager:r}){let o=`${e}/v1/conversations/${encodeURIComponent(t)}/attachments`;for(let s=0;s<2;s+=1){let i=await r.get(),d=await fetch(o,{body:n,headers:{Authorization:`Bearer ${i}`,"Content-Type":n.type,"X-HeroUI-Agent-Protocol-Version":String(6),"X-HeroUI-Agent-SDK-Version":We},method:"POST"});if(d.status===401&&s===0){r.clear();continue}if(!d.ok)throw new Error(await gp(d));let l=await d.json().catch(()=>null);if(typeof l?.url!="string")throw new Error("The attachment upload returned an invalid response.");return{filename:n.name,mediaType:n.type,type:"file",url:l.url}}throw new Error("The attachment could not be uploaded. Try again.")}async function gp(e){let t=await e.json().catch(()=>null);return typeof t?.error=="string"&&t.error.trim()?t.error:e.status===413?"Each attachment must be 10 MB or smaller.":e.status===415?"This attachment type is not supported.":"The attachment could not be uploaded. Try again."}import{z as xe}from"zod";var fp=64*1024,hp=15e3,yp=5*6e4,vp=xe.discriminatedUnion("action",[xe.object({action:xe.literal("execute"),claimId:xe.string().uuid(),idempotencyKey:xe.string().trim().min(1).max(160)}).strict(),xe.object({action:xe.literal("replay"),idempotencyKey:xe.string().trim().min(1).max(160),output:xe.unknown()}).strict(),xe.object({action:xe.literal("wait"),idempotencyKey:xe.string().trim().min(1).max(160),retryAfterMs:xe.number().int().min(25).max(5e3)}).strict()]),bp=xe.object({output:xe.unknown(),status:xe.enum(["completed","failed","interrupted"])}).strict();async function Di({activeToolCallIds:e,run:t,toolCallId:n}){if(e.has(n))return{status:"already-active"};e.add(n);try{return{status:"completed",value:await t()}}catch(r){throw e.delete(n),r}}function ls(e){return Array.isArray(e)?`[${e.map(ls).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${ls(n)}`).join(",")}}`:JSON.stringify(e)??"undefined"}async function Sp(e){return[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))].map(n=>n.toString(16).padStart(2,"0")).join("")}function Cp(e){return{error:e instanceof Error?e.message.slice(0,1e3):"The tool could not be executed"}}function Ap(e){let t=e??{done:!0},n;try{n=JSON.stringify(t)}catch{return{output:{error:"The client tool returned a non-serializable result"},status:"failed"}}return n===void 0?{output:{done:!0},status:"completed"}:new TextEncoder().encode(n).byteLength>fp?{output:{error:"The client tool result exceeded the 64 KiB limit"},status:"failed"}:{output:JSON.parse(n),status:"completed"}}function Li({approvalApproved:e,decision:t,needsApproval:n,state:r}){return r==="approval-responded"?e===!0:r!=="input-available"?!1:!n||t==="approved"}async function Tp(e){return Sp(ls(e))}function Hi({context:e,execution:t,input:n,tool:r}){return r.execute(Ar(r,n),e,t)}async function Ui({conversationId:e,execute:t,input:n,maxWaitMs:r=yp,now:o=Date.now,rpc:s,submitOutput:i,toolCallId:d,toolName:l,wait:c=m=>new Promise(p=>setTimeout(p,m))}){let m={inputHash:await Tp(n),protocolVersion:6,toolCallId:d,toolName:l},p=o(),S;for(;S=vp.parse(await s.claim(m)),S.action==="wait";){if(o()-p+S.retryAfterMs>r)throw new Error("Timed out waiting for the existing client tool execution");await c(S.retryAfterMs)}if(S.action==="replay")return await i(S.output),"replayed";let u={conversationId:e,idempotencyKey:S.idempotencyKey,toolCallId:d},h,x;try{({output:h,status:x}=Ap(await t(u)))}catch(A){x="failed",h=Cp(A)}let w;for(;;)try{w=bp.parse(await s.complete({...m,claimId:S.claimId,output:h,status:x}));break}catch(A){if(o()-p+250>r)throw A;await c(250)}return await i(w.output),"executed"}var cs=hp;var Rp=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;function Bi(e){return e.map(({description:t,inputSchema:n,name:r})=>({description:t,name:r,parameters:n}))}function Fi(e){return Object.fromEntries(Bi(e).map(({description:t,name:n,parameters:r})=>[n,{description:t,execute:()=>{throw new Error("HeroUI client tools execute through the approval-aware bridge")},parameters:r}]))}function Vi(e){try{let t=JSON.parse(e);return t.type!=="cf_agent_tool_approval"||t.approved!==!0||t.autoContinue!==!0?e:JSON.stringify({...t,autoContinue:!1})}catch{return e}}function us({clientSubmittedAt:e,clientTools:t,imageSearch:n,modelId:r,newsSearch:o,pageContext:s,permissionMode:i,turnId:d,webSearch:l}){if(!Rp.test(d))throw new Error("HeroUI Agent turnId must be a UUID");if(!Number.isSafeInteger(e)||e<=0)throw new Error("HeroUI Agent clientSubmittedAt must be a positive timestamp");return{clientSubmittedAt:e,clientTools:Bi(t),imageSearch:n,...r?{modelId:r}:{},newsSearch:o,pageContext:s,permissionMode:i,protocolVersion:6,requestId:d,sdkVersion:We,turnId:d,webSearch:l}}function $i(e){return e.replace(/^\/+|\/+$/g,"")}function Ki(e){let t=new URL(e.baseUrl),n=$i(t.pathname),r=$i(e.path);if(!r)throw new Error("The assistant returned an invalid connection path");return{basePath:n||r,host:t.host,...n?{path:r}:{},protocol:t.protocol==="http:"?"ws":"wss"}}function Gi(e,t){let n=e;return{next:async()=>{if(n){let r=n;return n=null,r}return t()},refresh:t}}function qi(e){if(typeof e.data!="string")return null;try{let t=JSON.parse(e.data);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Qi(e,{fillComposer:t,setSelection:n,submitPrompt:r}){return e.type==="followup"?(r(e.prompt),!0):e.type==="submit"?(n({componentId:e.componentId,componentTitle:e.componentTitle,datum:{actionId:e.actionId,values:e.values}}),e.prompt&&t(e.prompt),!0):e.type==="tool"?(t(e.prompt??e.label),!0):!1}function Mp(e){return e==="composeUI"||e==="renderComponent"}function ds(e){if(!e||typeof e!="object")return!1;let t=e,n=t.state;if(n!=="input-streaming"&&n!=="input-available")return!1;let r=t.type,o=r==="dynamic-tool"?t.toolName:typeof r=="string"&&r.startsWith("tool-")?r.slice(5):null;return Mp(o)}import{Xmark as $p}from"@gravity-ui/icons";import{File as wp,FileCode as Ep,FileLetterP as Pp,FileLetterW as Ip,FileLetterX as xp,FileText as Np,FileZipper as kp,MusicNote as _p,Picture as Op,Video as Dp}from"@gravity-ui/icons";var Lp=new Set(["csv","ods","xls","xlsm","xlsx"]),Hp=new Set(["doc","docx","odt","rtf"]),Up=new Set(["css","go","html","java","js","json","jsx","mdx","php","py","rb","rs","scss","sh","sql","swift","ts","tsx","xml","yaml","yml"]),Bp=new Set(["7z","bz2","gz","rar","tar","tgz","zip"]),Fp=new Set(["log","md","text","txt"]);function Vp(e){let t=e.trim().toLowerCase(),n=t.lastIndexOf(".");return n>0?t.slice(n+1):""}function zr(e){let t=Vp(e.name),n=e.type.toLowerCase();return Lp.has(t)||n.includes("csv")||n.includes("excel")||n.includes("spreadsheet")?{Icon:xp,kind:"spreadsheet",label:"Spreadsheet"}:t==="pdf"||n==="application/pdf"?{Icon:Pp,kind:"pdf",label:"PDF document"}:Hp.has(t)||n.includes("wordprocessingml")?{Icon:Ip,kind:"document",label:"Document"}:n.startsWith("image/")?{Icon:Op,kind:"image",label:"Image"}:n.startsWith("video/")?{Icon:Dp,kind:"video",label:"Video"}:n.startsWith("audio/")?{Icon:_p,kind:"audio",label:"Audio"}:Bp.has(t)||n.includes("zip")?{Icon:kp,kind:"archive",label:"Archive"}:Up.has(t)?{Icon:Ep,kind:"code",label:"Code file"}:Fp.has(t)||n.startsWith("text/")?{Icon:Np,kind:"text",label:"Text document"}:{Icon:wp,kind:"file",label:"File"}}import{jsx as Mn,jsxs as zi}from"react/jsx-runtime";function ps({file:e,onRemove:t}){let{Icon:n,kind:r,label:o}=zr(e);return zi("span",{className:"ha-attachment","data-kind":r,children:[Mn("span",{"aria-hidden":"true",className:"ha-attachment-icon",children:Mn(n,{})}),zi("span",{className:"ha-attachment-copy",children:[Mn("span",{className:"ha-attachment-name",title:e.name,children:e.name}),Mn("span",{className:"ha-attachment-type",children:o})]}),Mn("button",{"aria-label":`Remove ${e.name}`,type:"button",onClick:t,children:Mn($p,{"aria-hidden":"true"})})]})}import{Globe as Kp,Xmark as Gp}from"@gravity-ui/icons";import{jsx as ms,jsxs as Wi}from"react/jsx-runtime";function ji({onRemove:e,title:t}){return ms("div",{className:"ha-context",children:Wi("button",{"aria-label":`Remove Ask about this: ${t}`,className:"ha-chip",type:"button",onClick:e,children:[ms(Kp,{"aria-hidden":"true",className:"ha-chip-leading"}),Wi("span",{className:"ha-chip-title",title:t,children:["Ask about this: ",t]}),ms(Gp,{"aria-hidden":"true",className:"ha-chip-remove"})]})})}import{useCallback as Wr,useState as qp}from"react";import{jsx as Qp}from"react/jsx-runtime";function gs(e){return e.dataTransfer?.types?.includes("Files")??!1}function Yi({children:e,className:t,"data-controls-revealed":n,"data-dictating":r,"data-expanded":o,disabled:s=!1,onFileIntent:i,onFilesSelected:d}){let[l,c]=qp(!1),m=Wr(h=>{gs(h)&&(i?.(),!s&&(h.preventDefault(),c(!0)))},[s,i]),p=Wr(h=>{s||!gs(h)||(h.preventDefault(),h.dataTransfer.dropEffect="copy",c(!0))},[s]),S=Wr(h=>{let x=h.relatedTarget;x&&h.currentTarget.contains(x)||c(!1)},[]),u=Wr(h=>{gs(h)&&(i?.(),h.preventDefault(),c(!1),!(s||h.dataTransfer.files.length===0)&&d(Array.from(h.dataTransfer.files)))},[s,i,d]);return Qp("div",{className:t,"data-controls-revealed":n,"data-dictating":r,"data-dragging":l||void 0,"data-expanded":o,onDragEnterCapture:m,onDragLeaveCapture:S,onDragOverCapture:p,onDropCapture:u,children:e})}var fs="Enter";var Xi="Control+Shift+D";function Ji(e){return!e.defaultPrevented&&!e.isComposing&&!e.repeat&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&e.key==="Enter"}function Zi(e){return!e.defaultPrevented&&!e.isComposing&&!e.repeat&&!e.altKey&&e.ctrlKey&&!e.metaKey&&e.shiftKey&&e.key.toLowerCase()==="d"}function el(e,t){if(e.defaultPrevented||e.isComposing||e.repeat||e.altKey||!e.ctrlKey||e.metaKey||e.shiftKey)return null;let n=Number(e.key);return!Number.isInteger(n)||n<1||n>Math.min(t,9)?null:n-1}function hs(){return{activeTurnIds:new Set,busyIds:new Set,completedIds:new Set}}function tl(e,t){let{activeConversationId:n,busy:r,conversationId:o,failed:s,turnActive:i}=t,d=e.activeTurnIds.has(o),l=new Set(e.activeTurnIds),c=new Set(e.busyIds),m=new Set(e.completedIds);return r?c.add(o):c.delete(o),i?l.add(o):r||l.delete(o),(r||n===o)&&m.delete(o),!r&&d&&!s&&n!==o&&m.add(o),{activeTurnIds:l,busyIds:c,completedIds:m}}function ys(e,t){if(!e.completedIds.has(t))return e;let n=new Set(e.completedIds);return n.delete(t),{...e,completedIds:n}}function nl(e,t){if(!e.activeTurnIds.has(t)&&!e.busyIds.has(t)&&!e.completedIds.has(t))return e;let n=new Set(e.activeTurnIds),r=new Set(e.busyIds),o=new Set(e.completedIds);return n.delete(t),r.delete(t),o.delete(t),{activeTurnIds:n,busyIds:r,completedIds:o}}function rl(e,t,n=()=>crypto.randomUUID()){return e?.conversationEpoch===t?e:{conversationEpoch:t,conversationId:n()}}function jr({conversationEpoch:e,optimisticTarget:t,requestedConversationId:n,storedConversationId:r}){return n===null&&t?.conversationEpoch===e&&Rt(t.conversationId)?t.conversationId:Fo(n,r)}function ol({conversationEpoch:e,optimisticTarget:t,readyConversationId:n,readyEpoch:r,requestedConversationId:o}){if(r!==e)return null;let s=o===null?t?.conversationEpoch===e?t.conversationId:null:typeof o=="string"?o:n;return n===s?n:null}import{jsx as vs}from"react/jsx-runtime";function Yr({agentId:e,composerControlsAvailable:t,composerControlsRevealed:n,composerEndSlot:r,composerFooterSlot:o,composerStartSlot:s,greeting:i,loadingLabel:d,onComposerControlsReveal:l,placeholder:c,showStartScreen:m,suggestedPrompts:p}){return m?vs(Da,{composerConnecting:!0,agentId:e,composerControlsAvailable:t,composerControlsRevealed:n,composerEndSlot:r,composerFooterSlot:o,composerStartSlot:s,greeting:i,placeholder:c,suggestedPrompts:p,onComposerControlsReveal:l,onIntent:()=>{}}):vs("div",{className:"ha-loading",children:vs(tn,{className:"ha-progress ha-progress-shimmer",children:d})})}function zp(e,t){if(!e)return 1e3;let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.max(250,Math.ceil(n*1e3));let r=Date.parse(e);return Number.isFinite(r)?Math.max(250,r-t):1e3}async function sl({initialResponse:e,maxWaitMs:t=3e5,now:n=Date.now,request:r,sleep:o=s=>new Promise(i=>setTimeout(i,s))}){let s=n(),i=e;for(;i.status===409;){let d=zp(i.headers.get("Retry-After"),n());if(n()-s+d>t)return i;await o(d),i=await r()}return i}var Jn="Thinking\u2026";function al({activeStreamKey:e,activeTurnMessageId:t}){return e!==null&&t===null}function il({continuingAssistantMessageId:e,isActiveTurn:t,streamingAssistantMessageId:n,trackedActivityMessageId:r}){return t?n??r??e:null}function ll({hasActiveActivity:e,hasError:t,hasResponseStarted:n,isActiveTurn:r,messageCount:o,preferHomeWhileEmpty:s=!1,progress:i,runtimeStatus:d}){let l=o>0,c=!s&&!l&&(d==="pending"||d==="streaming"),m=!l&&!t&&!r&&!c;return e||n?{showHome:m,standaloneStatus:null}:r?{showHome:m,standaloneStatus:i??Jn}:c?{showHome:m,standaloneStatus:"Loading chat\u2026"}:{showHome:m,standaloneStatus:null}}import{jsx as Wp}from"react/jsx-runtime";function cl({activeConversationId:e,children:t,routes:n}){return Object.values(n).map(r=>{let o=r.conversationId===e;return Wp("div",{className:"ha-conversation-route","data-active":o||void 0,"data-conversation-route":r.conversationId,hidden:!o,children:t(r,o)},r.conversationId)})}function ul({isActive:e,lastUserMessageId:t,pendingTurn:n}){let r=t??null,o=n?r!==n.previousUserMessageId:r!==null,s=e?o?r:null:r;return{activeStreamKey:e?n?.scrollKey??null:null,activeTurnMessageId:s}}import{ChevronDown as tm}from"@gravity-ui/icons";import{Button as nm}from"@heroui/react";import{useLayoutEffect as rm,useRef as om}from"react";import{useCallback as Dt,useEffect as jp,useLayoutEffect as Yp,useRef as Ke,useState as Xp}from"react";var Lt=4,rn=1,dl="--ha-active-turn-spacer-height",pl='[data-role="user"][data-stream-anchor="true"]',Jp={hasOverflow:!1,isAtBottom:!0};function Zn(e){let t=e.scrollHeight-e.clientHeight>Lt,n=!t||e.scrollHeight-Math.max(0,e.scrollTop)-e.clientHeight<=Lt;return{hasOverflow:t,isAtBottom:n}}function Zp({anchorTop:e,clientHeight:t,contentHeight:n,paddingTop:r}){let o=Math.max(0,n-e);return Math.min(Math.max(t-o-r,0),t)}function em(e,t){return e.hasOverflow===t.hasOverflow&&e.isAtBottom===t.isAtBottom}function ml(e){return e==="smooth"&&!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"smooth":"auto"}function gl(e){let t=Ke(0),n=Ke(!0),r=Ke(!1),o=Ke(null),s=Ke(!1),i=Ke(!1),d=Ke(null),l=Ke(0),c=Ke(null),m=Ke(null),p=Ke(!1),S=Ke(!1),u=Ke(!1),[h,x]=Xp(Jp),w=Dt(b=>{x(f=>em(f,b)?f:b)},[]),A=Dt(b=>{t.current=0,b.style.removeProperty(dl)},[]),O=Dt(b=>{let f=c.current?b.querySelector(pl):null;if(!f)return t.current;let v=b.getBoundingClientRect(),y=f.getBoundingClientRect().top-v.top+b.scrollTop,M=b.scrollHeight-t.current,T=Number.parseFloat(window.getComputedStyle(b).paddingTop)||0,P=Zp({anchorTop:y,clientHeight:b.clientHeight,contentHeight:M,paddingTop:T});return Math.abs(P-t.current)>1&&(t.current=P,b.style.setProperty(dl,`${P}px`)),t.current},[]),_=Dt((b="smooth")=>{let f=e.current;if(!f)return;c.current=null,m.current=null,i.current=!1,p.current=!1,S.current=!1,u.current=!1,A(f),n.current=!0,r.current=!1,l.current=f.scrollTop,w({hasOverflow:Zn(f).hasOverflow,isAtBottom:!0});let v=f.scrollHeight,R=Math.max(0,v-f.clientHeight);s.current=Math.abs(Math.max(0,f.scrollTop)-R)>rn,typeof f.scrollTo=="function"?f.scrollTo({behavior:ml(b),top:v}):f.scrollTop=v,l.current=Math.max(0,f.scrollTop)},[A,e,w]),N=Dt(b=>{if(!c.current)return null;let f=b.querySelector(pl);if(f){let v=Number.parseFloat(window.getComputedStyle(b).paddingTop)||0;m.current=Math.max(0,f.offsetTop-v)}return m.current},[]),L=Dt((b,f,v="auto")=>{let R=Math.max(0,b.scrollHeight-b.clientHeight),y=Math.min(f,R),M=ml(v),T=Math.abs(Math.max(0,b.scrollTop)-y)>rn;i.current=M==="smooth"&&T,s.current=T,!T&&t.current>Lt&&(p.current=!0),l.current=b.scrollTop,w({hasOverflow:R>Lt,isAtBottom:R-y<=Lt}),typeof b.scrollTo=="function"?b.scrollTo({behavior:M,top:f}):(b.scrollTop=f,i.current=!1),l.current=Math.max(0,b.scrollTop)},[w]),$=Dt(()=>{let b=e.current;if(!b)return;O(b);let f=Zn(b),v=Math.max(0,b.scrollTop),R=v<l.current-rn;if(l.current=v,R&&!f.isAtBottom){n.current=!1,r.current=!0,s.current=!1,i.current=!1,c.current=null,m.current=null,S.current=!1,w(f);return}!r.current&&(!f.hasOverflow||f.isAtBottom)&&(n.current=!0);let y=c.current!==null,M=N(b);if(y){if(r.current=!0,M!==null&&i.current){let T=Math.max(0,b.scrollHeight-b.clientHeight),P=Math.min(M,T);if(Math.abs(v-P)>rn){w({hasOverflow:f.hasOverflow,isAtBottom:!0});return}s.current=!1,i.current=!1,p.current=t.current>Lt}if(M!==null&&S.current){S.current=!1,L(b,M,"smooth");return}n.current=!1,w(f);return}if(n.current&&!r.current){_("auto");return}w(f)},[N,e,_,L,w,O]),X=Dt(b=>{let f=e.current;if(!f||o.current===b)return;let v=o.current!==null;if(o.current=b,b)p.current=!1,d.current!==b?(d.current=b,c.current=b,m.current=null,S.current=!0,u.current=!1,r.current=!0,n.current=!0):(c.current=null,m.current=null,S.current=!1);else if(v){c.current=null,m.current=null,s.current=!1,i.current=!1,p.current=t.current>Lt,S.current=!1,r.current=!0;let R=Zn(f);n.current=!1,w(R)}},[e,w]);return Yp(()=>{let b=e.current;b&&(l.current=b.scrollTop,$(),r.current=!0,n.current=!1)},[$,e]),jp(()=>{let b=e.current;if(!b)return;let f=()=>{let F=Math.max(0,b.scrollTop);s.current&&typeof b.scrollTo=="function"&&b.scrollTo({behavior:"auto",top:F}),u.current=!0,n.current=!1,r.current=!0,s.current=!1,i.current=!1,c.current=null,m.current=null,S.current=!1,l.current=F,w(Zn(b))},v=F=>{F.deltaY<0&&f()},R=null,y=F=>{R=F.touches[0]?.clientY??null},M=F=>{let K=F.touches[0]?.clientY??null;R!==null&&K!==null&&K>R&&f(),R=K},T=()=>{let F=Zn(b),K=Math.max(0,b.scrollTop),ye=K<l.current-rn,Se=K>l.current+rn;if(l.current=K,u.current){F.isAtBottom&&Se&&!p.current?(u.current=!1,n.current=!0,r.current=!1):(n.current=!1,r.current=!0),w(F);return}if(p.current){s.current=!1,i.current=!1,n.current=!1,r.current=!0,w(F);return}if(s.current&&!ye){let H=N(b),B=Math.max(0,b.scrollHeight-b.clientHeight),D=Math.min(H??B,B),k=F.isAtBottom||Math.abs(K-D)<=rn,Y=i.current;k&&(s.current=!1,i.current=!1,H!==null&&(p.current=t.current>Lt,r.current=!0,n.current=!1)),w(Y&&!k?{hasOverflow:F.hasOverflow,isAtBottom:!0}:H===null?r.current?F:{hasOverflow:F.hasOverflow,isAtBottom:n.current}:F);return}s.current=!1,i.current=!1,c.current=null,m.current=null,S.current=!1,n.current=F.isAtBottom,r.current=!F.isAtBottom,w(F)};b.addEventListener("scroll",T,{passive:!0}),b.addEventListener("touchmove",M,{passive:!0}),b.addEventListener("touchstart",y,{passive:!0}),b.addEventListener("wheel",v,{passive:!0});let P,z=new Set,ie=()=>{if(!P)return;let F=new Set(Array.from(b.children));for(let K of z)F.has(K)||(P.unobserve(K),z.delete(K));for(let K of F)z.has(K)||(P.observe(K),z.add(K))};typeof ResizeObserver<"u"&&(P=new ResizeObserver($),P.observe(b),ie());let j=typeof MutationObserver>"u"?void 0:new MutationObserver(F=>{F.some(K=>K.type==="childList"&&K.target===b)&&ie(),$()});return j?.observe(b,{characterData:!0,childList:!0,subtree:!0}),()=>{b.removeEventListener("scroll",T),b.removeEventListener("touchmove",M),b.removeEventListener("touchstart",y),b.removeEventListener("wheel",v),j&&j.disconnect(),P&&P.disconnect()}},[N,$,e,w]),{hasOverflow:h.hasOverflow,isAtBottom:h.isAtBottom,maintainScrollPosition:$,scrollToBottom:_,setPinnedStream:X}}import{jsx as Xr,jsxs as sm}from"react/jsx-runtime";function fl({activityPhase:e=null,children:t,streamKey:n=null}){let r=om(null),{hasOverflow:o,isAtBottom:s,maintainScrollPosition:i,scrollToBottom:d,setPinnedStream:l}=gl(r),c=o&&!s;return nn(r),rm(()=>{l(n),i()},[t,i,l,n]),sm("div",{className:"ha-conversation","data-activity-phase":e??void 0,children:[Xr("div",{ref:r,"aria-live":"polite",className:"ha-messages",role:"log",children:t}),Xr("div",{"aria-hidden":c?void 0:!0,className:"ha-scroll-button-container","data-state":c?"visible":"hidden",children:Xr(nm,{isIconOnly:!0,"aria-hidden":c?void 0:!0,"aria-label":"Scroll to bottom",className:"ha-scroll-button",isDisabled:!c,size:"sm",variant:"secondary",onPress:()=>d("smooth"),children:Xr(tm,{"aria-hidden":"true"})})})]})}import{Suspense as am,lazy as im}from"react";var bs;function Ss(){return bs??=import("./component-renderer-GG6JVRUG.js").then(e=>({default:e.ComponentRenderer})),bs}function hl(){Ss().catch(()=>{bs=void 0})}import{jsx as yl}from"react/jsx-runtime";var lm=im(Ss);function vl(e){return yl(am,{fallback:null,children:yl(lm,{...e})})}import{ArrowsRotateLeft as cm,Check as um,Copy as dm,ThumbsDown as pm,ThumbsUp as mm}from"@gravity-ui/icons";import{Button as Jr,Popover as Zr,TextArea as gm}from"@heroui/react";import{useCallback as fm,useEffect as hm,useRef as bl,useState as er}from"react";import{Fragment as Sm,jsx as Re,jsxs as tr}from"react/jsx-runtime";var ym=2e3,vm=1e3,bm=[{label:"Incorrect",value:"incorrect"},{label:"Off topic",value:"not_relevant"},{label:"Missing details",value:"incomplete"},{label:"Unclear",value:"unclear"},{label:"Missed instructions",value:"did_not_follow_instructions"},{label:"Other",value:"other"}];function Sl({actions:e,feedback:t,onCopy:n,onFeedback:r,onRetry:o}){let[s,i]=er(!1),[d,l]=er(!1),[c,m]=er(""),[p,S]=er([]),[u,h]=er(),x=bl(null),w=bl(0),A=fm(f=>{h(f?.closest(".ha-panel")??void 0)},[]);hm(()=>()=>{x.current!==null&&window.clearTimeout(x.current)},[]);let O=e.includes("copy")&&n,_=e.includes("feedback")&&r,N=e.includes("retry")&&o;if(!O&&!_&&!N)return null;let L=()=>{n?.(),i(!0),x.current!==null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{i(!1),x.current=null},ym)},$=f=>{!f&&Date.now()-w.current<350||l(f)},X=f=>{S(v=>v.includes(f)?v.filter(R=>R!==f):[...v,f])},b=()=>{let f=c.trim();r?.("down",{...f?{comment:f}:{},reasons:p}),l(!1)};return tr("div",{"aria-label":"Message actions",className:"ha-message-actions",role:"group",children:[O?Re("button",{"aria-label":s?"Copied":"Copy response",className:"ha-message-action","data-copied":s||void 0,type:"button",onClick:L,children:Re("span",{className:"ha-message-action-icon",children:s?Re(um,{"aria-hidden":"true"}):Re(dm,{"aria-hidden":"true"})},s?"check":"copy")}):null,_?tr(Sm,{children:[Re("button",{"aria-label":"Good response","aria-pressed":t==="up",className:"ha-message-action","data-selected":t==="up"||void 0,type:"button",onClick:()=>r?.("up"),children:Re(mm,{"aria-hidden":"true"})}),tr(Zr,{isOpen:d,onOpenChange:$,children:[Re(Jr,{ref:A,isIconOnly:!0,"aria-label":"Bad response","aria-pressed":t==="down",className:"ha-message-action ha-feedback-trigger","data-open":d||void 0,"data-selected":t==="down"||void 0,size:"sm",variant:"ghost",onPointerDown:()=>{w.current=Date.now()},children:Re(pm,{"aria-hidden":"true"})}),Re(Zr.Content,{className:"ha-feedback-popover",offset:8,placement:"top start",UNSTABLE_portalContainer:u,children:tr(Zr.Dialog,{className:"ha-feedback-dialog",children:[Re(Zr.Heading,{className:"ha-feedback-heading",children:"Help us improve"}),Re("p",{className:"ha-feedback-description",children:"What could be better?"}),Re("div",{"aria-label":"Feedback reasons",className:"ha-feedback-reasons",role:"group",children:bm.map(f=>{let v=p.includes(f.value);return Re(Jr,{"aria-pressed":v,className:"ha-feedback-reason",size:"sm",variant:v?"secondary":"outline",onPress:()=>X(f.value),children:f.label},f.value)})}),Re(gm,{fullWidth:!0,"aria-label":"Additional feedback",className:"ha-feedback-textarea",maxLength:vm,placeholder:"Add details (optional)",rows:3,value:c,variant:"secondary",onChange:f=>m(f.target.value)}),Re("p",{className:"ha-feedback-privacy",children:"Avoid sharing sensitive information."}),tr("div",{className:"ha-feedback-footer",children:[Re(Jr,{className:"ha-feedback-cancel",size:"sm",variant:"ghost",onPress:()=>l(!1),children:"Cancel"}),Re(Jr,{className:"ha-feedback-submit",size:"sm",variant:"primary",onPress:b,children:t==="down"?"Update":"Send"})]})]})})]})]}):null,N?Re("button",{"aria-label":"Retry response",className:"ha-message-action",type:"button",onClick:o,children:Re(cm,{"aria-hidden":"true"})}):null]})}import{jsx as wn,jsxs as Cl}from"react/jsx-runtime";function Cs({file:e}){let t=e.filename?.trim()||"Attachment",n=e.mediaType?.trim()||"",{Icon:r,kind:o,label:s}=zr({name:t,type:n});return o==="image"?wn("a",{"aria-label":`Open ${t}`,className:"ha-message-image",download:e.filename,href:e.url,rel:"noopener noreferrer",target:"_blank",title:t,children:wn("span",{"aria-hidden":"true",style:{backgroundImage:`url(${JSON.stringify(e.url)})`}})}):Cl("a",{className:"ha-message-file","data-kind":o,download:e.filename,href:e.url,rel:"noopener noreferrer",target:"_blank",children:[wn("span",{"aria-hidden":"true",className:"ha-message-file-icon",children:wn(r,{})}),Cl("span",{className:"ha-message-file-copy",children:[wn("span",{className:"ha-message-file-name",title:t,children:t}),wn("span",{className:"ha-message-file-type",children:s})]})]})}function on(){return{blockedMessageId:null,isPaused:!1,messages:[]}}function As(e,t,n="append"){return e.messages.some(r=>r.id===t.id)?e:{...e,messages:n==="prepend"?[t,...e.messages]:[...e.messages,t]}}function nr(e,t){return e.messages.findIndex(r=>r.id===t)===-1?e:{...e,blockedMessageId:e.blockedMessageId===t?null:e.blockedMessageId,messages:e.messages.filter(r=>r.id!==t)}}function Al(e,t,n,r){let o=e.messages.findIndex(m=>m.id===t),s=e.messages.findIndex(m=>m.id===n);if(o===-1||s===-1||o===s)return e;let i=[...e.messages],[d]=i.splice(o,1),c=i.findIndex(m=>m.id===n)+(r==="after"?1:0);return i.splice(c,0,d),i.every((m,p)=>m.id===e.messages[p]?.id)?e:{...e,messages:i}}function rr(e,t){return e.isPaused===t?e:{...e,isPaused:t}}function ht(e,t){return e.blockedMessageId===t?e:{...e,blockedMessageId:t}}function Tl(e){let t=e.text.trim();return t||`${e.files.length} attachment${e.files.length===1?"":"s"}`}function yt(e){return e.deliveryStatus??"pending"}function En(e,t,n){let r=e.messages.findIndex(s=>s.id===t);if(r===-1||yt(e.messages[r])===n)return e;let o=[...e.messages];return o[r]={...o[r],deliveryStatus:n},{...e,messages:o}}var Cm="heroui-agent-message-outbox",Am=1,Ht="conversation-outboxes",Tm=":message-outbox:",sn=new Map;function Ts(e,t){return`${e}${Tm}${t}:v1`}async function Rl(e){await sn.get(e)?.catch(()=>{});let t=await Ms();if(!t)return on();try{let n=t.transaction(Ht,"readonly"),r=await xm(n.objectStore(Ht).get(e));return await ws(n),Rm(r,e)}catch{return on()}finally{t.close()}}function Rs(e,t,n=Date.now()){return Pl(e,async()=>{let r=t.messages.length>0?await Mm(t):null,o=await Ms();if(!o)throw new Error("Durable message storage is unavailable");try{let s=o.transaction(Ht,"readwrite"),i=s.objectStore(Ht);t.messages.length===0?i.delete(e):i.put({key:e,savedAt:n,state:r}),await ws(s)}finally{o.close()}})}function Ml(e){return Pl(e,async()=>{let t=await Ms();if(t)try{let n=t.transaction(Ht,"readwrite");n.objectStore(Ht).delete(e),await ws(n)}finally{t.close()}})}function wl(e,t){let n=new Set(t.messages.map(o=>o.id)),r=[...e.messages.filter(o=>!n.has(o.id)),...t.messages];return{blockedMessageId:t.blockedMessageId??e.blockedMessageId,isPaused:t.isPaused||e.isPaused,messages:r}}function El(e,t){let n=e.messages.filter(o=>!t.has(o.id)).map(o=>yt(o)==="sending"?{...o,deliveryStatus:"pending"}:o),r=new Set(n.map(o=>o.id));return{...e,blockedMessageId:e.blockedMessageId&&r.has(e.blockedMessageId)?e.blockedMessageId:null,messages:n}}function Rm(e,t){if(!e||typeof e!="object")return on();let n=e,r=n.state;if(n.key!==t||typeof n.savedAt!="number"||!r||typeof r!="object"||typeof r.isPaused!="boolean"||!Array.isArray(r.messages))return on();let o=r.messages.map(Em).filter(i=>i!==null),s=new Set(o.map(i=>i.id));return{blockedMessageId:typeof r.blockedMessageId=="string"&&s.has(r.blockedMessageId)?r.blockedMessageId:null,isPaused:r.isPaused,messages:o}}async function Mm(e){return{blockedMessageId:e.blockedMessageId,isPaused:e.isPaused,messages:await Promise.all(e.messages.map(async t=>({...t,files:await Promise.all(t.files.map(wm))})))}}async function wm(e){return{bytes:await e.arrayBuffer(),lastModified:e.lastModified,name:e.name,type:e.type}}function Em(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.id=="string"&&t.id.length>0&&typeof t.text=="string"&&Array.isArray(t.files)&&(t.isInitialTurn===void 0||typeof t.isInitialTurn=="boolean")&&(t.deliveryStatus===void 0||t.deliveryStatus==="pending"||t.deliveryStatus==="sending"||t.deliveryStatus==="admitted")){let n=t.files.map(Pm).filter(r=>r!==null);return n.length!==t.files.length?null:{...t,files:n}}return null}function Pm(e){if(typeof File<"u"&&e instanceof File)return e;if(typeof File>"u"||!e||typeof e!="object")return null;let t=e;return!Im(t.bytes)||typeof t.lastModified!="number"||typeof t.name!="string"||typeof t.type!="string"?null:new File([t.bytes],t.name,{lastModified:t.lastModified,type:t.type})}function Im(e){return Object.prototype.toString.call(e)==="[object ArrayBuffer]"}function Pl(e,t){let r=(sn.get(e)??Promise.resolve()).catch(()=>{}).then(t);return sn.set(e,r),r.then(()=>{sn.get(e)===r&&sn.delete(e)},()=>{sn.get(e)===r&&sn.delete(e)}),r}function Ms(){return typeof indexedDB>"u"?Promise.resolve(null):new Promise((e,t)=>{let n=indexedDB.open(Cm,Am);n.onerror=()=>t(n.error??new Error("Unable to open message outbox")),n.onupgradeneeded=()=>{let r=n.result;r.objectStoreNames.contains(Ht)||r.createObjectStore(Ht,{keyPath:"key"})},n.onsuccess=()=>e(n.result)})}function xm(e){return new Promise((t,n)=>{e.onerror=()=>n(e.error??new Error("IndexedDB request failed")),e.onsuccess=()=>t(e.result)})}function ws(e){return new Promise((t,n)=>{e.onabort=()=>n(e.error??new Error("IndexedDB write aborted")),e.onerror=()=>n(e.error??new Error("IndexedDB transaction failed")),e.oncomplete=()=>t()})}function Il({hasChatError:e,hasPendingClientToolCalls:t,hasReadyClientToolContinuation:n,isLocalPending:r,isResuming:o,isRunning:s,recoveryError:i}){return o||s||t||r||n&&!i&&!e}function xl(e,t){return e.text?{files:t,text:e.text}:{files:t}}function Nl(e){let t=e.text.trim();return t||`${e.files.length} attachment${e.files.length===1?"":"s"}`}function kl({activeMessageId:e,authoritativeMessageCount:t,isNewChatStartScreen:n,queuedMessageCount:r}){return n&&t===0&&r===0&&e===null}function _l({authoritativeMessageCount:e,localTurn:t,queue:n}){return e>0?null:t??n.messages.find(o=>o.isInitialTurn&&yt(o)!=="admitted")??null}function Ol(e,t){return e.messages.filter(n=>yt(n)==="pending"&&(n.id!==t||e.isPaused||e.blockedMessageId===t))}function Dl({isClientTool:e,state:t}){return e&&(t==="input-streaming"||t==="input-available"||t==="approval-requested"||t==="approval-responded")}function Ll({activeMessageId:e,isBusy:t,isReordering:n=!1,queue:r}){return e||t||n||r.isPaused||r.blockedMessageId||r.messages.length===0||r.messages.some(o=>yt(o)==="sending")?null:r.messages.find(o=>yt(o)==="pending")??null}function Hl(e,t){return e.key!=="ArrowUp"||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||e.nativeEvent.isComposing||!t?.focusLastMessage()?!1:(e.preventDefault(),!0)}import{ArrowUp as Nm,CircleExclamation as km,Clock as _m,Grip as Om,Pencil as Dm,TrashBin as Lm}from"@gravity-ui/icons";import{useImperativeHandle as Hm,useLayoutEffect as Um,useRef as Es}from"react";import{useRef as eo,useState as to}from"react";function Ul({messages:e,onReorder:t,onReorderStateChange:n}){let r=eo(null),o=eo(null),s=eo(null),i=eo(null),[d,l]=to(""),[c,m]=to(null),[p,S]=to(null),[u,h]=to(null),x=v=>{o.current=v,S(v)},w=()=>{let v=r.current!==null;r.current=null,m(null),x(null),v&&n?.(s.current!==null)},A=(v,R,y)=>{let M=e.findIndex(P=>P.id===v)+1,T=e.findIndex(P=>P.id===R)+1;l(`Moved queued message ${M} ${y} queued message ${T}.`)},O=(v,R,y)=>{let M=e.findIndex(z=>z.id===v),T=e.findIndex(z=>z.id===R),P=y==="before"&&M===T-1||y==="after"&&M===T+1;M===-1||T===-1||M===T||P||(t(v,R,y),A(v,R,y))},_=(v,R)=>{e.length<2||v.pointerType==="mouse"&&v.button!==0||(v.currentTarget.setPointerCapture?.(v.pointerId),r.current={hasMoved:!1,messageId:R,pointerId:v.pointerId,startX:v.clientX,startY:v.clientY},s.current=null,h(null),m(R),x(null),n?.(!0))},N=v=>{let R=r.current;if(!R||R.pointerId!==v.pointerId||!R.hasMoved&&Math.hypot(v.clientX-R.startX,v.clientY-R.startY)<4)return;R.hasMoved=!0;let y=v.currentTarget.closest(".ha-message-queue"),M=0;if(y){let F=y.getBoundingClientRect(),K=28;v.clientY<F.top+K?M=-12:v.clientY>F.bottom-K&&(M=12)}let z=v.currentTarget.getRootNode().elementFromPoint?.(v.clientX,v.clientY)?.closest("[data-queue-message-id]"),ie=z?.dataset.queueMessageId,j=null;if(z&&ie&&ie!==R.messageId){let F=z.getBoundingClientRect(),K=v.clientY<F.top+F.height/2?"before":"after";j={messageId:ie,position:K}}if(y&&M!==0&&(y.scrollTop+=M),!j){x(null);return}o.current?.messageId===j.messageId&&o.current.position===j.position||x(j)},L=(v,R)=>{let y=r.current;if(!y||y.pointerId!==v.pointerId)return;v.currentTarget.hasPointerCapture?.(v.pointerId)&&v.currentTarget.releasePointerCapture?.(v.pointerId);let M=o.current;R&&y.hasMoved&&(i.current=y.messageId),R&&y.hasMoved&&M&&O(y.messageId,M.messageId,M.position),w()},$=(v,R,y)=>{let M=v.key==="ArrowUp"?-1:v.key==="ArrowDown"?1:0;if(!M)return;let T=e[y+M];T&&(v.preventDefault(),O(R,T.id,M===-1?"before":"after"))},X=v=>{let R=i.current===v;if(i.current=null,R)return;let y=s.current===v?null:v;s.current=y,h(y),n?.(r.current!==null||y!==null)},b=v=>{s.current===v&&(s.current=null,h(null),n?.(r.current!==null))};return{announcement:d,closePositionPicker:b,draggedMessageId:c,dropTarget:p,finishPointerDrag:L,handleReorderKeyDown:$,moveMessageToPosition:(v,R,y)=>{let M=e[y];if(!M||R===y){b(v);return}O(v,M.id,R<y?"after":"before"),b(v)},positionPickerMessageId:u,startPointerDrag:_,togglePositionPicker:X,updatePointerDrag:N}}import{jsx as Ie,jsxs as or}from"react/jsx-runtime";function no(e,t){let n=e?.querySelectorAll("[data-queue-message-id]")[t];return n?(n.focus({preventScroll:!0}),n.scrollIntoView?.({block:"nearest"}),!0):!1}function Bl({blockedMessageId:e,isSendNowDisabled:t,messages:n,onEdit:r,onFocusComposer:o,onRemove:s,onReorder:i,onReorderStateChange:d,onSendNow:l,ref:c}){let m=Es(null),p=Es(null),S=Es(n),{announcement:u,closePositionPicker:h,draggedMessageId:x,dropTarget:w,finishPointerDrag:A,handleReorderKeyDown:O,moveMessageToPosition:_,positionPickerMessageId:N,startPointerDrag:L,togglePositionPicker:$,updatePointerDrag:X}=Ul({messages:n,onReorder:i,onReorderStateChange:d});if(Hm(c,()=>({focusLastMessage:()=>no(p.current,n.length-1)}),[n.length]),Um(()=>{let f=S.current;S.current=n;let v=m.current;if(!v||n.some(M=>M.id===v))return;let R=f.findIndex(M=>M.id===v),y=Math.min(R,n.length-1);m.current=null,(R<0||!no(p.current,y))&&o()},[n,o]),n.length===0)return null;let b=(f,v)=>{if(f.target===f.currentTarget&&!(f.key!=="ArrowUp"&&f.key!=="ArrowDown")){if(f.preventDefault(),f.key==="ArrowUp"){no(p.current,v-1);return}no(p.current,v+1)||o()}};return or("section",{"aria-label":"Queued messages",className:"ha-message-queue",children:[Ie("div",{className:"ha-message-queue-header",children:"Queued"}),Ie("ol",{ref:p,className:"ha-message-queue-list",children:n.map((f,v)=>{let R=e===f.id,y=v+1,M=R?`ha-queued-message-status-${f.id}`:void 0;return or("li",{"aria-describedby":M,"aria-keyshortcuts":"ArrowUp ArrowDown",className:"ha-message-queue-item","data-blocked":R?"true":void 0,"data-dragging":x===f.id?"true":void 0,"data-queue-message-id":f.id,tabIndex:-1,title:R?"This message could not be sent":void 0,"data-drop-position":w?.messageId===f.id?w.position:void 0,onKeyDown:T=>b(T,v),onBlur:T=>{let P=T.relatedTarget;m.current===f.id&&(!P||!T.currentTarget.contains(P))&&(m.current=null)},onFocus:()=>{m.current=f.id},children:[Ie("button",{"aria-keyshortcuts":"ArrowUp ArrowDown","aria-label":`Reorder queued message ${y}`,className:"ha-message-queue-drag-handle",disabled:n.length<2,title:n.length>1?"Drag to reorder or click for options":void 0,type:"button",onClick:()=>$(f.id),onKeyDown:T=>O(T,f.id,v),onPointerCancel:T=>A(T,!1),onPointerDown:T=>L(T,f.id),onPointerMove:X,onPointerUp:T=>A(T,!0),children:Ie(Om,{"aria-hidden":"true"})}),N===f.id?Ie("select",{autoFocus:!0,"aria-label":`Move queued message ${y} to position`,className:"ha-message-queue-position-select",value:v,onBlur:()=>h(f.id),onChange:T=>_(f.id,v,Number(T.currentTarget.value)),children:n.map((T,P)=>or("option",{value:P,children:["Position ",P+1,P===v?" (current)":""]},T.id))}):Ie("span",{"aria-hidden":"true",className:"ha-message-queue-icon",children:R?Ie(km,{"aria-hidden":"true"}):Ie(_m,{"aria-hidden":"true"})}),or("span",{className:"ha-message-queue-content",children:[Ie("span",{className:"ha-message-queue-preview",children:Tl(f)}),R?Ie("span",{className:"ha-message-queue-status",id:M,role:"status",children:"Could not send"}):null]}),or("span",{className:"ha-message-queue-actions",children:[Ie("button",{"aria-label":`Send queued message ${y} now`,className:"ha-message-queue-action",disabled:t,title:"Send now",type:"button",onClick:()=>l(f.id),children:Ie(Nm,{"aria-hidden":"true"})}),Ie("button",{"aria-label":`Edit queued message ${y}`,className:"ha-message-queue-action",title:"Edit",type:"button",onClick:()=>r(f.id),children:Ie(Dm,{"aria-hidden":"true"})}),Ie("button",{"aria-label":`Remove queued message ${y}`,className:"ha-message-queue-action",title:"Remove",type:"button",onClick:()=>s(f.id),children:Ie(Lm,{"aria-hidden":"true"})})]})]},f.id)})}),Ie("span",{"aria-live":"polite",className:"ha-message-queue-announcement",role:"status",children:u})]})}import{FileText as qm}from"@gravity-ui/icons";import Wl,{createContext as Qm,useContext as zm,useMemo as Wm}from"react";import{composeRenderProps as jm}from"react-aria-components";import{mergeRefs as Bm}from"@react-aria/utils";import{useControlledState as Fm}from"@react-stately/utils";import{createContext as Vm,useCallback as Xe,useContext as Vl,useEffect as Fl,useMemo as $l,useRef as ro,useState as $m}from"react";import{OverlayArrow as Km,Popover as Gm,composeRenderProps as Kl}from"react-aria-components";import{jsx as Pn}from"react/jsx-runtime";var Ps=Vm({handleCancelClose:()=>{},handleClose:()=>{},handleOpen:()=>{},isOpen:!1,isPointerInsideRef:{current:!1},setPortalContainer:()=>{},triggerRef:{current:null}}),Is=({children:e,closeDelay:t=300,defaultOpen:n=!1,onOpenChange:r,open:o,openDelay:s=700})=>{let[i,d]=Fm(o,n,r),[l,c]=$m(),m=ro(null),p=ro(!1),S=ro(void 0),u=ro(void 0),h=Xe(()=>{clearTimeout(S.current),clearTimeout(u.current)},[]);Fl(()=>h,[h]),Fl(()=>{if(!i)return;let _=N=>{N.key==="Escape"&&(d(!1),h())};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[h,i,d]);let x=Xe((_=!1)=>{h(),_||s<=0?d(!0):S.current=setTimeout(()=>d(!0),s)},[h,s,d]),w=Xe((_=!1)=>{h(),_||t<=0?d(!1):u.current=setTimeout(()=>d(!1),t)},[h,t,d]),A=Xe(()=>{clearTimeout(u.current)},[]),O=$l(()=>({handleCancelClose:A,handleClose:w,handleOpen:x,isOpen:i,isPointerInsideRef:p,portalContainer:l,setPortalContainer:c,triggerRef:m}),[A,w,x,i,l]);return Pn(Ps,{value:O,children:e})},Gl=({children:e,className:t,onBlur:n,onFocus:r,onPointerEnter:o,onPointerLeave:s,ref:i,...d})=>{let{handleClose:l,handleOpen:c,isPointerInsideRef:m,setPortalContainer:p,triggerRef:S}=Vl(Ps),u=Xe(_=>{S.current=_,p(bn(_))},[p,S]),h=$l(()=>Bm(i,u),[i,u]),x=Xe(_=>{_.pointerType==="mouse"&&c(),o?.(_)},[c,o]),w=Xe(_=>{_.pointerType==="mouse"&&l(),s?.(_)},[l,s]),A=Xe(_=>{c(!0),r?.(_)},[c,r]),O=Xe(_=>{m.current||l(),n?.(_)},[l,m,n]);return Pn("span",{ref:h,className:me("aui-hover-card__trigger",t),"data-slot":"hover-card-trigger",onBlur:O,onFocus:A,onPointerEnter:x,onPointerLeave:w,...d,children:e})},ql=({UNSTABLE_portalContainer:e,children:t,className:n,offset:r=8,onOpenChange:o,onPointerEnter:s,onPointerLeave:i,placement:d="top",...l})=>{let{handleCancelClose:c,handleClose:m,isOpen:p,isPointerInsideRef:S,portalContainer:u,triggerRef:h}=Vl(Ps),x=Xe(O=>{S.current=!0,c(),s?.(O)},[c,S,s]),w=Xe(O=>{S.current=!1,m(),i?.(O)},[m,S,i]),A=Xe(O=>{O||m(!0),o?.(O)},[m,o]);return Pn(Gm,{isNonModal:!0,"data-slot":"hover-card-content",isOpen:p,offset:r,placement:d,triggerRef:h,UNSTABLE_portalContainer:e??u,className:Kl(n,O=>me("aui-hover-card__content",O)??""),onOpenChange:A,onPointerEnter:x,onPointerLeave:w,...l,children:O=>typeof t=="function"?t(O):t})},Ql=({children:e,className:t,...n})=>Pn(Km,{"data-slot":"hover-card-arrow",className:Kl(t,r=>me("aui-hover-card__arrow",r)??""),...n,children:e??Pn("svg",{fill:"none",height:"12",viewBox:"0 0 12 12",width:"12",xmlns:"http://www.w3.org/2000/svg",children:Pn("path",{d:"M0 0C5.48483 8 6.5 8 12 0Z"})})});var sr=Object.assign(Is,{Arrow:Ql,Content:ql,Root:Is,Trigger:Gl});function zl(e){try{return new URL(e).hostname.replace(/^www\./,"")}catch{return e.split("/").pop()||e}}import{Fragment as xs,jsx as ae,jsxs as Ut}from"react/jsx-runtime";var jl=Qm({sourceType:"url"}),ar=()=>zm(jl);function Ym(e){return e.trim().charAt(0).toUpperCase()||"?"}var Ns=({children:e,className:t,description:n,enablePreview:r,faviconUrl:o,href:s,locator:i,sourceType:d=s?"url":"document",title:l,...c})=>{let m=s?zl(s):void 0,S=r??(d==="url"&&!!s?!!(n||l):!!(n||i)),u=Wm(()=>({description:n,domain:m,enablePreview:S,faviconUrl:o,href:s,locator:i,sourceType:d,title:l}),[n,m,S,o,s,i,d,l]),h=e??Ut(xs,{children:[ae(ks,{}),S?ae(_s,{description:n,title:l}):null]}),x=ae("div",{className:me("aui-chat-source",t),"data-has-locator":i?"true":void 0,"data-slot":"chat-source","data-source-type":d,...c,children:h});return ae(jl,{value:u,children:S?ae(sr,{closeDelay:0,openDelay:150,children:x}):x})},ks=({children:e,className:t,label:n,...r})=>{let{domain:o,enablePreview:s,href:i,locator:d,sourceType:l,title:c}=ar(),m=l==="url"&&i,p=e??n??(m?Ut(xs,{children:[ae(ao,{}),ae(so,{children:c??o}),d?ae(oo,{children:d}):null]}):Ut(xs,{children:[ae(io,{}),ae(so,{children:c}),d?ae(oo,{children:d}):null]}));if(m){let h=ae("a",{"aria-label":`Open source: ${c??o??i}`,className:"aui-chat-source__trigger-link",href:i,rel:"noopener noreferrer",target:"_blank",...r,children:p});return ae("span",{className:me("aui-chat-source__trigger",t),"data-slot":"chat-source-trigger",children:s?ae(sr.Trigger,{children:h}):h})}let S=[c,d].filter(Boolean).join(", ")||"Document",u=ae("span",{className:s?void 0:"aui-chat-source__trigger-link",...s?{}:r,children:p});return ae("span",{className:me("aui-chat-source__trigger",t),"data-slot":"chat-source-trigger",children:s?ae(sr.Trigger,{children:ae("button",{"aria-label":`Source: ${S}`,className:"aui-chat-source__trigger-link",type:"button",...r,children:p})}):u})},oo=({children:e,className:t,...n})=>{let{locator:r}=ar();return e??r?ae("span",{className:me("aui-chat-source__locator",t),"data-slot":"chat-source-locator",...n,children:e??r}):null},ao=({children:e,className:t,faviconUrl:n})=>{let{domain:r,faviconUrl:o,href:s,title:i}=ar(),d=i??r??s??"Source",l=n??o;if(e&&Wl.isValidElement(e)){let c=e;return Wl.cloneElement(c,{className:me("aui-chat-source__icon",t,c.props.className),"data-slot":"chat-source-icon"})}return Ut("span",{"aria-hidden":"true",className:me("aui-chat-source__icon",t),"data-slot":"chat-source-icon",children:[ae("span",{className:"aui-chat-source__icon-fallback",children:Ym(d)}),l?ae("img",{alt:"",className:"aui-chat-source__favicon","data-slot":"chat-source-favicon",decoding:"async",height:14,loading:"lazy",referrerPolicy:"no-referrer",src:l,width:14,onError:c=>{c.currentTarget.hidden=!0}}):null]})},io=({className:e})=>ae(qm,{className:me("aui-chat-source__document-icon",e),"data-slot":"chat-source-document-icon"}),so=({children:e,className:t,...n})=>{let{domain:r,title:o}=ar();return ae("span",{className:me("aui-chat-source__title",t),"data-slot":"chat-source-title",...n,children:e??o??r})},_s=({children:e,className:t,description:n,title:r,...o})=>{let{description:s,domain:i,enablePreview:d,href:l,locator:c,sourceType:m,title:p}=ar();if(!d)return null;let S=r??p,u=n??s,h=m==="url"&&l?Ut("a",{className:"aui-chat-source__preview-link",href:l,rel:"noopener noreferrer",target:"_blank",children:[Ut("div",{className:"aui-chat-source__preview-header",children:[ae(ao,{}),ae("span",{className:"aui-chat-source__preview-domain",children:i})]}),S?ae("div",{className:"aui-chat-source__preview-title",children:S}):null,u?ae("div",{className:"aui-chat-source__preview-description",children:u}):null]}):Ut("div",{className:"aui-chat-source__preview-link","data-source-type":"document",children:[Ut("div",{className:"aui-chat-source__preview-header",children:[ae(io,{}),ae("span",{className:"aui-chat-source__preview-domain",children:S??"Document"})]}),c?ae("div",{className:"aui-chat-source__preview-title",children:c}):null,u?ae("div",{className:"aui-chat-source__preview-description",children:u}):null]});return ae(sr.Content,{"data-slot":"chat-source-preview",offset:8,placement:"top",className:jm(t,x=>me("aui-chat-source__preview",x)??""),...o,children:e??h})};import{Disclosure as In}from"@heroui/react";import{composeRenderProps as Os}from"react-aria-components";import{jsx as Bt,jsxs as Xm}from"react/jsx-runtime";var Ds=({children:e,className:t,...n})=>Bt(In,{"data-slot":"chat-sources",className:Os(t,r=>me("aui-chat-sources",r)??""),...n,children:e}),Yl=({children:e,className:t,...n})=>Bt(In.Heading,{children:Xm(In.Trigger,{"data-slot":"chat-sources-trigger",className:Os(t,r=>me("aui-chat-sources__trigger",r)??""),...n,children:[Bt("span",{className:"aui-chat-sources__trigger-label",children:e}),Bt(In.Indicator,{className:"aui-chat-sources__indicator"})]})}),Xl=({children:e,className:t,...n})=>Bt(In.Content,{"data-slot":"chat-sources-content",className:Os(t,r=>me("aui-chat-sources__content",r)??""),...n,children:Bt(In.Body,{children:Bt("div",{className:"aui-chat-sources__content-body",children:e})})}),Jl=({children:e,className:t,role:n="list",...r})=>Bt("div",{className:me("aui-chat-sources__list",t),"data-slot":"chat-sources-list",role:n,...r,children:e});var Zl=Object.assign(Ns,{DocumentIcon:io,Icon:ao,Locator:oo,Preview:_s,Root:Ns,Title:so,Trigger:ks}),ir=Object.assign(Ds,{Content:Xl,List:Jl,Root:Ds,Trigger:Yl});import{jsx as Mt,jsxs as ec}from"react/jsx-runtime";function Jm(e){return`https://www.google.com/s2/favicons?domain_url=${encodeURIComponent(e)}&sz=64`}function tc({inList:e=!1,source:t}){let n="url"in t?t.url:void 0;return Mt(Zl,{description:t.excerpt,faviconUrl:n?Jm(n):void 0,href:n,locator:t.locator,role:e?"listitem":void 0,sourceType:t.sourceType??"url",title:t.title})}function Zm({sources:e}){return Mt(ir.List,{"aria-label":"Sources",children:e.map(t=>Mt(tc,{inList:!0,source:t},t.sourceId))})}function nc({sources:e}){return e.length===0?null:e.length===1?Mt("div",{"aria-label":"Sources",className:"ha-message-sources","data-count":"1",role:"group",children:Mt(tc,{source:e[0]})}):ec(ir,{className:"ha-message-sources","data-count":e.length,children:[ec(ir.Trigger,{"aria-label":`${e.length} sources`,children:[Mt("span",{className:"ha-sources-label",children:"Sources"}),Mt("span",{"aria-hidden":"true",className:"ha-sources-count",children:e.length})]}),Mt(ir.Content,{children:Mt(Zm,{sources:e})})]})}function eg(e){try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:(t.hash="",t.toString())}catch{return null}}function rc(e){let t=new Map;for(let n of e){if(n.type!=="data-sources")continue;let r=Ti.safeParse(n.data);if(r.success)for(let o of r.data.items){if("url"in o){let i=eg(o.url);i&&!t.has(i)&&t.set(i,{...o,url:i});continue}let s=`document:${o.title}:${o.locator??o.sourceId}`;t.has(s)||t.set(s,o)}}return[...t.values()]}function oc(e,{hasContent:t,isStreaming:n}){return n||!t?[]:e}import{Plus as tg}from"@gravity-ui/icons";import{Button as ng}from"@heroui/react";import{jsx as sc}from"react/jsx-runtime";function ac({isDisabled:e=!1,onPress:t}){return sc(ng,{isIconOnly:!0,"aria-label":"New chat",className:"ha-icon-button ha-new-chat-button",isDisabled:e,size:"sm",variant:"ghost",onPress:t,children:sc(tg,{"aria-hidden":"true"})})}function ic(e){return`heroui-agent:project-config:${e}`}function lc(e){try{let t=window.localStorage.getItem(ic(e));if(!t)return null;let n=Ur.safeParse(JSON.parse(t));return n.success?n.data:null}catch{return null}}function cc(e,t){try{window.localStorage.setItem(ic(e),JSON.stringify(t))}catch{}}var rg=["runtimeAdmittedAt","providerRequestedAt","providerFirstEventAt","firstSemanticTextAt","completedAt"];function uc(e,t,n){if(!n||typeof n!="object"||Array.isArray(n)||typeof window>"u")return!1;let r=n,o={};for(let i of rg){let d=r[i];typeof d=="number"&&Number.isFinite(d)&&(o[i]=d)}if(typeof r.turnId=="string"&&r.turnId&&(o.turnId=r.turnId),Object.keys(o).length===0)return!1;let s={agentId:e,conversationId:t,...o};return window.dispatchEvent(new CustomEvent(Ua,{detail:s})),!0}import{ChevronDown as og,Ellipsis as sg,Pencil as ag,Plus as ig,TrashBin as lg}from"@gravity-ui/icons";import{Button as an,Dropdown as lr,Input as cg,Label as dc,Modal as ot,Popover as Ls,TextField as ug}from"@heroui/react";import{useCallback as dg,useRef as Hs,useState as Ft}from"react";import{Fragment as hc,jsx as Z,jsxs as Ce}from"react/jsx-runtime";var pc="rename",mc="delete",pg=80,gc=new Set;function Us({activeConversationId:e,busyConversationIds:t=gc,completedConversationIds:n=gc,groups:r,isNewConversationDisabled:o=!1,onDeleteConversation:s,onNewConversation:i,onRenameConversation:d,onSelectConversation:l,variant:c="popover"}){let[m,p]=Ft(!1),[S,u]=Ft(!1),[h,x]=Ft(null),[w,A]=Ft(null),[O,_]=Ft(""),[N,L]=Ft(null),[$,X]=Ft(!1),[b,f]=Ft(),v=Hs(0),R=Hs(0),y=Hs(null);nn(y);let T=r.flatMap(D=>D.items).find(D=>D.id===e)?.title??"New chat",P=dg(D=>{f(D??void 0)},[]),z=()=>{x(null),p(!1)},ie=D=>{!D&&Date.now()-v.current<350||(D||x(null),p(D))},j=(D,k)=>{!k&&Date.now()-R.current<350||x(k?D:null)},F=(D,k)=>{z(),A({item:D,type:k}),_(D.title),L(null),u(!0)},K=()=>{$||(L(null),u(!1))},ye=(D,k)=>{k===pc&&F(D,"rename"),k===mc&&!t.has(D.id)&&F(D,"delete")},Se=async()=>{if(!w||w.type!=="rename"||$)return;let D=O.trim();if(!D){L("Enter a name for this chat.");return}if(D===w.item.title){u(!1);return}X(!0),L(null);try{await d(w.item.id,D),A({...w,item:{...w.item,title:D}}),u(!1)}catch(k){L(k instanceof Error?k.message:"The chat could not be renamed")}finally{X(!1)}},H=async()=>{if(!(!w||w.type!=="delete"||$)){X(!0),L(null);try{await s(w.item.id),u(!1)}catch(D){L(D instanceof Error?D.message:"The chat could not be deleted")}finally{X(!1)}}},B=r.length?r.map(D=>Ce("section",{className:"ha-session-group",children:[Z("h3",{children:D.label}),Z("div",{className:"ha-session-list",children:D.items.map(k=>{let Y=k.id===e,re=t.has(k.id),oe=!re&&n.has(k.id);return Ce("div",{className:"ha-session-row","data-actions-open":h===k.id?"true":void 0,"data-active":Y||void 0,"data-completed":oe||void 0,children:[Ce("button",{"aria-current":Y?"page":void 0,className:"ha-session-select",type:"button","aria-label":oe?`${k.title}, new response available`:void 0,onClick:()=>{z(),Y||l(k.id)},children:[re?Z(tn,{className:"ha-session-title ha-session-shimmer",children:k.title}):Z("span",{className:"ha-session-title",children:k.title}),oe?Z("span",{"aria-hidden":"true",className:"ha-session-completed-dot"}):null]}),Ce(lr,{isOpen:h===k.id,onOpenChange:Me=>j(k.id,Me),children:[Z(an,{isIconOnly:!0,"aria-label":`Chat actions for ${k.title}`,className:"ha-session-actions-trigger",size:"sm",variant:"ghost",onPointerDown:()=>{R.current=Date.now()},children:Z(sg,{"aria-hidden":"true"})}),Z(lr.Popover,{className:"ha-session-actions-menu",placement:"bottom end",UNSTABLE_portalContainer:b,children:Ce(lr.Menu,{"aria-label":`Actions for ${k.title}`,onAction:Me=>ye(k,Me),children:[Ce(lr.Item,{id:pc,textValue:"Rename",children:[Z(ag,{"aria-hidden":"true"}),Z(dc,{children:"Rename"})]}),Ce(lr.Item,{id:mc,isDisabled:re,textValue:re?"Delete unavailable while responding":"Delete",variant:"danger",children:[Z(lg,{"aria-hidden":"true",className:"ha-session-delete-icon"}),Z(dc,{children:re?"Delete after response":"Delete"})]})]})})]})]},k.id)})})]},D.label)):Z("p",{className:"ha-session-empty",children:"Your recent chats will appear here."});return Ce("div",{"data-variant":c,className:c==="sidebar"?"ha-session-picker ha-session-sidebar":"ha-session-picker",children:[c==="sidebar"?Ce(hc,{children:[Ce("div",{className:"ha-session-sidebar-header",children:[Z("h2",{children:"Chats"}),Ce(an,{fullWidth:!0,className:"ha-session-new-chat",isDisabled:o,size:"sm",variant:"tertiary",onPress:()=>{z(),i?.()},children:[Z(ig,{"aria-hidden":"true"}),"New chat"]})]}),Z("nav",{ref:y,"aria-label":"Recent chats",className:"ha-session-sidebar-history",children:B})]}):Ce(Ls,{isOpen:m,onOpenChange:ie,children:[Ce(an,{"aria-label":"Choose a chat",className:"ha-session-trigger",size:"sm",variant:"ghost",onPointerDown:()=>{v.current=Date.now()},children:[Z("span",{className:"font-medium",children:T}),Z(og,{"aria-hidden":"true"})]}),Z(Ls.Content,{isNonModal:!0,className:"ha-session-menu",placement:"bottom start",UNSTABLE_portalContainer:b,children:Z(Ls.Dialog,{"aria-label":"Chat history",className:"ha-session-history-dialog",children:B})})]}),Z(ot.Backdrop,{className:"ha-session-modal-backdrop",isDismissable:!$,isKeyboardDismissDisabled:$,isOpen:S,UNSTABLE_portalContainer:b,onOpenChange:D=>{D||K()},children:Z(ot.Container,{placement:"center",size:"sm",children:Z(ot.Dialog,{className:"ha-session-modal",children:Z(mg,{dialog:w,isPending:$,mutationError:N,renameTitle:O,onClose:K,onDelete:H,onRename:Se,onRenameTitleChange:_})})})}),Z("div",{ref:P,className:"ha-session-portal","data-open":m||S||h?"true":void 0,onPointerDown:D=>{D.target?.closest(".ha-session-menu, .ha-session-actions-menu, .ha-session-modal-backdrop")||(m||h)&&z()}})]})}function mg({dialog:e,isPending:t,mutationError:n,onClose:r,onDelete:o,onRename:s,onRenameTitleChange:i,renameTitle:d}){return e?.type==="rename"?Ce("form",{onSubmit:l=>{l.preventDefault(),s()},children:[Z(ot.Header,{children:Z(ot.Heading,{children:"Rename chat"})}),Ce(ot.Body,{children:[Z(ug,{autoFocus:!0,fullWidth:!0,"aria-label":"Chat name",isInvalid:!!n,name:"title",children:Z(cg,{maxLength:pg,value:d,variant:"secondary",onChange:l=>i(l.target.value)})}),Z(fc,{message:n})]}),Ce(ot.Footer,{children:[Z(an,{fullWidth:!0,isDisabled:t,type:"button",variant:"outline",onPress:r,children:"Cancel"}),Z(an,{fullWidth:!0,isPending:t,type:"submit",children:t?"Saving\u2026":"Submit"})]})]}):e?.type!=="delete"?null:Ce(hc,{children:[Z(ot.Header,{children:Z(ot.Heading,{children:"Delete chat?"})}),Ce(ot.Body,{children:[Ce("p",{children:["Are you sure you want to delete ",Ce("strong",{children:["\u201C",e.item.title,"\u201D"]}),"?"]}),Z(fc,{message:n})]}),Ce(ot.Footer,{children:[Z(an,{fullWidth:!0,isDisabled:t,variant:"outline",onPress:r,children:"Cancel"}),Z(an,{fullWidth:!0,isPending:t,variant:"danger",onPress:()=>void o(),children:t?"Deleting\u2026":"Delete"})]})]})}function fc({message:e}){return e?Z("p",{className:"ha-session-modal-error",role:"alert",children:e}):null}import{useEffect as gg,useState as fg}from"react";import{jsx as vg}from"react/jsx-runtime";var lo=["Thinking\u2026","Analyzing request\u2026","Preparing next steps\u2026"],hg=1600,yg=5e3;function yc(){let[e,t]=fg(0);return gg(()=>{let n=e===lo.length-1,r=window.setTimeout(()=>{t(o=>(o+1)%lo.length)},n?yg:hg);return()=>window.clearTimeout(r)},[e]),vg(Gr,{ariaLabel:"Working on your request\u2026",label:lo[e]??lo[0]})}function vc({now:e=()=>performance.now(),nowWallClock:t=()=>Date.now(),report:n,schedulePaint:r=o=>requestAnimationFrame(o)}){let o=new Map,s=null,i=(l,c)=>{o.has(l)||o.set(l,{painted:new Set,scheduled:new Set,startedAt:c?.startedAt??e(),startedAtWallClock:c?.startedAtWallClock??t()})},d=(l,c,m)=>{let p=o.get(l);!p||p.painted.has(c)||(p.scheduled.delete(c),p.painted.add(c),n({latencyMs:Math.max(0,Math.round(m-p.startedAt)),messageId:l,metric:c}))};return{activate(l){i(l),s=l},begin:i,complete(l){s===l&&(s=null)},getActiveMessageId(){return s},getStartedAtWallClock(l){return o.get(l)?.startedAtWallClock},markAfterPaint(l,c){let m=o.get(l);!m||m.painted.has(c)||m.scheduled.has(c)||(m.scheduled.add(c),r(()=>{d(l,c,e())}))},markPaintedAt(l,c,m){d(l,c,m)}}}function Bs(e,{hasActivity:t=!1,hasTransientData:n=!1}={}){if(!e||e.role!=="assistant")return{hasServerContent:!1,hasText:!1};let r=e.parts.some(s=>s.type==="text"&&s.text.trim().length>0),o=e.parts.some(s=>s.type==="file"||s.type==="data-component"||s.type==="data-sources");return{hasServerContent:r||o||t||n,hasText:r}}function bc({isPendingPart:e,messages:t,terminal:n}){if(n)return!1;let r=t.at(-1);return!!(r?.role==="assistant"&&r.parts.some(o=>e(o)))}function ln({attempt:e,currentAttempt:t,manualStopRequested:n,stalledStopRequested:r}){return e===t&&!n&&!r}async function Sc(e,t){return await e?.catch(()=>{}),t()}function Cc({hasPendingClientToolCalls:e,isAutoContinuationPending:t,isRecovering:n,isRunning:r,localPending:o,stalled:s}){return!s&&(r||e||o||t||n)}function Ac({hasActiveTurn:e,hasPendingClientToolCalls:t,isResuming:n,stalled:r}){return e&&!t&&!n&&!r}function Tc(e){let t=globalThis.setTimeout(e,12e4);return()=>globalThis.clearTimeout(t)}function Rc(e){let t=globalThis.setTimeout(e,12e4);return()=>globalThis.clearTimeout(t)}import{useCallback as bg,useEffect as cr,useRef as Mc,useState as wc}from"react";var Sg=300;function Ec({attachments:e,draftKey:t,input:n,setAttachments:r,setInput:o}){let[s,i]=wc(null),[d,l]=wc(null),c=Mc(n),m=Mc(null);return cr(()=>{c.current=n},[n]),cr(()=>{let p=!1,S=Va(t);return queueMicrotask(()=>{p||(S&&o(u=>u||S),l(t))}),$a(t).then(u=>{p||(u.length>0&&r(h=>h.length>0?h:u),i(t))}),()=>{p=!0}},[t,r,o]),cr(()=>{if(d!==t)return;let p=()=>Uo(t,n);return m.current=window.setTimeout(p,Sg),window.addEventListener("pagehide",p),()=>{m.current!==null&&window.clearTimeout(m.current),m.current=null,window.removeEventListener("pagehide",p)}},[t,n,d]),cr(()=>{if(d===t)return()=>Uo(t,c.current)},[t,d]),cr(()=>{s===t&&Ka(t,e)},[e,t,s]),bg(()=>{c.current="",m.current!==null&&window.clearTimeout(m.current),m.current=null,wr(t)},[t])}import{useCallback as Cg,useState as Ag}from"react";function Pc(e){return`${e}:model`}function Tg(e){if(typeof window>"u")return;let t=Pc(e);try{let n=window.localStorage.getItem(t);if(n===null)return;let r=Ra(n);if(wa(r))return r!==n&&window.localStorage.setItem(t,r),r;window.localStorage.removeItem(t)}catch{}}function Rg(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(Pc(e),t)}catch{}}function Fs(e,t){let[n,r]=Ag(()=>Tg(e)),o=n??t??Ma,s=Cg(i=>{r(i),Rg(e,i)},[e]);return{selectedModelId:o,setSelectedModelId:s}}var Ic="The recording could not be transcribed. Try again.",xc="No speech was detected. Try again when you are ready.",Mg="Voice transcription took too long. Try again.",wg=3e4;function Eg(e){let t=new AbortController,n=!1,r=()=>t.abort(e.reason);e.aborted?r():e.addEventListener("abort",r,{once:!0});let o=setTimeout(()=>{n=!0,t.abort()},wg);return{didTimeOut:()=>n,dispose:()=>{clearTimeout(o),e.removeEventListener("abort",r)},signal:t.signal}}function Pg(e,t){return t.aborted?Promise.reject(t.reason):new Promise((n,r)=>{let o=()=>r(t.reason),s=()=>t.removeEventListener("abort",o);t.addEventListener("abort",o,{once:!0}),e.then(i=>{s(),n(i)},i=>{s(),r(i)})})}function Ig(e,t){return{Authorization:`Bearer ${e}`,"Content-Type":t,"X-HeroUI-Agent-Protocol-Version":String(6),"X-HeroUI-Agent-SDK-Version":We}}function xg(e){return e===413?"The recording is too long. Try a shorter message.":e===415?"This browser's recording format is not supported.":e===422?xc:e===429?"Voice dictation is busy. Wait a moment and try again.":Ic}async function Nc({apiBaseUrl:e,audio:t,conversationId:n,language:r,signal:o,tokenManager:s}){let i=new URL(`${e}/v1/conversations/${encodeURIComponent(n)}/transcriptions`),d=Eg(o);r?.trim()&&i.searchParams.set("language",r.trim());try{for(let l=0;l<2;l+=1){let c=await Pg(s.get(),d.signal),m=await fetch(i,{body:t,headers:Ig(c,t.type||"audio/webm"),method:"POST",signal:d.signal});if(m.status===401&&l===0){s.clear();continue}if(!m.ok)throw new Error(xg(m.status));let p=await m.json().catch(()=>null),S=typeof p?.text=="string"?p.text.trim():"";if(!S)throw new Error(xc);return S}}catch(l){throw d.didTimeOut()&&!o.aborted?new Error(Mg,{cause:l}):l}finally{d.dispose()}throw new Error(Ic)}import{Fragment as cn,jsx as I,jsxs as Pe}from"react/jsx-runtime";var Dc=on();async function $g(e){try{let t=await e;if(!t.ok)return null;let n=Ur.safeParse(await t.json());return n.success?n.data:null}catch{return null}}function Vs(e){return e.type==="dynamic-tool"&&e.toolName?e.toolName:e.type.startsWith("tool-")?e.type.slice(5):null}function Kg({composerControlsRevealed:e,conversationEpoch:t,identityEpoch:n,identityReset:r,onClose:o,onComposerControlsReveal:s,onNewConversation:i,onReady:d,onSelectConversation:l,onUnreadChange:c,open:m,options:p,requestedConversationId:S,shellComposerEndSlot:u,shellComposerFooterSlot:h,showReadyLoader:x,tokenManager:w}){let[A,O]=ee(null),[_,N]=ee({}),L=ce(_),$=ce(A),[X,b]=ee(null),[f,v]=ee([]),[R,y]=ee(hs),M=ce(R),[T,P]=ee({}),[z,ie]=ee(0),j=A?_[A]??null:null;$t(()=>{L.current=_,$.current=A},[A,_]);let F=W(E=>{N(U=>({...U,[E.conversationId]:E})),O(E.conversationId)},[]),K=W(E=>{N(U=>{let V=U[E];return V?.runtime?{...U,[E]:{...V,composerReady:!1,runtime:null}}:U}),$.current===E&&ie(U=>U+1)},[]),ye=W(E=>{let U=M.current,V=E(U);V!==U&&(M.current=V,y(V),c(V.completedIds.size>0))},[c]),Se=W((E,U)=>{ye(V=>tl(V,{...U,activeConversationId:m?$.current:null,conversationId:E}))},[ye,m]);be(()=>{!m||!A||ye(E=>ys(E,A))},[A,ye,m]);let H=W(E=>{ye(U=>ys(U,E)),l(E)},[ye,l]),B=W(()=>{$.current=null,O(null),b(null),i()},[i]),D=W((E,U)=>{P(V=>{let J=V[E]??Dc,se=U(J);return se===J?V:{...V,[E]:se}})},[]),k=ce(null),Y=ce(null),re=p.apiBaseUrl,oe=p.agentId,Me=Vt(d),Ge=W((E,U)=>{let V=ol({conversationEpoch:t,optimisticTarget:Y.current,readyConversationId:E,readyEpoch:U,requestedConversationId:S});V&&(N(J=>{let se=J[V];return!se||se.composerReady?J:{...J,[V]:{...se,composerReady:!0}}}),O(V),d(U))},[t,d,S]),st=Ae(()=>{try{return Ot(vn(p.tools,p.permissionDefaultMode)),p.permissionShowPicker&&Ot(vn(p.tools,"ask")),null}catch(E){return E instanceof Error?E.message:"The client tools could not be loaded"}},[p.permissionDefaultMode,p.permissionShowPicker,p.tools]),at=st?null:Ii(p),un=Vt(E=>Ni(p,w,E)),xn=Vt(E=>{ke(p,w,E,"embed_loaded")}),wt=ce(n);$t(()=>{if(wt.current===n)return;wt.current=n,k.current=null,Y.current=null,L.current={},$.current=null,N({}),O(null),v([]);let E=hs();M.current=E,y(E),P({}),r?w.reset():w.clear()},[n,r,w]),$t(()=>{if(S!==null||st)return;let E=rl(Y.current,t);Y.current=E;let U=k.current;if(!U)return;let V=E.conversationId;localStorage.setItem(U.storageKey,V),b(null),v(J=>{let se=Kn(J,V,Ir([]),Date.now());return Nt(U.historyKey,se),se}),N(J=>({...J,[V]:{composerReady:!1,config:U.config,conversationId:V,historyKey:U.historyKey,readyEpoch:t,runtime:null,showStartScreenWhileConnecting:!0,storageKey:U.storageKey}})),O(V)},[st,t,S]),be(()=>{let E=!1;if(st){b(st),O(null),Me(t);return}let U=k.current;if(U){let J=jr({conversationEpoch:t,optimisticTarget:Y.current,requestedConversationId:S,storedConversationId:localStorage.getItem(U.storageKey)}),se=J?L.current[J]:void 0;if(se?.runtime){b(null),N(ve=>({...ve,[se.conversationId]:{...se,readyEpoch:t}})),se.composerReady&&O(se.conversationId);return}}let V=jr({conversationEpoch:t,optimisticTarget:Y.current,requestedConversationId:S,storedConversationId:null});return b(null),O(V??(typeof S=="string"&&Rt(S)?S:null)),(async()=>{try{let J=await w.subjectHash(),se=`heroui-agent:conversation:${oe}:${J}`,ve=`heroui-agent:history:${oe}:${J}`,_e=jr({conversationEpoch:t,optimisticTarget:Y.current,requestedConversationId:S,storedConversationId:localStorage.getItem(se)})??crypto.randomUUID();localStorage.setItem(se,_e);let qe=Vo(ve);E||v(qe);let we=U?.config??lc(oe),Gt=we?null:Xn(w,`${re}/v1/agents/${encodeURIComponent(oe)}/config`),ct=Xn(w,`${re}/v1/agents/${encodeURIComponent(oe)}/conversations`).catch(()=>null),Nn=await un(_e),dn=we??(Gt?await $g(Gt):null);if(!dn||!Nn)throw new Error("The data assistant could not be loaded");we||cc(oe,dn);let De=qe.find(ut=>ut.id===_e),kn=Kn(qe,_e,De?.title??Ir([]),De?.updatedAt??Date.now());if(kn!==qe&&Nt(ve,kn),!E){k.current={config:dn,historyKey:ve,storageKey:se},v(kn);let ut=L.current[_e],le={composerReady:!1,config:dn,conversationId:_e,historyKey:ve,readyEpoch:t,runtime:Nn.runtime,showStartScreenWhileConnecting:ut?.showStartScreenWhileConnecting??S===null,storageKey:se};F(le)}ct.then(async ut=>{if(!ut?.ok)return;let le=Pr((await ut.json()).conversations);E||v(qt=>{let _n=$o(qt,le);return Nt(ve,_n),_n})}),xn(_e)}catch(J){if(!E&&S===void 0&&Ei(J)){B();return}E||(b(J instanceof Error?J.message:"The data assistant could not be loaded"),Me(t))}})(),()=>{E=!0}},[re,F,at,st,t,n,oe,S,z,B,w]);let Je=W((E,U,V)=>{let J=k.current?.historyKey;J&&v(se=>{let ve=Kn(se,E,U,Date.now(),V);return Nt(J,ve),ve})},[]),pe=W(E=>{N(U=>{let V=U[E];return V?.showStartScreenWhileConnecting?{...U,[E]:{...V,showStartScreenWhileConnecting:!1}}:U})},[]),Oe=W(async(E,U)=>{let V=async()=>{let se=await w.get(),ve=new Headers(U.headers);for(let[qe,we]of Object.entries(Qr(se)))ve.set(qe,we);let _e=await fetch(`${re}/v1/conversations/${encodeURIComponent(E)}`,{...U,headers:ve});if(_e.status===401){w.clear();let qe=await w.get(),we=new Headers(U.headers);for(let[Gt,ct]of Object.entries(Qr(qe)))we.set(Gt,ct);_e=await fetch(`${re}/v1/conversations/${encodeURIComponent(E)}`,{...U,headers:we})}return _e},J=await V();if(U.method==="DELETE"&&J.status===409&&(J=await sl({initialResponse:J,request:V})),!J.ok)throw new Error(U.method==="DELETE"?"The chat could not be deleted":"The chat could not be renamed")},[re,w]),vt=W(async(E,U)=>{await Oe(E,{body:JSON.stringify({title:U}),headers:{"Content-Type":"application/json"},method:"PATCH"});let V=k.current?.historyKey;V&&v(J=>{let se=J.map(ve=>ve.id===E?{...ve,title:U}:ve);return Nt(V,se),se})},[Oe]),it=W(async E=>{await Oe(E,{method:"DELETE"});let U=k.current;U&&(v(V=>{let J=V.filter(se=>se.id!==E);return Nt(U.historyKey,J),J}),localStorage.removeItem(Tr(U.storageKey,E)),localStorage.removeItem(ko(U.storageKey,E)),wr(Bo(U.storageKey,E)),Ml(Ts(U.storageKey,E)),N(V=>{if(!(E in V))return V;let J={...V};return delete J[E],J}),ye(V=>nl(V,E)),P(V=>{if(!(E in V))return V;let J={...V};return delete J[E],J}),A===E&&B())},[A,ye,Oe,B]),ge=Ae(()=>{let E=p.suggestedPrompts;return E?.length?Object.fromEntries(Object.entries(_).map(([U,V])=>[U,{...V,config:{...V.config,suggestedPrompts:E}}])):_},[p.suggestedPrompts,_]),Et=A?ge[A]?.config??null:null,Kt=ce(null);be(()=>{!m||!j?.runtime||Kt.current===j.conversationId||(Kt.current=j.conversationId,ke(p,w,j.conversationId,"opened"))},[m,p,j,w]);let Pt=st??X,ur=Ae(()=>qo(f),[f]),uo=f.find(E=>E.id===A)?.title??"New chat",bt=k.current?"Loading chat\u2026":"Loading assistant\u2026",lt=S===null&&(!j||j.showStartScreenWhileConnecting);return I(cn,{children:Pe(Aa,{keepMounted:!0,agentId:p.agentId,defaultExpanded:p.panelExpanded,expandable:!x&&p.panelExpandable,expandedTitle:uo,modal:p.viewMode!=="sidebar",name:Et?.name??"Data assistant",open:m,actionsSlot:x?I(cn,{}):I(ac,{isDisabled:lt,onPress:B}),expandedSidebarSlot:x?void 0:I(Us,{activeConversationId:A,busyConversationIds:R.busyIds,completedConversationIds:R.completedIds,groups:ur,isNewConversationDisabled:lt,variant:"sidebar",onDeleteConversation:it,onNewConversation:B,onRenameConversation:vt,onSelectConversation:H}),historySlot:x?I(cn,{}):I(Us,{activeConversationId:A,busyConversationIds:R.busyIds,completedConversationIds:R.completedIds,groups:ur,onDeleteConversation:it,onRenameConversation:vt,onSelectConversation:H}),onClose:o,onNewConversation:x?void 0:B,children:[Pt?I("div",{className:"ha-loading",role:"alert",children:Pt}):x?I(Ca,{indicator:I(Hg,{"aria-hidden":!0,color:"current",size:"md"})}):!j||!j.runtime||!Et?lt&&j?I(Lc,{composerControlsRevealed:e,loadingLabel:bt,options:p,route:j,onComposerControlsReveal:s},`pending-${t}`):I(Yr,{agentId:p.agentId,composerControlsAvailable:p.composerControlsAvailable,composerControlsRevealed:e,composerEndSlot:u,composerFooterSlot:h,greeting:p.greeting,loadingLabel:bt,placeholder:p.composerPlaceholder,showStartScreen:lt,suggestedPrompts:p.suggestedPrompts??[],composerStartSlot:I(Fc,{agentId:p.agentId,options:p}),onComposerControlsReveal:s},`pending-${t}`):null,I("div",{className:"ha-runtime-content",hidden:!!Pt||x,children:I(cl,{activeConversationId:Pt?null:A,routes:ge,children:(E,U)=>I(Ha,{variant:E.config.surfaceVariant,children:E.runtime?I(Fg,{fallback:U&&E.showStartScreenWhileConnecting?I(Lc,{composerControlsRevealed:e,loadingLabel:"Connecting chat\u2026",options:p,route:E,onComposerControlsReveal:s}):I(Yr,{agentId:p.agentId,composerControlsAvailable:p.composerControlsAvailable,composerControlsRevealed:e,greeting:p.greeting,loadingLabel:"Connecting chat\u2026",placeholder:p.composerPlaceholder,showStartScreen:!1,suggestedPrompts:p.suggestedPrompts??[],onComposerControlsReveal:s}),children:I(qg,{active:U,composerControlsRevealed:!!U&&e,config:E.config,conversationEpoch:E.readyEpoch,conversationId:E.conversationId,options:p,runtime:E.runtime,showStartScreenWhileHydrating:E.showStartScreenWhileConnecting,storageKey:E.storageKey,tokenManager:w,messageQueue:T[E.conversationId]??Dc,onComposerControlsReveal:s,onConversationStatusChange:Se,onMessageQueueChange:D,onReady:Ge,onRuntimeRevisionStale:K,onConversationStarted:V=>{pe(E.conversationId),Je(E.conversationId,V)},onConversationTitled:V=>Je(E.conversationId,V,{replaceTitle:!0})})}):null})})})]})})}function Lc({composerControlsRevealed:e,loadingLabel:t,onComposerControlsReveal:n,options:r,route:o}){return I(Yr,{showStartScreen:!0,agentId:r.agentId,composerControlsAvailable:r.composerControlsAvailable,composerControlsRevealed:e,composerStartSlot:I(Fc,{agentId:r.agentId,options:r}),greeting:r.greeting,loadingLabel:t,placeholder:r.composerPlaceholder,suggestedPrompts:r.suggestedPrompts??[],composerEndSlot:I(Gg,{conversationId:o.conversationId,options:r,storageKey:o.storageKey}),composerFooterSlot:r.composerDisclaimer?I("p",{className:"ha-footnote",children:Io(r.composerDisclaimer)}):null,onComposerControlsReveal:n})}function Fc({agentId:e,options:t}){let n=ce(null),[r,o]=ee(()=>No(e)),[s,i]=ee(null),d=l=>{let c=Rn(l,t.composerAttachmentContentTypes);o(c.files),i(c.error),Na(e,c.files)};return t.composerAttachmentContentTypes.length===0?null:Pe(cn,{children:[I("input",{ref:n,multiple:!0,accept:t.composerAttachmentAccept,"aria-label":"Choose files to attach",className:"ha-file-input",type:"file",onChange:l=>{d(Array.from(l.currentTarget.files??[])),l.currentTarget.value=""}}),r.length>0?I(Do,{"aria-label":"Selected attachments",className:"ha-attachments",offset:1,size:24,children:r.map(l=>I(ps,{file:l,onRemove:()=>d(r.filter(c=>c!==l))},`${l.name}-${l.size}-${l.lastModified}`))}):null,I("button",{"aria-label":"Attach files",className:"ha-attach",type:"button",onClick:()=>n.current?.click(),children:I(Bc,{"aria-hidden":"true"})}),s?I("span",{className:"ha-dictation-error",role:"alert",children:s}):null]})}function Gg({conversationId:e,options:t,storageKey:n}){let r=Tr(n,e),[o,s]=ee(()=>Rr(r)??t.permissionDefaultMode),{selectedModelId:i,setSelectedModelId:d}=Fs(n,t.composerDefaultModel),l=c=>{s(c),Mr(r,c)};return Pe(cn,{children:[t.permissionShowPicker&&t.tools.length>0?I(Nr,{"aria-label":"Tool permissions",className:"ha-permission-picker",value:o,onChange:l}):null,t.composerModelPicker?I(xr,{"aria-label":"AI model",className:"ha-model-picker",options:xo,placement:t.permissionShowPicker&&t.tools.length>0?"top":"top start",value:i,onChange:d}):null,t.composerDictation?Pe("button",{disabled:!0,"aria-label":"Dictate message",className:"ha-dictation",type:"button",children:[I(Uc,{"aria-hidden":"true"}),I(Vn,{children:"Dictate message"})]}):null]})}function qg({active:e,composerControlsRevealed:t,config:n,conversationEpoch:r,conversationId:o,messageQueue:s,onComposerControlsReveal:i,onConversationStarted:d,onConversationStatusChange:l,onConversationTitled:c,onMessageQueueChange:m,onReady:p,onRuntimeRevisionStale:S,options:u,runtime:h,showStartScreenWhileHydrating:x,storageKey:w,tokenManager:A}){let{selectedModelId:O,setSelectedModelId:_}=Fs(w,u.composerDefaultModel),N=ko(w,o),L=Tr(w,o),$=u.composerAttachmentAccept,X=Ae(()=>({key:$}),[$]),[b,f]=ee(()=>({files:Rn(No(u.agentId),u.composerAttachmentContentTypes).files,policy:X})),[v,R]=ee(()=>({error:null,policy:X})),y=Ae(()=>b.policy===X?b.files:[],[X,b]),M=v.policy===X?v.error:null,T=W(a=>{f(g=>{let C=g.policy===X?g.files:[],G=typeof a=="function"?a(C):a;return{files:Rn(G,u.composerAttachmentContentTypes).files,policy:X}})},[X,u.composerAttachmentContentTypes]),P=W(a=>R({error:a,policy:X}),[X]),[z,ie]=ee(()=>{let a=u.permissionShowPicker?Rr(N):void 0;return a?{modelId:void 0,permissionMode:a}:void 0}),[j,F]=ee({}),[K,ye]=ee({}),[Se,H]=ee(!1),[B]=ee(()=>Ea(u.agentId)),[D,k]=ee(()=>B?.submitted?"":B?.prompt??""),[Y,re]=ee(()=>B?.submitted?{files:y,id:B.messageId,text:B.prompt}:null),[oe,Me]=ee(()=>{let a=u.permissionShowPicker?Rr(L):void 0;return{configuredDefaultMode:u.permissionDefaultMode,selectedMode:a??u.permissionDefaultMode}}),[Ge,st]=ee(!1),[at,un]=ee(!0),[xn,wt]=ee(!1),[Je,pe]=ee(!1),[Oe,vt]=ee(()=>new Set),[it,ge]=ee(null),[Et,Kt]=ee(0),[Pt,ur]=ee(0),[uo,bt]=ee(!1),[lt,E]=ee(!1),[U,V]=ee(null),[J,se]=ee({}),ve=W(a=>{u.permissionShowPicker?Mr(N,a.permissionMode):_o(N),ie(a)},[N,u.permissionShowPicker]),_e=oe.configuredDefaultMode===u.permissionDefaultMode?oe.selectedMode:u.permissionDefaultMode,qe=W(a=>{Mr(L,a),Me({configuredDefaultMode:u.permissionDefaultMode,selectedMode:a})},[u.permissionDefaultMode,L]),we=u.permissionShowPicker?_e:u.permissionDefaultMode,Gt=u.permissionShowPicker?z?.permissionMode??we:u.permissionDefaultMode,ct=Ae(()=>vn(u.tools,Gt),[Gt,u.tools]),Nn=Ae(()=>Ot(ct),[ct]),dn=Ae(()=>Fi(Nn),[Nn]),De=Ae(()=>new Map(ct.map(a=>[a.name,a])),[ct]),kn=Ae(()=>new Set(ct.map(a=>a.name)),[ct]),ut=ce(new Set),le=ce(null),qt=ce(new Set),_n=ce(!1),Le=ce(s),po=ce(null),Ze=ce(!1),He=ce(!1),Qt=ce(null),dr=ce(0),dt=ce(0),It=ce(null),zt=ce(null),pr=ce(null),mo=ce(new Set),go=ce(new Map),On=ce(()=>{}),$s=ce(null),Ks=ce(null),St=ce(null),Ee=Ae(()=>vc({report:({latencyMs:a,messageId:g,metric:C})=>{ke(u,A,o,C,{latencyMs:a,latencyOrigin:"user_submit",messageId:g})}}),[o,u,A]),Vc=Ae(()=>Bo(w,o),[o,w]),Dn=Ae(()=>Ts(w,o),[o,w]),Gs=Ec({attachments:y,draftKey:Vc,input:D,setAttachments:T,setInput:k}),$c=W((a,{language:g,signal:C})=>Nc({apiBaseUrl:u.apiBaseUrl,audio:a,conversationId:o,...g?{language:g}:{},signal:C,tokenManager:A}),[o,u.apiBaseUrl,A]),{cancel:Qe,elapsedSeconds:fo,error:ho,isActive:Ne,isRecording:Kc,isSupported:Wt,isTranscribing:Ln,start:qs,stop:Qs,stream:Gc}=Zo({onValueChange:k,transcribe:$c,value:D}),yo=t||Ne||y.length>0||M!==null||ho!==null,zs=W(()=>{u.composerControlsAvailable&&i()},[i,u.composerControlsAvailable]),qc=a=>{$n(u.agentId,!0,a.currentTarget),zs()},Qc=a=>{let g=a.currentTarget.querySelector(".ha-composer");g&&xa(g,a.relatedTarget)||$n(u.agentId,!1)};be(()=>{Le.current=s},[s]),be(()=>{u.composerDictation||Qe()},[Qe,u.composerDictation]),be(()=>{e||Qe()},[e,Qe]);let pn=u.composerModelPicker?O:u.composerDefaultModel,mn=W(a=>{Le.current=a,m(o,()=>a)},[o,m]),et=W(async(a,{applyAfterPersist:g=!1}={})=>{let C=Le.current,G=a(C);if(G!==C){g?Le.current=G:mn(G);try{await Rs(Dn,G)}catch(ue){throw Le.current===G&&(g?Le.current=C:mn(C)),ue}g&&Le.current===G&&mn(G)}},[mn,Dn]),ze=W(a=>{et(a).catch(()=>{})},[et]),zc=W(a=>{qt.current.add(a),et(g=>nr(En(g,a,"admitted"),a)).catch(()=>{})},[et]);be(()=>{let a=!1;return un(!0),Rl(Dn).then(async g=>{if(a)return;let C=wl(g,Le.current),G=qt.current,ue={...C,messages:C.messages.filter(de=>!G.has(de.id))};mn(ue),await Rs(Dn,ue)}).catch(()=>{}).finally(()=>{a||un(!1)}),()=>{a=!0}},[mn,Dn]);let mr=W(()=>{Ze.current=!1,He.current=!1,It.current=null,E(!1)},[]),Ws=W(a=>{ln({attempt:a,currentAttempt:dt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current})&&pe(!1)},[]),{agent:jt,connectionEpoch:gr,connectionError:pt,isHydrating:Wc,isReconnecting:js,retryConnection:jc}=Wg({conversationId:o,onRuntimeRevisionStale:S,onTurnAdmitted:zc,options:u,runtime:h,tokenManager:A}),Yc=Vt(p);$t(()=>{Yc(o,r)},[e,r,o]),be(()=>{if(at||gr===0)return;let a=[];for(let G of Le.current.messages)yt(G)==="sending"&&a.push(G.id);if(a.length===0){wt(!1);return}let g=!1,C;return wt(!0),(async()=>{let G=[];for(let he=0;he<a.length;he+=50)G.push(a.slice(he,he+50));let ue=async he=>{let Cr=await Promise.all(G.map(async mt=>({response:await jt.call(Fa,[{protocolVersion:6,turnIds:mt}],{timeout:15e3}),turnIds:new Set(mt)}))),Be=new Set;for(let{response:mt,turnIds:wo}of Cr){if(mt.protocolVersion!==6||!Array.isArray(mt.turns))throw new Error("Invalid turn admission status response");for(let yn of mt.turns)yn.status==="admitted"&&wo.has(yn.turnId)&&Be.add(yn.turnId)}return Be.size===a.length||he>=4?Be:(await new Promise(mt=>window.setTimeout(mt,500)),ue(he+1))},de;try{de=await ue(0)}catch{g||(C=window.setTimeout(()=>ur(he=>he+1),1e3));return}if(!g){for(let he of de)qt.current.add(he);await et(he=>El(he,de))}})().catch(()=>{}).finally(()=>{g||wt(!1)}),()=>{g=!0,C!==void 0&&window.clearTimeout(C)}},[jt,et,gr,at,Pt]);let Xc=Ae(()=>new Proxy(jt,{get(a,g){if(g==="send")return G=>a.send(Vi(G));let C=Reflect.get(a,g,a);return typeof C=="function"?C.bind(a):C}}),[jt]),Q=_g({agent:Xc,cancelOnClientAbort:!1,experimental_throttle:60,getInitialMessages:null,onData:a=>{if(a.type!=="data-conversation-title"){let g=Ee.getActiveMessageId();g&&mo.current.add(g)}if(a.type==="data-progress"&&a.data&&typeof a.data=="object"&&"label"in a.data&&typeof a.data.label=="string"&&ge(a.data.label),a.type==="data-conversation-title"&&a.data&&typeof a.data=="object"&&"title"in a.data&&typeof a.data.title=="string"&&a.data.title.trim()&&c(a.data.title.trim()),a.type==="data-component"){let g=a.data&&typeof a.data=="object"&&"kind"in a.data?a.data:null;ke(u,A,o,"component_rendered",{componentType:g?.kind})}a.type==="data-runtime-timing"&&uc(u.agentId,o,a.data)},onError:a=>{if(Ze.current||He.current){It.current=null,pe(!1),ge(null),queueMicrotask(()=>On.current());return}It.current=a,pe(!1),ge(null),ke(u,A,o,"failure",{messageId:Ee.getActiveMessageId()??void 0,source:"cloudflare-chat"})},onFinish:({isError:a})=>{if(Ze.current||He.current){It.current=null,pe(!1),ge(null),queueMicrotask(()=>On.current());return}a&&!It.current&&(It.current=new Error("The request could not be completed")),pe(!1),ge(null)},resume:!0,syncMessagesToServer:!1,tools:dn}),{clearError:Ys,setMessages:Xs}=Q;$t(()=>{On.current=Ys},[Ys]);let Ct=Q.status==="submitted"||Q.status==="streaming"||Q.isStreaming,xt=uo||lt,Hn=!xt&&Q.isToolContinuation,vo=!!(xt||Q.error||Q.connectionError||pt),Yt=Ae(()=>!vo&&(Oe.size>0||bc({isPendingPart:a=>{let g=a,C=Vs(g);return Dl({isClientTool:!!(C&&De.has(C)),state:g.state})},messages:Q.messages,terminal:vo})),[Q.messages,De,vo,Oe]),Ue=Cc({hasPendingClientToolCalls:Yt,isAutoContinuationPending:Hn,isRecovering:Q.isRecovering,isRunning:Ct,localPending:Je,stalled:lt});be(()=>{if(Ue)return;let a=Ee.getActiveMessageId();a&&(Ee.complete(a),mo.current.delete(a),go.current.delete(a))},[Ue,Ee]);let Xt=!pt&&(Wc||js||at||xn),bo=Xt||Ue,So=xt||!!Q.error||!!Q.connectionError||!!pt,At=bo||So,Js=Il({hasChatError:!!(Q.error||Q.connectionError||pt),hasPendingClientToolCalls:Yt,hasReadyClientToolContinuation:Hn,isLocalPending:Je,isResuming:Xt,isRunning:Ct,recoveryError:xt}),Zs=Vt(l);be(()=>{z&&!Ct&&!Yt&&!Je&&!Xt&&!Hn&&(_o(N),ie(void 0))},[z,N,Yt,Hn,Xt,Ct,Je]),be(()=>{Zs(o,{busy:bo,failed:So,turnActive:Ue})},[So,o,Ue,bo]),be(()=>()=>{Zs(o,{busy:!1,failed:!0,turnActive:!1})},[o]);let Tt=Q.messages.at(-1),ea=Ct&&Tt?.role==="assistant"?Tt.id:null,Jc=Tt?.role==="assistant"&&(Yt||Hn||Q.isRecovering)?Tt.id:null,Jt=il({continuingAssistantMessageId:Jc,isActiveTurn:Ue,streamingAssistantMessageId:ea,trackedActivityMessageId:zt.current}),Co=Jt===Tt?.id?Tt:void 0,ta=!!(Co&&ns(Co,De,{isStreaming:!0}).length>0),Zc=Bs(Co).hasServerContent;be(()=>{if(Ue&&Jt){if(zt.current===Jt)return;let C=pr.current??Date.now();zt.current=Jt,F(G=>({...G,[Jt]:{startedAt:C}}));return}let a=zt.current;if(Ue||!a)return;let g=Date.now();F(C=>{let G=C[a];return!G||G.completedAt?C:{...C,[a]:{...G,completedAt:g}}}),zt.current=null,pr.current=null},[Jt,Ue]);let fr=W(async(a,g,C)=>{Q.addToolOutput({output:C,toolCallId:g,toolName:a})},[Q.addToolOutput]),Ao=W((a,g)=>{vt(C=>{if(C.has(a)===g)return C;let G=new Set(C);return g?G.add(a):G.delete(a),G})},[]),hr=W(async(a,g)=>{await Di({activeToolCallIds:ut.current,run:async()=>{Ao(g.toolCallId,!0),ge("Fetching live data\u2026");try{await Ui({conversationId:o,execute:C=>Hi({context:u.context,execution:C,input:g.input,tool:a}),input:g.input,rpc:{claim:C=>jt.call("claimClientToolEffect",[C],{timeout:cs}),complete:C=>jt.call("completeClientToolEffect",[C],{timeout:cs})},submitOutput:C=>fr(a.name,g.toolCallId,C),toolCallId:g.toolCallId,toolName:a.name}),ge("Analyzing the results\u2026")}finally{Ao(g.toolCallId,!1)}},toolCallId:g.toolCallId})},[jt,o,u.context,Ao,fr]),eu=W((a,g,C)=>{let G=g.toolCallId;if(se(ue=>({...ue,[G]:C?"approved":"rejected"})),ge(C?"Applying your change\u2026":"Updating your request\u2026"),ke(u,A,o,C?"action_approved":"action_declined"),g.approval?.id)Q.addToolApprovalResponse({approved:C,id:g.approval.id});else if(!C)fr(a,G,{reason:"The user declined this tool call",rejected:!0});else{se(ue=>({...ue,[G]:"rejected"}));return}if(C){let ue=De.get(a);ue&&hr(ue,g).catch(()=>{})}else ut.current.add(G)},[Q.addToolApprovalResponse,De,o,hr,u,fr,A]);be(()=>{for(let a of Q.messages)if(a.role==="assistant")for(let g of a.parts){let C=Vs(g);if(!C)continue;let G=De.get(C);!G||ut.current.has(g.toolCallId)||Li({approvalApproved:g.approval?.approved,decision:J[g.toolCallId],needsApproval:G.needsApproval===!0,state:g.state})&&hr(G,g).catch(()=>{})}},[Q.messages,De,gr,hr,J]);let To=W(a=>{H(_a(a,{hasAttachments:yo&&y.length>0}))},[y.length,yo]);$t(()=>{To(St.current)},[D,Ne,To]);let na=W(a=>{if(a.length===0)return;let g=Rn([...y,...a],u.composerAttachmentContentTypes);P(g.error),T(g.files)},[y,u.composerAttachmentContentTypes,P,T]),ra=W(()=>{Qe(),Gs(),k(""),T([]),P(null),V(null)},[Qe,Gs,P,T]),tu=W(()=>St.current?.focus(),[]),Ro=W(()=>{if(Ln){Qe(),requestAnimationFrame(()=>St.current?.focus());return}if(Ne){Qs(),requestAnimationFrame(()=>St.current?.focus());return}qs()},[Qe,Ne,Ln,qs,Qs]);be(()=>{if(!e||!u.composerDictation||!Wt)return;let a=g=>{Zi(g)&&(g.preventDefault(),St.current?.focus({preventScroll:!0}),Ro())};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e,Wt,u.composerDictation,Ro]),$t(()=>{e&&Ia(u.agentId,St.current)},[e,u.agentId]);let oa=W(async a=>{let g=++dt.current,C=Q.messages,G=C.findLast(Be=>Be.role==="user")?.id,ue=C.findLast(Be=>Be.role==="assistant")?.id,de=u.permissionShowPicker?a.permissionMode??we:u.permissionDefaultMode,he=Ot(vn(u.tools,de));ve({modelId:a.modelId,permissionMode:de}),zt.current=null,go.current.set(a.id,ue),Ee.activate(a.id);let Cr=Ee.getStartedAtWallClock(a.id)??Date.now();pr.current=Cr,mr(),po.current={previousUserMessageId:G??null,scrollKey:crypto.randomUUID()},pe(!0),bt(!1),E(!1),ge(jn("accepted")),d(Ko(a.text,a.files));try{let Be=await Hc(u,a.selection);if(!ln({attempt:g,currentAttempt:dt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;a.files.length>0&&ge("Uploading attachments\u2026");let mt=await Oi({acceptedContentTypes:u.composerAttachmentContentTypes,apiBaseUrl:u.apiBaseUrl,conversationId:o,files:a.files,tokenManager:A});if(!ln({attempt:g,currentAttempt:dt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;ke(u,A,o,"message_sent",{messageId:a.id});let wo=us({clientSubmittedAt:Cr,clientTools:he,imageSearch:u.imageSearch,modelId:a.modelId,newsSearch:u.newsSearch,pageContext:Be,permissionMode:de,turnId:a.id,webSearch:u.webSearch});ge(jn("accepted")),await Q.sendMessage(xl(a,mt),{body:wo});let yn=It.current;if(yn)throw It.current=null,yn}catch(Be){if(!ln({attempt:g,currentAttempt:dt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;throw Be instanceof Error&&P(Be.message),Xs(C),Q.clearError(),bt(!1),E(!1),pe(!1),ge(null),Be}},[Q,ve,we,o,d,u,mr,P,Xs,A,Ee]),Un=W((a,{resumeDrainAfter:g=!0}={})=>{le.current=a.id,oa(a).catch(()=>{le.current===a.id&&(le.current=null),qt.current.has(a.id)||ze(C=>ht(En(As(C,{...a,deliveryStatus:"pending"},"prepend"),a.id,"pending"),a.id))}).finally(()=>{le.current===a.id&&(le.current=null),g&&Kt(C=>C+1)})},[oa,ze]),Zt=W((a,g)=>{let C=a.trim();if(!C&&y.length===0)return;let G=!At&&!le.current&&Le.current.messages.length===0,ue=kl({activeMessageId:le.current,authoritativeMessageCount:Q.messages.length,isNewChatStartScreen:x,queuedMessageCount:Le.current.messages.length}),de={files:y,id:g?.messageId??crypto.randomUUID(),...ue?{isInitialTurn:!0}:{},...pn?{modelId:pn}:{},permissionMode:we,selection:U,text:C};G&&(de.deliveryStatus="sending"),ue&&re({files:de.files,id:de.id,text:de.text}),Ee.begin(de.id,g),g?.firstFeedbackPaintedAt!==void 0&&Ee.markPaintedAt(de.id,"first_feedback_paint",g.firstFeedbackPaintedAt),G&&(le.current=de.id),et(he=>rr(As(he,de),!1),{applyAfterPersist:!0}).then(()=>{ra(),G?Un(de):Kt(he=>he+1)}).catch(he=>{G&&(le.current=null),ue&&re(null),g&&k(C),P(he instanceof Error?he.message:"This message could not be saved before sending")})},[y,pn,we,et,Q.messages.length,At,ra,U,Un,P,x,Ee]),gn=n.suggestedPrompts,nu=Vt(a=>Zt(a.prompt,a));be(()=>{if(!e)return;ka(u.agentId);let a=Pa(u.agentId);a&&(a.submitted?nu(a):k(g=>g||a.prompt))},[e,u.agentId]),be(()=>{if(!e||!u.suggestedPromptShortcuts||Q.messages.length>0||gn.length===0)return;let a=g=>{let C=el(g,gn.length);if(C===null)return;let G=gn[C];G&&(g.preventDefault(),Zt(G))};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e,Q.messages.length,u.suggestedPromptShortcuts,Zt,gn]);let sa=a=>{a.preventDefault(),Zt(D)},ru=Vt(async a=>{try{await et(g=>En(g,a.id,"sending"))}catch(g){le.current===a.id&&(le.current=null),P(g instanceof Error?g.message:"This message could not be saved before sending"),ze(C=>ht(C,a.id));return}le.current===a.id&&Un({...a,deliveryStatus:"sending"})}),ou=W(a=>{_n.current=a,st(a)},[]);be(()=>{let a=Ll({activeMessageId:le.current,isBusy:At,isReordering:Ge,queue:s});a&&(le.current=a.id,queueMicrotask(()=>{if(_n.current){le.current===a.id&&(le.current=null);return}le.current===a.id&&ru(a)}))},[At,Ge,s,Et]);let su=W(a=>{re(g=>g?.id===a?null:g),ze(g=>nr(g,a))},[ze]),au=W((a,g,C)=>{ze(G=>Al(ht(G,null),a,g,C))},[ze]),iu=W(a=>{let g=Le.current.messages.find(C=>C.id===a);g&&(Qe(),k(g.text),T(g.files),g.modelId&&_(g.modelId),g.permissionMode&&qe(g.permissionMode),V(g.selection),H(!0),re(C=>C?.id===a?null:C),ze(C=>nr(ht(C,null),a)),requestAnimationFrame(()=>St.current?.focus()))},[Qe,T,ze,qe,_]),lu=W(a=>{if(At||le.current)return;let g=Le.current.messages.find(C=>C.id===a);g&&(le.current=g.id,et(C=>rr(En(ht(C,null),a,"sending"),!0)).then(()=>{le.current===g.id&&Un({...g,deliveryStatus:"sending"},{resumeDrainAfter:!1})}).catch(C=>{le.current===g.id&&(le.current=null),P(C instanceof Error?C.message:"This message could not be saved before sending")}))},[et,At,Un,P]),aa=W(()=>{let a=le.current;dr.current+=1,dt.current+=1,Ze.current=!0,He.current=!1,le.current=null,re(null),ze(C=>rr(a&&!qt.current.has(a)?En(ht(C,null),a,"pending"):ht(C,null),!0)),pe(!1),ge(null),bt(!1),E(!1),ke(u,A,o,"stopped");let g=Promise.resolve().then(()=>Q.stop()).catch(()=>{}).finally(()=>{Qt.current===g&&(Qt.current=null),On.current()});Qt.current=g},[Q,o,u,ze,A]),cu=Vt(()=>{if(Ze.current||He.current)return;let a=le.current;dr.current+=1,dt.current+=1,He.current=!0,le.current=null,ze(C=>rr(a?nr(ht(C,null),a):ht(C,null),!0)),pe(!1),ge(null),bt(!1),E(!0),ke(u,A,o,"turn_stalled",{messageId:a??void 0,source:"client-inactivity-watchdog"});let g=Promise.resolve().then(()=>Q.stop()).catch(()=>{}).finally(()=>{Qt.current===g&&(Qt.current=null),On.current(),He.current&&E(!0)});Qt.current=g});be(()=>{if(Ac({hasActiveTurn:Ue,hasPendingClientToolCalls:Yt,isResuming:Xt,stalled:lt}))return Tc(cu)},[Q.isRecovering,Q.messages,Q.status,gr,Ue,Yt,Xt,Je,it,lt]);let uu=W(a=>{if(ke(u,A,o,`component_${a.type}`,{actionId:"actionId"in a?a.actionId:void 0,componentId:a.componentId,format:"format"in a?a.format:void 0,hasToolName:"toolName"in a}),a.type==="tool"){let g=Sa(De,a.toolName);if(g){(async()=>{try{let C=Ar(g,a.args),G=`component-action-${crypto.randomUUID()}`;await g.execute(C,u.context,{conversationId:o,idempotencyKey:`heroui-agent-component-action:${o}:${G}`,toolCallId:G})}catch{}})();return}}Qi(a,{fillComposer:g=>{Qe(),k(g),H(!0),requestAnimationFrame(()=>St.current?.focus())},setSelection:V,submitPrompt:Zt})},[Qe,De,o,u,Zt,A]),du=W(a=>{let g=a.parts.filter(C=>C.type==="text").map(C=>C.text).join(`
4
-
5
- `).trim();g&&(navigator.clipboard?.writeText(g).catch(()=>{}),ke(u,A,o,"message_copied",{messageId:a.id}))},[o,u,A]),pu=W((a,g,C)=>{let G=K[a]===g&&!C;if(ye(ue=>{let de={...ue};return G?delete de[a]:de[a]=g,de}),!G){let ue=C?.comment,de=C?.reasons??[];ke(u,A,o,g==="up"?"feedback_up":"feedback_down",{feedbackCommentLength:ue?.length??0,feedbackReasons:de,hasFeedbackComment:!!ue,messageId:a});try{Promise.resolve(u.onFeedback?.({...ue?{comment:ue}:{},conversationId:o,messageId:a,rating:g==="up"?"positive":"negative",reasons:de})).catch(()=>{})}catch{}}},[o,K,u,A]),ia=W(()=>{let a=++dr.current;(async()=>{let g=Qt.current;if(!await Sc(g,()=>dr.current===a))return;let C=++dt.current,G=Ot(vn(u.tools,we)),ue=crypto.randomUUID(),de=Date.now();zt.current=null,pr.current=de,ve({modelId:pn,permissionMode:we}),mr(),po.current=null,pe(!0),bt(!1),E(!1),ge(jn("accepted")),ke(u,A,o,"retry");try{let he=await Hc(u,U);if(!ln({attempt:C,currentAttempt:dt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;await Q.regenerate({body:us({clientSubmittedAt:de,clientTools:G,imageSearch:u.imageSearch,modelId:pn,newsSearch:u.newsSearch,pageContext:he,permissionMode:we,turnId:ue,webSearch:u.webSearch})})}catch{if(!ln({attempt:C,currentAttempt:dt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;bt(!0)}finally{Ws(C)}})()},[ve,Q,pn,we,Ws,o,u,mr,U,A]),mu=Q.messages.findLast(a=>a.role==="assistant")?.id,tt=_l({authoritativeMessageCount:Q.messages.length,localTurn:Y,queue:s}),fn=Ae(()=>tt?{id:tt.id,parts:[{text:Nl(tt),type:"text"}],role:"user"}:null,[tt]),Bn=Ae(()=>fn?[fn,...Q.messages]:Q.messages,[Q.messages,fn]),gu=fn!==null,yr=!!(tt&&!s.isPaused&&s.blockedMessageId!==tt.id),la=!!(Q.error||Q.connectionError||xt||pt),ca=Bn.findLast(a=>a.role==="user")?.id,{activeStreamKey:vr,activeTurnMessageId:ua}=ul({isActive:Ue||yr,lastUserMessageId:ca,pendingTurn:fn&&yr?{previousUserMessageId:null,scrollKey:fn.id}:po.current}),da=ci({clientToolNames:kn,isLocalPending:Je,isRecovering:Q.isRecovering||js,isStreaming:Ct,messages:Q.messages,status:Q.status}),{showHome:pa,standaloneStatus:fu}=ll({hasActiveActivity:ta,hasError:la,hasResponseStarted:Zc,isActiveTurn:Ue||yr,messageCount:Bn.length,preferHomeWhileEmpty:x,progress:yr?Jn:it??jn(da),runtimeStatus:Xt?"pending":"ready"}),ma=al({activeStreamKey:vr,activeTurnMessageId:ua}),ga=pa||ma&&Bn.length===0,nt=Ee.getActiveMessageId(),hu=nt?go.current.get(nt):void 0,fa=nt&&Tt?.role==="assistant"&&Tt.id!==hu?Tt:void 0,Fn=Bs(fa,{hasActivity:!!(fa&&ta),hasTransientData:!!(nt&&mo.current.has(nt))}),Mo=gu&&la?null:fu,br=!ma&&Mo&&(e||Mo!==Jn)?Mo:null,ha=!!br;$t(()=>{if(e){for(let a of s.messages)Ee.markAfterPaint(a.id,"first_feedback_paint");tt&&Ee.markAfterPaint(tt.id,"first_feedback_paint"),nt&&((ha||Fn.hasServerContent||Q.error||Q.connectionError||xt||pt)&&Ee.markAfterPaint(nt,"first_feedback_paint"),Fn.hasServerContent&&Ee.markAfterPaint(nt,"first_server_content_paint"),Fn.hasText&&Ee.markAfterPaint(nt,"first_text_paint"))}},[e,nt,Q.connectionError,Q.error,ha,s.messages,tt,xt,pt,Fn.hasServerContent,Fn.hasText,Ee]);let yu=Ae(()=>Ol(s,tt?.id??null),[s,tt?.id]),Sr=!!(D.trim()||y.length>0),ya=Ln?"Cancel transcription":Ne?"Stop dictation":"Dictate message",va=Wt?ya:"Voice dictation is not supported in this browser",hn=Ct&&!Sr?"Stop answering":At&&!(x&&Bn.length===0)?"Queue message":"Send message";return Pe(cn,{children:[Pe(fl,{activityPhase:da,streamKey:vr,children:[ga?Pe("div",{className:"ha-empty",children:[I("h2",{children:u.greeting}),I("p",{children:"Live answers with charts, metrics, and tables."})]}):Bn.map(a=>I(Qg,{actions:u.messageActions,activityTiming:j[a.id],canRetry:a.id===mu&&!At,clientTools:De,exportFormats:u.componentExportFormats,feedback:K[a.id]??null,isActivityActive:a.id===Jt,isStreaming:a.id===ea,markdownAnimation:u.markdownAnimation,markdownCaret:u.markdownCaret,markdownPlugins:u.markdownPlugins,message:a,toolDecisions:J,turnAnchor:a.id===ua&&vr!==null?"active":a.id===ca?"latest":null,onAction:uu,onClientToolDecision:eu,onCopy:du,onFeedback:pu,onRetry:ia,onSelect:V},a.id)),br?I("div",{className:"ha-message","data-role":"assistant","data-stream-anchor":"true","data-turn-feedback-id":nt??void 0,children:I("div",{className:"ha-message-body",children:br===Jn?I(yc,{},vr??o):I(Gr,{label:br})})}):null,Q.error||Q.connectionError||xt||pt?Pe("div",{className:"ha-error",role:"alert",children:[I("span",{children:pt?"The assistant connection could not be restored.":lt?"The assistant stopped responding. Please retry.":"The request could not be completed."}),I("button",{type:"button",onClick:pt?jc:ia,children:"Retry"})]}):null]}),Pe("form",{className:"ha-composer-wrap",onBlur:Qc,onSubmit:sa,children:[pa&&gn.length>0?I("div",{"aria-label":"Suggested prompts",className:"ha-suggestions",role:"group",children:gn.map((a,g)=>Pe("button",{className:"ha-suggestion",type:"button","aria-keyshortcuts":u.suggestedPromptShortcuts?`Control+${g+1}`:void 0,onClick:()=>Zt(a),children:[I("span",{children:a}),u.suggestedPromptShortcuts?Pe("span",{"aria-hidden":"true",className:"ha-suggestion-shortcut",children:[I("kbd",{children:"Ctrl"}),I("kbd",{children:g+1})]}):I(Dg,{"aria-hidden":"true"})]},a))}):null,U?I(ji,{title:U.componentTitle,onRemove:()=>V(null)}):null,ga?null:I(Bl,{ref:Ks,blockedMessageId:s.blockedMessageId,isSendNowDisabled:At,messages:yu,onEdit:iu,onFocusComposer:tu,onRemove:su,onReorder:au,onReorderStateChange:ou,onSendNow:lu}),Pe(Yi,{className:"@container ha-composer","data-controls-revealed":yo||void 0,"data-dictating":Ne||void 0,"data-expanded":Ne||Se?!0:void 0,disabled:u.composerAttachmentContentTypes.length===0,onFilesSelected:na,onFileIntent:u.composerAttachmentContentTypes.length>0?zs:void 0,children:[I("textarea",{ref:St,"aria-label":"Message the assistant",placeholder:u.composerPlaceholder,readOnly:Ne,rows:1,value:D,onFocus:qc,onSelect:a=>$n(u.agentId,!0,a.currentTarget),onChange:a=>{k(a.currentTarget.value),$n(u.agentId,!0,a.currentTarget),To(a.currentTarget)},onKeyDown:a=>{if(!Ne&&!Hl(a,Ks.current)&&Ji(a.nativeEvent)){if(a.preventDefault(),Ct&&!Sr){aa();return}sa(a)}}}),u.composerAttachmentContentTypes.length>0?I("input",{ref:$s,multiple:!0,accept:u.composerAttachmentAccept,"aria-label":"Choose files to attach",className:"ha-file-input",type:"file",onChange:a=>{let g=Array.from(a.currentTarget.files??[]);na(g),a.currentTarget.value=""}}):null,y.length>0?I(Do,{"aria-label":"Selected attachments",className:"ha-attachments",offset:1,size:24,children:y.map(a=>I(ps,{file:a,onRemove:()=>{P(null),T(g=>g.filter(C=>C!==a))}},`${a.name}-${a.size}-${a.lastModified}`))}):null,u.composerAttachmentContentTypes.length>0?I("button",{"aria-label":"Attach files",className:"ha-attach",type:"button",onClick:()=>$s.current?.click(),children:I(Bc,{"aria-hidden":"true"})}):null,Ne?I("div",{className:"ha-dictation-session",children:Ln?I("span",{className:"ha-dictation-status",role:"status",children:"Transcribing\u2026"}):Pe(cn,{children:[I(jo,{active:Kc,"aria-hidden":"true",className:"ha-dictation-waveform",height:28,stream:Gc}),I("time",{"aria-label":`Recording duration ${Hr(fo)}`,className:"ha-dictation-duration",dateTime:`PT${fo}S`,children:Hr(fo)})]})}):null,u.permissionShowPicker&&u.tools.length>0&&!Ne?I(Nr,{"aria-label":"Tool permissions",className:"ha-permission-picker",isDisabled:Js,value:_e,onChange:qe}):null,u.composerModelPicker&&!Ne?I(xr,{"aria-label":"AI model",className:"ha-model-picker",isDisabled:Js,options:xo,value:O,placement:u.permissionShowPicker&&u.tools.length>0?"top":"top start",onChange:_}):null,u.composerDictation?Pe("button",{"aria-keyshortcuts":Wt?Xi:void 0,"aria-label":ya,"aria-pressed":Ne,className:"ha-dictation","data-shortcut":Wt?"\u2303\u21E7D":void 0,"data-tooltip":va,disabled:!Wt,type:"button",onClick:Ro,children:[Ln?I(Lg,{"aria-hidden":"true"}):Ne?I(Oc,{"aria-hidden":"true"}):I(Uc,{"aria-hidden":"true"}),I(Vn,{shortcut:Wt?"\u2303\u21E7D":void 0,children:va})]}):null,M||u.composerDictation&&ho?I("span",{className:"ha-dictation-error",role:"alert",children:M??ho}):null,Ct&&!Sr?Pe("button",{"aria-keyshortcuts":fs,"aria-label":hn,className:"ha-send","data-shortcut":"\u21B5","data-tooltip":hn,type:"button",onClick:aa,children:[I(Oc,{"aria-hidden":"true"}),I(Vn,{shortcut:"\u21B5",children:hn})]}):Pe("button",{"aria-keyshortcuts":fs,"aria-label":hn,className:"ha-send","data-shortcut":"\u21B5","data-tooltip":hn,disabled:!Sr||Ne,type:"submit",children:[I(Og,{"aria-hidden":"true"}),I(Vn,{shortcut:"\u21B5",children:hn})]})]}),I("div",{className:"ha-composer-footer","data-revealed":!!u.composerDisclaimer||void 0,children:I("div",{className:"ha-composer-footer-content",children:u.composerDisclaimer?I("p",{className:"ha-footnote",children:Io(u.composerDisclaimer)}):null})}),I(Oa,{})]})]})}function Qg({actions:e,activityTiming:t,canRetry:n,clientTools:r,exportFormats:o,feedback:s,isActivityActive:i,isStreaming:d,markdownAnimation:l,markdownCaret:c,markdownPlugins:m,message:p,onAction:S,onClientToolDecision:u,onCopy:h,onFeedback:x,onRetry:w,onSelect:A,toolDecisions:O,turnAnchor:_}){let N=ns(p,r,{isStreaming:i}),L=rc(p.parts),$=p.parts.some(ds);be(()=>{$&&hl()},[$]);let X=d?p.parts.findLastIndex(T=>T.type==="text"):-1,b=p.role==="user"?p.parts.flatMap((T,P)=>T.type==="file"?[I(Cs,{file:T},`${p.id}-attachment-${P}`)]:[]):[],{items:f,latestContentPartIndex:v}=p.parts.reduce((T,P,z)=>{let ie=K=>({items:[...T.items,K],latestContentPartIndex:z});if(P.type==="text")return P.text.trim()?ie(p.role==="assistant"?I($r,{animated:l,caret:c,isStreaming:z===X,plugins:m,children:P.text},`${p.id}-text-${z}`):I("p",{className:"ha-message-text",children:P.text},`${p.id}-text-${z}`)):T;if(P.type==="file")return p.role==="user"?T:ie(I(Cs,{file:P},`${p.id}-file-${z}`));if(P.type==="data-component")return ie(I(vl,{component:P.data,exportFormats:o,onAction:S,onSelect:A},P.data.id));if(ds(P))return T;let j=Vs(P),F=j?r.get(j):void 0;if(j&&F){let K=P;return K.state!=="approval-requested"||O[K.toolCallId]?T:ie(I(zg,{decision:O[K.toolCallId],part:K,tool:F,onDecision:ye=>u(j,K,ye)},K.toolCallId))}return T},{items:[],latestContentPartIndex:-1}),R=li(N,{hasContent:f.length>0,latestContentPartIndex:v}),y=oc(L,{hasContent:f.length>0,isStreaming:i});if(f.length===0&&b.length===0&&N.length===0&&y.length===0)return null;if(p.role==="user")return Pe("div",{className:"ha-message","data-role":"user","data-stream-anchor":_==="active"?!0:void 0,"data-turn-anchor":_?!0:void 0,children:[b.length>0?I("div",{"aria-label":"Message attachments",className:"ha-message-attachments",children:b}):null,f.length>0?I("div",{className:"ha-bubble",children:I("div",{className:"ha-message-content",children:f})}):null]});let M=p.parts.some(T=>T.type==="text"&&T.text.trim().length>0);return I("div",{className:"ha-message","data-role":"assistant","data-stream-anchor":i?!0:void 0,children:Pe("div",{className:"ha-message-body",children:[N.length>0?I(Si,{completedAt:t?.completedAt,hasResponseStarted:R,isStreaming:i,items:N,markdownAnimation:l,markdownPlugins:m,startedAt:t?.startedAt}):null,f.length>0?I("div",{className:"ha-message-content",children:f}):null,I(nc,{sources:y}),!i&&f.length>0&&e.length>0?I(Sl,{actions:e,feedback:s,onCopy:M?()=>h(p):void 0,onFeedback:(T,P)=>x(p.id,T,P),onRetry:n?w:void 0}):null]})})}function zg({decision:e,onDecision:t,part:n,tool:r}){if(n.state!=="approval-requested"||e)return null;let o=r.icon;return I(qa,{"data-tool-status":"approval-requested",icon:o?I(o,{color:r.iconColor,size:16}):void 0,input:n.input,title:r.displayName??r.name,onApprove:()=>t(!0),onDeny:()=>t(!1)})}function Wg({conversationId:e,onRuntimeRevisionStale:t,onTurnAdmitted:n,options:r,runtime:o,tokenManager:s}){let i=Ae(()=>Ki(o),[o]),d=r.apiBaseUrl,l=Ae(()=>Gi(o,()=>ki({apiBaseUrl:d},s,e,o.runtimeRevision)),[d,e,o,s]),[c,m]=ee(0),[p,S]=ee(0),[u,h]=ee(null),[x,w]=ee(!0),[A,O]=ee(!1),_=ce(null),N=ce(!1),L=Vg(),$=W(()=>{let M=new Error("The assistant connection could not be restored");_.current=M,N.current=!1,h(M),w(!1),O(!1)},[]),X=W(async()=>{try{return{ticket:(await l.next()).ticket}}catch(M){return M instanceof Tn?(t(e),new Promise(()=>{})):($(),{ticket:""})}},[e,$,t,l]),b=W(()=>{_.current=null,h(null),m(M=>M+1),O(!1),N.current&&(N.current=!1,ke(r,s,e,"reconnected"))},[e,r,s]),f=W(M=>{if(!_.current){if(Ug(M)){$();return}N.current=!0,w(!0),O(!0)}},[$]),v=W(M=>{let T=qi(M),P=typeof T?.type=="string"?T.type:null;P===Ba&&T?.protocolVersion===6&&typeof T.turnId=="string"&&n(T.turnId),(P==="cf_agent_chat_messages"||P==="cf_agent_stream_resume_none"||P==="cf_agent_stream_resuming"||P==="cf_agent_stream_pending"||P==="cf_agent_use_chat_response")&&(_.current=null,h(null),w(!1))},[n]),R=Bg({agent:"HeroUIConversationAgent",basePath:i.basePath,cacheTtl:3600*1e3,enabled:_.current===null,host:i.host,name:e,...i.path?{path:i.path}:{},onClose:f,onConnectionError:$,onIdentityChange:()=>{},onMessage:v,onOpen:b,protocol:i.protocol,query:X,queryDeps:[e,o.runtimeRevision,L,p]});be(()=>{if(!(u||!x&&!A))return Rc($)},[c,u,$,x,A]);let y=W(()=>{_.current=null,N.current=!0,h(null),w(!0),O(!0),S(M=>M+1)},[]);return be(()=>{if(u)return;let M=!1,T=null,P,z=j=>{M||(P=window.setTimeout(()=>void ie(),j))},ie=async()=>{let j;try{j=await l.refresh()}catch(F){if(F instanceof Tn){t(e);return}if(F instanceof Yn&&!F.retryable){$();return}if(T??=Date.now(),Date.now()-T>=12e4){$();return}z(15e3);return}try{await R.call("renewConnection",[j.ticket],{timeout:15e3}),T=null,z(27e4)}catch{R.reconnect()}};return z(27e4),()=>{M=!0,P!==void 0&&window.clearTimeout(P)}},[R,c,u,e,$,t,l]),{agent:R,connectionEpoch:c,connectionError:u,isHydrating:x,isReconnecting:A,retryConnection:y}}async function Hc(e,t){let n=await e.context?.page?.()??{},r=t?{...n,componentSelection:t}:n,o;try{o=JSON.stringify(r)}catch{throw new Error("HeroUI Agent page context must be JSON serializable")}if(new TextEncoder().encode(o).byteLength>16*1024)throw new Error("HeroUI Agent page context exceeds 16KB");return JSON.parse(o)}export{Kg as default};