@heroui/agent 0.2.0-beta.10 → 0.2.0-beta.11
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/dist/{chunk-5XUOZ2ZC.js → chunk-QDIT4IVA.js} +2 -2
- package/dist/chunk-TV4IIQ5G.js +2 -0
- package/dist/contracts.d.ts +1 -1
- package/dist/contracts.js +1 -1
- package/dist/{embed-runtime-ZZKIK7WA.js → embed-runtime-RJ7JHMFX.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/next.js +1 -1
- package/dist/server.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-A53R5SMW.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{C as tn,a as qe,b as je,d as de,e as ze,h as Ke,i as Ye,j as Qe,m as fe,o as Ze,p as en,u as nn}from"./chunk-
|
|
2
|
-
`),document.head.append(t),()=>t.remove()}return()=>{}}import{Fragment as En,jsx as O,jsxs as vn}from"react/jsx-runtime";var yt=600,bt=5*6e4,Ct="heroui-agent:open:";function we(e){return`${Ct}${e}`}function wt(e){if(typeof window>"u")return!1;try{return window.sessionStorage.getItem(we(e))==="true"}catch{return!1}}function be(e,n){try{n?window.sessionStorage.setItem(we(e),"true"):window.sessionStorage.removeItem(we(e))}catch{}}var Sn;function kn(){return Sn??=import(/* webpackPrefetch: true */"./embed-runtime-
|
|
1
|
+
import{C as tn,a as qe,b as je,d as de,e as ze,h as Ke,i as Ye,j as Qe,m as fe,o as Ze,p as en,u as nn}from"./chunk-TV4IIQ5G.js";import{a as Be}from"./chunk-6ZJJN322.js";import{d as Je,e as Xe}from"./chunk-OA3TG5CS.js";import{useCallback as C,useEffect as w,useEffectEvent as gt,useLayoutEffect as An,useMemo as Ce,useRef as v,useState as p,useSyncExternalStore as Nn}from"react";import{createRoot as ht}from"react-dom/client";import{SparklesFill as Kn}from"@gravity-ui/icons";import{jsx as Bn}from"react/jsx-runtime";function on(e){return Bn(Kn,{...e})}import{jsx as me}from"react/jsx-runtime";function Jn(e){return/\.svg(?:[?#]|$)/i.test(e)||/^data:image\/svg\+xml[;,]/i.test(e)}function rn(e){return`url("${e.replace(/["\\\n\r]/g,encodeURIComponent)}")`}function sn({icon:e}){return e?Jn(e)?me("span",{"aria-hidden":"true",className:"ha-launcher__icon ha-launcher__icon--tinted",style:{WebkitMaskImage:rn(e),maskImage:rn(e)}}):me("img",{alt:"",className:"ha-launcher__icon",src:e}):me(on,{})}function an(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cn(e,n){if(n===void 0)return e;if(!an(e)||!an(n))return n;let t={...e};for(let[r,a]of Object.entries(n))a!==void 0&&(t[r]=r in e?cn(e[r],a):a);return t}function ln(e,n){if(!e)return n;let t={appearance:e.appearance,capabilities:e.capabilities,composer:e.composer,markdown:e.markdown,permissions:e.permissions,responseActions:e.responseActions,startScreen:e.startScreen},r=cn(t,{appearance:n.appearance,capabilities:n.capabilities,composer:n.composer,markdown:n.markdown?{...n.markdown,plugins:void 0}:void 0,permissions:n.permissions,responseActions:n.responseActions,startScreen:n.startScreen});return{...n,...r}}function un(e){return!!e.appearance?.theme?.typography?.fontFamily?.trim()}var dn=1,c=Symbol("invalid");function G(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function S(e){if(e!==void 0)return typeof e=="string"?e:c}function I(e){if(e!==void 0)return typeof e=="boolean"?e:c}function pe(e){if(e!==void 0)return typeof e=="number"&&Number.isFinite(e)?e:c}function M(e){return n=>{if(n!==void 0)return typeof n=="string"&&e.includes(n)?n:c}}function fn(e){if(e===void 0)return;if(typeof e=="string")return e;if(!G(e))return c;let n=S(e.dark),t=S(e.light);return n===c||t===c?c:{...n===void 0?{}:{dark:n},...t===void 0?{}:{light:t}}}function Xn(e){if(e===void 0)return;if(!G(e))return c;let n={};for(let[t,r]of Object.entries(e)){if(typeof r!="string")return c;n[t]=r}return n}function Yn(e){if(e!==void 0)return!Array.isArray(e)||e.some(n=>typeof n!="string")?c:e}function b(e,n){if(e===void 0||!G(e))return c;let t={};for(let[r,a]of Object.entries(n)){let l=a(e[r]);if(l===c)return c;l!==void 0&&(t[r]=l)}return t}function T(e){return e===c?void 0:e}var Qn=["accent","background","foreground","overlay","surface","surfaceSecondary","tooltip"];function Zn(e){return b(e,{launcher:n=>n===void 0?void 0:b(n,{background:fn,icon:S,position:M(["bottom-left","bottom-right"]),style:Xn}),panel:n=>n===void 0?void 0:b(n,{expandable:I,expanded:I,initialHeight:t=>t===void 0||typeof t=="string"?t:pe(t),initialWidth:t=>t===void 0||typeof t=="string"?t:pe(t)}),theme:n=>n===void 0?void 0:b(n,{colorScheme:M(["dark","light","system"]),colors:t=>t===void 0?void 0:b(t,Object.fromEntries(Qn.map(r=>[r,fn]))),designTheme:M(["base","brutalism","glass","mouve"]),radius:M(["pill","round","sharp","soft"]),typography:t=>t===void 0?void 0:b(t,{baseSize:pe,fontFamily:S})}),viewMode:M(["floating","sidebar"])})}function et(e){return b(e,{attachments:n=>{if(n===void 0||n===!1)return n;if(!Array.isArray(n))return c;let t=n.filter(r=>typeof r=="string"&&Ke(r));return t.length===n.length?t:c},defaultModel:S,dictation:I,disclaimer:n=>n===!1?!1:S(n),modelPicker:I,placeholder:S})}function nt(e){return b(e,{animated:n=>{if(n===void 0||n===!1)return n;if(!G(n))return c;let t=M(["blurIn","fadeIn","slideUp"])(n.animation);return t===c||t===void 0?c:{...n,animation:t}},caret:n=>n===!1?!1:M(["block","circle"])(n)})}function tt(e){if(e===void 0||e===!1)return e;if(!Array.isArray(e))return c;let n=["copy","feedback","retry"],t=e.filter(r=>typeof r=="string"&&n.includes(r));return t.length===e.length?t:c}function Z(e){if(!G(e)||e.version!==dn)return null;let n=e.revision;if(typeof n!="string"||!n)return null;let t=T(Zn(e.appearance)),r=T(b(e.capabilities,{imageSearch:I,newsSearch:I,webSearch:I})),a=T(et(e.composer)),l=T(nt(e.markdown)),f=T(b(e.permissions,{defaultMode:M(["ask","auto","full"]),showPicker:I})),u=T(tt(e.responseActions)),m=T(b(e.startScreen,{greeting:S,promptShortcuts:I,prompts:Yn})),k=T(b(e.webfont,{familyName:g=>typeof g=="string"&&g?g:c,fontFaceUrl:S,stylesheetUrl:S}));return{...t?{appearance:t}:{},...r?{capabilities:r}:{},...a?{composer:a}:{},...l?{markdown:l}:{},...f?{permissions:f}:{},...u===void 0?{}:{responseActions:u},...m?{startScreen:m}:{},...k?{webfont:k}:{},revision:n,version:dn}}function ge(e){return`heroui-agent:config:${e}`}var mn=1;function pn(e){try{let n=window.localStorage.getItem(ge(e));if(!n)return null;let t=JSON.parse(n);if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let a=t;if(a.cacheVersion===mn&&typeof a.cachedAt=="number"&&Number.isFinite(a.cachedAt)){let l=Z(a.config);return l?{cachedAt:a.cachedAt,config:l,legacy:!1}:null}}let r=Z(t);return r?{cachedAt:0,config:r,legacy:!0}:null}catch{return null}}function he(e,n,t=Date.now()){try{let r={cacheVersion:mn,cachedAt:t,config:n};window.localStorage.setItem(ge(e),JSON.stringify(r))}catch{}}function gn(e){try{window.localStorage.removeItem(ge(e))}catch{}}async function hn(e,n,t={}){try{let r=await fetch(`${e}/v1/agents/${encodeURIComponent(n)}/appearance`,{headers:t.revision?{"If-None-Match":`"${t.revision}"`}:{},...t.signal?{signal:t.signal}:{}});if(r.status===304)return{status:"not-modified"};if(r.status===404||r.status===410)return{status:"missing"};if(!r.ok)return{status:"unavailable"};let a=Z(await r.json());return a?{config:a,status:"ok"}:{status:"unavailable"}}catch{return{status:"unavailable"}}}import{ChevronDown as ot,Microphone as rt,Plus as it,ShieldCheck as st}from"@gravity-ui/icons";import{useEffect as at,useRef as ct}from"react";import{Fragment as Cn,jsx as h,jsxs as ye}from"react/jsx-runtime";var lt={ask:"Ask for approval",auto:"Approve for me",full:"Full access"};function bn({onFileDialogActiveChange:e,onIntent:n,options:t}){return{end:h(dt,{options:t}),footer:t.composerDisclaimer?h("p",{className:"ha-footnote",children:Be(t.composerDisclaimer)}):null,start:t.composerAttachmentContentTypes.length>0?h(ut,{accept:t.composerAttachmentAccept,agentId:t.agentId,onFileDialogActiveChange:e,onIntent:n}):null}}function ut({accept:e,agentId:n,onFileDialogActiveChange:t,onIntent:r}){let a=ct(null);return at(()=>{let l=a.current,f,u=()=>t(!1),m=()=>{f=window.setTimeout(u,0)};return l?.addEventListener("cancel",u),window.addEventListener("focus",m),()=>{l?.removeEventListener("cancel",u),window.removeEventListener("focus",m),window.clearTimeout(f)}},[t]),ye(Cn,{children:[h("input",{ref:a,multiple:!0,accept:e,"aria-label":"Choose files to attach",className:"ha-file-input",type:"file",onChange:l=>{en(n,Array.from(l.currentTarget.files??[])),l.currentTarget.value="",t(!1),r()}}),h("button",{"aria-label":"Attach files",className:"ha-attach",type:"button",onClick:()=>{t(!0),a.current?.click()},children:h(it,{"aria-hidden":"true"})})]})}function dt({options:e}){let n=e.composerDefaultModel??Je,t=Xe.find(r=>r.id===n)?.label??n;return ye(Cn,{children:[e.permissionShowPicker&&e.tools.length>0?h(yn,{icon:h(st,{"aria-hidden":"true",className:"aui-permission-picker__trigger-icon"}),kind:"permission",label:lt[e.permissionDefaultMode],tone:e.permissionDefaultMode==="full"?"warning":void 0}):null,e.composerModelPicker?h(yn,{kind:"model",label:t}):null,e.composerDictation?h("button",{disabled:!0,"aria-label":"Dictate message",className:"ha-dictation",type:"button",children:h(rt,{"aria-hidden":"true"})}):null]})}function yn({icon:e,kind:n,label:t,tone:r}){let a=`aui-${n}-picker`;return h("div",{className:`${a} ha-${n}-picker`,"data-tone":r,children:ye("button",{disabled:!0,"aria-label":n==="model"?"AI model":"Tool permissions",className:`${a}__trigger ha-shell-picker-trigger`,type:"button",children:[e,h("span",{className:`${a}__value`,children:t}),h(ot,{"aria-hidden":"true",className:`${a}__indicator`})]})})}var ft=[".woff2",".woff",".ttf",".otf",".eot"];function mt(e){return`heroui-agent-font-${e.familyName.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`}function pt(e){let n=e.includes(":vf@")||e.includes("-wght-")||e.includes("-opsz-");return e.endsWith(".woff")?"woff":e.endsWith(".ttf")?"truetype":e.endsWith(".otf")?"opentype":n?"woff2-variations":"woff2"}function wn(e,n){try{let t=new URL(e);if(t.protocol!=="https:")return!1;if(!n)return!0;let r=t.pathname.toLowerCase();return ft.some(a=>r.endsWith(a))}catch{return!1}}function Rn(e){if(!e||typeof document>"u")return()=>{};let n=mt(e);if(document.getElementById(n))return()=>{};if(e.stylesheetUrl&&wn(e.stylesheetUrl,!1)){let t=document.createElement("link");return t.id=n,t.rel="stylesheet",t.href=e.stylesheetUrl,document.head.append(t),()=>t.remove()}if(e.fontFaceUrl&&wn(e.fontFaceUrl,!0)){let t=document.createElement("style"),r=e.fontFaceUrl.includes(":vf@")||e.fontFaceUrl.includes("-wght-")||e.fontFaceUrl.includes("-opsz-");return t.id=n,t.textContent=["@font-face {",` font-family: '${e.familyName.replaceAll("'","")}';`," font-style: normal;"," font-display: swap;",` font-weight: ${r?"100 900":"400"};`,` src: url(${e.fontFaceUrl}) format('${pt(e.fontFaceUrl)}');`,"}"].join(`
|
|
2
|
+
`),document.head.append(t),()=>t.remove()}return()=>{}}import{Fragment as En,jsx as O,jsxs as vn}from"react/jsx-runtime";var yt=600,bt=5*6e4,Ct="heroui-agent:open:";function we(e){return`${Ct}${e}`}function wt(e){if(typeof window>"u")return!1;try{return window.sessionStorage.getItem(we(e))==="true"}catch{return!1}}function be(e,n){try{n?window.sessionStorage.setItem(we(e),"true"):window.sessionStorage.removeItem(we(e))}catch{}}var Sn;function kn(){return Sn??=import(/* webpackPrefetch: true */"./embed-runtime-RJ7JHMFX.js").then(e=>e.default),Sn}var D=new Map,Re=new Set;function Tn(e){return e?D.get(e):[...D.values()][D.size-1]}function In(){for(let e of Re)e()}function Rt(e){return Re.add(e),()=>Re.delete(e)}function At(e){let n=window.matchMedia?.("(prefers-color-scheme: dark)");return n?.addEventListener?.("change",e),()=>n?.removeEventListener?.("change",e)}function St(){return window.matchMedia?.("(prefers-color-scheme: dark)").matches===!0}function U(e,n,...t){let r=Tn(e);if(!r){console.warn("HeroUI Agent is not mounted yet. Add <HeroUIAgent /> to your layout.");return}let a=r[n];a(...t)}function kt(e,n,t){let[r]=p(()=>!t||typeof window>"u"?null:pn(e)),[a,l]=p(()=>{if(!t)return{config:null,presentationReady:!0};let f=r?Date.now()-r.cachedAt:Number.POSITIVE_INFINITY,u=r!==null&&!r.legacy&&f>=0&&f<=bt;return{config:u?r.config:null,presentationReady:u}});return w(()=>{if(!t)return;let f=new AbortController,u=!0,m=g=>{l(q=>q.presentationReady?q:{config:g,presentationReady:!0})},k=window.setTimeout(()=>{u&&(f.abort(),m(r?.config??null))},yt);return hn(n,e,{...r?.config.revision?{revision:r.config.revision}:{},signal:f.signal}).then(g=>{if(!(!u||f.signal.aborted)){if(g.status==="ok"){he(e,g.config),m(g.config);return}if(g.status==="not-modified"){r&&he(e,r.config),m(r?.config??null);return}if(g.status==="missing"){gn(e),m(null);return}m(r?.config??null)}}).finally(()=>{!u||f.signal.aborted||window.clearTimeout(k)}),()=>{u=!1,f.abort(),window.clearTimeout(k)}},[n,r,t,e]),t?a:{config:null,presentationReady:!0}}function io(e){let n=C(()=>Tn(e)?.ready??!1,[e]),t=Nn(Rt,n,()=>!1);return Ce(()=>({hide:()=>U(e,"hide"),newConversation:r=>U(e,"newConversation",r),preload:()=>U(e,"preload"),ready:t,refreshAuth:()=>U(e,"refreshAuth"),show:()=>U(e,"show"),shutdown:()=>U(e,"shutdown"),toggle:()=>U(e,"toggle")}),[e,t])}function so(e){let n=`${e.agentId}\0${e._api?.baseUrl??""}\0${e.remoteConfig!==!1}`;return O(It,{...e},n)}function It(e){let{_api:n,agentId:t,appearance:r,capabilities:a,componentExports:l,composer:f,context:u,getAuthToken:m,markdown:k,onFeedback:g,onReady:q,permissions:Mn,preload:On,remoteConfig:Pn=!0,reopenOnRefresh:Ae,responseActions:_n,showLauncher:Ln,startNewConversationOnOpen:Un,startScreen:xn,tools:Se}=e,j=k?.plugins,Fn=(n?.baseUrl??"https://api.heroui.com").replace(/\/$/,""),{config:ke,presentationReady:x}=kt(t,Fn,Pn),Ie=JSON.stringify({_api:n,appearance:r,capabilities:a,componentExports:l,composer:f,markdown:k?{...k,plugins:void 0}:void 0,permissions:Mn,preload:On,remote:ke,reopenOnRefresh:Ae,responseActions:_n,showLauncher:Ln,startNewConversationOnOpen:Un,startScreen:xn}),o=Ce(()=>{let{remote:i,...s}=JSON.parse(Ie),d=ln(i,{...s,agentId:t,getAuthToken:m});return tn({...d,context:u,markdown:d.markdown?{...d.markdown,plugins:j}:j?{plugins:j}:void 0,onFeedback:g,tools:Se})},[u,m,j,g,t,Ie,Se]),z=Ce(()=>new qe(t,m),[t,m]),ve=un(e),Ee=ke?.webfont;w(()=>{if(!ve)return Rn(Ee)},[ve,Ee]);let[K]=p(()=>Ae===!0&&wt(t)),[ee,V]=p(K),[P,$n]=p(1),[Ne,Te]=p(1),[Me,Oe]=p(!1),[B,Hn]=p(K||o.startNewConversationOnOpen?null:void 0),[E,Dn]=p(null),[J,Vn]=p(null),[Pe,Wn]=p(!1),[ne,te]=p(!1),[Gn,_e]=p(null),oe=v(1),Le=v(null),re=v(!1),ie=v(null),Ue=v(null),F=v(K),se=v(null),X=v(null),ae=v([]),qn=Nn(At,St,()=>!1),ce=o.designTheme==="base"?null:`${o.designTheme}-${o.colorScheme==="system"?qn?"dark":"light":o.colorScheme}`,_=x&&Gn===P&&J!==null,y=x&&ee,[Y,jn]=p(K||o.preload),R=C(()=>jn(!0),[]),[W,$]=p(!1),[xe,Fe]=p(!1),le=C(()=>$(!0),[]);w(()=>{if(!W||!E)return;let i=()=>{queueMicrotask(()=>{let s=E.querySelector(".ha-composer:not([hidden] *)");s&&Ze(s,document.activeElement)||$(!1)})};return E.addEventListener("focusout",i),()=>E.removeEventListener("focusout",i)},[W,E]),w(()=>{Y&&z.get().catch(()=>{})},[Y,z]),w(()=>{o.reopenOnRefresh?be(o.agentId,ee):be(o.agentId,!1)},[ee,o.agentId,o.reopenOnRefresh]),w(()=>{if(!Y)return;if(!x){kn().catch(()=>{});return}let i=!0;return kn().then(s=>{i&&Vn(()=>s)}).catch(()=>{}),()=>{i=!1}},[x,Y]),w(()=>{if(!y||o.viewMode!=="sidebar"||window.innerWidth<640)return;let i=document.documentElement,s=i.style.marginRight,d=i.style.transition,A=window.matchMedia("(prefers-reduced-motion: reduce)").matches,ue=Math.min(de(o.agentId,window.innerWidth),window.innerWidth);return A||(i.style.transition=[d,"margin-right .28s cubic-bezier(.2,.8,.2,1)"].filter(Boolean).join(", ")),i.style.marginRight=`${ue}px`,()=>{i.style.marginRight=s,window.setTimeout(()=>{i.style.transition=d},300)}},[y,o.agentId,o.viewMode]),w(()=>{let i=document.createElement("div"),s=document.createElement("div");i.dataset.herouiAgent=o.agentId,s.className="ha-root",se.current=i,ie.current=s,X.current=ht(s),i.append(s),document.body.append(i);let d=!0;return queueMicrotask(()=>{d&&Dn(s)}),()=>{d=!1,fe(o.agentId,!1);let A=X.current;ie.current=null,se.current=null,X.current=null,ae.current=[],queueMicrotask(()=>{A?.unmount(),i.remove()})}},[o.agentId]),An(()=>{let i=ie.current,s=se.current;if(!i||!s)return;i.className=ce?`ha-root ${ce}`:"ha-root",i.dataset.theme=o.colorScheme,i.dataset.viewMode=o.viewMode,i.dataset.position=o.launcherPosition,s.dataset.open=y?"true":"false",s.dataset.viewMode=o.viewMode,s.dataset.position=o.launcherPosition,o.launcherOffset?(s.style.setProperty("--ha-launcher-x",`${o.launcherOffset.x}px`),s.style.setProperty("--ha-launcher-y",`${o.launcherOffset.y}px`)):(s.style.removeProperty("--ha-launcher-x"),s.style.removeProperty("--ha-launcher-y")),o.viewMode==="sidebar"&&s.style.setProperty("--ha-sidebar-width",`${de(o.agentId,window.innerWidth)}px`);let d={...o.themeStyle,...o.panelStyle};for(let A of ae.current)A in d||i.style.removeProperty(A);for(let[A,ue]of Object.entries(d))i.style.setProperty(A,ue);ae.current=Object.keys(d)},[ce,y,o.colorScheme,o.agentId,o.launcherOffset,o.launcherPosition,o.panelStyle,o.themeStyle,o.viewMode,E]);let N=C(i=>{fe(o.agentId,!1),Fe(!1),_e(null),Hn(i);let s=oe.current+1;oe.current=s,$n(s)},[o.agentId]),$e=C(i=>{oe.current===i&&(Wn(!0),_e(i))},[]),zn=gt(()=>q?.());w(()=>{!_||Ue.current===P||(Ue.current=P,zn())},[P,_]);let L=C(()=>{F.current=!1,re.current=!0,V(!1),$(!1),N(o.startNewConversationOnOpen?null:void 0)},[o.startNewConversationOnOpen,N]);w(()=>{y||!_||!re.current||(re.current=!1,requestAnimationFrame(()=>Le.current?.focus()))},[y,_]);let H=C(()=>{F.current=!0,V(!0),R()},[R]),He=R,Q=C(i=>{let s=i?Ye(i):null;s&&Qe(o.agentId,s),F.current=!0,V(!0),$(!1),R(),N(null)},[o.agentId,N,R]),De=C(i=>{F.current=!0,V(!0),$(!1),R(),N(i)},[N,R]),Ve=C(()=>{y||F.current?L():H()},[L,y,H]),We=C(()=>{te(!1),Oe(!1),Te(i=>i+1)},[]),Ge=C(()=>{let i=[`heroui-agent:anonymous:${o.agentId}`,`heroui-agent:conversation:${o.agentId}:`,`heroui-agent:history:${o.agentId}:`];for(let s=localStorage.length-1;s>=0;s-=1){let d=localStorage.key(s);d&&i.some(A=>d.startsWith(A))&&localStorage.removeItem(d)}F.current=!1,te(!1),V(!1),$(!1),be(o.agentId,!1),Oe(!0),Te(s=>s+1),N(),window.setTimeout(()=>{import("./composer-draft-NSKK65F3.js").then(({clearAgentComposerDraftsForProject:s})=>s(o.agentId)).catch(()=>{})},0)},[o.agentId,N]);return w(()=>{let i={hide:L,newConversation:Q,preload:He,ready:_,refreshAuth:We,show:H,shutdown:Ge,toggle:Ve};return D.set(o.agentId,i),In(),()=>{D.get(o.agentId)===i&&(D.delete(o.agentId),In())}},[L,Q,o.agentId,He,_,We,H,Ge,Ve]),An(()=>{let i=X.current;if(!E||!i)return;let s=bn({onFileDialogActiveChange:Fe,onIntent:R,options:o});i.render(vn(En,{children:[x&&o.showLauncher&&!y?vn("button",{ref:Le,"aria-expanded":!1,"aria-haspopup":"dialog",className:"ha-launcher",style:o.launcherStyle,type:"button","aria-label":ne?"Open data assistant, unread messages":"Open data assistant",onClick:H,children:[O(sn,{icon:o.launcherIcon}),ne?O("span",{"aria-hidden":"true",className:"ha-launcher__unread"}):null]}):null,J&&!xe?O(J,{composerControlsRevealed:W,conversationEpoch:P,identityEpoch:Ne,identityReset:Me,open:y,options:o,requestedConversationId:B,shellComposerEndSlot:s.end,shellComposerFooterSlot:s.footer,showReadyLoader:!Pe&&B!==null,tokenManager:z,onClose:L,onComposerControlsReveal:le,onNewConversation:Q,onReady:$e,onSelectConversation:De,onUnreadChange:te}):O(ze,{agentId:o.agentId,defaultExpanded:o.panelExpanded,expandable:o.panelExpandable,historySlot:O(En,{}),modal:o.viewMode!=="sidebar",name:"Data assistant",open:y,onClose:L,children:B===null?O(nn,{composerConnecting:!0,agentId:o.agentId,composerControlsAvailable:o.composerControlsAvailable,composerControlsRevealed:W,composerEndSlot:s.end,composerFooterSlot:s.footer,composerStartSlot:s.start,greeting:o.greeting,placeholder:o.composerPlaceholder,suggestedPrompts:o.suggestedPrompts??[],onComposerControlsReveal:le,onIntent:R},`shell-${P}`):O(je,{})})]}))},[J,W,xe,P,$e,ne,Pe,L,Ne,Me,y,Q,o,E,_,x,B,R,le,De,H,z]),null}export{io as a,so as b};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as ce,e as de,f as ue}from"./chunk-2XBFFSW2.js";import{jsx as We,jsxs as Ue}from"react/jsx-runtime";function ht({indicator:e,label:t="Loading agent\u2026"}){return Ue("div",{"aria-live":"polite",className:"ha-agent-loading",role:"status",children:[e,We("span",{children:t})]})}import{jsx as me,jsxs as Be}from"react/jsx-runtime";function U({children:e,shortcut:t}){return Be("span",{"aria-hidden":"true",className:"ha-control-tooltip",children:[me("span",{children:e}),t?me("kbd",{className:"ha-control-tooltip__shortcut",children:t}):null]})}import{ChevronsCollapseUpRight as $e,ChevronsExpandUpRight as Ve}from"@gravity-ui/icons";import{useCallback as he,useEffect as B,useEffectEvent as Xe,useRef as Q,useState as G}from"react";function pe(e){return`heroui-agent:sidebar-width:${e}`}function Z(e,t){let n=Math.min(720,Math.floor(t*.9)),o=Math.max(n,320);return Math.min(Math.max(Math.round(e),320),o)}function ge(e,t){let n=Number.NaN;try{n=Number(localStorage.getItem(pe(e))??Number.NaN)}catch{}return Z(Number.isFinite(n)?n:420,t)}function J(e,t){try{localStorage.setItem(pe(e),String(Math.round(t)))}catch{}}import{jsx as d,jsxs as I}from"react/jsx-runtime";function Et({actionsSlot:e,agentId:t,children:n,defaultExpanded:o=!1,expandable:l=!0,expandedSidebarSlot:f,expandedTitle:y,historySlot:a,keepMounted:c=!1,modal:p,name:S,onClose:E,onNewConversation:w,open:h}){let v=Q(null),u=Q(0),[k,q]=G(!1),O=Xe(E),[g,H]=G(o),P=!p&&!k,A=p||k||P&&g,[R,M]=G(!1),i=!k&&l,m=P&&g&&f;return B(()=>{let r=window.matchMedia?.("(max-width: 639px)");if(!r)return;let T=()=>q(r.matches);return T(),r.addEventListener?.("change",T),()=>r.removeEventListener?.("change",T)},[]),B(()=>{if(!R)return;let r=v.current;if(!r)return;let T=()=>M(!1),C=L=>{let{propertyName:F,target:Y}=L;Y===r&&(F!=="width"&&F!=="height"||T())},D=window.setTimeout(T,600);return r.addEventListener("transitionend",C),()=>{window.clearTimeout(D),r.removeEventListener("transitionend",C)}},[R]),B(()=>{if(!h)return;let r=v.current;if(!r)return;let T=document.activeElement instanceof HTMLElement?document.activeElement:null;r.open||(A&&typeof r.showModal=="function"?r.showModal():!A&&typeof r.show=="function"?r.show():r.open=!0);let C=document.documentElement,D=window.scrollX,L=window.scrollY,F=C.style.overflow,Y=document.body.style.overflow,Ie=document.body.style.position,_e=document.body.style.top,Oe=document.body.style.left,De=document.body.style.right,Le=document.body.style.width;A&&(C.style.overflow="hidden",document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`${-L}px`,document.body.style.left=`${-D}px`,document.body.style.right="0",document.body.style.width="100%");let Fe=r.querySelector("button,textarea,input,[tabindex]:not([tabindex='-1'])");r.contains(document.activeElement)||Fe?.focus();let re=b=>{if(!A&&b.key==="Escape"){if(fe(r)){u.current=Date.now(),b.preventDefault(),b.stopPropagation();return}b.preventDefault(),O();return}if(!A||b.key!=="Tab")return;let W=Array.from(r.querySelectorAll("button:not(:disabled),textarea:not(:disabled),input:not(:disabled),[tabindex]:not([tabindex='-1'])"));if(W.length===0)return;let ae=W[0],ie=W[W.length-1],se=r.getRootNode(),le=se instanceof ShadowRoot?se.activeElement:document.activeElement;b.shiftKey&&le===ae?(b.preventDefault(),ie.focus()):!b.shiftKey&&le===ie&&(b.preventDefault(),ae.focus())};return r.addEventListener("keydown",re),()=>{r.removeEventListener("keydown",re),typeof r.close=="function"?r.close():r.open=!1,C.style.overflow=F,document.body.style.overflow=Y,document.body.style.position=Ie,document.body.style.top=_e,document.body.style.left=Oe,document.body.style.right=De,document.body.style.width=Le,A&&window.scrollTo(D,L),document.activeElement===document.body&&T?.focus()}},[A,h]),!h&&!c?null:I("dialog",{ref:v,"aria-label":S,"aria-modal":A,className:"ha-panel","data-agent-overlay-root":"","data-expanded":!k&&g?"true":void 0,"data-expanded-sidebar":m?"true":void 0,"data-resizing":R?"true":void 0,hidden:!h,onCancel:r=>{if(r.preventDefault(),Date.now()-u.current<350||fe(v.current)){u.current=Date.now();return}E()},children:[P&&!g?d(je,{agentId:t,panelRef:v}):null,m?d("aside",{"aria-label":"Chat history",className:"ha-expanded-sidebar",children:f}):null,I("div",{className:"ha-panel-main",children:[I("header",{className:"ha-header",children:[m?d("span",{className:"ha-session-title ha-expanded-chat-title",children:y??S}):a??d("strong",{children:S}),I("div",{className:"ha-header-actions",children:[m?null:e??(w?d("button",{"aria-label":"New chat",className:"ha-icon-button ha-new-chat-button",type:"button",onClick:w,children:d(Ye,{})}):null),i?d("button",{"aria-expanded":g,"aria-label":g?"Collapse assistant":"Expand assistant",className:"ha-expand-button ha-icon-button",type:"button",onClick:()=>{M(!0),H(r=>!r)},children:g?d($e,{"aria-hidden":"true"}):d(Ve,{"aria-hidden":"true"})}):null,I("button",{"aria-keyshortcuts":"Escape","aria-label":"Close assistant",className:"ha-close-button ha-icon-button","data-shortcut":"ESC","data-tooltip":"Close assistant",type:"button",onClick:E,children:[d(qe,{}),d(U,{shortcut:"ESC",children:"Close assistant"})]})]})]}),n,d("div",{className:"ha-overlay-portal","data-agent-overlay-portal":""})]})]})}function fe(e){let t=e?.querySelector(['[data-slot$="-popover"]','[data-slot="agent-ui-image-modal"]','[data-slot="modal-dialog"]',".ha-feedback-popover"].join(","));return t?(t.querySelector('button[aria-label="Dismiss"]')?.click(),!0):!1}function je({agentId:e,panelRef:t}){let[n,o]=G(420),l=Q(null),f=he(a=>{let c=t.current,p=c?.getRootNode();(p instanceof ShadowRoot?p.host:c?.closest("[data-heroui-agent]"))?.style.setProperty("--ha-sidebar-width",`${a}px`),window.innerWidth>=640&&(document.documentElement.style.marginRight=`${Math.min(a,window.innerWidth)}px`),o(a)},[t]);B(()=>{o(ge(e,window.innerWidth))},[e]);let y=he((a,c)=>{let p=Z(a,window.innerWidth);return f(p),c&&J(e,p),p},[f,e]);return d("div",{"aria-label":"Resize assistant panel","aria-orientation":"vertical","aria-valuemax":720,"aria-valuemin":320,"aria-valuenow":n,className:"ha-resize-handle",role:"separator",tabIndex:0,onKeyDown:a=>{let c=a.key==="ArrowLeft"?24:a.key==="ArrowRight"?-24:0;c!==0&&(a.preventDefault(),y(n+c,!0))},onPointerCancel:a=>{let c=l.current;c&&(l.current=null,delete a.currentTarget.dataset.resizing,t.current&&delete t.current.dataset.dragResizing,document.documentElement.style.transition=c.pageTransition,y(c.startWidth,!1))},onPointerDown:a=>{a.button!==0&&a.pointerType==="mouse"||(a.preventDefault(),a.currentTarget.setPointerCapture(a.pointerId),a.currentTarget.dataset.resizing="true",l.current={currentWidth:n,pageTransition:document.documentElement.style.transition,startWidth:n,startX:a.clientX},document.documentElement.style.transition="none",t.current&&(t.current.dataset.dragResizing="true"))},onPointerMove:a=>{let c=l.current;c&&(c.currentWidth=y(c.startWidth+(c.startX-a.clientX),!1))},onPointerUp:a=>{let c=l.current;c&&(l.current=null,delete a.currentTarget.dataset.resizing,t.current&&delete t.current.dataset.dragResizing,a.currentTarget.releasePointerCapture(a.pointerId),document.documentElement.style.transition=c.pageTransition,J(e,c.currentWidth))}})}function qe(){return d("svg",{"aria-hidden":"true",fill:"none",height:"18",viewBox:"0 0 18 18",width:"18",children:d("path",{d:"m4.25 4.25 9.5 9.5m0-9.5-9.5 9.5",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"1.6"})})}function Ye(){return d("svg",{"aria-hidden":"true",fill:"none",height:"18",viewBox:"0 0 18 18",width:"18",children:d("path",{d:"M9 4v10M4 9h10",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"1.6"})})}function Ae(e){let t=performance.now(),n=Date.now(),o=e.trim();return o?{messageId:crypto.randomUUID(),prompt:o,startedAt:t,startedAtWallClock:n,submitted:!0}:null}var N=new Map,z=new Map,Ze=10080*60*1e3,K=new Map;function be(e){return`heroui-agent:shell-draft:${e}:composer-draft:v1`}function ee(e,t){try{let n=be(e);t.trim()?localStorage.setItem(n,JSON.stringify({prompt:t,savedAt:Date.now()})):localStorage.removeItem(n)}catch{}}function Je(e){let t=be(e);try{let n=JSON.parse(localStorage.getItem(t)??"null");if(n&&typeof n.prompt=="string"&&n.prompt.trim()&&typeof n.savedAt=="number"&&Date.now()-n.savedAt<=Ze)return n.prompt;localStorage.removeItem(t)}catch{}return""}function $(e,t){if(!t.prompt.trim()&&!t.submitted){N.delete(e),ee(e,"");return}N.set(e,t),t.submitted||ee(e,t.prompt)}function te(e){let t=N.get(e);if(t)return t;let n=Je(e);return n?{prompt:n,submitted:!1}:void 0}function ye(e,t,n){let o=N.get(e);!o?.submitted||o.messageId!==t||o.firstFeedbackPaintedAt!==void 0||N.set(e,{...o,firstFeedbackPaintedAt:n})}function Ct(e){let t=te(e);return N.delete(e),ee(e,""),t}function _(e,t,n){t?K.set(e,[n?.selectionStart??0,n?.selectionEnd??0,n?.selectionDirection??"none"]):K.delete(e)}function ve(e,t){let n=K.get(e);if(!n||!t)return;t.focus({preventScroll:!0});let o=Math.min(n[0],t.value.length),l=Math.min(n[1],t.value.length);t.setSelectionRange(o,l,n[2]),K.set(e,[o,l,n[2]])}function Te(e,t){return t instanceof Node?e.contains(t)||e.closest(".ha-composer-wrap")?.querySelector(".ha-footnote")?.contains(t)===!0||e.closest(".ha-root")?.querySelector(".ha-overlay-portal")?.contains(t)===!0:!1}function Nt(e,t){t.length===0?z.delete(e):z.set(e,t)}function Qe(e){return z.get(e)??[]}function Ht(e){let t=Qe(e);return z.delete(e),t}function we(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function et(e){let t=getComputedStyle(e),n=Number.parseFloat(t.lineHeight);if(Number.isFinite(n)&&n>0)return n;let o=Number.parseFloat(t.fontSize);return Number.isFinite(o)&&o>0?o*1.2:20}function tt(e){let t=getComputedStyle(e);return we(t.paddingTop)+we(t.paddingBottom)}function nt(e){let t=e.style.height,n=e.style.minHeight,o=e.style.maxHeight;e.style.height="0px",e.style.minHeight="0px",e.style.maxHeight="none";let l=e.scrollHeight;return e.style.height=t,e.style.minHeight=n,e.style.maxHeight=o,l}function ot(e){if(e.value.includes(`
|
|
2
|
+
`))return!0;if(e.clientWidth===0)return!1;let t=nt(e),n=tt(e),o=et(e);return Math.max(0,t-n)>o*1.5}function ne(e,{hasAttachments:t=!1,maxHeight:n=120}={}){if(!e)return!1;let o=e.value.length>0;return t||o&&ot(e)?(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,n)}px`,!0):(e.style.height="auto",!1)}import{jsx as oe,jsxs as xe}from"react/jsx-runtime";var rt="https://heroui.pro/?utm_source=heroui-agent&utm_medium=referral&utm_campaign=powered-by-hero";function Se(){return xe("a",{"aria-label":"Powered by HeroUI Pro (opens in a new tab)",className:"ha-powered-by",href:rt,rel:"noopener noreferrer",target:"_blank",children:[oe("span",{children:"Powered by"}),xe("svg",{"aria-hidden":"true",className:"ha-powered-by-logo",fill:"none",viewBox:"0 0 140 44",children:[oe("path",{d:"M.678 11.385V24.04c0 .599.307 1.155.813 1.471l8.628 5.396c1.15.719 2.639-.11 2.639-1.47V18.798c0-.612.322-1.18.847-1.491l5.263-3.13v27.267c0 1.355 1.48 2.186 2.63 1.476l8.905-5.497a1.72 1.72 0 0 0 .822-1.476V9.765c0-1.349-1.467-2.18-2.618-1.484l-9.74 5.897V2.556c0-1.345-1.46-2.177-2.61-1.488L1.52 9.897a1.72 1.72 0 0 0-.842 1.488Z",fill:"currentColor"}),oe("path",{d:"M63.876 24.071c0-3.59-1.468-5.246-4.405-5.246-3.363 0-5.732 2.255-5.732 7.316v11.595h-6.063V5.528h6.063v11.779c1.468-2.393 3.884-3.59 7.2-3.59 5.637 0 8.953 3.451 8.953 9.25v14.769h-6.016V24.071ZM84.9 38.473c-7.533 0-12.317-4.877-12.317-12.378 0-7.408 4.737-12.378 12.317-12.378 8.195 0 12.648 5.798 11.416 13.942H78.647c.331 3.865 2.605 6.075 6.253 6.075 2.984 0 4.784-1.52 5.258-3.037h6.016c-.947 4.509-5.115 7.776-11.274 7.776ZM78.789 23.657h11.653c-.047-3.175-2.132-5.338-5.685-5.338-3.174 0-5.4 1.84-5.968 5.338ZM99.623 20.344c0-3.82 2.131-5.89 6.205-5.89h7.77v4.97h-7.912v18.312h-6.063V20.344ZM126.863 38.473c-7.674 0-12.553-4.924-12.553-12.378 0-7.454 4.879-12.378 12.553-12.378 7.58 0 12.459 4.924 12.459 12.378 0 7.454-4.88 12.378-12.46 12.378Zm0-5.016c3.79 0 6.3-2.898 6.3-7.362 0-4.463-2.51-7.408-6.3-7.408-3.838 0-6.348 2.945-6.348 7.408 0 4.464 2.51 7.362 6.348 7.362Z",fill:"currentColor"})]})]})}var Ee=new Set(["ask","auto","full"]);function V(e){return Ee.has(e)?e:"auto"}function Ot(e,t){return`${e}:permission-mode:${t}:v1`}function Dt(e,t){return`${e}:active-permission-mode:${t}:v1`}function Lt(e){try{let t=localStorage.getItem(e);return t!==null&&Ee.has(t)?V(t):void 0}catch{return}}function Ft(e,t){try{localStorage.setItem(e,t)}catch{}}function Wt(e){try{localStorage.removeItem(e)}catch{}}function Ut(e,t){let n=V(t);if(n==="auto")return e;let o=n==="ask";return e.map(l=>!!l.needsApproval===o?l:{...l,needsApproval:o})}function ke(e){return`heroui-agent:anonymous:${e}`}var Me=class{constructor(t,n){this.agentId=t;this.getAuthToken=n}cached=null;generation=0;pending=null;clear(){this.generation+=1,this.cached=null,this.pending=null}reset(){this.clear();try{localStorage.removeItem(ke(this.agentId))}catch{}}async get(){if(this.cached&&this.expiresAt(this.cached)>Date.now()+6e4)return this.cached.token;let t=this.generation,n=this.pending??this.refresh();this.pending||(this.pending=n);try{let o=await n;return t!==this.generation?this.get():(this.cached=o,o.token)}finally{this.pending===n&&(this.pending=null)}}async subjectHash(){let t=await this.get(),n=at(t),o=typeof n.sub=="string"?n.sub:"anonymous",l=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${this.agentId}:${o}`));return Array.from(new Uint8Array(l),f=>f.toString(16).padStart(2,"0")).join("").slice(0,24)}anonymousId(){let t=ke(this.agentId);try{let n=localStorage.getItem(t);if(n)return n;let o=crypto.randomUUID();return localStorage.setItem(t,o),o}catch{return crypto.randomUUID()}}expiresAt(t){return t.expiresAt}async refresh(){let t=await this.getAuthToken({agentId:this.agentId,anonymousId:this.anonymousId()});if(!t||typeof t.token!="string"||!t.token.trim()||typeof t.expiresAt!="number"||!Number.isFinite(t.expiresAt)||t.expiresAt<=0)throw new Error("Auth token callback returned invalid data");return{expiresAt:t.expiresAt,token:t.token}}};function at(e){try{let t=e.split(".")[1];if(!t)return{};let n=t.replace(/-/g,"+").replace(/_/g,"/"),o=n.padEnd(Math.ceil(n.length/4)*4,"=");return JSON.parse(atob(o))}catch{return{}}}var it={"application/json":"json","application/pdf":"pdf","image/gif":"gif","image/jpeg":"jpg","image/png":"png","image/webp":"webp","text/csv":"csv","text/markdown":"md","text/plain":"txt","text/tab-separated-values":"tsv"},X=Object.freeze(Object.keys(it)),zt=X.join(","),st=new Set(X);function Ce(e){return st.has(e.trim().toLowerCase())}import{useEffect as lt,useLayoutEffect as Ne,useRef as ct,useState as j}from"react";import{Fragment as He,jsx as s,jsxs as x}from"react/jsx-runtime";function Yt({agentId:e,composerConnecting:t=!1,composerControlsAvailable:n,composerControlsRevealed:o,composerEndSlot:l,composerFooterSlot:f,composerStartSlot:y,greeting:a,onComposerControlsReveal:c,onIntent:p,placeholder:S,suggestedPrompts:E}){let[w]=j(()=>te(e)),[h,v]=j(()=>w?.submitted?"":w?.prompt??""),[u,k]=j(()=>w?.submitted?w:null),[q,O]=j(!1),g=ct(null),H=n??!!(y||l),P=o??(H&&q),A=i=>{_(e,!0,i.currentTarget),O(H),H&&c?.(),p()},R=i=>{let m=i.currentTarget.querySelector(".ha-composer");m&&Te(m,i.relatedTarget)||(O(!1),_(e,!1))};Ne(()=>{ve(e,g.current),ne(g.current)},[e]),lt(()=>{u||$(e,{prompt:h,submitted:!1})},[h,e,u]),Ne(()=>{if(!u)return;let i=requestAnimationFrame(m=>{ye(e,u.messageId,m)});return()=>cancelAnimationFrame(i)},[e,u]);let M=i=>{if(u)return;let m=Ae(i);m&&(k(m),v(""),g.current.style.height="auto",$(e,m),p())};return x(He,{children:[s("div",{className:"ha-conversation",children:s("div",{"aria-live":"polite",className:"ha-messages",role:"log",children:u?x(He,{children:[s("div",{className:"ha-message","data-role":"user",children:s("div",{className:"ha-bubble",children:s("div",{className:"ha-message-content",children:s("p",{className:"ha-message-text",children:u.prompt})})})}),s("div",{className:"ha-message","data-role":"assistant","data-stream-anchor":"true","data-turn-feedback-id":u.messageId,children:s("div",{className:"ha-message-body",children:s("div",{"aria-label":"Working on your request\u2026",className:"ha-progress ha-activity-status ha-progress-shimmer",role:"status",children:s("span",{"aria-hidden":"true",className:"ha-shimmer",children:"Thinking\u2026"})})})})]}):x("div",{className:"ha-empty",children:[s("h2",{children:a}),s("p",{children:"Live answers with charts, metrics, and tables."})]})})}),x("form",{className:"ha-composer-wrap",onBlur:R,onSubmit:i=>{i.preventDefault(),M(h)},children:[!u&&E.length>0?s("div",{"aria-label":"Suggested prompts",className:"ha-suggestions",role:"group",children:E.map(i=>x("button",{className:"ha-suggestion",type:"button",onClick:()=>M(i),children:[s("span",{children:i}),s(ut,{})]},i))}):null,x("div",{className:"@container ha-composer","data-connecting":t||void 0,"data-controls-revealed":P||void 0,children:[y,s("textarea",{ref:g,"aria-label":"Message the assistant",placeholder:S,readOnly:!!u,rows:1,value:h,onFocus:A,onSelect:i=>_(e,!0,i.currentTarget),onChange:i=>{let m=i.currentTarget.value;$(e,{prompt:m,submitted:!1}),_(e,!0,i.currentTarget),v(m),ne(i.currentTarget),p()},onKeyDown:i=>{i.key!=="Enter"||i.shiftKey||(i.preventDefault(),M(h))}}),l,x("button",{"aria-label":"Send message",className:"ha-send",disabled:!h.trim()||!!u,type:"submit",children:[s(dt,{}),s(U,{shortcut:"\u21B5",children:"Send message"})]})]}),s("div",{className:"ha-composer-footer","data-revealed":!!f||void 0,children:s("div",{className:"ha-composer-footer-content",children:f})}),s(Se,{})]})]})}function dt(){return s("svg",{"aria-hidden":"true",fill:"none",height:"18",viewBox:"0 0 18 18",width:"18",children:s("path",{d:"M9 14.5V3.5m0 0L4.5 8M9 3.5 13.5 8",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.6"})})}function ut(){return s("svg",{"aria-hidden":"true",fill:"none",height:"16",viewBox:"0 0 16 16",width:"16",children:s("path",{d:"M5 11 11 5m0 0H6m5 0v5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5"})})}var mt={animation:"fadeIn",duration:160,easing:"ease-out",sep:"word",stagger:18};function Pe(e){return typeof e=="number"?Number.isFinite(e)?`${Math.round(e)}px`:void 0:e?.trim()||void 0}function pt(e){let t=Pe(e?.initialWidth),n=Pe(e?.initialHeight);return{...t?{"--ha-panel-width":t}:{},...n?{"--ha-panel-height":n}:{}}}function Re(e){return e===void 0||!Number.isFinite(e)?24:Math.min(Math.max(Math.round(e),0),200)}function gt(e){if(e===void 0)return[...X];if(e===!1||!Array.isArray(e))return[];let t=new Set;for(let n of e){if(typeof n!="string")continue;let o=n.trim().toLowerCase();Ce(o)&&t.add(o)}return[...t]}function nn(e){if(typeof e.agentId!="string"||!e.agentId.trim())throw new Error("HeroUI Agent agentId is required");if(typeof e.getAuthToken!="function")throw new Error("HeroUI Agent getAuthToken is required");let t=gt(e.composer?.attachments),n=typeof e.composer?.disclaimer=="string"&&e.composer.disclaimer.trim().slice(0,240)||void 0;return{apiBaseUrl:(e._api?.baseUrl??"https://api.heroui.com").replace(/\/$/,""),colorScheme:e.appearance?.theme?.colorScheme??"system",componentExportFormats:e.componentExports===!1?[]:e.componentExports??["csv","svg","png"],composerAttachmentAccept:t.join(","),composerAttachmentContentTypes:t,composerControlsAvailable:t.length>0||e.permissions?.showPicker===!0&&!!e.tools?.length||e.composer?.modelPicker===!0||(e.composer?.dictation??!0),composerDefaultModel:e.composer?.defaultModel,composerDictation:e.composer?.dictation??!0,designTheme:ce(e.appearance?.theme?.designTheme),...n?{composerDisclaimer:n}:{},agentId:e.agentId,composerModelPicker:e.composer?.modelPicker??!1,composerPlaceholder:e.composer?.placeholder?.trim().slice(0,120)||"Ask anything\u2026",context:e.context,getAuthToken:e.getAuthToken,greeting:e.startScreen?.greeting?.trim().slice(0,120)||"Ask about your data",launcherPosition:e.appearance?.launcher?.position??"bottom-right",markdownAnimation:e.markdown?.animated??mt,markdownCaret:e.markdown?.caret??"block",markdownPlugins:e.markdown?.plugins,messageActions:e.responseActions===!1?[]:e.responseActions??["copy","feedback","retry"],onFeedback:e.onFeedback,panelExpandable:e.appearance?.panel?.expandable??!0,panelExpanded:e.appearance?.panel?.expanded??!1,panelStyle:pt(e.appearance?.panel),permissionDefaultMode:V(e.permissions?.defaultMode),permissionShowPicker:e.permissions?.showPicker===!0,preload:e.preload??!0,reopenOnRefresh:e.reopenOnRefresh??!1,showLauncher:e.showLauncher??!0,startNewConversationOnOpen:e.startNewConversationOnOpen??!1,suggestedPromptShortcuts:e.startScreen?.promptShortcuts??!1,...e.appearance?.launcher?.icon?.trim()?{launcherIcon:e.appearance.launcher.icon.trim()}:{},...e.appearance?.launcher?.style?{launcherStyle:e.appearance.launcher.style}:{},...e.appearance?.launcher?.offset?{launcherOffset:{x:Re(e.appearance.launcher.offset.x),y:Re(e.appearance.launcher.offset.y)}}:{},imageSearch:(e.capabilities?.webSearch??!1)&&(e.capabilities?.imageSearch??!0),newsSearch:(e.capabilities?.webSearch??!1)&&(e.capabilities?.newsSearch??!1),suggestedPrompts:e.startScreen?.prompts?.map(o=>o.trim()).filter(Boolean).slice(0,5),themeStyle:{...ue(e.appearance?.theme),...de(e.appearance?.launcher?.background)},tools:e.tools??[],viewMode:e.appearance?.viewMode??"floating",webSearch:e.capabilities?.webSearch??!1}}export{Me as a,ht as b,U as c,ge as d,Et as e,it as f,X as g,Ce as h,Ae as i,$ as j,te as k,Ct as l,_ as m,ve as n,Te as o,Nt as p,Qe as q,Ht as r,ne as s,Se as t,Yt as u,Ot as v,Dt as w,Lt as x,Ft as y,Wt as z,Ut as A,mt as B,nn as C};
|
package/dist/contracts.d.ts
CHANGED
|
@@ -1181,7 +1181,7 @@ declare const clientToolsSchema: z.ZodArray<z.ZodObject<{
|
|
|
1181
1181
|
type ClientToolManifestEntry = z.infer<typeof clientToolManifestEntrySchema>;
|
|
1182
1182
|
|
|
1183
1183
|
declare const HEROUI_AGENT_PROTOCOL_VERSION: 6;
|
|
1184
|
-
declare const HEROUI_AGENT_SDK_VERSION: "0.2.0-beta.
|
|
1184
|
+
declare const HEROUI_AGENT_SDK_VERSION: "0.2.0-beta.11";
|
|
1185
1185
|
|
|
1186
1186
|
/** Browser event emitted when protocol-v6 runtime latency checkpoints arrive. */
|
|
1187
1187
|
declare const HEROUI_AGENT_RUNTIME_TIMING_EVENT: "heroui-agent:runtime-timing";
|
package/dist/contracts.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var vo=5,wo=10485760,ht={"application/json":"json","application/pdf":"pdf","image/gif":"gif","image/jpeg":"jpg","image/png":"png","image/webp":"webp","text/csv":"csv","text/markdown":"md","text/plain":"txt","text/tab-separated-values":"tsv"},he=Object.freeze(Object.keys(ht)),_o=he.join(","),ft=new Set(he),Eo=new Set(["application/json","text/csv","text/markdown","text/plain","text/tab-separated-values"]);function fe(t){return ft.has(t.trim().toLowerCase())}var ye=1,u=Symbol("invalid");function D(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function v(t){if(t!==void 0)return typeof t=="string"?t:u}function _(t){if(t!==void 0)return typeof t=="boolean"?t:u}function Y(t){if(t!==void 0)return typeof t=="number"&&Number.isFinite(t)?t:u}function z(t){return n=>{if(n!==void 0)return typeof n=="string"&&t.includes(n)?n:u}}function Ce(t){if(t===void 0)return;if(typeof t=="string")return t;if(!D(t))return u;let n=v(t.dark),a=v(t.light);return n===u||a===u?u:{...n===void 0?{}:{dark:n},...a===void 0?{}:{light:a}}}function yt(t){if(t===void 0)return;if(!D(t))return u;let n={};for(let[a,i]of Object.entries(t)){if(typeof i!="string")return u;n[a]=i}return n}function Ct(t){if(t!==void 0)return!Array.isArray(t)||t.some(n=>typeof n!="string")?u:t}function x(t,n){if(t===void 0||!D(t))return u;let a={};for(let[i,l]of Object.entries(n)){let d=l(t[i]);if(d===u)return u;d!==void 0&&(a[i]=d)}return a}function U(t){return t===u?void 0:t}var bt=["accent","background","foreground","overlay","surface","surfaceSecondary","tooltip"];function xt(t){return x(t,{launcher:n=>n===void 0?void 0:x(n,{background:Ce,icon:v,position:z(["bottom-left","bottom-right"]),style:yt}),panel:n=>n===void 0?void 0:x(n,{expandable:_,expanded:_,initialHeight:a=>a===void 0||typeof a=="string"?a:Y(a),initialWidth:a=>a===void 0||typeof a=="string"?a:Y(a)}),theme:n=>n===void 0?void 0:x(n,{colorScheme:z(["dark","light","system"]),colors:a=>a===void 0?void 0:x(a,Object.fromEntries(bt.map(i=>[i,Ce]))),designTheme:z(["base","brutalism","glass","mouve"]),radius:z(["pill","round","sharp","soft"]),typography:a=>a===void 0?void 0:x(a,{baseSize:Y,fontFamily:v})}),viewMode:z(["floating","sidebar"])})}function At(t){return x(t,{attachments:n=>{if(n===void 0||n===!1)return n;if(!Array.isArray(n))return u;let a=n.filter(i=>typeof i=="string"&&fe(i));return a.length===n.length?a:u},defaultModel:v,dictation:_,disclaimer:n=>n===!1?!1:v(n),modelPicker:_,placeholder:v})}function kt(t){return x(t,{animated:n=>{if(n===void 0||n===!1)return n;if(!D(n))return u;let a=z(["blurIn","fadeIn","slideUp"])(n.animation);return a===u||a===void 0?u:{...n,animation:a}},caret:n=>n===!1?!1:z(["block","circle"])(n)})}function It(t){if(t===void 0||t===!1)return t;if(!Array.isArray(t))return u;let n=["copy","feedback","retry"],a=t.filter(i=>typeof i=="string"&&n.includes(i));return a.length===t.length?a:u}function Uo(t){if(!D(t)||t.version!==ye)return null;let n=t.revision;if(typeof n!="string"||!n)return null;let a=U(xt(t.appearance)),i=U(x(t.capabilities,{imageSearch:_,newsSearch:_,webSearch:_})),l=U(At(t.composer)),d=U(kt(t.markdown)),f=U(x(t.permissions,{defaultMode:z(["ask","auto","full"]),showPicker:_})),h=U(It(t.responseActions)),R=U(x(t.startScreen,{greeting:v,promptShortcuts:_,prompts:Ct})),b=U(x(t.webfont,{familyName:S=>typeof S=="string"&&S?S:u,fontFaceUrl:v,stylesheetUrl:v}));return{...a?{appearance:a}:{},...i?{capabilities:i}:{},...l?{composer:l}:{},...d?{markdown:d}:{},...f?{permissions:f}:{},...h===void 0?{}:{responseActions:h},...R?{startScreen:R}:{},...b?{webfont:b}:{},revision:n,version:ye}}var be={accordion:"display-information","action-group":"actions","area-chart":"data-visualization","bar-chart":"data-visualization",callout:"display-information","candlestick-chart":"data-visualization","channel-message":"display-information","code-block":"display-information","comparison-list":"data-visualization","composed-chart":"data-visualization","create-event":"display-information","data-table":"data-visualization",diagram:"display-information","donut-chart":"data-visualization","enable-notification":"display-information","event-session":"display-information","flight-tracker":"display-information",followup:"actions",form:"form-elements","funnel-chart":"data-visualization","gauge-chart":"data-visualization",heatmap:"data-visualization",image:"display-information","kpi-grid":"data-visualization","line-chart":"data-visualization",list:"display-information","list-block":"display-information",map:"display-information","meter-list":"data-visualization","metric-grid":"data-visualization","pie-chart":"data-visualization","player-card":"display-information",playlist:"display-information","product-card":"display-information","product-signals":"data-visualization","purchase-complete":"display-information","purchase-items":"display-information","radar-chart":"data-visualization","radial-chart":"data-visualization","record-card":"display-information","ride-status":"display-information","sankey-chart":"data-visualization","scatter-chart":"data-visualization",steps:"display-information","sunburst-chart":"data-visualization","switch-group":"form-elements",tabs:"display-information","tag-list":"display-information",text:"display-information","toggle-group":"form-elements","view-event":"display-information","weather-current":"display-information","weather-forecast":"display-information"};import{z as e}from"zod";function xe(t){return{maximum:t.max??(t.format?.style==="percent"?1:100),minimum:t.min??0}}var Tt=["activity","alert","briefcase","calendar","chart","check","clock","code","credit-card","database","device-desktop","device-mobile","document","dollar","flag","globe","heart","home","info","lightning","location","mail","percent","person","question","receipt","rocket","route","search","shopping-bag","speedometer","star","tag","target","users"],St=["clear","partly-cloudy","cloudy","fog","drizzle","rain","snow","thunderstorm","windy","unknown"],vt=e.string().trim().min(1).max(120),r=e.string().trim().min(1).max(320),M=e.string().trim().min(1).max(1e4),c=e.string().trim().min(1).max(80),m=e.string().trim().min(1).max(100),G=e.string().regex(/^\d{4}-\d{2}-\d{2}$/),W=e.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/),wt=e.union([e.string().max(500),e.number(),e.boolean(),e.null()]),O=e.record(e.string().max(80),wt),s=e.object({description:r.optional(),id:m,title:vt}),ee=e.enum(["outline","plain","surface","surface-secondary","surface-tertiary","widget"]).describe("Card hierarchy: surface for the primary standalone group; surface-secondary for supporting information; surface-tertiary for one featured or emphasized group; outline for equal peers and comparisons; plain for a structural section already separated by surrounding layout; widget for a compact interactive group with actions or controls."),_t=e.enum(["compact","details","media"]).describe("Record information layout: details for a full labeled fact set; compact for a brief summary or repeated peer cards; media for an image-led product, place, person, or event and only when an image is available."),C=e.discriminatedUnion("style",[e.object({compact:e.boolean().optional(),style:e.literal("number")}),e.object({maximumFractionDigits:e.number().int().min(0).max(4).optional(),style:e.literal("percent")}),e.object({compact:e.boolean().optional(),currency:e.string().regex(/^[A-Z]{3}$/),style:e.literal("currency")})]),w=e.enum(["accent","chart-1","chart-2","chart-3","chart-4","chart-5","danger","default","success","warning"]),Ie=e.record(e.string().trim().min(1).max(80),w).refine(t=>Object.keys(t).length<=50,"At most 50 category colors are allowed"),ne=e.object({color:w.optional(),dataKey:c,format:C.optional(),label:r}),Et=ne.extend({axis:e.enum(["left","right"]).optional(),stacked:e.boolean().optional(),type:e.enum(["area","bar","line"])}),Nt=e.object({id:m,label:r,maxItems:e.number().int().min(1).max(200).optional()}),H=s.extend({data:e.array(O).min(1).max(200),defaultRangeId:m.optional(),ranges:e.array(Nt).min(2).max(8).optional(),series:e.array(ne).min(1).max(5),showSummary:e.boolean().optional(),xKey:c}),q=s.extend({colors:Ie.optional(),data:e.array(O).min(1).max(50),format:C.optional(),labelKey:c,valueKey:c}),Rt=s.extend({colors:Ie.optional(),data:e.array(O).min(1).max(200),format:C.optional(),groupKey:c.optional(),kind:e.literal("scatter-chart"),labelKey:c.optional(),sizeKey:c.optional(),xKey:c,yKey:c}),Ut=s.extend({color:w.optional(),data:e.array(O).min(1).max(400),format:C.optional(),kind:e.literal("heatmap"),valueKey:c,xKey:c,yKey:c}),zt=H.extend({baseline:e.number().finite().optional(),kind:e.literal("line-chart"),mode:e.enum(["live","profit-loss","standard"]).optional(),negativeColor:w.optional(),positiveColor:w.optional(),windowSize:e.number().int().min(2).max(200).optional()}).superRefine((t,n)=>{(t.mode==="live"||t.mode==="profit-loss")&&t.series.length!==1&&n.addIssue({code:"custom",message:`${t.mode} line charts require exactly one series`,path:["series"]})}),Ot=s.extend({closeKey:c,data:e.array(O).min(1).max(200),downColor:w.optional(),format:C.optional(),highKey:c,kind:e.literal("candlestick-chart"),lowKey:c,openKey:c,upColor:w.optional(),xKey:c}).superRefine((t,n)=>{for(let[a,i]of t.data.entries()){let l=i[t.openKey],d=i[t.highKey],f=i[t.lowKey],h=i[t.closeKey];if([l,d,f,h].some(ge=>typeof ge!="number"||!Number.isFinite(ge))){n.addIssue({code:"custom",message:"Every candlestick row needs finite open, high, low, and close values",path:["data",a]});continue}let b=l,S=d,K=f,ue=h;(K>Math.min(b,ue)||S<Math.max(b,ue)||K>S)&&n.addIssue({code:"custom",message:"Candlestick low/high values must contain the open and close values",path:["data",a]})}}),Lt=q.extend({data:e.array(O).min(2).max(20),kind:e.literal("funnel-chart"),orientation:e.enum(["horizontal","vertical"]).optional(),showPercentages:e.boolean().optional()}).superRefine((t,n)=>{let a=t.data.map((i,l)=>{let d=i[t.valueKey];return typeof d!="number"||!Number.isFinite(d)||d<0?(n.addIssue({code:"custom",message:"Every funnel stage needs a finite, non-negative value",path:["data",l,t.valueKey]}),0):d});a.some(i=>i>0)||n.addIssue({code:"custom",message:"A funnel needs at least one stage above zero",path:["data"]}),(a[0]??0)<=0&&n.addIssue({code:"custom",message:"A funnel's first stage must be above zero",path:["data",0,t.valueKey]});for(let i=1;i<a.length;i+=1)(a[i]??0)>(a[i-1]??0)&&n.addIssue({code:"custom",message:"Funnel stages must not increase",path:["data",i,t.valueKey]})}),Mt=s.extend({color:w.optional(),format:C.optional(),kind:e.literal("gauge-chart"),label:r,max:e.number().finite().optional(),min:e.number().finite().optional(),notches:e.number().int().min(6).max(60).optional(),orientation:e.enum(["arc","linear"]).optional(),value:e.number().finite()}).superRefine((t,n)=>{let{maximum:a,minimum:i}=xe(t);a<=i?n.addIssue({code:"custom",message:"Gauge max must be greater than min",path:["max"]}):(t.value<i||t.value>a)&&n.addIssue({code:"custom",message:"Gauge value must be within its min/max range",path:["value"]})}),Te=e.lazy(()=>e.object({children:e.array(Te).min(1).max(12).optional(),color:w.optional(),id:m,label:r,value:e.number().finite().positive().optional()}).superRefine((t,n)=>{t.children?.length&&t.value!==void 0&&n.addIssue({code:"custom",message:"Sunburst branch values are derived from their children",path:["value"]}),!t.children?.length&&t.value===void 0&&n.addIssue({code:"custom",message:"Every sunburst leaf needs a positive value",path:["value"]})})),Gt=s.extend({data:Te,format:C.optional(),kind:e.literal("sunburst-chart")}).superRefine((t,n)=>{let a=new Set,i=0,l=0,d=(f,h)=>{i+=1,l=Math.max(l,h),a.has(f.id)&&n.addIssue({code:"custom",message:`Duplicate sunburst node id "${f.id}"`}),a.add(f.id),f.children?.forEach(R=>d(R,h+1))};t.data.children?.length||n.addIssue({code:"custom",message:"A sunburst root needs at least one child",path:["data","children"]}),d(t.data,0),i>60&&n.addIssue({code:"custom",message:"Sunburst charts allow at most 60 nodes"}),l>4&&n.addIssue({code:"custom",message:"Sunburst charts allow at most four nested levels"})}),Z=e.object({label:r,value:c}),jt=e.object({end:G,start:G}).refine(t=>t.start<=t.end,"The start date must not be after the end date"),A={description:r.optional(),label:r,name:c,required:e.boolean().optional()},Bt=e.discriminatedUnion("kind",[e.object({...A,defaultValue:e.string().max(500).optional(),inputType:e.enum(["email","number","password","search","tel","text","url"]).optional(),kind:e.literal("input"),placeholder:e.string().max(160).optional()}),e.object({...A,defaultValue:e.string().max(2e3).optional(),kind:e.literal("textarea"),placeholder:e.string().max(160).optional(),rows:e.number().int().min(2).max(12).optional()}),e.object({...A,defaultValue:c.optional(),kind:e.literal("select"),options:e.array(Z).min(1).max(30),placeholder:e.string().max(160).optional()}),e.object({...A,defaultValue:c.optional(),kind:e.literal("radio-group"),options:e.array(Z).min(1).max(12),placeholder:e.string().max(160).optional()}),e.object({...A,defaultValue:e.array(c).max(20).optional(),kind:e.literal("checkbox-group"),options:e.array(Z).min(1).max(20)}),e.object({...A,defaultValue:e.array(c).max(50).optional(),kind:e.literal("combobox"),options:e.array(Z.extend({description:e.string().trim().min(1).max(120).optional()})).min(1).max(200).describe("Prefer this over select once there are more options than someone would scan \u2014 it filters as they type. Values must be unique."),placeholder:e.string().max(160).optional(),selectionMode:e.enum(["multiple","single"]).optional()}).superRefine((t,n)=>{let a=new Set(t.options.map(i=>i.value));a.size!==t.options.length&&n.addIssue({code:"custom",message:"Combobox option values must be unique",path:["options"]}),(t.selectionMode??"single")==="single"&&(t.defaultValue?.length??0)>1&&n.addIssue({code:"custom",message:"A single-selection combobox takes at most one default value",path:["defaultValue"]}),t.defaultValue?.some(i=>!a.has(i))&&n.addIssue({code:"custom",message:"Every combobox default value must be one of the options",path:["defaultValue"]})}),e.object({...A,defaultValue:e.number().optional(),kind:e.literal("slider"),max:e.number(),min:e.number(),step:e.number().positive().optional()}),e.object({...A,defaultValue:e.number().optional(),format:C.optional(),kind:e.literal("number"),max:e.number().optional(),min:e.number().optional(),placeholder:e.string().max(160).optional(),step:e.number().positive().optional()}),e.object({...A,defaultValue:e.boolean().optional(),kind:e.literal("switch")}),e.object({...A,defaultValue:G.optional(),kind:e.literal("date-picker"),max:G.optional(),min:G.optional()}),e.object({...A,defaultValue:jt.optional(),kind:e.literal("date-range-picker"),max:G.optional(),min:G.optional()}),e.object({...A,defaultValue:W.optional(),hourCycle:e.union([e.literal(12),e.literal(24)]).optional(),kind:e.literal("time-field"),max:W.optional(),min:W.optional()})]),oe=e.enum(["danger","outline","primary","secondary","tertiary"]),N=e.enum(Tt),Se=e.object({arguments:e.record(e.string().max(80),e.unknown()).refine(t=>JSON.stringify(t).length<=4096,"Tool call arguments must serialize to at most 4KB of JSON"),name:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/)}),y=e.object({id:m,label:r,prompt:e.string().trim().min(1).max(2e3).optional(),toolCall:Se.optional(),variant:oe.optional()}),ve=e.object({latitude:e.number().finite().min(-85.051129).max(85.051129),longitude:e.number().finite().min(-180).max(180)}),te=e.string().trim().min(1).max(2e3).refine(t=>{try{let n=new URL(t);return["http:","https:"].includes(n.protocol)&&!n.username&&!n.password}catch{return!1}},{message:"URL must use HTTP or HTTPS and cannot include credentials"}),Dt=e.string().trim().min(1).max(2e3).refine(t=>{try{let n=new URL(t);return["http:","https:","mailto:","tel:"].includes(n.protocol)&&!n.username&&!n.password}catch{return!1}},{message:"Link must use HTTP, HTTPS, mailto, or tel and cannot include credentials"}),F={id:m,label:r,variant:oe.optional()},Pt=e.string().trim().min(5).max(2e3).refine(t=>/^tel:\+?[0-9().\-\s]+$/.test(t)&&/\d/.test(t.slice(4)),"Phone links must use the tel: scheme and contain a phone number"),Vt=e.discriminatedUnion("kind",[e.object({...F,href:Pt,kind:e.literal("call")}),e.object({...F,href:te,kind:e.literal("directions")}),e.object({...F,href:Dt,kind:e.literal("other")}),e.object({...F,href:te,kind:e.literal("website")})]),Kt=ve.extend({actions:e.array(Vt).max(4).optional(),address:r.optional(),category:e.string().trim().min(1).max(100).optional(),id:m,images:e.array(e.object({alt:r,src:te})).max(4).optional().describe("Prefer one representative image per location when a trusted tool or web image search returns one. The first image becomes the result-card thumbnail; initials are the fallback."),notes:e.string().trim().min(1).max(2e3).optional(),rating:e.number().finite().min(0).max(5).optional(),relevance:e.number().finite().min(0).max(1).optional(),reviewCount:e.number().int().nonnegative().max(1e9).optional(),title:r}),P=e.string().trim().min(1).max(2e3).refine(t=>{if(t.startsWith("/"))return!t.startsWith("//");try{let n=new URL(t);return["http:","https:"].includes(n.protocol)&&!n.username&&!n.password}catch{return!1}},{message:"Image sources must be HTTP(S) URLs or root-relative paths"}),I=e.object({alt:r,src:P.refine(t=>!t.split(/[?#]/,1)[0]?.toLowerCase().endsWith(".svg"),"Response-composition images must be raster images")}),ae=e.string().regex(/^[A-Z]{3}$/),Zt=e.object({amount:e.number().finite().nonnegative().max(1e9),currency:ae}),X=e.enum(St),Ae=e.enum(["celsius","fahrenheit"]),ke=e.object({label:r,status:r.optional(),time:e.string().trim().min(1).max(80)}),j=e.enum(["accent","danger","default","muted","success","warning"]),Ft=e.object({actions:e.array(y).max(3).optional(),badge:e.object({label:r,tone:j.optional()}).optional(),description:r.optional(),id:m,image:e.object({alt:r,src:P}),meta:e.string().trim().min(1).max(160).optional(),name:r,price:e.object({amount:e.number().finite().nonnegative().max(1e9),currency:ae.optional()}),rating:e.object({count:e.number().int().nonnegative().max(1e9).optional(),value:e.number().finite().min(0).max(5)}).optional()}),Ht=e.enum(["accent","danger","default","success","warning"]),qt=e.object({description:r.optional(),format:C.optional(),id:m,label:r,max:e.number().optional(),min:e.number().optional(),tone:Ht.optional(),value:e.number()}).superRefine((t,n)=>{let a=t.min??0,i=t.max??(t.format?.style==="percent"?1:100);i<=a&&n.addIssue({code:"custom",message:"Meter max must be greater than min"}),(t.value<a||t.value>i)&&n.addIssue({code:"custom",message:"Meter value must be within its min/max range"})}),o={accordion:s.extend({kind:e.literal("accordion"),sections:e.array(e.object({content:M,defaultOpen:e.boolean().optional(),id:m,title:r})).min(1).max(12)}),actions:s.extend({actions:e.array(y).min(1).max(8),kind:e.literal("action-group"),orientation:e.enum(["horizontal","vertical"]).optional()}),area:H.extend({kind:e.literal("area-chart"),stacked:e.boolean().optional()}),bar:H.extend({kind:e.literal("bar-chart"),layout:e.enum(["horizontal","vertical"]).optional(),stacked:e.boolean().optional()}),callout:s.extend({content:M,icon:N.optional(),kind:e.literal("callout"),tone:e.enum(["accent","danger","neutral","success","warning"]).optional()}),candlestick:Ot,channelMessage:s.extend({attachments:e.array(e.object({id:m,image:I.optional(),name:r})).max(8).optional(),author:e.object({image:I.optional(),name:r}),channel:r,content:M,kind:e.literal("channel-message"),timestamp:e.string().trim().min(1).max(80)}),code:s.extend({code:e.string().min(1).max(2e4),kind:e.literal("code-block"),language:e.string().trim().max(40).optional()}),comparison:s.extend({items:e.array(e.object({change:e.number().optional(),format:C.optional(),label:r,note:e.string().trim().max(180).optional(),value:e.number()})).min(1).max(12),kind:e.literal("comparison-list")}),composed:H.extend({kind:e.literal("composed-chart"),series:e.array(Et).min(2).max(5)}),createEvent:s.extend({actions:e.array(y).max(2).optional(),date:e.object({day:e.number().int().min(1).max(31),weekday:e.string().trim().min(1).max(20)}),events:e.array(e.object({id:m,status:e.enum(["existing","proposed"]).optional(),time:e.string().trim().min(1).max(80),title:r,tone:j.optional()})).min(1).max(12),kind:e.literal("create-event")}),diagram:s.extend({chart:e.string().trim().min(1).max(4e3).describe('Mermaid source. Pick the diagram type from the relationship: "flowchart LR" for a process or decision path, "sequenceDiagram" for an exchange between parties over time, "erDiagram" for how records relate, "stateDiagram-v2" for the states something moves between. Example: "flowchart LR\\n A[Order placed] --> B{In stock?}\\n B -- yes --> C[Ship]\\n B -- no --> D[Backorder]". Never include HTML, script tags, or click directives.'),kind:e.literal("diagram")}).superRefine((t,n)=>{/<\s*script|javascript:|^\s*click\s+\S/im.test(t.chart)&&n.addIssue({code:"custom",message:"Diagram source cannot contain HTML, script URLs, or click directives",path:["chart"]})}),donut:q.extend({kind:e.literal("donut-chart")}),enableNotification:s.extend({actions:e.tuple([y,y]),kind:e.literal("enable-notification")}),eventSession:s.extend({action:y.optional(),eyebrow:e.string().trim().min(1).max(100).optional(),kind:e.literal("event-session"),location:r,speakers:e.array(e.object({image:I.optional(),name:r,role:r})).max(8),time:e.string().trim().min(1).max(80)}),flightTracker:s.extend({airline:e.object({logo:I.optional(),name:r}),date:e.string().trim().min(1).max(80),destination:ke,flightNumber:e.string().trim().min(1).max(40),kind:e.literal("flight-tracker"),origin:ke,progress:e.number().finite().min(0).max(100).optional()}),followup:s.extend({kind:e.literal("followup"),prompts:e.array(e.object({id:m,label:r,prompt:M})).min(1).max(8)}),form:s.extend({actions:e.array(y).min(1).max(4),fields:e.array(Bt).min(1).max(20),kind:e.literal("form")}),funnel:Lt,gauge:Mt,heatmap:Ut,image:s.extend({images:e.array(e.object({alt:r,aspectRatio:e.enum(["landscape","portrait","square","wide"]).optional(),caption:r.optional(),src:P})).min(1).max(6),kind:e.literal("image"),variant:e.enum(["grid","horizontal"]).optional().describe("Use horizontal for a swipeable gallery in narrow chat interfaces.")}),kpiGrid:s.extend({kind:e.literal("kpi-grid"),metrics:e.array(e.object({change:e.number().optional(),color:w.optional(),format:C.optional(),icon:N.optional(),label:r,trend:e.array(e.number().finite()).min(2).max(60).describe("The values behind this KPI, oldest to newest, drawn as a sparkline. The last point should agree with value."),value:e.number()})).min(1).max(4)}),line:zt,list:s.extend({items:e.array(e.object({checked:e.boolean().optional(),children:e.array(r).max(8).optional(),id:m,text:r})).min(1).max(30),kind:e.literal("list"),style:e.enum(["bulleted","checklist","numbered"]).optional()}),listBlock:s.extend({items:e.array(e.object({description:r.optional(),icon:N.optional(),id:m,imageAlt:r.optional(),imageUrl:P.optional(),meta:e.string().trim().max(100).optional(),rating:e.number().min(0).max(5).optional(),title:r})).min(1).max(20),kind:e.literal("list-block")}),map:s.extend({initialLocationId:m.optional(),kind:e.literal("map"),locations:e.array(Kt).min(1).max(12),viewport:e.object({center:ve,zoom:e.number().int().min(1).max(18)}).optional()}).superRefine((t,n)=>{let a=new Set;for(let[i,l]of t.locations.entries()){a.has(l.id)&&n.addIssue({code:"custom",message:`Duplicate map location id "${l.id}"`,path:["locations",i,"id"]}),a.add(l.id);let d=new Set;for(let[f,h]of(l.actions??[]).entries())d.has(h.id)&&n.addIssue({code:"custom",message:`Duplicate action id "${h.id}" for map location "${l.id}"`,path:["locations",i,"actions",f,"id"]}),d.add(h.id)}t.initialLocationId&&!a.has(t.initialLocationId)&&n.addIssue({code:"custom",message:"The initial map location must reference one of the locations",path:["initialLocationId"]})}).describe("A ranked, map-synchronized set of places or professionals. Coordinates and listing facts must come from tools or user data; never invent them."),meterList:s.extend({items:e.array(qt).min(1).max(8),kind:e.literal("meter-list")}),metricGrid:s.extend({kind:e.literal("metric-grid"),metrics:e.array(e.object({change:e.number().optional(),format:C.optional(),icon:N.optional(),label:r,value:e.number()})).min(1).max(4)}),pie:q.extend({kind:e.literal("pie-chart")}),playerCard:s.extend({backgroundImage:I.optional(),jerseyNumber:e.string().trim().min(1).max(20).optional(),kind:e.literal("player-card"),playerName:r,stats:e.array(e.object({label:e.string().trim().min(1).max(40),value:e.union([e.string().trim().min(1).max(80),e.number().finite()])})).min(1).max(8)}),playlist:s.extend({actions:e.array(y).max(2).optional(),cover:I.optional(),kind:e.literal("playlist"),tracks:e.array(e.object({action:y.optional(),artist:r,id:m,image:I.optional(),title:r})).min(1).max(20)}),productCard:s.extend({actions:e.array(y).max(3).optional(),kind:e.literal("product-card"),products:e.array(Ft).min(1).max(8),variant:ee.optional()}).superRefine((t,n)=>{let a=new Set;for(let[i,l]of t.products.entries())a.has(l.id)&&n.addIssue({code:"custom",message:`Duplicate product id "${l.id}"`,path:["products",i,"id"]}),a.add(l.id)}).describe("A commerce product presentation: one product renders an image-led spotlight, several render a store-style grid. Product facts (id, name, image, price, rating, availability) must come from tools or user data; never invent them."),purchaseComplete:s.extend({action:y.optional(),details:e.array(e.object({label:r,value:r})).max(8),kind:e.literal("purchase-complete"),paid:Zt.optional(),product:e.object({description:r.optional(),image:I.optional(),name:r})}),purchaseItems:s.extend({actions:e.array(y).max(3).optional(),currency:ae,items:e.array(e.object({description:r.optional(),id:m,image:I.optional(),name:r,price:e.number().finite().nonnegative().max(1e9).optional(),quantity:e.number().int().positive().max(1e4).optional()})).min(1).max(20),kind:e.literal("purchase-items"),totals:e.array(e.object({amount:e.number().finite().nonnegative().max(1e9),emphasis:e.boolean().optional(),label:r})).min(1).max(8)}),radar:s.extend({angleKey:c,data:e.array(O).min(3).max(50),kind:e.literal("radar-chart"),series:e.array(ne).min(1).max(5)}),radial:q.extend({endAngle:e.number().min(-360).max(360).optional(),kind:e.literal("radial-chart"),maxValue:e.number().positive().optional(),startAngle:e.number().min(-360).max(360).optional()}),recordCard:s.extend({actions:e.array(y).max(4).optional(),eyebrow:e.string().trim().max(100).optional(),fields:e.array(e.object({icon:N.optional(),label:r,tone:j.optional(),value:e.string().trim().min(1).max(500)})).max(12),image:e.object({alt:r,src:P}).optional(),kind:e.literal("record-card"),layout:_t.optional(),status:e.object({label:r,tone:j.optional()}).optional(),variant:ee.optional()}).superRefine((t,n)=>{t.layout==="media"&&!t.image&&n.addIssue({code:"custom",message:"The media record layout requires an image",path:["image"]}),t.layout==="compact"&&t.fields.length>4&&n.addIssue({code:"custom",message:"The compact record layout supports at most four fields",path:["fields"]})}),rideStatus:s.extend({driver:e.object({image:I.optional(),name:r}),eta:e.string().trim().min(1).max(80),kind:e.literal("ride-status"),pickup:r}),sankey:s.extend({format:C.optional(),kind:e.literal("sankey-chart"),links:e.array(e.object({source:m,target:m,value:e.number().positive()})).min(1).max(100),nodes:e.array(e.object({id:m,label:r})).min(2).max(40)}),scatter:Rt,steps:s.extend({kind:e.literal("steps"),steps:e.array(e.object({content:r.optional(),icon:N.optional(),id:m,image:I.optional().describe("A representative raster image for this step. Prefer this over icon for place itineraries when a trusted image URL is available."),meta:e.string().trim().max(100).optional(),progress:e.number().min(0).max(100).optional(),status:e.enum(["blocked","cancelled","completed","failed","in-progress","pending","complete","current","upcoming"]).optional(),timestamp:e.string().trim().max(100).optional(),title:r})).min(1).max(12),variant:e.enum(["steps","timeline"]).optional()}),sunburst:Gt,switches:s.extend({items:e.array(e.object({defaultSelected:e.boolean().optional(),description:r.optional(),id:m,label:r})).min(1).max(20),kind:e.literal("switch-group")}),table:s.extend({columns:e.array(e.object({format:C.optional(),key:c,label:r})).min(1).max(12),filterable:e.boolean().optional(),kind:e.literal("data-table"),rows:e.array(O).max(200),variant:e.enum(["primary","secondary"]).optional()}),tabs:s.extend({defaultValue:m.optional(),kind:e.literal("tabs"),tabs:e.array(e.union([e.object({children:e.never().optional(),content:M,id:m,label:r}),e.object({children:e.array(e.lazy(()=>le)).min(1).max(12),content:e.never().optional(),id:m,label:r})])).min(1).max(10),variant:e.enum(["primary","secondary"]).optional()}),tags:s.extend({kind:e.literal("tag-list"),tags:e.array(r).min(1).max(30)}),text:s.extend({content:M,kind:e.literal("text"),variant:e.enum(["card","clear"]).optional()}),toggles:s.extend({defaultValue:e.array(m).max(12).optional(),items:e.array(e.object({id:m,label:r})).min(1).max(12),kind:e.literal("toggle-group"),selectionMode:e.enum(["multiple","single"]).optional()}),viewEvent:s.extend({date:e.string().trim().min(1).max(80),kind:e.literal("view-event"),time:e.string().trim().min(1).max(80),tone:j.optional()}),weatherCurrent:s.extend({condition:X,details:e.array(e.object({label:r,value:r})).max(6).optional(),kind:e.literal("weather-current"),location:r,temperature:e.number().finite().min(-150).max(150),unit:Ae}),weatherForecast:s.extend({condition:X,forecast:e.array(e.object({condition:X,label:e.string().trim().min(1).max(40),temperature:e.number().finite().min(-150).max(150)})).min(2).max(10),high:e.number().finite().min(-150).max(150),kind:e.literal("weather-forecast"),location:r,low:e.number().finite().min(-150).max(150),unit:Ae})},$t=o.metricGrid,Yt=o.kpiGrid,Wt=o.line,Xt=o.area,Jt=o.bar,Qt=o.composed,en=o.pie,tn=o.donut,nn=o.radar,on=o.radial,an=o.sankey,rn=o.scatter,sn=o.heatmap,ln=o.candlestick,pn=o.funnel,mn=o.gauge,cn=o.sunburst,dn=o.table,un=o.comparison,gn=o.meterList,hn=o.form,fn=o.text,yn=o.callout,Cn=o.image,bn=o.map,xn=o.tags,An=o.list,kn=o.listBlock,In=o.accordion,Tn=o.steps,Sn=o.code,vn=o.diagram,jo=o.tabs.superRefine(st),wn=o.actions,_n=o.followup,En=o.switches,Nn=o.toggles,Rn=o.recordCard,Un=o.productCard,zn=o.flightTracker,On=o.createEvent,Ln=o.playlist,Mn=o.rideStatus,Gn=o.purchaseItems,jn=o.channelMessage,Bn=o.purchaseComplete,Dn=o.playerCard,Pn=o.viewEvent,Vn=o.eventSession,Kn=o.enableNotification,Zn=o.weatherForecast,Fn=o.weatherCurrent,Hn=e.discriminatedUnion("kind",[o.metricGrid,o.kpiGrid,o.line,o.area,o.bar,o.composed,o.pie,o.donut,o.radar,o.radial,o.sankey,o.scatter,o.heatmap,o.candlestick,o.funnel,o.gauge,o.sunburst,o.table,o.comparison,o.meterList]),we=s.extend({defaultValue:m.optional(),kind:e.literal("product-signals"),tabs:e.array(e.object({component:Hn,id:m,label:r})).min(2).max(4)}),qn=we.superRefine((t,n)=>{let a=new Set;for(let[i,l]of t.tabs.entries())a.has(l.id)&&n.addIssue({code:"custom",message:`Duplicate product signal tab id "${l.id}"`,path:["tabs",i,"id"]}),a.add(l.id);t.defaultValue&&!a.has(t.defaultValue)&&n.addIssue({code:"custom",message:"The default product signal must reference one of the tabs",path:["defaultValue"]})}),$n=e.discriminatedUnion("kind",[o.metricGrid,o.kpiGrid,o.line,o.area,o.bar,o.composed,o.pie,o.donut,o.radar,o.radial,o.sankey,o.scatter,o.heatmap,o.candlestick,o.funnel,o.gauge,o.sunburst,o.table,o.comparison,o.meterList,o.form,o.text,o.callout,o.image,o.map,o.tags,o.list,o.listBlock,o.accordion,o.steps,o.code,o.diagram,o.tabs,o.actions,o.followup,o.switches,o.toggles,o.recordCard,o.productCard,o.flightTracker,o.createEvent,o.playlist,o.rideStatus,o.purchaseItems,o.channelMessage,o.purchaseComplete,o.playerCard,o.viewEvent,o.eventSession,o.enableNotification,o.weatherForecast,o.weatherCurrent]);function Yn(t){if(!t)return;let n=new Set;for(let a of t){if(n.has(a.id))return a.id;n.add(a.id)}}var re=e.union([$n,qn]).superRefine((t,n)=>{let a=[];switch(t.kind){case"channel-message":a.push({items:t.attachments,path:"attachments"});break;case"create-event":a.push({items:t.events,path:"events"}),a.push({items:t.actions,path:"actions"});break;case"enable-notification":a.push({items:t.actions,path:"actions"});break;case"playlist":a.push({items:t.tracks,path:"tracks"}),a.push({items:t.actions,path:"actions"});break;case"purchase-items":a.push({items:t.items,path:"items"}),a.push({items:t.actions,path:"actions"});break;case"tabs":{st(t,n);break}default:break}for(let i of a){let l=Yn(i.items);l&&n.addIssue({code:"custom",message:`Duplicate ${i.path} id "${l}"`,path:[i.path]})}}),_e=s.extend({children:e.array(re).min(1).max(4),kind:e.literal("dashboard"),layout:e.enum(["chart-table","grid","metrics-chart","stack"])}),Wn=_e,Ee=e.union([re,Wn]),Bo=e.object({component:Ee}),J=6,B=48,Ne=new Set(["card","col","grid","item-card","item-card-group","row"]),Re=new Set(["divider","spacer"]),Ue=new Set(["badge","button","heading","icon","progress","rating"]),ze=Ne,Oe=Re,Le=Ue;function Me(t){return Ne.has(t.kind)}function Ge(t){return t.kind==="item-card"?[...t.left??[],...t.middle,...t.right??[]]:t.children}function Do(t){return Re.has(t.kind)}function Po(t){return Ue.has(t.kind)}var T=e.object({id:m}),ie=e.enum(["lg","md","none","sm"]),je=e.enum(["center","end","start","stretch"]),Be=e.enum(["between","center","end","start"]),$=e.array(e.lazy(()=>le)).min(1).max(B),De=T.extend({kind:e.literal("spacer"),size:e.enum(["auto","lg","md","sm"]).optional()}),Pe=T.extend({kind:e.literal("divider")}),Ve=T.extend({icon:N.optional(),kind:e.literal("heading"),level:e.union([e.literal(1),e.literal(2),e.literal(3),e.literal(4)]).optional(),text:r}),Ke=T.extend({icon:N.optional(),kind:e.literal("button"),label:r,prompt:e.string().trim().min(1).max(2e3).optional(),toolCall:Se.optional(),variant:oe.optional()}).refine(t=>!!(t.prompt??t.toolCall),{message:"Buttons need a prompt or a toolCall to do something when pressed"}),Ze=T.extend({kind:e.literal("badge"),label:r,tone:j.optional(),variant:e.enum(["soft","solid"]).optional()}),Fe=T.extend({kind:e.literal("icon"),name:N,size:e.enum(["lg","md","sm"]).optional(),tone:j.optional()}),He=T.extend({count:e.number().int().nonnegative().max(1e9).optional(),kind:e.literal("rating"),value:e.number().finite().min(0).max(5)}),qe=T.extend({kind:e.literal("progress"),label:r.optional(),value:e.number().finite().min(0).max(100)}),$e=e.enum(["default","outline","secondary","tertiary","transparent"]),Q=e.lazy(()=>le),Ye=s.extend({action:y.optional().describe("Makes the whole row pressable. Omit when a slot contains its own button or other interactive control."),isDisabled:e.boolean().optional(),isSelected:e.boolean().optional(),kind:e.literal("item-card"),left:e.array(Q).min(1).max(4).optional().describe("Leading slot. Prefer one icon node or a compact visual."),middle:e.array(Q).min(1).max(8).describe("Primary flexible slot. Prefer a level-4 heading followed by a clear text node for a title and description."),right:e.array(Q).min(1).max(4).optional().describe("Trailing slot. Prefer a badge, short value, icon, or button."),variant:$e.optional()}),Xn=new Set(["accordion","action-group","button","followup","form","map","switch-group","tabs","toggle-group"]);function We(t){for(let n of t)if(Xn.has(n.kind)||Me(n)&&We(Ge(n)))return!0;return!1}var se=Ye.superRefine((t,n)=>{t.action&&We([...t.left??[],...t.middle,...t.right??[]])&&n.addIssue({code:"custom",message:"A pressable item-card cannot contain buttons or other interactive descendants. Remove action from the card or move the nested control outside it."})}),Xe=s.extend({children:e.array(se).min(1).max(12),columns:e.union([e.literal(2),e.literal(3)]).optional(),kind:e.literal("item-card-group"),layout:e.enum(["grid","list"]).optional(),showHeader:e.boolean().optional(),variant:$e.optional()}),Je=Xe.superRefine((t,n)=>{t.columns&&t.layout!=="grid"&&n.addIssue({code:"custom",message:"Item-card group columns only apply when layout is grid.",path:["columns"]})}),Qe=T.extend({align:je.optional(),children:$,gap:ie.optional(),justify:Be.optional(),kind:e.literal("row")}),et=T.extend({align:je.optional(),children:$,gap:ie.optional(),justify:Be.optional(),kind:e.literal("col")}),tt=T.extend({children:$,columns:e.union([e.literal(1),e.literal(2),e.literal(3),e.literal(4)]),gap:ie.optional(),kind:e.literal("grid")}),nt=s.extend({children:$,kind:e.literal("card"),variant:ee.optional()}),ot=Qe,at=et,rt=tt,it=nt,le=e.union([re,De,Pe,Ve,Ke,Ze,Fe,He,qe,ot,at,rt,it,se,Je]);function Jn(t,n){to(t,n)}function Qn(t,n){let a=t.tabs.flatMap(i=>i.children??[]);a.length!==0&<(a,n,t.id,2,1)}function st(t,n){let a=new Set;for(let[i,l]of t.tabs.entries())a.has(l.id)&&n.addIssue({code:"custom",message:`Duplicate tab id "${l.id}"`,path:["tabs",i,"id"]}),a.add(l.id);t.defaultValue&&!a.has(t.defaultValue)&&n.addIssue({code:"custom",message:"The default tab must reference one of the tabs",path:["defaultValue"]}),Qn(t,n)}function eo(t){return Me(t)?Ge(t):t.kind==="tabs"?t.tabs.flatMap(n=>n.children??[]):[]}function lt(t,n,a,i=1,l=0){let d=new Set,f=l,h=l>0?i-1:0;a&&d.add(a);let R=(b,S)=>{if(f+=1,h=Math.max(h,S),d.has(b.id)&&n.addIssue({code:"custom",message:`Duplicate component id "${b.id}" in the composed UI tree. Every node needs a unique id.`}),d.add(b.id),!(S>J))for(let K of eo(b))R(K,S+1)};for(let b of t)R(b,i);h>J&&n.addIssue({code:"custom",message:`Composed UI trees can nest at most ${J} levels deep.`}),f>B&&n.addIssue({code:"custom",message:`Composed UI trees can contain at most ${B} components.`})}function to(t,n){lt([t],n)}var pt=e.union([ot,at,rt,it,se,Je]).superRefine(Jn),Vo=e.union([Ee,pt]),Ko=e.object({component:pt}),E=t=>e.array(e.unknown()).min(1).max(t).describe("Child nodes. Each is any catalog component; look its kind up separately."),Zo={accordion:In,"action-group":wn,"area-chart":Xt,badge:Ze,"bar-chart":Jt,button:Ke,callout:yn,"candlestick-chart":ln,card:nt.extend({children:E(B)}),"channel-message":jn,"code-block":Sn,col:et.extend({children:E(B)}),"comparison-list":un,"composed-chart":Qt,"create-event":On,dashboard:_e.extend({children:E(4)}),"data-table":dn,diagram:vn,divider:Pe,"donut-chart":tn,"enable-notification":Kn,"event-session":Vn,"flight-tracker":zn,followup:_n,form:hn,"funnel-chart":pn,"gauge-chart":mn,grid:tt.extend({children:E(B)}),heading:Ve,heatmap:sn,icon:Fe,image:Cn,"item-card":Ye.extend({left:E(4).optional().describe("Leading slot nodes."),middle:E(8).describe("Primary flexible slot nodes."),right:E(4).optional().describe("Trailing slot nodes.")}),"item-card-group":Xe.extend({children:e.array(e.unknown()).min(1).max(12).describe("One to twelve item-card children. Look up item-card for each child's schema.")}),"kpi-grid":Yt,"line-chart":Wt,list:An,"list-block":kn,map:bn,"meter-list":gn,"metric-grid":$t,"pie-chart":en,"player-card":Dn,playlist:Ln,"product-card":Un,"product-signals":we.extend({tabs:e.array(e.object({component:e.unknown().describe("One analytical component: metric-grid, kpi-grid, any chart, data-table, comparison-list, or meter-list. Look its kind up separately."),id:m,label:r})).min(2).max(4)}),progress:qe,"purchase-complete":Bn,"purchase-items":Gn,"radar-chart":nn,"radial-chart":on,rating:He,"record-card":Rn,"ride-status":Mn,row:Qe.extend({children:E(B)}),"sankey-chart":an,"scatter-chart":rn,spacer:De,steps:Tn,"sunburst-chart":cn,"switch-group":En,tabs:s.extend({defaultValue:m.optional(),kind:e.literal("tabs"),tabs:e.array(e.union([e.object({content:M,id:m,label:r}),e.object({children:E(12).describe("Rich panel nodes rendered as one vertical stack. Look up every child kind separately."),id:m,label:r})])).min(1).max(10),variant:e.enum(["primary","secondary"]).optional()}),"tag-list":xn,text:fn,"toggle-group":Nn,"view-event":Pn,"weather-current":Fn,"weather-forecast":Zn};var ct={accordion:"collapsible sections of longer prose","action-group":"buttons that send prompts or call client tools","area-chart":"one continuous time series with a filled trend",badge:"a small toned status label","bar-chart":"ranked or categorical comparison, horizontal layout for rankings",button:"one action with a prompt or client-tool call",callout:"one short toned notice: info, success, warning, or danger","candlestick-chart":"open-high-low-close price movement over ordered periods",card:"titled surface grouping related children","channel-message":"a quoted workspace message with author and attachments","code-block":"a syntax-highlighted snippet",col:"stacks children vertically","comparison-list":"labeled values with change deltas, no axes","composed-chart":"two to five mixed area/bar/line series, optional dual axis","create-event":"a proposed calendar slot beside surrounding events",dashboard:"up to four analytical children in a fixed layout","data-table":"exact values in filterable rows and columns",diagram:"a flowchart, sequence, ER, or state diagram from Mermaid source, for processes and relationships prose cannot show",divider:"a rule between sections","donut-chart":"proportions of a whole with a hollow center","enable-notification":"a binary notification opt-in with two actions","event-session":"a conference session with time, location, and speakers","flight-tracker":"a flight's route, times, and live progress",followup:"suggested next prompts the user can send",form:"input fields with submit actions","funnel-chart":"drop-off through ordered conversion or pipeline stages","gauge-chart":"one bounded value against its minimum and maximum",grid:"one to four equal columns of peers",heading:"a section title, levels one to four",heatmap:"two-dimensional intensity across x and y",icon:"one semantic glyph from the icon vocabulary",image:"one to six real image URLs with captions in a grid or horizontal chat gallery","item-card":"one compact three-slot row with composable left, middle, and right content","item-card-group":"one to twelve related item-card rows in a list or grid","kpi-grid":"up to four headline KPIs, each with a sparkline of its own history","line-chart":"overlapping series, a live signal, or one series split around a baseline",list:"bulleted, numbered, or checklist items with optional children","list-block":"richer rows with title, description, meta, rating, icon, or image",map:"ranked places pinned by exact latitude and longitude","meter-list":"bounded quantities such as quota, utilization, or budget","metric-grid":"up to four headline KPIs with no history to plot","pie-chart":"proportions of a whole","player-card":"an athlete with jersey, portrait, and stat lines",playlist:"a track collection with cover and per-track actions","product-card":"purchasable items with image, price, rating, availability","product-signals":"two to four related analytical views in tabs",progress:"a zero to one hundred percentage bar","purchase-complete":"confirmation after a successful transaction","purchase-items":"a cart or order summary with line items and totals","radar-chart":"multivariate comparison across three or more axes","radial-chart":"compact circular measure",rating:"a zero to five star score with optional count","record-card":"one entity's labeled facts, layouts details/compact/media","ride-status":"pickup ETA and driver for a ride in progress",row:"places complementary children side by side","sankey-chart":"flow volumes between source and target nodes","scatter-chart":"correlation between two numeric fields, optional grouping",spacer:"a gap between siblings",steps:"task progress or a chronological timeline, up to twelve entries","sunburst-chart":"hierarchical part-to-whole values across nested levels","switch-group":"toggleable boolean preferences",tabs:"parallel text or rich multi-component sections behind labeled tabs","tag-list":"short keyword chips",text:"explanatory markdown prose","toggle-group":"single or multiple choice from short options","view-event":"one calendar event's date, time, and tone","weather-current":"current conditions in one location","weather-forecast":"multi-day or future conditions with highs and lows"},no={actions:"actions","data-visualization":"data","display-information":"display","form-elements":"forms"};function oo(t){return t==="dashboard"||ze.has(t)?"containers":Oe.has(t)?"layout":Le.has(t)?"primitives":no[be[t]]??"display"}var mt=Object.fromEntries(Object.entries(ct).map(([t,n])=>[t,{group:oo(t),summary:n}])),pe=Object.keys(ct).sort(),ao=[["containers","Containers"],["layout","Layout"],["primitives","Primitives"],["data","Data"],["display","Content"],["actions","Actions"],["forms","Forms"]];function $o(){return ao.map(([n,a])=>{let i=pe.filter(l=>mt[l].group===n).map(l=>`${l} \u2014 ${mt[l].summary}`);return`${a}: ${i.join("; ")}.`}).join(`
|
|
2
|
-
`)}import{z as L}from"zod";var ro=["callMcpTool","composeUI","executeSandbox","getComponentSchema","renderComponent","searchKnowledge","searchMcpTools","searchWeb"],io="mcp_",so=20,lo=16*1024,po=L.object({description:L.string().trim().min(1).max(1e3),inputSchema:L.record(L.string(),L.unknown()),name:L.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).refine(t=>!ro.includes(t)&&!t.toLowerCase().startsWith(io),"Client tool name is reserved by the HeroUI Agent runtime"),needsApproval:L.boolean().optional()}),Xo=L.array(po).max(so).superRefine((t,n)=>{let a=new Set;for(let i of t)a.has(i.name)&&n.addIssue({code:"custom",message:`Duplicate client tool name: ${i.name}`}),a.add(i.name);new TextEncoder().encode(JSON.stringify(t)).byteLength>lo&&n.addIssue({code:"custom",message:"Client tool manifest exceeds 16KB"})});import{z as p}from"zod";var V=6,dt="0.2.0-beta.10";var mo=p.enum(["light","dark","system"]),co=p.enum(["outline","plain","surface","surface-secondary"]),uo=new Set(["[object object]","0","anonymous","distinct_id","distinctid","email","false","guest","id","nan","none","not_authenticated","null","true","undefined"]),me=p.string().trim().min(1).max(200).refine(t=>!uo.has(t.toLowerCase()),{message:"Identity id is reserved"}),go=p.discriminatedUnion("type",[p.object({id:me,type:p.literal("anonymous")}),p.object({id:me,type:p.literal("user")})]),ho=p.object({avatarUrl:p.string().trim().pipe(p.url()).optional(),email:p.string().trim().max(320).pipe(p.email()).optional(),name:p.string().trim().max(120).optional()}),na=p.object({anonymousId:me.optional(),identity:go,profile:ho.optional()}),oa=p.object({expiresAt:p.number().int().positive(),token:p.string().trim().min(1)}),aa=p.object({agentId:p.string().trim().min(1).max(100),apiKeyId:p.string().trim().min(1).max(100),aud:p.literal("heroui-agent"),exp:p.number().int().positive(),iat:p.number().int().positive(),iss:p.literal("https://api.heroui.com"),jti:p.uuid(),protocolVersion:p.literal(6),sub:p.string().trim().min(1).max(200)}),ra={embed:"embed",preview:"preview"},ia=p.object({agentId:p.string(),minimumProtocolVersion:p.literal(6),name:p.string().trim().min(1).max(120),protocolVersion:p.literal(6),sdkVersion:p.string().default(dt),suggestedPrompts:p.array(p.string().trim().min(1).max(160)).max(5),surfaceVariant:co.default("plain"),theme:mo});import{z as k}from"zod";var ut=k.object({excerpt:k.string().trim().min(1).max(2e3).optional(),locator:k.string().trim().min(1).max(160).optional(),sourceId:k.string().trim().min(1).max(120)}),fo=k.string().trim().max(2048).refine(t=>{try{return["http:","https:"].includes(new URL(t).protocol)}catch{return!1}}),yo=k.union([ut.extend({sourceType:k.literal("document"),title:k.string().trim().min(1).max(200)}),ut.extend({sourceType:k.literal("url").optional(),title:k.string().trim().min(1).max(200).optional(),url:fo})]),pa=k.object({items:k.array(yo).min(1).max(16)});var ce=["moonshotai/Kimi-K3","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","google/gemini-3.6-flash","anthropic/claude-sonnet-5","anthropic/claude-opus-4.8"],Co={"google/gemini-3.5-flash":"google/gemini-3.6-flash"};function de(t){return Co[t]??t}var ca="openai/gpt-5.6-luna",bo=[{description:"Flagship model for coding, reasoning, and knowledge work",id:"moonshotai/Kimi-K3",label:"Kimi K3",provider:"Moonshot AI",tier:"light"},{description:"Fast answers and lightweight agent workflows",id:"openai/gpt-5.6-luna",label:"GPT-5.6 Luna",provider:"OpenAI",tier:"light"},{description:"Balanced reasoning for everyday agent tasks",id:"openai/gpt-5.6-terra",label:"GPT-5.6 Terra",provider:"OpenAI",tier:"codegen"},{description:"Deep reasoning for complex, multi-step analysis",id:"openai/gpt-5.6-sol",label:"GPT-5.6 Sol",provider:"OpenAI",tier:"complex"},{description:"Fast multimodal analysis with a large context window",id:"google/gemini-3.6-flash",label:"Gemini 3.6 Flash",provider:"Google",tier:"light"},{description:"Strong agentic reasoning and polished UI decisions",id:"anthropic/claude-sonnet-5",label:"Claude Sonnet 5",provider:"Anthropic",tier:"codegen"},{description:"Highest-capability Claude for difficult research and analysis",id:"anthropic/claude-opus-4.8",label:"Claude Opus 4.8",provider:"Anthropic",tier:"complex"}],xo=new Set(ce);function da(t){return typeof t=="string"&&xo.has(t)}function ua(t){let n=t?de(t):void 0;return bo.find(a=>a.id===n)?.tier??"light"}import{z as gt}from"zod";var ya=gt.preprocess(t=>typeof t=="string"?de(t):t,gt.enum(ce));var ba="heroui-agent:runtime-timing",xa="heroui_agent_turn_admitted",Aa="getTurnAdmissionStatuses",ka=50;import{z as g}from"zod";var Ao=["action_approved","action_declined","component_copy","component_export","component_followup","component_rendered","component_submit","component_tool","embed_loaded","failure","feedback_down","feedback_up","first_chunk","first_feedback_paint","first_server_content_paint","first_text_paint","message_copied","message_sent","opened","reconnected","retry","stopped","turn_completed","turn_stalled"],ko=["client-inactivity-watchdog","cloudflare-chat","message-send-failed","stream-error"],Io=["did_not_follow_instructions","incomplete","incorrect","not_relevant","other","unclear"],To=["client_stopped","conversation_deleted","provider_error","provider_rate_limited","provider_timeout","turn_deadline_exceeded","turn_stalled","unknown"],So=g.object({actionId:g.string().trim().min(1).max(256).optional(),componentId:g.string().trim().min(1).max(256).optional(),componentType:g.enum(pe).optional(),feedbackComment:g.string().trim().max(1e3).optional(),feedbackCommentLength:g.number().int().min(0).max(1e3).optional(),feedbackReasons:g.array(g.enum(Io)).max(6).optional(),format:g.enum(["csv","json","png","svg","text"]).optional(),hasFeedbackComment:g.boolean().optional(),hasToolName:g.boolean().optional(),latencyMs:g.number().finite().min(0).max(1800*1e3).optional(),latencyOrigin:g.literal("user_submit").optional(),messageId:g.string().trim().min(1).max(256).optional(),protocolVersion:g.literal(6).optional(),sdkVersion:g.string().trim().min(1).max(80).optional(),source:g.enum(ko).optional(),toolName:g.string().trim().min(1).max(160).optional()}).strict(),va=g.object({conversationId:g.string().uuid(),event:g.enum(Ao),properties:So.default({})}).strict(),wa=g.enum(To);export{ra as AGENT_CONVERSATION_SOURCE,ce as AGENT_MODEL_IDS,bo as AGENT_MODEL_OPTIONS,mt as AGENT_UI_CATALOG,ze as AGENT_UI_CONTAINER_KINDS,pe as AGENT_UI_KIND_NAMES,Zo as AGENT_UI_KIND_SCHEMAS,Oe as AGENT_UI_LAYOUT_LEAF_KINDS,Le as AGENT_UI_PRIMITIVE_KINDS,J as COMPOSED_UI_MAX_DEPTH,B as COMPOSED_UI_MAX_NODES,ca as DEFAULT_AGENT_PICKER_MODEL_ID,_o as HEROUI_AGENT_ATTACHMENT_ACCEPT,he as HEROUI_AGENT_ATTACHMENT_CONTENT_TYPES,ht as HEROUI_AGENT_ATTACHMENT_EXTENSION_BY_CONTENT_TYPE,wo as HEROUI_AGENT_ATTACHMENT_MAX_BYTES,Ao as HEROUI_AGENT_EMBED_EVENT_NAMES,ko as HEROUI_AGENT_EMBED_EVENT_SOURCES,Io as HEROUI_AGENT_FEEDBACK_REASONS,vo as HEROUI_AGENT_MAX_ATTACHMENTS,V as HEROUI_AGENT_PROTOCOL_VERSION,ye as HEROUI_AGENT_REMOTE_CONFIG_VERSION,ba as HEROUI_AGENT_RUNTIME_TIMING_EVENT,dt as HEROUI_AGENT_SDK_VERSION,Eo as HEROUI_AGENT_TEXT_ATTACHMENT_CONTENT_TYPES,ka as HEROUI_AGENT_TURN_ADMISSION_STATUS_MAX_IDS,Aa as HEROUI_AGENT_TURN_ADMISSION_STATUS_METHOD,xa as HEROUI_AGENT_TURN_ADMITTED_FRAME_TYPE,To as HEROUI_AGENT_TURN_ERROR_CODES,Co as LEGACY_AGENT_MODEL_IDS,so as MAX_CLIENT_TOOLS,lo as MAX_CLIENT_TOOLS_BYTES,ro as RESERVED_AGENT_TOOL_NAMES,io as RESERVED_AGENT_TOOL_PREFIX,In as accordionComponentSchema,wn as actionGroupComponentSchema,go as agentAuthIdentitySchema,ho as agentAuthProfileSchema,oa as agentAuthTokenSchema,Tt as agentIconNames,N as agentIconSchema,me as agentIdentityIdSchema,ya as agentModelIdSchema,ia as agentProjectConfigSchema,yo as agentSourceSchema,pa as agentSourcesSchema,co as agentSurfaceVariantSchema,mo as agentThemeSchema,aa as agentTokenClaimsSchema,Ee as agentUIComponentSchema,re as agentUILeafComponentSchema,le as agentUINodeSchema,Vo as agentUIRenderableSchema,Hn as analyticalLeafComponentSchema,Xt as areaChartComponentSchema,Ze as badgeComponentSchema,Jt as barChartComponentSchema,Ke as buttonComponentSchema,yn as calloutComponentSchema,ln as candlestickChartComponentSchema,it as cardComponentSchema,ee as cardComponentVariantSchema,jn as channelMessageComponentSchema,w as chartColorSchema,po as clientToolManifestEntrySchema,Xo as clientToolsSchema,Sn as codeBlockComponentSchema,at as colComponentSchema,un as comparisonListComponentSchema,Ko as composeUIInputSchema,Qt as composedChartComponentSchema,pt as composedUIComponentSchema,na as createAgentAuthTokenRequestSchema,On as createEventComponentSchema,Wn as dashboardComponentSchema,dn as dataTableComponentSchema,vn as diagramComponentSchema,Pe as dividerComponentSchema,tn as donutChartComponentSchema,Kn as enableNotificationComponentSchema,Vn as eventSessionComponentSchema,zn as flightTrackerComponentSchema,_n as followupComponentSchema,hn as formComponentSchema,pn as funnelChartComponentSchema,mn as gaugeChartComponentSchema,ua as getAgentModelTier,Ge as getAgentUIContainerChildren,rt as gridComponentSchema,Ve as headingComponentSchema,sn as heatmapComponentSchema,So as heroUIAgentEmbedEventPropertiesSchema,va as heroUIAgentEmbedEventSchema,wa as heroUIAgentTurnErrorCodeSchema,Fe as iconComponentSchema,Cn as imageComponentSchema,da as isAgentModelId,Me as isAgentUIContainerComponent,Do as isAgentUILayoutLeafComponent,Po as isAgentUIPrimitiveComponent,fe as isHeroUIAgentAttachmentContentType,se as itemCardComponentSchema,Je as itemCardGroupComponentSchema,Yt as kpiGridComponentSchema,Wt as lineChartComponentSchema,kn as listBlockComponentSchema,An as listComponentSchema,bn as mapComponentSchema,gn as meterListComponentSchema,$t as metricGridComponentSchema,C as numberFormatSchema,Uo as parseAgentRemoteConfig,en as pieChartComponentSchema,Dn as playerCardComponentSchema,Ln as playlistComponentSchema,Un as productCardComponentSchema,qn as productSignalsComponentSchema,qe as progressComponentSchema,Bn as purchaseCompleteComponentSchema,Gn as purchaseItemsComponentSchema,nn as radarChartComponentSchema,on as radialChartComponentSchema,He as ratingComponentSchema,Rn as recordCardComponentSchema,_t as recordCardLayoutSchema,$o as renderAgentUICatalogPrompt,Bo as renderComponentInputSchema,de as resolveAgentModelId,Mn as rideStatusComponentSchema,ot as rowComponentSchema,an as sankeyChartComponentSchema,rn as scatterChartComponentSchema,De as spacerComponentSchema,Tn as stepsComponentSchema,cn as sunburstChartComponentSchema,En as switchGroupComponentSchema,jo as tabsComponentSchema,xn as tagListComponentSchema,fn as textComponentSchema,Nn as toggleGroupComponentSchema,Pn as viewEventComponentSchema,X as weatherConditionSchema,St as weatherConditions,Fn as weatherCurrentComponentSchema,Zn as weatherForecastComponentSchema};
|
|
2
|
+
`)}import{z as L}from"zod";var ro=["callMcpTool","composeUI","executeSandbox","getComponentSchema","renderComponent","searchKnowledge","searchMcpTools","searchWeb"],io="mcp_",so=20,lo=16*1024,po=L.object({description:L.string().trim().min(1).max(1e3),inputSchema:L.record(L.string(),L.unknown()),name:L.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).refine(t=>!ro.includes(t)&&!t.toLowerCase().startsWith(io),"Client tool name is reserved by the HeroUI Agent runtime"),needsApproval:L.boolean().optional()}),Xo=L.array(po).max(so).superRefine((t,n)=>{let a=new Set;for(let i of t)a.has(i.name)&&n.addIssue({code:"custom",message:`Duplicate client tool name: ${i.name}`}),a.add(i.name);new TextEncoder().encode(JSON.stringify(t)).byteLength>lo&&n.addIssue({code:"custom",message:"Client tool manifest exceeds 16KB"})});import{z as p}from"zod";var V=6,dt="0.2.0-beta.11";var mo=p.enum(["light","dark","system"]),co=p.enum(["outline","plain","surface","surface-secondary"]),uo=new Set(["[object object]","0","anonymous","distinct_id","distinctid","email","false","guest","id","nan","none","not_authenticated","null","true","undefined"]),me=p.string().trim().min(1).max(200).refine(t=>!uo.has(t.toLowerCase()),{message:"Identity id is reserved"}),go=p.discriminatedUnion("type",[p.object({id:me,type:p.literal("anonymous")}),p.object({id:me,type:p.literal("user")})]),ho=p.object({avatarUrl:p.string().trim().pipe(p.url()).optional(),email:p.string().trim().max(320).pipe(p.email()).optional(),name:p.string().trim().max(120).optional()}),na=p.object({anonymousId:me.optional(),identity:go,profile:ho.optional()}),oa=p.object({expiresAt:p.number().int().positive(),token:p.string().trim().min(1)}),aa=p.object({agentId:p.string().trim().min(1).max(100),apiKeyId:p.string().trim().min(1).max(100),aud:p.literal("heroui-agent"),exp:p.number().int().positive(),iat:p.number().int().positive(),iss:p.literal("https://api.heroui.com"),jti:p.uuid(),protocolVersion:p.literal(6),sub:p.string().trim().min(1).max(200)}),ra={embed:"embed",preview:"preview"},ia=p.object({agentId:p.string(),minimumProtocolVersion:p.literal(6),name:p.string().trim().min(1).max(120),protocolVersion:p.literal(6),sdkVersion:p.string().default(dt),suggestedPrompts:p.array(p.string().trim().min(1).max(160)).max(5),surfaceVariant:co.default("plain"),theme:mo});import{z as k}from"zod";var ut=k.object({excerpt:k.string().trim().min(1).max(2e3).optional(),locator:k.string().trim().min(1).max(160).optional(),sourceId:k.string().trim().min(1).max(120)}),fo=k.string().trim().max(2048).refine(t=>{try{return["http:","https:"].includes(new URL(t).protocol)}catch{return!1}}),yo=k.union([ut.extend({sourceType:k.literal("document"),title:k.string().trim().min(1).max(200)}),ut.extend({sourceType:k.literal("url").optional(),title:k.string().trim().min(1).max(200).optional(),url:fo})]),pa=k.object({items:k.array(yo).min(1).max(16)});var ce=["moonshotai/Kimi-K3","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","google/gemini-3.6-flash","anthropic/claude-sonnet-5","anthropic/claude-opus-4.8"],Co={"google/gemini-3.5-flash":"google/gemini-3.6-flash"};function de(t){return Co[t]??t}var ca="openai/gpt-5.6-luna",bo=[{description:"Flagship model for coding, reasoning, and knowledge work",id:"moonshotai/Kimi-K3",label:"Kimi K3",provider:"Moonshot AI",tier:"light"},{description:"Fast answers and lightweight agent workflows",id:"openai/gpt-5.6-luna",label:"GPT-5.6 Luna",provider:"OpenAI",tier:"light"},{description:"Balanced reasoning for everyday agent tasks",id:"openai/gpt-5.6-terra",label:"GPT-5.6 Terra",provider:"OpenAI",tier:"codegen"},{description:"Deep reasoning for complex, multi-step analysis",id:"openai/gpt-5.6-sol",label:"GPT-5.6 Sol",provider:"OpenAI",tier:"complex"},{description:"Fast multimodal analysis with a large context window",id:"google/gemini-3.6-flash",label:"Gemini 3.6 Flash",provider:"Google",tier:"light"},{description:"Strong agentic reasoning and polished UI decisions",id:"anthropic/claude-sonnet-5",label:"Claude Sonnet 5",provider:"Anthropic",tier:"codegen"},{description:"Highest-capability Claude for difficult research and analysis",id:"anthropic/claude-opus-4.8",label:"Claude Opus 4.8",provider:"Anthropic",tier:"complex"}],xo=new Set(ce);function da(t){return typeof t=="string"&&xo.has(t)}function ua(t){let n=t?de(t):void 0;return bo.find(a=>a.id===n)?.tier??"light"}import{z as gt}from"zod";var ya=gt.preprocess(t=>typeof t=="string"?de(t):t,gt.enum(ce));var ba="heroui-agent:runtime-timing",xa="heroui_agent_turn_admitted",Aa="getTurnAdmissionStatuses",ka=50;import{z as g}from"zod";var Ao=["action_approved","action_declined","component_copy","component_export","component_followup","component_rendered","component_submit","component_tool","embed_loaded","failure","feedback_down","feedback_up","first_chunk","first_feedback_paint","first_server_content_paint","first_text_paint","message_copied","message_sent","opened","reconnected","retry","stopped","turn_completed","turn_stalled"],ko=["client-inactivity-watchdog","cloudflare-chat","message-send-failed","stream-error"],Io=["did_not_follow_instructions","incomplete","incorrect","not_relevant","other","unclear"],To=["client_stopped","conversation_deleted","provider_error","provider_rate_limited","provider_timeout","turn_deadline_exceeded","turn_stalled","unknown"],So=g.object({actionId:g.string().trim().min(1).max(256).optional(),componentId:g.string().trim().min(1).max(256).optional(),componentType:g.enum(pe).optional(),feedbackComment:g.string().trim().max(1e3).optional(),feedbackCommentLength:g.number().int().min(0).max(1e3).optional(),feedbackReasons:g.array(g.enum(Io)).max(6).optional(),format:g.enum(["csv","json","png","svg","text"]).optional(),hasFeedbackComment:g.boolean().optional(),hasToolName:g.boolean().optional(),latencyMs:g.number().finite().min(0).max(1800*1e3).optional(),latencyOrigin:g.literal("user_submit").optional(),messageId:g.string().trim().min(1).max(256).optional(),protocolVersion:g.literal(6).optional(),sdkVersion:g.string().trim().min(1).max(80).optional(),source:g.enum(ko).optional(),toolName:g.string().trim().min(1).max(160).optional()}).strict(),va=g.object({conversationId:g.string().uuid(),event:g.enum(Ao),properties:So.default({})}).strict(),wa=g.enum(To);export{ra as AGENT_CONVERSATION_SOURCE,ce as AGENT_MODEL_IDS,bo as AGENT_MODEL_OPTIONS,mt as AGENT_UI_CATALOG,ze as AGENT_UI_CONTAINER_KINDS,pe as AGENT_UI_KIND_NAMES,Zo as AGENT_UI_KIND_SCHEMAS,Oe as AGENT_UI_LAYOUT_LEAF_KINDS,Le as AGENT_UI_PRIMITIVE_KINDS,J as COMPOSED_UI_MAX_DEPTH,B as COMPOSED_UI_MAX_NODES,ca as DEFAULT_AGENT_PICKER_MODEL_ID,_o as HEROUI_AGENT_ATTACHMENT_ACCEPT,he as HEROUI_AGENT_ATTACHMENT_CONTENT_TYPES,ht as HEROUI_AGENT_ATTACHMENT_EXTENSION_BY_CONTENT_TYPE,wo as HEROUI_AGENT_ATTACHMENT_MAX_BYTES,Ao as HEROUI_AGENT_EMBED_EVENT_NAMES,ko as HEROUI_AGENT_EMBED_EVENT_SOURCES,Io as HEROUI_AGENT_FEEDBACK_REASONS,vo as HEROUI_AGENT_MAX_ATTACHMENTS,V as HEROUI_AGENT_PROTOCOL_VERSION,ye as HEROUI_AGENT_REMOTE_CONFIG_VERSION,ba as HEROUI_AGENT_RUNTIME_TIMING_EVENT,dt as HEROUI_AGENT_SDK_VERSION,Eo as HEROUI_AGENT_TEXT_ATTACHMENT_CONTENT_TYPES,ka as HEROUI_AGENT_TURN_ADMISSION_STATUS_MAX_IDS,Aa as HEROUI_AGENT_TURN_ADMISSION_STATUS_METHOD,xa as HEROUI_AGENT_TURN_ADMITTED_FRAME_TYPE,To as HEROUI_AGENT_TURN_ERROR_CODES,Co as LEGACY_AGENT_MODEL_IDS,so as MAX_CLIENT_TOOLS,lo as MAX_CLIENT_TOOLS_BYTES,ro as RESERVED_AGENT_TOOL_NAMES,io as RESERVED_AGENT_TOOL_PREFIX,In as accordionComponentSchema,wn as actionGroupComponentSchema,go as agentAuthIdentitySchema,ho as agentAuthProfileSchema,oa as agentAuthTokenSchema,Tt as agentIconNames,N as agentIconSchema,me as agentIdentityIdSchema,ya as agentModelIdSchema,ia as agentProjectConfigSchema,yo as agentSourceSchema,pa as agentSourcesSchema,co as agentSurfaceVariantSchema,mo as agentThemeSchema,aa as agentTokenClaimsSchema,Ee as agentUIComponentSchema,re as agentUILeafComponentSchema,le as agentUINodeSchema,Vo as agentUIRenderableSchema,Hn as analyticalLeafComponentSchema,Xt as areaChartComponentSchema,Ze as badgeComponentSchema,Jt as barChartComponentSchema,Ke as buttonComponentSchema,yn as calloutComponentSchema,ln as candlestickChartComponentSchema,it as cardComponentSchema,ee as cardComponentVariantSchema,jn as channelMessageComponentSchema,w as chartColorSchema,po as clientToolManifestEntrySchema,Xo as clientToolsSchema,Sn as codeBlockComponentSchema,at as colComponentSchema,un as comparisonListComponentSchema,Ko as composeUIInputSchema,Qt as composedChartComponentSchema,pt as composedUIComponentSchema,na as createAgentAuthTokenRequestSchema,On as createEventComponentSchema,Wn as dashboardComponentSchema,dn as dataTableComponentSchema,vn as diagramComponentSchema,Pe as dividerComponentSchema,tn as donutChartComponentSchema,Kn as enableNotificationComponentSchema,Vn as eventSessionComponentSchema,zn as flightTrackerComponentSchema,_n as followupComponentSchema,hn as formComponentSchema,pn as funnelChartComponentSchema,mn as gaugeChartComponentSchema,ua as getAgentModelTier,Ge as getAgentUIContainerChildren,rt as gridComponentSchema,Ve as headingComponentSchema,sn as heatmapComponentSchema,So as heroUIAgentEmbedEventPropertiesSchema,va as heroUIAgentEmbedEventSchema,wa as heroUIAgentTurnErrorCodeSchema,Fe as iconComponentSchema,Cn as imageComponentSchema,da as isAgentModelId,Me as isAgentUIContainerComponent,Do as isAgentUILayoutLeafComponent,Po as isAgentUIPrimitiveComponent,fe as isHeroUIAgentAttachmentContentType,se as itemCardComponentSchema,Je as itemCardGroupComponentSchema,Yt as kpiGridComponentSchema,Wt as lineChartComponentSchema,kn as listBlockComponentSchema,An as listComponentSchema,bn as mapComponentSchema,gn as meterListComponentSchema,$t as metricGridComponentSchema,C as numberFormatSchema,Uo as parseAgentRemoteConfig,en as pieChartComponentSchema,Dn as playerCardComponentSchema,Ln as playlistComponentSchema,Un as productCardComponentSchema,qn as productSignalsComponentSchema,qe as progressComponentSchema,Bn as purchaseCompleteComponentSchema,Gn as purchaseItemsComponentSchema,nn as radarChartComponentSchema,on as radialChartComponentSchema,He as ratingComponentSchema,Rn as recordCardComponentSchema,_t as recordCardLayoutSchema,$o as renderAgentUICatalogPrompt,Bo as renderComponentInputSchema,de as resolveAgentModelId,Mn as rideStatusComponentSchema,ot as rowComponentSchema,an as sankeyChartComponentSchema,rn as scatterChartComponentSchema,De as spacerComponentSchema,Tn as stepsComponentSchema,cn as sunburstChartComponentSchema,En as switchGroupComponentSchema,jo as tabsComponentSchema,xn as tagListComponentSchema,fn as textComponentSchema,Nn as toggleGroupComponentSchema,Pn as viewEventComponentSchema,X as weatherConditionSchema,St as weatherConditions,Fn as weatherCurrentComponentSchema,Zn as weatherForecastComponentSchema};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use client";import{a as Oo,b as Do,c as Ho}from"./chunk-MXLGM4WV.js";import{a as Ha,c as bn}from"./chunk-S6OIAJSC.js";import{a as me}from"./chunk-CR3H7AVI.js";import{A as vn,B as La,b as Ca,c as Vn,e as Aa,f as Ta,g as Eo,h as Po,k as Ea,l as Pa,m as $n,n as Ia,o as xa,p as Na,q as No,r as ka,s as _a,t as Oa,u as Da,v as Tr,w as ko,x as Rr,y as Mr,z as _o}from"./chunk-A53R5SMW.js";import{a as Io}from"./chunk-6ZJJN322.js";import{b as ba,c as Ar,d as Sa}from"./chunk-64RI74L5.js";import{c as Ra,d as Ma,e as xo,f as wa}from"./chunk-OA3TG5CS.js";import{a as Ua,b as Ba,c as Fa,d as Lo}from"./chunk-7KCGPNEN.js";import"./chunk-2XBFFSW2.js";import{a as Bo,b as $a,c as Ka,d as wr}from"./chunk-RNNGE7KM.js";import{a as Va,b as Uo}from"./chunk-PZJ4NC3J.js";import{useAgentChat as _g}from"@cloudflare/ai-chat/react";import{ArrowUp as Og,ArrowUpRight as Dg,Microphone as Uc,Plus as Bc,StopFill as Oc,Xmark as Lg}from"@gravity-ui/icons";function Rt(e){return!!(e&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e))}function Fo(e,t){return e===null?null:typeof e=="string"?Rt(e)?e:null:Rt(t)?t:null}var Er=30,Ga=52;function Vo(e){try{let t=JSON.parse(localStorage.getItem(e)??"[]");return Pr(t)}catch{return[]}}function Pr(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object"&&"id"in t&&typeof t.id=="string"&&Rt(t.id)&&"title"in t&&typeof t.title=="string"&&"updatedAt"in t&&typeof t.updatedAt=="number")).sort((t,n)=>n.updatedAt-t.updatedAt).slice(0,Er):[]}function $o(e,t){let n=new Map(e.map(r=>[r.id,r]));for(let r of t){let o=n.get(r.id);(!o||r.updatedAt>=o.updatedAt)&&n.set(r.id,r)}return[...n.values()].sort((r,o)=>o.updatedAt-r.updatedAt).slice(0,Er)}function Nt(e,t){localStorage.setItem(e,JSON.stringify(t.slice(0,Er)))}function Kn(e,t,n,r,{replaceTitle:o=!1}={}){if(!n)return e;let s=e.find(d=>d.id===t);return[{id:t,title:o?n:s?.title??n,updatedAt:r},...e.filter(d=>d.id!==t)].sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,Er)}function Ir(e){let t=e?.find(r=>r.role==="user"),n=t?.parts.filter(r=>r.type==="text").map(r=>r.text??"").join(" ");return n?.trim()?Go(n):t?"Attachment":null}function Ko(e,t){return e?Go(e):t[0]?.name||"Attachment"}function Go(e){let t=e.replace(/\s+/g," ").trim();return t.length>Ga?`${t.slice(0,Ga-1).trimEnd()}\u2026`:t}function qo(e){let t=new Date;t.setHours(0,0,0,0);let n=t.getTime(),r=n-8640*60*1e3,o=[{items:[],label:"Today"},{items:[],label:"Previous 7 days"},{items:[],label:"Older"}];for(let s of e)s.updatedAt>=n?o[0].items.push(s):s.updatedAt>=r?o[1].items.push(s):o[2].items.push(s);return o.filter(s=>s.items.length>0)}import{Disclosure as Sn}from"@heroui/react";import{jsx as Fe,jsxs as en}from"react/jsx-runtime";function vu(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase().replace(/^\w/,t=>t.toUpperCase())}function bu(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=Object.entries(e);return t.length===0||t.some(([,n])=>typeof n=="object")?null:t.map(([n,r])=>[vu(n),String(r)])}function qa({approveLabel:e="Allow",className:t,denyLabel:n="Deny",hint:r="Waiting for your approval",icon:o,input:s,onApprove:i,onDeny:d,title:l,...c}){let m=bu(s),p=s!=null&&(typeof s!="object"||Object.keys(s).length>0);return en("section",{"aria-label":l,className:me("aui-approval",t),"data-slot":"agent-ui-approval",...c,children:[en("div",{className:"aui-approval__heading","data-slot":"agent-ui-approval-heading",children:[o?Fe("span",{"aria-hidden":!0,className:"aui-approval__icon","data-slot":"agent-ui-approval-icon",children:o}):null,en("div",{className:"aui-approval__heading-text",children:[Fe("strong",{className:"aui-approval__title",children:l}),r?Fe("span",{className:"aui-approval__hint",children:r}):null]})]}),p?en(Sn,{defaultExpanded:!0,className:"aui-approval__disclosure",children:[Fe(Sn.Heading,{children:en(Sn.Trigger,{className:"aui-approval__disclosure-trigger",children:["Review action details",Fe(Sn.Indicator,{})]})}),Fe(Sn.Content,{children:Fe(Sn.Body,{children:m?Fe("dl",{className:"aui-approval__details","data-slot":"agent-ui-approval-details",children:m.map(([S,u])=>en("div",{className:"aui-approval__detail",children:[Fe("dt",{children:S}),Fe("dd",{children:u})]},S))}):Fe("pre",{className:"aui-approval__pre",children:JSON.stringify(s,null,2)})})})]}):null,en("div",{className:"aui-approval__actions","data-slot":"agent-ui-approval-actions",children:[Fe(Oo,{size:"md",variant:"tertiary",onClick:d,children:n}),Fe(Oo,{size:"md",variant:"primary",onClick:i,children:e})]})]})}import{Description as Mu,Label as wu,ListBox as Qo,Select as qn}from"@heroui/react";import{useCallback as Eu,useEffect as Pu,useRef as za,useState as Wa}from"react";import{useId as Su}from"react";import{jsx as q,jsxs as Gn}from"react/jsx-runtime";function Qa({className:e,provider:t}){let n=t?.toLowerCase();return n==="openai"?q(Cu,{className:e,"data-provider":"openai"}):n==="google"?q(Au,{className:e,"data-provider":"google"}):n==="anthropic"?q(Tu,{className:e,"data-provider":"anthropic"}):n==="moonshot ai"?q(Ru,{className:e,"data-provider":"moonshot-ai"}):null}function Cu(e){return q("svg",{"aria-hidden":"true",fill:"currentColor",focusable:"false",role:"presentation",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",...e,children:q("path",{d:"M22.282 9.821a5.985 5.985 0 0 0-.516-4.911 6.046 6.046 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.182a5.985 5.985 0 0 0-3.998 2.9 6.046 6.046 0 0 0 .743 7.096 5.98 5.98 0 0 0 .511 4.911 6.051 6.051 0 0 0 6.515 2.9A5.985 5.985 0 0 0 13.26 24a6.056 6.056 0 0 0 5.772-4.206 5.99 5.99 0 0 0 3.997-2.9 6.056 6.056 0 0 0-.747-7.073m-9.022 12.608a4.476 4.476 0 0 1-2.877-1.041l.142-.08 4.778-2.758a.795.795 0 0 0 .393-.682v-6.737l2.02 1.169a.07.07 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494M3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085 4.783 2.758a.77.77 0 0 0 .781 0l5.843-3.368v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.141-1.646M2.341 7.896a4.485 4.485 0 0 1 2.365-1.973V11.6a.766.766 0 0 0 .388.677l5.814 3.354-2.02 1.169a.08.08 0 0 1-.071 0l-4.83-2.787A4.504 4.504 0 0 1 2.34 7.872zm16.596 3.856-5.833-3.388L15.119 7.2a.08.08 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.104v-5.677a.79.79 0 0 0-.407-.667m2.011-3.023-.142-.085-4.773-2.782a.776.776 0 0 0-.786 0L9.409 9.23V6.897a.07.07 0 0 1 .028-.061l4.83-2.787a4.499 4.499 0 0 1 6.68 4.66zM8.307 12.863l-2.02-1.164a.08.08 0 0 1-.038-.056V6.074a4.499 4.499 0 0 1 7.376-3.453l-.142.08-4.778 2.758a.795.795 0 0 0-.393.682zm1.098-2.365 2.602-1.5 2.607 1.5v2.999l-2.598 1.5-2.607-1.5Z"})})}function Au(e){let t=Su().replace(/:/g,""),n=`${t}-gemini-shape`,r=`${t}-gemini-mask`,o=`${t}-gemini-yellow-blur`,s=`${t}-gemini-red-blur`,i=`${t}-gemini-green-blur`,d=`${t}-gemini-blue-blur`,l=`${t}-gemini-gold-blur`,c=`${t}-gemini-cyan-blur`,m=`${t}-gemini-violet-blur`,p=`${t}-gemini-coral-blur`,S=`${t}-gemini-lemon-blur`;return Gn("svg",{"aria-hidden":"true",fill:"none",focusable:"false",role:"presentation",viewBox:"0 0 32 32",xmlns:"http://www.w3.org/2000/svg",...e,children:[q("path",{d:"M0 0h32v32H0z",fill:"none"}),q("defs",{children:q("path",{d:"M57.067 28.61q-7.396-3.184-12.945-8.732q-5.547-5.546-8.732-12.944a38.4 38.4 0 0 1-1.97-5.824A1.464 1.464 0 0 0 32 .001c-.671 0-1.255.458-1.419 1.11a38.4 38.4 0 0 1-1.971 5.823q-3.186 7.397-8.732 12.944q-5.548 5.548-12.945 8.732a38.4 38.4 0 0 1-5.824 1.972A1.464 1.464 0 0 0 0 32c0 .67.458 1.255 1.11 1.418a38.4 38.4 0 0 1 5.823 1.972q7.396 3.184 12.945 8.732q5.55 5.546 8.732 12.944a38.4 38.4 0 0 1 1.971 5.824c.164.65.749 1.11 1.419 1.11s1.255-.458 1.419-1.11a38.4 38.4 0 0 1 1.971-5.823q3.185-7.395 8.732-12.944q5.548-5.548 12.945-8.732a38.4 38.4 0 0 1 5.824-1.972A1.464 1.464 0 0 0 64 32.001c0-.672-.458-1.255-1.11-1.42a38.4 38.4 0 0 1-5.823-1.97",fill:"#fff",id:n})}),Gn("g",{fill:"none",children:[Gn("g",{mask:`url(#${r})`,transform:"translate(2 2)scale(.4375)",children:[q("use",{href:`#${n}`}),q("g",{filter:`url(#${o})`,children:q("ellipse",{cx:"14.208",cy:"16.716",fill:"#ffe432",rx:"14.208",ry:"16.716",transform:"rotate(19.552 -43.96 -16.268)"})}),q("g",{filter:`url(#${s})`,children:q("ellipse",{cx:"27.054",cy:"2.551",fill:"#fc413d",rx:"18.394",ry:"18.799"})}),q("g",{filter:`url(#${i})`,children:q("ellipse",{cx:"19.224",cy:"24.904",fill:"#00b95c",rx:"19.224",ry:"24.904",transform:"rotate(-2.799 667.58 51.694)"})}),q("g",{filter:`url(#${i})`,children:q("ellipse",{cx:"18.843",cy:"20.744",fill:"#00b95c",rx:"18.843",ry:"20.744",transform:"rotate(-31.317 81.174 36.482)"})}),q("g",{filter:`url(#${d})`,children:q("ellipse",{cx:"66.462",cy:"24.977",fill:"#3186ff",rx:"18.093",ry:"17.423"})}),q("g",{filter:`url(#${l})`,children:q("ellipse",{cx:"20.929",cy:"22.075",fill:"#fbbc04",rx:"20.929",ry:"22.075",transform:"rotate(37.251 9.618 -7.898)"})}),q("g",{filter:`url(#${c})`,children:q("ellipse",{cx:"24.131",cy:"22.292",fill:"#3186ff",rx:"24.131",ry:"22.292",transform:"rotate(34.51 19.317 63.957)"})}),q("g",{filter:`url(#${m})`,children:q("path",{d:"M54.226-2.304c2.794 3.799-.797 11.184-8.02 16.497c-7.222 5.312-15.342 6.539-18.136 2.74S28.866 5.75 36.09.436c7.223-5.312 15.343-6.539 18.136-2.74",fill:"#749bff"})}),q("g",{filter:`url(#${p})`,children:q("ellipse",{cx:"27.585",cy:"17.148",fill:"#fc413d",rx:"27.585",ry:"17.148",transform:"rotate(-42.847 5.973 20.37)"})}),q("g",{filter:`url(#${S})`,children:q("ellipse",{cx:"14.782",cy:"8.596",fill:"#ffee48",rx:"14.782",ry:"8.596",transform:"rotate(35.592 -44.338 25.191)"})})]}),Gn("defs",{children:[q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"42.756",id:o,width:"38.868",x:"-19.618",y:"12.903",children:q("feGaussianBlur",{stdDeviation:"2.46"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"85.162",id:s,width:"84.353",x:"-15.122",y:"-40.03",children:q("feGaussianBlur",{stdDeviation:"11.891"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"90.22",id:i,width:"78.916",x:"-20.768",y:"11.483",children:q("feGaussianBlur",{stdDeviation:"10.109"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"73.27",id:d,width:"74.611",x:"29.156",y:"-11.658",children:q("feGaussianBlur",{stdDeviation:"9.606"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"78.151",id:l,width:"77.538",x:"-38.291",y:"-16.269",children:q("feGaussianBlur",{stdDeviation:"8.706"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"76.898",id:c,width:"78.218",x:"7.78",y:"-6.098",children:q("feGaussianBlur",{stdDeviation:"7.775"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"51.479",id:m,width:"55.879",x:"13.208",y:"-18.425",children:q("feGaussianBlur",{stdDeviation:"6.957"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"68.674",id:p,width:"70.203",x:"-15.474",y:"-31.027",children:q("feGaussianBlur",{stdDeviation:"5.876"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"51.261",id:S,width:"55.137",x:"-14.173",y:"20.474",children:q("feGaussianBlur",{stdDeviation:"7.273"})}),q("mask",{height:"64",id:r,maskUnits:"userSpaceOnUse",width:"64",x:"0",y:"0",children:q("use",{href:`#${n}`})})]})]})]})}function Tu(e){return q("svg",{"aria-hidden":"true",fill:"none",focusable:"false",role:"presentation",viewBox:"0 0 256 257",xmlns:"http://www.w3.org/2000/svg",...e,children:q("path",{d:"m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0l10.63 1.426 4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999z",fill:"#d97757"})})}function Ru(e){return Gn("svg",{"aria-hidden":"true",clipRule:"evenodd",fillRule:"evenodd",focusable:"false",role:"presentation",strokeLinejoin:"round",strokeMiterlimit:2,viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",...e,children:[q("path",{d:"M503 114.333v280c0 60.711-49.29 110-110 110H113c-60.711 0-110-49.289-110-110v-280c0-60.71 49.289-110 110-110h280c60.71 0 110 49.29 110 110z"}),q("path",{d:"M342.065 189.759c1.886-2.42 3.541-4.63 5.289-6.77.81-1.007.74-1.771-.046-2.824-7.58-9.965-8.298-21.028-3.935-32.254 3.275-8.448 10.52-12.406 19.373-13.25 5.52-.521 10.936.046 15.959 2.73 6.596 3.53 10.438 8.912 11.688 16.341.995 5.926.81 11.712-.868 17.452-2.974 10.161-10.277 15.427-20.287 16.758-8.31 1.11-16.734 1.25-25.113 1.817-.648.046-1.308 0-2.06 0z",fill:"#027aff"}),q("path",{d:"M321.512 144.254h-50.064l-39.637 90.384h-56.036v-89.99H131v232.868h44.787v-98.103h78.973c13.598 0 26.015-7.927 31.744-20.252v118.355h44.787v-98.103c0-23.342-18.239-42.97-41.523-44.671v-.116h-24.593a45.577 45.577 0 0026.884-24.534l29.453-65.838z",fill:"#fff"})]})}import{jsx as gt,jsxs as Qn}from"react/jsx-runtime";function Iu({description:e,provider:t}){return t?e?`${t} \xB7 ${e}`:t:e}function xr({"aria-label":e="AI model",className:t,isDisabled:n=!1,onChange:r,options:o,placement:s="top start",value:i}){let[d,l]=Wa(!1),[c,m]=Wa(),p=za(0),S=za(null),u=n||o.length===0,h=o.find(A=>A.id===i),x=Eu(A=>{S.current=A,A?.setAttribute("aria-keyshortcuts","Control+Shift+M"),m(bn(A))},[]),w=A=>{!A&&Date.now()-p.current<350||l(A)};return Pu(()=>{if(u)return;let A=O=>{O.defaultPrevented||O.isComposing||O.repeat||!O.ctrlKey||!O.shiftKey||O.altKey||O.metaKey||O.key.toLowerCase()!=="m"||(O.preventDefault(),S.current?.focus(),l(!0))};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[u]),Qn(qn,{"aria-label":e,className:me("aui-model-picker",t),isDisabled:u,isOpen:d,value:i,onOpenChange:w,onChange:A=>{A!=null&&r(A),l(!1)},children:[Qn(qn.Trigger,{ref:x,className:"aui-model-picker__trigger","data-shortcut":"\u2303\u21E7M","data-slot":"agent-ui-model-picker-trigger","data-tooltip":"Select model",onPointerDown:()=>{p.current=Date.now()},children:[gt(qn.Value,{className:"aui-model-picker__value",children:h?.label??i}),gt(qn.Indicator,{className:"aui-model-picker__indicator"}),Qn("span",{"aria-hidden":"true",className:"aui-picker-tooltip",children:[gt("span",{children:"Select model"}),gt("kbd",{className:"aui-picker-tooltip__shortcut",children:"\u2303\u21E7M"})]})]}),gt(qn.Popover,{className:"aui-model-picker__popover",placement:s,UNSTABLE_portalContainer:c,children:gt(Qo,{"aria-label":`${e} options`,className:"aui-model-picker__list",children:o.map(A=>{let O=Iu(A);return Qn(Qo.Item,{className:"aui-model-picker__option","data-description":O,id:A.id,textValue:A.label,children:[gt(Qa,{className:"aui-model-picker__option-icon",provider:A.provider}),Qn("span",{className:"aui-model-picker__option-copy",children:[gt(wu,{className:"aui-model-picker__option-label",children:A.label}),O?gt(Mu,{className:"aui-model-picker__option-description",title:O,children:O}):null]}),gt(Qo.ItemIndicator,{className:"aui-model-picker__option-indicator"})]},A.id)})})})]})}import{Hand as xu,LockOpen as Nu,ShieldCheck as Ja}from"@gravity-ui/icons";import{Description as ku,Label as _u,ListBox as zo,Select as zn}from"@heroui/react";import{useCallback as Ou,useEffect as Du,useRef as ja,useState as Ya}from"react";import{jsx as rt,jsxs as Wn}from"react/jsx-runtime";var Xa=[{description:"Ask before every client tool action.",icon:xu,id:"ask",label:"Ask for approval"},{description:"Only ask for actions marked as needing approval.",icon:Ja,id:"auto",label:"Approve for me"},{description:"Run client tools without asking for approval.",icon:Nu,id:"full",label:"Full access"}];function Nr({"aria-label":e="Tool permissions",className:t,isDisabled:n=!1,onChange:r,value:o}){let[s,i]=Ya(!1),[d,l]=Ya(),c=ja(0),m=ja(null),p=Xa.find(h=>h.id===o),S=Ou(h=>{m.current=h,h?.setAttribute("aria-keyshortcuts","Control+Shift+P"),l(bn(h))},[]),u=h=>{!h&&Date.now()-c.current<350||i(h)};return Du(()=>{if(n)return;let h=x=>{x.defaultPrevented||x.isComposing||x.repeat||!x.ctrlKey||!x.shiftKey||x.altKey||x.metaKey||x.key.toLowerCase()!=="p"||(x.preventDefault(),m.current?.focus(),i(!0))};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[n]),Wn(zn,{"aria-label":e,className:me("aui-permission-picker",t),"data-tone":o==="full"?"warning":void 0,isDisabled:n,isOpen:s,value:o,onOpenChange:u,onChange:h=>{h!=null&&r(h),i(!1)},children:[Wn(zn.Trigger,{ref:S,className:"aui-permission-picker__trigger","data-shortcut":"\u2303\u21E7P","data-slot":"agent-ui-permission-picker-trigger","data-tooltip":"Change permissions",onPointerDown:()=>{c.current=Date.now()},children:[rt(Ja,{"aria-hidden":"true",className:"aui-permission-picker__trigger-icon"}),rt(zn.Value,{className:"aui-permission-picker__value",children:p?.label??o}),rt(zn.Indicator,{className:"aui-permission-picker__indicator"}),Wn("span",{"aria-hidden":"true",className:"aui-picker-tooltip",children:[rt("span",{children:"Change permissions"}),rt("kbd",{className:"aui-picker-tooltip__shortcut",children:"\u2303\u21E7P"})]})]}),rt(zn.Popover,{className:"aui-permission-picker__popover",placement:"top start",UNSTABLE_portalContainer:d,children:rt(zo,{"aria-label":`${e} options`,className:"aui-permission-picker__list",children:Xa.map(h=>{let x=h.icon;return Wn(zo.Item,{className:"aui-permission-picker__option","data-description":h.description,"data-tone":h.id==="full"?"warning":void 0,id:h.id,textValue:h.label,children:[rt(x,{"aria-hidden":"true",className:"aui-permission-picker__option-icon"}),Wn("span",{className:"aui-permission-picker__option-copy",children:[rt(_u,{className:"aui-permission-picker__option-label",children:h.label}),rt(ku,{className:"aui-permission-picker__option-description",title:h.description,children:h.description})]}),rt(zo.ItemIndicator,{className:"aui-permission-picker__option-indicator"})]},h.id)})})})]})}import{useEffect as Wo,useRef as Cn}from"react";import{jsx as ei}from"react/jsx-runtime";var Lu=40,Za=2;function kr(e,t,n){return Math.min(n,Math.max(t,e))}function Hu(e){let t=kr(Math.round(e),32,32768);return 2**Math.round(Math.log2(t))}function Uu(e){return e instanceof Error?e:new Error("Unable to access the microphone.")}function Bu(){let e=window;return e.AudioContext??e.webkitAudioContext}function Fu(e){e?.getTracks().forEach(t=>t.stop())}function Vu(e){if(!(!e||e.state==="closed"))try{e.close().catch(()=>{})}catch{}}function $u(e,t,n,r,o){let s=Math.min(r/2,o/2);if(typeof e.roundRect!="function"){e.fillRect(t,n,r,o);return}e.beginPath(),e.roundRect(t,n,r,o,s),e.fill()}function jo({active:e=!1,"aria-label":t,barGap:n=2,barWidth:r=2,className:o,deviceId:s,fadeEdges:i=!0,fadeWidth:d=20,fftSize:l=256,height:c=Lu,onError:m,onStreamEnd:p,onStreamReady:S,role:u,sensitivity:h=1.15,smoothingTimeConstant:x=.82,stream:w,style:A,...O}){let _=Cn(null),N=Cn({onError:m,onStreamEnd:p,onStreamReady:S}),L=Cn(null),$=Cn(null),X=Cn(null),b=Cn([]);Wo(()=>{N.current={onError:m,onStreamEnd:p,onStreamReady:S}},[m,p,S]),Wo(()=>{if(!e||w===null){_.current=null;return}let M,T=!1,P=!1,z=!1,ie=w===void 0,j,F=w,K=Se=>{try{j?.disconnect()}catch{}j=void 0,_.current?.context===M&&(_.current=null),Vu(M),M=void 0,ie&&Fu(F),F=void 0,Se&&P&&!z&&(z=!0,N.current.onStreamEnd?.())};return(async()=>{try{let Se=Bu();if(!Se)throw new Error("Live audio analysis is not supported in this browser.");if(!F){if(!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone capture is not supported in this browser.");F=await navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,...s?{deviceId:{exact:s}}:{},echoCancellation:!0,noiseSuppression:!0}})}if(T){K(!1);return}M=new Se;let H=M.createAnalyser();if(H.fftSize=Hu(l),H.smoothingTimeConstant=kr(x,0,1),j=M.createMediaStreamSource(F),j.connect(H),M.state==="suspended"&&await M.resume(),T){K(!1);return}_.current=H,X.current=new Uint8Array(H.frequencyBinCount),P=!0,N.current.onStreamReady?.(F)}catch(Se){K(!1),T||N.current.onError?.(Uu(Se))}})(),()=>{T=!0,K(!0)}},[e,s,l,w,x]),Wo(()=>{let M=L.current,T=$.current;if(!M||!T)return;let P=M.getContext("2d");if(!P)return;let z=0,ie=getComputedStyle(M).color||"#000",j=0,F=0,K=0,ye=D=>{if(K<=0||F<=0)return;D-j>500&&(ie=getComputedStyle(M).color||ie,j=D),P.clearRect(0,0,K,F),P.fillStyle=ie;let k=Math.max(1,r),Y=Math.max(0,n),re=k+Y,oe=Math.max(1,Math.floor((K+Y)/re)),Me=Math.ceil(oe/2),Ge=_.current;b.current.length!==Me&&(b.current=Array.from({length:Me},()=>0));let at=b.current;if(e&&Ge){let pe=X.current;(!pe||pe.length!==Ge.frequencyBinCount)&&(pe=new Uint8Array(Ge.frequencyBinCount),X.current=pe),Ge.getByteFrequencyData(pe);let Oe=Math.max(1,Math.floor(pe.length*.025)),vt=Math.max(Oe+1,Math.floor(pe.length*.46)),it=kr(h,0,4);for(let ge=0;ge<Me;ge+=1){let Et=Me<=1?0:ge/(Me-1),Kt=Math.min(pe.length-1,Math.round(Oe+Et*(vt-Oe))),Pt=Math.pow((pe[Kt]??0)/255*it,.72);at[ge]=kr((at[ge]??0)*.56+Pt*.44,0,1)}}else at.fill(0);let un=Math.max(Za,F*.84),xn=F/2,wt=oe*k+(oe-1)*Y,Je=(K-wt)/2;for(let pe=0;pe<oe;pe+=1){let Oe=Me-1-Math.min(pe,oe-1-pe),vt=e?at[Oe]??0:0,it=Math.max(Za,vt*un),ge=Je+pe*re,Et=xn-it/2;P.globalAlpha=e?.38+vt*.62:.2,$u(P,ge,Et,k,it)}P.globalAlpha=1},Se=()=>{let D=T.getBoundingClientRect(),k=Math.max(1,window.devicePixelRatio||1),Y=getComputedStyle(M).color||ie;K=Math.max(0,D.width),F=Math.max(0,D.height),M.width=Math.max(1,Math.round(K*k)),M.height=Math.max(1,Math.round(F*k)),M.style.width=`${K}px`,M.style.height=`${F}px`,P.setTransform(k,0,0,k,0,0),ie=Y,ye(performance.now())},H=D=>{ye(D),z=requestAnimationFrame(H)};Se();let B;return typeof ResizeObserver>"u"?window.addEventListener("resize",Se):(B=new ResizeObserver(Se),B.observe(T)),e&&(z=requestAnimationFrame(H)),()=>{z&&cancelAnimationFrame(z),B?.disconnect(),window.removeEventListener("resize",Se)}},[e,n,r,h]);let f=typeof c=="number"?`${Math.max(1,c)}px`:c,v={...A,height:f},R=`${Math.max(0,d)}px`,y=`linear-gradient(90deg, transparent 0, #000 min(${R}, 20%), #000 calc(100% - min(${R}, 20%)), transparent 100%)`;return ei("div",{...O,ref:$,"aria-label":t??(e?"Live microphone waveform":"Microphone waveform"),className:me("aui-voice-live-waveform",o),"data-active":e||void 0,"data-fade-edges":i||void 0,"data-slot":"agent-ui-voice-live-waveform",role:u??"img",style:v,children:ei("canvas",{ref:L,"aria-hidden":"true",className:"aui-voice-live-waveform__canvas",style:i?{WebkitMaskImage:y,maskImage:y}:void 0})})}import{useCallback as Ve,useEffect as ti,useRef as $e,useState as _r,useSyncExternalStore as Ku}from"react";var Lr={"audio-capture":"No microphone was found. Check your audio input and try again.","bad-grammar":"Speech recognition could not understand the requested grammar.",language:"Speech recognition is not available for this language.","language-not-supported":"Speech recognition is not available for this language.",network:"Speech recognition lost its network connection. Try again.","no-speech":"No speech was detected. Try again when you are ready.","not-allowed":"Voice dictation was blocked. Check microphone and speech recognition permissions and try again.","service-not-allowed":"Speech recognition is blocked by your browser settings."},ri="Microphone access is blocked for this page. Allow microphone access and try again.",Gu="Microphone access is enabled, but speech recognition is blocked in this browser or embedded preview.",Xo="Voice dictation is not supported in this browser.",oi="Voice recording stopped unexpectedly. Try again.",qu=["audio/webm;codecs=opus","audio/mp4","audio/webm","audio/ogg;codecs=opus"],Qu=/\s+/g;function Dr(e,t){let n=t.trim().replace(Qu," ");return n?!e||/\s$/.test(e)||/^[,.;:!?)]/.test(n)?`${e}${n}`:`${e} ${n}`:e}function Hr(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0,n=t%60,r=Math.floor(t/60),o=r%60,s=Math.floor(r/60),i=String(n).padStart(2,"0");return s>0?`${s}:${String(o).padStart(2,"0")}:${i}`:`${o}:${i}`}function Jo(e,t,n="unknown"){if(e==="not-allowed"){if(n==="denied")return ri;if(n==="granted")return Gu}return Lr[e]??(t?.trim()||"Voice dictation stopped unexpectedly.")}async function zu(){if(typeof navigator>"u"||!navigator.permissions?.query)return"unknown";try{return(await navigator.permissions.query({name:"microphone"})).state}catch{return"unknown"}}function si(){if(typeof window>"u")return;let e=window;return e.SpeechRecognition??e.webkitSpeechRecognition}function Wu(){return!!si()}function ni(){return typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof MediaRecorder<"u"}function ju(){if(!(typeof MediaRecorder>"u"||typeof MediaRecorder.isTypeSupported!="function"))return qu.find(e=>MediaRecorder.isTypeSupported(e))}function Or(e){e?.getTracks().forEach(t=>t.stop())}function Yo(e){if(typeof DOMException<"u"&&e instanceof DOMException){if(e.name==="NotAllowedError"||e.name==="SecurityError")return ri;if(e.name==="NotFoundError"||e.name==="DevicesNotFoundError")return Lr["audio-capture"]}return e instanceof Error&&e.message.trim()?e.message:"Microphone access could not be started."}function Yu(e){return e.error??new Error(oi)}function Xu(){return()=>{}}function Zo({language:e,onValueChange:t,transcribe:n,value:r}){let[o,s]=_r("idle"),[i,d]=_r(0),[l,c]=_r(null),[m,p]=_r(null),S=Ve(()=>n?ni():Wu(),[n]),u=Ku(Xu,S,()=>!1),h=$e("idle"),x=$e(r),w=$e(null),A=$e(e),O=$e(t),_=$e(null),N=$e(null),L=$e(0),$=$e(0),X=$e(n),b=$e(null),f=$e(new Map),v=$e(r);ti(()=>{A.current=e,O.current=t,X.current=n,v.current=r},[e,t,n,r]);let R=Ve(H=>{h.current=H,s(H)},[]),y=Ve(()=>{w.current!==null&&(clearInterval(w.current),w.current=null)},[]),M=Ve(()=>{y(),$.current=Date.now(),d(0),w.current=setInterval(()=>{d(Math.floor((Date.now()-$.current)/1e3))},250)},[y]),T=Ve(H=>{H.onend=null,H.onerror=null,H.onresult=null,H.onstart=null},[]),P=Ve(H=>{H.ondataavailable=null,H.onerror=null,H.onstop=null},[]),z=Ve((H,B)=>{if(P(H.recorder),B&&H.recorder.state!=="inactive")try{H.recorder.stop()}catch{}Or(H.stream)},[P]),ie=Ve(async H=>{if(L.current!==H.session||_.current!==H){z(H,!1);return}_.current=null,P(H.recorder),Or(H.stream),p(null),y(),R("transcribing");let B=H.recorder.mimeType||H.chunks[0]?.type||"audio/webm",D=new Blob(H.chunks,{type:B}),k=X.current;if(!k||D.size===0){R("idle"),c(D.size===0?Lr["no-speech"]:oi);return}let Y=new AbortController;b.current=Y;try{let re=await k(D,{...A.current?{language:A.current}:{},signal:Y.signal});if(L.current!==H.session||Y.signal.aborted)return;if(!re.trim()){c(Lr["no-speech"]);return}O.current(Dr(x.current,re)),c(null)}catch(re){if(L.current!==H.session||Y.signal.aborted)return;c(re instanceof Error&&re.message.trim()?re.message:"Voice transcription could not be completed. Try again.")}finally{b.current===Y&&(b.current=null),L.current===H.session&&R("idle")}},[P,z,y,R]),j=Ve(()=>{L.current+=1,y(),b.current?.abort(),b.current=null,c(null),p(null),R("idle");let H=_.current,B=N.current;if(_.current=null,N.current=null,f.current.clear(),H&&z(H,!0),!!B){T(B);try{B.abort()}catch{}}},[T,z,y,R]),F=Ve(()=>{if(h.current==="transcribing"){j();return}let H=_.current;if(H){y(),R("transcribing");try{H.recorder.stop()}catch(D){L.current+=1,_.current=null,z(H,!1),p(null),R("idle"),c(D instanceof Error?D.message:"Voice recording could not be stopped cleanly.")}return}if(h.current==="recording"){j();return}let B=N.current;if(B){y();try{B.stop()}catch(D){R("idle"),L.current+=1,N.current=null,f.current.clear(),T(B);try{B.abort()}catch{}c(D instanceof Error?D.message:"Voice dictation could not be stopped cleanly.")}}},[j,T,z,y,R]),K=Ve(async()=>{if(!ni()){c(Xo);return}let H=L.current+1;L.current=H,x.current=v.current,c(null),d(0),p(null),R("recording");let B;try{B=await navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0}})}catch(Y){if(L.current!==H)return;R("idle"),c(Yo(Y));return}if(L.current!==H){Or(B);return}let D;try{let Y=ju();D=Y?new MediaRecorder(B,{mimeType:Y}):new MediaRecorder(B)}catch(Y){if(Or(B),L.current!==H)return;R("idle"),c(Yo(Y));return}let k={chunks:[],recorder:D,session:H,stream:B};D.ondataavailable=Y=>{Y.data.size>0&&k.chunks.push(Y.data)},D.onerror=Y=>{L.current!==H||_.current!==k||(L.current+=1,_.current=null,y(),z(k,!0),p(null),R("idle"),c(Yu(Y).message))},D.onstop=()=>{ie(k)},_.current=k,p(B);try{D.start(1e3),M()}catch(Y){L.current+=1,_.current=null,z(k,!1),p(null),R("idle"),c(Yo(Y))}},[z,ie,M,y,R]),ye=Ve(()=>{let H=si();if(!H){c(Xo);return}let B;try{B=new H}catch(k){c(k instanceof Error?k.message:"Voice dictation could not be started.");return}let D=L.current+1;L.current=D,x.current=v.current,f.current=new Map,B.continuous=!0,B.interimResults=!0,B.maxAlternatives=1,A.current&&(B.lang=A.current),B.onstart=()=>{L.current===D&&(R("recognizing"),M())},B.onresult=k=>{if(L.current!==D)return;let Y=Math.max(0,k.resultIndex);for(let oe of f.current.keys())oe>=Y&&f.current.delete(oe);for(let oe=Y;oe<k.results.length;oe+=1){let Ge=k.results[oe]?.[0]?.transcript;typeof Ge=="string"&&f.current.set(oe,Ge)}let re=Array.from(f.current.entries()).sort(([oe],[Me])=>oe-Me).map(([,oe])=>oe).reduce(Dr,"");O.current(Dr(x.current,re))},B.onerror=k=>{if(L.current!==D)return;y(),R("idle"),f.current.clear(),L.current+=1;let Y=L.current;k.error!=="aborted"&&(k.error==="not-allowed"?zu().then(re=>{L.current===Y&&c(Jo(k.error,k.message,re))}):c(Jo(k.error,k.message))),N.current===B&&(N.current=null,T(B))},B.onend=()=>{L.current===D&&(y(),R("idle"),N.current===B&&(N.current=null,T(B)))},N.current=B,c(null),d(0),R("recognizing");try{B.start()}catch(k){T(B),N.current=null,y(),R("idle"),c(k instanceof Error?k.message:"Voice dictation could not be started.")}},[T,M,y,R]),Se=Ve(()=>{h.current!=="idle"||N.current||_.current||b.current||(X.current?K():ye())},[ye,K]);return ti(()=>()=>{L.current+=1,y(),b.current?.abort(),b.current=null;let H=_.current,B=N.current;if(_.current=null,N.current=null,H&&z(H,!0),!!B){T(B);try{B.abort()}catch{}}},[T,z,y]),{cancel:j,elapsedSeconds:i,error:l,isActive:o!=="idle",isRecording:o==="recording",isSupported:u,isTranscribing:o==="transcribing",start:Se,stop:F,stream:m}}import{Spinner as Hg}from"@heroui/react/spinner";import{isTerminalCloseEvent as Ug}from"agents/client";import{useAgent as Bg}from"agents/react";import{Suspense as Fg,useCallback as W,useEffect as be,useEffectEvent as Vt,useId as Vg,useLayoutEffect as $t,useMemo as Ae,useRef as ce,useState as ee}from"react";import{z as te}from"zod";var We="0.2.0-beta.10";var Ju=te.enum(["light","dark","system"]),Zu=te.enum(["outline","plain","surface","surface-secondary"]),ed=new Set(["[object object]","0","anonymous","distinct_id","distinctid","email","false","guest","id","nan","none","not_authenticated","null","true","undefined"]),es=te.string().trim().min(1).max(200).refine(e=>!ed.has(e.toLowerCase()),{message:"Identity id is reserved"}),td=te.discriminatedUnion("type",[te.object({id:es,type:te.literal("anonymous")}),te.object({id:es,type:te.literal("user")})]),nd=te.object({avatarUrl:te.string().trim().pipe(te.url()).optional(),email:te.string().trim().max(320).pipe(te.email()).optional(),name:te.string().trim().max(120).optional()}),$f=te.object({anonymousId:es.optional(),identity:td,profile:nd.optional()}),Kf=te.object({expiresAt:te.number().int().positive(),token:te.string().trim().min(1)}),Gf=te.object({agentId:te.string().trim().min(1).max(100),apiKeyId:te.string().trim().min(1).max(100),aud:te.literal("heroui-agent"),exp:te.number().int().positive(),iat:te.number().int().positive(),iss:te.literal("https://api.heroui.com"),jti:te.uuid(),protocolVersion:te.literal(6),sub:te.string().trim().min(1).max(200)});var Ur=te.object({agentId:te.string(),minimumProtocolVersion:te.literal(6),name:te.string().trim().min(1).max(120),protocolVersion:te.literal(6),sdkVersion:te.string().default(We),suggestedPrompts:te.array(te.string().trim().min(1).max(160)).max(5),surfaceVariant:Zu.default("plain"),theme:Ju});var rd="understanding your request";function od(e){let t=e.replace(/\r\n?/g,`
|
|
1
|
+
"use client";import{a as Oo,b as Do,c as Ho}from"./chunk-MXLGM4WV.js";import{a as Ha,c as bn}from"./chunk-S6OIAJSC.js";import{a as me}from"./chunk-CR3H7AVI.js";import{A as vn,B as La,b as Ca,c as Vn,e as Aa,f as Ta,g as Eo,h as Po,k as Ea,l as Pa,m as $n,n as Ia,o as xa,p as Na,q as No,r as ka,s as _a,t as Oa,u as Da,v as Tr,w as ko,x as Rr,y as Mr,z as _o}from"./chunk-TV4IIQ5G.js";import{a as Io}from"./chunk-6ZJJN322.js";import{b as ba,c as Ar,d as Sa}from"./chunk-64RI74L5.js";import{c as Ra,d as Ma,e as xo,f as wa}from"./chunk-OA3TG5CS.js";import{a as Ua,b as Ba,c as Fa,d as Lo}from"./chunk-7KCGPNEN.js";import"./chunk-2XBFFSW2.js";import{a as Bo,b as $a,c as Ka,d as wr}from"./chunk-RNNGE7KM.js";import{a as Va,b as Uo}from"./chunk-PZJ4NC3J.js";import{useAgentChat as _g}from"@cloudflare/ai-chat/react";import{ArrowUp as Og,ArrowUpRight as Dg,Microphone as Uc,Plus as Bc,StopFill as Oc,Xmark as Lg}from"@gravity-ui/icons";function Rt(e){return!!(e&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e))}function Fo(e,t){return e===null?null:typeof e=="string"?Rt(e)?e:null:Rt(t)?t:null}var Er=30,Ga=52;function Vo(e){try{let t=JSON.parse(localStorage.getItem(e)??"[]");return Pr(t)}catch{return[]}}function Pr(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object"&&"id"in t&&typeof t.id=="string"&&Rt(t.id)&&"title"in t&&typeof t.title=="string"&&"updatedAt"in t&&typeof t.updatedAt=="number")).sort((t,n)=>n.updatedAt-t.updatedAt).slice(0,Er):[]}function $o(e,t){let n=new Map(e.map(r=>[r.id,r]));for(let r of t){let o=n.get(r.id);(!o||r.updatedAt>=o.updatedAt)&&n.set(r.id,r)}return[...n.values()].sort((r,o)=>o.updatedAt-r.updatedAt).slice(0,Er)}function Nt(e,t){localStorage.setItem(e,JSON.stringify(t.slice(0,Er)))}function Kn(e,t,n,r,{replaceTitle:o=!1}={}){if(!n)return e;let s=e.find(d=>d.id===t);return[{id:t,title:o?n:s?.title??n,updatedAt:r},...e.filter(d=>d.id!==t)].sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,Er)}function Ir(e){let t=e?.find(r=>r.role==="user"),n=t?.parts.filter(r=>r.type==="text").map(r=>r.text??"").join(" ");return n?.trim()?Go(n):t?"Attachment":null}function Ko(e,t){return e?Go(e):t[0]?.name||"Attachment"}function Go(e){let t=e.replace(/\s+/g," ").trim();return t.length>Ga?`${t.slice(0,Ga-1).trimEnd()}\u2026`:t}function qo(e){let t=new Date;t.setHours(0,0,0,0);let n=t.getTime(),r=n-8640*60*1e3,o=[{items:[],label:"Today"},{items:[],label:"Previous 7 days"},{items:[],label:"Older"}];for(let s of e)s.updatedAt>=n?o[0].items.push(s):s.updatedAt>=r?o[1].items.push(s):o[2].items.push(s);return o.filter(s=>s.items.length>0)}import{Disclosure as Sn}from"@heroui/react";import{jsx as Fe,jsxs as en}from"react/jsx-runtime";function vu(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase().replace(/^\w/,t=>t.toUpperCase())}function bu(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=Object.entries(e);return t.length===0||t.some(([,n])=>typeof n=="object")?null:t.map(([n,r])=>[vu(n),String(r)])}function qa({approveLabel:e="Allow",className:t,denyLabel:n="Deny",hint:r="Waiting for your approval",icon:o,input:s,onApprove:i,onDeny:d,title:l,...c}){let m=bu(s),p=s!=null&&(typeof s!="object"||Object.keys(s).length>0);return en("section",{"aria-label":l,className:me("aui-approval",t),"data-slot":"agent-ui-approval",...c,children:[en("div",{className:"aui-approval__heading","data-slot":"agent-ui-approval-heading",children:[o?Fe("span",{"aria-hidden":!0,className:"aui-approval__icon","data-slot":"agent-ui-approval-icon",children:o}):null,en("div",{className:"aui-approval__heading-text",children:[Fe("strong",{className:"aui-approval__title",children:l}),r?Fe("span",{className:"aui-approval__hint",children:r}):null]})]}),p?en(Sn,{defaultExpanded:!0,className:"aui-approval__disclosure",children:[Fe(Sn.Heading,{children:en(Sn.Trigger,{className:"aui-approval__disclosure-trigger",children:["Review action details",Fe(Sn.Indicator,{})]})}),Fe(Sn.Content,{children:Fe(Sn.Body,{children:m?Fe("dl",{className:"aui-approval__details","data-slot":"agent-ui-approval-details",children:m.map(([S,u])=>en("div",{className:"aui-approval__detail",children:[Fe("dt",{children:S}),Fe("dd",{children:u})]},S))}):Fe("pre",{className:"aui-approval__pre",children:JSON.stringify(s,null,2)})})})]}):null,en("div",{className:"aui-approval__actions","data-slot":"agent-ui-approval-actions",children:[Fe(Oo,{size:"md",variant:"tertiary",onClick:d,children:n}),Fe(Oo,{size:"md",variant:"primary",onClick:i,children:e})]})]})}import{Description as Mu,Label as wu,ListBox as Qo,Select as qn}from"@heroui/react";import{useCallback as Eu,useEffect as Pu,useRef as za,useState as Wa}from"react";import{useId as Su}from"react";import{jsx as q,jsxs as Gn}from"react/jsx-runtime";function Qa({className:e,provider:t}){let n=t?.toLowerCase();return n==="openai"?q(Cu,{className:e,"data-provider":"openai"}):n==="google"?q(Au,{className:e,"data-provider":"google"}):n==="anthropic"?q(Tu,{className:e,"data-provider":"anthropic"}):n==="moonshot ai"?q(Ru,{className:e,"data-provider":"moonshot-ai"}):null}function Cu(e){return q("svg",{"aria-hidden":"true",fill:"currentColor",focusable:"false",role:"presentation",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",...e,children:q("path",{d:"M22.282 9.821a5.985 5.985 0 0 0-.516-4.911 6.046 6.046 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.182a5.985 5.985 0 0 0-3.998 2.9 6.046 6.046 0 0 0 .743 7.096 5.98 5.98 0 0 0 .511 4.911 6.051 6.051 0 0 0 6.515 2.9A5.985 5.985 0 0 0 13.26 24a6.056 6.056 0 0 0 5.772-4.206 5.99 5.99 0 0 0 3.997-2.9 6.056 6.056 0 0 0-.747-7.073m-9.022 12.608a4.476 4.476 0 0 1-2.877-1.041l.142-.08 4.778-2.758a.795.795 0 0 0 .393-.682v-6.737l2.02 1.169a.07.07 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494M3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085 4.783 2.758a.77.77 0 0 0 .781 0l5.843-3.368v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.141-1.646M2.341 7.896a4.485 4.485 0 0 1 2.365-1.973V11.6a.766.766 0 0 0 .388.677l5.814 3.354-2.02 1.169a.08.08 0 0 1-.071 0l-4.83-2.787A4.504 4.504 0 0 1 2.34 7.872zm16.596 3.856-5.833-3.388L15.119 7.2a.08.08 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.104v-5.677a.79.79 0 0 0-.407-.667m2.011-3.023-.142-.085-4.773-2.782a.776.776 0 0 0-.786 0L9.409 9.23V6.897a.07.07 0 0 1 .028-.061l4.83-2.787a4.499 4.499 0 0 1 6.68 4.66zM8.307 12.863l-2.02-1.164a.08.08 0 0 1-.038-.056V6.074a4.499 4.499 0 0 1 7.376-3.453l-.142.08-4.778 2.758a.795.795 0 0 0-.393.682zm1.098-2.365 2.602-1.5 2.607 1.5v2.999l-2.598 1.5-2.607-1.5Z"})})}function Au(e){let t=Su().replace(/:/g,""),n=`${t}-gemini-shape`,r=`${t}-gemini-mask`,o=`${t}-gemini-yellow-blur`,s=`${t}-gemini-red-blur`,i=`${t}-gemini-green-blur`,d=`${t}-gemini-blue-blur`,l=`${t}-gemini-gold-blur`,c=`${t}-gemini-cyan-blur`,m=`${t}-gemini-violet-blur`,p=`${t}-gemini-coral-blur`,S=`${t}-gemini-lemon-blur`;return Gn("svg",{"aria-hidden":"true",fill:"none",focusable:"false",role:"presentation",viewBox:"0 0 32 32",xmlns:"http://www.w3.org/2000/svg",...e,children:[q("path",{d:"M0 0h32v32H0z",fill:"none"}),q("defs",{children:q("path",{d:"M57.067 28.61q-7.396-3.184-12.945-8.732q-5.547-5.546-8.732-12.944a38.4 38.4 0 0 1-1.97-5.824A1.464 1.464 0 0 0 32 .001c-.671 0-1.255.458-1.419 1.11a38.4 38.4 0 0 1-1.971 5.823q-3.186 7.397-8.732 12.944q-5.548 5.548-12.945 8.732a38.4 38.4 0 0 1-5.824 1.972A1.464 1.464 0 0 0 0 32c0 .67.458 1.255 1.11 1.418a38.4 38.4 0 0 1 5.823 1.972q7.396 3.184 12.945 8.732q5.55 5.546 8.732 12.944a38.4 38.4 0 0 1 1.971 5.824c.164.65.749 1.11 1.419 1.11s1.255-.458 1.419-1.11a38.4 38.4 0 0 1 1.971-5.823q3.185-7.395 8.732-12.944q5.548-5.548 12.945-8.732a38.4 38.4 0 0 1 5.824-1.972A1.464 1.464 0 0 0 64 32.001c0-.672-.458-1.255-1.11-1.42a38.4 38.4 0 0 1-5.823-1.97",fill:"#fff",id:n})}),Gn("g",{fill:"none",children:[Gn("g",{mask:`url(#${r})`,transform:"translate(2 2)scale(.4375)",children:[q("use",{href:`#${n}`}),q("g",{filter:`url(#${o})`,children:q("ellipse",{cx:"14.208",cy:"16.716",fill:"#ffe432",rx:"14.208",ry:"16.716",transform:"rotate(19.552 -43.96 -16.268)"})}),q("g",{filter:`url(#${s})`,children:q("ellipse",{cx:"27.054",cy:"2.551",fill:"#fc413d",rx:"18.394",ry:"18.799"})}),q("g",{filter:`url(#${i})`,children:q("ellipse",{cx:"19.224",cy:"24.904",fill:"#00b95c",rx:"19.224",ry:"24.904",transform:"rotate(-2.799 667.58 51.694)"})}),q("g",{filter:`url(#${i})`,children:q("ellipse",{cx:"18.843",cy:"20.744",fill:"#00b95c",rx:"18.843",ry:"20.744",transform:"rotate(-31.317 81.174 36.482)"})}),q("g",{filter:`url(#${d})`,children:q("ellipse",{cx:"66.462",cy:"24.977",fill:"#3186ff",rx:"18.093",ry:"17.423"})}),q("g",{filter:`url(#${l})`,children:q("ellipse",{cx:"20.929",cy:"22.075",fill:"#fbbc04",rx:"20.929",ry:"22.075",transform:"rotate(37.251 9.618 -7.898)"})}),q("g",{filter:`url(#${c})`,children:q("ellipse",{cx:"24.131",cy:"22.292",fill:"#3186ff",rx:"24.131",ry:"22.292",transform:"rotate(34.51 19.317 63.957)"})}),q("g",{filter:`url(#${m})`,children:q("path",{d:"M54.226-2.304c2.794 3.799-.797 11.184-8.02 16.497c-7.222 5.312-15.342 6.539-18.136 2.74S28.866 5.75 36.09.436c7.223-5.312 15.343-6.539 18.136-2.74",fill:"#749bff"})}),q("g",{filter:`url(#${p})`,children:q("ellipse",{cx:"27.585",cy:"17.148",fill:"#fc413d",rx:"27.585",ry:"17.148",transform:"rotate(-42.847 5.973 20.37)"})}),q("g",{filter:`url(#${S})`,children:q("ellipse",{cx:"14.782",cy:"8.596",fill:"#ffee48",rx:"14.782",ry:"8.596",transform:"rotate(35.592 -44.338 25.191)"})})]}),Gn("defs",{children:[q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"42.756",id:o,width:"38.868",x:"-19.618",y:"12.903",children:q("feGaussianBlur",{stdDeviation:"2.46"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"85.162",id:s,width:"84.353",x:"-15.122",y:"-40.03",children:q("feGaussianBlur",{stdDeviation:"11.891"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"90.22",id:i,width:"78.916",x:"-20.768",y:"11.483",children:q("feGaussianBlur",{stdDeviation:"10.109"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"73.27",id:d,width:"74.611",x:"29.156",y:"-11.658",children:q("feGaussianBlur",{stdDeviation:"9.606"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"78.151",id:l,width:"77.538",x:"-38.291",y:"-16.269",children:q("feGaussianBlur",{stdDeviation:"8.706"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"76.898",id:c,width:"78.218",x:"7.78",y:"-6.098",children:q("feGaussianBlur",{stdDeviation:"7.775"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"51.479",id:m,width:"55.879",x:"13.208",y:"-18.425",children:q("feGaussianBlur",{stdDeviation:"6.957"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"68.674",id:p,width:"70.203",x:"-15.474",y:"-31.027",children:q("feGaussianBlur",{stdDeviation:"5.876"})}),q("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"51.261",id:S,width:"55.137",x:"-14.173",y:"20.474",children:q("feGaussianBlur",{stdDeviation:"7.273"})}),q("mask",{height:"64",id:r,maskUnits:"userSpaceOnUse",width:"64",x:"0",y:"0",children:q("use",{href:`#${n}`})})]})]})]})}function Tu(e){return q("svg",{"aria-hidden":"true",fill:"none",focusable:"false",role:"presentation",viewBox:"0 0 256 257",xmlns:"http://www.w3.org/2000/svg",...e,children:q("path",{d:"m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0l10.63 1.426 4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999z",fill:"#d97757"})})}function Ru(e){return Gn("svg",{"aria-hidden":"true",clipRule:"evenodd",fillRule:"evenodd",focusable:"false",role:"presentation",strokeLinejoin:"round",strokeMiterlimit:2,viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",...e,children:[q("path",{d:"M503 114.333v280c0 60.711-49.29 110-110 110H113c-60.711 0-110-49.289-110-110v-280c0-60.71 49.289-110 110-110h280c60.71 0 110 49.29 110 110z"}),q("path",{d:"M342.065 189.759c1.886-2.42 3.541-4.63 5.289-6.77.81-1.007.74-1.771-.046-2.824-7.58-9.965-8.298-21.028-3.935-32.254 3.275-8.448 10.52-12.406 19.373-13.25 5.52-.521 10.936.046 15.959 2.73 6.596 3.53 10.438 8.912 11.688 16.341.995 5.926.81 11.712-.868 17.452-2.974 10.161-10.277 15.427-20.287 16.758-8.31 1.11-16.734 1.25-25.113 1.817-.648.046-1.308 0-2.06 0z",fill:"#027aff"}),q("path",{d:"M321.512 144.254h-50.064l-39.637 90.384h-56.036v-89.99H131v232.868h44.787v-98.103h78.973c13.598 0 26.015-7.927 31.744-20.252v118.355h44.787v-98.103c0-23.342-18.239-42.97-41.523-44.671v-.116h-24.593a45.577 45.577 0 0026.884-24.534l29.453-65.838z",fill:"#fff"})]})}import{jsx as gt,jsxs as Qn}from"react/jsx-runtime";function Iu({description:e,provider:t}){return t?e?`${t} \xB7 ${e}`:t:e}function xr({"aria-label":e="AI model",className:t,isDisabled:n=!1,onChange:r,options:o,placement:s="top start",value:i}){let[d,l]=Wa(!1),[c,m]=Wa(),p=za(0),S=za(null),u=n||o.length===0,h=o.find(A=>A.id===i),x=Eu(A=>{S.current=A,A?.setAttribute("aria-keyshortcuts","Control+Shift+M"),m(bn(A))},[]),w=A=>{!A&&Date.now()-p.current<350||l(A)};return Pu(()=>{if(u)return;let A=O=>{O.defaultPrevented||O.isComposing||O.repeat||!O.ctrlKey||!O.shiftKey||O.altKey||O.metaKey||O.key.toLowerCase()!=="m"||(O.preventDefault(),S.current?.focus(),l(!0))};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[u]),Qn(qn,{"aria-label":e,className:me("aui-model-picker",t),isDisabled:u,isOpen:d,value:i,onOpenChange:w,onChange:A=>{A!=null&&r(A),l(!1)},children:[Qn(qn.Trigger,{ref:x,className:"aui-model-picker__trigger","data-shortcut":"\u2303\u21E7M","data-slot":"agent-ui-model-picker-trigger","data-tooltip":"Select model",onPointerDown:()=>{p.current=Date.now()},children:[gt(qn.Value,{className:"aui-model-picker__value",children:h?.label??i}),gt(qn.Indicator,{className:"aui-model-picker__indicator"}),Qn("span",{"aria-hidden":"true",className:"aui-picker-tooltip",children:[gt("span",{children:"Select model"}),gt("kbd",{className:"aui-picker-tooltip__shortcut",children:"\u2303\u21E7M"})]})]}),gt(qn.Popover,{className:"aui-model-picker__popover",placement:s,UNSTABLE_portalContainer:c,children:gt(Qo,{"aria-label":`${e} options`,className:"aui-model-picker__list",children:o.map(A=>{let O=Iu(A);return Qn(Qo.Item,{className:"aui-model-picker__option","data-description":O,id:A.id,textValue:A.label,children:[gt(Qa,{className:"aui-model-picker__option-icon",provider:A.provider}),Qn("span",{className:"aui-model-picker__option-copy",children:[gt(wu,{className:"aui-model-picker__option-label",children:A.label}),O?gt(Mu,{className:"aui-model-picker__option-description",title:O,children:O}):null]}),gt(Qo.ItemIndicator,{className:"aui-model-picker__option-indicator"})]},A.id)})})})]})}import{Hand as xu,LockOpen as Nu,ShieldCheck as Ja}from"@gravity-ui/icons";import{Description as ku,Label as _u,ListBox as zo,Select as zn}from"@heroui/react";import{useCallback as Ou,useEffect as Du,useRef as ja,useState as Ya}from"react";import{jsx as rt,jsxs as Wn}from"react/jsx-runtime";var Xa=[{description:"Ask before every client tool action.",icon:xu,id:"ask",label:"Ask for approval"},{description:"Only ask for actions marked as needing approval.",icon:Ja,id:"auto",label:"Approve for me"},{description:"Run client tools without asking for approval.",icon:Nu,id:"full",label:"Full access"}];function Nr({"aria-label":e="Tool permissions",className:t,isDisabled:n=!1,onChange:r,value:o}){let[s,i]=Ya(!1),[d,l]=Ya(),c=ja(0),m=ja(null),p=Xa.find(h=>h.id===o),S=Ou(h=>{m.current=h,h?.setAttribute("aria-keyshortcuts","Control+Shift+P"),l(bn(h))},[]),u=h=>{!h&&Date.now()-c.current<350||i(h)};return Du(()=>{if(n)return;let h=x=>{x.defaultPrevented||x.isComposing||x.repeat||!x.ctrlKey||!x.shiftKey||x.altKey||x.metaKey||x.key.toLowerCase()!=="p"||(x.preventDefault(),m.current?.focus(),i(!0))};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[n]),Wn(zn,{"aria-label":e,className:me("aui-permission-picker",t),"data-tone":o==="full"?"warning":void 0,isDisabled:n,isOpen:s,value:o,onOpenChange:u,onChange:h=>{h!=null&&r(h),i(!1)},children:[Wn(zn.Trigger,{ref:S,className:"aui-permission-picker__trigger","data-shortcut":"\u2303\u21E7P","data-slot":"agent-ui-permission-picker-trigger","data-tooltip":"Change permissions",onPointerDown:()=>{c.current=Date.now()},children:[rt(Ja,{"aria-hidden":"true",className:"aui-permission-picker__trigger-icon"}),rt(zn.Value,{className:"aui-permission-picker__value",children:p?.label??o}),rt(zn.Indicator,{className:"aui-permission-picker__indicator"}),Wn("span",{"aria-hidden":"true",className:"aui-picker-tooltip",children:[rt("span",{children:"Change permissions"}),rt("kbd",{className:"aui-picker-tooltip__shortcut",children:"\u2303\u21E7P"})]})]}),rt(zn.Popover,{className:"aui-permission-picker__popover",placement:"top start",UNSTABLE_portalContainer:d,children:rt(zo,{"aria-label":`${e} options`,className:"aui-permission-picker__list",children:Xa.map(h=>{let x=h.icon;return Wn(zo.Item,{className:"aui-permission-picker__option","data-description":h.description,"data-tone":h.id==="full"?"warning":void 0,id:h.id,textValue:h.label,children:[rt(x,{"aria-hidden":"true",className:"aui-permission-picker__option-icon"}),Wn("span",{className:"aui-permission-picker__option-copy",children:[rt(_u,{className:"aui-permission-picker__option-label",children:h.label}),rt(ku,{className:"aui-permission-picker__option-description",title:h.description,children:h.description})]}),rt(zo.ItemIndicator,{className:"aui-permission-picker__option-indicator"})]},h.id)})})})]})}import{useEffect as Wo,useRef as Cn}from"react";import{jsx as ei}from"react/jsx-runtime";var Lu=40,Za=2;function kr(e,t,n){return Math.min(n,Math.max(t,e))}function Hu(e){let t=kr(Math.round(e),32,32768);return 2**Math.round(Math.log2(t))}function Uu(e){return e instanceof Error?e:new Error("Unable to access the microphone.")}function Bu(){let e=window;return e.AudioContext??e.webkitAudioContext}function Fu(e){e?.getTracks().forEach(t=>t.stop())}function Vu(e){if(!(!e||e.state==="closed"))try{e.close().catch(()=>{})}catch{}}function $u(e,t,n,r,o){let s=Math.min(r/2,o/2);if(typeof e.roundRect!="function"){e.fillRect(t,n,r,o);return}e.beginPath(),e.roundRect(t,n,r,o,s),e.fill()}function jo({active:e=!1,"aria-label":t,barGap:n=2,barWidth:r=2,className:o,deviceId:s,fadeEdges:i=!0,fadeWidth:d=20,fftSize:l=256,height:c=Lu,onError:m,onStreamEnd:p,onStreamReady:S,role:u,sensitivity:h=1.15,smoothingTimeConstant:x=.82,stream:w,style:A,...O}){let _=Cn(null),N=Cn({onError:m,onStreamEnd:p,onStreamReady:S}),L=Cn(null),$=Cn(null),X=Cn(null),b=Cn([]);Wo(()=>{N.current={onError:m,onStreamEnd:p,onStreamReady:S}},[m,p,S]),Wo(()=>{if(!e||w===null){_.current=null;return}let M,T=!1,P=!1,z=!1,ie=w===void 0,j,F=w,K=Se=>{try{j?.disconnect()}catch{}j=void 0,_.current?.context===M&&(_.current=null),Vu(M),M=void 0,ie&&Fu(F),F=void 0,Se&&P&&!z&&(z=!0,N.current.onStreamEnd?.())};return(async()=>{try{let Se=Bu();if(!Se)throw new Error("Live audio analysis is not supported in this browser.");if(!F){if(!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone capture is not supported in this browser.");F=await navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,...s?{deviceId:{exact:s}}:{},echoCancellation:!0,noiseSuppression:!0}})}if(T){K(!1);return}M=new Se;let H=M.createAnalyser();if(H.fftSize=Hu(l),H.smoothingTimeConstant=kr(x,0,1),j=M.createMediaStreamSource(F),j.connect(H),M.state==="suspended"&&await M.resume(),T){K(!1);return}_.current=H,X.current=new Uint8Array(H.frequencyBinCount),P=!0,N.current.onStreamReady?.(F)}catch(Se){K(!1),T||N.current.onError?.(Uu(Se))}})(),()=>{T=!0,K(!0)}},[e,s,l,w,x]),Wo(()=>{let M=L.current,T=$.current;if(!M||!T)return;let P=M.getContext("2d");if(!P)return;let z=0,ie=getComputedStyle(M).color||"#000",j=0,F=0,K=0,ye=D=>{if(K<=0||F<=0)return;D-j>500&&(ie=getComputedStyle(M).color||ie,j=D),P.clearRect(0,0,K,F),P.fillStyle=ie;let k=Math.max(1,r),Y=Math.max(0,n),re=k+Y,oe=Math.max(1,Math.floor((K+Y)/re)),Me=Math.ceil(oe/2),Ge=_.current;b.current.length!==Me&&(b.current=Array.from({length:Me},()=>0));let at=b.current;if(e&&Ge){let pe=X.current;(!pe||pe.length!==Ge.frequencyBinCount)&&(pe=new Uint8Array(Ge.frequencyBinCount),X.current=pe),Ge.getByteFrequencyData(pe);let Oe=Math.max(1,Math.floor(pe.length*.025)),vt=Math.max(Oe+1,Math.floor(pe.length*.46)),it=kr(h,0,4);for(let ge=0;ge<Me;ge+=1){let Et=Me<=1?0:ge/(Me-1),Kt=Math.min(pe.length-1,Math.round(Oe+Et*(vt-Oe))),Pt=Math.pow((pe[Kt]??0)/255*it,.72);at[ge]=kr((at[ge]??0)*.56+Pt*.44,0,1)}}else at.fill(0);let un=Math.max(Za,F*.84),xn=F/2,wt=oe*k+(oe-1)*Y,Je=(K-wt)/2;for(let pe=0;pe<oe;pe+=1){let Oe=Me-1-Math.min(pe,oe-1-pe),vt=e?at[Oe]??0:0,it=Math.max(Za,vt*un),ge=Je+pe*re,Et=xn-it/2;P.globalAlpha=e?.38+vt*.62:.2,$u(P,ge,Et,k,it)}P.globalAlpha=1},Se=()=>{let D=T.getBoundingClientRect(),k=Math.max(1,window.devicePixelRatio||1),Y=getComputedStyle(M).color||ie;K=Math.max(0,D.width),F=Math.max(0,D.height),M.width=Math.max(1,Math.round(K*k)),M.height=Math.max(1,Math.round(F*k)),M.style.width=`${K}px`,M.style.height=`${F}px`,P.setTransform(k,0,0,k,0,0),ie=Y,ye(performance.now())},H=D=>{ye(D),z=requestAnimationFrame(H)};Se();let B;return typeof ResizeObserver>"u"?window.addEventListener("resize",Se):(B=new ResizeObserver(Se),B.observe(T)),e&&(z=requestAnimationFrame(H)),()=>{z&&cancelAnimationFrame(z),B?.disconnect(),window.removeEventListener("resize",Se)}},[e,n,r,h]);let f=typeof c=="number"?`${Math.max(1,c)}px`:c,v={...A,height:f},R=`${Math.max(0,d)}px`,y=`linear-gradient(90deg, transparent 0, #000 min(${R}, 20%), #000 calc(100% - min(${R}, 20%)), transparent 100%)`;return ei("div",{...O,ref:$,"aria-label":t??(e?"Live microphone waveform":"Microphone waveform"),className:me("aui-voice-live-waveform",o),"data-active":e||void 0,"data-fade-edges":i||void 0,"data-slot":"agent-ui-voice-live-waveform",role:u??"img",style:v,children:ei("canvas",{ref:L,"aria-hidden":"true",className:"aui-voice-live-waveform__canvas",style:i?{WebkitMaskImage:y,maskImage:y}:void 0})})}import{useCallback as Ve,useEffect as ti,useRef as $e,useState as _r,useSyncExternalStore as Ku}from"react";var Lr={"audio-capture":"No microphone was found. Check your audio input and try again.","bad-grammar":"Speech recognition could not understand the requested grammar.",language:"Speech recognition is not available for this language.","language-not-supported":"Speech recognition is not available for this language.",network:"Speech recognition lost its network connection. Try again.","no-speech":"No speech was detected. Try again when you are ready.","not-allowed":"Voice dictation was blocked. Check microphone and speech recognition permissions and try again.","service-not-allowed":"Speech recognition is blocked by your browser settings."},ri="Microphone access is blocked for this page. Allow microphone access and try again.",Gu="Microphone access is enabled, but speech recognition is blocked in this browser or embedded preview.",Xo="Voice dictation is not supported in this browser.",oi="Voice recording stopped unexpectedly. Try again.",qu=["audio/webm;codecs=opus","audio/mp4","audio/webm","audio/ogg;codecs=opus"],Qu=/\s+/g;function Dr(e,t){let n=t.trim().replace(Qu," ");return n?!e||/\s$/.test(e)||/^[,.;:!?)]/.test(n)?`${e}${n}`:`${e} ${n}`:e}function Hr(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0,n=t%60,r=Math.floor(t/60),o=r%60,s=Math.floor(r/60),i=String(n).padStart(2,"0");return s>0?`${s}:${String(o).padStart(2,"0")}:${i}`:`${o}:${i}`}function Jo(e,t,n="unknown"){if(e==="not-allowed"){if(n==="denied")return ri;if(n==="granted")return Gu}return Lr[e]??(t?.trim()||"Voice dictation stopped unexpectedly.")}async function zu(){if(typeof navigator>"u"||!navigator.permissions?.query)return"unknown";try{return(await navigator.permissions.query({name:"microphone"})).state}catch{return"unknown"}}function si(){if(typeof window>"u")return;let e=window;return e.SpeechRecognition??e.webkitSpeechRecognition}function Wu(){return!!si()}function ni(){return typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof MediaRecorder<"u"}function ju(){if(!(typeof MediaRecorder>"u"||typeof MediaRecorder.isTypeSupported!="function"))return qu.find(e=>MediaRecorder.isTypeSupported(e))}function Or(e){e?.getTracks().forEach(t=>t.stop())}function Yo(e){if(typeof DOMException<"u"&&e instanceof DOMException){if(e.name==="NotAllowedError"||e.name==="SecurityError")return ri;if(e.name==="NotFoundError"||e.name==="DevicesNotFoundError")return Lr["audio-capture"]}return e instanceof Error&&e.message.trim()?e.message:"Microphone access could not be started."}function Yu(e){return e.error??new Error(oi)}function Xu(){return()=>{}}function Zo({language:e,onValueChange:t,transcribe:n,value:r}){let[o,s]=_r("idle"),[i,d]=_r(0),[l,c]=_r(null),[m,p]=_r(null),S=Ve(()=>n?ni():Wu(),[n]),u=Ku(Xu,S,()=>!1),h=$e("idle"),x=$e(r),w=$e(null),A=$e(e),O=$e(t),_=$e(null),N=$e(null),L=$e(0),$=$e(0),X=$e(n),b=$e(null),f=$e(new Map),v=$e(r);ti(()=>{A.current=e,O.current=t,X.current=n,v.current=r},[e,t,n,r]);let R=Ve(H=>{h.current=H,s(H)},[]),y=Ve(()=>{w.current!==null&&(clearInterval(w.current),w.current=null)},[]),M=Ve(()=>{y(),$.current=Date.now(),d(0),w.current=setInterval(()=>{d(Math.floor((Date.now()-$.current)/1e3))},250)},[y]),T=Ve(H=>{H.onend=null,H.onerror=null,H.onresult=null,H.onstart=null},[]),P=Ve(H=>{H.ondataavailable=null,H.onerror=null,H.onstop=null},[]),z=Ve((H,B)=>{if(P(H.recorder),B&&H.recorder.state!=="inactive")try{H.recorder.stop()}catch{}Or(H.stream)},[P]),ie=Ve(async H=>{if(L.current!==H.session||_.current!==H){z(H,!1);return}_.current=null,P(H.recorder),Or(H.stream),p(null),y(),R("transcribing");let B=H.recorder.mimeType||H.chunks[0]?.type||"audio/webm",D=new Blob(H.chunks,{type:B}),k=X.current;if(!k||D.size===0){R("idle"),c(D.size===0?Lr["no-speech"]:oi);return}let Y=new AbortController;b.current=Y;try{let re=await k(D,{...A.current?{language:A.current}:{},signal:Y.signal});if(L.current!==H.session||Y.signal.aborted)return;if(!re.trim()){c(Lr["no-speech"]);return}O.current(Dr(x.current,re)),c(null)}catch(re){if(L.current!==H.session||Y.signal.aborted)return;c(re instanceof Error&&re.message.trim()?re.message:"Voice transcription could not be completed. Try again.")}finally{b.current===Y&&(b.current=null),L.current===H.session&&R("idle")}},[P,z,y,R]),j=Ve(()=>{L.current+=1,y(),b.current?.abort(),b.current=null,c(null),p(null),R("idle");let H=_.current,B=N.current;if(_.current=null,N.current=null,f.current.clear(),H&&z(H,!0),!!B){T(B);try{B.abort()}catch{}}},[T,z,y,R]),F=Ve(()=>{if(h.current==="transcribing"){j();return}let H=_.current;if(H){y(),R("transcribing");try{H.recorder.stop()}catch(D){L.current+=1,_.current=null,z(H,!1),p(null),R("idle"),c(D instanceof Error?D.message:"Voice recording could not be stopped cleanly.")}return}if(h.current==="recording"){j();return}let B=N.current;if(B){y();try{B.stop()}catch(D){R("idle"),L.current+=1,N.current=null,f.current.clear(),T(B);try{B.abort()}catch{}c(D instanceof Error?D.message:"Voice dictation could not be stopped cleanly.")}}},[j,T,z,y,R]),K=Ve(async()=>{if(!ni()){c(Xo);return}let H=L.current+1;L.current=H,x.current=v.current,c(null),d(0),p(null),R("recording");let B;try{B=await navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0}})}catch(Y){if(L.current!==H)return;R("idle"),c(Yo(Y));return}if(L.current!==H){Or(B);return}let D;try{let Y=ju();D=Y?new MediaRecorder(B,{mimeType:Y}):new MediaRecorder(B)}catch(Y){if(Or(B),L.current!==H)return;R("idle"),c(Yo(Y));return}let k={chunks:[],recorder:D,session:H,stream:B};D.ondataavailable=Y=>{Y.data.size>0&&k.chunks.push(Y.data)},D.onerror=Y=>{L.current!==H||_.current!==k||(L.current+=1,_.current=null,y(),z(k,!0),p(null),R("idle"),c(Yu(Y).message))},D.onstop=()=>{ie(k)},_.current=k,p(B);try{D.start(1e3),M()}catch(Y){L.current+=1,_.current=null,z(k,!1),p(null),R("idle"),c(Yo(Y))}},[z,ie,M,y,R]),ye=Ve(()=>{let H=si();if(!H){c(Xo);return}let B;try{B=new H}catch(k){c(k instanceof Error?k.message:"Voice dictation could not be started.");return}let D=L.current+1;L.current=D,x.current=v.current,f.current=new Map,B.continuous=!0,B.interimResults=!0,B.maxAlternatives=1,A.current&&(B.lang=A.current),B.onstart=()=>{L.current===D&&(R("recognizing"),M())},B.onresult=k=>{if(L.current!==D)return;let Y=Math.max(0,k.resultIndex);for(let oe of f.current.keys())oe>=Y&&f.current.delete(oe);for(let oe=Y;oe<k.results.length;oe+=1){let Ge=k.results[oe]?.[0]?.transcript;typeof Ge=="string"&&f.current.set(oe,Ge)}let re=Array.from(f.current.entries()).sort(([oe],[Me])=>oe-Me).map(([,oe])=>oe).reduce(Dr,"");O.current(Dr(x.current,re))},B.onerror=k=>{if(L.current!==D)return;y(),R("idle"),f.current.clear(),L.current+=1;let Y=L.current;k.error!=="aborted"&&(k.error==="not-allowed"?zu().then(re=>{L.current===Y&&c(Jo(k.error,k.message,re))}):c(Jo(k.error,k.message))),N.current===B&&(N.current=null,T(B))},B.onend=()=>{L.current===D&&(y(),R("idle"),N.current===B&&(N.current=null,T(B)))},N.current=B,c(null),d(0),R("recognizing");try{B.start()}catch(k){T(B),N.current=null,y(),R("idle"),c(k instanceof Error?k.message:"Voice dictation could not be started.")}},[T,M,y,R]),Se=Ve(()=>{h.current!=="idle"||N.current||_.current||b.current||(X.current?K():ye())},[ye,K]);return ti(()=>()=>{L.current+=1,y(),b.current?.abort(),b.current=null;let H=_.current,B=N.current;if(_.current=null,N.current=null,H&&z(H,!0),!!B){T(B);try{B.abort()}catch{}}},[T,z,y]),{cancel:j,elapsedSeconds:i,error:l,isActive:o!=="idle",isRecording:o==="recording",isSupported:u,isTranscribing:o==="transcribing",start:Se,stop:F,stream:m}}import{Spinner as Hg}from"@heroui/react/spinner";import{isTerminalCloseEvent as Ug}from"agents/client";import{useAgent as Bg}from"agents/react";import{Suspense as Fg,useCallback as W,useEffect as be,useEffectEvent as Vt,useId as Vg,useLayoutEffect as $t,useMemo as Ae,useRef as ce,useState as ee}from"react";import{z as te}from"zod";var We="0.2.0-beta.11";var Ju=te.enum(["light","dark","system"]),Zu=te.enum(["outline","plain","surface","surface-secondary"]),ed=new Set(["[object object]","0","anonymous","distinct_id","distinctid","email","false","guest","id","nan","none","not_authenticated","null","true","undefined"]),es=te.string().trim().min(1).max(200).refine(e=>!ed.has(e.toLowerCase()),{message:"Identity id is reserved"}),td=te.discriminatedUnion("type",[te.object({id:es,type:te.literal("anonymous")}),te.object({id:es,type:te.literal("user")})]),nd=te.object({avatarUrl:te.string().trim().pipe(te.url()).optional(),email:te.string().trim().max(320).pipe(te.email()).optional(),name:te.string().trim().max(120).optional()}),$f=te.object({anonymousId:es.optional(),identity:td,profile:nd.optional()}),Kf=te.object({expiresAt:te.number().int().positive(),token:te.string().trim().min(1)}),Gf=te.object({agentId:te.string().trim().min(1).max(100),apiKeyId:te.string().trim().min(1).max(100),aud:te.literal("heroui-agent"),exp:te.number().int().positive(),iat:te.number().int().positive(),iss:te.literal("https://api.heroui.com"),jti:te.uuid(),protocolVersion:te.literal(6),sub:te.string().trim().min(1).max(200)});var Ur=te.object({agentId:te.string(),minimumProtocolVersion:te.literal(6),name:te.string().trim().min(1).max(120),protocolVersion:te.literal(6),sdkVersion:te.string().default(We),suggestedPrompts:te.array(te.string().trim().min(1).max(160)).max(5),surfaceVariant:Zu.default("plain"),theme:Ju});var rd="understanding your request";function od(e){let t=e.replace(/\r\n?/g,`
|
|
2
2
|
`).trim();if(!t)return null;if(t.length<=1600)return t;let n=t.slice(0,1601),r=n.lastIndexOf(" "),o=r>=1600*.8?r:1600;return`${n.slice(0,o).trimEnd()}\u2026`}function sd(e){let t=e.replace(/\[([^\]]+)\]\([^\s)]+\)/g,"$1").replace(/[*_`~]/g,"").replace(/\s+/g," ").replace(/[.…!?:;,|—–-]+$/u,"").trim();return!t||t.length>80?null:t.replace(/^\p{Ll}/u,n=>n.toLocaleUpperCase())}function ad(e,t){let n=e.replace(/\r\n?/g,`
|
|
3
3
|
`).trim();if(!n)return null;let r=/^#{1,6}\s+([^\n]+)\n+([\s\S]+)$/u.exec(n),o=/^(?:\*\*([^*\n]+)\*\*|__([^_\n]+)__)([\s\S]+)$/u.exec(n),s=r?.[1]??o?.[1]??o?.[2],i=r?.[2]??o?.[3],d=s?sd(s):null,l=i?.replace(/^\s*(?:[|:—–-]\s*)?/u,"").trim(),c=od(d&&l?l:n);return c?{detail:c,label:d??(t===0?"Thinking through your request":"Thinking through the next step")}:null}function id(e){if(!e.input||typeof e.input!="object"||Array.isArray(e.input))return null;let t=e.input.query;if(typeof t!="string")return null;let n=t.replace(/\s+/g," ").trim();return!n||n.length>300?null:n}function ts(e){return e.toLocaleLowerCase().replace(/[.…]+$/u,"").trim()}function ld(e,t){return t!=="accepted"&&t!=="preparing"?!1:ts(e)===rd}function ai(e){return e.type==="dynamic-tool"&&e.toolName?e.toolName:e.type.startsWith("tool-")?e.type.slice(5):null}function ii(e){return e==="renderComponent"||e==="composeUI"}var cd={ai:"AI",api:"API",crm:"CRM",csv:"CSV",id:"ID",mcp:"MCP",sql:"SQL",ui:"UI",url:"URL"};function ud(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").trim().split(/\s+/).map((n,r)=>{let o=cd[n.toLowerCase()];return o||(r===0?n.replace(/^\w/,s=>s.toUpperCase()):n)}).join(" ")}function Br(e){let t=e.toLowerCase();return/search|find|look up|research/.test(t)?"search":/web|source|browse|url/.test(t)?"browse":/code|sandbox|python|script|compute/.test(t)?"code":/chart|graph|visual|plot/.test(t)?"chart":/data|query|load|fetch|metric|table|account/.test(t)?"data":"thinking"}function li(e,t){if(!t.hasContent)return!1;let n=e.reduce((r,o)=>Math.max(r,o.messagePartIndex??-1),-1);return t.latestContentPartIndex>=n}function ns(e,t,n={}){if(e.role!=="assistant")return[];let r=[],o=new Set,s=0,i;for(let[l,c]of e.parts.entries()){if(c.type==="reasoning"){let N=ad(c.text,s);if(!N)continue;r.push({active:n.isStreaming===!0&&c.state!=="done",detail:N.detail,detailVisibility:"always",id:`${e.id}-reasoning-${l}`,kind:"thinking",label:N.label,messagePartIndex:l,stateKnown:c.state!==void 0,...r.length===0&&i?{title:i}:{}}),s+=1;continue}if(c.type==="data-activity"){let N=c.data.label.trim(),L=c.data.title?.trim();if(L&&!i){i=L;let $=r[0];$&&!$.title&&(r[0]={...$,title:L})}if(ld(N,c.data.stage)||L&&ts(N)===ts(L))continue;if(N&&o.has(N)){let $=r.findIndex(b=>b.label===N),X=r[$];L&&X&&!X.title&&(r[$]={...X,title:L})}else N&&(o.add(N),r.push({active:!1,detail:c.data.detail,id:c.id??`${e.id}-activity-${l}`,kind:c.data.kind??Br(N),label:N,messagePartIndex:l,sources:c.data.sources,stateKnown:!1,...L||r.length===0&&i?{title:L??i}:{}}));continue}let m=ai(c);if(!m)continue;let p=c,S=ii(m),u=S&&e.parts.slice(l+1).some(N=>{let L=ai(N);return L!==null&&ii(L)&&N.state==="output-available"});if(S&&p.state==="output-error"&&(n.isStreaming||u))continue;let h=m==="searchWeb"?id(p):null,x=S?"Building your data view":m==="executeSandbox"?"Analyzing your data":m==="getComponentSchema"?"Preparing your data view":h?`Searching the web for \u201C${h}\u201D`:t.get(m)?.displayName??ud(m),A=p.state==="output-denied"||!!(p.output&&typeof p.output=="object"&&"rejected"in p.output&&p.output.rejected)?h?`Skipped web search for \u201C${h}\u201D`:`Skipped ${x}`:p.state==="output-error"?h?`Couldn\u2019t search the web for \u201C${h}\u201D`:`Couldn\u2019t complete ${x}`:x,O=["input-available","input-streaming","approval-requested","approval-responded"].includes(p.state),_=r.findIndex(N=>N.label===A);if(_>=0){let N=r[_];N&&(r[_]={...N,active:O,messagePartIndex:l,stateKnown:!0,...!N.title&&i?{title:i}:{}});continue}o.add(A),r.push({active:O,id:p.toolCallId||`${e.id}-tool-${l}`,kind:S?"chart":m==="executeSandbox"?"code":m==="getComponentSchema"?"thinking":Br(A),label:A,messagePartIndex:l,stateKnown:!0,...r.length===0&&i?{title:i}:{}})}if(!n.isStreaming||r.length===0||r.some(l=>l.active))return r;let d=r.length-1;return r[d]?.stateKnown?r:r.map((l,c)=>({...l,active:c===d}))}var dd={accepted:"Thinking\u2026",generating:"Writing the answer\u2026",preparing:"Preparing the answer\u2026",recovering:"Recovering your answer\u2026","running-server-tool":"Running tools\u2026","waiting-client-tool":"Waiting for a browser action\u2026"},pd=new Set(["accepted","preparing","generating","waiting-client-tool","running-server-tool","recovering"]);function md(e){return e.type==="dynamic-tool"&&e.toolName?e.toolName:e.type.startsWith("tool-")?e.type.slice(5):null}function jn(e){return e?dd[e]:null}function ci({clientToolNames:e,isLocalPending:t,isRecovering:n,isStreaming:r,messages:o,status:s}){if(n)return"recovering";let i=o.findLast(d=>d.role==="assistant");if(i){for(let l=i.parts.length-1;l>=0;l-=1){let c=i.parts[l],m=md(c);if(m&&["input-streaming","input-available","approval-requested","approval-responded"].includes(c.state??""))return e.has(m)?"waiting-client-tool":"running-server-tool";if(c.type==="data-activity"||c.type==="data-progress"){let p=c.data?.stage;if(typeof p=="string"&&pd.has(p))return p}}let d=i.parts.some(l=>l.type==="text"&&l.text.trim().length>0||l.type==="data-component");if(r&&d)return"generating"}return r||s==="streaming"?"preparing":t||s==="submitted"?"accepted":null}import{ChartColumn as Od,CircleCheck as Dd,Code as Ld,Database as Hd,Globe as hi,Magnifier as Ud,Wrench as Bd}from"@gravity-ui/icons";import{Disclosure as je}from"@heroui/react";import{useEffect as yi,useRef as ss,useState as as}from"react";import{useEffect as fd,useState as hd}from"react";import{jsx as gd}from"react/jsx-runtime";function tn({children:e,className:t,...n}){return gd("span",{...n,className:`ha-shimmer${t?` ${t}`:""}`,children:e})}import{jsx as Fr,jsxs as vd}from"react/jsx-runtime";var yd=280;function Vr({animateOnMount:e=!0,children:t,className:n,...r}){let[o,s]=hd(()=>({current:{animate:e,id:0,text:t},previous:null}));o.current.text!==t&&s({current:{animate:!0,id:o.current.id+1,text:t},previous:o.current});let i=o.current.id,d=o.previous;return fd(()=>{if(!d)return;let l=window.setTimeout(()=>{s(c=>c.current.id===i?{...c,previous:null}:c)},yd);return()=>window.clearTimeout(l)},[i,d]),vd("span",{...r,"aria-label":r["aria-label"]??t,className:`ha-status-text${n?` ${n}`:""}`,"data-slot":"animated-text",children:[Fr("span",{"aria-hidden":"true","data-slot":"animated-text-value",className:o.current.animate?"ha-status-text__value ha-status-text__value--animated":"ha-status-text__value",children:Fr(tn,{children:o.current.text})},o.current.id),o.previous?Fr("span",{"aria-hidden":"true",className:"ha-status-text__value ha-status-text__value--exiting","data-slot":"animated-text-previous-value",children:Fr(tn,{children:o.previous.text})},o.previous.id):null]})}import{Code as bd,Heading as An,Link as Sd,Paragraph as Cd,Separator as Ad,Table as kt}from"@heroui/react";import{Children as ui,Suspense as di,isValidElement as pi,lazy as Td,memo as Rd,useMemo as Md}from"react";import{jsx as fe,jsxs as Nd}from"react/jsx-runtime";var wd=Td(()=>import("streamdown").then(e=>({default:e.Streamdown})));function Ed(e){return e?.match(/language-([^\s]+)/)?.[1]??"plaintext"}function Pd(e,t){return e?.find(n=>Array.isArray(n.language)?n.language.includes(t):n.language===t)}function rs(e){return ui.toArray(e?.props.children).filter(t=>pi(t))}function os(e,t){return ui.toArray(e).find(n=>pi(n)&&n.props.node?.tagName===t)}function Id({children:e}){let t=os(e,"thead"),n=os(e,"tbody"),r=os(t?.props.children,"tr"),o=rs(r),s=rs(n);return fe(kt,{"data-slot":"markdown-table",variant:"secondary",children:fe(kt.ScrollContainer,{children:Nd(kt.Content,{"aria-label":"Markdown table",children:[fe(kt.Header,{children:o.map((i,d)=>fe(kt.Column,{id:`column-${d}`,isRowHeader:d===0,children:i.props.children},String(i.key)))}),fe(kt.Body,{children:s.map((i,d)=>fe(kt.Row,{id:`row-${d}`,children:rs(i).map(l=>fe(kt.Cell,{children:l.props.children},String(l.key)))},String(i.key)))})]})})})}function xd(e,t){function n({children:o,className:s,node:i}){let d=Ed(s),l=String(o??"").replace(/\n$/,""),c=Pd(e?.renderers,d);if(c){let m=c.component,p=i?.properties?.metastring;return fe(di,{fallback:fe(Ho,{code:l,language:d}),children:fe(m,{code:l,isIncomplete:t,language:d,meta:typeof p=="string"?p:void 0})})}return fe(Ho,{code:l,language:d})}function r({children:o,className:s}){return fe(bd,{className:s,"data-slot":"markdown-inline-code",children:o})}return{a:({children:o,className:s,href:i})=>fe(Sd,{className:s,href:i,rel:"noreferrer",target:"_blank",children:o}),code:n,h1:({children:o,className:s})=>fe(An,{className:s,level:1,children:o}),h2:({children:o,className:s})=>fe(An,{className:s,level:2,children:o}),h3:({children:o,className:s})=>fe(An,{className:s,level:3,children:o}),h4:({children:o,className:s})=>fe(An,{className:s,level:4,children:o}),h5:({children:o,className:s})=>fe(An,{className:s,level:5,children:o}),h6:({children:o,className:s})=>fe(An,{className:s,level:6,children:o}),hr:({className:o})=>fe(Ad,{className:o,"data-slot":"markdown-separator",variant:"tertiary"}),inlineCode:r,p:({children:o,className:s})=>fe(Cd,{className:s,"data-slot":"markdown-paragraph",size:"sm",children:o}),table:Id}}var $r=Rd(function({animated:t=La,caret:n="block",children:r,isStreaming:o=!1,plugins:s}){let i=Md(()=>xd(s,o),[o,s]);return fe(di,{fallback:fe("div",{className:"ha-markdown","data-streaming":o?!0:void 0,children:fe("p",{children:r})}),children:fe("div",{className:"ha-markdown","data-streaming":o?!0:void 0,children:fe(wd,{normalizeHtmlIndentation:!0,parseIncompleteMarkdown:!0,animated:t,caret:o&&n!==!1?n:void 0,components:i,controls:!1,isAnimating:o,lineNumbers:!1,linkSafety:{enabled:!1},mode:o?"streaming":"static",plugins:s,children:r})})})});import{useEffect as kd}from"react";function _d(e,t=1){let n=e.scrollTop>t,r=e.scrollTop+e.clientHeight+t<e.scrollHeight;return n&&r?"both":n?"top":r?"bottom":"none"}function mi(e,t){delete e.dataset.topScroll,delete e.dataset.bottomScroll,delete e.dataset.topBottomScroll,t==="both"?e.dataset.topBottomScroll="true":t==="top"?e.dataset.topScroll="true":t==="bottom"&&(e.dataset.bottomScroll="true")}function nn(e,t=1){kd(()=>{let n=e.current;if(!n)return;let r=null,o=null,s=()=>{r!==null&&cancelAnimationFrame(r),r=requestAnimationFrame(()=>{r=null;let l=_d(n,t);l!==o&&(o=l,mi(n,l))})};s(),n.addEventListener("scroll",s,{passive:!0});let i=typeof ResizeObserver>"u"?null:new ResizeObserver(s),d=typeof MutationObserver>"u"?null:new MutationObserver(s);return i?.observe(n),d?.observe(n,{characterData:!0,childList:!0,subtree:!0}),()=>{n.removeEventListener("scroll",s),i?.disconnect(),d?.disconnect(),r!==null&&cancelAnimationFrame(r),mi(n,"none")}},[t,e])}import{jsx as ne,jsxs as ft}from"react/jsx-runtime";var Fd=24,Vd=160,$d=220;function vi(e,t,n,r){let o=ss(!0);yi(()=>{let s=e.current;if(!s)return;let i,d=!1,l=()=>{let h=s.scrollHeight-s.scrollTop-s.clientHeight;o.current=h<=Fd},c=()=>{d||l()},m=()=>{d=!1,window.clearTimeout(i),requestAnimationFrame(l)},p=()=>{if(!r||!n||!o.current)return;let h=typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,x=s.scrollHeight;if(typeof s.scrollTo!="function"){s.scrollTop=x;return}d=!h,s.scrollTo({behavior:h?"auto":"smooth",top:x}),window.clearTimeout(i),i=window.setTimeout(()=>{d=!1,l()},360)};s.addEventListener("scroll",c,{passive:!0}),s.addEventListener("pointerdown",m,{passive:!0}),s.addEventListener("touchstart",m,{passive:!0}),s.addEventListener("wheel",m,{passive:!0}),p();let S=s.firstElementChild,u=S&&typeof ResizeObserver<"u"?new ResizeObserver(p):null;return S&&u?.observe(S),()=>{s.removeEventListener("scroll",c),s.removeEventListener("pointerdown",m),s.removeEventListener("touchstart",m),s.removeEventListener("wheel",m),u?.disconnect(),window.clearTimeout(i)}},[t,r,n,e])}function Kd(e){let[t,n]=as(()=>({isStreaming:e,phase:e?"expanded":"collapsed"})),r=t.phase;return t.isStreaming!==e&&(r=e?"expanded":"fading",n({isStreaming:e,phase:r})),yi(()=>{if(e||r==="collapsed"||r==="expanded")return;let o=typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,s=o?"collapsed":r==="fading"?"collapsing":"collapsed",i=o?0:r==="fading"?Vd:$d,d=window.setTimeout(()=>{n(l=>l.isStreaming===e&&l.phase===r?{...l,phase:s}:l)},i);return()=>window.clearTimeout(d)},[e,r]),r}var Gd={browse:hi,chart:Od,code:Ld,data:Hd,search:Ud,thinking:Bd},gi="Working on your request";function Kr(e){return e.toLocaleLowerCase().replace(/\s+/g," ").replace(/[.…!?:;,]+$/u,"").trim()}function qd(e){let t=e.find(d=>d.title?.trim()),n=t?.title?.trim(),r=e.find(d=>Kr(d.label)!=="understanding your request")??e[0],o=t??r,s=o?.kind??Br(o?.label??n??""),i=new Set(e.map(d=>Kr(d.label)));return n&&!i.has(Kr(n))?{kind:s,title:n}:{kind:s,title:i.has(Kr(gi))?"Making progress":gi}}function fi({active:e}){return ft("span",{className:"ha-activity-icon","data-state":e?"active":"complete",children:[ne("span",{"aria-hidden":"true",className:"ha-activity-icon-state ha-activity-icon-state--active",children:ne("span",{className:"ha-activity-spinner"})}),ne("span",{"aria-hidden":"true",className:"ha-activity-icon-state ha-activity-icon-state--complete",children:ne(Dd,{})})]})}function bi({active:e,label:t}){return e?ne(Vr,{className:"ha-activity-step-label ha-progress-shimmer",children:t}):ne("span",{className:"ha-activity-step-label",children:t})}function Qd({detail:e,isDetailActive:t,isLabelActive:n,isTurnActive:r,label:o,markdownAnimation:s,markdownPlugins:i}){let[d,l]=as(()=>({isDetailActive:t,isExpanded:t})),c=d.isExpanded;d.isDetailActive!==t&&(c=t,l({isDetailActive:t,isExpanded:c}));let m=ss(null);return nn(m),vi(m,e,t&&r,c),ft(je,{className:"ha-activity-step-disclosure",isExpanded:c,onExpandedChange:p=>l({isDetailActive:t,isExpanded:p}),children:[ne(je.Heading,{children:ft(je.Trigger,{className:"ha-activity-step-trigger",children:[ne(bi,{active:n,label:o}),ne(je.Indicator,{className:"ha-activity-step-chevron"})]})}),ne(je.Content,{className:"ha-activity-step-disclosure-content",children:ne(je.Body,{className:"ha-activity-detail",children:ne("div",{ref:m,className:"ha-activity-detail-inner",children:ne($r,{animated:s,caret:!1,isStreaming:t?r:!1,plugins:i,children:e})})})})]})}function zd(e){let t=Math.max(1,Math.round(e/1e3)),n=Math.floor(t/3600),r=Math.floor(t%3600/60),o=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${o}s`:`${o}s`}function Gr({ariaLabel:e,label:t}){return ne("div",{className:"ha-progress ha-activity-status",children:ne(Vr,{"aria-label":e,className:"ha-progress-shimmer",role:"status",children:t})})}function Si({completedAt:e,defaultOpen:t=!1,hasResponseStarted:n=!1,isStreaming:r,items:o,markdownAnimation:s,markdownPlugins:i,startedAt:d}){let l=r&&!n,c=Kd(r),[m,p]=as(null),S=ss(null),u=o.findLastIndex(y=>y.active),h=o.length-1,x=l?u>=0?u:h:-1,w=o.map((y,M)=>({...y,active:M===x})),A=qd(w),O=m===null&&!t&&!r&&(c==="fading"||c==="collapsing"),N=m??(t||c==="expanded"||c==="fading"),L=m!==null||t?N?"expanded":"collapsed":c,$=d!==void 0&&e!==void 0&&!r?Math.max(0,e-d):null,X=$===null?"Activity":`Worked for ${zd($)}`,b=r||O?A.title:$===null?"Activity":X,f=A.kind,v=Gd[f],R=w.map(y=>`${y.id}:${y.active?1:0}:${y.detail??""}:${y.sources?.map(M=>M.label).join(",")}`).join("|");return nn(S),vi(S,R,r,N),ft(je,{className:"ha-activity","data-complete":r?void 0:"true","data-phase":L,isExpanded:N,onExpandedChange:p,children:[ne(je.Heading,{children:ft(je.Trigger,{className:"ha-activity-trigger",children:[ne("span",{"aria-hidden":"true",className:"ha-activity-summary-icon",children:ne("span",{children:ne(v,{})},f)}),r||O?ne(Vr,{className:"ha-activity-summary-label ha-progress ha-progress-shimmer",role:"status",children:b}):ne("span",{className:"ha-activity-summary-label ha-activity-summary-label--complete ha-progress",children:b}),ne(je.Indicator,{className:"ha-activity-chevron"})]})}),ne(je.Content,{className:"ha-activity-disclosure-content",children:ne(je.Body,{children:ne("div",{ref:S,className:"ha-activity-panel",children:ft("ol",{"aria-label":"Thinking steps",children:[w.map((y,M)=>ft("li",{"aria-current":y.active?"step":void 0,className:"ha-activity-item","data-active":y.active||void 0,"data-state":y.active?"active":"complete",children:[ne(fi,{active:y.active}),ft("div",{className:"ha-activity-content",children:[y.detail&&(y.active||y.detailVisibility==="always")?ne(Qd,{detail:y.detail,isDetailActive:l?o[M]?.active===!0:!1,isLabelActive:y.active,isTurnActive:r,label:y.label,markdownAnimation:s,markdownPlugins:i}):ne(bi,{active:y.active,label:y.label}),y.sources?.length?ne("span",{"aria-label":"Sources",className:"ha-activity-sources",children:y.sources.map(T=>ft("span",{className:"ha-activity-source",children:[ne(hi,{"aria-hidden":"true"}),T.label]},T.label))}):null]})]},y.id)),r?null:ft("li",{className:"ha-activity-item","data-complete":"true","data-state":"complete",children:[ne(fi,{active:!1}),ne("div",{className:"ha-activity-content",children:ne("span",{className:"ha-activity-step-label",children:"Final response ready"})})]})]})})})})]})}import{z as tp}from"zod";import{z as _t}from"zod";var Wd=["callMcpTool","composeUI","executeSandbox","getComponentSchema","renderComponent","searchKnowledge","searchMcpTools","searchWeb"],jd="mcp_",Yd=20,Xd=16*1024,Jd=_t.object({description:_t.string().trim().min(1).max(1e3),inputSchema:_t.record(_t.string(),_t.unknown()),name:_t.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).refine(e=>!Wd.includes(e)&&!e.toLowerCase().startsWith(jd),"Client tool name is reserved by the HeroUI Agent runtime"),needsApproval:_t.boolean().optional()}),Ci=_t.array(Jd).max(Yd).superRefine((e,t)=>{let n=new Set;for(let r of e)n.has(r.name)&&t.addIssue({code:"custom",message:`Duplicate client tool name: ${r.name}`}),n.add(r.name);new TextEncoder().encode(JSON.stringify(e)).byteLength>Xd&&t.addIssue({code:"custom",message:"Client tool manifest exceeds 16KB"})});import{z as Ye}from"zod";var Ai=Ye.object({excerpt:Ye.string().trim().min(1).max(2e3).optional(),locator:Ye.string().trim().min(1).max(160).optional(),sourceId:Ye.string().trim().min(1).max(120)}),Zd=Ye.string().trim().max(2048).refine(e=>{try{return["http:","https:"].includes(new URL(e).protocol)}catch{return!1}}),ep=Ye.union([Ai.extend({sourceType:Ye.literal("document"),title:Ye.string().trim().min(1).max(200)}),Ai.extend({sourceType:Ye.literal("url").optional(),title:Ye.string().trim().min(1).max(200).optional(),url:Zd})]),Ti=Ye.object({items:Ye.array(ep).min(1).max(16)});function np(e){return ba(e.parameters)?tp.toJSONSchema(e.parameters):e.parameters}function Ot(e){return Ci.parse(e.map(t=>({description:t.description,inputSchema:np(t),name:t.name,...t.needsApproval?{needsApproval:!0}:{}})))}var Tn=class extends Error{constructor(){super("The assistant configuration changed and must be bootstrapped again"),this.name="AgentRuntimeRevisionStaleError"}},Yn=class extends Error{retryable;status;constructor(t){super("Could not refresh the assistant connection"),this.name="AgentRuntimeTicketError",this.status=t,this.retryable=t===408||t===429||t>=500}},qr=class extends Error{code;status;constructor(t,n){super("Could not bootstrap the assistant conversation"),this.name="AgentConversationBootstrapError",this.code=n,this.status=t}},rp=250,op=2e3,wi=new Set(["CONVERSATION_LEASE_CONFLICT","SETTLEMENT_ACKNOWLEDGEMENT_PENDING"]),sp=15e3,Ri=3e4;function Ei(e){return e instanceof qr&&e.status===409&&wi.has(e.code)}function ap(e){return e===408||e===429||e>=500}function ip(e,t){if(!e)return null;let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.max(250,Math.ceil(n*1e3));let r=Date.parse(e);return Number.isFinite(r)?Math.max(250,r-t):null}function lp(e,t){return new Promise((n,r)=>{if(t.aborted){r(t.reason);return}let o=()=>{globalThis.clearTimeout(s),r(t.reason)},s=globalThis.setTimeout(()=>{t.removeEventListener("abort",o),n()},e);t.addEventListener("abort",o,{once:!0})})}function Pi(e){return{clientTools:Ot(e.tools),imageSearch:e.imageSearch,...e.composerDefaultModel?{modelId:e.composerDefaultModel}:{},newsSearch:e.newsSearch,webSearch:e.webSearch}}function Ii(e){return JSON.stringify(Pi(e))}function Qr(e,t=!1){return{Authorization:`Bearer ${e}`,...t?{"Content-Type":"application/json"}:{},"X-HeroUI-Agent-Protocol-Version":String(6),"X-HeroUI-Agent-SDK-Version":We}}async function Xn(e,t,n={}){let r=async()=>{let s=new Headers(n.headers);return s.set("Authorization",`Bearer ${await e.get()}`),s.set("X-HeroUI-Agent-Protocol-Version",String(6)),s.set("X-HeroUI-Agent-SDK-Version",We),fetch(t,{...n,headers:s})},o=await r();return o.status===401&&(e.clear(),o=await r()),o}function Mi(e){if(typeof e!="string"||!e)return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}var cp=/^sha256:[0-9a-f]{64}$/u;function xi(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.baseUrl!="string"||typeof t.path!="string"||typeof t.ticket!="string"||!t.baseUrl||!t.path||!t.ticket||!Mi(t.ticketExpiresAt)||!Mi(t.connectionExpiresAt)||typeof t.runtimeRevision!="string"||!cp.test(t.runtimeRevision))return null;try{let n=new URL(t.baseUrl);if(n.protocol!=="http:"&&n.protocol!=="https:")return null}catch{return null}return{baseUrl:t.baseUrl,connectionExpiresAt:t.connectionExpiresAt,path:t.path,runtimeRevision:t.runtimeRevision,ticket:t.ticket,ticketExpiresAt:t.ticketExpiresAt}}function up(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,n=t.conversation,r=xi(t.runtime);if(t.protocolVersion!==6||!n||typeof n!="object"||Array.isArray(n)||!r)return null;let o=n;return typeof o.id!="string"||typeof o.agentId!="string"||typeof o.projectId!="string"||!o.id||!o.agentId||!o.projectId||r.path!==`/v1/conversations/${encodeURIComponent(o.id)}/connect`?null:{conversation:{agentId:o.agentId,id:o.id,projectId:o.projectId},protocolVersion:6,runtime:r}}function dp(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return xi(t.runtime??t)}async function Ni(e,t,n){let r=new AbortController,o=Date.now()+Ri,s=globalThis.setTimeout(()=>r.abort(new Error("Assistant conversation bootstrap request timed out")),Ri),i=rp;try{for(;;){let d=await Xn(t,`${e.apiBaseUrl}/v1/conversations/${encodeURIComponent(n)}/bootstrap`,{body:JSON.stringify(Pi(e)),headers:{"Content-Type":"application/json"},method:"POST",signal:r.signal});if(!d.ok){let c=await d.json().catch(()=>null),m=typeof c?.code=="string"?c.code.toUpperCase():"";if(d.status===409&&wi.has(m))throw new qr(d.status,m);if(!ap(d.status))return null;let p=Date.now(),S=ip(d.headers.get("Retry-After"),p)??i;if(p+S>=o)return null;await lp(S,r.signal),i=Math.min(i*2,op);continue}let l=up(await d.json().catch(()=>null));return l?.conversation.id!==n||l?.conversation.agentId!==e.agentId?null:l}}finally{globalThis.clearTimeout(s)}}async function ki(e,t,n,r){let o=new AbortController,s=globalThis.setTimeout(()=>o.abort(new Error("Assistant connection ticket request timed out")),sp);try{let i=await Xn(t,`${e.apiBaseUrl}/v1/conversations/${encodeURIComponent(n)}/runtime-ticket`,{body:JSON.stringify({runtimeRevision:String(r)}),headers:{"Content-Type":"application/json"},method:"POST",signal:o.signal}),d=await i.json().catch(()=>null);if(!i.ok){let c=typeof d?.code=="string"?d.code.toUpperCase():"";throw i.status===409||c.includes("STALE")&&c.includes("REVISION")?new Tn:new Yn(i.status)}let l=dp(d);if(!l||l.runtimeRevision!==r||l.path!==`/v1/conversations/${encodeURIComponent(n)}/connect`)throw new Error("The assistant returned an invalid connection ticket");return l}finally{globalThis.clearTimeout(s)}}async function ke(e,t,n,r,o={}){try{await fetch(`${e.apiBaseUrl}/v1/agents/${encodeURIComponent(e.agentId)}/events`,{body:JSON.stringify({conversationId:n,event:r,properties:{...o,protocolVersion:6,sdkVersion:We}}),headers:Qr(await t.get(),!0),keepalive:!0,method:"POST"})}catch{}}function Rn(e,t=Eo){let n=new Set(t),o=e.filter(s=>Po(s.type)&&n.has(s.type.trim().toLowerCase())&&s.size>0&&s.size<=10485760).slice(0,5);return e.length>5?{error:`You can attach up to ${5} files at a time.`,files:o}:e.some(s=>!Po(s.type)||!n.has(s.type.trim().toLowerCase()))?{error:pp(t),files:o}:e.some(s=>s.size===0)?{error:"Empty files cannot be attached.",files:o}:e.some(s=>s.size>10485760)?{error:"Each attachment must be 10 MB or smaller.",files:o}:{error:null,files:o}}async function Oi({acceptedContentTypes:e=Eo,apiBaseUrl:t,conversationId:n,files:r,tokenManager:o}){if(r.length===0)return[];let s=Rn(r,e);if(s.error||s.files.length!==r.length)throw new Error(s.error??"One or more attachments are not supported.");return Promise.all(r.map(i=>mp({apiBaseUrl:t,conversationId:n,file:i,tokenManager:o})))}function pp(e){if(e.length===0)return"File attachments are disabled for this agent.";let t=e.map(o=>{let s=Ta[o];return s==="jpg"?"JPEG":s==="md"?"Markdown":s.toUpperCase()}),n=[...new Set(t)];return`Use ${n.length===1?n[0]:n.length===2?n.join(" or "):`${n.slice(0,-1).join(", ")}, or ${n.at(-1)}`} files.`}async function mp({apiBaseUrl:e,conversationId:t,file:n,tokenManager:r}){let o=`${e}/v1/conversations/${encodeURIComponent(t)}/attachments`;for(let s=0;s<2;s+=1){let i=await r.get(),d=await fetch(o,{body:n,headers:{Authorization:`Bearer ${i}`,"Content-Type":n.type,"X-HeroUI-Agent-Protocol-Version":String(6),"X-HeroUI-Agent-SDK-Version":We},method:"POST"});if(d.status===401&&s===0){r.clear();continue}if(!d.ok)throw new Error(await gp(d));let l=await d.json().catch(()=>null);if(typeof l?.url!="string")throw new Error("The attachment upload returned an invalid response.");return{filename:n.name,mediaType:n.type,type:"file",url:l.url}}throw new Error("The attachment could not be uploaded. Try again.")}async function gp(e){let t=await e.json().catch(()=>null);return typeof t?.error=="string"&&t.error.trim()?t.error:e.status===413?"Each attachment must be 10 MB or smaller.":e.status===415?"This attachment type is not supported.":"The attachment could not be uploaded. Try again."}import{z as xe}from"zod";var fp=64*1024,hp=15e3,yp=5*6e4,vp=xe.discriminatedUnion("action",[xe.object({action:xe.literal("execute"),claimId:xe.string().uuid(),idempotencyKey:xe.string().trim().min(1).max(160)}).strict(),xe.object({action:xe.literal("replay"),idempotencyKey:xe.string().trim().min(1).max(160),output:xe.unknown()}).strict(),xe.object({action:xe.literal("wait"),idempotencyKey:xe.string().trim().min(1).max(160),retryAfterMs:xe.number().int().min(25).max(5e3)}).strict()]),bp=xe.object({output:xe.unknown(),status:xe.enum(["completed","failed","interrupted"])}).strict();async function Di({activeToolCallIds:e,run:t,toolCallId:n}){if(e.has(n))return{status:"already-active"};e.add(n);try{return{status:"completed",value:await t()}}catch(r){throw e.delete(n),r}}function ls(e){return Array.isArray(e)?`[${e.map(ls).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${ls(n)}`).join(",")}}`:JSON.stringify(e)??"undefined"}async function Sp(e){return[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))].map(n=>n.toString(16).padStart(2,"0")).join("")}function Cp(e){return{error:e instanceof Error?e.message.slice(0,1e3):"The tool could not be executed"}}function Ap(e){let t=e??{done:!0},n;try{n=JSON.stringify(t)}catch{return{output:{error:"The client tool returned a non-serializable result"},status:"failed"}}return n===void 0?{output:{done:!0},status:"completed"}:new TextEncoder().encode(n).byteLength>fp?{output:{error:"The client tool result exceeded the 64 KiB limit"},status:"failed"}:{output:JSON.parse(n),status:"completed"}}function Li({approvalApproved:e,decision:t,needsApproval:n,state:r}){return r==="approval-responded"?e===!0:r!=="input-available"?!1:!n||t==="approved"}async function Tp(e){return Sp(ls(e))}function Hi({context:e,execution:t,input:n,tool:r}){return r.execute(Ar(r,n),e,t)}async function Ui({conversationId:e,execute:t,input:n,maxWaitMs:r=yp,now:o=Date.now,rpc:s,submitOutput:i,toolCallId:d,toolName:l,wait:c=m=>new Promise(p=>setTimeout(p,m))}){let m={inputHash:await Tp(n),protocolVersion:6,toolCallId:d,toolName:l},p=o(),S;for(;S=vp.parse(await s.claim(m)),S.action==="wait";){if(o()-p+S.retryAfterMs>r)throw new Error("Timed out waiting for the existing client tool execution");await c(S.retryAfterMs)}if(S.action==="replay")return await i(S.output),"replayed";let u={conversationId:e,idempotencyKey:S.idempotencyKey,toolCallId:d},h,x;try{({output:h,status:x}=Ap(await t(u)))}catch(A){x="failed",h=Cp(A)}let w;for(;;)try{w=bp.parse(await s.complete({...m,claimId:S.claimId,output:h,status:x}));break}catch(A){if(o()-p+250>r)throw A;await c(250)}return await i(w.output),"executed"}var cs=hp;var Rp=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;function Bi(e){return e.map(({description:t,inputSchema:n,name:r})=>({description:t,name:r,parameters:n}))}function Fi(e){return Object.fromEntries(Bi(e).map(({description:t,name:n,parameters:r})=>[n,{description:t,execute:()=>{throw new Error("HeroUI client tools execute through the approval-aware bridge")},parameters:r}]))}function Vi(e){try{let t=JSON.parse(e);return t.type!=="cf_agent_tool_approval"||t.approved!==!0||t.autoContinue!==!0?e:JSON.stringify({...t,autoContinue:!1})}catch{return e}}function us({clientSubmittedAt:e,clientTools:t,imageSearch:n,modelId:r,newsSearch:o,pageContext:s,permissionMode:i,turnId:d,webSearch:l}){if(!Rp.test(d))throw new Error("HeroUI Agent turnId must be a UUID");if(!Number.isSafeInteger(e)||e<=0)throw new Error("HeroUI Agent clientSubmittedAt must be a positive timestamp");return{clientSubmittedAt:e,clientTools:Bi(t),imageSearch:n,...r?{modelId:r}:{},newsSearch:o,pageContext:s,permissionMode:i,protocolVersion:6,requestId:d,sdkVersion:We,turnId:d,webSearch:l}}function $i(e){return e.replace(/^\/+|\/+$/g,"")}function Ki(e){let t=new URL(e.baseUrl),n=$i(t.pathname),r=$i(e.path);if(!r)throw new Error("The assistant returned an invalid connection path");return{basePath:n||r,host:t.host,...n?{path:r}:{},protocol:t.protocol==="http:"?"ws":"wss"}}function Gi(e,t){let n=e;return{next:async()=>{if(n){let r=n;return n=null,r}return t()},refresh:t}}function qi(e){if(typeof e.data!="string")return null;try{let t=JSON.parse(e.data);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Qi(e,{fillComposer:t,setSelection:n,submitPrompt:r}){return e.type==="followup"?(r(e.prompt),!0):e.type==="submit"?(n({componentId:e.componentId,componentTitle:e.componentTitle,datum:{actionId:e.actionId,values:e.values}}),e.prompt&&t(e.prompt),!0):e.type==="tool"?(t(e.prompt??e.label),!0):!1}function Mp(e){return e==="composeUI"||e==="renderComponent"}function ds(e){if(!e||typeof e!="object")return!1;let t=e,n=t.state;if(n!=="input-streaming"&&n!=="input-available")return!1;let r=t.type,o=r==="dynamic-tool"?t.toolName:typeof r=="string"&&r.startsWith("tool-")?r.slice(5):null;return Mp(o)}import{Xmark as $p}from"@gravity-ui/icons";import{File as wp,FileCode as Ep,FileLetterP as Pp,FileLetterW as Ip,FileLetterX as xp,FileText as Np,FileZipper as kp,MusicNote as _p,Picture as Op,Video as Dp}from"@gravity-ui/icons";var Lp=new Set(["csv","ods","xls","xlsm","xlsx"]),Hp=new Set(["doc","docx","odt","rtf"]),Up=new Set(["css","go","html","java","js","json","jsx","mdx","php","py","rb","rs","scss","sh","sql","swift","ts","tsx","xml","yaml","yml"]),Bp=new Set(["7z","bz2","gz","rar","tar","tgz","zip"]),Fp=new Set(["log","md","text","txt"]);function Vp(e){let t=e.trim().toLowerCase(),n=t.lastIndexOf(".");return n>0?t.slice(n+1):""}function zr(e){let t=Vp(e.name),n=e.type.toLowerCase();return Lp.has(t)||n.includes("csv")||n.includes("excel")||n.includes("spreadsheet")?{Icon:xp,kind:"spreadsheet",label:"Spreadsheet"}:t==="pdf"||n==="application/pdf"?{Icon:Pp,kind:"pdf",label:"PDF document"}:Hp.has(t)||n.includes("wordprocessingml")?{Icon:Ip,kind:"document",label:"Document"}:n.startsWith("image/")?{Icon:Op,kind:"image",label:"Image"}:n.startsWith("video/")?{Icon:Dp,kind:"video",label:"Video"}:n.startsWith("audio/")?{Icon:_p,kind:"audio",label:"Audio"}:Bp.has(t)||n.includes("zip")?{Icon:kp,kind:"archive",label:"Archive"}:Up.has(t)?{Icon:Ep,kind:"code",label:"Code file"}:Fp.has(t)||n.startsWith("text/")?{Icon:Np,kind:"text",label:"Text document"}:{Icon:wp,kind:"file",label:"File"}}import{jsx as Mn,jsxs as zi}from"react/jsx-runtime";function ps({file:e,onRemove:t}){let{Icon:n,kind:r,label:o}=zr(e);return zi("span",{className:"ha-attachment","data-kind":r,children:[Mn("span",{"aria-hidden":"true",className:"ha-attachment-icon",children:Mn(n,{})}),zi("span",{className:"ha-attachment-copy",children:[Mn("span",{className:"ha-attachment-name",title:e.name,children:e.name}),Mn("span",{className:"ha-attachment-type",children:o})]}),Mn("button",{"aria-label":`Remove ${e.name}`,type:"button",onClick:t,children:Mn($p,{"aria-hidden":"true"})})]})}import{Globe as Kp,Xmark as Gp}from"@gravity-ui/icons";import{jsx as ms,jsxs as Wi}from"react/jsx-runtime";function ji({onRemove:e,title:t}){return ms("div",{className:"ha-context",children:Wi("button",{"aria-label":`Remove Ask about this: ${t}`,className:"ha-chip",type:"button",onClick:e,children:[ms(Kp,{"aria-hidden":"true",className:"ha-chip-leading"}),Wi("span",{className:"ha-chip-title",title:t,children:["Ask about this: ",t]}),ms(Gp,{"aria-hidden":"true",className:"ha-chip-remove"})]})})}import{useCallback as Wr,useState as qp}from"react";import{jsx as Qp}from"react/jsx-runtime";function gs(e){return e.dataTransfer?.types?.includes("Files")??!1}function Yi({children:e,className:t,"data-controls-revealed":n,"data-dictating":r,"data-expanded":o,disabled:s=!1,onFileIntent:i,onFilesSelected:d}){let[l,c]=qp(!1),m=Wr(h=>{gs(h)&&(i?.(),!s&&(h.preventDefault(),c(!0)))},[s,i]),p=Wr(h=>{s||!gs(h)||(h.preventDefault(),h.dataTransfer.dropEffect="copy",c(!0))},[s]),S=Wr(h=>{let x=h.relatedTarget;x&&h.currentTarget.contains(x)||c(!1)},[]),u=Wr(h=>{gs(h)&&(i?.(),h.preventDefault(),c(!1),!(s||h.dataTransfer.files.length===0)&&d(Array.from(h.dataTransfer.files)))},[s,i,d]);return Qp("div",{className:t,"data-controls-revealed":n,"data-dictating":r,"data-dragging":l||void 0,"data-expanded":o,onDragEnterCapture:m,onDragLeaveCapture:S,onDragOverCapture:p,onDropCapture:u,children:e})}var fs="Enter";var Xi="Control+Shift+D";function Ji(e){return!e.defaultPrevented&&!e.isComposing&&!e.repeat&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&e.key==="Enter"}function Zi(e){return!e.defaultPrevented&&!e.isComposing&&!e.repeat&&!e.altKey&&e.ctrlKey&&!e.metaKey&&e.shiftKey&&e.key.toLowerCase()==="d"}function el(e,t){if(e.defaultPrevented||e.isComposing||e.repeat||e.altKey||!e.ctrlKey||e.metaKey||e.shiftKey)return null;let n=Number(e.key);return!Number.isInteger(n)||n<1||n>Math.min(t,9)?null:n-1}function hs(){return{activeTurnIds:new Set,busyIds:new Set,completedIds:new Set}}function tl(e,t){let{activeConversationId:n,busy:r,conversationId:o,failed:s,turnActive:i}=t,d=e.activeTurnIds.has(o),l=new Set(e.activeTurnIds),c=new Set(e.busyIds),m=new Set(e.completedIds);return r?c.add(o):c.delete(o),i?l.add(o):r||l.delete(o),(r||n===o)&&m.delete(o),!r&&d&&!s&&n!==o&&m.add(o),{activeTurnIds:l,busyIds:c,completedIds:m}}function ys(e,t){if(!e.completedIds.has(t))return e;let n=new Set(e.completedIds);return n.delete(t),{...e,completedIds:n}}function nl(e,t){if(!e.activeTurnIds.has(t)&&!e.busyIds.has(t)&&!e.completedIds.has(t))return e;let n=new Set(e.activeTurnIds),r=new Set(e.busyIds),o=new Set(e.completedIds);return n.delete(t),r.delete(t),o.delete(t),{activeTurnIds:n,busyIds:r,completedIds:o}}function rl(e,t,n=()=>crypto.randomUUID()){return e?.conversationEpoch===t?e:{conversationEpoch:t,conversationId:n()}}function jr({conversationEpoch:e,optimisticTarget:t,requestedConversationId:n,storedConversationId:r}){return n===null&&t?.conversationEpoch===e&&Rt(t.conversationId)?t.conversationId:Fo(n,r)}function ol({conversationEpoch:e,optimisticTarget:t,readyConversationId:n,readyEpoch:r,requestedConversationId:o}){if(r!==e)return null;let s=o===null?t?.conversationEpoch===e?t.conversationId:null:typeof o=="string"?o:n;return n===s?n:null}import{jsx as vs}from"react/jsx-runtime";function Yr({agentId:e,composerControlsAvailable:t,composerControlsRevealed:n,composerEndSlot:r,composerFooterSlot:o,composerStartSlot:s,greeting:i,loadingLabel:d,onComposerControlsReveal:l,placeholder:c,showStartScreen:m,suggestedPrompts:p}){return m?vs(Da,{composerConnecting:!0,agentId:e,composerControlsAvailable:t,composerControlsRevealed:n,composerEndSlot:r,composerFooterSlot:o,composerStartSlot:s,greeting:i,placeholder:c,suggestedPrompts:p,onComposerControlsReveal:l,onIntent:()=>{}}):vs("div",{className:"ha-loading",children:vs(tn,{className:"ha-progress ha-progress-shimmer",children:d})})}function zp(e,t){if(!e)return 1e3;let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.max(250,Math.ceil(n*1e3));let r=Date.parse(e);return Number.isFinite(r)?Math.max(250,r-t):1e3}async function sl({initialResponse:e,maxWaitMs:t=3e5,now:n=Date.now,request:r,sleep:o=s=>new Promise(i=>setTimeout(i,s))}){let s=n(),i=e;for(;i.status===409;){let d=zp(i.headers.get("Retry-After"),n());if(n()-s+d>t)return i;await o(d),i=await r()}return i}var Jn="Thinking\u2026";function al({activeStreamKey:e,activeTurnMessageId:t}){return e!==null&&t===null}function il({continuingAssistantMessageId:e,isActiveTurn:t,streamingAssistantMessageId:n,trackedActivityMessageId:r}){return t?n??r??e:null}function ll({hasActiveActivity:e,hasError:t,hasResponseStarted:n,isActiveTurn:r,messageCount:o,preferHomeWhileEmpty:s=!1,progress:i,runtimeStatus:d}){let l=o>0,c=!s&&!l&&(d==="pending"||d==="streaming"),m=!l&&!t&&!r&&!c;return e||n?{showHome:m,standaloneStatus:null}:r?{showHome:m,standaloneStatus:i??Jn}:c?{showHome:m,standaloneStatus:"Loading chat\u2026"}:{showHome:m,standaloneStatus:null}}import{jsx as Wp}from"react/jsx-runtime";function cl({activeConversationId:e,children:t,routes:n}){return Object.values(n).map(r=>{let o=r.conversationId===e;return Wp("div",{className:"ha-conversation-route","data-active":o||void 0,"data-conversation-route":r.conversationId,hidden:!o,children:t(r,o)},r.conversationId)})}function ul({isActive:e,lastUserMessageId:t,pendingTurn:n}){let r=t??null,o=n?r!==n.previousUserMessageId:r!==null,s=e?o?r:null:r;return{activeStreamKey:e?n?.scrollKey??null:null,activeTurnMessageId:s}}import{ChevronDown as tm}from"@gravity-ui/icons";import{Button as nm}from"@heroui/react";import{useLayoutEffect as rm,useRef as om}from"react";import{useCallback as Dt,useEffect as jp,useLayoutEffect as Yp,useRef as Ke,useState as Xp}from"react";var Lt=4,rn=1,dl="--ha-active-turn-spacer-height",pl='[data-role="user"][data-stream-anchor="true"]',Jp={hasOverflow:!1,isAtBottom:!0};function Zn(e){let t=e.scrollHeight-e.clientHeight>Lt,n=!t||e.scrollHeight-Math.max(0,e.scrollTop)-e.clientHeight<=Lt;return{hasOverflow:t,isAtBottom:n}}function Zp({anchorTop:e,clientHeight:t,contentHeight:n,paddingTop:r}){let o=Math.max(0,n-e);return Math.min(Math.max(t-o-r,0),t)}function em(e,t){return e.hasOverflow===t.hasOverflow&&e.isAtBottom===t.isAtBottom}function ml(e){return e==="smooth"&&!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"smooth":"auto"}function gl(e){let t=Ke(0),n=Ke(!0),r=Ke(!1),o=Ke(null),s=Ke(!1),i=Ke(!1),d=Ke(null),l=Ke(0),c=Ke(null),m=Ke(null),p=Ke(!1),S=Ke(!1),u=Ke(!1),[h,x]=Xp(Jp),w=Dt(b=>{x(f=>em(f,b)?f:b)},[]),A=Dt(b=>{t.current=0,b.style.removeProperty(dl)},[]),O=Dt(b=>{let f=c.current?b.querySelector(pl):null;if(!f)return t.current;let v=b.getBoundingClientRect(),y=f.getBoundingClientRect().top-v.top+b.scrollTop,M=b.scrollHeight-t.current,T=Number.parseFloat(window.getComputedStyle(b).paddingTop)||0,P=Zp({anchorTop:y,clientHeight:b.clientHeight,contentHeight:M,paddingTop:T});return Math.abs(P-t.current)>1&&(t.current=P,b.style.setProperty(dl,`${P}px`)),t.current},[]),_=Dt((b="smooth")=>{let f=e.current;if(!f)return;c.current=null,m.current=null,i.current=!1,p.current=!1,S.current=!1,u.current=!1,A(f),n.current=!0,r.current=!1,l.current=f.scrollTop,w({hasOverflow:Zn(f).hasOverflow,isAtBottom:!0});let v=f.scrollHeight,R=Math.max(0,v-f.clientHeight);s.current=Math.abs(Math.max(0,f.scrollTop)-R)>rn,typeof f.scrollTo=="function"?f.scrollTo({behavior:ml(b),top:v}):f.scrollTop=v,l.current=Math.max(0,f.scrollTop)},[A,e,w]),N=Dt(b=>{if(!c.current)return null;let f=b.querySelector(pl);if(f){let v=Number.parseFloat(window.getComputedStyle(b).paddingTop)||0;m.current=Math.max(0,f.offsetTop-v)}return m.current},[]),L=Dt((b,f,v="auto")=>{let R=Math.max(0,b.scrollHeight-b.clientHeight),y=Math.min(f,R),M=ml(v),T=Math.abs(Math.max(0,b.scrollTop)-y)>rn;i.current=M==="smooth"&&T,s.current=T,!T&&t.current>Lt&&(p.current=!0),l.current=b.scrollTop,w({hasOverflow:R>Lt,isAtBottom:R-y<=Lt}),typeof b.scrollTo=="function"?b.scrollTo({behavior:M,top:f}):(b.scrollTop=f,i.current=!1),l.current=Math.max(0,b.scrollTop)},[w]),$=Dt(()=>{let b=e.current;if(!b)return;O(b);let f=Zn(b),v=Math.max(0,b.scrollTop),R=v<l.current-rn;if(l.current=v,R&&!f.isAtBottom){n.current=!1,r.current=!0,s.current=!1,i.current=!1,c.current=null,m.current=null,S.current=!1,w(f);return}!r.current&&(!f.hasOverflow||f.isAtBottom)&&(n.current=!0);let y=c.current!==null,M=N(b);if(y){if(r.current=!0,M!==null&&i.current){let T=Math.max(0,b.scrollHeight-b.clientHeight),P=Math.min(M,T);if(Math.abs(v-P)>rn){w({hasOverflow:f.hasOverflow,isAtBottom:!0});return}s.current=!1,i.current=!1,p.current=t.current>Lt}if(M!==null&&S.current){S.current=!1,L(b,M,"smooth");return}n.current=!1,w(f);return}if(n.current&&!r.current){_("auto");return}w(f)},[N,e,_,L,w,O]),X=Dt(b=>{let f=e.current;if(!f||o.current===b)return;let v=o.current!==null;if(o.current=b,b)p.current=!1,d.current!==b?(d.current=b,c.current=b,m.current=null,S.current=!0,u.current=!1,r.current=!0,n.current=!0):(c.current=null,m.current=null,S.current=!1);else if(v){c.current=null,m.current=null,s.current=!1,i.current=!1,p.current=t.current>Lt,S.current=!1,r.current=!0;let R=Zn(f);n.current=!1,w(R)}},[e,w]);return Yp(()=>{let b=e.current;b&&(l.current=b.scrollTop,$(),r.current=!0,n.current=!1)},[$,e]),jp(()=>{let b=e.current;if(!b)return;let f=()=>{let F=Math.max(0,b.scrollTop);s.current&&typeof b.scrollTo=="function"&&b.scrollTo({behavior:"auto",top:F}),u.current=!0,n.current=!1,r.current=!0,s.current=!1,i.current=!1,c.current=null,m.current=null,S.current=!1,l.current=F,w(Zn(b))},v=F=>{F.deltaY<0&&f()},R=null,y=F=>{R=F.touches[0]?.clientY??null},M=F=>{let K=F.touches[0]?.clientY??null;R!==null&&K!==null&&K>R&&f(),R=K},T=()=>{let F=Zn(b),K=Math.max(0,b.scrollTop),ye=K<l.current-rn,Se=K>l.current+rn;if(l.current=K,u.current){F.isAtBottom&&Se&&!p.current?(u.current=!1,n.current=!0,r.current=!1):(n.current=!1,r.current=!0),w(F);return}if(p.current){s.current=!1,i.current=!1,n.current=!1,r.current=!0,w(F);return}if(s.current&&!ye){let H=N(b),B=Math.max(0,b.scrollHeight-b.clientHeight),D=Math.min(H??B,B),k=F.isAtBottom||Math.abs(K-D)<=rn,Y=i.current;k&&(s.current=!1,i.current=!1,H!==null&&(p.current=t.current>Lt,r.current=!0,n.current=!1)),w(Y&&!k?{hasOverflow:F.hasOverflow,isAtBottom:!0}:H===null?r.current?F:{hasOverflow:F.hasOverflow,isAtBottom:n.current}:F);return}s.current=!1,i.current=!1,c.current=null,m.current=null,S.current=!1,n.current=F.isAtBottom,r.current=!F.isAtBottom,w(F)};b.addEventListener("scroll",T,{passive:!0}),b.addEventListener("touchmove",M,{passive:!0}),b.addEventListener("touchstart",y,{passive:!0}),b.addEventListener("wheel",v,{passive:!0});let P,z=new Set,ie=()=>{if(!P)return;let F=new Set(Array.from(b.children));for(let K of z)F.has(K)||(P.unobserve(K),z.delete(K));for(let K of F)z.has(K)||(P.observe(K),z.add(K))};typeof ResizeObserver<"u"&&(P=new ResizeObserver($),P.observe(b),ie());let j=typeof MutationObserver>"u"?void 0:new MutationObserver(F=>{F.some(K=>K.type==="childList"&&K.target===b)&&ie(),$()});return j?.observe(b,{characterData:!0,childList:!0,subtree:!0}),()=>{b.removeEventListener("scroll",T),b.removeEventListener("touchmove",M),b.removeEventListener("touchstart",y),b.removeEventListener("wheel",v),j&&j.disconnect(),P&&P.disconnect()}},[N,$,e,w]),{hasOverflow:h.hasOverflow,isAtBottom:h.isAtBottom,maintainScrollPosition:$,scrollToBottom:_,setPinnedStream:X}}import{jsx as Xr,jsxs as sm}from"react/jsx-runtime";function fl({activityPhase:e=null,children:t,streamKey:n=null}){let r=om(null),{hasOverflow:o,isAtBottom:s,maintainScrollPosition:i,scrollToBottom:d,setPinnedStream:l}=gl(r),c=o&&!s;return nn(r),rm(()=>{l(n),i()},[t,i,l,n]),sm("div",{className:"ha-conversation","data-activity-phase":e??void 0,children:[Xr("div",{ref:r,"aria-live":"polite",className:"ha-messages",role:"log",children:t}),Xr("div",{"aria-hidden":c?void 0:!0,className:"ha-scroll-button-container","data-state":c?"visible":"hidden",children:Xr(nm,{isIconOnly:!0,"aria-hidden":c?void 0:!0,"aria-label":"Scroll to bottom",className:"ha-scroll-button",isDisabled:!c,size:"sm",variant:"secondary",onPress:()=>d("smooth"),children:Xr(tm,{"aria-hidden":"true"})})})]})}import{Suspense as am,lazy as im}from"react";var bs;function Ss(){return bs??=import("./component-renderer-GG6JVRUG.js").then(e=>({default:e.ComponentRenderer})),bs}function hl(){Ss().catch(()=>{bs=void 0})}import{jsx as yl}from"react/jsx-runtime";var lm=im(Ss);function vl(e){return yl(am,{fallback:null,children:yl(lm,{...e})})}import{ArrowsRotateLeft as cm,Check as um,Copy as dm,ThumbsDown as pm,ThumbsUp as mm}from"@gravity-ui/icons";import{Button as Jr,Popover as Zr,TextArea as gm}from"@heroui/react";import{useCallback as fm,useEffect as hm,useRef as bl,useState as er}from"react";import{Fragment as Sm,jsx as Re,jsxs as tr}from"react/jsx-runtime";var ym=2e3,vm=1e3,bm=[{label:"Incorrect",value:"incorrect"},{label:"Off topic",value:"not_relevant"},{label:"Missing details",value:"incomplete"},{label:"Unclear",value:"unclear"},{label:"Missed instructions",value:"did_not_follow_instructions"},{label:"Other",value:"other"}];function Sl({actions:e,feedback:t,onCopy:n,onFeedback:r,onRetry:o}){let[s,i]=er(!1),[d,l]=er(!1),[c,m]=er(""),[p,S]=er([]),[u,h]=er(),x=bl(null),w=bl(0),A=fm(f=>{h(f?.closest(".ha-panel")??void 0)},[]);hm(()=>()=>{x.current!==null&&window.clearTimeout(x.current)},[]);let O=e.includes("copy")&&n,_=e.includes("feedback")&&r,N=e.includes("retry")&&o;if(!O&&!_&&!N)return null;let L=()=>{n?.(),i(!0),x.current!==null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{i(!1),x.current=null},ym)},$=f=>{!f&&Date.now()-w.current<350||l(f)},X=f=>{S(v=>v.includes(f)?v.filter(R=>R!==f):[...v,f])},b=()=>{let f=c.trim();r?.("down",{...f?{comment:f}:{},reasons:p}),l(!1)};return tr("div",{"aria-label":"Message actions",className:"ha-message-actions",role:"group",children:[O?Re("button",{"aria-label":s?"Copied":"Copy response",className:"ha-message-action","data-copied":s||void 0,type:"button",onClick:L,children:Re("span",{className:"ha-message-action-icon",children:s?Re(um,{"aria-hidden":"true"}):Re(dm,{"aria-hidden":"true"})},s?"check":"copy")}):null,_?tr(Sm,{children:[Re("button",{"aria-label":"Good response","aria-pressed":t==="up",className:"ha-message-action","data-selected":t==="up"||void 0,type:"button",onClick:()=>r?.("up"),children:Re(mm,{"aria-hidden":"true"})}),tr(Zr,{isOpen:d,onOpenChange:$,children:[Re(Jr,{ref:A,isIconOnly:!0,"aria-label":"Bad response","aria-pressed":t==="down",className:"ha-message-action ha-feedback-trigger","data-open":d||void 0,"data-selected":t==="down"||void 0,size:"sm",variant:"ghost",onPointerDown:()=>{w.current=Date.now()},children:Re(pm,{"aria-hidden":"true"})}),Re(Zr.Content,{className:"ha-feedback-popover",offset:8,placement:"top start",UNSTABLE_portalContainer:u,children:tr(Zr.Dialog,{className:"ha-feedback-dialog",children:[Re(Zr.Heading,{className:"ha-feedback-heading",children:"Help us improve"}),Re("p",{className:"ha-feedback-description",children:"What could be better?"}),Re("div",{"aria-label":"Feedback reasons",className:"ha-feedback-reasons",role:"group",children:bm.map(f=>{let v=p.includes(f.value);return Re(Jr,{"aria-pressed":v,className:"ha-feedback-reason",size:"sm",variant:v?"secondary":"outline",onPress:()=>X(f.value),children:f.label},f.value)})}),Re(gm,{fullWidth:!0,"aria-label":"Additional feedback",className:"ha-feedback-textarea",maxLength:vm,placeholder:"Add details (optional)",rows:3,value:c,variant:"secondary",onChange:f=>m(f.target.value)}),Re("p",{className:"ha-feedback-privacy",children:"Avoid sharing sensitive information."}),tr("div",{className:"ha-feedback-footer",children:[Re(Jr,{className:"ha-feedback-cancel",size:"sm",variant:"ghost",onPress:()=>l(!1),children:"Cancel"}),Re(Jr,{className:"ha-feedback-submit",size:"sm",variant:"primary",onPress:b,children:t==="down"?"Update":"Send"})]})]})})]})]}):null,N?Re("button",{"aria-label":"Retry response",className:"ha-message-action",type:"button",onClick:o,children:Re(cm,{"aria-hidden":"true"})}):null]})}import{jsx as wn,jsxs as Cl}from"react/jsx-runtime";function Cs({file:e}){let t=e.filename?.trim()||"Attachment",n=e.mediaType?.trim()||"",{Icon:r,kind:o,label:s}=zr({name:t,type:n});return o==="image"?wn("a",{"aria-label":`Open ${t}`,className:"ha-message-image",download:e.filename,href:e.url,rel:"noopener noreferrer",target:"_blank",title:t,children:wn("span",{"aria-hidden":"true",style:{backgroundImage:`url(${JSON.stringify(e.url)})`}})}):Cl("a",{className:"ha-message-file","data-kind":o,download:e.filename,href:e.url,rel:"noopener noreferrer",target:"_blank",children:[wn("span",{"aria-hidden":"true",className:"ha-message-file-icon",children:wn(r,{})}),Cl("span",{className:"ha-message-file-copy",children:[wn("span",{className:"ha-message-file-name",title:t,children:t}),wn("span",{className:"ha-message-file-type",children:s})]})]})}function on(){return{blockedMessageId:null,isPaused:!1,messages:[]}}function As(e,t,n="append"){return e.messages.some(r=>r.id===t.id)?e:{...e,messages:n==="prepend"?[t,...e.messages]:[...e.messages,t]}}function nr(e,t){return e.messages.findIndex(r=>r.id===t)===-1?e:{...e,blockedMessageId:e.blockedMessageId===t?null:e.blockedMessageId,messages:e.messages.filter(r=>r.id!==t)}}function Al(e,t,n,r){let o=e.messages.findIndex(m=>m.id===t),s=e.messages.findIndex(m=>m.id===n);if(o===-1||s===-1||o===s)return e;let i=[...e.messages],[d]=i.splice(o,1),c=i.findIndex(m=>m.id===n)+(r==="after"?1:0);return i.splice(c,0,d),i.every((m,p)=>m.id===e.messages[p]?.id)?e:{...e,messages:i}}function rr(e,t){return e.isPaused===t?e:{...e,isPaused:t}}function ht(e,t){return e.blockedMessageId===t?e:{...e,blockedMessageId:t}}function Tl(e){let t=e.text.trim();return t||`${e.files.length} attachment${e.files.length===1?"":"s"}`}function yt(e){return e.deliveryStatus??"pending"}function En(e,t,n){let r=e.messages.findIndex(s=>s.id===t);if(r===-1||yt(e.messages[r])===n)return e;let o=[...e.messages];return o[r]={...o[r],deliveryStatus:n},{...e,messages:o}}var Cm="heroui-agent-message-outbox",Am=1,Ht="conversation-outboxes",Tm=":message-outbox:",sn=new Map;function Ts(e,t){return`${e}${Tm}${t}:v1`}async function Rl(e){await sn.get(e)?.catch(()=>{});let t=await Ms();if(!t)return on();try{let n=t.transaction(Ht,"readonly"),r=await xm(n.objectStore(Ht).get(e));return await ws(n),Rm(r,e)}catch{return on()}finally{t.close()}}function Rs(e,t,n=Date.now()){return Pl(e,async()=>{let r=t.messages.length>0?await Mm(t):null,o=await Ms();if(!o)throw new Error("Durable message storage is unavailable");try{let s=o.transaction(Ht,"readwrite"),i=s.objectStore(Ht);t.messages.length===0?i.delete(e):i.put({key:e,savedAt:n,state:r}),await ws(s)}finally{o.close()}})}function Ml(e){return Pl(e,async()=>{let t=await Ms();if(t)try{let n=t.transaction(Ht,"readwrite");n.objectStore(Ht).delete(e),await ws(n)}finally{t.close()}})}function wl(e,t){let n=new Set(t.messages.map(o=>o.id)),r=[...e.messages.filter(o=>!n.has(o.id)),...t.messages];return{blockedMessageId:t.blockedMessageId??e.blockedMessageId,isPaused:t.isPaused||e.isPaused,messages:r}}function El(e,t){let n=e.messages.filter(o=>!t.has(o.id)).map(o=>yt(o)==="sending"?{...o,deliveryStatus:"pending"}:o),r=new Set(n.map(o=>o.id));return{...e,blockedMessageId:e.blockedMessageId&&r.has(e.blockedMessageId)?e.blockedMessageId:null,messages:n}}function Rm(e,t){if(!e||typeof e!="object")return on();let n=e,r=n.state;if(n.key!==t||typeof n.savedAt!="number"||!r||typeof r!="object"||typeof r.isPaused!="boolean"||!Array.isArray(r.messages))return on();let o=r.messages.map(Em).filter(i=>i!==null),s=new Set(o.map(i=>i.id));return{blockedMessageId:typeof r.blockedMessageId=="string"&&s.has(r.blockedMessageId)?r.blockedMessageId:null,isPaused:r.isPaused,messages:o}}async function Mm(e){return{blockedMessageId:e.blockedMessageId,isPaused:e.isPaused,messages:await Promise.all(e.messages.map(async t=>({...t,files:await Promise.all(t.files.map(wm))})))}}async function wm(e){return{bytes:await e.arrayBuffer(),lastModified:e.lastModified,name:e.name,type:e.type}}function Em(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.id=="string"&&t.id.length>0&&typeof t.text=="string"&&Array.isArray(t.files)&&(t.isInitialTurn===void 0||typeof t.isInitialTurn=="boolean")&&(t.deliveryStatus===void 0||t.deliveryStatus==="pending"||t.deliveryStatus==="sending"||t.deliveryStatus==="admitted")){let n=t.files.map(Pm).filter(r=>r!==null);return n.length!==t.files.length?null:{...t,files:n}}return null}function Pm(e){if(typeof File<"u"&&e instanceof File)return e;if(typeof File>"u"||!e||typeof e!="object")return null;let t=e;return!Im(t.bytes)||typeof t.lastModified!="number"||typeof t.name!="string"||typeof t.type!="string"?null:new File([t.bytes],t.name,{lastModified:t.lastModified,type:t.type})}function Im(e){return Object.prototype.toString.call(e)==="[object ArrayBuffer]"}function Pl(e,t){let r=(sn.get(e)??Promise.resolve()).catch(()=>{}).then(t);return sn.set(e,r),r.then(()=>{sn.get(e)===r&&sn.delete(e)},()=>{sn.get(e)===r&&sn.delete(e)}),r}function Ms(){return typeof indexedDB>"u"?Promise.resolve(null):new Promise((e,t)=>{let n=indexedDB.open(Cm,Am);n.onerror=()=>t(n.error??new Error("Unable to open message outbox")),n.onupgradeneeded=()=>{let r=n.result;r.objectStoreNames.contains(Ht)||r.createObjectStore(Ht,{keyPath:"key"})},n.onsuccess=()=>e(n.result)})}function xm(e){return new Promise((t,n)=>{e.onerror=()=>n(e.error??new Error("IndexedDB request failed")),e.onsuccess=()=>t(e.result)})}function ws(e){return new Promise((t,n)=>{e.onabort=()=>n(e.error??new Error("IndexedDB write aborted")),e.onerror=()=>n(e.error??new Error("IndexedDB transaction failed")),e.oncomplete=()=>t()})}function Il({hasChatError:e,hasPendingClientToolCalls:t,hasReadyClientToolContinuation:n,isLocalPending:r,isResuming:o,isRunning:s,recoveryError:i}){return o||s||t||r||n&&!i&&!e}function xl(e,t){return e.text?{files:t,text:e.text}:{files:t}}function Nl(e){let t=e.text.trim();return t||`${e.files.length} attachment${e.files.length===1?"":"s"}`}function kl({activeMessageId:e,authoritativeMessageCount:t,isNewChatStartScreen:n,queuedMessageCount:r}){return n&&t===0&&r===0&&e===null}function _l({authoritativeMessageCount:e,localTurn:t,queue:n}){return e>0?null:t??n.messages.find(o=>o.isInitialTurn&&yt(o)!=="admitted")??null}function Ol(e,t){return e.messages.filter(n=>yt(n)==="pending"&&(n.id!==t||e.isPaused||e.blockedMessageId===t))}function Dl({isClientTool:e,state:t}){return e&&(t==="input-streaming"||t==="input-available"||t==="approval-requested"||t==="approval-responded")}function Ll({activeMessageId:e,isBusy:t,isReordering:n=!1,queue:r}){return e||t||n||r.isPaused||r.blockedMessageId||r.messages.length===0||r.messages.some(o=>yt(o)==="sending")?null:r.messages.find(o=>yt(o)==="pending")??null}function Hl(e,t){return e.key!=="ArrowUp"||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||e.nativeEvent.isComposing||!t?.focusLastMessage()?!1:(e.preventDefault(),!0)}import{ArrowUp as Nm,CircleExclamation as km,Clock as _m,Grip as Om,Pencil as Dm,TrashBin as Lm}from"@gravity-ui/icons";import{useImperativeHandle as Hm,useLayoutEffect as Um,useRef as Es}from"react";import{useRef as eo,useState as to}from"react";function Ul({messages:e,onReorder:t,onReorderStateChange:n}){let r=eo(null),o=eo(null),s=eo(null),i=eo(null),[d,l]=to(""),[c,m]=to(null),[p,S]=to(null),[u,h]=to(null),x=v=>{o.current=v,S(v)},w=()=>{let v=r.current!==null;r.current=null,m(null),x(null),v&&n?.(s.current!==null)},A=(v,R,y)=>{let M=e.findIndex(P=>P.id===v)+1,T=e.findIndex(P=>P.id===R)+1;l(`Moved queued message ${M} ${y} queued message ${T}.`)},O=(v,R,y)=>{let M=e.findIndex(z=>z.id===v),T=e.findIndex(z=>z.id===R),P=y==="before"&&M===T-1||y==="after"&&M===T+1;M===-1||T===-1||M===T||P||(t(v,R,y),A(v,R,y))},_=(v,R)=>{e.length<2||v.pointerType==="mouse"&&v.button!==0||(v.currentTarget.setPointerCapture?.(v.pointerId),r.current={hasMoved:!1,messageId:R,pointerId:v.pointerId,startX:v.clientX,startY:v.clientY},s.current=null,h(null),m(R),x(null),n?.(!0))},N=v=>{let R=r.current;if(!R||R.pointerId!==v.pointerId||!R.hasMoved&&Math.hypot(v.clientX-R.startX,v.clientY-R.startY)<4)return;R.hasMoved=!0;let y=v.currentTarget.closest(".ha-message-queue"),M=0;if(y){let F=y.getBoundingClientRect(),K=28;v.clientY<F.top+K?M=-12:v.clientY>F.bottom-K&&(M=12)}let z=v.currentTarget.getRootNode().elementFromPoint?.(v.clientX,v.clientY)?.closest("[data-queue-message-id]"),ie=z?.dataset.queueMessageId,j=null;if(z&&ie&&ie!==R.messageId){let F=z.getBoundingClientRect(),K=v.clientY<F.top+F.height/2?"before":"after";j={messageId:ie,position:K}}if(y&&M!==0&&(y.scrollTop+=M),!j){x(null);return}o.current?.messageId===j.messageId&&o.current.position===j.position||x(j)},L=(v,R)=>{let y=r.current;if(!y||y.pointerId!==v.pointerId)return;v.currentTarget.hasPointerCapture?.(v.pointerId)&&v.currentTarget.releasePointerCapture?.(v.pointerId);let M=o.current;R&&y.hasMoved&&(i.current=y.messageId),R&&y.hasMoved&&M&&O(y.messageId,M.messageId,M.position),w()},$=(v,R,y)=>{let M=v.key==="ArrowUp"?-1:v.key==="ArrowDown"?1:0;if(!M)return;let T=e[y+M];T&&(v.preventDefault(),O(R,T.id,M===-1?"before":"after"))},X=v=>{let R=i.current===v;if(i.current=null,R)return;let y=s.current===v?null:v;s.current=y,h(y),n?.(r.current!==null||y!==null)},b=v=>{s.current===v&&(s.current=null,h(null),n?.(r.current!==null))};return{announcement:d,closePositionPicker:b,draggedMessageId:c,dropTarget:p,finishPointerDrag:L,handleReorderKeyDown:$,moveMessageToPosition:(v,R,y)=>{let M=e[y];if(!M||R===y){b(v);return}O(v,M.id,R<y?"after":"before"),b(v)},positionPickerMessageId:u,startPointerDrag:_,togglePositionPicker:X,updatePointerDrag:N}}import{jsx as Ie,jsxs as or}from"react/jsx-runtime";function no(e,t){let n=e?.querySelectorAll("[data-queue-message-id]")[t];return n?(n.focus({preventScroll:!0}),n.scrollIntoView?.({block:"nearest"}),!0):!1}function Bl({blockedMessageId:e,isSendNowDisabled:t,messages:n,onEdit:r,onFocusComposer:o,onRemove:s,onReorder:i,onReorderStateChange:d,onSendNow:l,ref:c}){let m=Es(null),p=Es(null),S=Es(n),{announcement:u,closePositionPicker:h,draggedMessageId:x,dropTarget:w,finishPointerDrag:A,handleReorderKeyDown:O,moveMessageToPosition:_,positionPickerMessageId:N,startPointerDrag:L,togglePositionPicker:$,updatePointerDrag:X}=Ul({messages:n,onReorder:i,onReorderStateChange:d});if(Hm(c,()=>({focusLastMessage:()=>no(p.current,n.length-1)}),[n.length]),Um(()=>{let f=S.current;S.current=n;let v=m.current;if(!v||n.some(M=>M.id===v))return;let R=f.findIndex(M=>M.id===v),y=Math.min(R,n.length-1);m.current=null,(R<0||!no(p.current,y))&&o()},[n,o]),n.length===0)return null;let b=(f,v)=>{if(f.target===f.currentTarget&&!(f.key!=="ArrowUp"&&f.key!=="ArrowDown")){if(f.preventDefault(),f.key==="ArrowUp"){no(p.current,v-1);return}no(p.current,v+1)||o()}};return or("section",{"aria-label":"Queued messages",className:"ha-message-queue",children:[Ie("div",{className:"ha-message-queue-header",children:"Queued"}),Ie("ol",{ref:p,className:"ha-message-queue-list",children:n.map((f,v)=>{let R=e===f.id,y=v+1,M=R?`ha-queued-message-status-${f.id}`:void 0;return or("li",{"aria-describedby":M,"aria-keyshortcuts":"ArrowUp ArrowDown",className:"ha-message-queue-item","data-blocked":R?"true":void 0,"data-dragging":x===f.id?"true":void 0,"data-queue-message-id":f.id,tabIndex:-1,title:R?"This message could not be sent":void 0,"data-drop-position":w?.messageId===f.id?w.position:void 0,onKeyDown:T=>b(T,v),onBlur:T=>{let P=T.relatedTarget;m.current===f.id&&(!P||!T.currentTarget.contains(P))&&(m.current=null)},onFocus:()=>{m.current=f.id},children:[Ie("button",{"aria-keyshortcuts":"ArrowUp ArrowDown","aria-label":`Reorder queued message ${y}`,className:"ha-message-queue-drag-handle",disabled:n.length<2,title:n.length>1?"Drag to reorder or click for options":void 0,type:"button",onClick:()=>$(f.id),onKeyDown:T=>O(T,f.id,v),onPointerCancel:T=>A(T,!1),onPointerDown:T=>L(T,f.id),onPointerMove:X,onPointerUp:T=>A(T,!0),children:Ie(Om,{"aria-hidden":"true"})}),N===f.id?Ie("select",{autoFocus:!0,"aria-label":`Move queued message ${y} to position`,className:"ha-message-queue-position-select",value:v,onBlur:()=>h(f.id),onChange:T=>_(f.id,v,Number(T.currentTarget.value)),children:n.map((T,P)=>or("option",{value:P,children:["Position ",P+1,P===v?" (current)":""]},T.id))}):Ie("span",{"aria-hidden":"true",className:"ha-message-queue-icon",children:R?Ie(km,{"aria-hidden":"true"}):Ie(_m,{"aria-hidden":"true"})}),or("span",{className:"ha-message-queue-content",children:[Ie("span",{className:"ha-message-queue-preview",children:Tl(f)}),R?Ie("span",{className:"ha-message-queue-status",id:M,role:"status",children:"Could not send"}):null]}),or("span",{className:"ha-message-queue-actions",children:[Ie("button",{"aria-label":`Send queued message ${y} now`,className:"ha-message-queue-action",disabled:t,title:"Send now",type:"button",onClick:()=>l(f.id),children:Ie(Nm,{"aria-hidden":"true"})}),Ie("button",{"aria-label":`Edit queued message ${y}`,className:"ha-message-queue-action",title:"Edit",type:"button",onClick:()=>r(f.id),children:Ie(Dm,{"aria-hidden":"true"})}),Ie("button",{"aria-label":`Remove queued message ${y}`,className:"ha-message-queue-action",title:"Remove",type:"button",onClick:()=>s(f.id),children:Ie(Lm,{"aria-hidden":"true"})})]})]},f.id)})}),Ie("span",{"aria-live":"polite",className:"ha-message-queue-announcement",role:"status",children:u})]})}import{FileText as qm}from"@gravity-ui/icons";import Wl,{createContext as Qm,useContext as zm,useMemo as Wm}from"react";import{composeRenderProps as jm}from"react-aria-components";import{mergeRefs as Bm}from"@react-aria/utils";import{useControlledState as Fm}from"@react-stately/utils";import{createContext as Vm,useCallback as Xe,useContext as Vl,useEffect as Fl,useMemo as $l,useRef as ro,useState as $m}from"react";import{OverlayArrow as Km,Popover as Gm,composeRenderProps as Kl}from"react-aria-components";import{jsx as Pn}from"react/jsx-runtime";var Ps=Vm({handleCancelClose:()=>{},handleClose:()=>{},handleOpen:()=>{},isOpen:!1,isPointerInsideRef:{current:!1},setPortalContainer:()=>{},triggerRef:{current:null}}),Is=({children:e,closeDelay:t=300,defaultOpen:n=!1,onOpenChange:r,open:o,openDelay:s=700})=>{let[i,d]=Fm(o,n,r),[l,c]=$m(),m=ro(null),p=ro(!1),S=ro(void 0),u=ro(void 0),h=Xe(()=>{clearTimeout(S.current),clearTimeout(u.current)},[]);Fl(()=>h,[h]),Fl(()=>{if(!i)return;let _=N=>{N.key==="Escape"&&(d(!1),h())};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[h,i,d]);let x=Xe((_=!1)=>{h(),_||s<=0?d(!0):S.current=setTimeout(()=>d(!0),s)},[h,s,d]),w=Xe((_=!1)=>{h(),_||t<=0?d(!1):u.current=setTimeout(()=>d(!1),t)},[h,t,d]),A=Xe(()=>{clearTimeout(u.current)},[]),O=$l(()=>({handleCancelClose:A,handleClose:w,handleOpen:x,isOpen:i,isPointerInsideRef:p,portalContainer:l,setPortalContainer:c,triggerRef:m}),[A,w,x,i,l]);return Pn(Ps,{value:O,children:e})},Gl=({children:e,className:t,onBlur:n,onFocus:r,onPointerEnter:o,onPointerLeave:s,ref:i,...d})=>{let{handleClose:l,handleOpen:c,isPointerInsideRef:m,setPortalContainer:p,triggerRef:S}=Vl(Ps),u=Xe(_=>{S.current=_,p(bn(_))},[p,S]),h=$l(()=>Bm(i,u),[i,u]),x=Xe(_=>{_.pointerType==="mouse"&&c(),o?.(_)},[c,o]),w=Xe(_=>{_.pointerType==="mouse"&&l(),s?.(_)},[l,s]),A=Xe(_=>{c(!0),r?.(_)},[c,r]),O=Xe(_=>{m.current||l(),n?.(_)},[l,m,n]);return Pn("span",{ref:h,className:me("aui-hover-card__trigger",t),"data-slot":"hover-card-trigger",onBlur:O,onFocus:A,onPointerEnter:x,onPointerLeave:w,...d,children:e})},ql=({UNSTABLE_portalContainer:e,children:t,className:n,offset:r=8,onOpenChange:o,onPointerEnter:s,onPointerLeave:i,placement:d="top",...l})=>{let{handleCancelClose:c,handleClose:m,isOpen:p,isPointerInsideRef:S,portalContainer:u,triggerRef:h}=Vl(Ps),x=Xe(O=>{S.current=!0,c(),s?.(O)},[c,S,s]),w=Xe(O=>{S.current=!1,m(),i?.(O)},[m,S,i]),A=Xe(O=>{O||m(!0),o?.(O)},[m,o]);return Pn(Gm,{isNonModal:!0,"data-slot":"hover-card-content",isOpen:p,offset:r,placement:d,triggerRef:h,UNSTABLE_portalContainer:e??u,className:Kl(n,O=>me("aui-hover-card__content",O)??""),onOpenChange:A,onPointerEnter:x,onPointerLeave:w,...l,children:O=>typeof t=="function"?t(O):t})},Ql=({children:e,className:t,...n})=>Pn(Km,{"data-slot":"hover-card-arrow",className:Kl(t,r=>me("aui-hover-card__arrow",r)??""),...n,children:e??Pn("svg",{fill:"none",height:"12",viewBox:"0 0 12 12",width:"12",xmlns:"http://www.w3.org/2000/svg",children:Pn("path",{d:"M0 0C5.48483 8 6.5 8 12 0Z"})})});var sr=Object.assign(Is,{Arrow:Ql,Content:ql,Root:Is,Trigger:Gl});function zl(e){try{return new URL(e).hostname.replace(/^www\./,"")}catch{return e.split("/").pop()||e}}import{Fragment as xs,jsx as ae,jsxs as Ut}from"react/jsx-runtime";var jl=Qm({sourceType:"url"}),ar=()=>zm(jl);function Ym(e){return e.trim().charAt(0).toUpperCase()||"?"}var Ns=({children:e,className:t,description:n,enablePreview:r,faviconUrl:o,href:s,locator:i,sourceType:d=s?"url":"document",title:l,...c})=>{let m=s?zl(s):void 0,S=r??(d==="url"&&!!s?!!(n||l):!!(n||i)),u=Wm(()=>({description:n,domain:m,enablePreview:S,faviconUrl:o,href:s,locator:i,sourceType:d,title:l}),[n,m,S,o,s,i,d,l]),h=e??Ut(xs,{children:[ae(ks,{}),S?ae(_s,{description:n,title:l}):null]}),x=ae("div",{className:me("aui-chat-source",t),"data-has-locator":i?"true":void 0,"data-slot":"chat-source","data-source-type":d,...c,children:h});return ae(jl,{value:u,children:S?ae(sr,{closeDelay:0,openDelay:150,children:x}):x})},ks=({children:e,className:t,label:n,...r})=>{let{domain:o,enablePreview:s,href:i,locator:d,sourceType:l,title:c}=ar(),m=l==="url"&&i,p=e??n??(m?Ut(xs,{children:[ae(ao,{}),ae(so,{children:c??o}),d?ae(oo,{children:d}):null]}):Ut(xs,{children:[ae(io,{}),ae(so,{children:c}),d?ae(oo,{children:d}):null]}));if(m){let h=ae("a",{"aria-label":`Open source: ${c??o??i}`,className:"aui-chat-source__trigger-link",href:i,rel:"noopener noreferrer",target:"_blank",...r,children:p});return ae("span",{className:me("aui-chat-source__trigger",t),"data-slot":"chat-source-trigger",children:s?ae(sr.Trigger,{children:h}):h})}let S=[c,d].filter(Boolean).join(", ")||"Document",u=ae("span",{className:s?void 0:"aui-chat-source__trigger-link",...s?{}:r,children:p});return ae("span",{className:me("aui-chat-source__trigger",t),"data-slot":"chat-source-trigger",children:s?ae(sr.Trigger,{children:ae("button",{"aria-label":`Source: ${S}`,className:"aui-chat-source__trigger-link",type:"button",...r,children:p})}):u})},oo=({children:e,className:t,...n})=>{let{locator:r}=ar();return e??r?ae("span",{className:me("aui-chat-source__locator",t),"data-slot":"chat-source-locator",...n,children:e??r}):null},ao=({children:e,className:t,faviconUrl:n})=>{let{domain:r,faviconUrl:o,href:s,title:i}=ar(),d=i??r??s??"Source",l=n??o;if(e&&Wl.isValidElement(e)){let c=e;return Wl.cloneElement(c,{className:me("aui-chat-source__icon",t,c.props.className),"data-slot":"chat-source-icon"})}return Ut("span",{"aria-hidden":"true",className:me("aui-chat-source__icon",t),"data-slot":"chat-source-icon",children:[ae("span",{className:"aui-chat-source__icon-fallback",children:Ym(d)}),l?ae("img",{alt:"",className:"aui-chat-source__favicon","data-slot":"chat-source-favicon",decoding:"async",height:14,loading:"lazy",referrerPolicy:"no-referrer",src:l,width:14,onError:c=>{c.currentTarget.hidden=!0}}):null]})},io=({className:e})=>ae(qm,{className:me("aui-chat-source__document-icon",e),"data-slot":"chat-source-document-icon"}),so=({children:e,className:t,...n})=>{let{domain:r,title:o}=ar();return ae("span",{className:me("aui-chat-source__title",t),"data-slot":"chat-source-title",...n,children:e??o??r})},_s=({children:e,className:t,description:n,title:r,...o})=>{let{description:s,domain:i,enablePreview:d,href:l,locator:c,sourceType:m,title:p}=ar();if(!d)return null;let S=r??p,u=n??s,h=m==="url"&&l?Ut("a",{className:"aui-chat-source__preview-link",href:l,rel:"noopener noreferrer",target:"_blank",children:[Ut("div",{className:"aui-chat-source__preview-header",children:[ae(ao,{}),ae("span",{className:"aui-chat-source__preview-domain",children:i})]}),S?ae("div",{className:"aui-chat-source__preview-title",children:S}):null,u?ae("div",{className:"aui-chat-source__preview-description",children:u}):null]}):Ut("div",{className:"aui-chat-source__preview-link","data-source-type":"document",children:[Ut("div",{className:"aui-chat-source__preview-header",children:[ae(io,{}),ae("span",{className:"aui-chat-source__preview-domain",children:S??"Document"})]}),c?ae("div",{className:"aui-chat-source__preview-title",children:c}):null,u?ae("div",{className:"aui-chat-source__preview-description",children:u}):null]});return ae(sr.Content,{"data-slot":"chat-source-preview",offset:8,placement:"top",className:jm(t,x=>me("aui-chat-source__preview",x)??""),...o,children:e??h})};import{Disclosure as In}from"@heroui/react";import{composeRenderProps as Os}from"react-aria-components";import{jsx as Bt,jsxs as Xm}from"react/jsx-runtime";var Ds=({children:e,className:t,...n})=>Bt(In,{"data-slot":"chat-sources",className:Os(t,r=>me("aui-chat-sources",r)??""),...n,children:e}),Yl=({children:e,className:t,...n})=>Bt(In.Heading,{children:Xm(In.Trigger,{"data-slot":"chat-sources-trigger",className:Os(t,r=>me("aui-chat-sources__trigger",r)??""),...n,children:[Bt("span",{className:"aui-chat-sources__trigger-label",children:e}),Bt(In.Indicator,{className:"aui-chat-sources__indicator"})]})}),Xl=({children:e,className:t,...n})=>Bt(In.Content,{"data-slot":"chat-sources-content",className:Os(t,r=>me("aui-chat-sources__content",r)??""),...n,children:Bt(In.Body,{children:Bt("div",{className:"aui-chat-sources__content-body",children:e})})}),Jl=({children:e,className:t,role:n="list",...r})=>Bt("div",{className:me("aui-chat-sources__list",t),"data-slot":"chat-sources-list",role:n,...r,children:e});var Zl=Object.assign(Ns,{DocumentIcon:io,Icon:ao,Locator:oo,Preview:_s,Root:Ns,Title:so,Trigger:ks}),ir=Object.assign(Ds,{Content:Xl,List:Jl,Root:Ds,Trigger:Yl});import{jsx as Mt,jsxs as ec}from"react/jsx-runtime";function Jm(e){return`https://www.google.com/s2/favicons?domain_url=${encodeURIComponent(e)}&sz=64`}function tc({inList:e=!1,source:t}){let n="url"in t?t.url:void 0;return Mt(Zl,{description:t.excerpt,faviconUrl:n?Jm(n):void 0,href:n,locator:t.locator,role:e?"listitem":void 0,sourceType:t.sourceType??"url",title:t.title})}function Zm({sources:e}){return Mt(ir.List,{"aria-label":"Sources",children:e.map(t=>Mt(tc,{inList:!0,source:t},t.sourceId))})}function nc({sources:e}){return e.length===0?null:e.length===1?Mt("div",{"aria-label":"Sources",className:"ha-message-sources","data-count":"1",role:"group",children:Mt(tc,{source:e[0]})}):ec(ir,{className:"ha-message-sources","data-count":e.length,children:[ec(ir.Trigger,{"aria-label":`${e.length} sources`,children:[Mt("span",{className:"ha-sources-label",children:"Sources"}),Mt("span",{"aria-hidden":"true",className:"ha-sources-count",children:e.length})]}),Mt(ir.Content,{children:Mt(Zm,{sources:e})})]})}function eg(e){try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:(t.hash="",t.toString())}catch{return null}}function rc(e){let t=new Map;for(let n of e){if(n.type!=="data-sources")continue;let r=Ti.safeParse(n.data);if(r.success)for(let o of r.data.items){if("url"in o){let i=eg(o.url);i&&!t.has(i)&&t.set(i,{...o,url:i});continue}let s=`document:${o.title}:${o.locator??o.sourceId}`;t.has(s)||t.set(s,o)}}return[...t.values()]}function oc(e,{hasContent:t,isStreaming:n}){return n||!t?[]:e}import{Plus as tg}from"@gravity-ui/icons";import{Button as ng}from"@heroui/react";import{jsx as sc}from"react/jsx-runtime";function ac({isDisabled:e=!1,onPress:t}){return sc(ng,{isIconOnly:!0,"aria-label":"New chat",className:"ha-icon-button ha-new-chat-button",isDisabled:e,size:"sm",variant:"ghost",onPress:t,children:sc(tg,{"aria-hidden":"true"})})}function ic(e){return`heroui-agent:project-config:${e}`}function lc(e){try{let t=window.localStorage.getItem(ic(e));if(!t)return null;let n=Ur.safeParse(JSON.parse(t));return n.success?n.data:null}catch{return null}}function cc(e,t){try{window.localStorage.setItem(ic(e),JSON.stringify(t))}catch{}}var rg=["runtimeAdmittedAt","providerRequestedAt","providerFirstEventAt","firstSemanticTextAt","completedAt"];function uc(e,t,n){if(!n||typeof n!="object"||Array.isArray(n)||typeof window>"u")return!1;let r=n,o={};for(let i of rg){let d=r[i];typeof d=="number"&&Number.isFinite(d)&&(o[i]=d)}if(typeof r.turnId=="string"&&r.turnId&&(o.turnId=r.turnId),Object.keys(o).length===0)return!1;let s={agentId:e,conversationId:t,...o};return window.dispatchEvent(new CustomEvent(Ua,{detail:s})),!0}import{ChevronDown as og,Ellipsis as sg,Pencil as ag,Plus as ig,TrashBin as lg}from"@gravity-ui/icons";import{Button as an,Dropdown as lr,Input as cg,Label as dc,Modal as ot,Popover as Ls,TextField as ug}from"@heroui/react";import{useCallback as dg,useRef as Hs,useState as Ft}from"react";import{Fragment as hc,jsx as Z,jsxs as Ce}from"react/jsx-runtime";var pc="rename",mc="delete",pg=80,gc=new Set;function Us({activeConversationId:e,busyConversationIds:t=gc,completedConversationIds:n=gc,groups:r,isNewConversationDisabled:o=!1,onDeleteConversation:s,onNewConversation:i,onRenameConversation:d,onSelectConversation:l,variant:c="popover"}){let[m,p]=Ft(!1),[S,u]=Ft(!1),[h,x]=Ft(null),[w,A]=Ft(null),[O,_]=Ft(""),[N,L]=Ft(null),[$,X]=Ft(!1),[b,f]=Ft(),v=Hs(0),R=Hs(0),y=Hs(null);nn(y);let T=r.flatMap(D=>D.items).find(D=>D.id===e)?.title??"New chat",P=dg(D=>{f(D??void 0)},[]),z=()=>{x(null),p(!1)},ie=D=>{!D&&Date.now()-v.current<350||(D||x(null),p(D))},j=(D,k)=>{!k&&Date.now()-R.current<350||x(k?D:null)},F=(D,k)=>{z(),A({item:D,type:k}),_(D.title),L(null),u(!0)},K=()=>{$||(L(null),u(!1))},ye=(D,k)=>{k===pc&&F(D,"rename"),k===mc&&!t.has(D.id)&&F(D,"delete")},Se=async()=>{if(!w||w.type!=="rename"||$)return;let D=O.trim();if(!D){L("Enter a name for this chat.");return}if(D===w.item.title){u(!1);return}X(!0),L(null);try{await d(w.item.id,D),A({...w,item:{...w.item,title:D}}),u(!1)}catch(k){L(k instanceof Error?k.message:"The chat could not be renamed")}finally{X(!1)}},H=async()=>{if(!(!w||w.type!=="delete"||$)){X(!0),L(null);try{await s(w.item.id),u(!1)}catch(D){L(D instanceof Error?D.message:"The chat could not be deleted")}finally{X(!1)}}},B=r.length?r.map(D=>Ce("section",{className:"ha-session-group",children:[Z("h3",{children:D.label}),Z("div",{className:"ha-session-list",children:D.items.map(k=>{let Y=k.id===e,re=t.has(k.id),oe=!re&&n.has(k.id);return Ce("div",{className:"ha-session-row","data-actions-open":h===k.id?"true":void 0,"data-active":Y||void 0,"data-completed":oe||void 0,children:[Ce("button",{"aria-current":Y?"page":void 0,className:"ha-session-select",type:"button","aria-label":oe?`${k.title}, new response available`:void 0,onClick:()=>{z(),Y||l(k.id)},children:[re?Z(tn,{className:"ha-session-title ha-session-shimmer",children:k.title}):Z("span",{className:"ha-session-title",children:k.title}),oe?Z("span",{"aria-hidden":"true",className:"ha-session-completed-dot"}):null]}),Ce(lr,{isOpen:h===k.id,onOpenChange:Me=>j(k.id,Me),children:[Z(an,{isIconOnly:!0,"aria-label":`Chat actions for ${k.title}`,className:"ha-session-actions-trigger",size:"sm",variant:"ghost",onPointerDown:()=>{R.current=Date.now()},children:Z(sg,{"aria-hidden":"true"})}),Z(lr.Popover,{className:"ha-session-actions-menu",placement:"bottom end",UNSTABLE_portalContainer:b,children:Ce(lr.Menu,{"aria-label":`Actions for ${k.title}`,onAction:Me=>ye(k,Me),children:[Ce(lr.Item,{id:pc,textValue:"Rename",children:[Z(ag,{"aria-hidden":"true"}),Z(dc,{children:"Rename"})]}),Ce(lr.Item,{id:mc,isDisabled:re,textValue:re?"Delete unavailable while responding":"Delete",variant:"danger",children:[Z(lg,{"aria-hidden":"true",className:"ha-session-delete-icon"}),Z(dc,{children:re?"Delete after response":"Delete"})]})]})})]})]},k.id)})})]},D.label)):Z("p",{className:"ha-session-empty",children:"Your recent chats will appear here."});return Ce("div",{"data-variant":c,className:c==="sidebar"?"ha-session-picker ha-session-sidebar":"ha-session-picker",children:[c==="sidebar"?Ce(hc,{children:[Ce("div",{className:"ha-session-sidebar-header",children:[Z("h2",{children:"Chats"}),Ce(an,{fullWidth:!0,className:"ha-session-new-chat",isDisabled:o,size:"sm",variant:"tertiary",onPress:()=>{z(),i?.()},children:[Z(ig,{"aria-hidden":"true"}),"New chat"]})]}),Z("nav",{ref:y,"aria-label":"Recent chats",className:"ha-session-sidebar-history",children:B})]}):Ce(Ls,{isOpen:m,onOpenChange:ie,children:[Ce(an,{"aria-label":"Choose a chat",className:"ha-session-trigger",size:"sm",variant:"ghost",onPointerDown:()=>{v.current=Date.now()},children:[Z("span",{className:"font-medium",children:T}),Z(og,{"aria-hidden":"true"})]}),Z(Ls.Content,{isNonModal:!0,className:"ha-session-menu",placement:"bottom start",UNSTABLE_portalContainer:b,children:Z(Ls.Dialog,{"aria-label":"Chat history",className:"ha-session-history-dialog",children:B})})]}),Z(ot.Backdrop,{className:"ha-session-modal-backdrop",isDismissable:!$,isKeyboardDismissDisabled:$,isOpen:S,UNSTABLE_portalContainer:b,onOpenChange:D=>{D||K()},children:Z(ot.Container,{placement:"center",size:"sm",children:Z(ot.Dialog,{className:"ha-session-modal",children:Z(mg,{dialog:w,isPending:$,mutationError:N,renameTitle:O,onClose:K,onDelete:H,onRename:Se,onRenameTitleChange:_})})})}),Z("div",{ref:P,className:"ha-session-portal","data-open":m||S||h?"true":void 0,onPointerDown:D=>{D.target?.closest(".ha-session-menu, .ha-session-actions-menu, .ha-session-modal-backdrop")||(m||h)&&z()}})]})}function mg({dialog:e,isPending:t,mutationError:n,onClose:r,onDelete:o,onRename:s,onRenameTitleChange:i,renameTitle:d}){return e?.type==="rename"?Ce("form",{onSubmit:l=>{l.preventDefault(),s()},children:[Z(ot.Header,{children:Z(ot.Heading,{children:"Rename chat"})}),Ce(ot.Body,{children:[Z(ug,{autoFocus:!0,fullWidth:!0,"aria-label":"Chat name",isInvalid:!!n,name:"title",children:Z(cg,{maxLength:pg,value:d,variant:"secondary",onChange:l=>i(l.target.value)})}),Z(fc,{message:n})]}),Ce(ot.Footer,{children:[Z(an,{fullWidth:!0,isDisabled:t,type:"button",variant:"outline",onPress:r,children:"Cancel"}),Z(an,{fullWidth:!0,isPending:t,type:"submit",children:t?"Saving\u2026":"Submit"})]})]}):e?.type!=="delete"?null:Ce(hc,{children:[Z(ot.Header,{children:Z(ot.Heading,{children:"Delete chat?"})}),Ce(ot.Body,{children:[Ce("p",{children:["Are you sure you want to delete ",Ce("strong",{children:["\u201C",e.item.title,"\u201D"]}),"?"]}),Z(fc,{message:n})]}),Ce(ot.Footer,{children:[Z(an,{fullWidth:!0,isDisabled:t,variant:"outline",onPress:r,children:"Cancel"}),Z(an,{fullWidth:!0,isPending:t,variant:"danger",onPress:()=>void o(),children:t?"Deleting\u2026":"Delete"})]})]})}function fc({message:e}){return e?Z("p",{className:"ha-session-modal-error",role:"alert",children:e}):null}import{useEffect as gg,useState as fg}from"react";import{jsx as vg}from"react/jsx-runtime";var lo=["Thinking\u2026","Analyzing request\u2026","Preparing next steps\u2026"],hg=1600,yg=5e3;function yc(){let[e,t]=fg(0);return gg(()=>{let n=e===lo.length-1,r=window.setTimeout(()=>{t(o=>(o+1)%lo.length)},n?yg:hg);return()=>window.clearTimeout(r)},[e]),vg(Gr,{ariaLabel:"Working on your request\u2026",label:lo[e]??lo[0]})}function vc({now:e=()=>performance.now(),nowWallClock:t=()=>Date.now(),report:n,schedulePaint:r=o=>requestAnimationFrame(o)}){let o=new Map,s=null,i=(l,c)=>{o.has(l)||o.set(l,{painted:new Set,scheduled:new Set,startedAt:c?.startedAt??e(),startedAtWallClock:c?.startedAtWallClock??t()})},d=(l,c,m)=>{let p=o.get(l);!p||p.painted.has(c)||(p.scheduled.delete(c),p.painted.add(c),n({latencyMs:Math.max(0,Math.round(m-p.startedAt)),messageId:l,metric:c}))};return{activate(l){i(l),s=l},begin:i,complete(l){s===l&&(s=null)},getActiveMessageId(){return s},getStartedAtWallClock(l){return o.get(l)?.startedAtWallClock},markAfterPaint(l,c){let m=o.get(l);!m||m.painted.has(c)||m.scheduled.has(c)||(m.scheduled.add(c),r(()=>{d(l,c,e())}))},markPaintedAt(l,c,m){d(l,c,m)}}}function Bs(e,{hasActivity:t=!1,hasTransientData:n=!1}={}){if(!e||e.role!=="assistant")return{hasServerContent:!1,hasText:!1};let r=e.parts.some(s=>s.type==="text"&&s.text.trim().length>0),o=e.parts.some(s=>s.type==="file"||s.type==="data-component"||s.type==="data-sources");return{hasServerContent:r||o||t||n,hasText:r}}function bc({isPendingPart:e,messages:t,terminal:n}){if(n)return!1;let r=t.at(-1);return!!(r?.role==="assistant"&&r.parts.some(o=>e(o)))}function ln({attempt:e,currentAttempt:t,manualStopRequested:n,stalledStopRequested:r}){return e===t&&!n&&!r}async function Sc(e,t){return await e?.catch(()=>{}),t()}function Cc({hasPendingClientToolCalls:e,isAutoContinuationPending:t,isRecovering:n,isRunning:r,localPending:o,stalled:s}){return!s&&(r||e||o||t||n)}function Ac({hasActiveTurn:e,hasPendingClientToolCalls:t,isResuming:n,stalled:r}){return e&&!t&&!n&&!r}function Tc(e){let t=globalThis.setTimeout(e,12e4);return()=>globalThis.clearTimeout(t)}function Rc(e){let t=globalThis.setTimeout(e,12e4);return()=>globalThis.clearTimeout(t)}import{useCallback as bg,useEffect as cr,useRef as Mc,useState as wc}from"react";var Sg=300;function Ec({attachments:e,draftKey:t,input:n,setAttachments:r,setInput:o}){let[s,i]=wc(null),[d,l]=wc(null),c=Mc(n),m=Mc(null);return cr(()=>{c.current=n},[n]),cr(()=>{let p=!1,S=Va(t);return queueMicrotask(()=>{p||(S&&o(u=>u||S),l(t))}),$a(t).then(u=>{p||(u.length>0&&r(h=>h.length>0?h:u),i(t))}),()=>{p=!0}},[t,r,o]),cr(()=>{if(d!==t)return;let p=()=>Uo(t,n);return m.current=window.setTimeout(p,Sg),window.addEventListener("pagehide",p),()=>{m.current!==null&&window.clearTimeout(m.current),m.current=null,window.removeEventListener("pagehide",p)}},[t,n,d]),cr(()=>{if(d===t)return()=>Uo(t,c.current)},[t,d]),cr(()=>{s===t&&Ka(t,e)},[e,t,s]),bg(()=>{c.current="",m.current!==null&&window.clearTimeout(m.current),m.current=null,wr(t)},[t])}import{useCallback as Cg,useState as Ag}from"react";function Pc(e){return`${e}:model`}function Tg(e){if(typeof window>"u")return;let t=Pc(e);try{let n=window.localStorage.getItem(t);if(n===null)return;let r=Ra(n);if(wa(r))return r!==n&&window.localStorage.setItem(t,r),r;window.localStorage.removeItem(t)}catch{}}function Rg(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(Pc(e),t)}catch{}}function Fs(e,t){let[n,r]=Ag(()=>Tg(e)),o=n??t??Ma,s=Cg(i=>{r(i),Rg(e,i)},[e]);return{selectedModelId:o,setSelectedModelId:s}}var Ic="The recording could not be transcribed. Try again.",xc="No speech was detected. Try again when you are ready.",Mg="Voice transcription took too long. Try again.",wg=3e4;function Eg(e){let t=new AbortController,n=!1,r=()=>t.abort(e.reason);e.aborted?r():e.addEventListener("abort",r,{once:!0});let o=setTimeout(()=>{n=!0,t.abort()},wg);return{didTimeOut:()=>n,dispose:()=>{clearTimeout(o),e.removeEventListener("abort",r)},signal:t.signal}}function Pg(e,t){return t.aborted?Promise.reject(t.reason):new Promise((n,r)=>{let o=()=>r(t.reason),s=()=>t.removeEventListener("abort",o);t.addEventListener("abort",o,{once:!0}),e.then(i=>{s(),n(i)},i=>{s(),r(i)})})}function Ig(e,t){return{Authorization:`Bearer ${e}`,"Content-Type":t,"X-HeroUI-Agent-Protocol-Version":String(6),"X-HeroUI-Agent-SDK-Version":We}}function xg(e){return e===413?"The recording is too long. Try a shorter message.":e===415?"This browser's recording format is not supported.":e===422?xc:e===429?"Voice dictation is busy. Wait a moment and try again.":Ic}async function Nc({apiBaseUrl:e,audio:t,conversationId:n,language:r,signal:o,tokenManager:s}){let i=new URL(`${e}/v1/conversations/${encodeURIComponent(n)}/transcriptions`),d=Eg(o);r?.trim()&&i.searchParams.set("language",r.trim());try{for(let l=0;l<2;l+=1){let c=await Pg(s.get(),d.signal),m=await fetch(i,{body:t,headers:Ig(c,t.type||"audio/webm"),method:"POST",signal:d.signal});if(m.status===401&&l===0){s.clear();continue}if(!m.ok)throw new Error(xg(m.status));let p=await m.json().catch(()=>null),S=typeof p?.text=="string"?p.text.trim():"";if(!S)throw new Error(xc);return S}}catch(l){throw d.didTimeOut()&&!o.aborted?new Error(Mg,{cause:l}):l}finally{d.dispose()}throw new Error(Ic)}import{Fragment as cn,jsx as I,jsxs as Pe}from"react/jsx-runtime";var Dc=on();async function $g(e){try{let t=await e;if(!t.ok)return null;let n=Ur.safeParse(await t.json());return n.success?n.data:null}catch{return null}}function Vs(e){return e.type==="dynamic-tool"&&e.toolName?e.toolName:e.type.startsWith("tool-")?e.type.slice(5):null}function Kg({composerControlsRevealed:e,conversationEpoch:t,identityEpoch:n,identityReset:r,onClose:o,onComposerControlsReveal:s,onNewConversation:i,onReady:d,onSelectConversation:l,onUnreadChange:c,open:m,options:p,requestedConversationId:S,shellComposerEndSlot:u,shellComposerFooterSlot:h,showReadyLoader:x,tokenManager:w}){let[A,O]=ee(null),[_,N]=ee({}),L=ce(_),$=ce(A),[X,b]=ee(null),[f,v]=ee([]),[R,y]=ee(hs),M=ce(R),[T,P]=ee({}),[z,ie]=ee(0),j=A?_[A]??null:null;$t(()=>{L.current=_,$.current=A},[A,_]);let F=W(E=>{N(U=>({...U,[E.conversationId]:E})),O(E.conversationId)},[]),K=W(E=>{N(U=>{let V=U[E];return V?.runtime?{...U,[E]:{...V,composerReady:!1,runtime:null}}:U}),$.current===E&&ie(U=>U+1)},[]),ye=W(E=>{let U=M.current,V=E(U);V!==U&&(M.current=V,y(V),c(V.completedIds.size>0))},[c]),Se=W((E,U)=>{ye(V=>tl(V,{...U,activeConversationId:m?$.current:null,conversationId:E}))},[ye,m]);be(()=>{!m||!A||ye(E=>ys(E,A))},[A,ye,m]);let H=W(E=>{ye(U=>ys(U,E)),l(E)},[ye,l]),B=W(()=>{$.current=null,O(null),b(null),i()},[i]),D=W((E,U)=>{P(V=>{let J=V[E]??Dc,se=U(J);return se===J?V:{...V,[E]:se}})},[]),k=ce(null),Y=ce(null),re=p.apiBaseUrl,oe=p.agentId,Me=Vt(d),Ge=W((E,U)=>{let V=ol({conversationEpoch:t,optimisticTarget:Y.current,readyConversationId:E,readyEpoch:U,requestedConversationId:S});V&&(N(J=>{let se=J[V];return!se||se.composerReady?J:{...J,[V]:{...se,composerReady:!0}}}),O(V),d(U))},[t,d,S]),st=Ae(()=>{try{return Ot(vn(p.tools,p.permissionDefaultMode)),p.permissionShowPicker&&Ot(vn(p.tools,"ask")),null}catch(E){return E instanceof Error?E.message:"The client tools could not be loaded"}},[p.permissionDefaultMode,p.permissionShowPicker,p.tools]),at=st?null:Ii(p),un=Vt(E=>Ni(p,w,E)),xn=Vt(E=>{ke(p,w,E,"embed_loaded")}),wt=ce(n);$t(()=>{if(wt.current===n)return;wt.current=n,k.current=null,Y.current=null,L.current={},$.current=null,N({}),O(null),v([]);let E=hs();M.current=E,y(E),P({}),r?w.reset():w.clear()},[n,r,w]),$t(()=>{if(S!==null||st)return;let E=rl(Y.current,t);Y.current=E;let U=k.current;if(!U)return;let V=E.conversationId;localStorage.setItem(U.storageKey,V),b(null),v(J=>{let se=Kn(J,V,Ir([]),Date.now());return Nt(U.historyKey,se),se}),N(J=>({...J,[V]:{composerReady:!1,config:U.config,conversationId:V,historyKey:U.historyKey,readyEpoch:t,runtime:null,showStartScreenWhileConnecting:!0,storageKey:U.storageKey}})),O(V)},[st,t,S]),be(()=>{let E=!1;if(st){b(st),O(null),Me(t);return}let U=k.current;if(U){let J=jr({conversationEpoch:t,optimisticTarget:Y.current,requestedConversationId:S,storedConversationId:localStorage.getItem(U.storageKey)}),se=J?L.current[J]:void 0;if(se?.runtime){b(null),N(ve=>({...ve,[se.conversationId]:{...se,readyEpoch:t}})),se.composerReady&&O(se.conversationId);return}}let V=jr({conversationEpoch:t,optimisticTarget:Y.current,requestedConversationId:S,storedConversationId:null});return b(null),O(V??(typeof S=="string"&&Rt(S)?S:null)),(async()=>{try{let J=await w.subjectHash(),se=`heroui-agent:conversation:${oe}:${J}`,ve=`heroui-agent:history:${oe}:${J}`,_e=jr({conversationEpoch:t,optimisticTarget:Y.current,requestedConversationId:S,storedConversationId:localStorage.getItem(se)})??crypto.randomUUID();localStorage.setItem(se,_e);let qe=Vo(ve);E||v(qe);let we=U?.config??lc(oe),Gt=we?null:Xn(w,`${re}/v1/agents/${encodeURIComponent(oe)}/config`),ct=Xn(w,`${re}/v1/agents/${encodeURIComponent(oe)}/conversations`).catch(()=>null),Nn=await un(_e),dn=we??(Gt?await $g(Gt):null);if(!dn||!Nn)throw new Error("The data assistant could not be loaded");we||cc(oe,dn);let De=qe.find(ut=>ut.id===_e),kn=Kn(qe,_e,De?.title??Ir([]),De?.updatedAt??Date.now());if(kn!==qe&&Nt(ve,kn),!E){k.current={config:dn,historyKey:ve,storageKey:se},v(kn);let ut=L.current[_e],le={composerReady:!1,config:dn,conversationId:_e,historyKey:ve,readyEpoch:t,runtime:Nn.runtime,showStartScreenWhileConnecting:ut?.showStartScreenWhileConnecting??S===null,storageKey:se};F(le)}ct.then(async ut=>{if(!ut?.ok)return;let le=Pr((await ut.json()).conversations);E||v(qt=>{let _n=$o(qt,le);return Nt(ve,_n),_n})}),xn(_e)}catch(J){if(!E&&S===void 0&&Ei(J)){B();return}E||(b(J instanceof Error?J.message:"The data assistant could not be loaded"),Me(t))}})(),()=>{E=!0}},[re,F,at,st,t,n,oe,S,z,B,w]);let Je=W((E,U,V)=>{let J=k.current?.historyKey;J&&v(se=>{let ve=Kn(se,E,U,Date.now(),V);return Nt(J,ve),ve})},[]),pe=W(E=>{N(U=>{let V=U[E];return V?.showStartScreenWhileConnecting?{...U,[E]:{...V,showStartScreenWhileConnecting:!1}}:U})},[]),Oe=W(async(E,U)=>{let V=async()=>{let se=await w.get(),ve=new Headers(U.headers);for(let[qe,we]of Object.entries(Qr(se)))ve.set(qe,we);let _e=await fetch(`${re}/v1/conversations/${encodeURIComponent(E)}`,{...U,headers:ve});if(_e.status===401){w.clear();let qe=await w.get(),we=new Headers(U.headers);for(let[Gt,ct]of Object.entries(Qr(qe)))we.set(Gt,ct);_e=await fetch(`${re}/v1/conversations/${encodeURIComponent(E)}`,{...U,headers:we})}return _e},J=await V();if(U.method==="DELETE"&&J.status===409&&(J=await sl({initialResponse:J,request:V})),!J.ok)throw new Error(U.method==="DELETE"?"The chat could not be deleted":"The chat could not be renamed")},[re,w]),vt=W(async(E,U)=>{await Oe(E,{body:JSON.stringify({title:U}),headers:{"Content-Type":"application/json"},method:"PATCH"});let V=k.current?.historyKey;V&&v(J=>{let se=J.map(ve=>ve.id===E?{...ve,title:U}:ve);return Nt(V,se),se})},[Oe]),it=W(async E=>{await Oe(E,{method:"DELETE"});let U=k.current;U&&(v(V=>{let J=V.filter(se=>se.id!==E);return Nt(U.historyKey,J),J}),localStorage.removeItem(Tr(U.storageKey,E)),localStorage.removeItem(ko(U.storageKey,E)),wr(Bo(U.storageKey,E)),Ml(Ts(U.storageKey,E)),N(V=>{if(!(E in V))return V;let J={...V};return delete J[E],J}),ye(V=>nl(V,E)),P(V=>{if(!(E in V))return V;let J={...V};return delete J[E],J}),A===E&&B())},[A,ye,Oe,B]),ge=Ae(()=>{let E=p.suggestedPrompts;return E?.length?Object.fromEntries(Object.entries(_).map(([U,V])=>[U,{...V,config:{...V.config,suggestedPrompts:E}}])):_},[p.suggestedPrompts,_]),Et=A?ge[A]?.config??null:null,Kt=ce(null);be(()=>{!m||!j?.runtime||Kt.current===j.conversationId||(Kt.current=j.conversationId,ke(p,w,j.conversationId,"opened"))},[m,p,j,w]);let Pt=st??X,ur=Ae(()=>qo(f),[f]),uo=f.find(E=>E.id===A)?.title??"New chat",bt=k.current?"Loading chat\u2026":"Loading assistant\u2026",lt=S===null&&(!j||j.showStartScreenWhileConnecting);return I(cn,{children:Pe(Aa,{keepMounted:!0,agentId:p.agentId,defaultExpanded:p.panelExpanded,expandable:!x&&p.panelExpandable,expandedTitle:uo,modal:p.viewMode!=="sidebar",name:Et?.name??"Data assistant",open:m,actionsSlot:x?I(cn,{}):I(ac,{isDisabled:lt,onPress:B}),expandedSidebarSlot:x?void 0:I(Us,{activeConversationId:A,busyConversationIds:R.busyIds,completedConversationIds:R.completedIds,groups:ur,isNewConversationDisabled:lt,variant:"sidebar",onDeleteConversation:it,onNewConversation:B,onRenameConversation:vt,onSelectConversation:H}),historySlot:x?I(cn,{}):I(Us,{activeConversationId:A,busyConversationIds:R.busyIds,completedConversationIds:R.completedIds,groups:ur,onDeleteConversation:it,onRenameConversation:vt,onSelectConversation:H}),onClose:o,onNewConversation:x?void 0:B,children:[Pt?I("div",{className:"ha-loading",role:"alert",children:Pt}):x?I(Ca,{indicator:I(Hg,{"aria-hidden":!0,color:"current",size:"md"})}):!j||!j.runtime||!Et?lt&&j?I(Lc,{composerControlsRevealed:e,loadingLabel:bt,options:p,route:j,onComposerControlsReveal:s},`pending-${t}`):I(Yr,{agentId:p.agentId,composerControlsAvailable:p.composerControlsAvailable,composerControlsRevealed:e,composerEndSlot:u,composerFooterSlot:h,greeting:p.greeting,loadingLabel:bt,placeholder:p.composerPlaceholder,showStartScreen:lt,suggestedPrompts:p.suggestedPrompts??[],composerStartSlot:I(Fc,{agentId:p.agentId,options:p}),onComposerControlsReveal:s},`pending-${t}`):null,I("div",{className:"ha-runtime-content",hidden:!!Pt||x,children:I(cl,{activeConversationId:Pt?null:A,routes:ge,children:(E,U)=>I(Ha,{variant:E.config.surfaceVariant,children:E.runtime?I(Fg,{fallback:U&&E.showStartScreenWhileConnecting?I(Lc,{composerControlsRevealed:e,loadingLabel:"Connecting chat\u2026",options:p,route:E,onComposerControlsReveal:s}):I(Yr,{agentId:p.agentId,composerControlsAvailable:p.composerControlsAvailable,composerControlsRevealed:e,greeting:p.greeting,loadingLabel:"Connecting chat\u2026",placeholder:p.composerPlaceholder,showStartScreen:!1,suggestedPrompts:p.suggestedPrompts??[],onComposerControlsReveal:s}),children:I(qg,{active:U,composerControlsRevealed:!!U&&e,config:E.config,conversationEpoch:E.readyEpoch,conversationId:E.conversationId,options:p,runtime:E.runtime,showStartScreenWhileHydrating:E.showStartScreenWhileConnecting,storageKey:E.storageKey,tokenManager:w,messageQueue:T[E.conversationId]??Dc,onComposerControlsReveal:s,onConversationStatusChange:Se,onMessageQueueChange:D,onReady:Ge,onRuntimeRevisionStale:K,onConversationStarted:V=>{pe(E.conversationId),Je(E.conversationId,V)},onConversationTitled:V=>Je(E.conversationId,V,{replaceTitle:!0})})}):null})})})]})})}function Lc({composerControlsRevealed:e,loadingLabel:t,onComposerControlsReveal:n,options:r,route:o}){return I(Yr,{showStartScreen:!0,agentId:r.agentId,composerControlsAvailable:r.composerControlsAvailable,composerControlsRevealed:e,composerStartSlot:I(Fc,{agentId:r.agentId,options:r}),greeting:r.greeting,loadingLabel:t,placeholder:r.composerPlaceholder,suggestedPrompts:r.suggestedPrompts??[],composerEndSlot:I(Gg,{conversationId:o.conversationId,options:r,storageKey:o.storageKey}),composerFooterSlot:r.composerDisclaimer?I("p",{className:"ha-footnote",children:Io(r.composerDisclaimer)}):null,onComposerControlsReveal:n})}function Fc({agentId:e,options:t}){let n=ce(null),[r,o]=ee(()=>No(e)),[s,i]=ee(null),d=l=>{let c=Rn(l,t.composerAttachmentContentTypes);o(c.files),i(c.error),Na(e,c.files)};return t.composerAttachmentContentTypes.length===0?null:Pe(cn,{children:[I("input",{ref:n,multiple:!0,accept:t.composerAttachmentAccept,"aria-label":"Choose files to attach",className:"ha-file-input",type:"file",onChange:l=>{d(Array.from(l.currentTarget.files??[])),l.currentTarget.value=""}}),r.length>0?I(Do,{"aria-label":"Selected attachments",className:"ha-attachments",offset:1,size:24,children:r.map(l=>I(ps,{file:l,onRemove:()=>d(r.filter(c=>c!==l))},`${l.name}-${l.size}-${l.lastModified}`))}):null,I("button",{"aria-label":"Attach files",className:"ha-attach",type:"button",onClick:()=>n.current?.click(),children:I(Bc,{"aria-hidden":"true"})}),s?I("span",{className:"ha-dictation-error",role:"alert",children:s}):null]})}function Gg({conversationId:e,options:t,storageKey:n}){let r=Tr(n,e),[o,s]=ee(()=>Rr(r)??t.permissionDefaultMode),{selectedModelId:i,setSelectedModelId:d}=Fs(n,t.composerDefaultModel),l=c=>{s(c),Mr(r,c)};return Pe(cn,{children:[t.permissionShowPicker&&t.tools.length>0?I(Nr,{"aria-label":"Tool permissions",className:"ha-permission-picker",value:o,onChange:l}):null,t.composerModelPicker?I(xr,{"aria-label":"AI model",className:"ha-model-picker",options:xo,placement:t.permissionShowPicker&&t.tools.length>0?"top":"top start",value:i,onChange:d}):null,t.composerDictation?Pe("button",{disabled:!0,"aria-label":"Dictate message",className:"ha-dictation",type:"button",children:[I(Uc,{"aria-hidden":"true"}),I(Vn,{children:"Dictate message"})]}):null]})}function qg({active:e,composerControlsRevealed:t,config:n,conversationEpoch:r,conversationId:o,messageQueue:s,onComposerControlsReveal:i,onConversationStarted:d,onConversationStatusChange:l,onConversationTitled:c,onMessageQueueChange:m,onReady:p,onRuntimeRevisionStale:S,options:u,runtime:h,showStartScreenWhileHydrating:x,storageKey:w,tokenManager:A}){let{selectedModelId:O,setSelectedModelId:_}=Fs(w,u.composerDefaultModel),N=ko(w,o),L=Tr(w,o),$=u.composerAttachmentAccept,X=Ae(()=>({key:$}),[$]),[b,f]=ee(()=>({files:Rn(No(u.agentId),u.composerAttachmentContentTypes).files,policy:X})),[v,R]=ee(()=>({error:null,policy:X})),y=Ae(()=>b.policy===X?b.files:[],[X,b]),M=v.policy===X?v.error:null,T=W(a=>{f(g=>{let C=g.policy===X?g.files:[],G=typeof a=="function"?a(C):a;return{files:Rn(G,u.composerAttachmentContentTypes).files,policy:X}})},[X,u.composerAttachmentContentTypes]),P=W(a=>R({error:a,policy:X}),[X]),[z,ie]=ee(()=>{let a=u.permissionShowPicker?Rr(N):void 0;return a?{modelId:void 0,permissionMode:a}:void 0}),[j,F]=ee({}),[K,ye]=ee({}),[Se,H]=ee(!1),[B]=ee(()=>Ea(u.agentId)),[D,k]=ee(()=>B?.submitted?"":B?.prompt??""),[Y,re]=ee(()=>B?.submitted?{files:y,id:B.messageId,text:B.prompt}:null),[oe,Me]=ee(()=>{let a=u.permissionShowPicker?Rr(L):void 0;return{configuredDefaultMode:u.permissionDefaultMode,selectedMode:a??u.permissionDefaultMode}}),[Ge,st]=ee(!1),[at,un]=ee(!0),[xn,wt]=ee(!1),[Je,pe]=ee(!1),[Oe,vt]=ee(()=>new Set),[it,ge]=ee(null),[Et,Kt]=ee(0),[Pt,ur]=ee(0),[uo,bt]=ee(!1),[lt,E]=ee(!1),[U,V]=ee(null),[J,se]=ee({}),ve=W(a=>{u.permissionShowPicker?Mr(N,a.permissionMode):_o(N),ie(a)},[N,u.permissionShowPicker]),_e=oe.configuredDefaultMode===u.permissionDefaultMode?oe.selectedMode:u.permissionDefaultMode,qe=W(a=>{Mr(L,a),Me({configuredDefaultMode:u.permissionDefaultMode,selectedMode:a})},[u.permissionDefaultMode,L]),we=u.permissionShowPicker?_e:u.permissionDefaultMode,Gt=u.permissionShowPicker?z?.permissionMode??we:u.permissionDefaultMode,ct=Ae(()=>vn(u.tools,Gt),[Gt,u.tools]),Nn=Ae(()=>Ot(ct),[ct]),dn=Ae(()=>Fi(Nn),[Nn]),De=Ae(()=>new Map(ct.map(a=>[a.name,a])),[ct]),kn=Ae(()=>new Set(ct.map(a=>a.name)),[ct]),ut=ce(new Set),le=ce(null),qt=ce(new Set),_n=ce(!1),Le=ce(s),po=ce(null),Ze=ce(!1),He=ce(!1),Qt=ce(null),dr=ce(0),dt=ce(0),It=ce(null),zt=ce(null),pr=ce(null),mo=ce(new Set),go=ce(new Map),On=ce(()=>{}),$s=ce(null),Ks=ce(null),St=ce(null),Ee=Ae(()=>vc({report:({latencyMs:a,messageId:g,metric:C})=>{ke(u,A,o,C,{latencyMs:a,latencyOrigin:"user_submit",messageId:g})}}),[o,u,A]),Vc=Ae(()=>Bo(w,o),[o,w]),Dn=Ae(()=>Ts(w,o),[o,w]),Gs=Ec({attachments:y,draftKey:Vc,input:D,setAttachments:T,setInput:k}),$c=W((a,{language:g,signal:C})=>Nc({apiBaseUrl:u.apiBaseUrl,audio:a,conversationId:o,...g?{language:g}:{},signal:C,tokenManager:A}),[o,u.apiBaseUrl,A]),{cancel:Qe,elapsedSeconds:fo,error:ho,isActive:Ne,isRecording:Kc,isSupported:Wt,isTranscribing:Ln,start:qs,stop:Qs,stream:Gc}=Zo({onValueChange:k,transcribe:$c,value:D}),yo=t||Ne||y.length>0||M!==null||ho!==null,zs=W(()=>{u.composerControlsAvailable&&i()},[i,u.composerControlsAvailable]),qc=a=>{$n(u.agentId,!0,a.currentTarget),zs()},Qc=a=>{let g=a.currentTarget.querySelector(".ha-composer");g&&xa(g,a.relatedTarget)||$n(u.agentId,!1)};be(()=>{Le.current=s},[s]),be(()=>{u.composerDictation||Qe()},[Qe,u.composerDictation]),be(()=>{e||Qe()},[e,Qe]);let pn=u.composerModelPicker?O:u.composerDefaultModel,mn=W(a=>{Le.current=a,m(o,()=>a)},[o,m]),et=W(async(a,{applyAfterPersist:g=!1}={})=>{let C=Le.current,G=a(C);if(G!==C){g?Le.current=G:mn(G);try{await Rs(Dn,G)}catch(ue){throw Le.current===G&&(g?Le.current=C:mn(C)),ue}g&&Le.current===G&&mn(G)}},[mn,Dn]),ze=W(a=>{et(a).catch(()=>{})},[et]),zc=W(a=>{qt.current.add(a),et(g=>nr(En(g,a,"admitted"),a)).catch(()=>{})},[et]);be(()=>{let a=!1;return un(!0),Rl(Dn).then(async g=>{if(a)return;let C=wl(g,Le.current),G=qt.current,ue={...C,messages:C.messages.filter(de=>!G.has(de.id))};mn(ue),await Rs(Dn,ue)}).catch(()=>{}).finally(()=>{a||un(!1)}),()=>{a=!0}},[mn,Dn]);let mr=W(()=>{Ze.current=!1,He.current=!1,It.current=null,E(!1)},[]),Ws=W(a=>{ln({attempt:a,currentAttempt:dt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current})&&pe(!1)},[]),{agent:jt,connectionEpoch:gr,connectionError:pt,isHydrating:Wc,isReconnecting:js,retryConnection:jc}=Wg({conversationId:o,onRuntimeRevisionStale:S,onTurnAdmitted:zc,options:u,runtime:h,tokenManager:A}),Yc=Vt(p);$t(()=>{Yc(o,r)},[e,r,o]),be(()=>{if(at||gr===0)return;let a=[];for(let G of Le.current.messages)yt(G)==="sending"&&a.push(G.id);if(a.length===0){wt(!1);return}let g=!1,C;return wt(!0),(async()=>{let G=[];for(let he=0;he<a.length;he+=50)G.push(a.slice(he,he+50));let ue=async he=>{let Cr=await Promise.all(G.map(async mt=>({response:await jt.call(Fa,[{protocolVersion:6,turnIds:mt}],{timeout:15e3}),turnIds:new Set(mt)}))),Be=new Set;for(let{response:mt,turnIds:wo}of Cr){if(mt.protocolVersion!==6||!Array.isArray(mt.turns))throw new Error("Invalid turn admission status response");for(let yn of mt.turns)yn.status==="admitted"&&wo.has(yn.turnId)&&Be.add(yn.turnId)}return Be.size===a.length||he>=4?Be:(await new Promise(mt=>window.setTimeout(mt,500)),ue(he+1))},de;try{de=await ue(0)}catch{g||(C=window.setTimeout(()=>ur(he=>he+1),1e3));return}if(!g){for(let he of de)qt.current.add(he);await et(he=>El(he,de))}})().catch(()=>{}).finally(()=>{g||wt(!1)}),()=>{g=!0,C!==void 0&&window.clearTimeout(C)}},[jt,et,gr,at,Pt]);let Xc=Ae(()=>new Proxy(jt,{get(a,g){if(g==="send")return G=>a.send(Vi(G));let C=Reflect.get(a,g,a);return typeof C=="function"?C.bind(a):C}}),[jt]),Q=_g({agent:Xc,cancelOnClientAbort:!1,experimental_throttle:60,getInitialMessages:null,onData:a=>{if(a.type!=="data-conversation-title"){let g=Ee.getActiveMessageId();g&&mo.current.add(g)}if(a.type==="data-progress"&&a.data&&typeof a.data=="object"&&"label"in a.data&&typeof a.data.label=="string"&&ge(a.data.label),a.type==="data-conversation-title"&&a.data&&typeof a.data=="object"&&"title"in a.data&&typeof a.data.title=="string"&&a.data.title.trim()&&c(a.data.title.trim()),a.type==="data-component"){let g=a.data&&typeof a.data=="object"&&"kind"in a.data?a.data:null;ke(u,A,o,"component_rendered",{componentType:g?.kind})}a.type==="data-runtime-timing"&&uc(u.agentId,o,a.data)},onError:a=>{if(Ze.current||He.current){It.current=null,pe(!1),ge(null),queueMicrotask(()=>On.current());return}It.current=a,pe(!1),ge(null),ke(u,A,o,"failure",{messageId:Ee.getActiveMessageId()??void 0,source:"cloudflare-chat"})},onFinish:({isError:a})=>{if(Ze.current||He.current){It.current=null,pe(!1),ge(null),queueMicrotask(()=>On.current());return}a&&!It.current&&(It.current=new Error("The request could not be completed")),pe(!1),ge(null)},resume:!0,syncMessagesToServer:!1,tools:dn}),{clearError:Ys,setMessages:Xs}=Q;$t(()=>{On.current=Ys},[Ys]);let Ct=Q.status==="submitted"||Q.status==="streaming"||Q.isStreaming,xt=uo||lt,Hn=!xt&&Q.isToolContinuation,vo=!!(xt||Q.error||Q.connectionError||pt),Yt=Ae(()=>!vo&&(Oe.size>0||bc({isPendingPart:a=>{let g=a,C=Vs(g);return Dl({isClientTool:!!(C&&De.has(C)),state:g.state})},messages:Q.messages,terminal:vo})),[Q.messages,De,vo,Oe]),Ue=Cc({hasPendingClientToolCalls:Yt,isAutoContinuationPending:Hn,isRecovering:Q.isRecovering,isRunning:Ct,localPending:Je,stalled:lt});be(()=>{if(Ue)return;let a=Ee.getActiveMessageId();a&&(Ee.complete(a),mo.current.delete(a),go.current.delete(a))},[Ue,Ee]);let Xt=!pt&&(Wc||js||at||xn),bo=Xt||Ue,So=xt||!!Q.error||!!Q.connectionError||!!pt,At=bo||So,Js=Il({hasChatError:!!(Q.error||Q.connectionError||pt),hasPendingClientToolCalls:Yt,hasReadyClientToolContinuation:Hn,isLocalPending:Je,isResuming:Xt,isRunning:Ct,recoveryError:xt}),Zs=Vt(l);be(()=>{z&&!Ct&&!Yt&&!Je&&!Xt&&!Hn&&(_o(N),ie(void 0))},[z,N,Yt,Hn,Xt,Ct,Je]),be(()=>{Zs(o,{busy:bo,failed:So,turnActive:Ue})},[So,o,Ue,bo]),be(()=>()=>{Zs(o,{busy:!1,failed:!0,turnActive:!1})},[o]);let Tt=Q.messages.at(-1),ea=Ct&&Tt?.role==="assistant"?Tt.id:null,Jc=Tt?.role==="assistant"&&(Yt||Hn||Q.isRecovering)?Tt.id:null,Jt=il({continuingAssistantMessageId:Jc,isActiveTurn:Ue,streamingAssistantMessageId:ea,trackedActivityMessageId:zt.current}),Co=Jt===Tt?.id?Tt:void 0,ta=!!(Co&&ns(Co,De,{isStreaming:!0}).length>0),Zc=Bs(Co).hasServerContent;be(()=>{if(Ue&&Jt){if(zt.current===Jt)return;let C=pr.current??Date.now();zt.current=Jt,F(G=>({...G,[Jt]:{startedAt:C}}));return}let a=zt.current;if(Ue||!a)return;let g=Date.now();F(C=>{let G=C[a];return!G||G.completedAt?C:{...C,[a]:{...G,completedAt:g}}}),zt.current=null,pr.current=null},[Jt,Ue]);let fr=W(async(a,g,C)=>{Q.addToolOutput({output:C,toolCallId:g,toolName:a})},[Q.addToolOutput]),Ao=W((a,g)=>{vt(C=>{if(C.has(a)===g)return C;let G=new Set(C);return g?G.add(a):G.delete(a),G})},[]),hr=W(async(a,g)=>{await Di({activeToolCallIds:ut.current,run:async()=>{Ao(g.toolCallId,!0),ge("Fetching live data\u2026");try{await Ui({conversationId:o,execute:C=>Hi({context:u.context,execution:C,input:g.input,tool:a}),input:g.input,rpc:{claim:C=>jt.call("claimClientToolEffect",[C],{timeout:cs}),complete:C=>jt.call("completeClientToolEffect",[C],{timeout:cs})},submitOutput:C=>fr(a.name,g.toolCallId,C),toolCallId:g.toolCallId,toolName:a.name}),ge("Analyzing the results\u2026")}finally{Ao(g.toolCallId,!1)}},toolCallId:g.toolCallId})},[jt,o,u.context,Ao,fr]),eu=W((a,g,C)=>{let G=g.toolCallId;if(se(ue=>({...ue,[G]:C?"approved":"rejected"})),ge(C?"Applying your change\u2026":"Updating your request\u2026"),ke(u,A,o,C?"action_approved":"action_declined"),g.approval?.id)Q.addToolApprovalResponse({approved:C,id:g.approval.id});else if(!C)fr(a,G,{reason:"The user declined this tool call",rejected:!0});else{se(ue=>({...ue,[G]:"rejected"}));return}if(C){let ue=De.get(a);ue&&hr(ue,g).catch(()=>{})}else ut.current.add(G)},[Q.addToolApprovalResponse,De,o,hr,u,fr,A]);be(()=>{for(let a of Q.messages)if(a.role==="assistant")for(let g of a.parts){let C=Vs(g);if(!C)continue;let G=De.get(C);!G||ut.current.has(g.toolCallId)||Li({approvalApproved:g.approval?.approved,decision:J[g.toolCallId],needsApproval:G.needsApproval===!0,state:g.state})&&hr(G,g).catch(()=>{})}},[Q.messages,De,gr,hr,J]);let To=W(a=>{H(_a(a,{hasAttachments:yo&&y.length>0}))},[y.length,yo]);$t(()=>{To(St.current)},[D,Ne,To]);let na=W(a=>{if(a.length===0)return;let g=Rn([...y,...a],u.composerAttachmentContentTypes);P(g.error),T(g.files)},[y,u.composerAttachmentContentTypes,P,T]),ra=W(()=>{Qe(),Gs(),k(""),T([]),P(null),V(null)},[Qe,Gs,P,T]),tu=W(()=>St.current?.focus(),[]),Ro=W(()=>{if(Ln){Qe(),requestAnimationFrame(()=>St.current?.focus());return}if(Ne){Qs(),requestAnimationFrame(()=>St.current?.focus());return}qs()},[Qe,Ne,Ln,qs,Qs]);be(()=>{if(!e||!u.composerDictation||!Wt)return;let a=g=>{Zi(g)&&(g.preventDefault(),St.current?.focus({preventScroll:!0}),Ro())};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e,Wt,u.composerDictation,Ro]),$t(()=>{e&&Ia(u.agentId,St.current)},[e,u.agentId]);let oa=W(async a=>{let g=++dt.current,C=Q.messages,G=C.findLast(Be=>Be.role==="user")?.id,ue=C.findLast(Be=>Be.role==="assistant")?.id,de=u.permissionShowPicker?a.permissionMode??we:u.permissionDefaultMode,he=Ot(vn(u.tools,de));ve({modelId:a.modelId,permissionMode:de}),zt.current=null,go.current.set(a.id,ue),Ee.activate(a.id);let Cr=Ee.getStartedAtWallClock(a.id)??Date.now();pr.current=Cr,mr(),po.current={previousUserMessageId:G??null,scrollKey:crypto.randomUUID()},pe(!0),bt(!1),E(!1),ge(jn("accepted")),d(Ko(a.text,a.files));try{let Be=await Hc(u,a.selection);if(!ln({attempt:g,currentAttempt:dt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;a.files.length>0&&ge("Uploading attachments\u2026");let mt=await Oi({acceptedContentTypes:u.composerAttachmentContentTypes,apiBaseUrl:u.apiBaseUrl,conversationId:o,files:a.files,tokenManager:A});if(!ln({attempt:g,currentAttempt:dt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;ke(u,A,o,"message_sent",{messageId:a.id});let wo=us({clientSubmittedAt:Cr,clientTools:he,imageSearch:u.imageSearch,modelId:a.modelId,newsSearch:u.newsSearch,pageContext:Be,permissionMode:de,turnId:a.id,webSearch:u.webSearch});ge(jn("accepted")),await Q.sendMessage(xl(a,mt),{body:wo});let yn=It.current;if(yn)throw It.current=null,yn}catch(Be){if(!ln({attempt:g,currentAttempt:dt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;throw Be instanceof Error&&P(Be.message),Xs(C),Q.clearError(),bt(!1),E(!1),pe(!1),ge(null),Be}},[Q,ve,we,o,d,u,mr,P,Xs,A,Ee]),Un=W((a,{resumeDrainAfter:g=!0}={})=>{le.current=a.id,oa(a).catch(()=>{le.current===a.id&&(le.current=null),qt.current.has(a.id)||ze(C=>ht(En(As(C,{...a,deliveryStatus:"pending"},"prepend"),a.id,"pending"),a.id))}).finally(()=>{le.current===a.id&&(le.current=null),g&&Kt(C=>C+1)})},[oa,ze]),Zt=W((a,g)=>{let C=a.trim();if(!C&&y.length===0)return;let G=!At&&!le.current&&Le.current.messages.length===0,ue=kl({activeMessageId:le.current,authoritativeMessageCount:Q.messages.length,isNewChatStartScreen:x,queuedMessageCount:Le.current.messages.length}),de={files:y,id:g?.messageId??crypto.randomUUID(),...ue?{isInitialTurn:!0}:{},...pn?{modelId:pn}:{},permissionMode:we,selection:U,text:C};G&&(de.deliveryStatus="sending"),ue&&re({files:de.files,id:de.id,text:de.text}),Ee.begin(de.id,g),g?.firstFeedbackPaintedAt!==void 0&&Ee.markPaintedAt(de.id,"first_feedback_paint",g.firstFeedbackPaintedAt),G&&(le.current=de.id),et(he=>rr(As(he,de),!1),{applyAfterPersist:!0}).then(()=>{ra(),G?Un(de):Kt(he=>he+1)}).catch(he=>{G&&(le.current=null),ue&&re(null),g&&k(C),P(he instanceof Error?he.message:"This message could not be saved before sending")})},[y,pn,we,et,Q.messages.length,At,ra,U,Un,P,x,Ee]),gn=n.suggestedPrompts,nu=Vt(a=>Zt(a.prompt,a));be(()=>{if(!e)return;ka(u.agentId);let a=Pa(u.agentId);a&&(a.submitted?nu(a):k(g=>g||a.prompt))},[e,u.agentId]),be(()=>{if(!e||!u.suggestedPromptShortcuts||Q.messages.length>0||gn.length===0)return;let a=g=>{let C=el(g,gn.length);if(C===null)return;let G=gn[C];G&&(g.preventDefault(),Zt(G))};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e,Q.messages.length,u.suggestedPromptShortcuts,Zt,gn]);let sa=a=>{a.preventDefault(),Zt(D)},ru=Vt(async a=>{try{await et(g=>En(g,a.id,"sending"))}catch(g){le.current===a.id&&(le.current=null),P(g instanceof Error?g.message:"This message could not be saved before sending"),ze(C=>ht(C,a.id));return}le.current===a.id&&Un({...a,deliveryStatus:"sending"})}),ou=W(a=>{_n.current=a,st(a)},[]);be(()=>{let a=Ll({activeMessageId:le.current,isBusy:At,isReordering:Ge,queue:s});a&&(le.current=a.id,queueMicrotask(()=>{if(_n.current){le.current===a.id&&(le.current=null);return}le.current===a.id&&ru(a)}))},[At,Ge,s,Et]);let su=W(a=>{re(g=>g?.id===a?null:g),ze(g=>nr(g,a))},[ze]),au=W((a,g,C)=>{ze(G=>Al(ht(G,null),a,g,C))},[ze]),iu=W(a=>{let g=Le.current.messages.find(C=>C.id===a);g&&(Qe(),k(g.text),T(g.files),g.modelId&&_(g.modelId),g.permissionMode&&qe(g.permissionMode),V(g.selection),H(!0),re(C=>C?.id===a?null:C),ze(C=>nr(ht(C,null),a)),requestAnimationFrame(()=>St.current?.focus()))},[Qe,T,ze,qe,_]),lu=W(a=>{if(At||le.current)return;let g=Le.current.messages.find(C=>C.id===a);g&&(le.current=g.id,et(C=>rr(En(ht(C,null),a,"sending"),!0)).then(()=>{le.current===g.id&&Un({...g,deliveryStatus:"sending"},{resumeDrainAfter:!1})}).catch(C=>{le.current===g.id&&(le.current=null),P(C instanceof Error?C.message:"This message could not be saved before sending")}))},[et,At,Un,P]),aa=W(()=>{let a=le.current;dr.current+=1,dt.current+=1,Ze.current=!0,He.current=!1,le.current=null,re(null),ze(C=>rr(a&&!qt.current.has(a)?En(ht(C,null),a,"pending"):ht(C,null),!0)),pe(!1),ge(null),bt(!1),E(!1),ke(u,A,o,"stopped");let g=Promise.resolve().then(()=>Q.stop()).catch(()=>{}).finally(()=>{Qt.current===g&&(Qt.current=null),On.current()});Qt.current=g},[Q,o,u,ze,A]),cu=Vt(()=>{if(Ze.current||He.current)return;let a=le.current;dr.current+=1,dt.current+=1,He.current=!0,le.current=null,ze(C=>rr(a?nr(ht(C,null),a):ht(C,null),!0)),pe(!1),ge(null),bt(!1),E(!0),ke(u,A,o,"turn_stalled",{messageId:a??void 0,source:"client-inactivity-watchdog"});let g=Promise.resolve().then(()=>Q.stop()).catch(()=>{}).finally(()=>{Qt.current===g&&(Qt.current=null),On.current(),He.current&&E(!0)});Qt.current=g});be(()=>{if(Ac({hasActiveTurn:Ue,hasPendingClientToolCalls:Yt,isResuming:Xt,stalled:lt}))return Tc(cu)},[Q.isRecovering,Q.messages,Q.status,gr,Ue,Yt,Xt,Je,it,lt]);let uu=W(a=>{if(ke(u,A,o,`component_${a.type}`,{actionId:"actionId"in a?a.actionId:void 0,componentId:a.componentId,format:"format"in a?a.format:void 0,hasToolName:"toolName"in a}),a.type==="tool"){let g=Sa(De,a.toolName);if(g){(async()=>{try{let C=Ar(g,a.args),G=`component-action-${crypto.randomUUID()}`;await g.execute(C,u.context,{conversationId:o,idempotencyKey:`heroui-agent-component-action:${o}:${G}`,toolCallId:G})}catch{}})();return}}Qi(a,{fillComposer:g=>{Qe(),k(g),H(!0),requestAnimationFrame(()=>St.current?.focus())},setSelection:V,submitPrompt:Zt})},[Qe,De,o,u,Zt,A]),du=W(a=>{let g=a.parts.filter(C=>C.type==="text").map(C=>C.text).join(`
|
|
4
4
|
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as m,b as a}from"./chunk-
|
|
1
|
+
import{a as m,b as a}from"./chunk-QDIT4IVA.js";import"./chunk-TV4IIQ5G.js";import"./chunk-6ZJJN322.js";import{a as e}from"./chunk-64RI74L5.js";import{a as t,b as n,c as o,d as r,e as A,f as g,g as i}from"./chunk-OA3TG5CS.js";import{a as s}from"./chunk-7KCGPNEN.js";import{a as p}from"./chunk-2XBFFSW2.js";export{p as AGENT_DESIGN_THEMES,t as AGENT_MODEL_IDS,A as AGENT_MODEL_OPTIONS,r as DEFAULT_AGENT_PICKER_MODEL_ID,s as HEROUI_AGENT_RUNTIME_TIMING_EVENT,a as HeroUIAgent,n as LEGACY_AGENT_MODEL_IDS,e as createToolHelper,i as getAgentModelTier,g as isAgentModelId,o as resolveAgentModelId,m as useAgent};
|
package/dist/next.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as i,b as p}from"./chunk-
|
|
1
|
+
import{a as i,b as p}from"./chunk-QDIT4IVA.js";import"./chunk-TV4IIQ5G.js";import"./chunk-6ZJJN322.js";import{a as e}from"./chunk-64RI74L5.js";import{a as t,d as n,e as o,f as r,g as A}from"./chunk-OA3TG5CS.js";import{a as g}from"./chunk-7KCGPNEN.js";import"./chunk-2XBFFSW2.js";export{t as AGENT_MODEL_IDS,o as AGENT_MODEL_OPTIONS,n as DEFAULT_AGENT_PICKER_MODEL_ID,g as HEROUI_AGENT_RUNTIME_TIMING_EVENT,p as HeroUIAgent,e as createToolHelper,A as getAgentModelTier,r as isAgentModelId,i as useAgent};
|
package/dist/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z as e}from"zod";var m="0.2.0-beta.
|
|
1
|
+
import{z as e}from"zod";var m="0.2.0-beta.11";var d=e.enum(["light","dark","system"]),A=e.enum(["outline","plain","surface","surface-secondary"]),y=new Set(["[object object]","0","anonymous","distinct_id","distinctid","email","false","guest","id","nan","none","not_authenticated","null","true","undefined"]),c=e.string().trim().min(1).max(200).refine(t=>!y.has(t.toLowerCase()),{message:"Identity id is reserved"}),f=e.discriminatedUnion("type",[e.object({id:c,type:e.literal("anonymous")}),e.object({id:c,type:e.literal("user")})]),S=e.object({avatarUrl:e.string().trim().pipe(e.url()).optional(),email:e.string().trim().max(320).pipe(e.email()).optional(),name:e.string().trim().max(120).optional()}),u=e.object({anonymousId:c.optional(),identity:f,profile:S.optional()}),g=e.object({expiresAt:e.number().int().positive(),token:e.string().trim().min(1)}),O=e.object({agentId:e.string().trim().min(1).max(100),apiKeyId:e.string().trim().min(1).max(100),aud:e.literal("heroui-agent"),exp:e.number().int().positive(),iat:e.number().int().positive(),iss:e.literal("https://api.heroui.com"),jti:e.uuid(),protocolVersion:e.literal(6),sub:e.string().trim().min(1).max(200)});var R=e.object({agentId:e.string(),minimumProtocolVersion:e.literal(6),name:e.string().trim().min(1).max(120),protocolVersion:e.literal(6),sdkVersion:e.string().default(m),suggestedPrompts:e.array(e.string().trim().min(1).max(160)).max(5),surfaceVariant:A.default("plain"),theme:d});var I="https://api.heroui.com",n=class extends Error{status;constructor(o,i,a){super(o,a),this.name="HeroUIAgentAuthError",this.status=i}};async function C(t){let o=t.apiKey.trim(),i=t.agentId.trim(),a=u.safeParse({anonymousId:t.anonymousId,identity:t.identity,profile:t.profile});if(!o||!i||!a.success)throw new n("Invalid HeroUI Agent auth token request",400);let h=(t.apiBaseUrl?.trim()||I).replace(/\/$/,""),r;try{r=await fetch(`${h}/v1/agents/${encodeURIComponent(i)}/auth-tokens`,{body:JSON.stringify(a.data),cache:"no-store",headers:{Accept:"application/json","Content-Type":"application/json","X-HeroUI-Agent-Key":o},method:"POST"})}catch(l){throw new n("HeroUI Agent authentication is unavailable",503,{cause:l})}if(!r.ok)throw new n("HeroUI Agent authentication failed",r.status);let p=g.safeParse(await r.json().catch(()=>null));if(!p.success)throw new n("HeroUI Agent authentication returned invalid data",502);return p.data}export{n as HeroUIAgentAuthError,C as createAuthToken};
|
package/package.json
CHANGED
package/dist/chunk-A53R5SMW.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{b as ce,e as de,f as ue}from"./chunk-2XBFFSW2.js";import{jsx as We,jsxs as Ue}from"react/jsx-runtime";function gt({indicator:e,label:t="Loading agent\u2026"}){return Ue("div",{"aria-live":"polite",className:"ha-agent-loading",role:"status",children:[e,We("span",{children:t})]})}import{jsx as me,jsxs as Be}from"react/jsx-runtime";function U({children:e,shortcut:t}){return Be("span",{"aria-hidden":"true",className:"ha-control-tooltip",children:[me("span",{children:e}),t?me("kbd",{className:"ha-control-tooltip__shortcut",children:t}):null]})}import{ChevronsCollapseUpRight as Ke,ChevronsExpandUpRight as $e}from"@gravity-ui/icons";import{useCallback as he,useEffect as J,useEffectEvent as Ve,useRef as Q,useState as B}from"react";function pe(e){return`heroui-agent:sidebar-width:${e}`}function Y(e,t){let n=Math.min(720,Math.floor(t*.9)),o=Math.max(n,320);return Math.min(Math.max(Math.round(e),320),o)}function ge(e,t){let n=Number.NaN;try{n=Number(localStorage.getItem(pe(e))??Number.NaN)}catch{}return Y(Number.isFinite(n)?n:420,t)}function Z(e,t){try{localStorage.setItem(pe(e),String(Math.round(t)))}catch{}}import{jsx as d,jsxs as I}from"react/jsx-runtime";function St({actionsSlot:e,agentId:t,children:n,defaultExpanded:o=!1,expandable:l=!0,expandedSidebarSlot:f,expandedTitle:y,historySlot:a,keepMounted:c=!1,modal:p,name:S,onClose:E,onNewConversation:w,open:h}){let v=Q(null),u=Q(0),[M,j]=B(()=>typeof window<"u"&&window.matchMedia?.("(max-width: 639px)").matches===!0),O=Ve(E),[g,H]=B(o),P=!p&&!M,A=p||M||P&&g,[R,k]=B(!1),i=!M&&l,m=P&&g&&f;return J(()=>{let r=window.matchMedia?.("(max-width: 639px)");if(!r)return;let T=()=>j(r.matches);return T(),r.addEventListener?.("change",T),()=>r.removeEventListener?.("change",T)},[]),J(()=>{if(!R)return;let r=v.current;if(!r)return;let T=()=>k(!1),C=L=>{let{propertyName:F,target:q}=L;q===r&&(F!=="width"&&F!=="height"||T())},D=window.setTimeout(T,600);return r.addEventListener("transitionend",C),()=>{window.clearTimeout(D),r.removeEventListener("transitionend",C)}},[R]),J(()=>{if(!h)return;let r=v.current;if(!r)return;let T=document.activeElement instanceof HTMLElement?document.activeElement:null;r.open||(A&&typeof r.showModal=="function"?r.showModal():!A&&typeof r.show=="function"?r.show():r.open=!0);let C=document.documentElement,D=window.scrollX,L=window.scrollY,F=C.style.overflow,q=document.body.style.overflow,Ie=document.body.style.position,_e=document.body.style.top,Oe=document.body.style.left,De=document.body.style.right,Le=document.body.style.width;A&&(C.style.overflow="hidden",document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`${-L}px`,document.body.style.left=`${-D}px`,document.body.style.right="0",document.body.style.width="100%");let Fe=r.querySelector("button,textarea,input,[tabindex]:not([tabindex='-1'])");r.contains(document.activeElement)||Fe?.focus();let re=b=>{if(!A&&b.key==="Escape"){if(fe(r)){u.current=Date.now(),b.preventDefault(),b.stopPropagation();return}b.preventDefault(),O();return}if(!A||b.key!=="Tab")return;let W=Array.from(r.querySelectorAll("button:not(:disabled),textarea:not(:disabled),input:not(:disabled),[tabindex]:not([tabindex='-1'])"));if(W.length===0)return;let ae=W[0],ie=W[W.length-1],se=r.getRootNode(),le=se instanceof ShadowRoot?se.activeElement:document.activeElement;b.shiftKey&&le===ae?(b.preventDefault(),ie.focus()):!b.shiftKey&&le===ie&&(b.preventDefault(),ae.focus())};return r.addEventListener("keydown",re),()=>{r.removeEventListener("keydown",re),typeof r.close=="function"?r.close():r.open=!1,C.style.overflow=F,document.body.style.overflow=q,document.body.style.position=Ie,document.body.style.top=_e,document.body.style.left=Oe,document.body.style.right=De,document.body.style.width=Le,A&&window.scrollTo(D,L),document.activeElement===document.body&&T?.focus()}},[A,h]),!h&&!c?null:I("dialog",{ref:v,"aria-label":S,"aria-modal":A,className:"ha-panel","data-agent-overlay-root":"","data-expanded":!M&&g?"true":void 0,"data-expanded-sidebar":m?"true":void 0,"data-resizing":R?"true":void 0,hidden:!h,onCancel:r=>{if(r.preventDefault(),Date.now()-u.current<350||fe(v.current)){u.current=Date.now();return}E()},children:[P&&!g?d(Xe,{agentId:t,panelRef:v}):null,m?d("aside",{"aria-label":"Chat history",className:"ha-expanded-sidebar",children:f}):null,I("div",{className:"ha-panel-main",children:[I("header",{className:"ha-header",children:[m?d("span",{className:"ha-session-title ha-expanded-chat-title",children:y??S}):a??d("strong",{children:S}),I("div",{className:"ha-header-actions",children:[m?null:e??(w?d("button",{"aria-label":"New chat",className:"ha-icon-button ha-new-chat-button",type:"button",onClick:w,children:d(qe,{})}):null),i?d("button",{"aria-expanded":g,"aria-label":g?"Collapse assistant":"Expand assistant",className:"ha-expand-button ha-icon-button",type:"button",onClick:()=>{k(!0),H(r=>!r)},children:g?d(Ke,{"aria-hidden":"true"}):d($e,{"aria-hidden":"true"})}):null,I("button",{"aria-keyshortcuts":"Escape","aria-label":"Close assistant",className:"ha-close-button ha-icon-button","data-shortcut":"ESC","data-tooltip":"Close assistant",type:"button",onClick:E,children:[d(je,{}),d(U,{shortcut:"ESC",children:"Close assistant"})]})]})]}),n,d("div",{className:"ha-overlay-portal","data-agent-overlay-portal":""})]})]})}function fe(e){let t=e?.querySelector(['[data-slot$="-popover"]','[data-slot="agent-ui-image-modal"]','[data-slot="modal-dialog"]',".ha-feedback-popover"].join(","));return t?(t.querySelector('button[aria-label="Dismiss"]')?.click(),!0):!1}function Xe({agentId:e,panelRef:t}){let[n,o]=B(()=>ge(e,window.innerWidth)),l=Q(null),f=he(a=>{let c=t.current,p=c?.getRootNode();(p instanceof ShadowRoot?p.host:c?.closest("[data-heroui-agent]"))?.style.setProperty("--ha-sidebar-width",`${a}px`),window.innerWidth>=640&&(document.documentElement.style.marginRight=`${Math.min(a,window.innerWidth)}px`),o(a)},[t]),y=he((a,c)=>{let p=Y(a,window.innerWidth);return f(p),c&&Z(e,p),p},[f,e]);return d("div",{"aria-label":"Resize assistant panel","aria-orientation":"vertical","aria-valuemax":720,"aria-valuemin":320,"aria-valuenow":n,className:"ha-resize-handle",role:"separator",tabIndex:0,onKeyDown:a=>{let c=a.key==="ArrowLeft"?24:a.key==="ArrowRight"?-24:0;c!==0&&(a.preventDefault(),y(n+c,!0))},onPointerCancel:a=>{let c=l.current;c&&(l.current=null,delete a.currentTarget.dataset.resizing,t.current&&delete t.current.dataset.dragResizing,document.documentElement.style.transition=c.pageTransition,y(c.startWidth,!1))},onPointerDown:a=>{a.button!==0&&a.pointerType==="mouse"||(a.preventDefault(),a.currentTarget.setPointerCapture(a.pointerId),a.currentTarget.dataset.resizing="true",l.current={currentWidth:n,pageTransition:document.documentElement.style.transition,startWidth:n,startX:a.clientX},document.documentElement.style.transition="none",t.current&&(t.current.dataset.dragResizing="true"))},onPointerMove:a=>{let c=l.current;c&&(c.currentWidth=y(c.startWidth+(c.startX-a.clientX),!1))},onPointerUp:a=>{let c=l.current;c&&(l.current=null,delete a.currentTarget.dataset.resizing,t.current&&delete t.current.dataset.dragResizing,a.currentTarget.releasePointerCapture(a.pointerId),document.documentElement.style.transition=c.pageTransition,Z(e,c.currentWidth))}})}function je(){return d("svg",{"aria-hidden":"true",fill:"none",height:"18",viewBox:"0 0 18 18",width:"18",children:d("path",{d:"m4.25 4.25 9.5 9.5m0-9.5-9.5 9.5",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"1.6"})})}function qe(){return d("svg",{"aria-hidden":"true",fill:"none",height:"18",viewBox:"0 0 18 18",width:"18",children:d("path",{d:"M9 4v10M4 9h10",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"1.6"})})}function Ae(e){let t=performance.now(),n=Date.now(),o=e.trim();return o?{messageId:crypto.randomUUID(),prompt:o,startedAt:t,startedAtWallClock:n,submitted:!0}:null}var N=new Map,G=new Map,Ye=10080*60*1e3,z=new Map;function be(e){return`heroui-agent:shell-draft:${e}:composer-draft:v1`}function ee(e,t){try{let n=be(e);t.trim()?localStorage.setItem(n,JSON.stringify({prompt:t,savedAt:Date.now()})):localStorage.removeItem(n)}catch{}}function Ze(e){let t=be(e);try{let n=JSON.parse(localStorage.getItem(t)??"null");if(n&&typeof n.prompt=="string"&&n.prompt.trim()&&typeof n.savedAt=="number"&&Date.now()-n.savedAt<=Ye)return n.prompt;localStorage.removeItem(t)}catch{}return""}function K(e,t){if(!t.prompt.trim()&&!t.submitted){N.delete(e),ee(e,"");return}N.set(e,t),t.submitted||ee(e,t.prompt)}function te(e){let t=N.get(e);if(t)return t;let n=Ze(e);return n?{prompt:n,submitted:!1}:void 0}function ye(e,t,n){let o=N.get(e);!o?.submitted||o.messageId!==t||o.firstFeedbackPaintedAt!==void 0||N.set(e,{...o,firstFeedbackPaintedAt:n})}function kt(e){let t=te(e);return N.delete(e),ee(e,""),t}function _(e,t,n){t?z.set(e,[n?.selectionStart??0,n?.selectionEnd??0,n?.selectionDirection??"none"]):z.delete(e)}function ve(e,t){let n=z.get(e);if(!n||!t)return;t.focus({preventScroll:!0});let o=Math.min(n[0],t.value.length),l=Math.min(n[1],t.value.length);t.setSelectionRange(o,l,n[2]),z.set(e,[o,l,n[2]])}function Te(e,t){return t instanceof Node?e.contains(t)||e.closest(".ha-composer-wrap")?.querySelector(".ha-footnote")?.contains(t)===!0||e.closest(".ha-root")?.querySelector(".ha-overlay-portal")?.contains(t)===!0:!1}function Ct(e,t){t.length===0?G.delete(e):G.set(e,t)}function Je(e){return G.get(e)??[]}function Nt(e){let t=Je(e);return G.delete(e),t}function we(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function Qe(e){let t=getComputedStyle(e),n=Number.parseFloat(t.lineHeight);if(Number.isFinite(n)&&n>0)return n;let o=Number.parseFloat(t.fontSize);return Number.isFinite(o)&&o>0?o*1.2:20}function et(e){let t=getComputedStyle(e);return we(t.paddingTop)+we(t.paddingBottom)}function tt(e){let t=e.style.height,n=e.style.minHeight,o=e.style.maxHeight;e.style.height="0px",e.style.minHeight="0px",e.style.maxHeight="none";let l=e.scrollHeight;return e.style.height=t,e.style.minHeight=n,e.style.maxHeight=o,l}function nt(e){if(e.value.includes(`
|
|
2
|
-
`))return!0;if(e.clientWidth===0)return!1;let t=tt(e),n=et(e),o=Qe(e);return Math.max(0,t-n)>o*1.5}function ne(e,{hasAttachments:t=!1,maxHeight:n=120}={}){if(!e)return!1;let o=e.value.length>0;return t||o&&nt(e)?(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,n)}px`,!0):(e.style.height="auto",!1)}import{jsx as oe,jsxs as xe}from"react/jsx-runtime";var ot="https://heroui.pro/?utm_source=heroui-agent&utm_medium=referral&utm_campaign=powered-by-hero";function Se(){return xe("a",{"aria-label":"Powered by HeroUI Pro (opens in a new tab)",className:"ha-powered-by",href:ot,rel:"noopener noreferrer",target:"_blank",children:[oe("span",{children:"Powered by"}),xe("svg",{"aria-hidden":"true",className:"ha-powered-by-logo",fill:"none",viewBox:"0 0 140 44",children:[oe("path",{d:"M.678 11.385V24.04c0 .599.307 1.155.813 1.471l8.628 5.396c1.15.719 2.639-.11 2.639-1.47V18.798c0-.612.322-1.18.847-1.491l5.263-3.13v27.267c0 1.355 1.48 2.186 2.63 1.476l8.905-5.497a1.72 1.72 0 0 0 .822-1.476V9.765c0-1.349-1.467-2.18-2.618-1.484l-9.74 5.897V2.556c0-1.345-1.46-2.177-2.61-1.488L1.52 9.897a1.72 1.72 0 0 0-.842 1.488Z",fill:"currentColor"}),oe("path",{d:"M63.876 24.071c0-3.59-1.468-5.246-4.405-5.246-3.363 0-5.732 2.255-5.732 7.316v11.595h-6.063V5.528h6.063v11.779c1.468-2.393 3.884-3.59 7.2-3.59 5.637 0 8.953 3.451 8.953 9.25v14.769h-6.016V24.071ZM84.9 38.473c-7.533 0-12.317-4.877-12.317-12.378 0-7.408 4.737-12.378 12.317-12.378 8.195 0 12.648 5.798 11.416 13.942H78.647c.331 3.865 2.605 6.075 6.253 6.075 2.984 0 4.784-1.52 5.258-3.037h6.016c-.947 4.509-5.115 7.776-11.274 7.776ZM78.789 23.657h11.653c-.047-3.175-2.132-5.338-5.685-5.338-3.174 0-5.4 1.84-5.968 5.338ZM99.623 20.344c0-3.82 2.131-5.89 6.205-5.89h7.77v4.97h-7.912v18.312h-6.063V20.344ZM126.863 38.473c-7.674 0-12.553-4.924-12.553-12.378 0-7.454 4.879-12.378 12.553-12.378 7.58 0 12.459 4.924 12.459 12.378 0 7.454-4.88 12.378-12.46 12.378Zm0-5.016c3.79 0 6.3-2.898 6.3-7.362 0-4.463-2.51-7.408-6.3-7.408-3.838 0-6.348 2.945-6.348 7.408 0 4.464 2.51 7.362 6.348 7.362Z",fill:"currentColor"})]})]})}var Ee=new Set(["ask","auto","full"]);function $(e){return Ee.has(e)?e:"auto"}function _t(e,t){return`${e}:permission-mode:${t}:v1`}function Ot(e,t){return`${e}:active-permission-mode:${t}:v1`}function Dt(e){try{let t=localStorage.getItem(e);return t!==null&&Ee.has(t)?$(t):void 0}catch{return}}function Lt(e,t){try{localStorage.setItem(e,t)}catch{}}function Ft(e){try{localStorage.removeItem(e)}catch{}}function Wt(e,t){let n=$(t);if(n==="auto")return e;let o=n==="ask";return e.map(l=>!!l.needsApproval===o?l:{...l,needsApproval:o})}function Me(e){return`heroui-agent:anonymous:${e}`}var ke=class{constructor(t,n){this.agentId=t;this.getAuthToken=n}cached=null;generation=0;pending=null;clear(){this.generation+=1,this.cached=null,this.pending=null}reset(){this.clear();try{localStorage.removeItem(Me(this.agentId))}catch{}}async get(){if(this.cached&&this.expiresAt(this.cached)>Date.now()+6e4)return this.cached.token;let t=this.generation,n=this.pending??this.refresh();this.pending||(this.pending=n);try{let o=await n;return t!==this.generation?this.get():(this.cached=o,o.token)}finally{this.pending===n&&(this.pending=null)}}async subjectHash(){let t=await this.get(),n=rt(t),o=typeof n.sub=="string"?n.sub:"anonymous",l=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${this.agentId}:${o}`));return Array.from(new Uint8Array(l),f=>f.toString(16).padStart(2,"0")).join("").slice(0,24)}anonymousId(){let t=Me(this.agentId);try{let n=localStorage.getItem(t);if(n)return n;let o=crypto.randomUUID();return localStorage.setItem(t,o),o}catch{return crypto.randomUUID()}}expiresAt(t){return t.expiresAt}async refresh(){let t=await this.getAuthToken({agentId:this.agentId,anonymousId:this.anonymousId()});if(!t||typeof t.token!="string"||!t.token.trim()||typeof t.expiresAt!="number"||!Number.isFinite(t.expiresAt)||t.expiresAt<=0)throw new Error("Auth token callback returned invalid data");return{expiresAt:t.expiresAt,token:t.token}}};function rt(e){try{let t=e.split(".")[1];if(!t)return{};let n=t.replace(/-/g,"+").replace(/_/g,"/"),o=n.padEnd(Math.ceil(n.length/4)*4,"=");return JSON.parse(atob(o))}catch{return{}}}var at={"application/json":"json","application/pdf":"pdf","image/gif":"gif","image/jpeg":"jpg","image/png":"png","image/webp":"webp","text/csv":"csv","text/markdown":"md","text/plain":"txt","text/tab-separated-values":"tsv"},V=Object.freeze(Object.keys(at)),Gt=V.join(","),it=new Set(V);function Ce(e){return it.has(e.trim().toLowerCase())}import{useEffect as st,useLayoutEffect as Ne,useRef as lt,useState as X}from"react";import{Fragment as He,jsx as s,jsxs as x}from"react/jsx-runtime";function qt({agentId:e,composerConnecting:t=!1,composerControlsAvailable:n,composerControlsRevealed:o,composerEndSlot:l,composerFooterSlot:f,composerStartSlot:y,greeting:a,onComposerControlsReveal:c,onIntent:p,placeholder:S,suggestedPrompts:E}){let[w]=X(()=>te(e)),[h,v]=X(()=>w?.submitted?"":w?.prompt??""),[u,M]=X(()=>w?.submitted?w:null),[j,O]=X(!1),g=lt(null),H=n??!!(y||l),P=o??(H&&j),A=i=>{_(e,!0,i.currentTarget),O(H),H&&c?.(),p()},R=i=>{let m=i.currentTarget.querySelector(".ha-composer");m&&Te(m,i.relatedTarget)||(O(!1),_(e,!1))};Ne(()=>{ve(e,g.current),ne(g.current)},[e]),st(()=>{u||K(e,{prompt:h,submitted:!1})},[h,e,u]),Ne(()=>{if(!u)return;let i=requestAnimationFrame(m=>{ye(e,u.messageId,m)});return()=>cancelAnimationFrame(i)},[e,u]);let k=i=>{if(u)return;let m=Ae(i);m&&(M(m),v(""),g.current.style.height="auto",K(e,m),p())};return x(He,{children:[s("div",{className:"ha-conversation",children:s("div",{"aria-live":"polite",className:"ha-messages",role:"log",children:u?x(He,{children:[s("div",{className:"ha-message","data-role":"user",children:s("div",{className:"ha-bubble",children:s("div",{className:"ha-message-content",children:s("p",{className:"ha-message-text",children:u.prompt})})})}),s("div",{className:"ha-message","data-role":"assistant","data-stream-anchor":"true","data-turn-feedback-id":u.messageId,children:s("div",{className:"ha-message-body",children:s("div",{"aria-label":"Working on your request\u2026",className:"ha-progress ha-activity-status ha-progress-shimmer",role:"status",children:s("span",{"aria-hidden":"true",className:"ha-shimmer",children:"Thinking\u2026"})})})})]}):x("div",{className:"ha-empty",children:[s("h2",{children:a}),s("p",{children:"Live answers with charts, metrics, and tables."})]})})}),x("form",{className:"ha-composer-wrap",onBlur:R,onSubmit:i=>{i.preventDefault(),k(h)},children:[!u&&E.length>0?s("div",{"aria-label":"Suggested prompts",className:"ha-suggestions",role:"group",children:E.map(i=>x("button",{className:"ha-suggestion",type:"button",onClick:()=>k(i),children:[s("span",{children:i}),s(dt,{})]},i))}):null,x("div",{className:"@container ha-composer","data-connecting":t||void 0,"data-controls-revealed":P||void 0,children:[y,s("textarea",{ref:g,"aria-label":"Message the assistant",placeholder:S,readOnly:!!u,rows:1,value:h,onFocus:A,onSelect:i=>_(e,!0,i.currentTarget),onChange:i=>{let m=i.currentTarget.value;K(e,{prompt:m,submitted:!1}),_(e,!0,i.currentTarget),v(m),ne(i.currentTarget),p()},onKeyDown:i=>{i.key!=="Enter"||i.shiftKey||(i.preventDefault(),k(h))}}),l,x("button",{"aria-label":"Send message",className:"ha-send",disabled:!h.trim()||!!u,type:"submit",children:[s(ct,{}),s(U,{shortcut:"\u21B5",children:"Send message"})]})]}),s("div",{className:"ha-composer-footer","data-revealed":!!f||void 0,children:s("div",{className:"ha-composer-footer-content",children:f})}),s(Se,{})]})]})}function ct(){return s("svg",{"aria-hidden":"true",fill:"none",height:"18",viewBox:"0 0 18 18",width:"18",children:s("path",{d:"M9 14.5V3.5m0 0L4.5 8M9 3.5 13.5 8",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.6"})})}function dt(){return s("svg",{"aria-hidden":"true",fill:"none",height:"16",viewBox:"0 0 16 16",width:"16",children:s("path",{d:"M5 11 11 5m0 0H6m5 0v5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5"})})}var ut={animation:"fadeIn",duration:160,easing:"ease-out",sep:"word",stagger:18};function Pe(e){return typeof e=="number"?Number.isFinite(e)?`${Math.round(e)}px`:void 0:e?.trim()||void 0}function mt(e){let t=Pe(e?.initialWidth),n=Pe(e?.initialHeight);return{...t?{"--ha-panel-width":t}:{},...n?{"--ha-panel-height":n}:{}}}function Re(e){return e===void 0||!Number.isFinite(e)?24:Math.min(Math.max(Math.round(e),0),200)}function pt(e){if(e===void 0)return[...V];if(e===!1||!Array.isArray(e))return[];let t=new Set;for(let n of e){if(typeof n!="string")continue;let o=n.trim().toLowerCase();Ce(o)&&t.add(o)}return[...t]}function tn(e){if(typeof e.agentId!="string"||!e.agentId.trim())throw new Error("HeroUI Agent agentId is required");if(typeof e.getAuthToken!="function")throw new Error("HeroUI Agent getAuthToken is required");let t=pt(e.composer?.attachments),n=typeof e.composer?.disclaimer=="string"&&e.composer.disclaimer.trim().slice(0,240)||void 0;return{apiBaseUrl:(e._api?.baseUrl??"https://api.heroui.com").replace(/\/$/,""),colorScheme:e.appearance?.theme?.colorScheme??"system",componentExportFormats:e.componentExports===!1?[]:e.componentExports??["csv","svg","png"],composerAttachmentAccept:t.join(","),composerAttachmentContentTypes:t,composerControlsAvailable:t.length>0||e.permissions?.showPicker===!0&&!!e.tools?.length||e.composer?.modelPicker===!0||(e.composer?.dictation??!0),composerDefaultModel:e.composer?.defaultModel,composerDictation:e.composer?.dictation??!0,designTheme:ce(e.appearance?.theme?.designTheme),...n?{composerDisclaimer:n}:{},agentId:e.agentId,composerModelPicker:e.composer?.modelPicker??!1,composerPlaceholder:e.composer?.placeholder?.trim().slice(0,120)||"Ask anything\u2026",context:e.context,getAuthToken:e.getAuthToken,greeting:e.startScreen?.greeting?.trim().slice(0,120)||"Ask about your data",launcherPosition:e.appearance?.launcher?.position??"bottom-right",markdownAnimation:e.markdown?.animated??ut,markdownCaret:e.markdown?.caret??"block",markdownPlugins:e.markdown?.plugins,messageActions:e.responseActions===!1?[]:e.responseActions??["copy","feedback","retry"],onFeedback:e.onFeedback,panelExpandable:e.appearance?.panel?.expandable??!0,panelExpanded:e.appearance?.panel?.expanded??!1,panelStyle:mt(e.appearance?.panel),permissionDefaultMode:$(e.permissions?.defaultMode),permissionShowPicker:e.permissions?.showPicker===!0,preload:e.preload??!0,reopenOnRefresh:e.reopenOnRefresh??!1,showLauncher:e.showLauncher??!0,startNewConversationOnOpen:e.startNewConversationOnOpen??!1,suggestedPromptShortcuts:e.startScreen?.promptShortcuts??!1,...e.appearance?.launcher?.icon?.trim()?{launcherIcon:e.appearance.launcher.icon.trim()}:{},...e.appearance?.launcher?.style?{launcherStyle:e.appearance.launcher.style}:{},...e.appearance?.launcher?.offset?{launcherOffset:{x:Re(e.appearance.launcher.offset.x),y:Re(e.appearance.launcher.offset.y)}}:{},imageSearch:(e.capabilities?.webSearch??!1)&&(e.capabilities?.imageSearch??!0),newsSearch:(e.capabilities?.webSearch??!1)&&(e.capabilities?.newsSearch??!1),suggestedPrompts:e.startScreen?.prompts?.map(o=>o.trim()).filter(Boolean).slice(0,5),themeStyle:{...ue(e.appearance?.theme),...de(e.appearance?.launcher?.background)},tools:e.tools??[],viewMode:e.appearance?.viewMode??"floating",webSearch:e.capabilities?.webSearch??!1}}export{ke as a,gt as b,U as c,ge as d,St as e,at as f,V as g,Ce as h,Ae as i,K as j,te as k,kt as l,_ as m,ve as n,Te as o,Ct as p,Je as q,Nt as r,ne as s,Se as t,qt as u,_t as v,Ot as w,Dt as x,Lt as y,Ft as z,Wt as A,ut as B,tn as C};
|