@heroui/agent 0.2.0-beta.12 → 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 +1,5 @@
1
- "use client";import{a as Oo,b as Do,d as Ho}from"./chunk-CLHBM3HQ.js";import{a as Ha,c as Sn}from"./chunk-S6OIAJSC.js";import{a as me}from"./chunk-CR3H7AVI.js";import{A as Mr,B as _o,C as bn,D as La,b as We,d as Ca,e as $n,g as Aa,h as Ta,i as Eo,j as Po,m as Ea,n as Pa,o as Kn,p as Ia,q as xa,r as ka,s as ko,t as Na,u as _a,v as Oa,w as Da,x as Tr,y as No,z as Rr}from"./chunk-IMH6S52M.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-UHHKMESI.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 Mt(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"?Mt(e)?e:null:Mt(t)?t:null}var Er=30,qa=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"&&Mt(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 qn(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()?qo(n):t?"Attachment":null}function Ko(e,t){return e?qo(e):t[0]?.name||"Attachment"}function qo(e){let t=e.replace(/\s+/g," ").trim();return t.length>qa?`${t.slice(0,qa-1).trimEnd()}\u2026`:t}function Go(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 Cn}from"@heroui/react";import{jsx as Fe,jsxs as tn}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 Ga({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 tn("section",{"aria-label":l,className:me("aui-approval",t),"data-slot":"agent-ui-approval",...c,children:[tn("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,tn("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?tn(Cn,{defaultExpanded:!0,className:"aui-approval__disclosure",children:[Fe(Cn.Heading,{children:tn(Cn.Trigger,{className:"aui-approval__disclosure-trigger",children:["Review action details",Fe(Cn.Indicator,{})]})}),Fe(Cn.Content,{children:Fe(Cn.Body,{children:m?Fe("dl",{className:"aui-approval__details","data-slot":"agent-ui-approval-details",children:m.map(([S,u])=>tn("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,tn("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 G,jsxs as Gn}from"react/jsx-runtime";function Qa({className:e,provider:t}){let n=t?.toLowerCase();return n==="openai"?G(Cu,{className:e,"data-provider":"openai"}):n==="google"?G(Au,{className:e,"data-provider":"google"}):n==="anthropic"?G(Tu,{className:e,"data-provider":"anthropic"}):n==="moonshot ai"?G(Ru,{className:e,"data-provider":"moonshot-ai"}):null}function Cu(e){return G("svg",{"aria-hidden":"true",fill:"currentColor",focusable:"false",role:"presentation",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",...e,children:G("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:[G("path",{d:"M0 0h32v32H0z",fill:"none"}),G("defs",{children:G("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:[G("use",{href:`#${n}`}),G("g",{filter:`url(#${o})`,children:G("ellipse",{cx:"14.208",cy:"16.716",fill:"#ffe432",rx:"14.208",ry:"16.716",transform:"rotate(19.552 -43.96 -16.268)"})}),G("g",{filter:`url(#${s})`,children:G("ellipse",{cx:"27.054",cy:"2.551",fill:"#fc413d",rx:"18.394",ry:"18.799"})}),G("g",{filter:`url(#${i})`,children:G("ellipse",{cx:"19.224",cy:"24.904",fill:"#00b95c",rx:"19.224",ry:"24.904",transform:"rotate(-2.799 667.58 51.694)"})}),G("g",{filter:`url(#${i})`,children:G("ellipse",{cx:"18.843",cy:"20.744",fill:"#00b95c",rx:"18.843",ry:"20.744",transform:"rotate(-31.317 81.174 36.482)"})}),G("g",{filter:`url(#${d})`,children:G("ellipse",{cx:"66.462",cy:"24.977",fill:"#3186ff",rx:"18.093",ry:"17.423"})}),G("g",{filter:`url(#${l})`,children:G("ellipse",{cx:"20.929",cy:"22.075",fill:"#fbbc04",rx:"20.929",ry:"22.075",transform:"rotate(37.251 9.618 -7.898)"})}),G("g",{filter:`url(#${c})`,children:G("ellipse",{cx:"24.131",cy:"22.292",fill:"#3186ff",rx:"24.131",ry:"22.292",transform:"rotate(34.51 19.317 63.957)"})}),G("g",{filter:`url(#${m})`,children:G("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"})}),G("g",{filter:`url(#${p})`,children:G("ellipse",{cx:"27.585",cy:"17.148",fill:"#fc413d",rx:"27.585",ry:"17.148",transform:"rotate(-42.847 5.973 20.37)"})}),G("g",{filter:`url(#${S})`,children:G("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:[G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"42.756",id:o,width:"38.868",x:"-19.618",y:"12.903",children:G("feGaussianBlur",{stdDeviation:"2.46"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"85.162",id:s,width:"84.353",x:"-15.122",y:"-40.03",children:G("feGaussianBlur",{stdDeviation:"11.891"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"90.22",id:i,width:"78.916",x:"-20.768",y:"11.483",children:G("feGaussianBlur",{stdDeviation:"10.109"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"73.27",id:d,width:"74.611",x:"29.156",y:"-11.658",children:G("feGaussianBlur",{stdDeviation:"9.606"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"78.151",id:l,width:"77.538",x:"-38.291",y:"-16.269",children:G("feGaussianBlur",{stdDeviation:"8.706"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"76.898",id:c,width:"78.218",x:"7.78",y:"-6.098",children:G("feGaussianBlur",{stdDeviation:"7.775"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"51.479",id:m,width:"55.879",x:"13.208",y:"-18.425",children:G("feGaussianBlur",{stdDeviation:"6.957"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"68.674",id:p,width:"70.203",x:"-15.474",y:"-31.027",children:G("feGaussianBlur",{stdDeviation:"5.876"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"51.261",id:S,width:"55.137",x:"-14.173",y:"20.474",children:G("feGaussianBlur",{stdDeviation:"7.273"})}),G("mask",{height:"64",id:r,maskUnits:"userSpaceOnUse",width:"64",x:"0",y:"0",children:G("use",{href:`#${n}`})})]})]})]})}function Tu(e){return G("svg",{"aria-hidden":"true",fill:"none",focusable:"false",role:"presentation",viewBox:"0 0 256 257",xmlns:"http://www.w3.org/2000/svg",...e,children:G("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:[G("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"}),G("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"}),G("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 ft,jsxs as zn}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(C=>C.id===i),x=Eu(C=>{S.current=C,C?.setAttribute("aria-keyshortcuts","Control+Shift+M"),m(Sn(C))},[]),w=C=>{!C&&Date.now()-p.current<350||l(C)};return Pu(()=>{if(u)return;let C=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",C),()=>document.removeEventListener("keydown",C)},[u]),zn(Qn,{"aria-label":e,className:me("aui-model-picker",t),isDisabled:u,isOpen:d,value:i,onOpenChange:w,onChange:C=>{C!=null&&r(C),l(!1)},children:[zn(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:[ft(Qn.Value,{className:"aui-model-picker__value",children:h?.label??i}),ft(Qn.Indicator,{className:"aui-model-picker__indicator"}),zn("span",{"aria-hidden":"true",className:"aui-picker-tooltip",children:[ft("span",{children:"Select model"}),ft("kbd",{className:"aui-picker-tooltip__shortcut",children:"\u2303\u21E7M"})]})]}),ft(Qn.Popover,{className:"aui-model-picker__popover",placement:s,UNSTABLE_portalContainer:c,children:ft(Qo,{"aria-label":`${e} options`,className:"aui-model-picker__list",children:o.map(C=>{let O=Iu(C);return zn(Qo.Item,{className:"aui-model-picker__option","data-description":O,id:C.id,textValue:C.label,children:[ft(Qa,{className:"aui-model-picker__option-icon",provider:C.provider}),zn("span",{className:"aui-model-picker__option-copy",children:[ft(wu,{className:"aui-model-picker__option-label",children:C.label}),O?ft(Mu,{className:"aui-model-picker__option-description",title:O,children:O}):null]}),ft(Qo.ItemIndicator,{className:"aui-model-picker__option-indicator"})]},C.id)})})})]})}import{Hand as xu,LockOpen as ku,ShieldCheck as Ja}from"@gravity-ui/icons";import{Description as Nu,Label as _u,ListBox as zo,Select as Wn}from"@heroui/react";import{useCallback as Ou,useEffect as Du,useRef as ja,useState as Ya}from"react";import{jsx as ot,jsxs as jn}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:ku,id:"full",label:"Full access"}];function kr({"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(Sn(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]),jn(Wn,{"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:[jn(Wn.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:[ot(Ja,{"aria-hidden":"true",className:"aui-permission-picker__trigger-icon"}),ot(Wn.Value,{className:"aui-permission-picker__value",children:p?.label??o}),ot(Wn.Indicator,{className:"aui-permission-picker__indicator"}),jn("span",{"aria-hidden":"true",className:"aui-picker-tooltip",children:[ot("span",{children:"Change permissions"}),ot("kbd",{className:"aui-picker-tooltip__shortcut",children:"\u2303\u21E7P"})]})]}),ot(Wn.Popover,{className:"aui-permission-picker__popover",placement:"top start",UNSTABLE_portalContainer:d,children:ot(zo,{"aria-label":`${e} options`,className:"aui-permission-picker__list",children:Xa.map(h=>{let x=h.icon;return jn(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:[ot(x,{"aria-hidden":"true",className:"aui-permission-picker__option-icon"}),jn("span",{className:"aui-permission-picker__option-copy",children:[ot(_u,{className:"aui-permission-picker__option-label",children:h.label}),ot(Nu,{className:"aui-permission-picker__option-description",title:h.description,children:h.description})]}),ot(zo.ItemIndicator,{className:"aui-permission-picker__option-indicator"})]},h.id)})})})]})}import{useEffect as Wo,useRef as An}from"react";import{jsx as ei}from"react/jsx-runtime";var Lu=40,Za=2;function Nr(e,t,n){return Math.min(n,Math.max(t,e))}function Hu(e){let t=Nr(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:C,...O}){let _=An(null),k=An({onError:m,onStreamEnd:p,onStreamReady:S}),L=An(null),$=An(null),X=An(null),b=An([]);Wo(()=>{k.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,k.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=Nr(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,k.current.onStreamReady?.(F)}catch(Se){K(!1),T||k.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 N=Math.max(1,r),Y=Math.max(0,n),re=N+Y,oe=Math.max(1,Math.floor((K+Y)/re)),Me=Math.ceil(oe/2),qe=_.current;b.current.length!==Me&&(b.current=Array.from({length:Me},()=>0));let it=b.current;if(e&&qe){let de=X.current;(!de||de.length!==qe.frequencyBinCount)&&(de=new Uint8Array(qe.frequencyBinCount),X.current=de),qe.getByteFrequencyData(de);let Oe=Math.max(1,Math.floor(de.length*.025)),bt=Math.max(Oe+1,Math.floor(de.length*.46)),lt=Nr(h,0,4);for(let ge=0;ge<Me;ge+=1){let Pt=Me<=1?0:ge/(Me-1),qt=Math.min(de.length-1,Math.round(Oe+Pt*(bt-Oe))),It=Math.pow((de[qt]??0)/255*lt,.72);it[ge]=Nr((it[ge]??0)*.56+It*.44,0,1)}}else it.fill(0);let dn=Math.max(Za,F*.84),kn=F/2,Et=oe*N+(oe-1)*Y,Je=(K-Et)/2;for(let de=0;de<oe;de+=1){let Oe=Me-1-Math.min(de,oe-1-de),bt=e?it[Oe]??0:0,lt=Math.max(Za,bt*dn),ge=Je+de*re,Pt=kn-lt/2;P.globalAlpha=e?.38+bt*.62:.2,$u(P,ge,Pt,N,lt)}P.globalAlpha=1},Se=()=>{let D=T.getBoundingClientRect(),N=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*N)),M.height=Math.max(1,Math.round(F*N)),M.style.width=`${K}px`,M.style.height=`${F}px`,P.setTransform(N,0,0,N,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={...C,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.",qu="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.",Gu=["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 qu}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 Gu.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),C=$e(e),O=$e(t),_=$e(null),k=$e(null),L=$e(0),$=$e(0),X=$e(n),b=$e(null),f=$e(new Map),v=$e(r);ti(()=>{C.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}),N=X.current;if(!N||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 N(D,{...C.current?{language:C.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=k.current;if(_.current=null,k.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=k.current;if(B){y();try{B.stop()}catch(D){R("idle"),L.current+=1,k.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 N={chunks:[],recorder:D,session:H,stream:B};D.ondataavailable=Y=>{Y.data.size>0&&N.chunks.push(Y.data)},D.onerror=Y=>{L.current!==H||_.current!==N||(L.current+=1,_.current=null,y(),z(N,!0),p(null),R("idle"),c(Yu(Y).message))},D.onstop=()=>{ie(N)},_.current=N,p(B);try{D.start(1e3),M()}catch(Y){L.current+=1,_.current=null,z(N,!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(N){c(N instanceof Error?N.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,C.current&&(B.lang=C.current),B.onstart=()=>{L.current===D&&(R("recognizing"),M())},B.onresult=N=>{if(L.current!==D)return;let Y=Math.max(0,N.resultIndex);for(let oe of f.current.keys())oe>=Y&&f.current.delete(oe);for(let oe=Y;oe<N.results.length;oe+=1){let qe=N.results[oe]?.[0]?.transcript;typeof qe=="string"&&f.current.set(oe,qe)}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=N=>{if(L.current!==D)return;y(),R("idle"),f.current.clear(),L.current+=1;let Y=L.current;N.error!=="aborted"&&(N.error==="not-allowed"?zu().then(re=>{L.current===Y&&c(Jo(N.error,N.message,re))}):c(Jo(N.error,N.message))),k.current===B&&(k.current=null,T(B))},B.onend=()=>{L.current===D&&(y(),R("idle"),k.current===B&&(k.current=null,T(B)))},k.current=B,c(null),d(0),R("recognizing");try{B.start()}catch(N){T(B),k.current=null,y(),R("idle"),c(N instanceof Error?N.message:"Voice dictation could not be started.")}},[T,M,y,R]),Se=Ve(()=>{h.current!=="idle"||k.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=k.current;if(_.current=null,k.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 $t,useId as Vg,useLayoutEffect as Kt,useMemo as Ae,useRef as ue,useState as ee}from"react";import{z as te}from"zod";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()}),Vf=te.object({anonymousId:es.optional(),identity:td,profile:nd.optional()}),$f=te.object({expiresAt:te.number().int().positive(),token:te.string().trim().min(1)}),Kf=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,`
1
+ "use client";import{a as Oo,b as Do,d as Ho}from"./chunk-CLHBM3HQ.js";import{a as Ha,c as Sn}from"./chunk-S6OIAJSC.js";import{a as me}from"./chunk-CR3H7AVI.js";import{A as Mr,B as _o,C as bn,D as La,b as We,d as Ca,e as $n,g as Aa,h as Ta,i as Eo,j as Po,m as Ea,n as Pa,o as Kn,p as Ia,q as xa,r as ka,s as ko,t as Na,u as _a,v as Oa,w as Da,x as Tr,y as No,z as Rr}from"./chunk-WVP7S2A4.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-UHHKMESI.js";import{a as Ua,b as Ba,c as Fa,d as Lo}from"./chunk-7KCGPNEN.js";import"./chunk-4JEZZR5J.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 Mt(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"?Mt(e)?e:null:Mt(t)?t:null}var Er=30,qa=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"&&Mt(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 qn(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()?qo(n):t?"Attachment":null}function Ko(e,t){return e?qo(e):t[0]?.name||"Attachment"}function qo(e){let t=e.replace(/\s+/g," ").trim();return t.length>qa?`${t.slice(0,qa-1).trimEnd()}\u2026`:t}function Go(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 Cn}from"@heroui/react";import{jsx as Fe,jsxs as tn}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 Ga({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 tn("section",{"aria-label":l,className:me("aui-approval",t),"data-slot":"agent-ui-approval",...c,children:[tn("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,tn("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?tn(Cn,{defaultExpanded:!0,className:"aui-approval__disclosure",children:[Fe(Cn.Heading,{children:tn(Cn.Trigger,{className:"aui-approval__disclosure-trigger",children:["Review action details",Fe(Cn.Indicator,{})]})}),Fe(Cn.Content,{children:Fe(Cn.Body,{children:m?Fe("dl",{className:"aui-approval__details","data-slot":"agent-ui-approval-details",children:m.map(([S,u])=>tn("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,tn("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 G,jsxs as Gn}from"react/jsx-runtime";function Qa({className:e,provider:t}){let n=t?.toLowerCase();return n==="openai"?G(Cu,{className:e,"data-provider":"openai"}):n==="google"?G(Au,{className:e,"data-provider":"google"}):n==="anthropic"?G(Tu,{className:e,"data-provider":"anthropic"}):n==="moonshot ai"?G(Ru,{className:e,"data-provider":"moonshot-ai"}):null}function Cu(e){return G("svg",{"aria-hidden":"true",fill:"currentColor",focusable:"false",role:"presentation",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",...e,children:G("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:[G("path",{d:"M0 0h32v32H0z",fill:"none"}),G("defs",{children:G("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:[G("use",{href:`#${n}`}),G("g",{filter:`url(#${o})`,children:G("ellipse",{cx:"14.208",cy:"16.716",fill:"#ffe432",rx:"14.208",ry:"16.716",transform:"rotate(19.552 -43.96 -16.268)"})}),G("g",{filter:`url(#${s})`,children:G("ellipse",{cx:"27.054",cy:"2.551",fill:"#fc413d",rx:"18.394",ry:"18.799"})}),G("g",{filter:`url(#${i})`,children:G("ellipse",{cx:"19.224",cy:"24.904",fill:"#00b95c",rx:"19.224",ry:"24.904",transform:"rotate(-2.799 667.58 51.694)"})}),G("g",{filter:`url(#${i})`,children:G("ellipse",{cx:"18.843",cy:"20.744",fill:"#00b95c",rx:"18.843",ry:"20.744",transform:"rotate(-31.317 81.174 36.482)"})}),G("g",{filter:`url(#${d})`,children:G("ellipse",{cx:"66.462",cy:"24.977",fill:"#3186ff",rx:"18.093",ry:"17.423"})}),G("g",{filter:`url(#${l})`,children:G("ellipse",{cx:"20.929",cy:"22.075",fill:"#fbbc04",rx:"20.929",ry:"22.075",transform:"rotate(37.251 9.618 -7.898)"})}),G("g",{filter:`url(#${c})`,children:G("ellipse",{cx:"24.131",cy:"22.292",fill:"#3186ff",rx:"24.131",ry:"22.292",transform:"rotate(34.51 19.317 63.957)"})}),G("g",{filter:`url(#${m})`,children:G("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"})}),G("g",{filter:`url(#${p})`,children:G("ellipse",{cx:"27.585",cy:"17.148",fill:"#fc413d",rx:"27.585",ry:"17.148",transform:"rotate(-42.847 5.973 20.37)"})}),G("g",{filter:`url(#${S})`,children:G("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:[G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"42.756",id:o,width:"38.868",x:"-19.618",y:"12.903",children:G("feGaussianBlur",{stdDeviation:"2.46"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"85.162",id:s,width:"84.353",x:"-15.122",y:"-40.03",children:G("feGaussianBlur",{stdDeviation:"11.891"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"90.22",id:i,width:"78.916",x:"-20.768",y:"11.483",children:G("feGaussianBlur",{stdDeviation:"10.109"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"73.27",id:d,width:"74.611",x:"29.156",y:"-11.658",children:G("feGaussianBlur",{stdDeviation:"9.606"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"78.151",id:l,width:"77.538",x:"-38.291",y:"-16.269",children:G("feGaussianBlur",{stdDeviation:"8.706"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"76.898",id:c,width:"78.218",x:"7.78",y:"-6.098",children:G("feGaussianBlur",{stdDeviation:"7.775"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"51.479",id:m,width:"55.879",x:"13.208",y:"-18.425",children:G("feGaussianBlur",{stdDeviation:"6.957"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"68.674",id:p,width:"70.203",x:"-15.474",y:"-31.027",children:G("feGaussianBlur",{stdDeviation:"5.876"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"51.261",id:S,width:"55.137",x:"-14.173",y:"20.474",children:G("feGaussianBlur",{stdDeviation:"7.273"})}),G("mask",{height:"64",id:r,maskUnits:"userSpaceOnUse",width:"64",x:"0",y:"0",children:G("use",{href:`#${n}`})})]})]})]})}function Tu(e){return G("svg",{"aria-hidden":"true",fill:"none",focusable:"false",role:"presentation",viewBox:"0 0 256 257",xmlns:"http://www.w3.org/2000/svg",...e,children:G("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:[G("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"}),G("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"}),G("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 ft,jsxs as zn}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(C=>C.id===i),x=Eu(C=>{S.current=C,C?.setAttribute("aria-keyshortcuts","Control+Shift+M"),m(Sn(C))},[]),w=C=>{!C&&Date.now()-p.current<350||l(C)};return Pu(()=>{if(u)return;let C=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",C),()=>document.removeEventListener("keydown",C)},[u]),zn(Qn,{"aria-label":e,className:me("aui-model-picker",t),isDisabled:u,isOpen:d,value:i,onOpenChange:w,onChange:C=>{C!=null&&r(C),l(!1)},children:[zn(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:[ft(Qn.Value,{className:"aui-model-picker__value",children:h?.label??i}),ft(Qn.Indicator,{className:"aui-model-picker__indicator"}),zn("span",{"aria-hidden":"true",className:"aui-picker-tooltip",children:[ft("span",{children:"Select model"}),ft("kbd",{className:"aui-picker-tooltip__shortcut",children:"\u2303\u21E7M"})]})]}),ft(Qn.Popover,{className:"aui-model-picker__popover",placement:s,UNSTABLE_portalContainer:c,children:ft(Qo,{"aria-label":`${e} options`,className:"aui-model-picker__list",children:o.map(C=>{let O=Iu(C);return zn(Qo.Item,{className:"aui-model-picker__option","data-description":O,id:C.id,textValue:C.label,children:[ft(Qa,{className:"aui-model-picker__option-icon",provider:C.provider}),zn("span",{className:"aui-model-picker__option-copy",children:[ft(wu,{className:"aui-model-picker__option-label",children:C.label}),O?ft(Mu,{className:"aui-model-picker__option-description",title:O,children:O}):null]}),ft(Qo.ItemIndicator,{className:"aui-model-picker__option-indicator"})]},C.id)})})})]})}import{Hand as xu,LockOpen as ku,ShieldCheck as Ja}from"@gravity-ui/icons";import{Description as Nu,Label as _u,ListBox as zo,Select as Wn}from"@heroui/react";import{useCallback as Ou,useEffect as Du,useRef as ja,useState as Ya}from"react";import{jsx as ot,jsxs as jn}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:ku,id:"full",label:"Full access"}];function kr({"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(Sn(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]),jn(Wn,{"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:[jn(Wn.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:[ot(Ja,{"aria-hidden":"true",className:"aui-permission-picker__trigger-icon"}),ot(Wn.Value,{className:"aui-permission-picker__value",children:p?.label??o}),ot(Wn.Indicator,{className:"aui-permission-picker__indicator"}),jn("span",{"aria-hidden":"true",className:"aui-picker-tooltip",children:[ot("span",{children:"Change permissions"}),ot("kbd",{className:"aui-picker-tooltip__shortcut",children:"\u2303\u21E7P"})]})]}),ot(Wn.Popover,{className:"aui-permission-picker__popover",placement:"top start",UNSTABLE_portalContainer:d,children:ot(zo,{"aria-label":`${e} options`,className:"aui-permission-picker__list",children:Xa.map(h=>{let x=h.icon;return jn(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:[ot(x,{"aria-hidden":"true",className:"aui-permission-picker__option-icon"}),jn("span",{className:"aui-permission-picker__option-copy",children:[ot(_u,{className:"aui-permission-picker__option-label",children:h.label}),ot(Nu,{className:"aui-permission-picker__option-description",title:h.description,children:h.description})]}),ot(zo.ItemIndicator,{className:"aui-permission-picker__option-indicator"})]},h.id)})})})]})}import{useEffect as Wo,useRef as An}from"react";import{jsx as ei}from"react/jsx-runtime";var Lu=40,Za=2;function Nr(e,t,n){return Math.min(n,Math.max(t,e))}function Hu(e){let t=Nr(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:C,...O}){let _=An(null),k=An({onError:m,onStreamEnd:p,onStreamReady:S}),L=An(null),$=An(null),X=An(null),b=An([]);Wo(()=>{k.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,k.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=Nr(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,k.current.onStreamReady?.(F)}catch(Se){K(!1),T||k.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 N=Math.max(1,r),Y=Math.max(0,n),re=N+Y,oe=Math.max(1,Math.floor((K+Y)/re)),Me=Math.ceil(oe/2),qe=_.current;b.current.length!==Me&&(b.current=Array.from({length:Me},()=>0));let it=b.current;if(e&&qe){let de=X.current;(!de||de.length!==qe.frequencyBinCount)&&(de=new Uint8Array(qe.frequencyBinCount),X.current=de),qe.getByteFrequencyData(de);let Oe=Math.max(1,Math.floor(de.length*.025)),bt=Math.max(Oe+1,Math.floor(de.length*.46)),lt=Nr(h,0,4);for(let ge=0;ge<Me;ge+=1){let Pt=Me<=1?0:ge/(Me-1),qt=Math.min(de.length-1,Math.round(Oe+Pt*(bt-Oe))),It=Math.pow((de[qt]??0)/255*lt,.72);it[ge]=Nr((it[ge]??0)*.56+It*.44,0,1)}}else it.fill(0);let dn=Math.max(Za,F*.84),kn=F/2,Et=oe*N+(oe-1)*Y,Je=(K-Et)/2;for(let de=0;de<oe;de+=1){let Oe=Me-1-Math.min(de,oe-1-de),bt=e?it[Oe]??0:0,lt=Math.max(Za,bt*dn),ge=Je+de*re,Pt=kn-lt/2;P.globalAlpha=e?.38+bt*.62:.2,$u(P,ge,Pt,N,lt)}P.globalAlpha=1},Se=()=>{let D=T.getBoundingClientRect(),N=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*N)),M.height=Math.max(1,Math.round(F*N)),M.style.width=`${K}px`,M.style.height=`${F}px`,P.setTransform(N,0,0,N,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={...C,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.",qu="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.",Gu=["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 qu}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 Gu.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),C=$e(e),O=$e(t),_=$e(null),k=$e(null),L=$e(0),$=$e(0),X=$e(n),b=$e(null),f=$e(new Map),v=$e(r);ti(()=>{C.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}),N=X.current;if(!N||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 N(D,{...C.current?{language:C.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=k.current;if(_.current=null,k.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=k.current;if(B){y();try{B.stop()}catch(D){R("idle"),L.current+=1,k.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 N={chunks:[],recorder:D,session:H,stream:B};D.ondataavailable=Y=>{Y.data.size>0&&N.chunks.push(Y.data)},D.onerror=Y=>{L.current!==H||_.current!==N||(L.current+=1,_.current=null,y(),z(N,!0),p(null),R("idle"),c(Yu(Y).message))},D.onstop=()=>{ie(N)},_.current=N,p(B);try{D.start(1e3),M()}catch(Y){L.current+=1,_.current=null,z(N,!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(N){c(N instanceof Error?N.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,C.current&&(B.lang=C.current),B.onstart=()=>{L.current===D&&(R("recognizing"),M())},B.onresult=N=>{if(L.current!==D)return;let Y=Math.max(0,N.resultIndex);for(let oe of f.current.keys())oe>=Y&&f.current.delete(oe);for(let oe=Y;oe<N.results.length;oe+=1){let qe=N.results[oe]?.[0]?.transcript;typeof qe=="string"&&f.current.set(oe,qe)}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=N=>{if(L.current!==D)return;y(),R("idle"),f.current.clear(),L.current+=1;let Y=L.current;N.error!=="aborted"&&(N.error==="not-allowed"?zu().then(re=>{L.current===Y&&c(Jo(N.error,N.message,re))}):c(Jo(N.error,N.message))),k.current===B&&(k.current=null,T(B))},B.onend=()=>{L.current===D&&(y(),R("idle"),k.current===B&&(k.current=null,T(B)))},k.current=B,c(null),d(0),R("recognizing");try{B.start()}catch(N){T(B),k.current=null,y(),R("idle"),c(N instanceof Error?N.message:"Voice dictation could not be started.")}},[T,M,y,R]),Se=Ve(()=>{h.current!=="idle"||k.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=k.current;if(_.current=null,k.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 $t,useId as Vg,useLayoutEffect as Kt,useMemo as Ae,useRef as ue,useState as ee}from"react";import{z as te}from"zod";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()}),Vf=te.object({anonymousId:es.optional(),identity:td,profile:nd.optional()}),$f=te.object({expiresAt:te.number().int().positive(),token:te.string().trim().min(1)}),Kf=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
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 k=ad(c.text,s);if(!k)continue;r.push({active:n.isStreaming===!0&&c.state!=="done",detail:k.detail,detailVisibility:"always",id:`${e.id}-reasoning-${l}`,kind:"thinking",label:k.label,messagePartIndex:l,stateKnown:c.state!==void 0,...r.length===0&&i?{title:i}:{}}),s+=1;continue}if(c.type==="data-activity"){let k=c.data.label.trim(),L=c.data.title?.trim();if(L&&!i){i=L;let $=r[0];$&&!$.title&&(r[0]={...$,title:L})}if(ld(k,c.data.stage)||L&&ts(k)===ts(L))continue;if(k&&o.has(k)){let $=r.findIndex(b=>b.label===k),X=r[$];L&&X&&!X.title&&(r[$]={...X,title:L})}else k&&(o.add(k),r.push({active:!1,detail:c.data.detail,id:c.id??`${e.id}-activity-${l}`,kind:c.data.kind??Br(k),label:k,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(k=>{let L=ai(k);return L!==null&&ii(L)&&k.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),C=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(k=>k.label===C);if(_>=0){let k=r[_];k&&(r[_]={...k,active:O,messagePartIndex:l,stateKnown:!0,...!k.title&&i?{title:i}:{}});continue}o.add(C),r.push({active:O,id:p.toolCallId||`${e.id}-tool-${l}`,kind:S?"chart":m==="executeSandbox"?"code":m==="getComponentSchema"?"thinking":Br(C),label:C,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 Yn(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 nn({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(nn,{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(nn,{children:o.previous.text})},o.previous.id):null]})}import{Code as bd,Heading as Tn,Link as Sd,Paragraph as Cd,Separator as Ad,Table as _t}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 kd}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(_t,{"data-slot":"markdown-table",variant:"secondary",children:fe(_t.ScrollContainer,{children:kd(_t.Content,{"aria-label":"Markdown table",children:[fe(_t.Header,{children:o.map((i,d)=>fe(_t.Column,{id:`column-${d}`,isRowHeader:d===0,children:i.props.children},String(i.key)))}),fe(_t.Body,{children:s.map((i,d)=>fe(_t.Row,{id:`row-${d}`,children:rs(i).map(l=>fe(_t.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(Tn,{className:s,level:1,children:o}),h2:({children:o,className:s})=>fe(Tn,{className:s,level:2,children:o}),h3:({children:o,className:s})=>fe(Tn,{className:s,level:3,children:o}),h4:({children:o,className:s})=>fe(Tn,{className:s,level:4,children:o}),h5:({children:o,className:s})=>fe(Tn,{className:s,level:5,children:o}),h6:({children:o,className:s})=>fe(Tn,{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 Nd}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 rn(e,t=1){Nd(()=>{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 ht}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 qd={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 Gd(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 ht("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 rn(m),vi(m,e,t&&r,c),ht(je,{className:"ha-activity-step-disclosure",isExpanded:c,onExpandedChange:p=>l({isDetailActive:t,isExpanded:p}),children:[ne(je.Heading,{children:ht(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 qr({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})),C=Gd(w),O=m===null&&!t&&!r&&(c==="fading"||c==="collapsing"),k=m??(t||c==="expanded"||c==="fading"),L=m!==null||t?k?"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?C.title:$===null?"Activity":X,f=C.kind,v=qd[f],R=w.map(y=>`${y.id}:${y.active?1:0}:${y.detail??""}:${y.sources?.map(M=>M.label).join(",")}`).join("|");return rn(S),vi(S,R,r,k),ht(je,{className:"ha-activity","data-complete":r?void 0:"true","data-phase":L,isExpanded:k,onExpandedChange:p,children:[ne(je.Heading,{children:ht(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:ht("ol",{"aria-label":"Thinking steps",children:[w.map((y,M)=>ht("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}),ht("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=>ht("span",{className:"ha-activity-source",children:[ne(hi,{"aria-hidden":"true"}),T.label]},T.label))}):null]})]},y.id)),r?null:ht("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 Ot}from"zod";var Wd=["callMcpTool","composeUI","executeSandbox","getComponentSchema","renderComponent","searchKnowledge","searchMcpTools","searchWeb"],jd="mcp_",Yd=20,Xd=16*1024,Jd=Ot.object({description:Ot.string().trim().min(1).max(1e3),inputSchema:Ot.record(Ot.string(),Ot.unknown()),name:Ot.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:Ot.boolean().optional()}),Ci=Ot.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 Dt(e){return Ci.parse(e.map(t=>({description:t.description,inputSchema:np(t),name:t.name,...t.needsApproval?{needsApproval:!0}:{}})))}var Rn=class extends Error{constructor(){super("The assistant configuration changed and must be bootstrapped again"),this.name="AgentRuntimeRevisionStaleError"}},Xn=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}},Gr=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 Gr&&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:Dt(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 Jn(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 ki(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 Jn(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 Gr(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 Ni(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 Jn(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 Rn:new Xn(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 Ne(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 Mn(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=Mn(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(C){x="failed",h=Cp(C)}let w;for(;;)try{w=bp.parse(await s.complete({...m,claimId:S.claimId,output:h,status:x}));break}catch(C){if(o()-p+250>r)throw C;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,generateConversationTitle:n,imageSearch:r,modelId:o,newsSearch:s,pageContext:i,permissionMode:d,turnId:l,webSearch:c}){if(!Rp.test(l))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),...n===void 0?{}:{generateConversationTitle:n},imageSearch:r,...o?{modelId:o}:{},newsSearch:s,pageContext:i,permissionMode:d,protocolVersion:6,requestId:l,sdkVersion:We,turnId:l,webSearch:c}}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 qi(e,t){let n=e;return{next:async()=>{if(n){let r=n;return n=null,r}return t()},refresh:t}}function Gi(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 kp,FileZipper as Np,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:Np,kind:"archive",label:"Archive"}:Up.has(t)?{Icon:Ep,kind:"code",label:"Code file"}:Fp.has(t)||n.startsWith("text/")?{Icon:kp,kind:"text",label:"Text document"}:{Icon:wp,kind:"file",label:"File"}}import{jsx as wn,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:[wn("span",{"aria-hidden":"true",className:"ha-attachment-icon",children:wn(n,{})}),zi("span",{className:"ha-attachment-copy",children:[wn("span",{className:"ha-attachment-name",title:e.name,children:e.name}),wn("span",{className:"ha-attachment-type",children:o})]}),wn("button",{"aria-label":`Remove ${e.name}`,type:"button",onClick:t,children:wn($p,{"aria-hidden":"true"})})]})}import{Globe as Kp,Xmark as qp}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(qp,{"aria-hidden":"true",className:"ha-chip-remove"})]})})}import{useCallback as Wr,useState as Gp}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]=Gp(!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&&Mt(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(nn,{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 Zn="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??Zn}: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 Lt,useEffect as jp,useLayoutEffect as Yp,useRef as Ke,useState as Xp}from"react";var Ht=4,on=1,dl="--ha-active-turn-spacer-height",pl='[data-role="user"][data-stream-anchor="true"]',Jp={hasOverflow:!1,isAtBottom:!0};function er(e){let t=e.scrollHeight-e.clientHeight>Ht,n=!t||e.scrollHeight-Math.max(0,e.scrollTop)-e.clientHeight<=Ht;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=Lt(b=>{x(f=>em(f,b)?f:b)},[]),C=Lt(b=>{t.current=0,b.style.removeProperty(dl)},[]),O=Lt(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},[]),_=Lt((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,C(f),n.current=!0,r.current=!1,l.current=f.scrollTop,w({hasOverflow:er(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)>on,typeof f.scrollTo=="function"?f.scrollTo({behavior:ml(b),top:v}):f.scrollTop=v,l.current=Math.max(0,f.scrollTop)},[C,e,w]),k=Lt(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=Lt((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)>on;i.current=M==="smooth"&&T,s.current=T,!T&&t.current>Ht&&(p.current=!0),l.current=b.scrollTop,w({hasOverflow:R>Ht,isAtBottom:R-y<=Ht}),typeof b.scrollTo=="function"?b.scrollTo({behavior:M,top:f}):(b.scrollTop=f,i.current=!1),l.current=Math.max(0,b.scrollTop)},[w]),$=Lt(()=>{let b=e.current;if(!b)return;O(b);let f=er(b),v=Math.max(0,b.scrollTop),R=v<l.current-on;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=k(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)>on){w({hasOverflow:f.hasOverflow,isAtBottom:!0});return}s.current=!1,i.current=!1,p.current=t.current>Ht}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)},[k,e,_,L,w,O]),X=Lt(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>Ht,S.current=!1,r.current=!0;let R=er(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(er(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=er(b),K=Math.max(0,b.scrollTop),ye=K<l.current-on,Se=K>l.current+on;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=k(b),B=Math.max(0,b.scrollHeight-b.clientHeight),D=Math.min(H??B,B),N=F.isAtBottom||Math.abs(K-D)<=on,Y=i.current;N&&(s.current=!1,i.current=!1,H!==null&&(p.current=t.current>Ht,r.current=!0,n.current=!1)),w(Y&&!N?{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()}},[k,$,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 rn(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-XOCP6UFF.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 tr}from"react";import{Fragment as Sm,jsx as Re,jsxs as nr}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]=tr(!1),[d,l]=tr(!1),[c,m]=tr(""),[p,S]=tr([]),[u,h]=tr(),x=bl(null),w=bl(0),C=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,k=e.includes("retry")&&o;if(!O&&!_&&!k)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 nr("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,_?nr(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"})}),nr(Zr,{isOpen:d,onOpenChange:$,children:[Re(Jr,{ref:C,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:nr(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."}),nr("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,k?Re("button",{"aria-label":"Retry response",className:"ha-message-action",type:"button",onClick:o,children:Re(cm,{"aria-hidden":"true"})}):null]})}import{jsx as En,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"?En("a",{"aria-label":`Open ${t}`,className:"ha-message-image",download:e.filename,href:e.url,rel:"noopener noreferrer",target:"_blank",title:t,children:En("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:[En("span",{"aria-hidden":"true",className:"ha-message-file-icon",children:En(r,{})}),Cl("span",{className:"ha-message-file-copy",children:[En("span",{className:"ha-message-file-name",title:t,children:t}),En("span",{className:"ha-message-file-type",children:s})]})]})}function sn(){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 rr(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 or(e,t){return e.isPaused===t?e:{...e,isPaused:t}}function yt(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 vt(e){return e.deliveryStatus??"pending"}function Pn(e,t,n){let r=e.messages.findIndex(s=>s.id===t);if(r===-1||vt(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,Ut="conversation-outboxes",Tm=":message-outbox:",an=new Map;function Ts(e,t){return`${e}${Tm}${t}:v1`}async function Rl(e){await an.get(e)?.catch(()=>{});let t=await Ms();if(!t)return sn();try{let n=t.transaction(Ut,"readonly"),r=await xm(n.objectStore(Ut).get(e));return await ws(n),Rm(r,e)}catch{return sn()}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(Ut,"readwrite"),i=s.objectStore(Ut);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(Ut,"readwrite");n.objectStore(Ut).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=>vt(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 sn();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 sn();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.generateConversationTitle===void 0||typeof t.generateConversationTitle=="boolean")&&(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=(an.get(e)??Promise.resolve()).catch(()=>{}).then(t);return an.set(e,r),r.then(()=>{an.get(e)===r&&an.delete(e)},()=>{an.get(e)===r&&an.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(Ut)||r.createObjectStore(Ut,{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 kl(e){let t=e.text.trim();return t||`${e.files.length} attachment${e.files.length===1?"":"s"}`}function Nl({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&&vt(o)!=="admitted")??null}function Ol(e,t){return e.messages.filter(n=>vt(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=>vt(o)==="sending")?null:r.messages.find(o=>vt(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 km,CircleExclamation as Nm,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)},C=(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),C(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))},k=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:k}}import{jsx as Ie,jsxs as sr}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:C,handleReorderKeyDown:O,moveMessageToPosition:_,positionPickerMessageId:k,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 sr("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 sr("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=>C(T,!1),onPointerDown:T=>L(T,f.id),onPointerMove:X,onPointerUp:T=>C(T,!0),children:Ie(Om,{"aria-hidden":"true"})}),k===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)=>sr("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(Nm,{"aria-hidden":"true"}):Ie(_m,{"aria-hidden":"true"})}),sr("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]}),sr("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(km,{"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 Gm}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 qm,composeRenderProps as Kl}from"react-aria-components";import{jsx as In}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 _=k=>{k.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]),C=Xe(()=>{clearTimeout(u.current)},[]),O=$l(()=>({handleCancelClose:C,handleClose:w,handleOpen:x,isOpen:i,isPointerInsideRef:p,portalContainer:l,setPortalContainer:c,triggerRef:m}),[C,w,x,i,l]);return In(Ps,{value:O,children:e})},ql=({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(Sn(_))},[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]),C=Xe(_=>{c(!0),r?.(_)},[c,r]),O=Xe(_=>{m.current||l(),n?.(_)},[l,m,n]);return In("span",{ref:h,className:me("aui-hover-card__trigger",t),"data-slot":"hover-card-trigger",onBlur:O,onFocus:C,onPointerEnter:x,onPointerLeave:w,...d,children:e})},Gl=({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]),C=Xe(O=>{O||m(!0),o?.(O)},[m,o]);return In(qm,{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:C,onPointerEnter:x,onPointerLeave:w,...l,children:O=>typeof t=="function"?t(O):t})},Ql=({children:e,className:t,...n})=>In(Km,{"data-slot":"hover-card-arrow",className:Kl(t,r=>me("aui-hover-card__arrow",r)??""),...n,children:e??In("svg",{fill:"none",height:"12",viewBox:"0 0 12 12",width:"12",xmlns:"http://www.w3.org/2000/svg",children:In("path",{d:"M0 0C5.48483 8 6.5 8 12 0Z"})})});var ar=Object.assign(Is,{Arrow:Ql,Content:Gl,Root:Is,Trigger:ql});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 Bt}from"react/jsx-runtime";var jl=Qm({sourceType:"url"}),ir=()=>zm(jl);function Ym(e){return e.trim().charAt(0).toUpperCase()||"?"}var ks=({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??Bt(xs,{children:[ae(Ns,{}),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(ar,{closeDelay:0,openDelay:150,children:x}):x})},Ns=({children:e,className:t,label:n,...r})=>{let{domain:o,enablePreview:s,href:i,locator:d,sourceType:l,title:c}=ir(),m=l==="url"&&i,p=e??n??(m?Bt(xs,{children:[ae(ao,{}),ae(so,{children:c??o}),d?ae(oo,{children:d}):null]}):Bt(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(ar.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(ar.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}=ir();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}=ir(),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 Bt("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(Gm,{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}=ir();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}=ir();if(!d)return null;let S=r??p,u=n??s,h=m==="url"&&l?Bt("a",{className:"aui-chat-source__preview-link",href:l,rel:"noopener noreferrer",target:"_blank",children:[Bt("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]}):Bt("div",{className:"aui-chat-source__preview-link","data-source-type":"document",children:[Bt("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(ar.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 xn}from"@heroui/react";import{composeRenderProps as Os}from"react-aria-components";import{jsx as Ft,jsxs as Xm}from"react/jsx-runtime";var Ds=({children:e,className:t,...n})=>Ft(xn,{"data-slot":"chat-sources",className:Os(t,r=>me("aui-chat-sources",r)??""),...n,children:e}),Yl=({children:e,className:t,...n})=>Ft(xn.Heading,{children:Xm(xn.Trigger,{"data-slot":"chat-sources-trigger",className:Os(t,r=>me("aui-chat-sources__trigger",r)??""),...n,children:[Ft("span",{className:"aui-chat-sources__trigger-label",children:e}),Ft(xn.Indicator,{className:"aui-chat-sources__indicator"})]})}),Xl=({children:e,className:t,...n})=>Ft(xn.Content,{"data-slot":"chat-sources-content",className:Os(t,r=>me("aui-chat-sources__content",r)??""),...n,children:Ft(xn.Body,{children:Ft("div",{className:"aui-chat-sources__content-body",children:e})})}),Jl=({children:e,className:t,role:n="list",...r})=>Ft("div",{className:me("aui-chat-sources__list",t),"data-slot":"chat-sources-list",role:n,...r,children:e});var Zl=Object.assign(ks,{DocumentIcon:io,Icon:ao,Locator:oo,Preview:_s,Root:ks,Title:so,Trigger:Ns}),lr=Object.assign(Ds,{Content:Xl,List:Jl,Root:Ds,Trigger:Yl});import{jsx as wt,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 wt(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 wt(lr.List,{"aria-label":"Sources",children:e.map(t=>wt(tc,{inList:!0,source:t},t.sourceId))})}function nc({sources:e}){return e.length===0?null:e.length===1?wt("div",{"aria-label":"Sources",className:"ha-message-sources","data-count":"1",role:"group",children:wt(tc,{source:e[0]})}):ec(lr,{className:"ha-message-sources","data-count":e.length,children:[ec(lr.Trigger,{"aria-label":`${e.length} sources`,children:[wt("span",{className:"ha-sources-label",children:"Sources"}),wt("span",{"aria-hidden":"true",className:"ha-sources-count",children:e.length})]}),wt(lr.Content,{children:wt(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 ln,Dropdown as cr,Input as cg,Label as dc,Modal as st,Popover as Ls,TextField as ug}from"@heroui/react";import{useCallback as dg,useRef as Hs,useState as Vt}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]=Vt(!1),[S,u]=Vt(!1),[h,x]=Vt(null),[w,C]=Vt(null),[O,_]=Vt(""),[k,L]=Vt(null),[$,X]=Vt(!1),[b,f]=Vt(),v=Hs(0),R=Hs(0),y=Hs(null);rn(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,N)=>{!N&&Date.now()-R.current<350||x(N?D:null)},F=(D,N)=>{z(),C({item:D,type:N}),_(D.title),L(null),u(!0)},K=()=>{$||(L(null),u(!1))},ye=(D,N)=>{N===pc&&F(D,"rename"),N===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),C({...w,item:{...w.item,title:D}}),u(!1)}catch(N){L(N instanceof Error?N.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(N=>{let Y=N.id===e,re=t.has(N.id),oe=!re&&n.has(N.id);return Ce("div",{className:"ha-session-row","data-actions-open":h===N.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?`${N.title}, new response available`:void 0,onClick:()=>{z(),Y||l(N.id)},children:[re?Z(nn,{className:"ha-session-title ha-session-shimmer",children:N.title}):Z("span",{className:"ha-session-title",children:N.title}),oe?Z("span",{"aria-hidden":"true",className:"ha-session-completed-dot"}):null]}),Ce(cr,{isOpen:h===N.id,onOpenChange:Me=>j(N.id,Me),children:[Z(ln,{isIconOnly:!0,"aria-label":`Chat actions for ${N.title}`,className:"ha-session-actions-trigger",size:"sm",variant:"ghost",onPointerDown:()=>{R.current=Date.now()},children:Z(sg,{"aria-hidden":"true"})}),Z(cr.Popover,{className:"ha-session-actions-menu",placement:"bottom end",UNSTABLE_portalContainer:b,children:Ce(cr.Menu,{"aria-label":`Actions for ${N.title}`,onAction:Me=>ye(N,Me),children:[Ce(cr.Item,{id:pc,textValue:"Rename",children:[Z(ag,{"aria-hidden":"true"}),Z(dc,{children:"Rename"})]}),Ce(cr.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"})]})]})})]})]},N.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(ln,{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(ln,{"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(st.Backdrop,{className:"ha-session-modal-backdrop",isDismissable:!$,isKeyboardDismissDisabled:$,isOpen:S,UNSTABLE_portalContainer:b,onOpenChange:D=>{D||K()},children:Z(st.Container,{placement:"center",size:"sm",children:Z(st.Dialog,{className:"ha-session-modal",children:Z(mg,{dialog:w,isPending:$,mutationError:k,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(st.Header,{children:Z(st.Heading,{children:"Rename chat"})}),Ce(st.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(st.Footer,{children:[Z(ln,{fullWidth:!0,isDisabled:t,type:"button",variant:"outline",onPress:r,children:"Cancel"}),Z(ln,{fullWidth:!0,isPending:t,type:"submit",children:t?"Saving\u2026":"Submit"})]})]}):e?.type!=="delete"?null:Ce(hc,{children:[Z(st.Header,{children:Z(st.Heading,{children:"Delete chat?"})}),Ce(st.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(st.Footer,{children:[Z(ln,{fullWidth:!0,isDisabled:t,variant:"outline",onPress:r,children:"Cancel"}),Z(ln,{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(qr,{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 cn({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 ur,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 ur(()=>{c.current=n},[n]),ur(()=>{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]),ur(()=>{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]),ur(()=>{if(d===t)return()=>Uo(t,c.current)},[t,d]),ur(()=>{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 kc({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 un,jsx as I,jsxs as Pe}from"react/jsx-runtime";var Dc=sn();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[C,O]=ee(null),[_,k]=ee({}),L=ue(_),$=ue(C),[X,b]=ee(null),[f,v]=ee([]),[R,y]=ee(hs),M=ue(R),[T,P]=ee({}),[z,ie]=ee(0),j=C?_[C]??null:null;Kt(()=>{L.current=_,$.current=C},[C,_]);let F=W(E=>{k(U=>({...U,[E.conversationId]:E})),O(E.conversationId)},[]),K=W(E=>{k(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||!C||ye(E=>ys(E,C))},[C,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}})},[]),N=ue(null),Y=ue(null),re=p.apiBaseUrl,oe=p.agentId,Me=$t(d),qe=W((E,U)=>{let V=ol({conversationEpoch:t,optimisticTarget:Y.current,readyConversationId:E,readyEpoch:U,requestedConversationId:S});V&&(k(J=>{let se=J[V];return!se||se.composerReady?J:{...J,[V]:{...se,composerReady:!0}}}),O(V),d(U))},[t,d,S]),at=Ae(()=>{try{return Dt(bn(p.tools,p.permissionDefaultMode)),p.permissionShowPicker&&Dt(bn(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]),it=at?null:Ii(p),dn=$t(E=>ki(p,w,E)),kn=$t(E=>{Ne(p,w,E,"embed_loaded")}),Et=ue(n);Kt(()=>{if(Et.current===n)return;Et.current=n,N.current=null,Y.current=null,L.current={},$.current=null,k({}),O(null),v([]);let E=hs();M.current=E,y(E),P({}),r?w.reset():w.clear()},[n,r,w]),Kt(()=>{if(S!==null||at)return;let E=rl(Y.current,t);Y.current=E;let U=N.current;if(!U)return;let V=E.conversationId;localStorage.setItem(U.storageKey,V),b(null),v(J=>{let se=qn(J,V,Ir([]),Date.now());return Nt(U.historyKey,se),se}),k(J=>({...J,[V]:{composerReady:!1,config:U.config,conversationId:V,historyKey:U.historyKey,readyEpoch:t,runtime:null,showStartScreenWhileConnecting:!0,storageKey:U.storageKey}})),O(V)},[at,t,S]),be(()=>{let E=!1;if(at){b(at),O(null),Me(t);return}let U=N.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),k(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"&&Mt(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 Ge=Vo(ve);E||v(Ge);let we=U?.config??lc(oe),Gt=we?null:Jn(w,`${re}/v1/agents/${encodeURIComponent(oe)}/config`),ut=Jn(w,`${re}/v1/agents/${encodeURIComponent(oe)}/conversations`).catch(()=>null),Nn=await dn(_e),pn=we??(Gt?await $g(Gt):null);if(!pn||!Nn)throw new Error("The data assistant could not be loaded");we||cc(oe,pn);let De=Ge.find(dt=>dt.id===_e),_n=qn(Ge,_e,De?.title??Ir([]),De?.updatedAt??Date.now());if(_n!==Ge&&Nt(ve,_n),!E){N.current={config:pn,historyKey:ve,storageKey:se},v(_n);let dt=L.current[_e],le={composerReady:!1,config:pn,conversationId:_e,historyKey:ve,readyEpoch:t,runtime:Nn.runtime,showStartScreenWhileConnecting:dt?.showStartScreenWhileConnecting??S===null,storageKey:se};F(le)}ut.then(async dt=>{if(!dt?.ok)return;let le=Pr((await dt.json()).conversations);E||v(Qt=>{let On=$o(Qt,le);return Nt(ve,On),On})}),kn(_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,it,at,t,n,oe,S,z,B,w]);let Je=W((E,U,V)=>{let J=N.current?.historyKey;J&&v(se=>{let ve=qn(se,E,U,Date.now(),V);return Nt(J,ve),ve})},[]),de=W(E=>{k(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[Ge,we]of Object.entries(Qr(se)))ve.set(Ge,we);let _e=await fetch(`${re}/v1/conversations/${encodeURIComponent(E)}`,{...U,headers:ve});if(_e.status===401){w.clear();let Ge=await w.get(),we=new Headers(U.headers);for(let[Gt,ut]of Object.entries(Qr(Ge)))we.set(Gt,ut);_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]),bt=W(async(E,U)=>{await Oe(E,{body:JSON.stringify({title:U}),headers:{"Content-Type":"application/json"},method:"PATCH"});let V=N.current?.historyKey;V&&v(J=>{let se=J.map(ve=>ve.id===E?{...ve,title:U}:ve);return Nt(V,se),se})},[Oe]),lt=W(async E=>{await Oe(E,{method:"DELETE"});let U=N.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(No(U.storageKey,E)),wr(Bo(U.storageKey,E)),Ml(Ts(U.storageKey,E)),k(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}),C===E&&B())},[C,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,_]),Pt=C?ge[C]?.config??null:null,qt=ue(null);be(()=>{!m||!j?.runtime||qt.current===j.conversationId||(qt.current=j.conversationId,Ne(p,w,j.conversationId,"opened"))},[m,p,j,w]);let It=at??X,dr=Ae(()=>Go(f),[f]),uo=f.find(E=>E.id===C)?.title??"New chat",St=N.current?"Loading chat\u2026":"Loading assistant\u2026",ct=S===null&&(!j||j.showStartScreenWhileConnecting);return I(un,{children:Pe(Aa,{keepMounted:!0,agentId:p.agentId,defaultExpanded:p.panelExpanded,expandable:!x&&p.panelExpandable,expandedTitle:uo,modal:p.viewMode!=="sidebar",name:Pt?.name??"Data assistant",open:m,actionsSlot:x?I(un,{}):I(ac,{isDisabled:ct,onPress:B}),expandedSidebarSlot:x?void 0:I(Us,{activeConversationId:C,busyConversationIds:R.busyIds,completedConversationIds:R.completedIds,groups:dr,isNewConversationDisabled:ct,variant:"sidebar",onDeleteConversation:lt,onNewConversation:B,onRenameConversation:bt,onSelectConversation:H}),historySlot:x?I(un,{}):I(Us,{activeConversationId:C,busyConversationIds:R.busyIds,completedConversationIds:R.completedIds,groups:dr,onDeleteConversation:lt,onRenameConversation:bt,onSelectConversation:H}),onClose:o,onNewConversation:x?void 0:B,children:[It?I("div",{className:"ha-loading",role:"alert",children:It}):x?I(Ca,{indicator:I(Hg,{"aria-hidden":!0,color:"current",size:"md"})}):!j||!j.runtime||!Pt?ct&&j?I(Lc,{composerControlsRevealed:e,loadingLabel:St,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:St,placeholder:p.composerPlaceholder,showStartScreen:ct,suggestedPrompts:p.suggestedPrompts??[],composerStartSlot:I(Fc,{agentId:p.agentId,options:p}),onComposerControlsReveal:s},`pending-${t}`):null,I("div",{className:"ha-runtime-content",hidden:!!It||x,children:I(cl,{activeConversationId:It?null:C,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(Gg,{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:qe,onRuntimeRevisionStale:K,onConversationStarted:V=>{de(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(qg,{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=ue(null),[r,o]=ee(()=>ko(e)),[s,i]=ee(null),d=l=>{let c=Mn(l,t.composerAttachmentContentTypes);o(c.files),i(c.error),ka(e,c.files)};return t.composerAttachmentContentTypes.length===0?null:Pe(un,{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 qg({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(un,{children:[t.permissionShowPicker&&t.tools.length>0?I(kr,{"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($n,{children:"Dictate message"})]}):null]})}function Gg({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:C}){let{selectedModelId:O,setSelectedModelId:_}=Fs(w,u.composerDefaultModel),k=No(w,o),L=Tr(w,o),$=u.composerAttachmentAccept,X=Ae(()=>({key:$}),[$]),[b,f]=ee(()=>({files:Mn(ko(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 A=g.policy===X?g.files:[],q=typeof a=="function"?a(A):a;return{files:Mn(q,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(k):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,N]=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}}),[qe,at]=ee(!1),[it,dn]=ee(!0),[kn,Et]=ee(!1),[Je,de]=ee(!1),[Oe,bt]=ee(()=>new Set),[lt,ge]=ee(null),[Pt,qt]=ee(0),[It,dr]=ee(0),[uo,St]=ee(!1),[ct,E]=ee(!1),[U,V]=ee(null),[J,se]=ee({}),ve=W(a=>{u.permissionShowPicker?Mr(k,a.permissionMode):_o(k),ie(a)},[k,u.permissionShowPicker]),_e=oe.configuredDefaultMode===u.permissionDefaultMode?oe.selectedMode:u.permissionDefaultMode,Ge=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,ut=Ae(()=>bn(u.tools,Gt),[Gt,u.tools]),Nn=Ae(()=>Dt(ut),[ut]),pn=Ae(()=>Fi(Nn),[Nn]),De=Ae(()=>new Map(ut.map(a=>[a.name,a])),[ut]),_n=Ae(()=>new Set(ut.map(a=>a.name)),[ut]),dt=ue(new Set),le=ue(null),Qt=ue(new Set),On=ue(!1),Le=ue(s),po=ue(null),Ze=ue(!1),He=ue(!1),zt=ue(null),pr=ue(0),pt=ue(0),xt=ue(null),Wt=ue(null),mr=ue(null),mo=ue(new Set),go=ue(new Map),Dn=ue(()=>{}),$s=ue(null),Ks=ue(null),Ct=ue(null),Ee=Ae(()=>vc({report:({latencyMs:a,messageId:g,metric:A})=>{Ne(u,C,o,A,{latencyMs:a,latencyOrigin:"user_submit",messageId:g})}}),[o,u,C]),Vc=Ae(()=>Bo(w,o),[o,w]),Ln=Ae(()=>Ts(w,o),[o,w]),qs=Ec({attachments:y,draftKey:Vc,input:D,setAttachments:T,setInput:N}),$c=W((a,{language:g,signal:A})=>kc({apiBaseUrl:u.apiBaseUrl,audio:a,conversationId:o,...g?{language:g}:{},signal:A,tokenManager:C}),[o,u.apiBaseUrl,C]),{cancel:Qe,elapsedSeconds:fo,error:ho,isActive:ke,isRecording:Kc,isSupported:jt,isTranscribing:Hn,start:Gs,stop:Qs,stream:qc}=Zo({onValueChange:N,transcribe:$c,value:D}),yo=t||ke||y.length>0||M!==null||ho!==null,zs=W(()=>{u.composerControlsAvailable&&i()},[i,u.composerControlsAvailable]),Gc=a=>{Kn(u.agentId,!0,a.currentTarget),zs()},Qc=a=>{let g=a.currentTarget.querySelector(".ha-composer");g&&xa(g,a.relatedTarget)||Kn(u.agentId,!1)};be(()=>{Le.current=s},[s]),be(()=>{u.composerDictation||Qe()},[Qe,u.composerDictation]),be(()=>{e||Qe()},[e,Qe]);let mn=u.composerModelPicker?O:u.composerDefaultModel,gn=W(a=>{Le.current=a,m(o,()=>a)},[o,m]),et=W(async(a,{applyAfterPersist:g=!1}={})=>{let A=Le.current,q=a(A);if(q!==A){g?Le.current=q:gn(q);try{await Rs(Ln,q)}catch(ce){throw Le.current===q&&(g?Le.current=A:gn(A)),ce}g&&Le.current===q&&gn(q)}},[gn,Ln]),ze=W(a=>{et(a).catch(()=>{})},[et]),zc=W(a=>{Qt.current.add(a),et(g=>rr(Pn(g,a,"admitted"),a)).catch(()=>{})},[et]);be(()=>{let a=!1;return dn(!0),Rl(Ln).then(async g=>{if(a)return;let A=wl(g,Le.current),q=Qt.current,ce={...A,messages:A.messages.filter(he=>!q.has(he.id))};gn(ce),await Rs(Ln,ce)}).catch(()=>{}).finally(()=>{a||dn(!1)}),()=>{a=!0}},[gn,Ln]);let gr=W(()=>{Ze.current=!1,He.current=!1,xt.current=null,E(!1)},[]),Ws=W(a=>{cn({attempt:a,currentAttempt:pt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current})&&de(!1)},[]),{agent:Yt,connectionEpoch:fr,connectionError:mt,isHydrating:Wc,isReconnecting:js,retryConnection:jc}=Wg({conversationId:o,onRuntimeRevisionStale:S,onTurnAdmitted:zc,options:u,runtime:h,tokenManager:C}),Yc=$t(p);Kt(()=>{Yc(o,r)},[e,r,o]),be(()=>{if(it||fr===0)return;let a=[];for(let q of Le.current.messages)vt(q)==="sending"&&a.push(q.id);if(a.length===0){Et(!1);return}let g=!1,A;return Et(!0),(async()=>{let q=[];for(let pe=0;pe<a.length;pe+=50)q.push(a.slice(pe,pe+50));let ce=async pe=>{let rt=await Promise.all(q.map(async gt=>({response:await Yt.call(Fa,[{protocolVersion:6,turnIds:gt}],{timeout:15e3}),turnIds:new Set(gt)}))),Be=new Set;for(let{response:gt,turnIds:wo}of rt){if(gt.protocolVersion!==6||!Array.isArray(gt.turns))throw new Error("Invalid turn admission status response");for(let vn of gt.turns)vn.status==="admitted"&&wo.has(vn.turnId)&&Be.add(vn.turnId)}return Be.size===a.length||pe>=4?Be:(await new Promise(gt=>window.setTimeout(gt,500)),ce(pe+1))},he;try{he=await ce(0)}catch{g||(A=window.setTimeout(()=>dr(pe=>pe+1),1e3));return}if(!g){for(let pe of he)Qt.current.add(pe);await et(pe=>El(pe,he))}})().catch(()=>{}).finally(()=>{g||Et(!1)}),()=>{g=!0,A!==void 0&&window.clearTimeout(A)}},[Yt,et,fr,it,It]);let Xc=Ae(()=>new Proxy(Yt,{get(a,g){if(g==="send")return q=>a.send(Vi(q));let A=Reflect.get(a,g,a);return typeof A=="function"?A.bind(a):A}}),[Yt]),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;Ne(u,C,o,"component_rendered",{componentType:g?.kind})}a.type==="data-runtime-timing"&&uc(u.agentId,o,a.data)},onError:a=>{if(Ze.current||He.current){xt.current=null,de(!1),ge(null),queueMicrotask(()=>Dn.current());return}xt.current=a,de(!1),ge(null),Ne(u,C,o,"failure",{messageId:Ee.getActiveMessageId()??void 0,source:"cloudflare-chat"})},onFinish:({isError:a})=>{if(Ze.current||He.current){xt.current=null,de(!1),ge(null),queueMicrotask(()=>Dn.current());return}a&&!xt.current&&(xt.current=new Error("The request could not be completed")),de(!1),ge(null)},resume:!0,syncMessagesToServer:!1,tools:pn}),{clearError:Ys,setMessages:Xs}=Q;Kt(()=>{Dn.current=Ys},[Ys]);let At=Q.status==="submitted"||Q.status==="streaming"||Q.isStreaming,kt=uo||ct,Un=!kt&&Q.isToolContinuation,vo=!!(kt||Q.error||Q.connectionError||mt),Xt=Ae(()=>!vo&&(Oe.size>0||bc({isPendingPart:a=>{let g=a,A=Vs(g);return Dl({isClientTool:!!(A&&De.has(A)),state:g.state})},messages:Q.messages,terminal:vo})),[Q.messages,De,vo,Oe]),Ue=Cc({hasPendingClientToolCalls:Xt,isAutoContinuationPending:Un,isRecovering:Q.isRecovering,isRunning:At,localPending:Je,stalled:ct});be(()=>{if(Ue)return;let a=Ee.getActiveMessageId();a&&(Ee.complete(a),mo.current.delete(a),go.current.delete(a))},[Ue,Ee]);let Jt=!mt&&(Wc||js||it||kn),bo=Jt||Ue,So=kt||!!Q.error||!!Q.connectionError||!!mt,Tt=bo||So,Js=Il({hasChatError:!!(Q.error||Q.connectionError||mt),hasPendingClientToolCalls:Xt,hasReadyClientToolContinuation:Un,isLocalPending:Je,isResuming:Jt,isRunning:At,recoveryError:kt}),Zs=$t(l);be(()=>{z&&!At&&!Xt&&!Je&&!Jt&&!Un&&(_o(k),ie(void 0))},[z,k,Xt,Un,Jt,At,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 Rt=Q.messages.at(-1),ea=At&&Rt?.role==="assistant"?Rt.id:null,Jc=Rt?.role==="assistant"&&(Xt||Un||Q.isRecovering)?Rt.id:null,Zt=il({continuingAssistantMessageId:Jc,isActiveTurn:Ue,streamingAssistantMessageId:ea,trackedActivityMessageId:Wt.current}),Co=Zt===Rt?.id?Rt:void 0,ta=!!(Co&&ns(Co,De,{isStreaming:!0}).length>0),Zc=Bs(Co).hasServerContent;be(()=>{if(Ue&&Zt){if(Wt.current===Zt)return;let A=mr.current??Date.now();Wt.current=Zt,F(q=>({...q,[Zt]:{startedAt:A}}));return}let a=Wt.current;if(Ue||!a)return;let g=Date.now();F(A=>{let q=A[a];return!q||q.completedAt?A:{...A,[a]:{...q,completedAt:g}}}),Wt.current=null,mr.current=null},[Zt,Ue]);let hr=W(async(a,g,A)=>{Q.addToolOutput({output:A,toolCallId:g,toolName:a})},[Q.addToolOutput]),Ao=W((a,g)=>{bt(A=>{if(A.has(a)===g)return A;let q=new Set(A);return g?q.add(a):q.delete(a),q})},[]),yr=W(async(a,g)=>{await Di({activeToolCallIds:dt.current,run:async()=>{Ao(g.toolCallId,!0),ge("Fetching live data\u2026");try{await Ui({conversationId:o,execute:A=>Hi({context:u.context,execution:A,input:g.input,tool:a}),input:g.input,rpc:{claim:A=>Yt.call("claimClientToolEffect",[A],{timeout:cs}),complete:A=>Yt.call("completeClientToolEffect",[A],{timeout:cs})},submitOutput:A=>hr(a.name,g.toolCallId,A),toolCallId:g.toolCallId,toolName:a.name}),ge("Analyzing the results\u2026")}finally{Ao(g.toolCallId,!1)}},toolCallId:g.toolCallId})},[Yt,o,u.context,Ao,hr]),eu=W((a,g,A)=>{let q=g.toolCallId;if(se(ce=>({...ce,[q]:A?"approved":"rejected"})),ge(A?"Applying your change\u2026":"Updating your request\u2026"),Ne(u,C,o,A?"action_approved":"action_declined"),g.approval?.id)Q.addToolApprovalResponse({approved:A,id:g.approval.id});else if(!A)hr(a,q,{reason:"The user declined this tool call",rejected:!0});else{se(ce=>({...ce,[q]:"rejected"}));return}if(A){let ce=De.get(a);ce&&yr(ce,g).catch(()=>{})}else dt.current.add(q)},[Q.addToolApprovalResponse,De,o,yr,u,hr,C]);be(()=>{for(let a of Q.messages)if(a.role==="assistant")for(let g of a.parts){let A=Vs(g);if(!A)continue;let q=De.get(A);!q||dt.current.has(g.toolCallId)||Li({approvalApproved:g.approval?.approved,decision:J[g.toolCallId],needsApproval:q.needsApproval===!0,state:g.state})&&yr(q,g).catch(()=>{})}},[Q.messages,De,fr,yr,J]);let To=W(a=>{H(_a(a,{hasAttachments:yo&&y.length>0}))},[y.length,yo]);Kt(()=>{To(Ct.current)},[D,ke,To]);let na=W(a=>{if(a.length===0)return;let g=Mn([...y,...a],u.composerAttachmentContentTypes);P(g.error),T(g.files)},[y,u.composerAttachmentContentTypes,P,T]),ra=W(()=>{Qe(),qs(),N(""),T([]),P(null),V(null)},[Qe,qs,P,T]),tu=W(()=>Ct.current?.focus(),[]),Ro=W(()=>{if(Hn){Qe(),requestAnimationFrame(()=>Ct.current?.focus());return}if(ke){Qs(),requestAnimationFrame(()=>Ct.current?.focus());return}Gs()},[Qe,ke,Hn,Gs,Qs]);be(()=>{if(!e||!u.composerDictation||!jt)return;let a=g=>{Zi(g)&&(g.preventDefault(),Ct.current?.focus({preventScroll:!0}),Ro())};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e,jt,u.composerDictation,Ro]),Kt(()=>{e&&Ia(u.agentId,Ct.current)},[e,u.agentId]);let oa=W(async a=>{let g=++pt.current,A=Q.messages,q=A.findLast(Be=>Be.role==="user")?.id,ce=A.findLast(Be=>Be.role==="assistant")?.id,he=u.permissionShowPicker?a.permissionMode??we:u.permissionDefaultMode,pe=Dt(bn(u.tools,he));ve({modelId:a.modelId,permissionMode:he}),Wt.current=null,go.current.set(a.id,ce),Ee.activate(a.id);let rt=Ee.getStartedAtWallClock(a.id)??Date.now();mr.current=rt,gr(),po.current={previousUserMessageId:q??null,scrollKey:crypto.randomUUID()},de(!0),St(!1),E(!1),ge(Yn("accepted")),d(Ko(a.text,a.files));try{let Be=await Hc(u,a.selection);if(!cn({attempt:g,currentAttempt:pt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;a.files.length>0&&ge("Uploading attachments\u2026");let gt=await Oi({acceptedContentTypes:u.composerAttachmentContentTypes,apiBaseUrl:u.apiBaseUrl,conversationId:o,files:a.files,tokenManager:C});if(!cn({attempt:g,currentAttempt:pt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;Ne(u,C,o,"message_sent",{messageId:a.id});let wo=us({clientSubmittedAt:rt,clientTools:pe,generateConversationTitle:a.generateConversationTitle,imageSearch:u.imageSearch,modelId:a.modelId,newsSearch:u.newsSearch,pageContext:Be,permissionMode:he,turnId:a.id,webSearch:u.webSearch});ge(Yn("accepted")),await Q.sendMessage(xl(a,gt),{body:wo});let vn=xt.current;if(vn)throw xt.current=null,vn}catch(Be){if(!cn({attempt:g,currentAttempt:pt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;throw Be instanceof Error&&P(Be.message),Xs(A),Q.clearError(),St(!1),E(!1),de(!1),ge(null),Be}},[Q,ve,we,o,d,u,gr,P,Xs,C,Ee]),Bn=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(A=>yt(Pn(As(A,{...a,deliveryStatus:"pending"},"prepend"),a.id,"pending"),a.id))}).finally(()=>{le.current===a.id&&(le.current=null),g&&qt(A=>A+1)})},[oa,ze]),en=W((a,g,A=g?.generateConversationTitle??!0)=>{let q=a.trim();if(!q&&y.length===0)return;let ce=!Tt&&!le.current&&Le.current.messages.length===0,he=Nl({activeMessageId:le.current,authoritativeMessageCount:Q.messages.length,isNewChatStartScreen:x,queuedMessageCount:Le.current.messages.length}),pe={files:y,...he&&!A?{generateConversationTitle:!1}:{},id:g?.messageId??crypto.randomUUID(),...he?{isInitialTurn:!0}:{},...mn?{modelId:mn}:{},permissionMode:we,selection:U,text:q};ce&&(pe.deliveryStatus="sending"),he&&re({files:pe.files,id:pe.id,text:pe.text}),Ee.begin(pe.id,g),g?.firstFeedbackPaintedAt!==void 0&&Ee.markPaintedAt(pe.id,"first_feedback_paint",g.firstFeedbackPaintedAt),ce&&(le.current=pe.id),et(rt=>or(As(rt,pe),!1),{applyAfterPersist:!0}).then(()=>{ra(),ce?Bn(pe):qt(rt=>rt+1)}).catch(rt=>{ce&&(le.current=null),he&&re(null),g&&N(q),P(rt instanceof Error?rt.message:"This message could not be saved before sending")})},[y,mn,we,et,Q.messages.length,Tt,ra,U,Bn,P,x,Ee]),fn=n.suggestedPrompts,nu=$t(a=>en(a.prompt,a));be(()=>{if(!e)return;Na(u.agentId);let a=Pa(u.agentId);a&&(a.submitted?nu(a):N(g=>g||a.prompt))},[e,u.agentId]),be(()=>{if(!e||!u.suggestedPromptShortcuts||Q.messages.length>0||fn.length===0)return;let a=g=>{let A=el(g,fn.length);if(A===null)return;let q=fn[A];q&&(g.preventDefault(),en(q,void 0,!1))};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e,Q.messages.length,u.suggestedPromptShortcuts,en,fn]);let sa=a=>{a.preventDefault(),en(D)},ru=$t(async a=>{try{await et(g=>Pn(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(A=>yt(A,a.id));return}le.current===a.id&&Bn({...a,deliveryStatus:"sending"})}),ou=W(a=>{On.current=a,at(a)},[]);be(()=>{let a=Ll({activeMessageId:le.current,isBusy:Tt,isReordering:qe,queue:s});a&&(le.current=a.id,queueMicrotask(()=>{if(On.current){le.current===a.id&&(le.current=null);return}le.current===a.id&&ru(a)}))},[Tt,qe,s,Pt]);let su=W(a=>{re(g=>g?.id===a?null:g),ze(g=>rr(g,a))},[ze]),au=W((a,g,A)=>{ze(q=>Al(yt(q,null),a,g,A))},[ze]),iu=W(a=>{let g=Le.current.messages.find(A=>A.id===a);g&&(Qe(),N(g.text),T(g.files),g.modelId&&_(g.modelId),g.permissionMode&&Ge(g.permissionMode),V(g.selection),H(!0),re(A=>A?.id===a?null:A),ze(A=>rr(yt(A,null),a)),requestAnimationFrame(()=>Ct.current?.focus()))},[Qe,T,ze,Ge,_]),lu=W(a=>{if(Tt||le.current)return;let g=Le.current.messages.find(A=>A.id===a);g&&(le.current=g.id,et(A=>or(Pn(yt(A,null),a,"sending"),!0)).then(()=>{le.current===g.id&&Bn({...g,deliveryStatus:"sending"},{resumeDrainAfter:!1})}).catch(A=>{le.current===g.id&&(le.current=null),P(A instanceof Error?A.message:"This message could not be saved before sending")}))},[et,Tt,Bn,P]),aa=W(()=>{let a=le.current;pr.current+=1,pt.current+=1,Ze.current=!0,He.current=!1,le.current=null,re(null),ze(A=>or(a&&!Qt.current.has(a)?Pn(yt(A,null),a,"pending"):yt(A,null),!0)),de(!1),ge(null),St(!1),E(!1),Ne(u,C,o,"stopped");let g=Promise.resolve().then(()=>Q.stop()).catch(()=>{}).finally(()=>{zt.current===g&&(zt.current=null),Dn.current()});zt.current=g},[Q,o,u,ze,C]),cu=$t(()=>{if(Ze.current||He.current)return;let a=le.current;pr.current+=1,pt.current+=1,He.current=!0,le.current=null,ze(A=>or(a?rr(yt(A,null),a):yt(A,null),!0)),de(!1),ge(null),St(!1),E(!0),Ne(u,C,o,"turn_stalled",{messageId:a??void 0,source:"client-inactivity-watchdog"});let g=Promise.resolve().then(()=>Q.stop()).catch(()=>{}).finally(()=>{zt.current===g&&(zt.current=null),Dn.current(),He.current&&E(!0)});zt.current=g});be(()=>{if(Ac({hasActiveTurn:Ue,hasPendingClientToolCalls:Xt,isResuming:Jt,stalled:ct}))return Tc(cu)},[Q.isRecovering,Q.messages,Q.status,fr,Ue,Xt,Jt,Je,lt,ct]);let uu=W(a=>{if(Ne(u,C,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 A=Ar(g,a.args),q=`component-action-${crypto.randomUUID()}`;await g.execute(A,u.context,{conversationId:o,idempotencyKey:`heroui-agent-component-action:${o}:${q}`,toolCallId:q})}catch{}})();return}}Qi(a,{fillComposer:g=>{Qe(),N(g),H(!0),requestAnimationFrame(()=>Ct.current?.focus())},setSelection:V,submitPrompt:en})},[Qe,De,o,u,en,C]),du=W(a=>{let g=a.parts.filter(A=>A.type==="text").map(A=>A.text).join(`
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 k=ad(c.text,s);if(!k)continue;r.push({active:n.isStreaming===!0&&c.state!=="done",detail:k.detail,detailVisibility:"always",id:`${e.id}-reasoning-${l}`,kind:"thinking",label:k.label,messagePartIndex:l,stateKnown:c.state!==void 0,...r.length===0&&i?{title:i}:{}}),s+=1;continue}if(c.type==="data-activity"){let k=c.data.label.trim(),L=c.data.title?.trim();if(L&&!i){i=L;let $=r[0];$&&!$.title&&(r[0]={...$,title:L})}if(ld(k,c.data.stage)||L&&ts(k)===ts(L))continue;if(k&&o.has(k)){let $=r.findIndex(b=>b.label===k),X=r[$];L&&X&&!X.title&&(r[$]={...X,title:L})}else k&&(o.add(k),r.push({active:!1,detail:c.data.detail,id:c.id??`${e.id}-activity-${l}`,kind:c.data.kind??Br(k),label:k,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(k=>{let L=ai(k);return L!==null&&ii(L)&&k.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),C=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(k=>k.label===C);if(_>=0){let k=r[_];k&&(r[_]={...k,active:O,messagePartIndex:l,stateKnown:!0,...!k.title&&i?{title:i}:{}});continue}o.add(C),r.push({active:O,id:p.toolCallId||`${e.id}-tool-${l}`,kind:S?"chart":m==="executeSandbox"?"code":m==="getComponentSchema"?"thinking":Br(C),label:C,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 Yn(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 nn({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(nn,{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(nn,{children:o.previous.text})},o.previous.id):null]})}import{Code as bd,Heading as Tn,Link as Sd,Paragraph as Cd,Separator as Ad,Table as _t}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 kd}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(_t,{"data-slot":"markdown-table",variant:"secondary",children:fe(_t.ScrollContainer,{children:kd(_t.Content,{"aria-label":"Markdown table",children:[fe(_t.Header,{children:o.map((i,d)=>fe(_t.Column,{id:`column-${d}`,isRowHeader:d===0,children:i.props.children},String(i.key)))}),fe(_t.Body,{children:s.map((i,d)=>fe(_t.Row,{id:`row-${d}`,children:rs(i).map(l=>fe(_t.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(Tn,{className:s,level:1,children:o}),h2:({children:o,className:s})=>fe(Tn,{className:s,level:2,children:o}),h3:({children:o,className:s})=>fe(Tn,{className:s,level:3,children:o}),h4:({children:o,className:s})=>fe(Tn,{className:s,level:4,children:o}),h5:({children:o,className:s})=>fe(Tn,{className:s,level:5,children:o}),h6:({children:o,className:s})=>fe(Tn,{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 Nd}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 rn(e,t=1){Nd(()=>{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 ht}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 qd={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 Gd(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 ht("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 rn(m),vi(m,e,t&&r,c),ht(je,{className:"ha-activity-step-disclosure",isExpanded:c,onExpandedChange:p=>l({isDetailActive:t,isExpanded:p}),children:[ne(je.Heading,{children:ht(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 qr({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})),C=Gd(w),O=m===null&&!t&&!r&&(c==="fading"||c==="collapsing"),k=m??(t||c==="expanded"||c==="fading"),L=m!==null||t?k?"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?C.title:$===null?"Activity":X,f=C.kind,v=qd[f],R=w.map(y=>`${y.id}:${y.active?1:0}:${y.detail??""}:${y.sources?.map(M=>M.label).join(",")}`).join("|");return rn(S),vi(S,R,r,k),ht(je,{className:"ha-activity","data-complete":r?void 0:"true","data-phase":L,isExpanded:k,onExpandedChange:p,children:[ne(je.Heading,{children:ht(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:ht("ol",{"aria-label":"Thinking steps",children:[w.map((y,M)=>ht("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}),ht("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=>ht("span",{className:"ha-activity-source",children:[ne(hi,{"aria-hidden":"true"}),T.label]},T.label))}):null]})]},y.id)),r?null:ht("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 Ot}from"zod";var Wd=["callMcpTool","composeUI","executeSandbox","getComponentSchema","renderComponent","searchKnowledge","searchMcpTools","searchWeb"],jd="mcp_",Yd=20,Xd=16*1024,Jd=Ot.object({description:Ot.string().trim().min(1).max(1e3),inputSchema:Ot.record(Ot.string(),Ot.unknown()),name:Ot.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:Ot.boolean().optional()}),Ci=Ot.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 Dt(e){return Ci.parse(e.map(t=>({description:t.description,inputSchema:np(t),name:t.name,...t.needsApproval?{needsApproval:!0}:{}})))}var Rn=class extends Error{constructor(){super("The assistant configuration changed and must be bootstrapped again"),this.name="AgentRuntimeRevisionStaleError"}},Xn=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}},Gr=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 Gr&&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:Dt(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 Jn(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 ki(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 Jn(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 Gr(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 Ni(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 Jn(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 Rn:new Xn(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 Ne(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 Mn(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=Mn(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(C){x="failed",h=Cp(C)}let w;for(;;)try{w=bp.parse(await s.complete({...m,claimId:S.claimId,output:h,status:x}));break}catch(C){if(o()-p+250>r)throw C;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,generateConversationTitle:n,imageSearch:r,modelId:o,newsSearch:s,pageContext:i,permissionMode:d,turnId:l,webSearch:c}){if(!Rp.test(l))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),...n===void 0?{}:{generateConversationTitle:n},imageSearch:r,...o?{modelId:o}:{},newsSearch:s,pageContext:i,permissionMode:d,protocolVersion:6,requestId:l,sdkVersion:We,turnId:l,webSearch:c}}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 qi(e,t){let n=e;return{next:async()=>{if(n){let r=n;return n=null,r}return t()},refresh:t}}function Gi(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 kp,FileZipper as Np,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:Np,kind:"archive",label:"Archive"}:Up.has(t)?{Icon:Ep,kind:"code",label:"Code file"}:Fp.has(t)||n.startsWith("text/")?{Icon:kp,kind:"text",label:"Text document"}:{Icon:wp,kind:"file",label:"File"}}import{jsx as wn,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:[wn("span",{"aria-hidden":"true",className:"ha-attachment-icon",children:wn(n,{})}),zi("span",{className:"ha-attachment-copy",children:[wn("span",{className:"ha-attachment-name",title:e.name,children:e.name}),wn("span",{className:"ha-attachment-type",children:o})]}),wn("button",{"aria-label":`Remove ${e.name}`,type:"button",onClick:t,children:wn($p,{"aria-hidden":"true"})})]})}import{Globe as Kp,Xmark as qp}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(qp,{"aria-hidden":"true",className:"ha-chip-remove"})]})})}import{useCallback as Wr,useState as Gp}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]=Gp(!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&&Mt(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(nn,{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 Zn="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??Zn}: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 Lt,useEffect as jp,useLayoutEffect as Yp,useRef as Ke,useState as Xp}from"react";var Ht=4,on=1,dl="--ha-active-turn-spacer-height",pl='[data-role="user"][data-stream-anchor="true"]',Jp={hasOverflow:!1,isAtBottom:!0};function er(e){let t=e.scrollHeight-e.clientHeight>Ht,n=!t||e.scrollHeight-Math.max(0,e.scrollTop)-e.clientHeight<=Ht;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=Lt(b=>{x(f=>em(f,b)?f:b)},[]),C=Lt(b=>{t.current=0,b.style.removeProperty(dl)},[]),O=Lt(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},[]),_=Lt((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,C(f),n.current=!0,r.current=!1,l.current=f.scrollTop,w({hasOverflow:er(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)>on,typeof f.scrollTo=="function"?f.scrollTo({behavior:ml(b),top:v}):f.scrollTop=v,l.current=Math.max(0,f.scrollTop)},[C,e,w]),k=Lt(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=Lt((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)>on;i.current=M==="smooth"&&T,s.current=T,!T&&t.current>Ht&&(p.current=!0),l.current=b.scrollTop,w({hasOverflow:R>Ht,isAtBottom:R-y<=Ht}),typeof b.scrollTo=="function"?b.scrollTo({behavior:M,top:f}):(b.scrollTop=f,i.current=!1),l.current=Math.max(0,b.scrollTop)},[w]),$=Lt(()=>{let b=e.current;if(!b)return;O(b);let f=er(b),v=Math.max(0,b.scrollTop),R=v<l.current-on;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=k(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)>on){w({hasOverflow:f.hasOverflow,isAtBottom:!0});return}s.current=!1,i.current=!1,p.current=t.current>Ht}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)},[k,e,_,L,w,O]),X=Lt(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>Ht,S.current=!1,r.current=!0;let R=er(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(er(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=er(b),K=Math.max(0,b.scrollTop),ye=K<l.current-on,Se=K>l.current+on;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=k(b),B=Math.max(0,b.scrollHeight-b.clientHeight),D=Math.min(H??B,B),N=F.isAtBottom||Math.abs(K-D)<=on,Y=i.current;N&&(s.current=!1,i.current=!1,H!==null&&(p.current=t.current>Ht,r.current=!0,n.current=!1)),w(Y&&!N?{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()}},[k,$,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 rn(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-XOCP6UFF.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 tr}from"react";import{Fragment as Sm,jsx as Re,jsxs as nr}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]=tr(!1),[d,l]=tr(!1),[c,m]=tr(""),[p,S]=tr([]),[u,h]=tr(),x=bl(null),w=bl(0),C=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,k=e.includes("retry")&&o;if(!O&&!_&&!k)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 nr("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,_?nr(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"})}),nr(Zr,{isOpen:d,onOpenChange:$,children:[Re(Jr,{ref:C,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:nr(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."}),nr("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,k?Re("button",{"aria-label":"Retry response",className:"ha-message-action",type:"button",onClick:o,children:Re(cm,{"aria-hidden":"true"})}):null]})}import{jsx as En,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"?En("a",{"aria-label":`Open ${t}`,className:"ha-message-image",download:e.filename,href:e.url,rel:"noopener noreferrer",target:"_blank",title:t,children:En("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:[En("span",{"aria-hidden":"true",className:"ha-message-file-icon",children:En(r,{})}),Cl("span",{className:"ha-message-file-copy",children:[En("span",{className:"ha-message-file-name",title:t,children:t}),En("span",{className:"ha-message-file-type",children:s})]})]})}function sn(){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 rr(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 or(e,t){return e.isPaused===t?e:{...e,isPaused:t}}function yt(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 vt(e){return e.deliveryStatus??"pending"}function Pn(e,t,n){let r=e.messages.findIndex(s=>s.id===t);if(r===-1||vt(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,Ut="conversation-outboxes",Tm=":message-outbox:",an=new Map;function Ts(e,t){return`${e}${Tm}${t}:v1`}async function Rl(e){await an.get(e)?.catch(()=>{});let t=await Ms();if(!t)return sn();try{let n=t.transaction(Ut,"readonly"),r=await xm(n.objectStore(Ut).get(e));return await ws(n),Rm(r,e)}catch{return sn()}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(Ut,"readwrite"),i=s.objectStore(Ut);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(Ut,"readwrite");n.objectStore(Ut).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=>vt(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 sn();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 sn();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.generateConversationTitle===void 0||typeof t.generateConversationTitle=="boolean")&&(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=(an.get(e)??Promise.resolve()).catch(()=>{}).then(t);return an.set(e,r),r.then(()=>{an.get(e)===r&&an.delete(e)},()=>{an.get(e)===r&&an.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(Ut)||r.createObjectStore(Ut,{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 kl(e){let t=e.text.trim();return t||`${e.files.length} attachment${e.files.length===1?"":"s"}`}function Nl({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&&vt(o)!=="admitted")??null}function Ol(e,t){return e.messages.filter(n=>vt(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=>vt(o)==="sending")?null:r.messages.find(o=>vt(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 km,CircleExclamation as Nm,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)},C=(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),C(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))},k=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:k}}import{jsx as Ie,jsxs as sr}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:C,handleReorderKeyDown:O,moveMessageToPosition:_,positionPickerMessageId:k,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 sr("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 sr("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=>C(T,!1),onPointerDown:T=>L(T,f.id),onPointerMove:X,onPointerUp:T=>C(T,!0),children:Ie(Om,{"aria-hidden":"true"})}),k===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)=>sr("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(Nm,{"aria-hidden":"true"}):Ie(_m,{"aria-hidden":"true"})}),sr("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]}),sr("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(km,{"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 Gm}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 qm,composeRenderProps as Kl}from"react-aria-components";import{jsx as In}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 _=k=>{k.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]),C=Xe(()=>{clearTimeout(u.current)},[]),O=$l(()=>({handleCancelClose:C,handleClose:w,handleOpen:x,isOpen:i,isPointerInsideRef:p,portalContainer:l,setPortalContainer:c,triggerRef:m}),[C,w,x,i,l]);return In(Ps,{value:O,children:e})},ql=({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(Sn(_))},[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]),C=Xe(_=>{c(!0),r?.(_)},[c,r]),O=Xe(_=>{m.current||l(),n?.(_)},[l,m,n]);return In("span",{ref:h,className:me("aui-hover-card__trigger",t),"data-slot":"hover-card-trigger",onBlur:O,onFocus:C,onPointerEnter:x,onPointerLeave:w,...d,children:e})},Gl=({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]),C=Xe(O=>{O||m(!0),o?.(O)},[m,o]);return In(qm,{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:C,onPointerEnter:x,onPointerLeave:w,...l,children:O=>typeof t=="function"?t(O):t})},Ql=({children:e,className:t,...n})=>In(Km,{"data-slot":"hover-card-arrow",className:Kl(t,r=>me("aui-hover-card__arrow",r)??""),...n,children:e??In("svg",{fill:"none",height:"12",viewBox:"0 0 12 12",width:"12",xmlns:"http://www.w3.org/2000/svg",children:In("path",{d:"M0 0C5.48483 8 6.5 8 12 0Z"})})});var ar=Object.assign(Is,{Arrow:Ql,Content:Gl,Root:Is,Trigger:ql});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 Bt}from"react/jsx-runtime";var jl=Qm({sourceType:"url"}),ir=()=>zm(jl);function Ym(e){return e.trim().charAt(0).toUpperCase()||"?"}var ks=({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??Bt(xs,{children:[ae(Ns,{}),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(ar,{closeDelay:0,openDelay:150,children:x}):x})},Ns=({children:e,className:t,label:n,...r})=>{let{domain:o,enablePreview:s,href:i,locator:d,sourceType:l,title:c}=ir(),m=l==="url"&&i,p=e??n??(m?Bt(xs,{children:[ae(ao,{}),ae(so,{children:c??o}),d?ae(oo,{children:d}):null]}):Bt(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(ar.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(ar.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}=ir();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}=ir(),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 Bt("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(Gm,{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}=ir();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}=ir();if(!d)return null;let S=r??p,u=n??s,h=m==="url"&&l?Bt("a",{className:"aui-chat-source__preview-link",href:l,rel:"noopener noreferrer",target:"_blank",children:[Bt("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]}):Bt("div",{className:"aui-chat-source__preview-link","data-source-type":"document",children:[Bt("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(ar.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 xn}from"@heroui/react";import{composeRenderProps as Os}from"react-aria-components";import{jsx as Ft,jsxs as Xm}from"react/jsx-runtime";var Ds=({children:e,className:t,...n})=>Ft(xn,{"data-slot":"chat-sources",className:Os(t,r=>me("aui-chat-sources",r)??""),...n,children:e}),Yl=({children:e,className:t,...n})=>Ft(xn.Heading,{children:Xm(xn.Trigger,{"data-slot":"chat-sources-trigger",className:Os(t,r=>me("aui-chat-sources__trigger",r)??""),...n,children:[Ft("span",{className:"aui-chat-sources__trigger-label",children:e}),Ft(xn.Indicator,{className:"aui-chat-sources__indicator"})]})}),Xl=({children:e,className:t,...n})=>Ft(xn.Content,{"data-slot":"chat-sources-content",className:Os(t,r=>me("aui-chat-sources__content",r)??""),...n,children:Ft(xn.Body,{children:Ft("div",{className:"aui-chat-sources__content-body",children:e})})}),Jl=({children:e,className:t,role:n="list",...r})=>Ft("div",{className:me("aui-chat-sources__list",t),"data-slot":"chat-sources-list",role:n,...r,children:e});var Zl=Object.assign(ks,{DocumentIcon:io,Icon:ao,Locator:oo,Preview:_s,Root:ks,Title:so,Trigger:Ns}),lr=Object.assign(Ds,{Content:Xl,List:Jl,Root:Ds,Trigger:Yl});import{jsx as wt,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 wt(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 wt(lr.List,{"aria-label":"Sources",children:e.map(t=>wt(tc,{inList:!0,source:t},t.sourceId))})}function nc({sources:e}){return e.length===0?null:e.length===1?wt("div",{"aria-label":"Sources",className:"ha-message-sources","data-count":"1",role:"group",children:wt(tc,{source:e[0]})}):ec(lr,{className:"ha-message-sources","data-count":e.length,children:[ec(lr.Trigger,{"aria-label":`${e.length} sources`,children:[wt("span",{className:"ha-sources-label",children:"Sources"}),wt("span",{"aria-hidden":"true",className:"ha-sources-count",children:e.length})]}),wt(lr.Content,{children:wt(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 ln,Dropdown as cr,Input as cg,Label as dc,Modal as st,Popover as Ls,TextField as ug}from"@heroui/react";import{useCallback as dg,useRef as Hs,useState as Vt}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]=Vt(!1),[S,u]=Vt(!1),[h,x]=Vt(null),[w,C]=Vt(null),[O,_]=Vt(""),[k,L]=Vt(null),[$,X]=Vt(!1),[b,f]=Vt(),v=Hs(0),R=Hs(0),y=Hs(null);rn(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,N)=>{!N&&Date.now()-R.current<350||x(N?D:null)},F=(D,N)=>{z(),C({item:D,type:N}),_(D.title),L(null),u(!0)},K=()=>{$||(L(null),u(!1))},ye=(D,N)=>{N===pc&&F(D,"rename"),N===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),C({...w,item:{...w.item,title:D}}),u(!1)}catch(N){L(N instanceof Error?N.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(N=>{let Y=N.id===e,re=t.has(N.id),oe=!re&&n.has(N.id);return Ce("div",{className:"ha-session-row","data-actions-open":h===N.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?`${N.title}, new response available`:void 0,onClick:()=>{z(),Y||l(N.id)},children:[re?Z(nn,{className:"ha-session-title ha-session-shimmer",children:N.title}):Z("span",{className:"ha-session-title",children:N.title}),oe?Z("span",{"aria-hidden":"true",className:"ha-session-completed-dot"}):null]}),Ce(cr,{isOpen:h===N.id,onOpenChange:Me=>j(N.id,Me),children:[Z(ln,{isIconOnly:!0,"aria-label":`Chat actions for ${N.title}`,className:"ha-session-actions-trigger",size:"sm",variant:"ghost",onPointerDown:()=>{R.current=Date.now()},children:Z(sg,{"aria-hidden":"true"})}),Z(cr.Popover,{className:"ha-session-actions-menu",placement:"bottom end",UNSTABLE_portalContainer:b,children:Ce(cr.Menu,{"aria-label":`Actions for ${N.title}`,onAction:Me=>ye(N,Me),children:[Ce(cr.Item,{id:pc,textValue:"Rename",children:[Z(ag,{"aria-hidden":"true"}),Z(dc,{children:"Rename"})]}),Ce(cr.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"})]})]})})]})]},N.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(ln,{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(ln,{"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(st.Backdrop,{className:"ha-session-modal-backdrop",isDismissable:!$,isKeyboardDismissDisabled:$,isOpen:S,UNSTABLE_portalContainer:b,onOpenChange:D=>{D||K()},children:Z(st.Container,{placement:"center",size:"sm",children:Z(st.Dialog,{className:"ha-session-modal",children:Z(mg,{dialog:w,isPending:$,mutationError:k,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(st.Header,{children:Z(st.Heading,{children:"Rename chat"})}),Ce(st.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(st.Footer,{children:[Z(ln,{fullWidth:!0,isDisabled:t,type:"button",variant:"outline",onPress:r,children:"Cancel"}),Z(ln,{fullWidth:!0,isPending:t,type:"submit",children:t?"Saving\u2026":"Submit"})]})]}):e?.type!=="delete"?null:Ce(hc,{children:[Z(st.Header,{children:Z(st.Heading,{children:"Delete chat?"})}),Ce(st.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(st.Footer,{children:[Z(ln,{fullWidth:!0,isDisabled:t,variant:"outline",onPress:r,children:"Cancel"}),Z(ln,{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(qr,{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 cn({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 ur,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 ur(()=>{c.current=n},[n]),ur(()=>{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]),ur(()=>{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]),ur(()=>{if(d===t)return()=>Uo(t,c.current)},[t,d]),ur(()=>{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 kc({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 un,jsx as I,jsxs as Pe}from"react/jsx-runtime";var Dc=sn();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[C,O]=ee(null),[_,k]=ee({}),L=ue(_),$=ue(C),[X,b]=ee(null),[f,v]=ee([]),[R,y]=ee(hs),M=ue(R),[T,P]=ee({}),[z,ie]=ee(0),j=C?_[C]??null:null;Kt(()=>{L.current=_,$.current=C},[C,_]);let F=W(E=>{k(U=>({...U,[E.conversationId]:E})),O(E.conversationId)},[]),K=W(E=>{k(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||!C||ye(E=>ys(E,C))},[C,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}})},[]),N=ue(null),Y=ue(null),re=p.apiBaseUrl,oe=p.agentId,Me=$t(d),qe=W((E,U)=>{let V=ol({conversationEpoch:t,optimisticTarget:Y.current,readyConversationId:E,readyEpoch:U,requestedConversationId:S});V&&(k(J=>{let se=J[V];return!se||se.composerReady?J:{...J,[V]:{...se,composerReady:!0}}}),O(V),d(U))},[t,d,S]),at=Ae(()=>{try{return Dt(bn(p.tools,p.permissionDefaultMode)),p.permissionShowPicker&&Dt(bn(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]),it=at?null:Ii(p),dn=$t(E=>ki(p,w,E)),kn=$t(E=>{Ne(p,w,E,"embed_loaded")}),Et=ue(n);Kt(()=>{if(Et.current===n)return;Et.current=n,N.current=null,Y.current=null,L.current={},$.current=null,k({}),O(null),v([]);let E=hs();M.current=E,y(E),P({}),r?w.reset():w.clear()},[n,r,w]),Kt(()=>{if(S!==null||at)return;let E=rl(Y.current,t);Y.current=E;let U=N.current;if(!U)return;let V=E.conversationId;localStorage.setItem(U.storageKey,V),b(null),v(J=>{let se=qn(J,V,Ir([]),Date.now());return Nt(U.historyKey,se),se}),k(J=>({...J,[V]:{composerReady:!1,config:U.config,conversationId:V,historyKey:U.historyKey,readyEpoch:t,runtime:null,showStartScreenWhileConnecting:!0,storageKey:U.storageKey}})),O(V)},[at,t,S]),be(()=>{let E=!1;if(at){b(at),O(null),Me(t);return}let U=N.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),k(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"&&Mt(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 Ge=Vo(ve);E||v(Ge);let we=U?.config??lc(oe),Gt=we?null:Jn(w,`${re}/v1/agents/${encodeURIComponent(oe)}/config`),ut=Jn(w,`${re}/v1/agents/${encodeURIComponent(oe)}/conversations`).catch(()=>null),Nn=await dn(_e),pn=we??(Gt?await $g(Gt):null);if(!pn||!Nn)throw new Error("The data assistant could not be loaded");we||cc(oe,pn);let De=Ge.find(dt=>dt.id===_e),_n=qn(Ge,_e,De?.title??Ir([]),De?.updatedAt??Date.now());if(_n!==Ge&&Nt(ve,_n),!E){N.current={config:pn,historyKey:ve,storageKey:se},v(_n);let dt=L.current[_e],le={composerReady:!1,config:pn,conversationId:_e,historyKey:ve,readyEpoch:t,runtime:Nn.runtime,showStartScreenWhileConnecting:dt?.showStartScreenWhileConnecting??S===null,storageKey:se};F(le)}ut.then(async dt=>{if(!dt?.ok)return;let le=Pr((await dt.json()).conversations);E||v(Qt=>{let On=$o(Qt,le);return Nt(ve,On),On})}),kn(_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,it,at,t,n,oe,S,z,B,w]);let Je=W((E,U,V)=>{let J=N.current?.historyKey;J&&v(se=>{let ve=qn(se,E,U,Date.now(),V);return Nt(J,ve),ve})},[]),de=W(E=>{k(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[Ge,we]of Object.entries(Qr(se)))ve.set(Ge,we);let _e=await fetch(`${re}/v1/conversations/${encodeURIComponent(E)}`,{...U,headers:ve});if(_e.status===401){w.clear();let Ge=await w.get(),we=new Headers(U.headers);for(let[Gt,ut]of Object.entries(Qr(Ge)))we.set(Gt,ut);_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]),bt=W(async(E,U)=>{await Oe(E,{body:JSON.stringify({title:U}),headers:{"Content-Type":"application/json"},method:"PATCH"});let V=N.current?.historyKey;V&&v(J=>{let se=J.map(ve=>ve.id===E?{...ve,title:U}:ve);return Nt(V,se),se})},[Oe]),lt=W(async E=>{await Oe(E,{method:"DELETE"});let U=N.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(No(U.storageKey,E)),wr(Bo(U.storageKey,E)),Ml(Ts(U.storageKey,E)),k(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}),C===E&&B())},[C,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,_]),Pt=C?ge[C]?.config??null:null,qt=ue(null);be(()=>{!m||!j?.runtime||qt.current===j.conversationId||(qt.current=j.conversationId,Ne(p,w,j.conversationId,"opened"))},[m,p,j,w]);let It=at??X,dr=Ae(()=>Go(f),[f]),uo=f.find(E=>E.id===C)?.title??"New chat",St=N.current?"Loading chat\u2026":"Loading assistant\u2026",ct=S===null&&(!j||j.showStartScreenWhileConnecting);return I(un,{children:Pe(Aa,{keepMounted:!0,agentId:p.agentId,defaultExpanded:p.panelExpanded,expandable:!x&&p.panelExpandable,expandedTitle:uo,name:Pt?.name??"Data assistant",open:m,viewMode:p.viewMode,actionsSlot:x?I(un,{}):I(ac,{isDisabled:ct,onPress:B}),expandedSidebarSlot:x?void 0:I(Us,{activeConversationId:C,busyConversationIds:R.busyIds,completedConversationIds:R.completedIds,groups:dr,isNewConversationDisabled:ct,variant:"sidebar",onDeleteConversation:lt,onNewConversation:B,onRenameConversation:bt,onSelectConversation:H}),historySlot:x?I(un,{}):I(Us,{activeConversationId:C,busyConversationIds:R.busyIds,completedConversationIds:R.completedIds,groups:dr,onDeleteConversation:lt,onRenameConversation:bt,onSelectConversation:H}),onClose:o,onNewConversation:x?void 0:B,children:[It?I("div",{className:"ha-loading",role:"alert",children:It}):x?I(Ca,{indicator:I(Hg,{"aria-hidden":!0,color:"current",size:"md"})}):!j||!j.runtime||!Pt?ct&&j?I(Lc,{composerControlsRevealed:e,loadingLabel:St,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:St,placeholder:p.composerPlaceholder,showStartScreen:ct,suggestedPrompts:p.suggestedPrompts??[],composerStartSlot:I(Fc,{agentId:p.agentId,options:p}),onComposerControlsReveal:s},`pending-${t}`):null,I("div",{className:"ha-runtime-content",hidden:!!It||x,children:I(cl,{activeConversationId:It?null:C,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(Gg,{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:qe,onRuntimeRevisionStale:K,onConversationStarted:V=>{de(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(qg,{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=ue(null),[r,o]=ee(()=>ko(e)),[s,i]=ee(null),d=l=>{let c=Mn(l,t.composerAttachmentContentTypes);o(c.files),i(c.error),ka(e,c.files)};return t.composerAttachmentContentTypes.length===0?null:Pe(un,{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 qg({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(un,{children:[t.permissionShowPicker&&t.tools.length>0?I(kr,{"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($n,{children:"Dictate message"})]}):null]})}function Gg({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:C}){let{selectedModelId:O,setSelectedModelId:_}=Fs(w,u.composerDefaultModel),k=No(w,o),L=Tr(w,o),$=u.composerAttachmentAccept,X=Ae(()=>({key:$}),[$]),[b,f]=ee(()=>({files:Mn(ko(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 A=g.policy===X?g.files:[],q=typeof a=="function"?a(A):a;return{files:Mn(q,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(k):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,N]=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}}),[qe,at]=ee(!1),[it,dn]=ee(!0),[kn,Et]=ee(!1),[Je,de]=ee(!1),[Oe,bt]=ee(()=>new Set),[lt,ge]=ee(null),[Pt,qt]=ee(0),[It,dr]=ee(0),[uo,St]=ee(!1),[ct,E]=ee(!1),[U,V]=ee(null),[J,se]=ee({}),ve=W(a=>{u.permissionShowPicker?Mr(k,a.permissionMode):_o(k),ie(a)},[k,u.permissionShowPicker]),_e=oe.configuredDefaultMode===u.permissionDefaultMode?oe.selectedMode:u.permissionDefaultMode,Ge=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,ut=Ae(()=>bn(u.tools,Gt),[Gt,u.tools]),Nn=Ae(()=>Dt(ut),[ut]),pn=Ae(()=>Fi(Nn),[Nn]),De=Ae(()=>new Map(ut.map(a=>[a.name,a])),[ut]),_n=Ae(()=>new Set(ut.map(a=>a.name)),[ut]),dt=ue(new Set),le=ue(null),Qt=ue(new Set),On=ue(!1),Le=ue(s),po=ue(null),Ze=ue(!1),He=ue(!1),zt=ue(null),pr=ue(0),pt=ue(0),xt=ue(null),Wt=ue(null),mr=ue(null),mo=ue(new Set),go=ue(new Map),Dn=ue(()=>{}),$s=ue(null),Ks=ue(null),Ct=ue(null),Ee=Ae(()=>vc({report:({latencyMs:a,messageId:g,metric:A})=>{Ne(u,C,o,A,{latencyMs:a,latencyOrigin:"user_submit",messageId:g})}}),[o,u,C]),Vc=Ae(()=>Bo(w,o),[o,w]),Ln=Ae(()=>Ts(w,o),[o,w]),qs=Ec({attachments:y,draftKey:Vc,input:D,setAttachments:T,setInput:N}),$c=W((a,{language:g,signal:A})=>kc({apiBaseUrl:u.apiBaseUrl,audio:a,conversationId:o,...g?{language:g}:{},signal:A,tokenManager:C}),[o,u.apiBaseUrl,C]),{cancel:Qe,elapsedSeconds:fo,error:ho,isActive:ke,isRecording:Kc,isSupported:jt,isTranscribing:Hn,start:Gs,stop:Qs,stream:qc}=Zo({onValueChange:N,transcribe:$c,value:D}),yo=t||ke||y.length>0||M!==null||ho!==null,zs=W(()=>{u.composerControlsAvailable&&i()},[i,u.composerControlsAvailable]),Gc=a=>{Kn(u.agentId,!0,a.currentTarget),zs()},Qc=a=>{let g=a.currentTarget.querySelector(".ha-composer");g&&xa(g,a.relatedTarget)||Kn(u.agentId,!1)};be(()=>{Le.current=s},[s]),be(()=>{u.composerDictation||Qe()},[Qe,u.composerDictation]),be(()=>{e||Qe()},[e,Qe]);let mn=u.composerModelPicker?O:u.composerDefaultModel,gn=W(a=>{Le.current=a,m(o,()=>a)},[o,m]),et=W(async(a,{applyAfterPersist:g=!1}={})=>{let A=Le.current,q=a(A);if(q!==A){g?Le.current=q:gn(q);try{await Rs(Ln,q)}catch(ce){throw Le.current===q&&(g?Le.current=A:gn(A)),ce}g&&Le.current===q&&gn(q)}},[gn,Ln]),ze=W(a=>{et(a).catch(()=>{})},[et]),zc=W(a=>{Qt.current.add(a),et(g=>rr(Pn(g,a,"admitted"),a)).catch(()=>{})},[et]);be(()=>{let a=!1;return dn(!0),Rl(Ln).then(async g=>{if(a)return;let A=wl(g,Le.current),q=Qt.current,ce={...A,messages:A.messages.filter(he=>!q.has(he.id))};gn(ce),await Rs(Ln,ce)}).catch(()=>{}).finally(()=>{a||dn(!1)}),()=>{a=!0}},[gn,Ln]);let gr=W(()=>{Ze.current=!1,He.current=!1,xt.current=null,E(!1)},[]),Ws=W(a=>{cn({attempt:a,currentAttempt:pt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current})&&de(!1)},[]),{agent:Yt,connectionEpoch:fr,connectionError:mt,isHydrating:Wc,isReconnecting:js,retryConnection:jc}=Wg({conversationId:o,onRuntimeRevisionStale:S,onTurnAdmitted:zc,options:u,runtime:h,tokenManager:C}),Yc=$t(p);Kt(()=>{Yc(o,r)},[e,r,o]),be(()=>{if(it||fr===0)return;let a=[];for(let q of Le.current.messages)vt(q)==="sending"&&a.push(q.id);if(a.length===0){Et(!1);return}let g=!1,A;return Et(!0),(async()=>{let q=[];for(let pe=0;pe<a.length;pe+=50)q.push(a.slice(pe,pe+50));let ce=async pe=>{let rt=await Promise.all(q.map(async gt=>({response:await Yt.call(Fa,[{protocolVersion:6,turnIds:gt}],{timeout:15e3}),turnIds:new Set(gt)}))),Be=new Set;for(let{response:gt,turnIds:wo}of rt){if(gt.protocolVersion!==6||!Array.isArray(gt.turns))throw new Error("Invalid turn admission status response");for(let vn of gt.turns)vn.status==="admitted"&&wo.has(vn.turnId)&&Be.add(vn.turnId)}return Be.size===a.length||pe>=4?Be:(await new Promise(gt=>window.setTimeout(gt,500)),ce(pe+1))},he;try{he=await ce(0)}catch{g||(A=window.setTimeout(()=>dr(pe=>pe+1),1e3));return}if(!g){for(let pe of he)Qt.current.add(pe);await et(pe=>El(pe,he))}})().catch(()=>{}).finally(()=>{g||Et(!1)}),()=>{g=!0,A!==void 0&&window.clearTimeout(A)}},[Yt,et,fr,it,It]);let Xc=Ae(()=>new Proxy(Yt,{get(a,g){if(g==="send")return q=>a.send(Vi(q));let A=Reflect.get(a,g,a);return typeof A=="function"?A.bind(a):A}}),[Yt]),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;Ne(u,C,o,"component_rendered",{componentType:g?.kind})}a.type==="data-runtime-timing"&&uc(u.agentId,o,a.data)},onError:a=>{if(Ze.current||He.current){xt.current=null,de(!1),ge(null),queueMicrotask(()=>Dn.current());return}xt.current=a,de(!1),ge(null),Ne(u,C,o,"failure",{messageId:Ee.getActiveMessageId()??void 0,source:"cloudflare-chat"})},onFinish:({isError:a})=>{if(Ze.current||He.current){xt.current=null,de(!1),ge(null),queueMicrotask(()=>Dn.current());return}a&&!xt.current&&(xt.current=new Error("The request could not be completed")),de(!1),ge(null)},resume:!0,syncMessagesToServer:!1,tools:pn}),{clearError:Ys,setMessages:Xs}=Q;Kt(()=>{Dn.current=Ys},[Ys]);let At=Q.status==="submitted"||Q.status==="streaming"||Q.isStreaming,kt=uo||ct,Un=!kt&&Q.isToolContinuation,vo=!!(kt||Q.error||Q.connectionError||mt),Xt=Ae(()=>!vo&&(Oe.size>0||bc({isPendingPart:a=>{let g=a,A=Vs(g);return Dl({isClientTool:!!(A&&De.has(A)),state:g.state})},messages:Q.messages,terminal:vo})),[Q.messages,De,vo,Oe]),Ue=Cc({hasPendingClientToolCalls:Xt,isAutoContinuationPending:Un,isRecovering:Q.isRecovering,isRunning:At,localPending:Je,stalled:ct});be(()=>{if(Ue)return;let a=Ee.getActiveMessageId();a&&(Ee.complete(a),mo.current.delete(a),go.current.delete(a))},[Ue,Ee]);let Jt=!mt&&(Wc||js||it||kn),bo=Jt||Ue,So=kt||!!Q.error||!!Q.connectionError||!!mt,Tt=bo||So,Js=Il({hasChatError:!!(Q.error||Q.connectionError||mt),hasPendingClientToolCalls:Xt,hasReadyClientToolContinuation:Un,isLocalPending:Je,isResuming:Jt,isRunning:At,recoveryError:kt}),Zs=$t(l);be(()=>{z&&!At&&!Xt&&!Je&&!Jt&&!Un&&(_o(k),ie(void 0))},[z,k,Xt,Un,Jt,At,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 Rt=Q.messages.at(-1),ea=At&&Rt?.role==="assistant"?Rt.id:null,Jc=Rt?.role==="assistant"&&(Xt||Un||Q.isRecovering)?Rt.id:null,Zt=il({continuingAssistantMessageId:Jc,isActiveTurn:Ue,streamingAssistantMessageId:ea,trackedActivityMessageId:Wt.current}),Co=Zt===Rt?.id?Rt:void 0,ta=!!(Co&&ns(Co,De,{isStreaming:!0}).length>0),Zc=Bs(Co).hasServerContent;be(()=>{if(Ue&&Zt){if(Wt.current===Zt)return;let A=mr.current??Date.now();Wt.current=Zt,F(q=>({...q,[Zt]:{startedAt:A}}));return}let a=Wt.current;if(Ue||!a)return;let g=Date.now();F(A=>{let q=A[a];return!q||q.completedAt?A:{...A,[a]:{...q,completedAt:g}}}),Wt.current=null,mr.current=null},[Zt,Ue]);let hr=W(async(a,g,A)=>{Q.addToolOutput({output:A,toolCallId:g,toolName:a})},[Q.addToolOutput]),Ao=W((a,g)=>{bt(A=>{if(A.has(a)===g)return A;let q=new Set(A);return g?q.add(a):q.delete(a),q})},[]),yr=W(async(a,g)=>{await Di({activeToolCallIds:dt.current,run:async()=>{Ao(g.toolCallId,!0),ge("Fetching live data\u2026");try{await Ui({conversationId:o,execute:A=>Hi({context:u.context,execution:A,input:g.input,tool:a}),input:g.input,rpc:{claim:A=>Yt.call("claimClientToolEffect",[A],{timeout:cs}),complete:A=>Yt.call("completeClientToolEffect",[A],{timeout:cs})},submitOutput:A=>hr(a.name,g.toolCallId,A),toolCallId:g.toolCallId,toolName:a.name}),ge("Analyzing the results\u2026")}finally{Ao(g.toolCallId,!1)}},toolCallId:g.toolCallId})},[Yt,o,u.context,Ao,hr]),eu=W((a,g,A)=>{let q=g.toolCallId;if(se(ce=>({...ce,[q]:A?"approved":"rejected"})),ge(A?"Applying your change\u2026":"Updating your request\u2026"),Ne(u,C,o,A?"action_approved":"action_declined"),g.approval?.id)Q.addToolApprovalResponse({approved:A,id:g.approval.id});else if(!A)hr(a,q,{reason:"The user declined this tool call",rejected:!0});else{se(ce=>({...ce,[q]:"rejected"}));return}if(A){let ce=De.get(a);ce&&yr(ce,g).catch(()=>{})}else dt.current.add(q)},[Q.addToolApprovalResponse,De,o,yr,u,hr,C]);be(()=>{for(let a of Q.messages)if(a.role==="assistant")for(let g of a.parts){let A=Vs(g);if(!A)continue;let q=De.get(A);!q||dt.current.has(g.toolCallId)||Li({approvalApproved:g.approval?.approved,decision:J[g.toolCallId],needsApproval:q.needsApproval===!0,state:g.state})&&yr(q,g).catch(()=>{})}},[Q.messages,De,fr,yr,J]);let To=W(a=>{H(_a(a,{hasAttachments:yo&&y.length>0}))},[y.length,yo]);Kt(()=>{To(Ct.current)},[D,ke,To]);let na=W(a=>{if(a.length===0)return;let g=Mn([...y,...a],u.composerAttachmentContentTypes);P(g.error),T(g.files)},[y,u.composerAttachmentContentTypes,P,T]),ra=W(()=>{Qe(),qs(),N(""),T([]),P(null),V(null)},[Qe,qs,P,T]),tu=W(()=>Ct.current?.focus(),[]),Ro=W(()=>{if(Hn){Qe(),requestAnimationFrame(()=>Ct.current?.focus());return}if(ke){Qs(),requestAnimationFrame(()=>Ct.current?.focus());return}Gs()},[Qe,ke,Hn,Gs,Qs]);be(()=>{if(!e||!u.composerDictation||!jt)return;let a=g=>{Zi(g)&&(g.preventDefault(),Ct.current?.focus({preventScroll:!0}),Ro())};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e,jt,u.composerDictation,Ro]),Kt(()=>{e&&Ia(u.agentId,Ct.current)},[e,u.agentId]);let oa=W(async a=>{let g=++pt.current,A=Q.messages,q=A.findLast(Be=>Be.role==="user")?.id,ce=A.findLast(Be=>Be.role==="assistant")?.id,he=u.permissionShowPicker?a.permissionMode??we:u.permissionDefaultMode,pe=Dt(bn(u.tools,he));ve({modelId:a.modelId,permissionMode:he}),Wt.current=null,go.current.set(a.id,ce),Ee.activate(a.id);let rt=Ee.getStartedAtWallClock(a.id)??Date.now();mr.current=rt,gr(),po.current={previousUserMessageId:q??null,scrollKey:crypto.randomUUID()},de(!0),St(!1),E(!1),ge(Yn("accepted")),d(Ko(a.text,a.files));try{let Be=await Hc(u,a.selection);if(!cn({attempt:g,currentAttempt:pt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;a.files.length>0&&ge("Uploading attachments\u2026");let gt=await Oi({acceptedContentTypes:u.composerAttachmentContentTypes,apiBaseUrl:u.apiBaseUrl,conversationId:o,files:a.files,tokenManager:C});if(!cn({attempt:g,currentAttempt:pt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;Ne(u,C,o,"message_sent",{messageId:a.id});let wo=us({clientSubmittedAt:rt,clientTools:pe,generateConversationTitle:a.generateConversationTitle,imageSearch:u.imageSearch,modelId:a.modelId,newsSearch:u.newsSearch,pageContext:Be,permissionMode:he,turnId:a.id,webSearch:u.webSearch});ge(Yn("accepted")),await Q.sendMessage(xl(a,gt),{body:wo});let vn=xt.current;if(vn)throw xt.current=null,vn}catch(Be){if(!cn({attempt:g,currentAttempt:pt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;throw Be instanceof Error&&P(Be.message),Xs(A),Q.clearError(),St(!1),E(!1),de(!1),ge(null),Be}},[Q,ve,we,o,d,u,gr,P,Xs,C,Ee]),Bn=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(A=>yt(Pn(As(A,{...a,deliveryStatus:"pending"},"prepend"),a.id,"pending"),a.id))}).finally(()=>{le.current===a.id&&(le.current=null),g&&qt(A=>A+1)})},[oa,ze]),en=W((a,g,A=g?.generateConversationTitle??!0)=>{let q=a.trim();if(!q&&y.length===0)return;let ce=!Tt&&!le.current&&Le.current.messages.length===0,he=Nl({activeMessageId:le.current,authoritativeMessageCount:Q.messages.length,isNewChatStartScreen:x,queuedMessageCount:Le.current.messages.length}),pe={files:y,...he&&!A?{generateConversationTitle:!1}:{},id:g?.messageId??crypto.randomUUID(),...he?{isInitialTurn:!0}:{},...mn?{modelId:mn}:{},permissionMode:we,selection:U,text:q};ce&&(pe.deliveryStatus="sending"),he&&re({files:pe.files,id:pe.id,text:pe.text}),Ee.begin(pe.id,g),g?.firstFeedbackPaintedAt!==void 0&&Ee.markPaintedAt(pe.id,"first_feedback_paint",g.firstFeedbackPaintedAt),ce&&(le.current=pe.id),et(rt=>or(As(rt,pe),!1),{applyAfterPersist:!0}).then(()=>{ra(),ce?Bn(pe):qt(rt=>rt+1)}).catch(rt=>{ce&&(le.current=null),he&&re(null),g&&N(q),P(rt instanceof Error?rt.message:"This message could not be saved before sending")})},[y,mn,we,et,Q.messages.length,Tt,ra,U,Bn,P,x,Ee]),fn=n.suggestedPrompts,nu=$t(a=>en(a.prompt,a));be(()=>{if(!e)return;Na(u.agentId);let a=Pa(u.agentId);a&&(a.submitted?nu(a):N(g=>g||a.prompt))},[e,u.agentId]),be(()=>{if(!e||!u.suggestedPromptShortcuts||Q.messages.length>0||fn.length===0)return;let a=g=>{let A=el(g,fn.length);if(A===null)return;let q=fn[A];q&&(g.preventDefault(),en(q,void 0,!1))};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e,Q.messages.length,u.suggestedPromptShortcuts,en,fn]);let sa=a=>{a.preventDefault(),en(D)},ru=$t(async a=>{try{await et(g=>Pn(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(A=>yt(A,a.id));return}le.current===a.id&&Bn({...a,deliveryStatus:"sending"})}),ou=W(a=>{On.current=a,at(a)},[]);be(()=>{let a=Ll({activeMessageId:le.current,isBusy:Tt,isReordering:qe,queue:s});a&&(le.current=a.id,queueMicrotask(()=>{if(On.current){le.current===a.id&&(le.current=null);return}le.current===a.id&&ru(a)}))},[Tt,qe,s,Pt]);let su=W(a=>{re(g=>g?.id===a?null:g),ze(g=>rr(g,a))},[ze]),au=W((a,g,A)=>{ze(q=>Al(yt(q,null),a,g,A))},[ze]),iu=W(a=>{let g=Le.current.messages.find(A=>A.id===a);g&&(Qe(),N(g.text),T(g.files),g.modelId&&_(g.modelId),g.permissionMode&&Ge(g.permissionMode),V(g.selection),H(!0),re(A=>A?.id===a?null:A),ze(A=>rr(yt(A,null),a)),requestAnimationFrame(()=>Ct.current?.focus()))},[Qe,T,ze,Ge,_]),lu=W(a=>{if(Tt||le.current)return;let g=Le.current.messages.find(A=>A.id===a);g&&(le.current=g.id,et(A=>or(Pn(yt(A,null),a,"sending"),!0)).then(()=>{le.current===g.id&&Bn({...g,deliveryStatus:"sending"},{resumeDrainAfter:!1})}).catch(A=>{le.current===g.id&&(le.current=null),P(A instanceof Error?A.message:"This message could not be saved before sending")}))},[et,Tt,Bn,P]),aa=W(()=>{let a=le.current;pr.current+=1,pt.current+=1,Ze.current=!0,He.current=!1,le.current=null,re(null),ze(A=>or(a&&!Qt.current.has(a)?Pn(yt(A,null),a,"pending"):yt(A,null),!0)),de(!1),ge(null),St(!1),E(!1),Ne(u,C,o,"stopped");let g=Promise.resolve().then(()=>Q.stop()).catch(()=>{}).finally(()=>{zt.current===g&&(zt.current=null),Dn.current()});zt.current=g},[Q,o,u,ze,C]),cu=$t(()=>{if(Ze.current||He.current)return;let a=le.current;pr.current+=1,pt.current+=1,He.current=!0,le.current=null,ze(A=>or(a?rr(yt(A,null),a):yt(A,null),!0)),de(!1),ge(null),St(!1),E(!0),Ne(u,C,o,"turn_stalled",{messageId:a??void 0,source:"client-inactivity-watchdog"});let g=Promise.resolve().then(()=>Q.stop()).catch(()=>{}).finally(()=>{zt.current===g&&(zt.current=null),Dn.current(),He.current&&E(!0)});zt.current=g});be(()=>{if(Ac({hasActiveTurn:Ue,hasPendingClientToolCalls:Xt,isResuming:Jt,stalled:ct}))return Tc(cu)},[Q.isRecovering,Q.messages,Q.status,fr,Ue,Xt,Jt,Je,lt,ct]);let uu=W(a=>{if(Ne(u,C,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 A=Ar(g,a.args),q=`component-action-${crypto.randomUUID()}`;await g.execute(A,u.context,{conversationId:o,idempotencyKey:`heroui-agent-component-action:${o}:${q}`,toolCallId:q})}catch{}})();return}}Qi(a,{fillComposer:g=>{Qe(),N(g),H(!0),requestAnimationFrame(()=>Ct.current?.focus())},setSelection:V,submitPrompt:en})},[Qe,De,o,u,en,C]),du=W(a=>{let g=a.parts.filter(A=>A.type==="text").map(A=>A.text).join(`
4
4
 
5
5
  `).trim();g&&(navigator.clipboard?.writeText(g).catch(()=>{}),Ne(u,C,o,"message_copied",{messageId:a.id}))},[o,u,C]),pu=W((a,g,A)=>{let q=K[a]===g&&!A;if(ye(ce=>{let he={...ce};return q?delete he[a]:he[a]=g,he}),!q){let ce=A?.comment,he=A?.reasons??[];Ne(u,C,o,g==="up"?"feedback_up":"feedback_down",{feedbackCommentLength:ce?.length??0,feedbackReasons:he,hasFeedbackComment:!!ce,messageId:a});try{Promise.resolve(u.onFeedback?.({...ce?{comment:ce}:{},conversationId:o,messageId:a,rating:g==="up"?"positive":"negative",reasons:he})).catch(()=>{})}catch{}}},[o,K,u,C]),ia=W(()=>{let a=++pr.current;(async()=>{let g=zt.current;if(!await Sc(g,()=>pr.current===a))return;let A=++pt.current,q=Dt(bn(u.tools,we)),ce=crypto.randomUUID(),he=Date.now();Wt.current=null,mr.current=he,ve({modelId:mn,permissionMode:we}),gr(),po.current=null,de(!0),St(!1),E(!1),ge(Yn("accepted")),Ne(u,C,o,"retry");try{let pe=await Hc(u,U);if(!cn({attempt:A,currentAttempt:pt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;await Q.regenerate({body:us({clientSubmittedAt:he,clientTools:q,imageSearch:u.imageSearch,modelId:mn,newsSearch:u.newsSearch,pageContext:pe,permissionMode:we,turnId:ce,webSearch:u.webSearch})})}catch{if(!cn({attempt:A,currentAttempt:pt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;St(!0)}finally{Ws(A)}})()},[ve,Q,mn,we,Ws,o,u,gr,U,C]),mu=Q.messages.findLast(a=>a.role==="assistant")?.id,tt=_l({authoritativeMessageCount:Q.messages.length,localTurn:Y,queue:s}),hn=Ae(()=>tt?{id:tt.id,parts:[{text:kl(tt),type:"text"}],role:"user"}:null,[tt]),Fn=Ae(()=>hn?[hn,...Q.messages]:Q.messages,[Q.messages,hn]),gu=hn!==null,vr=!!(tt&&!s.isPaused&&s.blockedMessageId!==tt.id),la=!!(Q.error||Q.connectionError||kt||mt),ca=Fn.findLast(a=>a.role==="user")?.id,{activeStreamKey:br,activeTurnMessageId:ua}=ul({isActive:Ue||vr,lastUserMessageId:ca,pendingTurn:hn&&vr?{previousUserMessageId:null,scrollKey:hn.id}:po.current}),da=ci({clientToolNames:_n,isLocalPending:Je,isRecovering:Q.isRecovering||js,isStreaming:At,messages:Q.messages,status:Q.status}),{showHome:pa,standaloneStatus:fu}=ll({hasActiveActivity:ta,hasError:la,hasResponseStarted:Zc,isActiveTurn:Ue||vr,messageCount:Fn.length,preferHomeWhileEmpty:x,progress:vr?Zn:lt??Yn(da),runtimeStatus:Jt?"pending":"ready"}),ma=al({activeStreamKey:br,activeTurnMessageId:ua}),ga=pa||ma&&Fn.length===0,nt=Ee.getActiveMessageId(),hu=nt?go.current.get(nt):void 0,fa=nt&&Rt?.role==="assistant"&&Rt.id!==hu?Rt:void 0,Vn=Bs(fa,{hasActivity:!!(fa&&ta),hasTransientData:!!(nt&&mo.current.has(nt))}),Mo=gu&&la?null:fu,Sr=!ma&&Mo&&(e||Mo!==Zn)?Mo:null,ha=!!Sr;Kt(()=>{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||Vn.hasServerContent||Q.error||Q.connectionError||kt||mt)&&Ee.markAfterPaint(nt,"first_feedback_paint"),Vn.hasServerContent&&Ee.markAfterPaint(nt,"first_server_content_paint"),Vn.hasText&&Ee.markAfterPaint(nt,"first_text_paint"))}},[e,nt,Q.connectionError,Q.error,ha,s.messages,tt,kt,mt,Vn.hasServerContent,Vn.hasText,Ee]);let yu=Ae(()=>Ol(s,tt?.id??null),[s,tt?.id]),Cr=!!(D.trim()||y.length>0),ya=Hn?"Cancel transcription":ke?"Stop dictation":"Dictate message",va=jt?ya:"Voice dictation is not supported in this browser",yn=At&&!Cr?"Stop answering":Tt&&!(x&&Fn.length===0)?"Queue message":"Send message";return Pe(un,{children:[Pe(fl,{activityPhase:da,streamKey:br,children:[ga?Pe("div",{className:"ha-empty",children:[I("h2",{children:u.greeting}),I("p",{children:"Live answers with charts, metrics, and tables."})]}):Fn.map(a=>I(Qg,{actions:u.messageActions,activityTiming:j[a.id],canRetry:a.id===mu&&!Tt,clientTools:De,exportFormats:u.componentExportFormats,feedback:K[a.id]??null,isActivityActive:a.id===Zt,isStreaming:a.id===ea,markdownAnimation:u.markdownAnimation,markdownCaret:u.markdownCaret,markdownPlugins:u.markdownPlugins,message:a,toolDecisions:J,turnAnchor:a.id===ua&&br!==null?"active":a.id===ca?"latest":null,onAction:uu,onClientToolDecision:eu,onCopy:du,onFeedback:pu,onRetry:ia,onSelect:V},a.id)),Sr?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:Sr===Zn?I(yc,{},br??o):I(qr,{label:Sr})})}):null,Q.error||Q.connectionError||kt||mt?Pe("div",{className:"ha-error",role:"alert",children:[I("span",{children:mt?"The assistant connection could not be restored.":ct?"The assistant stopped responding. Please retry.":"The request could not be completed."}),I("button",{type:"button",onClick:mt?jc:ia,children:"Retry"})]}):null]}),Pe("form",{className:"ha-composer-wrap",onBlur:Qc,onSubmit:sa,children:[pa&&fn.length>0?I("div",{"aria-label":"Suggested prompts",className:"ha-suggestions",role:"group",children:fn.map((a,g)=>Pe("button",{className:"ha-suggestion",type:"button","aria-keyshortcuts":u.suggestedPromptShortcuts?`Control+${g+1}`:void 0,onClick:()=>en(a,void 0,!1),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:Tt,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":ke||void 0,"data-expanded":ke||Se?!0:void 0,disabled:u.composerAttachmentContentTypes.length===0,onFilesSelected:na,onFileIntent:u.composerAttachmentContentTypes.length>0?zs:void 0,children:[I("textarea",{ref:Ct,"aria-label":"Message the assistant",placeholder:u.composerPlaceholder,readOnly:ke,rows:1,value:D,onFocus:Gc,onSelect:a=>Kn(u.agentId,!0,a.currentTarget),onChange:a=>{N(a.currentTarget.value),Kn(u.agentId,!0,a.currentTarget),To(a.currentTarget)},onKeyDown:a=>{if(!ke&&!Hl(a,Ks.current)&&Ji(a.nativeEvent)){if(a.preventDefault(),At&&!Cr){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(A=>A!==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,ke?I("div",{className:"ha-dictation-session",children:Hn?I("span",{className:"ha-dictation-status",role:"status",children:"Transcribing\u2026"}):Pe(un,{children:[I(jo,{active:Kc,"aria-hidden":"true",className:"ha-dictation-waveform",height:28,stream:qc}),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&&!ke?I(kr,{"aria-label":"Tool permissions",className:"ha-permission-picker",isDisabled:Js,value:_e,onChange:Ge}):null,u.composerModelPicker&&!ke?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":jt?Xi:void 0,"aria-label":ya,"aria-pressed":ke,className:"ha-dictation","data-shortcut":jt?"\u2303\u21E7D":void 0,"data-tooltip":va,disabled:!jt,type:"button",onClick:Ro,children:[Hn?I(Lg,{"aria-hidden":"true"}):ke?I(Oc,{"aria-hidden":"true"}):I(Uc,{"aria-hidden":"true"}),I($n,{shortcut:jt?"\u2303\u21E7D":void 0,children:va})]}):null,M||u.composerDictation&&ho?I("span",{className:"ha-dictation-error",role:"alert",children:M??ho}):null,At&&!Cr?Pe("button",{"aria-keyshortcuts":fs,"aria-label":yn,className:"ha-send","data-shortcut":"\u21B5","data-tooltip":yn,type:"button",onClick:aa,children:[I(Oc,{"aria-hidden":"true"}),I($n,{shortcut:"\u21B5",children:yn})]}):Pe("button",{"aria-keyshortcuts":fs,"aria-label":yn,className:"ha-send","data-shortcut":"\u21B5","data-tooltip":yn,disabled:!Cr||ke,type:"submit",children:[I(Og,{"aria-hidden":"true"}),I($n,{shortcut:"\u21B5",children:yn})]})]}),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:C,toolDecisions:O,turnAnchor:_}){let k=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:C},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(k,{hasContent:f.length>0,latestContentPartIndex:v}),y=oc(L,{hasContent:f.length>0,isStreaming:i});if(f.length===0&&b.length===0&&k.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:[k.length>0?I(Si,{completedAt:t?.completedAt,hasResponseStarted:R,isStreaming:i,items:k,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(Ga,{"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(()=>qi(o,()=>Ni({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),[C,O]=ee(!1),_=ue(null),k=ue(!1),L=Vg(),$=W(()=>{let M=new Error("The assistant connection could not be restored");_.current=M,k.current=!1,h(M),w(!1),O(!1)},[]),X=W(async()=>{try{return{ticket:(await l.next()).ticket}}catch(M){return M instanceof Rn?(t(e),new Promise(()=>{})):($(),{ticket:""})}},[e,$,t,l]),b=W(()=>{_.current=null,h(null),m(M=>M+1),O(!1),k.current&&(k.current=!1,Ne(r,s,e,"reconnected"))},[e,r,s]),f=W(M=>{if(!_.current){if(Ug(M)){$();return}k.current=!0,w(!0),O(!0)}},[$]),v=W(M=>{let T=Gi(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&&!C))return Rc($)},[c,u,$,x,C]);let y=W(()=>{_.current=null,k.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 Rn){t(e);return}if(F instanceof Xn&&!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:C,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};