@heroui/agent 0.2.0-beta.7 → 0.2.0-beta.9
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.
- package/CHANGELOG.md +20 -2
- package/README.md +15 -10
- package/dist/chart-content-BBHQVMP4.js +1 -0
- package/dist/chunk-2XBFFSW2.js +1 -0
- package/dist/chunk-64RI74L5.js +1 -0
- package/dist/chunk-6ZJJN322.js +1 -0
- package/dist/chunk-7KCGPNEN.js +1 -0
- package/dist/chunk-BBB5EHDN.js +5 -0
- package/dist/chunk-CR3H7AVI.js +1 -0
- package/dist/chunk-HCLXS4HQ.js +1 -0
- package/dist/chunk-MXLGM4WV.js +1 -0
- package/dist/chunk-OA3TG5CS.js +1 -0
- package/dist/chunk-PZJ4NC3J.js +1 -0
- package/dist/chunk-RNNGE7KM.js +1 -0
- package/dist/chunk-S6OIAJSC.js +1 -0
- package/dist/chunk-SUDHJNTJ.js +2 -0
- package/dist/chunk-WUAFMD7Z.js +2 -0
- package/dist/component-renderer-GG6JVRUG.js +1 -0
- package/dist/composer-draft-NSKK65F3.js +1 -0
- package/dist/composer-image-draft-KAGTNQR7.js +1 -0
- package/dist/contracts.d.ts +50 -19
- package/dist/contracts.js +2 -2545
- package/dist/css/index.css +1 -1
- package/dist/embed-runtime-GYXK7V6N.js +5 -0
- package/dist/identity-3P8-17km.d.ts +95 -0
- package/dist/index.d.ts +46 -10
- package/dist/index.js +1 -28
- package/dist/interactive-map-surface-WC2LPCR7.js +1 -0
- package/dist/internal/client-tools.js +1 -0
- package/dist/internal/models.js +1 -0
- package/dist/internal/runtime.js +1 -0
- package/dist/internal/theme.js +1 -0
- package/dist/next.d.ts +2 -1
- package/dist/next.js +1 -22
- package/dist/server.d.ts +1 -1
- package/dist/server.js +1 -260
- package/package.json +6 -6
- package/dist/chart-content-E4NPTUPR.js +0 -2696
- package/dist/chunk-3FG5NRTX.js +0 -9
- package/dist/chunk-6O3SFXJK.js +0 -325
- package/dist/chunk-FNGGMHVR.js +0 -625
- package/dist/chunk-OQGXZY5L.js +0 -1091
- package/dist/chunk-TOOT6SZ2.js +0 -74
- package/dist/chunk-V5S5FRGV.js +0 -984
- package/dist/chunk-VJA52U5P.js +0 -137
- package/dist/component-renderer-46EJDPTB.js +0 -10627
- package/dist/embed-runtime-UF7XJIFA.js +0 -7650
- package/dist/identity-Z6i6pL0F.d.ts +0 -166
- package/dist/interactive-map-surface-67KHT3VB.js +0 -362
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use client";import{a as _o,b as Oo,c as Lo}from"./chunk-MXLGM4WV.js";import{a as La,c as Sn}from"./chunk-S6OIAJSC.js";import{a as me}from"./chunk-CR3H7AVI.js";import{A as vn,B as Da,b as ba,c as Vn,e as Ca,f as Aa,g as wo,h as Eo,k as wa,l as Ea,m as $n,n as Pa,o as Ia,p as xa,q as xo,r as ka,s as Na,t as _a,u as Oa,v as Tr,w as ko,x as Rr,y as Mr,z as No}from"./chunk-WUAFMD7Z.js";import{a as Po}from"./chunk-6ZJJN322.js";import{b as va,c as Ar,d as Sa}from"./chunk-64RI74L5.js";import{c as Ta,d as Ra,e as Io,f as Ma}from"./chunk-OA3TG5CS.js";import{a as Ha,b as Ua,c as Ba,d as Do}from"./chunk-7KCGPNEN.js";import"./chunk-2XBFFSW2.js";import{a as Uo,b as Va,c as $a,d as wr}from"./chunk-RNNGE7KM.js";import{a as Fa,b as Ho}from"./chunk-PZJ4NC3J.js";import{useAgentChat as Mg}from"@cloudflare/ai-chat/react";import{ArrowUp as wg,ArrowUpRight as Eg,Microphone as Oc,Plus as Dc,StopFill as xc,Xmark as Pg}from"@gravity-ui/icons";function Rt(e){return!!(e&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e))}function Bo(e,t){return e===null?null:typeof e=="string"?Rt(e)?e:null:Rt(t)?t:null}var Er=30,Ka=52;function Fo(e){try{let t=JSON.parse(localStorage.getItem(e)??"[]");return Pr(t)}catch{return[]}}function Pr(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object"&&"id"in t&&typeof t.id=="string"&&Rt(t.id)&&"title"in t&&typeof t.title=="string"&&"updatedAt"in t&&typeof t.updatedAt=="number")).sort((t,n)=>n.updatedAt-t.updatedAt).slice(0,Er):[]}function Vo(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 kt(e,t){localStorage.setItem(e,JSON.stringify(t.slice(0,Er)))}function Kn(e,t,n,r,{replaceTitle:o=!1}={}){if(!n)return e;let s=e.find(d=>d.id===t);return[{id:t,title:o?n:s?.title??n,updatedAt:r},...e.filter(d=>d.id!==t)].sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,Er)}function Ir(e){let t=e?.find(r=>r.role==="user"),n=t?.parts.filter(r=>r.type==="text").map(r=>r.text??"").join(" ");return n?.trim()?Ko(n):t?"Attachment":null}function $o(e,t){return e?Ko(e):t[0]?.name||"Attachment"}function Ko(e){let t=e.replace(/\s+/g," ").trim();return t.length>Ka?`${t.slice(0,Ka-1).trimEnd()}\u2026`:t}function qo(e){let t=new Date;t.setHours(0,0,0,0);let n=t.getTime(),r=n-8640*60*1e3,o=[{items:[],label:"Today"},{items:[],label:"Previous 7 days"},{items:[],label:"Older"}];for(let s of e)s.updatedAt>=n?o[0].items.push(s):s.updatedAt>=r?o[1].items.push(s):o[2].items.push(s);return o.filter(s=>s.items.length>0)}import{Disclosure as bn}from"@heroui/react";import{jsx as Fe,jsxs as en}from"react/jsx-runtime";function gu(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase().replace(/^\w/,t=>t.toUpperCase())}function fu(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])=>[gu(n),String(r)])}function qa({approveLabel:e="Allow",className:t,denyLabel:n="Deny",hint:r="Waiting for your approval",icon:o,input:s,onApprove:i,onDeny:d,title:l,...c}){let m=fu(s),p=s!=null&&(typeof s!="object"||Object.keys(s).length>0);return en("section",{"aria-label":l,className:me("aui-approval",t),"data-slot":"agent-ui-approval",...c,children:[en("div",{className:"aui-approval__heading","data-slot":"agent-ui-approval-heading",children:[o?Fe("span",{"aria-hidden":!0,className:"aui-approval__icon","data-slot":"agent-ui-approval-icon",children:o}):null,en("div",{className:"aui-approval__heading-text",children:[Fe("strong",{className:"aui-approval__title",children:l}),r?Fe("span",{className:"aui-approval__hint",children:r}):null]})]}),p?en(bn,{defaultExpanded:!0,className:"aui-approval__disclosure",children:[Fe(bn.Heading,{children:en(bn.Trigger,{className:"aui-approval__disclosure-trigger",children:["Review action details",Fe(bn.Indicator,{})]})}),Fe(bn.Content,{children:Fe(bn.Body,{children:m?Fe("dl",{className:"aui-approval__details","data-slot":"agent-ui-approval-details",children:m.map(([C,u])=>en("div",{className:"aui-approval__detail",children:[Fe("dt",{children:C}),Fe("dd",{children:u})]},C))}):Fe("pre",{className:"aui-approval__pre",children:JSON.stringify(s,null,2)})})})]}):null,en("div",{className:"aui-approval__actions","data-slot":"agent-ui-approval-actions",children:[Fe(_o,{size:"md",variant:"tertiary",onClick:d,children:n}),Fe(_o,{size:"md",variant:"primary",onClick:i,children:e})]})]})}import{Description as Cu,Label as Au,ListBox as Go,Select as Gn}from"@heroui/react";import{useCallback as Tu,useEffect as Ru,useRef as Qa,useState as za}from"react";import{useId as hu}from"react";import{jsx as G,jsxs as qn}from"react/jsx-runtime";function Ga({className:e,provider:t}){let n=t?.toLowerCase();return n==="openai"?G(yu,{className:e,"data-provider":"openai"}):n==="google"?G(vu,{className:e,"data-provider":"google"}):n==="anthropic"?G(Su,{className:e,"data-provider":"anthropic"}):n==="moonshot ai"?G(bu,{className:e,"data-provider":"moonshot-ai"}):null}function yu(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 vu(e){let t=hu().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`,C=`${t}-gemini-lemon-blur`;return qn("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})}),qn("g",{fill:"none",children:[qn("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(#${C})`,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)"})})]}),qn("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:C,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 Su(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 bu(e){return qn("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 gt,jsxs as Qn}from"react/jsx-runtime";function Mu({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]=za(!1),[c,m]=za(),p=Qa(0),C=Qa(null),u=n||o.length===0,h=o.find(A=>A.id===i),x=Tu(A=>{C.current=A,A?.setAttribute("aria-keyshortcuts","Control+Shift+M"),m(Sn(A))},[]),w=A=>{!A&&Date.now()-p.current<350||l(A)};return Ru(()=>{if(u)return;let A=O=>{O.defaultPrevented||O.isComposing||O.repeat||!O.ctrlKey||!O.shiftKey||O.altKey||O.metaKey||O.key.toLowerCase()!=="m"||(O.preventDefault(),C.current?.focus(),l(!0))};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[u]),Qn(Gn,{"aria-label":e,className:me("aui-model-picker",t),isDisabled:u,isOpen:d,value:i,onOpenChange:w,onChange:A=>{A!=null&&r(A),l(!1)},children:[Qn(Gn.Trigger,{ref:x,className:"aui-model-picker__trigger","data-shortcut":"\u2303\u21E7M","data-slot":"agent-ui-model-picker-trigger","data-tooltip":"Select model",onPointerDown:()=>{p.current=Date.now()},children:[gt(Gn.Value,{className:"aui-model-picker__value",children:h?.label??i}),gt(Gn.Indicator,{className:"aui-model-picker__indicator"}),Qn("span",{"aria-hidden":"true",className:"aui-picker-tooltip",children:[gt("span",{children:"Select model"}),gt("kbd",{className:"aui-picker-tooltip__shortcut",children:"\u2303\u21E7M"})]})]}),gt(Gn.Popover,{className:"aui-model-picker__popover",placement:s,UNSTABLE_portalContainer:c,children:gt(Go,{"aria-label":`${e} options`,className:"aui-model-picker__list",children:o.map(A=>{let O=Mu(A);return Qn(Go.Item,{className:"aui-model-picker__option","data-description":O,id:A.id,textValue:A.label,children:[gt(Ga,{className:"aui-model-picker__option-icon",provider:A.provider}),Qn("span",{className:"aui-model-picker__option-copy",children:[gt(Au,{className:"aui-model-picker__option-label",children:A.label}),O?gt(Cu,{className:"aui-model-picker__option-description",title:O,children:O}):null]}),gt(Go.ItemIndicator,{className:"aui-model-picker__option-indicator"})]},A.id)})})})]})}import{Hand as wu,LockOpen as Eu,ShieldCheck as Xa}from"@gravity-ui/icons";import{Description as Pu,Label as Iu,ListBox as Qo,Select as zn}from"@heroui/react";import{useCallback as xu,useEffect as ku,useRef as Wa,useState as ja}from"react";import{jsx as rt,jsxs as Wn}from"react/jsx-runtime";var Ya=[{description:"Ask before every client tool action.",icon:wu,id:"ask",label:"Ask for approval"},{description:"Only ask for actions marked as needing approval.",icon:Xa,id:"auto",label:"Approve for me"},{description:"Run client tools without asking for approval.",icon:Eu,id:"full",label:"Full access"}];function kr({"aria-label":e="Tool permissions",className:t,isDisabled:n=!1,onChange:r,value:o}){let[s,i]=ja(!1),[d,l]=ja(),c=Wa(0),m=Wa(null),p=Ya.find(h=>h.id===o),C=xu(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 ku(()=>{if(n)return;let h=x=>{x.defaultPrevented||x.isComposing||x.repeat||!x.ctrlKey||!x.shiftKey||x.altKey||x.metaKey||x.key.toLowerCase()!=="p"||(x.preventDefault(),m.current?.focus(),i(!0))};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[n]),Wn(zn,{"aria-label":e,className:me("aui-permission-picker",t),"data-tone":o==="full"?"warning":void 0,isDisabled:n,isOpen:s,value:o,onOpenChange:u,onChange:h=>{h!=null&&r(h),i(!1)},children:[Wn(zn.Trigger,{ref:C,className:"aui-permission-picker__trigger","data-shortcut":"\u2303\u21E7P","data-slot":"agent-ui-permission-picker-trigger","data-tooltip":"Change permissions",onPointerDown:()=>{c.current=Date.now()},children:[rt(Xa,{"aria-hidden":"true",className:"aui-permission-picker__trigger-icon"}),rt(zn.Value,{className:"aui-permission-picker__value",children:p?.label??o}),rt(zn.Indicator,{className:"aui-permission-picker__indicator"}),Wn("span",{"aria-hidden":"true",className:"aui-picker-tooltip",children:[rt("span",{children:"Change permissions"}),rt("kbd",{className:"aui-picker-tooltip__shortcut",children:"\u2303\u21E7P"})]})]}),rt(zn.Popover,{className:"aui-permission-picker__popover",placement:"top start",UNSTABLE_portalContainer:d,children:rt(Qo,{"aria-label":`${e} options`,className:"aui-permission-picker__list",children:Ya.map(h=>{let x=h.icon;return Wn(Qo.Item,{className:"aui-permission-picker__option","data-description":h.description,"data-tone":h.id==="full"?"warning":void 0,id:h.id,textValue:h.label,children:[rt(x,{"aria-hidden":"true",className:"aui-permission-picker__option-icon"}),Wn("span",{className:"aui-permission-picker__option-copy",children:[rt(Iu,{className:"aui-permission-picker__option-label",children:h.label}),rt(Pu,{className:"aui-permission-picker__option-description",title:h.description,children:h.description})]}),rt(Qo.ItemIndicator,{className:"aui-permission-picker__option-indicator"})]},h.id)})})})]})}import{useEffect as zo,useRef as Cn}from"react";import{jsx as Za}from"react/jsx-runtime";var Nu=40,Ja=2;function Nr(e,t,n){return Math.min(n,Math.max(t,e))}function _u(e){let t=Nr(Math.round(e),32,32768);return 2**Math.round(Math.log2(t))}function Ou(e){return e instanceof Error?e:new Error("Unable to access the microphone.")}function Du(){let e=window;return e.AudioContext??e.webkitAudioContext}function Lu(e){e?.getTracks().forEach(t=>t.stop())}function Hu(e){if(!(!e||e.state==="closed"))try{e.close().catch(()=>{})}catch{}}function Uu(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 Wo({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=Nu,onError:m,onStreamEnd:p,onStreamReady:C,role:u,sensitivity:h=1.15,smoothingTimeConstant:x=.82,stream:w,style:A,...O}){let _=Cn(null),k=Cn({onError:m,onStreamEnd:p,onStreamReady:C}),L=Cn(null),$=Cn(null),X=Cn(null),S=Cn([]);zo(()=>{k.current={onError:m,onStreamEnd:p,onStreamReady:C}},[m,p,C]),zo(()=>{if(!e||w===null){_.current=null;return}let M,T=!1,P=!1,z=!1,ie=w===void 0,j,B=w,K=be=>{try{j?.disconnect()}catch{}j=void 0,_.current?.context===M&&(_.current=null),Hu(M),M=void 0,ie&&Lu(B),B=void 0,be&&P&&!z&&(z=!0,k.current.onStreamEnd?.())};return(async()=>{try{let be=Du();if(!be)throw new Error("Live audio analysis is not supported in this browser.");if(!B){if(!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone capture is not supported in this browser.");B=await navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,...s?{deviceId:{exact:s}}:{},echoCancellation:!0,noiseSuppression:!0}})}if(T){K(!1);return}M=new be;let H=M.createAnalyser();if(H.fftSize=_u(l),H.smoothingTimeConstant=Nr(x,0,1),j=M.createMediaStreamSource(B),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?.(B)}catch(be){K(!1),T||k.current.onError?.(Ou(be))}})(),()=>{T=!0,K(!0)}},[e,s,l,w,x]),zo(()=>{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,B=0,K=0,ye=D=>{if(K<=0||B<=0)return;D-j>500&&(ie=getComputedStyle(M).color||ie,j=D),P.clearRect(0,0,K,B),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;S.current.length!==Me&&(S.current=Array.from({length:Me},()=>0));let at=S.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)),vt=Math.max(Oe+1,Math.floor(de.length*.46)),it=Nr(h,0,4);for(let ge=0;ge<Me;ge+=1){let Et=Me<=1?0:ge/(Me-1),Kt=Math.min(de.length-1,Math.round(Oe+Et*(vt-Oe))),Pt=Math.pow((de[Kt]??0)/255*it,.72);at[ge]=Nr((at[ge]??0)*.56+Pt*.44,0,1)}}else at.fill(0);let un=Math.max(Ja,B*.84),xn=B/2,wt=oe*N+(oe-1)*Y,Je=(K-wt)/2;for(let de=0;de<oe;de+=1){let Oe=Me-1-Math.min(de,oe-1-de),vt=e?at[Oe]??0:0,it=Math.max(Ja,vt*un),ge=Je+de*re,Et=xn-it/2;P.globalAlpha=e?.38+vt*.62:.2,Uu(P,ge,Et,N,it)}P.globalAlpha=1},be=()=>{let D=T.getBoundingClientRect(),N=Math.max(1,window.devicePixelRatio||1),Y=getComputedStyle(M).color||ie;K=Math.max(0,D.width),B=Math.max(0,D.height),M.width=Math.max(1,Math.round(K*N)),M.height=Math.max(1,Math.round(B*N)),M.style.width=`${K}px`,M.style.height=`${B}px`,P.setTransform(N,0,0,N,0,0),ie=Y,ye(performance.now())},H=D=>{ye(D),z=requestAnimationFrame(H)};be();let F;return typeof ResizeObserver>"u"?window.addEventListener("resize",be):(F=new ResizeObserver(be),F.observe(T)),e&&(z=requestAnimationFrame(H)),()=>{z&&cancelAnimationFrame(z),F?.disconnect(),window.removeEventListener("resize",be)}},[e,n,r,h]);let f=typeof c=="number"?`${Math.max(1,c)}px`:c,v={...A,height:f},R=`${Math.max(0,d)}px`,y=`linear-gradient(90deg, transparent 0, #000 min(${R}, 20%), #000 calc(100% - min(${R}, 20%)), transparent 100%)`;return Za("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:Za("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 ei,useRef as $e,useState as _r,useSyncExternalStore as Bu}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."},ni="Microphone access is blocked for this page. Allow microphone access and try again.",Fu="Microphone access is enabled, but speech recognition is blocked in this browser or embedded preview.",Yo="Voice dictation is not supported in this browser.",ri="Voice recording stopped unexpectedly. Try again.",Vu=["audio/webm;codecs=opus","audio/mp4","audio/webm","audio/ogg;codecs=opus"],$u=/\s+/g;function Dr(e,t){let n=t.trim().replace($u," ");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 Xo(e,t,n="unknown"){if(e==="not-allowed"){if(n==="denied")return ni;if(n==="granted")return Fu}return Lr[e]??(t?.trim()||"Voice dictation stopped unexpectedly.")}async function Ku(){if(typeof navigator>"u"||!navigator.permissions?.query)return"unknown";try{return(await navigator.permissions.query({name:"microphone"})).state}catch{return"unknown"}}function oi(){if(typeof window>"u")return;let e=window;return e.SpeechRecognition??e.webkitSpeechRecognition}function qu(){return!!oi()}function ti(){return typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof MediaRecorder<"u"}function Gu(){if(!(typeof MediaRecorder>"u"||typeof MediaRecorder.isTypeSupported!="function"))return Vu.find(e=>MediaRecorder.isTypeSupported(e))}function Or(e){e?.getTracks().forEach(t=>t.stop())}function jo(e){if(typeof DOMException<"u"&&e instanceof DOMException){if(e.name==="NotAllowedError"||e.name==="SecurityError")return ni;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 Qu(e){return e.error??new Error(ri)}function zu(){return()=>{}}function Jo({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),C=Ve(()=>n?ti():qu(),[n]),u=Bu(zu,C,()=>!1),h=$e("idle"),x=$e(r),w=$e(null),A=$e(e),O=$e(t),_=$e(null),k=$e(null),L=$e(0),$=$e(0),X=$e(n),S=$e(null),f=$e(new Map),v=$e(r);ei(()=>{A.current=e,O.current=t,X.current=n,v.current=r},[e,t,n,r]);let R=Ve(H=>{h.current=H,s(H)},[]),y=Ve(()=>{w.current!==null&&(clearInterval(w.current),w.current=null)},[]),M=Ve(()=>{y(),$.current=Date.now(),d(0),w.current=setInterval(()=>{d(Math.floor((Date.now()-$.current)/1e3))},250)},[y]),T=Ve(H=>{H.onend=null,H.onerror=null,H.onresult=null,H.onstart=null},[]),P=Ve(H=>{H.ondataavailable=null,H.onerror=null,H.onstop=null},[]),z=Ve((H,F)=>{if(P(H.recorder),F&&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 F=H.recorder.mimeType||H.chunks[0]?.type||"audio/webm",D=new Blob(H.chunks,{type:F}),N=X.current;if(!N||D.size===0){R("idle"),c(D.size===0?Lr["no-speech"]:ri);return}let Y=new AbortController;S.current=Y;try{let re=await N(D,{...A.current?{language:A.current}:{},signal:Y.signal});if(L.current!==H.session||Y.signal.aborted)return;if(!re.trim()){c(Lr["no-speech"]);return}O.current(Dr(x.current,re)),c(null)}catch(re){if(L.current!==H.session||Y.signal.aborted)return;c(re instanceof Error&&re.message.trim()?re.message:"Voice transcription could not be completed. Try again.")}finally{S.current===Y&&(S.current=null),L.current===H.session&&R("idle")}},[P,z,y,R]),j=Ve(()=>{L.current+=1,y(),S.current?.abort(),S.current=null,c(null),p(null),R("idle");let H=_.current,F=k.current;if(_.current=null,k.current=null,f.current.clear(),H&&z(H,!0),!!F){T(F);try{F.abort()}catch{}}},[T,z,y,R]),B=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 F=k.current;if(F){y();try{F.stop()}catch(D){R("idle"),L.current+=1,k.current=null,f.current.clear(),T(F);try{F.abort()}catch{}c(D instanceof Error?D.message:"Voice dictation could not be stopped cleanly.")}}},[j,T,z,y,R]),K=Ve(async()=>{if(!ti()){c(Yo);return}let H=L.current+1;L.current=H,x.current=v.current,c(null),d(0),p(null),R("recording");let F;try{F=await navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0}})}catch(Y){if(L.current!==H)return;R("idle"),c(jo(Y));return}if(L.current!==H){Or(F);return}let D;try{let Y=Gu();D=Y?new MediaRecorder(F,{mimeType:Y}):new MediaRecorder(F)}catch(Y){if(Or(F),L.current!==H)return;R("idle"),c(jo(Y));return}let N={chunks:[],recorder:D,session:H,stream:F};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(Qu(Y).message))},D.onstop=()=>{ie(N)},_.current=N,p(F);try{D.start(1e3),M()}catch(Y){L.current+=1,_.current=null,z(N,!1),p(null),R("idle"),c(jo(Y))}},[z,ie,M,y,R]),ye=Ve(()=>{let H=oi();if(!H){c(Yo);return}let F;try{F=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,F.continuous=!0,F.interimResults=!0,F.maxAlternatives=1,A.current&&(F.lang=A.current),F.onstart=()=>{L.current===D&&(R("recognizing"),M())},F.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))},F.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"?Ku().then(re=>{L.current===Y&&c(Xo(N.error,N.message,re))}):c(Xo(N.error,N.message))),k.current===F&&(k.current=null,T(F))},F.onend=()=>{L.current===D&&(y(),R("idle"),k.current===F&&(k.current=null,T(F)))},k.current=F,c(null),d(0),R("recognizing");try{F.start()}catch(N){T(F),k.current=null,y(),R("idle"),c(N instanceof Error?N.message:"Voice dictation could not be started.")}},[T,M,y,R]),be=Ve(()=>{h.current!=="idle"||k.current||_.current||S.current||(X.current?K():ye())},[ye,K]);return ei(()=>()=>{L.current+=1,y(),S.current?.abort(),S.current=null;let H=_.current,F=k.current;if(_.current=null,k.current=null,H&&z(H,!0),!!F){T(F);try{F.abort()}catch{}}},[T,z,y]),{cancel:j,elapsedSeconds:i,error:l,isActive:o!=="idle",isRecording:o==="recording",isSupported:u,isTranscribing:o==="transcribing",start:be,stop:B,stream:m}}import{Spinner as Ig}from"@heroui/react/spinner";import{isTerminalCloseEvent as xg}from"agents/client";import{useAgent as kg}from"agents/react";import{Suspense as Ng,useCallback as W,useEffect as Se,useEffectEvent as Vt,useId as _g,useLayoutEffect as $t,useMemo as Ae,useRef as ce,useState as ee}from"react";import{z as te}from"zod";var We="0.2.0-beta.9";var Wu=te.enum(["light","dark","system"]),ju=te.enum(["outline","plain","surface","surface-secondary"]),Yu=new Set(["[object object]","0","anonymous","distinct_id","distinctid","email","false","guest","id","nan","none","not_authenticated","null","true","undefined"]),Zo=te.string().trim().min(1).max(200).refine(e=>!Yu.has(e.toLowerCase()),{message:"Identity id is reserved"}),Xu=te.discriminatedUnion("type",[te.object({id:Zo,type:te.literal("anonymous")}),te.object({id:Zo,type:te.literal("user")})]),Ju=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()}),Of=te.object({anonymousId:Zo.optional(),identity:Xu,profile:Ju.optional()}),Df=te.object({expiresAt:te.number().int().positive(),token:te.string().trim().min(1)}),Lf=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:ju.default("plain"),theme:Wu});var Zu="understanding your request";function ed(e){let t=e.replace(/\r\n?/g,`
|
|
2
|
+
`).trim();if(!t)return null;if(t.length<=1600)return t;let n=t.slice(0,1601),r=n.lastIndexOf(" "),o=r>=1600*.8?r:1600;return`${n.slice(0,o).trimEnd()}\u2026`}function td(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 nd(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?td(s):null,l=i?.replace(/^\s*(?:[|:—–-]\s*)?/u,"").trim(),c=ed(d&&l?l:n);return c?{detail:c,label:d??(t===0?"Thinking through your request":"Thinking through the next step")}:null}function rd(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 es(e){return e.toLocaleLowerCase().replace(/[.…]+$/u,"").trim()}function od(e,t){return t!=="accepted"&&t!=="preparing"?!1:es(e)===Zu}function si(e){return e.type==="dynamic-tool"&&e.toolName?e.toolName:e.type.startsWith("tool-")?e.type.slice(5):null}function ai(e){return e==="renderComponent"||e==="composeUI"}var sd={ai:"AI",api:"API",crm:"CRM",csv:"CSV",id:"ID",mcp:"MCP",sql:"SQL",ui:"UI",url:"URL"};function ad(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").trim().split(/\s+/).map((n,r)=>{let o=sd[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 ii(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 ts(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=nd(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(od(k,c.data.stage)||L&&es(k)===es(L))continue;if(k&&o.has(k)){let $=r.findIndex(S=>S.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=si(c);if(!m)continue;let p=c,C=ai(m),u=C&&e.parts.slice(l+1).some(k=>{let L=si(k);return L!==null&&ai(L)&&k.state==="output-available"});if(C&&p.state==="output-error"&&(n.isStreaming||u))continue;let h=m==="searchWeb"?rd(p):null,x=C?"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??ad(m),A=p.state==="output-denied"||!!(p.output&&typeof p.output=="object"&&"rejected"in p.output&&p.output.rejected)?h?`Skipped web search for \u201C${h}\u201D`:`Skipped ${x}`:p.state==="output-error"?h?`Couldn\u2019t search the web for \u201C${h}\u201D`:`Couldn\u2019t complete ${x}`:x,O=["input-available","input-streaming","approval-requested","approval-responded"].includes(p.state),_=r.findIndex(k=>k.label===A);if(_>=0){let k=r[_];k&&(r[_]={...k,active:O,messagePartIndex:l,stateKnown:!0,...!k.title&&i?{title:i}:{}});continue}o.add(A),r.push({active:O,id:p.toolCallId||`${e.id}-tool-${l}`,kind:C?"chart":m==="executeSandbox"?"code":m==="getComponentSchema"?"thinking":Br(A),label:A,messagePartIndex:l,stateKnown:!0,...r.length===0&&i?{title:i}:{}})}if(!n.isStreaming||r.length===0||r.some(l=>l.active))return r;let d=r.length-1;return r[d]?.stateKnown?r:r.map((l,c)=>({...l,active:c===d}))}var id={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"},ld=new Set(["accepted","preparing","generating","waiting-client-tool","running-server-tool","recovering"]);function cd(e){return e.type==="dynamic-tool"&&e.toolName?e.toolName:e.type.startsWith("tool-")?e.type.slice(5):null}function jn(e){return e?id[e]:null}function li({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=cd(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"&&ld.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 xd,CircleCheck as kd,Code as Nd,Database as _d,Globe as fi,Magnifier as Od,Wrench as Dd}from"@gravity-ui/icons";import{Disclosure as je}from"@heroui/react";import{useEffect as hi,useRef as os,useState as ss}from"react";import{useEffect as dd,useState as pd}from"react";import{jsx as ud}from"react/jsx-runtime";function tn({children:e,className:t,...n}){return ud("span",{...n,className:`ha-shimmer${t?` ${t}`:""}`,children:e})}import{jsx as Fr,jsxs as gd}from"react/jsx-runtime";var md=280;function Vr({animateOnMount:e=!0,children:t,className:n,...r}){let[o,s]=pd(()=>({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 dd(()=>{if(!d)return;let l=window.setTimeout(()=>{s(c=>c.current.id===i?{...c,previous:null}:c)},md);return()=>window.clearTimeout(l)},[i,d]),gd("span",{...r,"aria-label":r["aria-label"]??t,className:`ha-status-text${n?` ${n}`:""}`,"data-slot":"animated-text",children:[Fr("span",{"aria-hidden":"true","data-slot":"animated-text-value",className:o.current.animate?"ha-status-text__value ha-status-text__value--animated":"ha-status-text__value",children:Fr(tn,{children:o.current.text})},o.current.id),o.previous?Fr("span",{"aria-hidden":"true",className:"ha-status-text__value ha-status-text__value--exiting","data-slot":"animated-text-previous-value",children:Fr(tn,{children:o.previous.text})},o.previous.id):null]})}import{Code as fd,Heading as An,Link as hd,Paragraph as yd,Separator as vd,Table as Nt}from"@heroui/react";import{Children as ci,Suspense as ui,isValidElement as di,lazy as Sd,memo as bd,useMemo as Cd}from"react";import{jsx as fe,jsxs as Ed}from"react/jsx-runtime";var Ad=Sd(()=>import("streamdown").then(e=>({default:e.Streamdown})));function Td(e){return e?.match(/language-([^\s]+)/)?.[1]??"plaintext"}function Rd(e,t){return e?.find(n=>Array.isArray(n.language)?n.language.includes(t):n.language===t)}function ns(e){return ci.toArray(e?.props.children).filter(t=>di(t))}function rs(e,t){return ci.toArray(e).find(n=>di(n)&&n.props.node?.tagName===t)}function Md({children:e}){let t=rs(e,"thead"),n=rs(e,"tbody"),r=rs(t?.props.children,"tr"),o=ns(r),s=ns(n);return fe(Nt,{"data-slot":"markdown-table",variant:"secondary",children:fe(Nt.ScrollContainer,{children:Ed(Nt.Content,{"aria-label":"Markdown table",children:[fe(Nt.Header,{children:o.map((i,d)=>fe(Nt.Column,{id:`column-${d}`,isRowHeader:d===0,children:i.props.children},String(i.key)))}),fe(Nt.Body,{children:s.map((i,d)=>fe(Nt.Row,{id:`row-${d}`,children:ns(i).map(l=>fe(Nt.Cell,{children:l.props.children},String(l.key)))},String(i.key)))})]})})})}function wd(e,t){function n({children:o,className:s,node:i}){let d=Td(s),l=String(o??"").replace(/\n$/,""),c=Rd(e?.renderers,d);if(c){let m=c.component,p=i?.properties?.metastring;return fe(ui,{fallback:fe(Lo,{code:l,language:d}),children:fe(m,{code:l,isIncomplete:t,language:d,meta:typeof p=="string"?p:void 0})})}return fe(Lo,{code:l,language:d})}function r({children:o,className:s}){return fe(fd,{className:s,"data-slot":"markdown-inline-code",children:o})}return{a:({children:o,className:s,href:i})=>fe(hd,{className:s,href:i,rel:"noreferrer",target:"_blank",children:o}),code:n,h1:({children:o,className:s})=>fe(An,{className:s,level:1,children:o}),h2:({children:o,className:s})=>fe(An,{className:s,level:2,children:o}),h3:({children:o,className:s})=>fe(An,{className:s,level:3,children:o}),h4:({children:o,className:s})=>fe(An,{className:s,level:4,children:o}),h5:({children:o,className:s})=>fe(An,{className:s,level:5,children:o}),h6:({children:o,className:s})=>fe(An,{className:s,level:6,children:o}),hr:({className:o})=>fe(vd,{className:o,"data-slot":"markdown-separator",variant:"tertiary"}),inlineCode:r,p:({children:o,className:s})=>fe(yd,{className:s,"data-slot":"markdown-paragraph",size:"sm",children:o}),table:Md}}var $r=bd(function({animated:t=Da,caret:n="block",children:r,isStreaming:o=!1,plugins:s}){let i=Cd(()=>wd(s,o),[o,s]);return fe(ui,{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(Ad,{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 Pd}from"react";function Id(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 pi(e,t){delete e.dataset.topScroll,delete e.dataset.bottomScroll,delete e.dataset.topBottomScroll,t==="both"?e.dataset.topBottomScroll="true":t==="top"?e.dataset.topScroll="true":t==="bottom"&&(e.dataset.bottomScroll="true")}function nn(e,t=1){Pd(()=>{let n=e.current;if(!n)return;let r=null,o=null,s=()=>{r!==null&&cancelAnimationFrame(r),r=requestAnimationFrame(()=>{r=null;let l=Id(n,t);l!==o&&(o=l,pi(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),pi(n,"none")}},[t,e])}import{jsx as ne,jsxs as ft}from"react/jsx-runtime";var Ld=24,Hd=160,Ud=220;function yi(e,t,n,r){let o=os(!0);hi(()=>{let s=e.current;if(!s)return;let i,d=!1,l=()=>{let h=s.scrollHeight-s.scrollTop-s.clientHeight;o.current=h<=Ld},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 C=s.firstElementChild,u=C&&typeof ResizeObserver<"u"?new ResizeObserver(p):null;return C&&u?.observe(C),()=>{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 Bd(e){let[t,n]=ss(()=>({isStreaming:e,phase:e?"expanded":"collapsed"})),r=t.phase;return t.isStreaming!==e&&(r=e?"expanded":"fading",n({isStreaming:e,phase:r})),hi(()=>{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"?Hd:Ud,d=window.setTimeout(()=>{n(l=>l.isStreaming===e&&l.phase===r?{...l,phase:s}:l)},i);return()=>window.clearTimeout(d)},[e,r]),r}var Fd={browse:fi,chart:xd,code:Nd,data:_d,search:Od,thinking:Dd},mi="Working on your request";function Kr(e){return e.toLocaleLowerCase().replace(/\s+/g," ").replace(/[.…!?:;,]+$/u,"").trim()}function Vd(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(mi))?"Making progress":mi}}function gi({active:e}){return ft("span",{className:"ha-activity-icon","data-state":e?"active":"complete",children:[ne("span",{"aria-hidden":"true",className:"ha-activity-icon-state ha-activity-icon-state--active",children:ne("span",{className:"ha-activity-spinner"})}),ne("span",{"aria-hidden":"true",className:"ha-activity-icon-state ha-activity-icon-state--complete",children:ne(kd,{})})]})}function vi({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 $d({detail:e,isDetailActive:t,isLabelActive:n,isTurnActive:r,label:o,markdownAnimation:s,markdownPlugins:i}){let[d,l]=ss(()=>({isDetailActive:t,isExpanded:t})),c=d.isExpanded;d.isDetailActive!==t&&(c=t,l({isDetailActive:t,isExpanded:c}));let m=os(null);return nn(m),yi(m,e,t&&r,c),ft(je,{className:"ha-activity-step-disclosure",isExpanded:c,onExpandedChange:p=>l({isDetailActive:t,isExpanded:p}),children:[ne(je.Heading,{children:ft(je.Trigger,{className:"ha-activity-step-trigger",children:[ne(vi,{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 Kd(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=Bd(r),[m,p]=ss(null),C=os(null),u=o.findLastIndex(y=>y.active),h=o.length-1,x=l?u>=0?u:h:-1,w=o.map((y,M)=>({...y,active:M===x})),A=Vd(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 ${Kd($)}`,S=r||O?A.title:$===null?"Activity":X,f=A.kind,v=Fd[f],R=w.map(y=>`${y.id}:${y.active?1:0}:${y.detail??""}:${y.sources?.map(M=>M.label).join(",")}`).join("|");return nn(C),yi(C,R,r,k),ft(je,{className:"ha-activity","data-complete":r?void 0:"true","data-phase":L,isExpanded:k,onExpandedChange:p,children:[ne(je.Heading,{children:ft(je.Trigger,{className:"ha-activity-trigger",children:[ne("span",{"aria-hidden":"true",className:"ha-activity-summary-icon",children:ne("span",{children:ne(v,{})},f)}),r||O?ne(Vr,{className:"ha-activity-summary-label ha-progress ha-progress-shimmer",role:"status",children:S}):ne("span",{className:"ha-activity-summary-label ha-activity-summary-label--complete ha-progress",children:S}),ne(je.Indicator,{className:"ha-activity-chevron"})]})}),ne(je.Content,{className:"ha-activity-disclosure-content",children:ne(je.Body,{children:ne("div",{ref:C,className:"ha-activity-panel",children:ft("ol",{"aria-label":"Thinking steps",children:[w.map((y,M)=>ft("li",{"aria-current":y.active?"step":void 0,className:"ha-activity-item","data-active":y.active||void 0,"data-state":y.active?"active":"complete",children:[ne(gi,{active:y.active}),ft("div",{className:"ha-activity-content",children:[y.detail&&(y.active||y.detailVisibility==="always")?ne($d,{detail:y.detail,isDetailActive:l?o[M]?.active===!0:!1,isLabelActive:y.active,isTurnActive:r,label:y.label,markdownAnimation:s,markdownPlugins:i}):ne(vi,{active:y.active,label:y.label}),y.sources?.length?ne("span",{"aria-label":"Sources",className:"ha-activity-sources",children:y.sources.map(T=>ft("span",{className:"ha-activity-source",children:[ne(fi,{"aria-hidden":"true"}),T.label]},T.label))}):null]})]},y.id)),r?null:ft("li",{className:"ha-activity-item","data-complete":"true","data-state":"complete",children:[ne(gi,{active:!1}),ne("div",{className:"ha-activity-content",children:ne("span",{className:"ha-activity-step-label",children:"Final response ready"})})]})]})})})})]})}import{z as Xd}from"zod";import{z as _t}from"zod";var qd=["callMcpTool","composeUI","executeSandbox","getComponentSchema","renderComponent","searchKnowledge","searchMcpTools","searchWeb"],Gd="mcp_",Qd=20,zd=16*1024,Wd=_t.object({description:_t.string().trim().min(1).max(1e3),inputSchema:_t.record(_t.string(),_t.unknown()),name:_t.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).refine(e=>!qd.includes(e)&&!e.toLowerCase().startsWith(Gd),"Client tool name is reserved by the HeroUI Agent runtime"),needsApproval:_t.boolean().optional()}),bi=_t.array(Wd).max(Qd).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>zd&&t.addIssue({code:"custom",message:"Client tool manifest exceeds 16KB"})});import{z as Ye}from"zod";var Ci=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)}),jd=Ye.string().trim().max(2048).refine(e=>{try{return["http:","https:"].includes(new URL(e).protocol)}catch{return!1}}),Yd=Ye.union([Ci.extend({sourceType:Ye.literal("document"),title:Ye.string().trim().min(1).max(200)}),Ci.extend({sourceType:Ye.literal("url").optional(),title:Ye.string().trim().min(1).max(200).optional(),url:jd})]),Ai=Ye.object({items:Ye.array(Yd).min(1).max(16)});function Jd(e){return va(e.parameters)?Xd.toJSONSchema(e.parameters):e.parameters}function Ot(e){return bi.parse(e.map(t=>({description:t.description,inputSchema:Jd(t),name:t.name,...t.needsApproval?{needsApproval:!0}:{}})))}var Tn=class extends Error{constructor(){super("The assistant configuration changed and must be bootstrapped again"),this.name="AgentRuntimeRevisionStaleError"}},Yn=class extends Error{retryable;status;constructor(t){super("Could not refresh the assistant connection"),this.name="AgentRuntimeTicketError",this.status=t,this.retryable=t===408||t===429||t>=500}},Zd=15e3,ep=3e4;function Ri(e){return{clientTools:Ot(e.tools),imageSearch:e.imageSearch,...e.composerDefaultModel?{modelId:e.composerDefaultModel}:{},newsSearch:e.newsSearch,webSearch:e.webSearch}}function Mi(e){return JSON.stringify(Ri(e))}function Gr(e,t=!1){return{Authorization:`Bearer ${e}`,...t?{"Content-Type":"application/json"}:{},"X-HeroUI-Agent-Protocol-Version":String(6),"X-HeroUI-Agent-SDK-Version":We}}async function Xn(e,t,n={}){let r=async()=>{let s=new Headers(n.headers);return s.set("Authorization",`Bearer ${await e.get()}`),s.set("X-HeroUI-Agent-Protocol-Version",String(6)),s.set("X-HeroUI-Agent-SDK-Version",We),fetch(t,{...n,headers:s})},o=await r();return o.status===401&&(e.clear(),o=await r()),o}function Ti(e){if(typeof e!="string"||!e)return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}var tp=/^sha256:[0-9a-f]{64}$/u;function wi(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||!Ti(t.ticketExpiresAt)||!Ti(t.connectionExpiresAt)||typeof t.runtimeRevision!="string"||!tp.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 np(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,n=t.conversation,r=wi(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 rp(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return wi(t.runtime??t)}async function Ei(e,t,n){let r=new AbortController,o=globalThis.setTimeout(()=>r.abort(new Error("Assistant conversation bootstrap request timed out")),ep);try{let s=await Xn(t,`${e.apiBaseUrl}/v1/conversations/${encodeURIComponent(n)}/bootstrap`,{body:JSON.stringify(Ri(e)),headers:{"Content-Type":"application/json"},method:"POST",signal:r.signal});if(!s.ok)return null;let i=np(await s.json().catch(()=>null));return i?.conversation.id!==n||i?.conversation.agentId!==e.agentId?null:i}finally{globalThis.clearTimeout(o)}}async function Pi(e,t,n,r){let o=new AbortController,s=globalThis.setTimeout(()=>o.abort(new Error("Assistant connection ticket request timed out")),Zd);try{let i=await Xn(t,`${e.apiBaseUrl}/v1/conversations/${encodeURIComponent(n)}/runtime-ticket`,{body:JSON.stringify({runtimeRevision:String(r)}),headers:{"Content-Type":"application/json"},method:"POST",signal:o.signal}),d=await i.json().catch(()=>null);if(!i.ok){let c=typeof d?.code=="string"?d.code.toUpperCase():"";throw i.status===409||c.includes("STALE")&&c.includes("REVISION")?new Tn:new Yn(i.status)}let l=rp(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:Gr(await t.get(),!0),keepalive:!0,method:"POST"})}catch{}}function Rn(e,t=wo){let n=new Set(t),o=e.filter(s=>Eo(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=>!Eo(s.type)||!n.has(s.type.trim().toLowerCase()))?{error:op(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 xi({acceptedContentTypes:e=wo,apiBaseUrl:t,conversationId:n,files:r,tokenManager:o}){if(r.length===0)return[];let s=Rn(r,e);if(s.error||s.files.length!==r.length)throw new Error(s.error??"One or more attachments are not supported.");return Promise.all(r.map(i=>sp({apiBaseUrl:t,conversationId:n,file:i,tokenManager:o})))}function op(e){if(e.length===0)return"File attachments are disabled for this agent.";let t=e.map(o=>{let s=Aa[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 sp({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 ap(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 ap(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 ip=64*1024,lp=15e3,cp=5*6e4,up=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()]),dp=xe.object({output:xe.unknown(),status:xe.enum(["completed","failed","interrupted"])}).strict();async function ki({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 is(e){return Array.isArray(e)?`[${e.map(is).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${is(n)}`).join(",")}}`:JSON.stringify(e)??"undefined"}async function pp(e){return[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))].map(n=>n.toString(16).padStart(2,"0")).join("")}function mp(e){return{error:e instanceof Error?e.message.slice(0,1e3):"The tool could not be executed"}}function gp(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>ip?{output:{error:"The client tool result exceeded the 64 KiB limit"},status:"failed"}:{output:JSON.parse(n),status:"completed"}}function Ni({approvalApproved:e,decision:t,needsApproval:n,state:r}){return r==="approval-responded"?e===!0:r!=="input-available"?!1:!n||t==="approved"}async function fp(e){return pp(is(e))}function _i({context:e,execution:t,input:n,tool:r}){return r.execute(Ar(r,n),e,t)}async function Oi({conversationId:e,execute:t,input:n,maxWaitMs:r=cp,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 fp(n),protocolVersion:6,toolCallId:d,toolName:l},p=o(),C;for(;C=up.parse(await s.claim(m)),C.action==="wait";){if(o()-p+C.retryAfterMs>r)throw new Error("Timed out waiting for the existing client tool execution");await c(C.retryAfterMs)}if(C.action==="replay")return await i(C.output),"replayed";let u={conversationId:e,idempotencyKey:C.idempotencyKey,toolCallId:d},h,x;try{({output:h,status:x}=gp(await t(u)))}catch(A){x="failed",h=mp(A)}let w;for(;;)try{w=dp.parse(await s.complete({...m,claimId:C.claimId,output:h,status:x}));break}catch(A){if(o()-p+250>r)throw A;await c(250)}return await i(w.output),"executed"}var ls=lp;var hp=/^[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 Di(e){return e.map(({description:t,inputSchema:n,name:r})=>({description:t,name:r,parameters:n}))}function Li(e){return Object.fromEntries(Di(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 Hi(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 cs({clientSubmittedAt:e,clientTools:t,imageSearch:n,modelId:r,newsSearch:o,pageContext:s,permissionMode:i,turnId:d,webSearch:l}){if(!hp.test(d))throw new Error("HeroUI Agent turnId must be a UUID");if(!Number.isSafeInteger(e)||e<=0)throw new Error("HeroUI Agent clientSubmittedAt must be a positive timestamp");return{clientSubmittedAt:e,clientTools:Di(t),imageSearch:n,...r?{modelId:r}:{},newsSearch:o,pageContext:s,permissionMode:i,protocolVersion:6,requestId:d,sdkVersion:We,turnId:d,webSearch:l}}function Ui(e){return e.replace(/^\/+|\/+$/g,"")}function Bi(e){let t=new URL(e.baseUrl),n=Ui(t.pathname),r=Ui(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 Fi(e,t){let n=e;return{next:async()=>{if(n){let r=n;return n=null,r}return t()},refresh:t}}function Vi(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 $i(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 yp(e){return e==="composeUI"||e==="renderComponent"}function us(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 yp(o)}import{Xmark as Op}from"@gravity-ui/icons";import{File as vp,FileCode as Sp,FileLetterP as bp,FileLetterW as Cp,FileLetterX as Ap,FileText as Tp,FileZipper as Rp,MusicNote as Mp,Picture as wp,Video as Ep}from"@gravity-ui/icons";var Pp=new Set(["csv","ods","xls","xlsm","xlsx"]),Ip=new Set(["doc","docx","odt","rtf"]),xp=new Set(["css","go","html","java","js","json","jsx","mdx","php","py","rb","rs","scss","sh","sql","swift","ts","tsx","xml","yaml","yml"]),kp=new Set(["7z","bz2","gz","rar","tar","tgz","zip"]),Np=new Set(["log","md","text","txt"]);function _p(e){let t=e.trim().toLowerCase(),n=t.lastIndexOf(".");return n>0?t.slice(n+1):""}function Qr(e){let t=_p(e.name),n=e.type.toLowerCase();return Pp.has(t)||n.includes("csv")||n.includes("excel")||n.includes("spreadsheet")?{Icon:Ap,kind:"spreadsheet",label:"Spreadsheet"}:t==="pdf"||n==="application/pdf"?{Icon:bp,kind:"pdf",label:"PDF document"}:Ip.has(t)||n.includes("wordprocessingml")?{Icon:Cp,kind:"document",label:"Document"}:n.startsWith("image/")?{Icon:wp,kind:"image",label:"Image"}:n.startsWith("video/")?{Icon:Ep,kind:"video",label:"Video"}:n.startsWith("audio/")?{Icon:Mp,kind:"audio",label:"Audio"}:kp.has(t)||n.includes("zip")?{Icon:Rp,kind:"archive",label:"Archive"}:xp.has(t)?{Icon:Sp,kind:"code",label:"Code file"}:Np.has(t)||n.startsWith("text/")?{Icon:Tp,kind:"text",label:"Text document"}:{Icon:vp,kind:"file",label:"File"}}import{jsx as Mn,jsxs as Ki}from"react/jsx-runtime";function ds({file:e,onRemove:t}){let{Icon:n,kind:r,label:o}=Qr(e);return Ki("span",{className:"ha-attachment","data-kind":r,children:[Mn("span",{"aria-hidden":"true",className:"ha-attachment-icon",children:Mn(n,{})}),Ki("span",{className:"ha-attachment-copy",children:[Mn("span",{className:"ha-attachment-name",title:e.name,children:e.name}),Mn("span",{className:"ha-attachment-type",children:o})]}),Mn("button",{"aria-label":`Remove ${e.name}`,type:"button",onClick:t,children:Mn(Op,{"aria-hidden":"true"})})]})}import{Globe as Dp,Xmark as Lp}from"@gravity-ui/icons";import{jsx as ps,jsxs as qi}from"react/jsx-runtime";function Gi({onRemove:e,title:t}){return ps("div",{className:"ha-context",children:qi("button",{"aria-label":`Remove Ask about this: ${t}`,className:"ha-chip",type:"button",onClick:e,children:[ps(Dp,{"aria-hidden":"true",className:"ha-chip-leading"}),qi("span",{className:"ha-chip-title",title:t,children:["Ask about this: ",t]}),ps(Lp,{"aria-hidden":"true",className:"ha-chip-remove"})]})})}import{useCallback as zr,useState as Hp}from"react";import{jsx as Up}from"react/jsx-runtime";function ms(e){return e.dataTransfer?.types?.includes("Files")??!1}function Qi({children:e,className:t,"data-controls-revealed":n,"data-dictating":r,"data-expanded":o,disabled:s=!1,onFileIntent:i,onFilesSelected:d}){let[l,c]=Hp(!1),m=zr(h=>{ms(h)&&(i?.(),!s&&(h.preventDefault(),c(!0)))},[s,i]),p=zr(h=>{s||!ms(h)||(h.preventDefault(),h.dataTransfer.dropEffect="copy",c(!0))},[s]),C=zr(h=>{let x=h.relatedTarget;x&&h.currentTarget.contains(x)||c(!1)},[]),u=zr(h=>{ms(h)&&(i?.(),h.preventDefault(),c(!1),!(s||h.dataTransfer.files.length===0)&&d(Array.from(h.dataTransfer.files)))},[s,i,d]);return Up("div",{className:t,"data-controls-revealed":n,"data-dictating":r,"data-dragging":l||void 0,"data-expanded":o,onDragEnterCapture:m,onDragLeaveCapture:C,onDragOverCapture:p,onDropCapture:u,children:e})}var gs="Enter";var zi="Control+Shift+D";function Wi(e){return!e.defaultPrevented&&!e.isComposing&&!e.repeat&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&e.key==="Enter"}function ji(e){return!e.defaultPrevented&&!e.isComposing&&!e.repeat&&!e.altKey&&e.ctrlKey&&!e.metaKey&&e.shiftKey&&e.key.toLowerCase()==="d"}function Yi(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 fs(){return{activeTurnIds:new Set,busyIds:new Set,completedIds:new Set}}function Xi(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 hs(e,t){if(!e.completedIds.has(t))return e;let n=new Set(e.completedIds);return n.delete(t),{...e,completedIds:n}}function Ji(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 Zi(e,t,n=()=>crypto.randomUUID()){return e?.conversationEpoch===t?e:{conversationEpoch:t,conversationId:n()}}function Wr({conversationEpoch:e,optimisticTarget:t,requestedConversationId:n,storedConversationId:r}){return n===null&&t?.conversationEpoch===e&&Rt(t.conversationId)?t.conversationId:Bo(n,r)}function el({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 ys}from"react/jsx-runtime";function jr({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?ys(Oa,{composerConnecting:!0,agentId:e,composerControlsAvailable:t,composerControlsRevealed:n,composerEndSlot:r,composerFooterSlot:o,composerStartSlot:s,greeting:i,placeholder:c,suggestedPrompts:p,onComposerControlsReveal:l,onIntent:()=>{}}):ys("div",{className:"ha-loading",children:ys(tn,{className:"ha-progress ha-progress-shimmer",children:d})})}function Bp(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 tl({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=Bp(i.headers.get("Retry-After"),n());if(n()-s+d>t)return i;await o(d),i=await r()}return i}var Jn="Thinking\u2026";function nl({activeStreamKey:e,activeTurnMessageId:t}){return e!==null&&t===null}function rl({continuingAssistantMessageId:e,isActiveTurn:t,streamingAssistantMessageId:n,trackedActivityMessageId:r}){return t?n??r??e:null}function ol({hasActiveActivity:e,hasError:t,hasResponseStarted:n,isActiveTurn:r,messageCount:o,preferHomeWhileEmpty:s=!1,progress:i,runtimeStatus:d}){let l=o>0,c=!s&&!l&&(d==="pending"||d==="streaming"),m=!l&&!t&&!r&&!c;return e||n?{showHome:m,standaloneStatus:null}:r?{showHome:m,standaloneStatus:i??Jn}:c?{showHome:m,standaloneStatus:"Loading chat\u2026"}:{showHome:m,standaloneStatus:null}}import{jsx as Fp}from"react/jsx-runtime";function sl({activeConversationId:e,children:t,routes:n}){return Object.values(n).map(r=>{let o=r.conversationId===e;return Fp("div",{className:"ha-conversation-route","data-active":o||void 0,"data-conversation-route":r.conversationId,hidden:!o,children:t(r,o)},r.conversationId)})}function al({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 zp}from"@gravity-ui/icons";import{Button as Wp}from"@heroui/react";import{useLayoutEffect as jp,useRef as Yp}from"react";import{useCallback as Dt,useEffect as Vp,useLayoutEffect as $p,useRef as Ke,useState as Kp}from"react";var Lt=4,rn=1,il="--ha-active-turn-spacer-height",ll='[data-role="user"][data-stream-anchor="true"]',qp={hasOverflow:!1,isAtBottom:!0};function Zn(e){let t=e.scrollHeight-e.clientHeight>Lt,n=!t||e.scrollHeight-Math.max(0,e.scrollTop)-e.clientHeight<=Lt;return{hasOverflow:t,isAtBottom:n}}function Gp({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 Qp(e,t){return e.hasOverflow===t.hasOverflow&&e.isAtBottom===t.isAtBottom}function cl(e){return e==="smooth"&&!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"smooth":"auto"}function ul(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),C=Ke(!1),u=Ke(!1),[h,x]=Kp(qp),w=Dt(S=>{x(f=>Qp(f,S)?f:S)},[]),A=Dt(S=>{t.current=0,S.style.removeProperty(il)},[]),O=Dt(S=>{let f=c.current?S.querySelector(ll):null;if(!f)return t.current;let v=S.getBoundingClientRect(),y=f.getBoundingClientRect().top-v.top+S.scrollTop,M=S.scrollHeight-t.current,T=Number.parseFloat(window.getComputedStyle(S).paddingTop)||0,P=Gp({anchorTop:y,clientHeight:S.clientHeight,contentHeight:M,paddingTop:T});return Math.abs(P-t.current)>1&&(t.current=P,S.style.setProperty(il,`${P}px`)),t.current},[]),_=Dt((S="smooth")=>{let f=e.current;if(!f)return;c.current=null,m.current=null,i.current=!1,p.current=!1,C.current=!1,u.current=!1,A(f),n.current=!0,r.current=!1,l.current=f.scrollTop,w({hasOverflow:Zn(f).hasOverflow,isAtBottom:!0});let v=f.scrollHeight,R=Math.max(0,v-f.clientHeight);s.current=Math.abs(Math.max(0,f.scrollTop)-R)>rn,typeof f.scrollTo=="function"?f.scrollTo({behavior:cl(S),top:v}):f.scrollTop=v,l.current=Math.max(0,f.scrollTop)},[A,e,w]),k=Dt(S=>{if(!c.current)return null;let f=S.querySelector(ll);if(f){let v=Number.parseFloat(window.getComputedStyle(S).paddingTop)||0;m.current=Math.max(0,f.offsetTop-v)}return m.current},[]),L=Dt((S,f,v="auto")=>{let R=Math.max(0,S.scrollHeight-S.clientHeight),y=Math.min(f,R),M=cl(v),T=Math.abs(Math.max(0,S.scrollTop)-y)>rn;i.current=M==="smooth"&&T,s.current=T,!T&&t.current>Lt&&(p.current=!0),l.current=S.scrollTop,w({hasOverflow:R>Lt,isAtBottom:R-y<=Lt}),typeof S.scrollTo=="function"?S.scrollTo({behavior:M,top:f}):(S.scrollTop=f,i.current=!1),l.current=Math.max(0,S.scrollTop)},[w]),$=Dt(()=>{let S=e.current;if(!S)return;O(S);let f=Zn(S),v=Math.max(0,S.scrollTop),R=v<l.current-rn;if(l.current=v,R&&!f.isAtBottom){n.current=!1,r.current=!0,s.current=!1,i.current=!1,c.current=null,m.current=null,C.current=!1,w(f);return}!r.current&&(!f.hasOverflow||f.isAtBottom)&&(n.current=!0);let y=c.current!==null,M=k(S);if(y){if(r.current=!0,M!==null&&i.current){let T=Math.max(0,S.scrollHeight-S.clientHeight),P=Math.min(M,T);if(Math.abs(v-P)>rn){w({hasOverflow:f.hasOverflow,isAtBottom:!0});return}s.current=!1,i.current=!1,p.current=t.current>Lt}if(M!==null&&C.current){C.current=!1,L(S,M,"smooth");return}n.current=!1,w(f);return}if(n.current&&!r.current){_("auto");return}w(f)},[k,e,_,L,w,O]),X=Dt(S=>{let f=e.current;if(!f||o.current===S)return;let v=o.current!==null;if(o.current=S,S)p.current=!1,d.current!==S?(d.current=S,c.current=S,m.current=null,C.current=!0,u.current=!1,r.current=!0,n.current=!0):(c.current=null,m.current=null,C.current=!1);else if(v){c.current=null,m.current=null,s.current=!1,i.current=!1,p.current=t.current>Lt,C.current=!1,r.current=!0;let R=Zn(f);n.current=!1,w(R)}},[e,w]);return $p(()=>{let S=e.current;S&&(l.current=S.scrollTop,$(),r.current=!0,n.current=!1)},[$,e]),Vp(()=>{let S=e.current;if(!S)return;let f=()=>{let B=Math.max(0,S.scrollTop);s.current&&typeof S.scrollTo=="function"&&S.scrollTo({behavior:"auto",top:B}),u.current=!0,n.current=!1,r.current=!0,s.current=!1,i.current=!1,c.current=null,m.current=null,C.current=!1,l.current=B,w(Zn(S))},v=B=>{B.deltaY<0&&f()},R=null,y=B=>{R=B.touches[0]?.clientY??null},M=B=>{let K=B.touches[0]?.clientY??null;R!==null&&K!==null&&K>R&&f(),R=K},T=()=>{let B=Zn(S),K=Math.max(0,S.scrollTop),ye=K<l.current-rn,be=K>l.current+rn;if(l.current=K,u.current){B.isAtBottom&&be&&!p.current?(u.current=!1,n.current=!0,r.current=!1):(n.current=!1,r.current=!0),w(B);return}if(p.current){s.current=!1,i.current=!1,n.current=!1,r.current=!0,w(B);return}if(s.current&&!ye){let H=k(S),F=Math.max(0,S.scrollHeight-S.clientHeight),D=Math.min(H??F,F),N=B.isAtBottom||Math.abs(K-D)<=rn,Y=i.current;N&&(s.current=!1,i.current=!1,H!==null&&(p.current=t.current>Lt,r.current=!0,n.current=!1)),w(Y&&!N?{hasOverflow:B.hasOverflow,isAtBottom:!0}:H===null?r.current?B:{hasOverflow:B.hasOverflow,isAtBottom:n.current}:B);return}s.current=!1,i.current=!1,c.current=null,m.current=null,C.current=!1,n.current=B.isAtBottom,r.current=!B.isAtBottom,w(B)};S.addEventListener("scroll",T,{passive:!0}),S.addEventListener("touchmove",M,{passive:!0}),S.addEventListener("touchstart",y,{passive:!0}),S.addEventListener("wheel",v,{passive:!0});let P,z=new Set,ie=()=>{if(!P)return;let B=new Set(Array.from(S.children));for(let K of z)B.has(K)||(P.unobserve(K),z.delete(K));for(let K of B)z.has(K)||(P.observe(K),z.add(K))};typeof ResizeObserver<"u"&&(P=new ResizeObserver($),P.observe(S),ie());let j=typeof MutationObserver>"u"?void 0:new MutationObserver(B=>{B.some(K=>K.type==="childList"&&K.target===S)&&ie(),$()});return j?.observe(S,{characterData:!0,childList:!0,subtree:!0}),()=>{S.removeEventListener("scroll",T),S.removeEventListener("touchmove",M),S.removeEventListener("touchstart",y),S.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 Yr,jsxs as Xp}from"react/jsx-runtime";function dl({activityPhase:e=null,children:t,streamKey:n=null}){let r=Yp(null),{hasOverflow:o,isAtBottom:s,maintainScrollPosition:i,scrollToBottom:d,setPinnedStream:l}=ul(r),c=o&&!s;return nn(r),jp(()=>{l(n),i()},[t,i,l,n]),Xp("div",{className:"ha-conversation","data-activity-phase":e??void 0,children:[Yr("div",{ref:r,"aria-live":"polite",className:"ha-messages",role:"log",children:t}),Yr("div",{"aria-hidden":c?void 0:!0,className:"ha-scroll-button-container","data-state":c?"visible":"hidden",children:Yr(Wp,{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:Yr(zp,{"aria-hidden":"true"})})})]})}import{Suspense as Jp,lazy as Zp}from"react";var vs;function Ss(){return vs??=import("./component-renderer-GG6JVRUG.js").then(e=>({default:e.ComponentRenderer})),vs}function pl(){Ss().catch(()=>{vs=void 0})}import{jsx as ml}from"react/jsx-runtime";var em=Zp(Ss);function gl(e){return ml(Jp,{fallback:null,children:ml(em,{...e})})}import{ArrowsRotateLeft as tm,Check as nm,Copy as rm,ThumbsDown as om,ThumbsUp as sm}from"@gravity-ui/icons";import{Button as Xr,Popover as Jr,TextArea as am}from"@heroui/react";import{useCallback as im,useEffect as lm,useRef as fl,useState as er}from"react";import{Fragment as pm,jsx as Re,jsxs as tr}from"react/jsx-runtime";var cm=2e3,um=1e3,dm=[{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 hl({actions:e,feedback:t,onCopy:n,onFeedback:r,onRetry:o}){let[s,i]=er(!1),[d,l]=er(!1),[c,m]=er(""),[p,C]=er([]),[u,h]=er(),x=fl(null),w=fl(0),A=im(f=>{h(f?.closest(".ha-panel")??void 0)},[]);lm(()=>()=>{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},cm)},$=f=>{!f&&Date.now()-w.current<350||l(f)},X=f=>{C(v=>v.includes(f)?v.filter(R=>R!==f):[...v,f])},S=()=>{let f=c.trim();r?.("down",{...f?{comment:f}:{},reasons:p}),l(!1)};return tr("div",{"aria-label":"Message actions",className:"ha-message-actions",role:"group",children:[O?Re("button",{"aria-label":s?"Copied":"Copy response",className:"ha-message-action","data-copied":s||void 0,type:"button",onClick:L,children:Re("span",{className:"ha-message-action-icon",children:s?Re(nm,{"aria-hidden":"true"}):Re(rm,{"aria-hidden":"true"})},s?"check":"copy")}):null,_?tr(pm,{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(sm,{"aria-hidden":"true"})}),tr(Jr,{isOpen:d,onOpenChange:$,children:[Re(Xr,{ref:A,isIconOnly:!0,"aria-label":"Bad response","aria-pressed":t==="down",className:"ha-message-action ha-feedback-trigger","data-open":d||void 0,"data-selected":t==="down"||void 0,size:"sm",variant:"ghost",onPointerDown:()=>{w.current=Date.now()},children:Re(om,{"aria-hidden":"true"})}),Re(Jr.Content,{className:"ha-feedback-popover",offset:8,placement:"top start",UNSTABLE_portalContainer:u,children:tr(Jr.Dialog,{className:"ha-feedback-dialog",children:[Re(Jr.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:dm.map(f=>{let v=p.includes(f.value);return Re(Xr,{"aria-pressed":v,className:"ha-feedback-reason",size:"sm",variant:v?"secondary":"outline",onPress:()=>X(f.value),children:f.label},f.value)})}),Re(am,{fullWidth:!0,"aria-label":"Additional feedback",className:"ha-feedback-textarea",maxLength:um,placeholder:"Add details (optional)",rows:3,value:c,variant:"secondary",onChange:f=>m(f.target.value)}),Re("p",{className:"ha-feedback-privacy",children:"Avoid sharing sensitive information."}),tr("div",{className:"ha-feedback-footer",children:[Re(Xr,{className:"ha-feedback-cancel",size:"sm",variant:"ghost",onPress:()=>l(!1),children:"Cancel"}),Re(Xr,{className:"ha-feedback-submit",size:"sm",variant:"primary",onPress:S,children:t==="down"?"Update":"Send"})]})]})})]})]}):null,k?Re("button",{"aria-label":"Retry response",className:"ha-message-action",type:"button",onClick:o,children:Re(tm,{"aria-hidden":"true"})}):null]})}import{jsx as wn,jsxs as yl}from"react/jsx-runtime";function bs({file:e}){let t=e.filename?.trim()||"Attachment",n=e.mediaType?.trim()||"",{Icon:r,kind:o,label:s}=Qr({name:t,type:n});return o==="image"?wn("a",{"aria-label":`Open ${t}`,className:"ha-message-image",download:e.filename,href:e.url,rel:"noopener noreferrer",target:"_blank",title:t,children:wn("span",{"aria-hidden":"true",style:{backgroundImage:`url(${JSON.stringify(e.url)})`}})}):yl("a",{className:"ha-message-file","data-kind":o,download:e.filename,href:e.url,rel:"noopener noreferrer",target:"_blank",children:[wn("span",{"aria-hidden":"true",className:"ha-message-file-icon",children:wn(r,{})}),yl("span",{className:"ha-message-file-copy",children:[wn("span",{className:"ha-message-file-name",title:t,children:t}),wn("span",{className:"ha-message-file-type",children:s})]})]})}function on(){return{blockedMessageId:null,isPaused:!1,messages:[]}}function Cs(e,t,n="append"){return e.messages.some(r=>r.id===t.id)?e:{...e,messages:n==="prepend"?[t,...e.messages]:[...e.messages,t]}}function nr(e,t){return e.messages.findIndex(r=>r.id===t)===-1?e:{...e,blockedMessageId:e.blockedMessageId===t?null:e.blockedMessageId,messages:e.messages.filter(r=>r.id!==t)}}function vl(e,t,n,r){let o=e.messages.findIndex(m=>m.id===t),s=e.messages.findIndex(m=>m.id===n);if(o===-1||s===-1||o===s)return e;let i=[...e.messages],[d]=i.splice(o,1),c=i.findIndex(m=>m.id===n)+(r==="after"?1:0);return i.splice(c,0,d),i.every((m,p)=>m.id===e.messages[p]?.id)?e:{...e,messages:i}}function rr(e,t){return e.isPaused===t?e:{...e,isPaused:t}}function ht(e,t){return e.blockedMessageId===t?e:{...e,blockedMessageId:t}}function Sl(e){let t=e.text.trim();return t||`${e.files.length} attachment${e.files.length===1?"":"s"}`}function yt(e){return e.deliveryStatus??"pending"}function En(e,t,n){let r=e.messages.findIndex(s=>s.id===t);if(r===-1||yt(e.messages[r])===n)return e;let o=[...e.messages];return o[r]={...o[r],deliveryStatus:n},{...e,messages:o}}var mm="heroui-agent-message-outbox",gm=1,Ht="conversation-outboxes",fm=":message-outbox:",sn=new Map;function As(e,t){return`${e}${fm}${t}:v1`}async function bl(e){await sn.get(e)?.catch(()=>{});let t=await Rs();if(!t)return on();try{let n=t.transaction(Ht,"readonly"),r=await Am(n.objectStore(Ht).get(e));return await Ms(n),hm(r,e)}catch{return on()}finally{t.close()}}function Ts(e,t,n=Date.now()){return Rl(e,async()=>{let r=t.messages.length>0?await ym(t):null,o=await Rs();if(!o)throw new Error("Durable message storage is unavailable");try{let s=o.transaction(Ht,"readwrite"),i=s.objectStore(Ht);t.messages.length===0?i.delete(e):i.put({key:e,savedAt:n,state:r}),await Ms(s)}finally{o.close()}})}function Cl(e){return Rl(e,async()=>{let t=await Rs();if(t)try{let n=t.transaction(Ht,"readwrite");n.objectStore(Ht).delete(e),await Ms(n)}finally{t.close()}})}function Al(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 Tl(e,t){let n=e.messages.filter(o=>!t.has(o.id)).map(o=>yt(o)==="sending"?{...o,deliveryStatus:"pending"}:o),r=new Set(n.map(o=>o.id));return{...e,blockedMessageId:e.blockedMessageId&&r.has(e.blockedMessageId)?e.blockedMessageId:null,messages:n}}function hm(e,t){if(!e||typeof e!="object")return on();let n=e,r=n.state;if(n.key!==t||typeof n.savedAt!="number"||!r||typeof r!="object"||typeof r.isPaused!="boolean"||!Array.isArray(r.messages))return on();let o=r.messages.map(Sm).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 ym(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(vm))})))}}async function vm(e){return{bytes:await e.arrayBuffer(),lastModified:e.lastModified,name:e.name,type:e.type}}function Sm(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.id=="string"&&t.id.length>0&&typeof t.text=="string"&&Array.isArray(t.files)&&(t.isInitialTurn===void 0||typeof t.isInitialTurn=="boolean")&&(t.deliveryStatus===void 0||t.deliveryStatus==="pending"||t.deliveryStatus==="sending"||t.deliveryStatus==="admitted")){let n=t.files.map(bm).filter(r=>r!==null);return n.length!==t.files.length?null:{...t,files:n}}return null}function bm(e){if(typeof File<"u"&&e instanceof File)return e;if(typeof File>"u"||!e||typeof e!="object")return null;let t=e;return!Cm(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 Cm(e){return Object.prototype.toString.call(e)==="[object ArrayBuffer]"}function Rl(e,t){let r=(sn.get(e)??Promise.resolve()).catch(()=>{}).then(t);return sn.set(e,r),r.then(()=>{sn.get(e)===r&&sn.delete(e)},()=>{sn.get(e)===r&&sn.delete(e)}),r}function Rs(){return typeof indexedDB>"u"?Promise.resolve(null):new Promise((e,t)=>{let n=indexedDB.open(mm,gm);n.onerror=()=>t(n.error??new Error("Unable to open message outbox")),n.onupgradeneeded=()=>{let r=n.result;r.objectStoreNames.contains(Ht)||r.createObjectStore(Ht,{keyPath:"key"})},n.onsuccess=()=>e(n.result)})}function Am(e){return new Promise((t,n)=>{e.onerror=()=>n(e.error??new Error("IndexedDB request failed")),e.onsuccess=()=>t(e.result)})}function Ms(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 Ml({hasChatError:e,hasPendingClientToolCalls:t,hasReadyClientToolContinuation:n,isLocalPending:r,isResuming:o,isRunning:s,recoveryError:i}){return o||s||t||r||n&&!i&&!e}function wl(e,t){return e.text?{files:t,text:e.text}:{files:t}}function El(e){let t=e.text.trim();return t||`${e.files.length} attachment${e.files.length===1?"":"s"}`}function Pl({activeMessageId:e,authoritativeMessageCount:t,isNewChatStartScreen:n,queuedMessageCount:r}){return n&&t===0&&r===0&&e===null}function Il({authoritativeMessageCount:e,localTurn:t,queue:n}){return e>0?null:t??n.messages.find(o=>o.isInitialTurn&&yt(o)!=="admitted")??null}function xl(e,t){return e.messages.filter(n=>yt(n)==="pending"&&(n.id!==t||e.isPaused||e.blockedMessageId===t))}function kl({isClientTool:e,state:t}){return e&&(t==="input-streaming"||t==="input-available"||t==="approval-requested"||t==="approval-responded")}function Nl({activeMessageId:e,isBusy:t,isReordering:n=!1,queue:r}){return e||t||n||r.isPaused||r.blockedMessageId||r.messages.length===0||r.messages.some(o=>yt(o)==="sending")?null:r.messages.find(o=>yt(o)==="pending")??null}function _l(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 Tm,CircleExclamation as Rm,Clock as Mm,Grip as wm,Pencil as Em,TrashBin as Pm}from"@gravity-ui/icons";import{useImperativeHandle as Im,useLayoutEffect as xm,useRef as ws}from"react";import{useRef as Zr,useState as eo}from"react";function Ol({messages:e,onReorder:t,onReorderStateChange:n}){let r=Zr(null),o=Zr(null),s=Zr(null),i=Zr(null),[d,l]=eo(""),[c,m]=eo(null),[p,C]=eo(null),[u,h]=eo(null),x=v=>{o.current=v,C(v)},w=()=>{let v=r.current!==null;r.current=null,m(null),x(null),v&&n?.(s.current!==null)},A=(v,R,y)=>{let M=e.findIndex(P=>P.id===v)+1,T=e.findIndex(P=>P.id===R)+1;l(`Moved queued message ${M} ${y} queued message ${T}.`)},O=(v,R,y)=>{let M=e.findIndex(z=>z.id===v),T=e.findIndex(z=>z.id===R),P=y==="before"&&M===T-1||y==="after"&&M===T+1;M===-1||T===-1||M===T||P||(t(v,R,y),A(v,R,y))},_=(v,R)=>{e.length<2||v.pointerType==="mouse"&&v.button!==0||(v.currentTarget.setPointerCapture?.(v.pointerId),r.current={hasMoved:!1,messageId:R,pointerId:v.pointerId,startX:v.clientX,startY:v.clientY},s.current=null,h(null),m(R),x(null),n?.(!0))},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 B=y.getBoundingClientRect(),K=28;v.clientY<B.top+K?M=-12:v.clientY>B.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 B=z.getBoundingClientRect(),K=v.clientY<B.top+B.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)},S=v=>{s.current===v&&(s.current=null,h(null),n?.(r.current!==null))};return{announcement:d,closePositionPicker:S,draggedMessageId:c,dropTarget:p,finishPointerDrag:L,handleReorderKeyDown:$,moveMessageToPosition:(v,R,y)=>{let M=e[y];if(!M||R===y){S(v);return}O(v,M.id,R<y?"after":"before"),S(v)},positionPickerMessageId:u,startPointerDrag:_,togglePositionPicker:X,updatePointerDrag:k}}import{jsx as Ie,jsxs as or}from"react/jsx-runtime";function to(e,t){let n=e?.querySelectorAll("[data-queue-message-id]")[t];return n?(n.focus({preventScroll:!0}),n.scrollIntoView?.({block:"nearest"}),!0):!1}function Dl({blockedMessageId:e,isSendNowDisabled:t,messages:n,onEdit:r,onFocusComposer:o,onRemove:s,onReorder:i,onReorderStateChange:d,onSendNow:l,ref:c}){let m=ws(null),p=ws(null),C=ws(n),{announcement:u,closePositionPicker:h,draggedMessageId:x,dropTarget:w,finishPointerDrag:A,handleReorderKeyDown:O,moveMessageToPosition:_,positionPickerMessageId:k,startPointerDrag:L,togglePositionPicker:$,updatePointerDrag:X}=Ol({messages:n,onReorder:i,onReorderStateChange:d});if(Im(c,()=>({focusLastMessage:()=>to(p.current,n.length-1)}),[n.length]),xm(()=>{let f=C.current;C.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||!to(p.current,y))&&o()},[n,o]),n.length===0)return null;let S=(f,v)=>{if(f.target===f.currentTarget&&!(f.key!=="ArrowUp"&&f.key!=="ArrowDown")){if(f.preventDefault(),f.key==="ArrowUp"){to(p.current,v-1);return}to(p.current,v+1)||o()}};return or("section",{"aria-label":"Queued messages",className:"ha-message-queue",children:[Ie("div",{className:"ha-message-queue-header",children:"Queued"}),Ie("ol",{ref:p,className:"ha-message-queue-list",children:n.map((f,v)=>{let R=e===f.id,y=v+1,M=R?`ha-queued-message-status-${f.id}`:void 0;return or("li",{"aria-describedby":M,"aria-keyshortcuts":"ArrowUp ArrowDown",className:"ha-message-queue-item","data-blocked":R?"true":void 0,"data-dragging":x===f.id?"true":void 0,"data-queue-message-id":f.id,tabIndex:-1,title:R?"This message could not be sent":void 0,"data-drop-position":w?.messageId===f.id?w.position:void 0,onKeyDown:T=>S(T,v),onBlur:T=>{let P=T.relatedTarget;m.current===f.id&&(!P||!T.currentTarget.contains(P))&&(m.current=null)},onFocus:()=>{m.current=f.id},children:[Ie("button",{"aria-keyshortcuts":"ArrowUp ArrowDown","aria-label":`Reorder queued message ${y}`,className:"ha-message-queue-drag-handle",disabled:n.length<2,title:n.length>1?"Drag to reorder or click for options":void 0,type:"button",onClick:()=>$(f.id),onKeyDown:T=>O(T,f.id,v),onPointerCancel:T=>A(T,!1),onPointerDown:T=>L(T,f.id),onPointerMove:X,onPointerUp:T=>A(T,!0),children:Ie(wm,{"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)=>or("option",{value:P,children:["Position ",P+1,P===v?" (current)":""]},T.id))}):Ie("span",{"aria-hidden":"true",className:"ha-message-queue-icon",children:R?Ie(Rm,{"aria-hidden":"true"}):Ie(Mm,{"aria-hidden":"true"})}),or("span",{className:"ha-message-queue-content",children:[Ie("span",{className:"ha-message-queue-preview",children:Sl(f)}),R?Ie("span",{className:"ha-message-queue-status",id:M,role:"status",children:"Could not send"}):null]}),or("span",{className:"ha-message-queue-actions",children:[Ie("button",{"aria-label":`Send queued message ${y} now`,className:"ha-message-queue-action",disabled:t,title:"Send now",type:"button",onClick:()=>l(f.id),children:Ie(Tm,{"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(Em,{"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(Pm,{"aria-hidden":"true"})})]})]},f.id)})}),Ie("span",{"aria-live":"polite",className:"ha-message-queue-announcement",role:"status",children:u})]})}import{FileText as Hm}from"@gravity-ui/icons";import ql,{createContext as Um,useContext as Bm,useMemo as Fm}from"react";import{composeRenderProps as Vm}from"react-aria-components";import{mergeRefs as km}from"@react-aria/utils";import{useControlledState as Nm}from"@react-stately/utils";import{createContext as _m,useCallback as Xe,useContext as Hl,useEffect as Ll,useMemo as Ul,useRef as no,useState as Om}from"react";import{OverlayArrow as Dm,Popover as Lm,composeRenderProps as Bl}from"react-aria-components";import{jsx as Pn}from"react/jsx-runtime";var Es=_m({handleCancelClose:()=>{},handleClose:()=>{},handleOpen:()=>{},isOpen:!1,isPointerInsideRef:{current:!1},setPortalContainer:()=>{},triggerRef:{current:null}}),Ps=({children:e,closeDelay:t=300,defaultOpen:n=!1,onOpenChange:r,open:o,openDelay:s=700})=>{let[i,d]=Nm(o,n,r),[l,c]=Om(),m=no(null),p=no(!1),C=no(void 0),u=no(void 0),h=Xe(()=>{clearTimeout(C.current),clearTimeout(u.current)},[]);Ll(()=>h,[h]),Ll(()=>{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):C.current=setTimeout(()=>d(!0),s)},[h,s,d]),w=Xe((_=!1)=>{h(),_||t<=0?d(!1):u.current=setTimeout(()=>d(!1),t)},[h,t,d]),A=Xe(()=>{clearTimeout(u.current)},[]),O=Ul(()=>({handleCancelClose:A,handleClose:w,handleOpen:x,isOpen:i,isPointerInsideRef:p,portalContainer:l,setPortalContainer:c,triggerRef:m}),[A,w,x,i,l]);return Pn(Es,{value:O,children:e})},Fl=({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:C}=Hl(Es),u=Xe(_=>{C.current=_,p(Sn(_))},[p,C]),h=Ul(()=>km(i,u),[i,u]),x=Xe(_=>{_.pointerType==="mouse"&&c(),o?.(_)},[c,o]),w=Xe(_=>{_.pointerType==="mouse"&&l(),s?.(_)},[l,s]),A=Xe(_=>{c(!0),r?.(_)},[c,r]),O=Xe(_=>{m.current||l(),n?.(_)},[l,m,n]);return Pn("span",{ref:h,className:me("aui-hover-card__trigger",t),"data-slot":"hover-card-trigger",onBlur:O,onFocus:A,onPointerEnter:x,onPointerLeave:w,...d,children:e})},Vl=({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:C,portalContainer:u,triggerRef:h}=Hl(Es),x=Xe(O=>{C.current=!0,c(),s?.(O)},[c,C,s]),w=Xe(O=>{C.current=!1,m(),i?.(O)},[m,C,i]),A=Xe(O=>{O||m(!0),o?.(O)},[m,o]);return Pn(Lm,{isNonModal:!0,"data-slot":"hover-card-content",isOpen:p,offset:r,placement:d,triggerRef:h,UNSTABLE_portalContainer:e??u,className:Bl(n,O=>me("aui-hover-card__content",O)??""),onOpenChange:A,onPointerEnter:x,onPointerLeave:w,...l,children:O=>typeof t=="function"?t(O):t})},$l=({children:e,className:t,...n})=>Pn(Dm,{"data-slot":"hover-card-arrow",className:Bl(t,r=>me("aui-hover-card__arrow",r)??""),...n,children:e??Pn("svg",{fill:"none",height:"12",viewBox:"0 0 12 12",width:"12",xmlns:"http://www.w3.org/2000/svg",children:Pn("path",{d:"M0 0C5.48483 8 6.5 8 12 0Z"})})});var sr=Object.assign(Ps,{Arrow:$l,Content:Vl,Root:Ps,Trigger:Fl});function Kl(e){try{return new URL(e).hostname.replace(/^www\./,"")}catch{return e.split("/").pop()||e}}import{Fragment as Is,jsx as ae,jsxs as Ut}from"react/jsx-runtime";var Gl=Um({sourceType:"url"}),ar=()=>Bm(Gl);function $m(e){return e.trim().charAt(0).toUpperCase()||"?"}var xs=({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?Kl(s):void 0,C=r??(d==="url"&&!!s?!!(n||l):!!(n||i)),u=Fm(()=>({description:n,domain:m,enablePreview:C,faviconUrl:o,href:s,locator:i,sourceType:d,title:l}),[n,m,C,o,s,i,d,l]),h=e??Ut(Is,{children:[ae(ks,{}),C?ae(Ns,{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(Gl,{value:u,children:C?ae(sr,{closeDelay:0,openDelay:150,children:x}):x})},ks=({children:e,className:t,label:n,...r})=>{let{domain:o,enablePreview:s,href:i,locator:d,sourceType:l,title:c}=ar(),m=l==="url"&&i,p=e??n??(m?Ut(Is,{children:[ae(so,{}),ae(oo,{children:c??o}),d?ae(ro,{children:d}):null]}):Ut(Is,{children:[ae(ao,{}),ae(oo,{children:c}),d?ae(ro,{children:d}):null]}));if(m){let h=ae("a",{"aria-label":`Open source: ${c??o??i}`,className:"aui-chat-source__trigger-link",href:i,rel:"noopener noreferrer",target:"_blank",...r,children:p});return ae("span",{className:me("aui-chat-source__trigger",t),"data-slot":"chat-source-trigger",children:s?ae(sr.Trigger,{children:h}):h})}let C=[c,d].filter(Boolean).join(", ")||"Document",u=ae("span",{className:s?void 0:"aui-chat-source__trigger-link",...s?{}:r,children:p});return ae("span",{className:me("aui-chat-source__trigger",t),"data-slot":"chat-source-trigger",children:s?ae(sr.Trigger,{children:ae("button",{"aria-label":`Source: ${C}`,className:"aui-chat-source__trigger-link",type:"button",...r,children:p})}):u})},ro=({children:e,className:t,...n})=>{let{locator:r}=ar();return e??r?ae("span",{className:me("aui-chat-source__locator",t),"data-slot":"chat-source-locator",...n,children:e??r}):null},so=({children:e,className:t,faviconUrl:n})=>{let{domain:r,faviconUrl:o,href:s,title:i}=ar(),d=i??r??s??"Source",l=n??o;if(e&&ql.isValidElement(e)){let c=e;return ql.cloneElement(c,{className:me("aui-chat-source__icon",t,c.props.className),"data-slot":"chat-source-icon"})}return Ut("span",{"aria-hidden":"true",className:me("aui-chat-source__icon",t),"data-slot":"chat-source-icon",children:[ae("span",{className:"aui-chat-source__icon-fallback",children:$m(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]})},ao=({className:e})=>ae(Hm,{className:me("aui-chat-source__document-icon",e),"data-slot":"chat-source-document-icon"}),oo=({children:e,className:t,...n})=>{let{domain:r,title:o}=ar();return ae("span",{className:me("aui-chat-source__title",t),"data-slot":"chat-source-title",...n,children:e??o??r})},Ns=({children:e,className:t,description:n,title:r,...o})=>{let{description:s,domain:i,enablePreview:d,href:l,locator:c,sourceType:m,title:p}=ar();if(!d)return null;let C=r??p,u=n??s,h=m==="url"&&l?Ut("a",{className:"aui-chat-source__preview-link",href:l,rel:"noopener noreferrer",target:"_blank",children:[Ut("div",{className:"aui-chat-source__preview-header",children:[ae(so,{}),ae("span",{className:"aui-chat-source__preview-domain",children:i})]}),C?ae("div",{className:"aui-chat-source__preview-title",children:C}):null,u?ae("div",{className:"aui-chat-source__preview-description",children:u}):null]}):Ut("div",{className:"aui-chat-source__preview-link","data-source-type":"document",children:[Ut("div",{className:"aui-chat-source__preview-header",children:[ae(ao,{}),ae("span",{className:"aui-chat-source__preview-domain",children:C??"Document"})]}),c?ae("div",{className:"aui-chat-source__preview-title",children:c}):null,u?ae("div",{className:"aui-chat-source__preview-description",children:u}):null]});return ae(sr.Content,{"data-slot":"chat-source-preview",offset:8,placement:"top",className:Vm(t,x=>me("aui-chat-source__preview",x)??""),...o,children:e??h})};import{Disclosure as In}from"@heroui/react";import{composeRenderProps as _s}from"react-aria-components";import{jsx as Bt,jsxs as Km}from"react/jsx-runtime";var Os=({children:e,className:t,...n})=>Bt(In,{"data-slot":"chat-sources",className:_s(t,r=>me("aui-chat-sources",r)??""),...n,children:e}),Ql=({children:e,className:t,...n})=>Bt(In.Heading,{children:Km(In.Trigger,{"data-slot":"chat-sources-trigger",className:_s(t,r=>me("aui-chat-sources__trigger",r)??""),...n,children:[Bt("span",{className:"aui-chat-sources__trigger-label",children:e}),Bt(In.Indicator,{className:"aui-chat-sources__indicator"})]})}),zl=({children:e,className:t,...n})=>Bt(In.Content,{"data-slot":"chat-sources-content",className:_s(t,r=>me("aui-chat-sources__content",r)??""),...n,children:Bt(In.Body,{children:Bt("div",{className:"aui-chat-sources__content-body",children:e})})}),Wl=({children:e,className:t,role:n="list",...r})=>Bt("div",{className:me("aui-chat-sources__list",t),"data-slot":"chat-sources-list",role:n,...r,children:e});var jl=Object.assign(xs,{DocumentIcon:ao,Icon:so,Locator:ro,Preview:Ns,Root:xs,Title:oo,Trigger:ks}),ir=Object.assign(Os,{Content:zl,List:Wl,Root:Os,Trigger:Ql});import{jsx as Mt,jsxs as Yl}from"react/jsx-runtime";function qm(e){return`https://www.google.com/s2/favicons?domain_url=${encodeURIComponent(e)}&sz=64`}function Xl({inList:e=!1,source:t}){let n="url"in t?t.url:void 0;return Mt(jl,{description:t.excerpt,faviconUrl:n?qm(n):void 0,href:n,locator:t.locator,role:e?"listitem":void 0,sourceType:t.sourceType??"url",title:t.title})}function Gm({sources:e}){return Mt(ir.List,{"aria-label":"Sources",children:e.map(t=>Mt(Xl,{inList:!0,source:t},t.sourceId))})}function Jl({sources:e}){return e.length===0?null:e.length===1?Mt("div",{"aria-label":"Sources",className:"ha-message-sources","data-count":"1",role:"group",children:Mt(Xl,{source:e[0]})}):Yl(ir,{className:"ha-message-sources","data-count":e.length,children:[Yl(ir.Trigger,{"aria-label":`${e.length} sources`,children:[Mt("span",{className:"ha-sources-label",children:"Sources"}),Mt("span",{"aria-hidden":"true",className:"ha-sources-count",children:e.length})]}),Mt(ir.Content,{children:Mt(Gm,{sources:e})})]})}function Qm(e){try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:(t.hash="",t.toString())}catch{return null}}function Zl(e){let t=new Map;for(let n of e){if(n.type!=="data-sources")continue;let r=Ai.safeParse(n.data);if(r.success)for(let o of r.data.items){if("url"in o){let i=Qm(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 ec(e,{hasContent:t,isStreaming:n}){return n||!t?[]:e}import{Plus as zm}from"@gravity-ui/icons";import{Button as Wm}from"@heroui/react";import{jsx as tc}from"react/jsx-runtime";function nc({isDisabled:e=!1,onPress:t}){return tc(Wm,{isIconOnly:!0,"aria-label":"New chat",className:"ha-icon-button ha-new-chat-button",isDisabled:e,size:"sm",variant:"ghost",onPress:t,children:tc(zm,{"aria-hidden":"true"})})}function rc(e){return`heroui-agent:project-config:${e}`}function oc(e){try{let t=window.localStorage.getItem(rc(e));if(!t)return null;let n=Ur.safeParse(JSON.parse(t));return n.success?n.data:null}catch{return null}}function sc(e,t){try{window.localStorage.setItem(rc(e),JSON.stringify(t))}catch{}}var jm=["runtimeAdmittedAt","providerRequestedAt","providerFirstEventAt","firstSemanticTextAt","completedAt"];function ac(e,t,n){if(!n||typeof n!="object"||Array.isArray(n)||typeof window>"u")return!1;let r=n,o={};for(let i of jm){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(Ha,{detail:s})),!0}import{ChevronDown as Ym,Ellipsis as Xm,Pencil as Jm,Plus as Zm,TrashBin as eg}from"@gravity-ui/icons";import{Button as an,Dropdown as lr,Input as tg,Label as ic,Modal as ot,Popover as Ds,TextField as ng}from"@heroui/react";import{useCallback as rg,useRef as Ls,useState as Ft}from"react";import{Fragment as pc,jsx as Z,jsxs as Ce}from"react/jsx-runtime";var lc="rename",cc="delete",og=80,uc=new Set;function Hs({activeConversationId:e,busyConversationIds:t=uc,completedConversationIds:n=uc,groups:r,isNewConversationDisabled:o=!1,onDeleteConversation:s,onNewConversation:i,onRenameConversation:d,onSelectConversation:l,variant:c="popover"}){let[m,p]=Ft(!1),[C,u]=Ft(!1),[h,x]=Ft(null),[w,A]=Ft(null),[O,_]=Ft(""),[k,L]=Ft(null),[$,X]=Ft(!1),[S,f]=Ft(),v=Ls(0),R=Ls(0),y=Ls(null);nn(y);let T=r.flatMap(D=>D.items).find(D=>D.id===e)?.title??"New chat",P=rg(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)},B=(D,N)=>{z(),A({item:D,type:N}),_(D.title),L(null),u(!0)},K=()=>{$||(L(null),u(!1))},ye=(D,N)=>{N===lc&&B(D,"rename"),N===cc&&!t.has(D.id)&&B(D,"delete")},be=async()=>{if(!w||w.type!=="rename"||$)return;let D=O.trim();if(!D){L("Enter a name for this chat.");return}if(D===w.item.title){u(!1);return}X(!0),L(null);try{await d(w.item.id,D),A({...w,item:{...w.item,title:D}}),u(!1)}catch(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)}}},F=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(tn,{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(lr,{isOpen:h===N.id,onOpenChange:Me=>j(N.id,Me),children:[Z(an,{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(Xm,{"aria-hidden":"true"})}),Z(lr.Popover,{className:"ha-session-actions-menu",placement:"bottom end",UNSTABLE_portalContainer:S,children:Ce(lr.Menu,{"aria-label":`Actions for ${N.title}`,onAction:Me=>ye(N,Me),children:[Ce(lr.Item,{id:lc,textValue:"Rename",children:[Z(Jm,{"aria-hidden":"true"}),Z(ic,{children:"Rename"})]}),Ce(lr.Item,{id:cc,isDisabled:re,textValue:re?"Delete unavailable while responding":"Delete",variant:"danger",children:[Z(eg,{"aria-hidden":"true",className:"ha-session-delete-icon"}),Z(ic,{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(pc,{children:[Ce("div",{className:"ha-session-sidebar-header",children:[Z("h2",{children:"Chats"}),Ce(an,{fullWidth:!0,className:"ha-session-new-chat",isDisabled:o,size:"sm",variant:"tertiary",onPress:()=>{z(),i?.()},children:[Z(Zm,{"aria-hidden":"true"}),"New chat"]})]}),Z("nav",{ref:y,"aria-label":"Recent chats",className:"ha-session-sidebar-history",children:F})]}):Ce(Ds,{isOpen:m,onOpenChange:ie,children:[Ce(an,{"aria-label":"Choose a chat",className:"ha-session-trigger",size:"sm",variant:"ghost",onPointerDown:()=>{v.current=Date.now()},children:[Z("span",{className:"font-medium",children:T}),Z(Ym,{"aria-hidden":"true"})]}),Z(Ds.Content,{isNonModal:!0,className:"ha-session-menu",placement:"bottom start",UNSTABLE_portalContainer:S,children:Z(Ds.Dialog,{"aria-label":"Chat history",className:"ha-session-history-dialog",children:F})})]}),Z(ot.Backdrop,{className:"ha-session-modal-backdrop",isDismissable:!$,isKeyboardDismissDisabled:$,isOpen:C,UNSTABLE_portalContainer:S,onOpenChange:D=>{D||K()},children:Z(ot.Container,{placement:"center",size:"sm",children:Z(ot.Dialog,{className:"ha-session-modal",children:Z(sg,{dialog:w,isPending:$,mutationError:k,renameTitle:O,onClose:K,onDelete:H,onRename:be,onRenameTitleChange:_})})})}),Z("div",{ref:P,className:"ha-session-portal","data-open":m||C||h?"true":void 0,onPointerDown:D=>{D.target?.closest(".ha-session-menu, .ha-session-actions-menu, .ha-session-modal-backdrop")||(m||h)&&z()}})]})}function sg({dialog:e,isPending:t,mutationError:n,onClose:r,onDelete:o,onRename:s,onRenameTitleChange:i,renameTitle:d}){return e?.type==="rename"?Ce("form",{onSubmit:l=>{l.preventDefault(),s()},children:[Z(ot.Header,{children:Z(ot.Heading,{children:"Rename chat"})}),Ce(ot.Body,{children:[Z(ng,{autoFocus:!0,fullWidth:!0,"aria-label":"Chat name",isInvalid:!!n,name:"title",children:Z(tg,{maxLength:og,value:d,variant:"secondary",onChange:l=>i(l.target.value)})}),Z(dc,{message:n})]}),Ce(ot.Footer,{children:[Z(an,{fullWidth:!0,isDisabled:t,type:"button",variant:"outline",onPress:r,children:"Cancel"}),Z(an,{fullWidth:!0,isPending:t,type:"submit",children:t?"Saving\u2026":"Submit"})]})]}):e?.type!=="delete"?null:Ce(pc,{children:[Z(ot.Header,{children:Z(ot.Heading,{children:"Delete chat?"})}),Ce(ot.Body,{children:[Ce("p",{children:["Are you sure you want to delete ",Ce("strong",{children:["\u201C",e.item.title,"\u201D"]}),"?"]}),Z(dc,{message:n})]}),Ce(ot.Footer,{children:[Z(an,{fullWidth:!0,isDisabled:t,variant:"outline",onPress:r,children:"Cancel"}),Z(an,{fullWidth:!0,isPending:t,variant:"danger",onPress:()=>void o(),children:t?"Deleting\u2026":"Delete"})]})]})}function dc({message:e}){return e?Z("p",{className:"ha-session-modal-error",role:"alert",children:e}):null}import{useEffect as ag,useState as ig}from"react";import{jsx as ug}from"react/jsx-runtime";var io=["Thinking\u2026","Analyzing request\u2026","Preparing next steps\u2026"],lg=1600,cg=5e3;function mc(){let[e,t]=ig(0);return ag(()=>{let n=e===io.length-1,r=window.setTimeout(()=>{t(o=>(o+1)%io.length)},n?cg:lg);return()=>window.clearTimeout(r)},[e]),ug(qr,{ariaLabel:"Working on your request\u2026",label:io[e]??io[0]})}function gc({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 Us(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 fc({isPendingPart:e,messages:t,terminal:n}){if(n)return!1;let r=t.at(-1);return!!(r?.role==="assistant"&&r.parts.some(o=>e(o)))}function ln({attempt:e,currentAttempt:t,manualStopRequested:n,stalledStopRequested:r}){return e===t&&!n&&!r}async function hc(e,t){return await e?.catch(()=>{}),t()}function yc({hasPendingClientToolCalls:e,isAutoContinuationPending:t,isRecovering:n,isRunning:r,localPending:o,stalled:s}){return!s&&(r||e||o||t||n)}function vc({hasActiveTurn:e,hasPendingClientToolCalls:t,isResuming:n,stalled:r}){return e&&!t&&!n&&!r}function Sc(e){let t=globalThis.setTimeout(e,12e4);return()=>globalThis.clearTimeout(t)}function bc(e){let t=globalThis.setTimeout(e,12e4);return()=>globalThis.clearTimeout(t)}import{useCallback as dg,useEffect as cr,useRef as Cc,useState as Ac}from"react";var pg=300;function Tc({attachments:e,draftKey:t,input:n,setAttachments:r,setInput:o}){let[s,i]=Ac(null),[d,l]=Ac(null),c=Cc(n),m=Cc(null);return cr(()=>{c.current=n},[n]),cr(()=>{let p=!1,C=Fa(t);return queueMicrotask(()=>{p||(C&&o(u=>u||C),l(t))}),Va(t).then(u=>{p||(u.length>0&&r(h=>h.length>0?h:u),i(t))}),()=>{p=!0}},[t,r,o]),cr(()=>{if(d!==t)return;let p=()=>Ho(t,n);return m.current=window.setTimeout(p,pg),window.addEventListener("pagehide",p),()=>{m.current!==null&&window.clearTimeout(m.current),m.current=null,window.removeEventListener("pagehide",p)}},[t,n,d]),cr(()=>{if(d===t)return()=>Ho(t,c.current)},[t,d]),cr(()=>{s===t&&$a(t,e)},[e,t,s]),dg(()=>{c.current="",m.current!==null&&window.clearTimeout(m.current),m.current=null,wr(t)},[t])}import{useCallback as mg,useState as gg}from"react";function Rc(e){return`${e}:model`}function fg(e){if(typeof window>"u")return;let t=Rc(e);try{let n=window.localStorage.getItem(t);if(n===null)return;let r=Ta(n);if(Ma(r))return r!==n&&window.localStorage.setItem(t,r),r;window.localStorage.removeItem(t)}catch{}}function hg(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(Rc(e),t)}catch{}}function Bs(e,t){let[n,r]=gg(()=>fg(e)),o=n??t??Ra,s=mg(i=>{r(i),hg(e,i)},[e]);return{selectedModelId:o,setSelectedModelId:s}}var Mc="The recording could not be transcribed. Try again.",wc="No speech was detected. Try again when you are ready.",yg="Voice transcription took too long. Try again.",vg=3e4;function Sg(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()},vg);return{didTimeOut:()=>n,dispose:()=>{clearTimeout(o),e.removeEventListener("abort",r)},signal:t.signal}}function bg(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 Cg(e,t){return{Authorization:`Bearer ${e}`,"Content-Type":t,"X-HeroUI-Agent-Protocol-Version":String(6),"X-HeroUI-Agent-SDK-Version":We}}function Ag(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?wc:e===429?"Voice dictation is busy. Wait a moment and try again.":Mc}async function Ec({apiBaseUrl:e,audio:t,conversationId:n,language:r,signal:o,tokenManager:s}){let i=new URL(`${e}/v1/conversations/${encodeURIComponent(n)}/transcriptions`),d=Sg(o);r?.trim()&&i.searchParams.set("language",r.trim());try{for(let l=0;l<2;l+=1){let c=await bg(s.get(),d.signal),m=await fetch(i,{body:t,headers:Cg(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(Ag(m.status));let p=await m.json().catch(()=>null),C=typeof p?.text=="string"?p.text.trim():"";if(!C)throw new Error(wc);return C}}catch(l){throw d.didTimeOut()&&!o.aborted?new Error(yg,{cause:l}):l}finally{d.dispose()}throw new Error(Mc)}import{Fragment as cn,jsx as I,jsxs as Pe}from"react/jsx-runtime";var kc=on();async function Og(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 Fs(e){return e.type==="dynamic-tool"&&e.toolName?e.toolName:e.type.startsWith("tool-")?e.type.slice(5):null}function Dg({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:C,shellComposerEndSlot:u,shellComposerFooterSlot:h,showReadyLoader:x,tokenManager:w}){let[A,O]=ee(null),[_,k]=ee({}),L=ce(_),$=ce(A),[X,S]=ee(null),[f,v]=ee([]),[R,y]=ee(fs),M=ce(R),[T,P]=ee({}),[z,ie]=ee(0),j=A?_[A]??null:null;$t(()=>{L.current=_,$.current=A},[A,_]);let B=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]),be=W((E,U)=>{ye(V=>Xi(V,{...U,activeConversationId:m?$.current:null,conversationId:E}))},[ye,m]);Se(()=>{!m||!A||ye(E=>hs(E,A))},[A,ye,m]);let H=W(E=>{ye(U=>hs(U,E)),l(E)},[ye,l]),F=W(()=>{$.current=null,O(null),S(null),i()},[i]),D=W((E,U)=>{P(V=>{let J=V[E]??kc,se=U(J);return se===J?V:{...V,[E]:se}})},[]),N=ce(null),Y=ce(null),re=p.apiBaseUrl,oe=p.agentId,Me=Vt(d),qe=W((E,U)=>{let V=el({conversationEpoch:t,optimisticTarget:Y.current,readyConversationId:E,readyEpoch:U,requestedConversationId:C});V&&(k(J=>{let se=J[V];return!se||se.composerReady?J:{...J,[V]:{...se,composerReady:!0}}}),O(V),d(U))},[t,d,C]),st=Ae(()=>{try{return Ot(vn(p.tools,p.permissionDefaultMode)),p.permissionShowPicker&&Ot(vn(p.tools,"ask")),null}catch(E){return E instanceof Error?E.message:"The client tools could not be loaded"}},[p.permissionDefaultMode,p.permissionShowPicker,p.tools]),at=st?null:Mi(p),un=Vt(E=>Ei(p,w,E)),xn=Vt(E=>{Ne(p,w,E,"embed_loaded")}),wt=ce(n);$t(()=>{if(wt.current===n)return;wt.current=n,N.current=null,Y.current=null,L.current={},$.current=null,k({}),O(null),v([]);let E=fs();M.current=E,y(E),P({}),r?w.reset():w.clear()},[n,r,w]),$t(()=>{if(C!==null||st)return;let E=Zi(Y.current,t);Y.current=E;let U=N.current;if(!U)return;let V=E.conversationId;localStorage.setItem(U.storageKey,V),S(null),v(J=>{let se=Kn(J,V,Ir([]),Date.now());return kt(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)},[st,t,C]),Se(()=>{let E=!1;if(st){S(st),O(null),Me(t);return}let U=N.current;if(U){let J=Wr({conversationEpoch:t,optimisticTarget:Y.current,requestedConversationId:C,storedConversationId:localStorage.getItem(U.storageKey)}),se=J?L.current[J]:void 0;if(se?.runtime){S(null),k(ve=>({...ve,[se.conversationId]:{...se,readyEpoch:t}})),se.composerReady&&O(se.conversationId);return}}let V=Wr({conversationEpoch:t,optimisticTarget:Y.current,requestedConversationId:C,storedConversationId:null});return S(null),O(V??(typeof C=="string"&&Rt(C)?C:null)),(async()=>{try{let J=await w.subjectHash(),se=`heroui-agent:conversation:${oe}:${J}`,ve=`heroui-agent:history:${oe}:${J}`,_e=Wr({conversationEpoch:t,optimisticTarget:Y.current,requestedConversationId:C,storedConversationId:localStorage.getItem(se)})??crypto.randomUUID();localStorage.setItem(se,_e);let Ge=Fo(ve);E||v(Ge);let we=U?.config??oc(oe),qt=we?null:Xn(w,`${re}/v1/agents/${encodeURIComponent(oe)}/config`),ct=Xn(w,`${re}/v1/agents/${encodeURIComponent(oe)}/conversations`).catch(()=>null),kn=await un(_e),dn=we??(qt?await Og(qt):null);if(!dn||!kn)throw new Error("The data assistant could not be loaded");we||sc(oe,dn);let De=Ge.find(ut=>ut.id===_e),Nn=Kn(Ge,_e,De?.title??Ir([]),De?.updatedAt??Date.now());if(Nn!==Ge&&kt(ve,Nn),!E){N.current={config:dn,historyKey:ve,storageKey:se},v(Nn);let ut=L.current[_e],le={composerReady:!1,config:dn,conversationId:_e,historyKey:ve,readyEpoch:t,runtime:kn.runtime,showStartScreenWhileConnecting:ut?.showStartScreenWhileConnecting??C===null,storageKey:se};B(le)}ct.then(async ut=>{if(!ut?.ok)return;let le=Pr((await ut.json()).conversations);E||v(Gt=>{let _n=Vo(Gt,le);return kt(ve,_n),_n})}),xn(_e)}catch(J){E||(S(J instanceof Error?J.message:"The data assistant could not be loaded"),Me(t))}})(),()=>{E=!0}},[re,B,at,st,t,n,oe,C,z,w]);let Je=W((E,U,V)=>{let J=N.current?.historyKey;J&&v(se=>{let ve=Kn(se,E,U,Date.now(),V);return kt(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(Gr(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[qt,ct]of Object.entries(Gr(Ge)))we.set(qt,ct);_e=await fetch(`${re}/v1/conversations/${encodeURIComponent(E)}`,{...U,headers:we})}return _e},J=await V();if(U.method==="DELETE"&&J.status===409&&(J=await tl({initialResponse:J,request:V})),!J.ok)throw new Error(U.method==="DELETE"?"The chat could not be deleted":"The chat could not be renamed")},[re,w]),vt=W(async(E,U)=>{await Oe(E,{body:JSON.stringify({title:U}),headers:{"Content-Type":"application/json"},method:"PATCH"});let V=N.current?.historyKey;V&&v(J=>{let se=J.map(ve=>ve.id===E?{...ve,title:U}:ve);return kt(V,se),se})},[Oe]),it=W(async E=>{await Oe(E,{method:"DELETE"});let U=N.current;U&&(v(V=>{let J=V.filter(se=>se.id!==E);return kt(U.historyKey,J),J}),localStorage.removeItem(Tr(U.storageKey,E)),localStorage.removeItem(ko(U.storageKey,E)),wr(Uo(U.storageKey,E)),Cl(As(U.storageKey,E)),k(V=>{if(!(E in V))return V;let J={...V};return delete J[E],J}),ye(V=>Ji(V,E)),P(V=>{if(!(E in V))return V;let J={...V};return delete J[E],J}),A===E&&F())},[A,ye,Oe,F]),ge=Ae(()=>{let E=p.suggestedPrompts;return E?.length?Object.fromEntries(Object.entries(_).map(([U,V])=>[U,{...V,config:{...V.config,suggestedPrompts:E}}])):_},[p.suggestedPrompts,_]),Et=A?ge[A]?.config??null:null,Kt=ce(null);Se(()=>{!m||!j?.runtime||Kt.current===j.conversationId||(Kt.current=j.conversationId,Ne(p,w,j.conversationId,"opened"))},[m,p,j,w]);let Pt=st??X,ur=Ae(()=>qo(f),[f]),co=f.find(E=>E.id===A)?.title??"New chat",St=N.current?"Loading chat\u2026":"Loading assistant\u2026",lt=C===null&&(!j||j.showStartScreenWhileConnecting);return I(cn,{children:Pe(Ca,{keepMounted:!0,agentId:p.agentId,defaultExpanded:p.panelExpanded,expandable:!x&&p.panelExpandable,expandedTitle:co,modal:p.viewMode!=="sidebar",name:Et?.name??"Data assistant",open:m,actionsSlot:x?I(cn,{}):I(nc,{isDisabled:lt,onPress:F}),expandedSidebarSlot:x?void 0:I(Hs,{activeConversationId:A,busyConversationIds:R.busyIds,completedConversationIds:R.completedIds,groups:ur,isNewConversationDisabled:lt,variant:"sidebar",onDeleteConversation:it,onNewConversation:F,onRenameConversation:vt,onSelectConversation:H}),historySlot:x?I(cn,{}):I(Hs,{activeConversationId:A,busyConversationIds:R.busyIds,completedConversationIds:R.completedIds,groups:ur,onDeleteConversation:it,onRenameConversation:vt,onSelectConversation:H}),onClose:o,onNewConversation:x?void 0:F,children:[Pt?I("div",{className:"ha-loading",role:"alert",children:Pt}):x?I(ba,{indicator:I(Ig,{"aria-hidden":!0,color:"current",size:"md"})}):!j||!j.runtime||!Et?lt&&j?I(Nc,{composerControlsRevealed:e,loadingLabel:St,options:p,route:j,onComposerControlsReveal:s},`pending-${t}`):I(jr,{agentId:p.agentId,composerControlsAvailable:p.composerControlsAvailable,composerControlsRevealed:e,composerEndSlot:u,composerFooterSlot:h,greeting:p.greeting,loadingLabel:St,placeholder:p.composerPlaceholder,showStartScreen:lt,suggestedPrompts:p.suggestedPrompts??[],composerStartSlot:I(Lc,{agentId:p.agentId,options:p}),onComposerControlsReveal:s},`pending-${t}`):null,I("div",{className:"ha-runtime-content",hidden:!!Pt||x,children:I(sl,{activeConversationId:Pt?null:A,routes:ge,children:(E,U)=>I(La,{variant:E.config.surfaceVariant,children:E.runtime?I(Ng,{fallback:U&&E.showStartScreenWhileConnecting?I(Nc,{composerControlsRevealed:e,loadingLabel:"Connecting chat\u2026",options:p,route:E,onComposerControlsReveal:s}):I(jr,{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(Hg,{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]??kc,onComposerControlsReveal:s,onConversationStatusChange:be,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 Nc({composerControlsRevealed:e,loadingLabel:t,onComposerControlsReveal:n,options:r,route:o}){return I(jr,{showStartScreen:!0,agentId:r.agentId,composerControlsAvailable:r.composerControlsAvailable,composerControlsRevealed:e,composerStartSlot:I(Lc,{agentId:r.agentId,options:r}),greeting:r.greeting,loadingLabel:t,placeholder:r.composerPlaceholder,suggestedPrompts:r.suggestedPrompts??[],composerEndSlot:I(Lg,{conversationId:o.conversationId,options:r,storageKey:o.storageKey}),composerFooterSlot:r.composerDisclaimer?I("p",{className:"ha-footnote",children:Po(r.composerDisclaimer)}):null,onComposerControlsReveal:n})}function Lc({agentId:e,options:t}){let n=ce(null),[r,o]=ee(()=>xo(e)),[s,i]=ee(null),d=l=>{let c=Rn(l,t.composerAttachmentContentTypes);o(c.files),i(c.error),xa(e,c.files)};return t.composerAttachmentContentTypes.length===0?null:Pe(cn,{children:[I("input",{ref:n,multiple:!0,accept:t.composerAttachmentAccept,"aria-label":"Choose files to attach",className:"ha-file-input",type:"file",onChange:l=>{d(Array.from(l.currentTarget.files??[])),l.currentTarget.value=""}}),r.length>0?I(Oo,{"aria-label":"Selected attachments",className:"ha-attachments",offset:1,size:24,children:r.map(l=>I(ds,{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(Dc,{"aria-hidden":"true"})}),s?I("span",{className:"ha-dictation-error",role:"alert",children:s}):null]})}function Lg({conversationId:e,options:t,storageKey:n}){let r=Tr(n,e),[o,s]=ee(()=>Rr(r)??t.permissionDefaultMode),{selectedModelId:i,setSelectedModelId:d}=Bs(n,t.composerDefaultModel),l=c=>{s(c),Mr(r,c)};return Pe(cn,{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:Io,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(Oc,{"aria-hidden":"true"}),I(Vn,{children:"Dictate message"})]}):null]})}function Hg({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:C,options:u,runtime:h,showStartScreenWhileHydrating:x,storageKey:w,tokenManager:A}){let{selectedModelId:O,setSelectedModelId:_}=Bs(w,u.composerDefaultModel),k=ko(w,o),L=Tr(w,o),$=u.composerAttachmentAccept,X=Ae(()=>({key:$}),[$]),[S,f]=ee(()=>({files:Rn(xo(u.agentId),u.composerAttachmentContentTypes).files,policy:X})),[v,R]=ee(()=>({error:null,policy:X})),y=Ae(()=>S.policy===X?S.files:[],[X,S]),M=v.policy===X?v.error:null,T=W(a=>{f(g=>{let b=g.policy===X?g.files:[],q=typeof a=="function"?a(b):a;return{files:Rn(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,B]=ee({}),[K,ye]=ee({}),[be,H]=ee(!1),[F]=ee(()=>wa(u.agentId)),[D,N]=ee(()=>F?.submitted?"":F?.prompt??""),[Y,re]=ee(()=>F?.submitted?{files:y,id:F.messageId,text:F.prompt}:null),[oe,Me]=ee(()=>{let a=u.permissionShowPicker?Rr(L):void 0;return{configuredDefaultMode:u.permissionDefaultMode,selectedMode:a??u.permissionDefaultMode}}),[qe,st]=ee(!1),[at,un]=ee(!0),[xn,wt]=ee(!1),[Je,de]=ee(!1),[Oe,vt]=ee(()=>new Set),[it,ge]=ee(null),[Et,Kt]=ee(0),[Pt,ur]=ee(0),[co,St]=ee(!1),[lt,E]=ee(!1),[U,V]=ee(null),[J,se]=ee({}),ve=W(a=>{u.permissionShowPicker?Mr(k,a.permissionMode):No(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,qt=u.permissionShowPicker?z?.permissionMode??we:u.permissionDefaultMode,ct=Ae(()=>vn(u.tools,qt),[qt,u.tools]),kn=Ae(()=>Ot(ct),[ct]),dn=Ae(()=>Li(kn),[kn]),De=Ae(()=>new Map(ct.map(a=>[a.name,a])),[ct]),Nn=Ae(()=>new Set(ct.map(a=>a.name)),[ct]),ut=ce(new Set),le=ce(null),Gt=ce(new Set),_n=ce(!1),Le=ce(s),uo=ce(null),Ze=ce(!1),He=ce(!1),Qt=ce(null),dr=ce(0),dt=ce(0),It=ce(null),zt=ce(null),pr=ce(null),po=ce(new Set),mo=ce(new Map),On=ce(()=>{}),Vs=ce(null),$s=ce(null),bt=ce(null),Ee=Ae(()=>gc({report:({latencyMs:a,messageId:g,metric:b})=>{Ne(u,A,o,b,{latencyMs:a,latencyOrigin:"user_submit",messageId:g})}}),[o,u,A]),Hc=Ae(()=>Uo(w,o),[o,w]),Dn=Ae(()=>As(w,o),[o,w]),Ks=Tc({attachments:y,draftKey:Hc,input:D,setAttachments:T,setInput:N}),Uc=W((a,{language:g,signal:b})=>Ec({apiBaseUrl:u.apiBaseUrl,audio:a,conversationId:o,...g?{language:g}:{},signal:b,tokenManager:A}),[o,u.apiBaseUrl,A]),{cancel:Qe,elapsedSeconds:go,error:fo,isActive:ke,isRecording:Bc,isSupported:Wt,isTranscribing:Ln,start:qs,stop:Gs,stream:Fc}=Jo({onValueChange:N,transcribe:Uc,value:D}),ho=t||ke||y.length>0||M!==null||fo!==null,Qs=W(()=>{u.composerControlsAvailable&&i()},[i,u.composerControlsAvailable]),Vc=a=>{$n(u.agentId,!0,a.currentTarget),Qs()},$c=a=>{let g=a.currentTarget.querySelector(".ha-composer");g&&Ia(g,a.relatedTarget)||$n(u.agentId,!1)};Se(()=>{Le.current=s},[s]),Se(()=>{u.composerDictation||Qe()},[Qe,u.composerDictation]),Se(()=>{e||Qe()},[e,Qe]);let pn=u.composerModelPicker?O:u.composerDefaultModel,mn=W(a=>{Le.current=a,m(o,()=>a)},[o,m]),et=W(async(a,{applyAfterPersist:g=!1}={})=>{let b=Le.current,q=a(b);if(q!==b){g?Le.current=q:mn(q);try{await Ts(Dn,q)}catch(pe){throw Le.current===q&&(g?Le.current=b:mn(b)),pe}g&&Le.current===q&&mn(q)}},[mn,Dn]),ze=W(a=>{et(a).catch(()=>{})},[et]),Kc=W(a=>{Gt.current.add(a),et(g=>nr(En(g,a,"admitted"),a)).catch(()=>{})},[et]);Se(()=>{let a=!1;return un(!0),bl(Dn).then(async g=>{if(a)return;let b=Al(g,Le.current),q=Gt.current,pe={...b,messages:b.messages.filter(ue=>!q.has(ue.id))};mn(pe),await Ts(Dn,pe)}).catch(()=>{}).finally(()=>{a||un(!1)}),()=>{a=!0}},[mn,Dn]);let mr=W(()=>{Ze.current=!1,He.current=!1,It.current=null,E(!1)},[]),zs=W(a=>{ln({attempt:a,currentAttempt:dt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current})&&de(!1)},[]),{agent:jt,connectionEpoch:gr,connectionError:pt,isHydrating:qc,isReconnecting:Ws,retryConnection:Gc}=Fg({conversationId:o,onRuntimeRevisionStale:C,onTurnAdmitted:Kc,options:u,runtime:h,tokenManager:A}),Qc=Vt(p);$t(()=>{Qc(o,r)},[e,r,o]),Se(()=>{if(at||gr===0)return;let a=[];for(let q of Le.current.messages)yt(q)==="sending"&&a.push(q.id);if(a.length===0){wt(!1);return}let g=!1,b;return wt(!0),(async()=>{let q=[];for(let he=0;he<a.length;he+=50)q.push(a.slice(he,he+50));let pe=async he=>{let Cr=await Promise.all(q.map(async mt=>({response:await jt.call(Ba,[{protocolVersion:6,turnIds:mt}],{timeout:15e3}),turnIds:new Set(mt)}))),Be=new Set;for(let{response:mt,turnIds:Mo}of Cr){if(mt.protocolVersion!==6||!Array.isArray(mt.turns))throw new Error("Invalid turn admission status response");for(let yn of mt.turns)yn.status==="admitted"&&Mo.has(yn.turnId)&&Be.add(yn.turnId)}return Be.size===a.length||he>=4?Be:(await new Promise(mt=>window.setTimeout(mt,500)),pe(he+1))},ue;try{ue=await pe(0)}catch{g||(b=window.setTimeout(()=>ur(he=>he+1),1e3));return}if(!g){for(let he of ue)Gt.current.add(he);await et(he=>Tl(he,ue))}})().catch(()=>{}).finally(()=>{g||wt(!1)}),()=>{g=!0,b!==void 0&&window.clearTimeout(b)}},[jt,et,gr,at,Pt]);let zc=Ae(()=>new Proxy(jt,{get(a,g){if(g==="send")return q=>a.send(Hi(q));let b=Reflect.get(a,g,a);return typeof b=="function"?b.bind(a):b}}),[jt]),Q=Mg({agent:zc,cancelOnClientAbort:!1,experimental_throttle:60,getInitialMessages:null,onData:a=>{if(a.type!=="data-conversation-title"){let g=Ee.getActiveMessageId();g&&po.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,A,o,"component_rendered",{componentType:g?.kind})}a.type==="data-runtime-timing"&&ac(u.agentId,o,a.data)},onError:a=>{if(Ze.current||He.current){It.current=null,de(!1),ge(null),queueMicrotask(()=>On.current());return}It.current=a,de(!1),ge(null),Ne(u,A,o,"failure",{messageId:Ee.getActiveMessageId()??void 0,source:"cloudflare-chat"})},onFinish:({isError:a})=>{if(Ze.current||He.current){It.current=null,de(!1),ge(null),queueMicrotask(()=>On.current());return}a&&!It.current&&(It.current=new Error("The request could not be completed")),de(!1),ge(null)},resume:!0,syncMessagesToServer:!1,tools:dn}),{clearError:js,setMessages:Ys}=Q;$t(()=>{On.current=js},[js]);let Ct=Q.status==="submitted"||Q.status==="streaming"||Q.isStreaming,xt=co||lt,Hn=!xt&&Q.isToolContinuation,yo=!!(xt||Q.error||Q.connectionError||pt),Yt=Ae(()=>!yo&&(Oe.size>0||fc({isPendingPart:a=>{let g=a,b=Fs(g);return kl({isClientTool:!!(b&&De.has(b)),state:g.state})},messages:Q.messages,terminal:yo})),[Q.messages,De,yo,Oe]),Ue=yc({hasPendingClientToolCalls:Yt,isAutoContinuationPending:Hn,isRecovering:Q.isRecovering,isRunning:Ct,localPending:Je,stalled:lt});Se(()=>{if(Ue)return;let a=Ee.getActiveMessageId();a&&(Ee.complete(a),po.current.delete(a),mo.current.delete(a))},[Ue,Ee]);let Xt=!pt&&(qc||Ws||at||xn),vo=Xt||Ue,So=xt||!!Q.error||!!Q.connectionError||!!pt,At=vo||So,Xs=Ml({hasChatError:!!(Q.error||Q.connectionError||pt),hasPendingClientToolCalls:Yt,hasReadyClientToolContinuation:Hn,isLocalPending:Je,isResuming:Xt,isRunning:Ct,recoveryError:xt}),Js=Vt(l);Se(()=>{z&&!Ct&&!Yt&&!Je&&!Xt&&!Hn&&(No(k),ie(void 0))},[z,k,Yt,Hn,Xt,Ct,Je]),Se(()=>{Js(o,{busy:vo,failed:So,turnActive:Ue})},[So,o,Ue,vo]),Se(()=>()=>{Js(o,{busy:!1,failed:!0,turnActive:!1})},[o]);let Tt=Q.messages.at(-1),Zs=Ct&&Tt?.role==="assistant"?Tt.id:null,Wc=Tt?.role==="assistant"&&(Yt||Hn||Q.isRecovering)?Tt.id:null,Jt=rl({continuingAssistantMessageId:Wc,isActiveTurn:Ue,streamingAssistantMessageId:Zs,trackedActivityMessageId:zt.current}),bo=Jt===Tt?.id?Tt:void 0,ea=!!(bo&&ts(bo,De,{isStreaming:!0}).length>0),jc=Us(bo).hasServerContent;Se(()=>{if(Ue&&Jt){if(zt.current===Jt)return;let b=pr.current??Date.now();zt.current=Jt,B(q=>({...q,[Jt]:{startedAt:b}}));return}let a=zt.current;if(Ue||!a)return;let g=Date.now();B(b=>{let q=b[a];return!q||q.completedAt?b:{...b,[a]:{...q,completedAt:g}}}),zt.current=null,pr.current=null},[Jt,Ue]);let fr=W(async(a,g,b)=>{Q.addToolOutput({output:b,toolCallId:g,toolName:a})},[Q.addToolOutput]),Co=W((a,g)=>{vt(b=>{if(b.has(a)===g)return b;let q=new Set(b);return g?q.add(a):q.delete(a),q})},[]),hr=W(async(a,g)=>{await ki({activeToolCallIds:ut.current,run:async()=>{Co(g.toolCallId,!0),ge("Fetching live data\u2026");try{await Oi({conversationId:o,execute:b=>_i({context:u.context,execution:b,input:g.input,tool:a}),input:g.input,rpc:{claim:b=>jt.call("claimClientToolEffect",[b],{timeout:ls}),complete:b=>jt.call("completeClientToolEffect",[b],{timeout:ls})},submitOutput:b=>fr(a.name,g.toolCallId,b),toolCallId:g.toolCallId,toolName:a.name}),ge("Analyzing the results\u2026")}finally{Co(g.toolCallId,!1)}},toolCallId:g.toolCallId})},[jt,o,u.context,Co,fr]),Yc=W((a,g,b)=>{let q=g.toolCallId;if(se(pe=>({...pe,[q]:b?"approved":"rejected"})),ge(b?"Applying your change\u2026":"Updating your request\u2026"),Ne(u,A,o,b?"action_approved":"action_declined"),g.approval?.id)Q.addToolApprovalResponse({approved:b,id:g.approval.id});else if(!b)fr(a,q,{reason:"The user declined this tool call",rejected:!0});else{se(pe=>({...pe,[q]:"rejected"}));return}if(b){let pe=De.get(a);pe&&hr(pe,g).catch(()=>{})}else ut.current.add(q)},[Q.addToolApprovalResponse,De,o,hr,u,fr,A]);Se(()=>{for(let a of Q.messages)if(a.role==="assistant")for(let g of a.parts){let b=Fs(g);if(!b)continue;let q=De.get(b);!q||ut.current.has(g.toolCallId)||Ni({approvalApproved:g.approval?.approved,decision:J[g.toolCallId],needsApproval:q.needsApproval===!0,state:g.state})&&hr(q,g).catch(()=>{})}},[Q.messages,De,gr,hr,J]);let Ao=W(a=>{H(Na(a,{hasAttachments:ho&&y.length>0}))},[y.length,ho]);$t(()=>{Ao(bt.current)},[D,ke,Ao]);let ta=W(a=>{if(a.length===0)return;let g=Rn([...y,...a],u.composerAttachmentContentTypes);P(g.error),T(g.files)},[y,u.composerAttachmentContentTypes,P,T]),na=W(()=>{Qe(),Ks(),N(""),T([]),P(null),V(null)},[Qe,Ks,P,T]),Xc=W(()=>bt.current?.focus(),[]),To=W(()=>{if(Ln){Qe(),requestAnimationFrame(()=>bt.current?.focus());return}if(ke){Gs(),requestAnimationFrame(()=>bt.current?.focus());return}qs()},[Qe,ke,Ln,qs,Gs]);Se(()=>{if(!e||!u.composerDictation||!Wt)return;let a=g=>{ji(g)&&(g.preventDefault(),bt.current?.focus({preventScroll:!0}),To())};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e,Wt,u.composerDictation,To]),$t(()=>{e&&Pa(u.agentId,bt.current)},[e,u.agentId]);let ra=W(async a=>{let g=++dt.current,b=Q.messages,q=b.findLast(Be=>Be.role==="user")?.id,pe=b.findLast(Be=>Be.role==="assistant")?.id,ue=u.permissionShowPicker?a.permissionMode??we:u.permissionDefaultMode,he=Ot(vn(u.tools,ue));ve({modelId:a.modelId,permissionMode:ue}),zt.current=null,mo.current.set(a.id,pe),Ee.activate(a.id);let Cr=Ee.getStartedAtWallClock(a.id)??Date.now();pr.current=Cr,mr(),uo.current={previousUserMessageId:q??null,scrollKey:crypto.randomUUID()},de(!0),St(!1),E(!1),ge(jn("accepted")),d($o(a.text,a.files));try{let Be=await _c(u,a.selection);if(!ln({attempt:g,currentAttempt:dt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;a.files.length>0&&ge("Uploading attachments\u2026");let mt=await xi({acceptedContentTypes:u.composerAttachmentContentTypes,apiBaseUrl:u.apiBaseUrl,conversationId:o,files:a.files,tokenManager:A});if(!ln({attempt:g,currentAttempt:dt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;Ne(u,A,o,"message_sent",{messageId:a.id});let Mo=cs({clientSubmittedAt:Cr,clientTools:he,imageSearch:u.imageSearch,modelId:a.modelId,newsSearch:u.newsSearch,pageContext:Be,permissionMode:ue,turnId:a.id,webSearch:u.webSearch});ge(jn("accepted")),await Q.sendMessage(wl(a,mt),{body:Mo});let yn=It.current;if(yn)throw It.current=null,yn}catch(Be){if(!ln({attempt:g,currentAttempt:dt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;throw Be instanceof Error&&P(Be.message),Ys(b),Q.clearError(),St(!1),E(!1),de(!1),ge(null),Be}},[Q,ve,we,o,d,u,mr,P,Ys,A,Ee]),Un=W((a,{resumeDrainAfter:g=!0}={})=>{le.current=a.id,ra(a).catch(()=>{le.current===a.id&&(le.current=null),Gt.current.has(a.id)||ze(b=>ht(En(Cs(b,{...a,deliveryStatus:"pending"},"prepend"),a.id,"pending"),a.id))}).finally(()=>{le.current===a.id&&(le.current=null),g&&Kt(b=>b+1)})},[ra,ze]),Zt=W((a,g)=>{let b=a.trim();if(!b&&y.length===0)return;let q=!At&&!le.current&&Le.current.messages.length===0,pe=Pl({activeMessageId:le.current,authoritativeMessageCount:Q.messages.length,isNewChatStartScreen:x,queuedMessageCount:Le.current.messages.length}),ue={files:y,id:g?.messageId??crypto.randomUUID(),...pe?{isInitialTurn:!0}:{},...pn?{modelId:pn}:{},permissionMode:we,selection:U,text:b};q&&(ue.deliveryStatus="sending"),pe&&re({files:ue.files,id:ue.id,text:ue.text}),Ee.begin(ue.id,g),g?.firstFeedbackPaintedAt!==void 0&&Ee.markPaintedAt(ue.id,"first_feedback_paint",g.firstFeedbackPaintedAt),q&&(le.current=ue.id),et(he=>rr(Cs(he,ue),!1),{applyAfterPersist:!0}).then(()=>{na(),q?Un(ue):Kt(he=>he+1)}).catch(he=>{q&&(le.current=null),pe&&re(null),g&&N(b),P(he instanceof Error?he.message:"This message could not be saved before sending")})},[y,pn,we,et,Q.messages.length,At,na,U,Un,P,x,Ee]),gn=n.suggestedPrompts,Jc=Vt(a=>Zt(a.prompt,a));Se(()=>{if(!e)return;ka(u.agentId);let a=Ea(u.agentId);a&&(a.submitted?Jc(a):N(g=>g||a.prompt))},[e,u.agentId]),Se(()=>{if(!e||!u.suggestedPromptShortcuts||Q.messages.length>0||gn.length===0)return;let a=g=>{let b=Yi(g,gn.length);if(b===null)return;let q=gn[b];q&&(g.preventDefault(),Zt(q))};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e,Q.messages.length,u.suggestedPromptShortcuts,Zt,gn]);let oa=a=>{a.preventDefault(),Zt(D)},Zc=Vt(async a=>{try{await et(g=>En(g,a.id,"sending"))}catch(g){le.current===a.id&&(le.current=null),P(g instanceof Error?g.message:"This message could not be saved before sending"),ze(b=>ht(b,a.id));return}le.current===a.id&&Un({...a,deliveryStatus:"sending"})}),eu=W(a=>{_n.current=a,st(a)},[]);Se(()=>{let a=Nl({activeMessageId:le.current,isBusy:At,isReordering:qe,queue:s});a&&(le.current=a.id,queueMicrotask(()=>{if(_n.current){le.current===a.id&&(le.current=null);return}le.current===a.id&&Zc(a)}))},[At,qe,s,Et]);let tu=W(a=>{re(g=>g?.id===a?null:g),ze(g=>nr(g,a))},[ze]),nu=W((a,g,b)=>{ze(q=>vl(ht(q,null),a,g,b))},[ze]),ru=W(a=>{let g=Le.current.messages.find(b=>b.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(b=>b?.id===a?null:b),ze(b=>nr(ht(b,null),a)),requestAnimationFrame(()=>bt.current?.focus()))},[Qe,T,ze,Ge,_]),ou=W(a=>{if(At||le.current)return;let g=Le.current.messages.find(b=>b.id===a);g&&(le.current=g.id,et(b=>rr(En(ht(b,null),a,"sending"),!0)).then(()=>{le.current===g.id&&Un({...g,deliveryStatus:"sending"},{resumeDrainAfter:!1})}).catch(b=>{le.current===g.id&&(le.current=null),P(b instanceof Error?b.message:"This message could not be saved before sending")}))},[et,At,Un,P]),sa=W(()=>{let a=le.current;dr.current+=1,dt.current+=1,Ze.current=!0,He.current=!1,le.current=null,re(null),ze(b=>rr(a&&!Gt.current.has(a)?En(ht(b,null),a,"pending"):ht(b,null),!0)),de(!1),ge(null),St(!1),E(!1),Ne(u,A,o,"stopped");let g=Promise.resolve().then(()=>Q.stop()).catch(()=>{}).finally(()=>{Qt.current===g&&(Qt.current=null),On.current()});Qt.current=g},[Q,o,u,ze,A]),su=Vt(()=>{if(Ze.current||He.current)return;let a=le.current;dr.current+=1,dt.current+=1,He.current=!0,le.current=null,ze(b=>rr(a?nr(ht(b,null),a):ht(b,null),!0)),de(!1),ge(null),St(!1),E(!0),Ne(u,A,o,"turn_stalled",{messageId:a??void 0,source:"client-inactivity-watchdog"});let g=Promise.resolve().then(()=>Q.stop()).catch(()=>{}).finally(()=>{Qt.current===g&&(Qt.current=null),On.current(),He.current&&E(!0)});Qt.current=g});Se(()=>{if(vc({hasActiveTurn:Ue,hasPendingClientToolCalls:Yt,isResuming:Xt,stalled:lt}))return Sc(su)},[Q.isRecovering,Q.messages,Q.status,gr,Ue,Yt,Xt,Je,it,lt]);let au=W(a=>{if(Ne(u,A,o,`component_${a.type}`,{actionId:"actionId"in a?a.actionId:void 0,componentId:a.componentId,format:"format"in a?a.format:void 0,toolName:"toolName"in a?a.toolName:void 0}),a.type==="tool"){let g=Sa(De,a.toolName);if(g){(async()=>{try{let b=Ar(g,a.args),q=`component-action-${crypto.randomUUID()}`;await g.execute(b,u.context,{conversationId:o,idempotencyKey:`heroui-agent-component-action:${o}:${q}`,toolCallId:q})}catch{}})();return}}$i(a,{fillComposer:g=>{Qe(),N(g),H(!0),requestAnimationFrame(()=>bt.current?.focus())},setSelection:V,submitPrompt:Zt})},[Qe,De,o,u,Zt,A]),iu=W(a=>{let g=a.parts.filter(b=>b.type==="text").map(b=>b.text).join(`
|
|
4
|
+
|
|
5
|
+
`).trim();g&&(navigator.clipboard?.writeText(g).catch(()=>{}),Ne(u,A,o,"message_copied",{messageId:a.id}))},[o,u,A]),lu=W((a,g,b)=>{let q=K[a]===g&&!b;if(ye(pe=>{let ue={...pe};return q?delete ue[a]:ue[a]=g,ue}),!q){let pe=b?.comment,ue=b?.reasons??[];Ne(u,A,o,g==="up"?"feedback_up":"feedback_down",{feedbackComment:pe,feedbackReasons:ue,messageId:a});try{Promise.resolve(u.onFeedback?.({...pe?{comment:pe}:{},conversationId:o,messageId:a,rating:g==="up"?"positive":"negative",reasons:ue})).catch(()=>{})}catch{}}},[o,K,u,A]),aa=W(()=>{let a=++dr.current;(async()=>{let g=Qt.current;if(!await hc(g,()=>dr.current===a))return;let b=++dt.current,q=Ot(vn(u.tools,we)),pe=crypto.randomUUID(),ue=Date.now();zt.current=null,pr.current=ue,ve({modelId:pn,permissionMode:we}),mr(),uo.current=null,de(!0),St(!1),E(!1),ge(jn("accepted")),Ne(u,A,o,"retry");try{let he=await _c(u,U);if(!ln({attempt:b,currentAttempt:dt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;await Q.regenerate({body:cs({clientSubmittedAt:ue,clientTools:q,imageSearch:u.imageSearch,modelId:pn,newsSearch:u.newsSearch,pageContext:he,permissionMode:we,turnId:pe,webSearch:u.webSearch})})}catch{if(!ln({attempt:b,currentAttempt:dt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;St(!0)}finally{zs(b)}})()},[ve,Q,pn,we,zs,o,u,mr,U,A]),cu=Q.messages.findLast(a=>a.role==="assistant")?.id,tt=Il({authoritativeMessageCount:Q.messages.length,localTurn:Y,queue:s}),fn=Ae(()=>tt?{id:tt.id,parts:[{text:El(tt),type:"text"}],role:"user"}:null,[tt]),Bn=Ae(()=>fn?[fn,...Q.messages]:Q.messages,[Q.messages,fn]),uu=fn!==null,yr=!!(tt&&!s.isPaused&&s.blockedMessageId!==tt.id),ia=!!(Q.error||Q.connectionError||xt||pt),la=Bn.findLast(a=>a.role==="user")?.id,{activeStreamKey:vr,activeTurnMessageId:ca}=al({isActive:Ue||yr,lastUserMessageId:la,pendingTurn:fn&&yr?{previousUserMessageId:null,scrollKey:fn.id}:uo.current}),ua=li({clientToolNames:Nn,isLocalPending:Je,isRecovering:Q.isRecovering||Ws,isStreaming:Ct,messages:Q.messages,status:Q.status}),{showHome:da,standaloneStatus:du}=ol({hasActiveActivity:ea,hasError:ia,hasResponseStarted:jc,isActiveTurn:Ue||yr,messageCount:Bn.length,preferHomeWhileEmpty:x,progress:yr?Jn:it??jn(ua),runtimeStatus:Xt?"pending":"ready"}),pa=nl({activeStreamKey:vr,activeTurnMessageId:ca}),ma=da||pa&&Bn.length===0,nt=Ee.getActiveMessageId(),pu=nt?mo.current.get(nt):void 0,ga=nt&&Tt?.role==="assistant"&&Tt.id!==pu?Tt:void 0,Fn=Us(ga,{hasActivity:!!(ga&&ea),hasTransientData:!!(nt&&po.current.has(nt))}),Ro=uu&&ia?null:du,Sr=!pa&&Ro&&(e||Ro!==Jn)?Ro:null,fa=!!Sr;$t(()=>{if(e){for(let a of s.messages)Ee.markAfterPaint(a.id,"first_feedback_paint");tt&&Ee.markAfterPaint(tt.id,"first_feedback_paint"),nt&&((fa||Fn.hasServerContent||Q.error||Q.connectionError||xt||pt)&&Ee.markAfterPaint(nt,"first_feedback_paint"),Fn.hasServerContent&&Ee.markAfterPaint(nt,"first_server_content_paint"),Fn.hasText&&Ee.markAfterPaint(nt,"first_text_paint"))}},[e,nt,Q.connectionError,Q.error,fa,s.messages,tt,xt,pt,Fn.hasServerContent,Fn.hasText,Ee]);let mu=Ae(()=>xl(s,tt?.id??null),[s,tt?.id]),br=!!(D.trim()||y.length>0),ha=Ln?"Cancel transcription":ke?"Stop dictation":"Dictate message",ya=Wt?ha:"Voice dictation is not supported in this browser",hn=Ct&&!br?"Stop answering":At&&!(x&&Bn.length===0)?"Queue message":"Send message";return Pe(cn,{children:[Pe(dl,{activityPhase:ua,streamKey:vr,children:[ma?Pe("div",{className:"ha-empty",children:[I("h2",{children:u.greeting}),I("p",{children:"Live answers with charts, metrics, and tables."})]}):Bn.map(a=>I(Ug,{actions:u.messageActions,activityTiming:j[a.id],canRetry:a.id===cu&&!At,clientTools:De,exportFormats:u.componentExportFormats,feedback:K[a.id]??null,isActivityActive:a.id===Jt,isStreaming:a.id===Zs,markdownAnimation:u.markdownAnimation,markdownCaret:u.markdownCaret,markdownPlugins:u.markdownPlugins,message:a,toolDecisions:J,turnAnchor:a.id===ca&&vr!==null?"active":a.id===la?"latest":null,onAction:au,onClientToolDecision:Yc,onCopy:iu,onFeedback:lu,onRetry:aa,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===Jn?I(mc,{},vr??o):I(qr,{label:Sr})})}):null,Q.error||Q.connectionError||xt||pt?Pe("div",{className:"ha-error",role:"alert",children:[I("span",{children:pt?"The assistant connection could not be restored.":lt?"The assistant stopped responding. Please retry.":"The request could not be completed."}),I("button",{type:"button",onClick:pt?Gc:aa,children:"Retry"})]}):null]}),Pe("form",{className:"ha-composer-wrap",onBlur:$c,onSubmit:oa,children:[da&&gn.length>0?I("div",{"aria-label":"Suggested prompts",className:"ha-suggestions",role:"group",children:gn.map((a,g)=>Pe("button",{className:"ha-suggestion",type:"button","aria-keyshortcuts":u.suggestedPromptShortcuts?`Control+${g+1}`:void 0,onClick:()=>Zt(a),children:[I("span",{children:a}),u.suggestedPromptShortcuts?Pe("span",{"aria-hidden":"true",className:"ha-suggestion-shortcut",children:[I("kbd",{children:"Ctrl"}),I("kbd",{children:g+1})]}):I(Eg,{"aria-hidden":"true"})]},a))}):null,U?I(Gi,{title:U.componentTitle,onRemove:()=>V(null)}):null,ma?null:I(Dl,{ref:$s,blockedMessageId:s.blockedMessageId,isSendNowDisabled:At,messages:mu,onEdit:ru,onFocusComposer:Xc,onRemove:tu,onReorder:nu,onReorderStateChange:eu,onSendNow:ou}),Pe(Qi,{className:"@container ha-composer","data-controls-revealed":ho||void 0,"data-dictating":ke||void 0,"data-expanded":ke||be?!0:void 0,disabled:u.composerAttachmentContentTypes.length===0,onFilesSelected:ta,onFileIntent:u.composerAttachmentContentTypes.length>0?Qs:void 0,children:[I("textarea",{ref:bt,"aria-label":"Message the assistant",placeholder:u.composerPlaceholder,readOnly:ke,rows:1,value:D,onFocus:Vc,onSelect:a=>$n(u.agentId,!0,a.currentTarget),onChange:a=>{N(a.currentTarget.value),$n(u.agentId,!0,a.currentTarget),Ao(a.currentTarget)},onKeyDown:a=>{if(!ke&&!_l(a,$s.current)&&Wi(a.nativeEvent)){if(a.preventDefault(),Ct&&!br){sa();return}oa(a)}}}),u.composerAttachmentContentTypes.length>0?I("input",{ref:Vs,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??[]);ta(g),a.currentTarget.value=""}}):null,y.length>0?I(Oo,{"aria-label":"Selected attachments",className:"ha-attachments",offset:1,size:24,children:y.map(a=>I(ds,{file:a,onRemove:()=>{P(null),T(g=>g.filter(b=>b!==a))}},`${a.name}-${a.size}-${a.lastModified}`))}):null,u.composerAttachmentContentTypes.length>0?I("button",{"aria-label":"Attach files",className:"ha-attach",type:"button",onClick:()=>Vs.current?.click(),children:I(Dc,{"aria-hidden":"true"})}):null,ke?I("div",{className:"ha-dictation-session",children:Ln?I("span",{className:"ha-dictation-status",role:"status",children:"Transcribing\u2026"}):Pe(cn,{children:[I(Wo,{active:Bc,"aria-hidden":"true",className:"ha-dictation-waveform",height:28,stream:Fc}),I("time",{"aria-label":`Recording duration ${Hr(go)}`,className:"ha-dictation-duration",dateTime:`PT${go}S`,children:Hr(go)})]})}):null,u.permissionShowPicker&&u.tools.length>0&&!ke?I(kr,{"aria-label":"Tool permissions",className:"ha-permission-picker",isDisabled:Xs,value:_e,onChange:Ge}):null,u.composerModelPicker&&!ke?I(xr,{"aria-label":"AI model",className:"ha-model-picker",isDisabled:Xs,options:Io,value:O,placement:u.permissionShowPicker&&u.tools.length>0?"top":"top start",onChange:_}):null,u.composerDictation?Pe("button",{"aria-keyshortcuts":Wt?zi:void 0,"aria-label":ha,"aria-pressed":ke,className:"ha-dictation","data-shortcut":Wt?"\u2303\u21E7D":void 0,"data-tooltip":ya,disabled:!Wt,type:"button",onClick:To,children:[Ln?I(Pg,{"aria-hidden":"true"}):ke?I(xc,{"aria-hidden":"true"}):I(Oc,{"aria-hidden":"true"}),I(Vn,{shortcut:Wt?"\u2303\u21E7D":void 0,children:ya})]}):null,M||u.composerDictation&&fo?I("span",{className:"ha-dictation-error",role:"alert",children:M??fo}):null,Ct&&!br?Pe("button",{"aria-keyshortcuts":gs,"aria-label":hn,className:"ha-send","data-shortcut":"\u21B5","data-tooltip":hn,type:"button",onClick:sa,children:[I(xc,{"aria-hidden":"true"}),I(Vn,{shortcut:"\u21B5",children:hn})]}):Pe("button",{"aria-keyshortcuts":gs,"aria-label":hn,className:"ha-send","data-shortcut":"\u21B5","data-tooltip":hn,disabled:!br||ke,type:"submit",children:[I(wg,{"aria-hidden":"true"}),I(Vn,{shortcut:"\u21B5",children:hn})]})]}),I("div",{className:"ha-composer-footer","data-revealed":!!u.composerDisclaimer||void 0,children:I("div",{className:"ha-composer-footer-content",children:u.composerDisclaimer?I("p",{className:"ha-footnote",children:Po(u.composerDisclaimer)}):null})}),I(_a,{})]})]})}function Ug({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:C,onClientToolDecision:u,onCopy:h,onFeedback:x,onRetry:w,onSelect:A,toolDecisions:O,turnAnchor:_}){let k=ts(p,r,{isStreaming:i}),L=Zl(p.parts),$=p.parts.some(us);Se(()=>{$&&pl()},[$]);let X=d?p.parts.findLastIndex(T=>T.type==="text"):-1,S=p.role==="user"?p.parts.flatMap((T,P)=>T.type==="file"?[I(bs,{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(bs,{file:P},`${p.id}-file-${z}`));if(P.type==="data-component")return ie(I(gl,{component:P.data,exportFormats:o,onAction:C,onSelect:A},P.data.id));if(us(P))return T;let j=Fs(P),B=j?r.get(j):void 0;if(j&&B){let K=P;return K.state!=="approval-requested"||O[K.toolCallId]?T:ie(I(Bg,{decision:O[K.toolCallId],part:K,tool:B,onDecision:ye=>u(j,K,ye)},K.toolCallId))}return T},{items:[],latestContentPartIndex:-1}),R=ii(k,{hasContent:f.length>0,latestContentPartIndex:v}),y=ec(L,{hasContent:f.length>0,isStreaming:i});if(f.length===0&&S.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:[S.length>0?I("div",{"aria-label":"Message attachments",className:"ha-message-attachments",children:S}):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(Jl,{sources:y}),!i&&f.length>0&&e.length>0?I(hl,{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 Bg({decision:e,onDecision:t,part:n,tool:r}){if(n.state!=="approval-requested"||e)return null;let o=r.icon;return I(qa,{"data-tool-status":"approval-requested",icon:o?I(o,{color:r.iconColor,size:16}):void 0,input:n.input,title:r.displayName??r.name,onApprove:()=>t(!0),onDeny:()=>t(!1)})}function Fg({conversationId:e,onRuntimeRevisionStale:t,onTurnAdmitted:n,options:r,runtime:o,tokenManager:s}){let i=Ae(()=>Bi(o),[o]),d=r.apiBaseUrl,l=Ae(()=>Fi(o,()=>Pi({apiBaseUrl:d},s,e,o.runtimeRevision)),[d,e,o,s]),[c,m]=ee(0),[p,C]=ee(0),[u,h]=ee(null),[x,w]=ee(!0),[A,O]=ee(!1),_=ce(null),k=ce(!1),L=_g(),$=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 Tn?(t(e),new Promise(()=>{})):($(),{ticket:""})}},[e,$,t,l]),S=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(xg(M)){$();return}k.current=!0,w(!0),O(!0)}},[$]),v=W(M=>{let T=Vi(M),P=typeof T?.type=="string"?T.type:null;P===Ua&&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=kg({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:S,protocol:i.protocol,query:X,queryDeps:[e,o.runtimeRevision,L,p]});Se(()=>{if(!(u||!x&&!A))return bc($)},[c,u,$,x,A]);let y=W(()=>{_.current=null,k.current=!0,h(null),w(!0),O(!0),C(M=>M+1)},[]);return Se(()=>{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(B){if(B instanceof Tn){t(e);return}if(B instanceof Yn&&!B.retryable){$();return}if(T??=Date.now(),Date.now()-T>=12e4){$();return}z(15e3);return}try{await R.call("renewConnection",[j.ticket],{timeout:15e3}),T=null,z(27e4)}catch{R.reconnect()}};return z(27e4),()=>{M=!0,P!==void 0&&window.clearTimeout(P)}},[R,c,u,e,$,t,l]),{agent:R,connectionEpoch:c,connectionError:u,isHydrating:x,isReconnecting:A,retryConnection:y}}async function _c(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{Dg as default};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
declare const agentThemeSchema: z.ZodEnum<{
|
|
4
|
+
dark: "dark";
|
|
5
|
+
light: "light";
|
|
6
|
+
system: "system";
|
|
7
|
+
}>;
|
|
8
|
+
declare const agentSurfaceVariantSchema: z.ZodEnum<{
|
|
9
|
+
surface: "surface";
|
|
10
|
+
outline: "outline";
|
|
11
|
+
plain: "plain";
|
|
12
|
+
"surface-secondary": "surface-secondary";
|
|
13
|
+
}>;
|
|
14
|
+
declare const agentIdentityIdSchema: z.ZodString;
|
|
15
|
+
declare const agentAuthIdentitySchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
16
|
+
id: z.ZodString;
|
|
17
|
+
type: z.ZodLiteral<"anonymous">;
|
|
18
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
19
|
+
id: z.ZodString;
|
|
20
|
+
type: z.ZodLiteral<"user">;
|
|
21
|
+
}, z.core.$strip>], "type">;
|
|
22
|
+
declare const agentAuthProfileSchema: z.ZodObject<{
|
|
23
|
+
avatarUrl: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodURL>>;
|
|
24
|
+
email: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodEmail>>;
|
|
25
|
+
name: z.ZodOptional<z.ZodString>;
|
|
26
|
+
}, z.core.$strip>;
|
|
27
|
+
/** Server-to-server request for a short-lived browser credential. */
|
|
28
|
+
declare const createAgentAuthTokenRequestSchema: z.ZodObject<{
|
|
29
|
+
anonymousId: z.ZodOptional<z.ZodString>;
|
|
30
|
+
identity: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
31
|
+
id: z.ZodString;
|
|
32
|
+
type: z.ZodLiteral<"anonymous">;
|
|
33
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
34
|
+
id: z.ZodString;
|
|
35
|
+
type: z.ZodLiteral<"user">;
|
|
36
|
+
}, z.core.$strip>], "type">;
|
|
37
|
+
profile: z.ZodOptional<z.ZodObject<{
|
|
38
|
+
avatarUrl: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodURL>>;
|
|
39
|
+
email: z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodEmail>>;
|
|
40
|
+
name: z.ZodOptional<z.ZodString>;
|
|
41
|
+
}, z.core.$strip>>;
|
|
42
|
+
}, z.core.$strip>;
|
|
43
|
+
declare const agentAuthTokenSchema: z.ZodObject<{
|
|
44
|
+
expiresAt: z.ZodNumber;
|
|
45
|
+
token: z.ZodString;
|
|
46
|
+
}, z.core.$strip>;
|
|
47
|
+
declare const agentTokenClaimsSchema: z.ZodObject<{
|
|
48
|
+
agentId: z.ZodString;
|
|
49
|
+
apiKeyId: z.ZodString;
|
|
50
|
+
aud: z.ZodLiteral<"heroui-agent">;
|
|
51
|
+
exp: z.ZodNumber;
|
|
52
|
+
iat: z.ZodNumber;
|
|
53
|
+
iss: z.ZodLiteral<"https://api.heroui.com">;
|
|
54
|
+
jti: z.ZodUUID;
|
|
55
|
+
protocolVersion: z.ZodLiteral<6>;
|
|
56
|
+
sub: z.ZodString;
|
|
57
|
+
}, z.core.$strip>;
|
|
58
|
+
/**
|
|
59
|
+
* How a persisted conversation was started. Rows written before this existed
|
|
60
|
+
* carry no source and are treated as `embed`.
|
|
61
|
+
*/
|
|
62
|
+
declare const AGENT_CONVERSATION_SOURCE: {
|
|
63
|
+
readonly embed: "embed";
|
|
64
|
+
readonly preview: "preview";
|
|
65
|
+
};
|
|
66
|
+
type AgentConversationSource = (typeof AGENT_CONVERSATION_SOURCE)[keyof typeof AGENT_CONVERSATION_SOURCE];
|
|
67
|
+
declare const agentProjectConfigSchema: z.ZodObject<{
|
|
68
|
+
agentId: z.ZodString;
|
|
69
|
+
minimumProtocolVersion: z.ZodLiteral<6>;
|
|
70
|
+
name: z.ZodString;
|
|
71
|
+
protocolVersion: z.ZodLiteral<6>;
|
|
72
|
+
sdkVersion: z.ZodDefault<z.ZodString>;
|
|
73
|
+
suggestedPrompts: z.ZodArray<z.ZodString>;
|
|
74
|
+
surfaceVariant: z.ZodDefault<z.ZodEnum<{
|
|
75
|
+
surface: "surface";
|
|
76
|
+
outline: "outline";
|
|
77
|
+
plain: "plain";
|
|
78
|
+
"surface-secondary": "surface-secondary";
|
|
79
|
+
}>>;
|
|
80
|
+
theme: z.ZodEnum<{
|
|
81
|
+
dark: "dark";
|
|
82
|
+
light: "light";
|
|
83
|
+
system: "system";
|
|
84
|
+
}>;
|
|
85
|
+
}, z.core.$strip>;
|
|
86
|
+
type AgentAuthIdentity = z.infer<typeof agentAuthIdentitySchema>;
|
|
87
|
+
type AgentAuthProfile = z.infer<typeof agentAuthProfileSchema>;
|
|
88
|
+
type AgentAuthToken = z.infer<typeof agentAuthTokenSchema>;
|
|
89
|
+
type CreateAgentAuthTokenRequest = z.infer<typeof createAgentAuthTokenRequestSchema>;
|
|
90
|
+
type AgentTokenClaims = z.infer<typeof agentTokenClaimsSchema>;
|
|
91
|
+
type AgentTheme = z.infer<typeof agentThemeSchema>;
|
|
92
|
+
type AgentSurfaceVariant = z.infer<typeof agentSurfaceVariantSchema>;
|
|
93
|
+
type AgentProjectConfig = z.infer<typeof agentProjectConfigSchema>;
|
|
94
|
+
|
|
95
|
+
export { AGENT_CONVERSATION_SOURCE as A, type CreateAgentAuthTokenRequest as C, type AgentAuthIdentity as a, type AgentAuthProfile as b, type AgentAuthToken as c, type AgentConversationSource as d, type AgentProjectConfig as e, type AgentSurfaceVariant as f, type AgentTheme as g, type AgentTokenClaims as h, agentAuthIdentitySchema as i, agentAuthProfileSchema as j, agentAuthTokenSchema as k, agentIdentityIdSchema as l, agentProjectConfigSchema as m, agentSurfaceVariantSchema as n, agentThemeSchema as o, agentTokenClaimsSchema as p, createAgentAuthTokenRequestSchema as q };
|