@heroui/agent 0.2.0-beta.16 → 0.2.0-beta.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0-beta.17
4
+
5
+ - Publish prereleases with `--tag latest` so `npm i @heroui/agent` gets this
6
+ version. OIDC trusted publishing cannot `dist-tag add` (E401 on 0.2.0-beta.16).
7
+
3
8
  ## 0.2.0-beta.16
4
9
 
5
10
  - Move conversation shimmers to the GPU with a mask and translate animation;
@@ -1,2 +1,2 @@
1
- import{b as de,e as ue,f as me}from"./chunk-4JEZZR5J.js";var xt="0.2.0-beta.16",pe="https://api.heroui.pro";import{jsx as Ge,jsxs as Ke}from"react/jsx-runtime";function Et({indicator:e,label:t="Loading agent\u2026"}){return Ke("div",{"aria-live":"polite",className:"ha-agent-loading",role:"status",children:[e,Ge("span",{children:t})]})}import{jsx as ge,jsxs as Ve}from"react/jsx-runtime";function V({children:e,shortcut:t}){return Ve("span",{"aria-hidden":"true",className:"ha-control-tooltip",children:[ge("span",{children:e}),t?ge("kbd",{className:"ha-control-tooltip__shortcut",children:t}):null]})}import{ChevronsCollapseUpRight as Ye,ChevronsExpandUpRight as qe}from"@gravity-ui/icons";import{useCallback as Ae,useEffect as $,useEffectEvent as je,useLayoutEffect as Ze,useRef as re,useState as z}from"react";function he(e){return`heroui-agent:sidebar-width:${e}`}function ne(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 fe(e,t){let n=Number.NaN;try{n=Number(localStorage.getItem(he(e))??Number.NaN)}catch{}return ne(Number.isFinite(n)?n:420,t)}function oe(e,t){try{localStorage.setItem(he(e),String(Math.round(t)))}catch{}}import{jsx as d,jsxs as R}from"react/jsx-runtime";function Je(e,t){return e===!1?!1:e===void 0||e===!0||!(t instanceof Element)?!0:e(t)}function It({actionsSlot:e,agentId:t,children:n,defaultExpanded:o=!1,expandable:a=!0,expandedSidebarSlot:b,expandedTitle:w,historySlot:i,keepMounted:c=!1,name:m,onClose:k,onNewConversation:H,open:f,shouldCloseOnInteractOutside:y,showBetaBadge:L=!1,viewMode:p}){let x=re(null),O=re(0),[_,M]=z(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:null),N=je(k),[v,Q]=z(o),F=_!==null,S=_??!1,s=p==="floating",g=!s&&!S,h=S||g&&v,[ee,ce]=z(!1),Le=!S&&a,B=g&&v&&b;return Ze(()=>{let r=window.matchMedia?.("(max-width: 639px)");if(!r)return;let A=()=>M(r.matches);return A(),r.addEventListener?.("change",A),()=>r.removeEventListener?.("change",A)},[]),$(()=>{if(!ee)return;let r=x.current;if(!r)return;let A=()=>ce(!1),E=U=>{let{propertyName:u,target:T}=U;T===r&&(u!=="width"&&u!=="height"||A())},te=window.setTimeout(A,600);return r.addEventListener("transitionend",E),()=>{window.clearTimeout(te),r.removeEventListener("transitionend",E)}},[ee]),$(()=>{if(!f||!F)return;let r=x.current;if(!r)return;let A=document.activeElement instanceof HTMLElement?document.activeElement:null;r.open||(h&&typeof r.showModal=="function"?r.showModal():!h&&typeof r.show=="function"?r.show():r.open=!0);let E;if(h){let u=document.documentElement,T=window.scrollX,I=window.scrollY,W=u.style.overflow,G=document.body.style.overflow,K=document.body.style.position,Fe=document.body.style.top,Be=document.body.style.left,Ue=document.body.style.right,We=document.body.style.width;u.style.overflow="hidden",document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`${-I}px`,document.body.style.left=`${-T}px`,document.body.style.right="0",document.body.style.width="100%",E=()=>{u.style.overflow=W,document.body.style.overflow=G,document.body.style.position=K,document.body.style.top=Fe,document.body.style.left=Be,document.body.style.right=Ue,document.body.style.width=We,window.scrollTo(T,I)}}let te=r.querySelector("button,textarea,input,[tabindex]:not([tabindex='-1'])");r.contains(document.activeElement)||te?.focus();let U=u=>{if(!h&&u.key==="Escape"){if(be(r)){O.current=Date.now(),u.preventDefault(),u.stopPropagation();return}u.preventDefault(),N();return}if(!h||u.key!=="Tab")return;let T=Array.from(r.querySelectorAll("button:not(:disabled),textarea:not(:disabled),input:not(:disabled),[tabindex]:not([tabindex='-1'])"));if(T.length===0)return;let I=T[0],W=T[T.length-1],G=r.getRootNode(),K=G instanceof ShadowRoot?G.activeElement:document.activeElement;u.shiftKey&&K===I?(u.preventDefault(),W.focus()):!u.shiftKey&&K===W&&(u.preventDefault(),I.focus())};return r.addEventListener("keydown",U),()=>{r.removeEventListener("keydown",U),typeof r.close=="function"?r.close():r.open=!1,E?.(),document.activeElement===document.body&&A?.focus()}},[h,f,F]),$(()=>{if(!f||!s||h)return;let r=x.current;if(!r)return;let A=E=>{E.composedPath().includes(r)||Je(y,E.target)&&N()};return document.addEventListener("click",A,!0),()=>document.removeEventListener("click",A,!0)},[h,s,f,y]),!f&&!c?null:R("dialog",{ref:x,"aria-label":m,"aria-modal":h,className:"ha-panel","data-agent-overlay-root":"","data-expanded":!S&&v?"true":void 0,"data-expanded-sidebar":B?"true":void 0,"data-resizing":ee?"true":void 0,hidden:!f,onCancel:r=>{if(r.preventDefault(),Date.now()-O.current<350||be(x.current)){O.current=Date.now();return}k()},children:[g&&!v?d(Qe,{agentId:t,panelRef:x}):null,B?d("aside",{"aria-label":"Chat history",className:"ha-expanded-sidebar",children:b}):null,R("div",{className:"ha-panel-main",children:[R("header",{className:"ha-header",children:[R("div",{className:"ha-header-title",children:[B?d("span",{className:"ha-session-title ha-expanded-chat-title",children:w??m}):i??d("strong",{children:m}),L?d("span",{className:"ha-beta-badge",children:"Beta"}):null]}),R("div",{className:"ha-header-actions",children:[B?null:e??(H?d("button",{"aria-label":"New chat",className:"ha-icon-button ha-new-chat-button",type:"button",onClick:H,children:d(tt,{})}):null),Le?d("button",{"aria-expanded":v,"aria-label":v?"Collapse assistant":"Expand assistant",className:"ha-expand-button ha-icon-button",type:"button",onClick:()=>{ce(!0),Q(r=>!r)},children:v?d(Ye,{"aria-hidden":"true"}):d(qe,{"aria-hidden":"true"})}):null,R("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:k,children:[d(et,{}),d(V,{shortcut:"ESC",children:"Close assistant"})]})]})]}),n,d("div",{className:"ha-overlay-portal","data-agent-overlay-portal":""})]})]})}function be(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 Qe({agentId:e,panelRef:t}){let[n,o]=z(420),a=re(null),b=Ae(i=>{let c=t.current,m=c?.getRootNode();(m instanceof ShadowRoot?m.host:c?.closest("[data-heroui-agent]"))?.style.setProperty("--ha-sidebar-width",`${i}px`),window.innerWidth>=640&&(document.documentElement.style.marginRight=`${Math.min(i,window.innerWidth)}px`),o(i)},[t]);$(()=>{o(fe(e,window.innerWidth))},[e]);let w=Ae((i,c)=>{let m=ne(i,window.innerWidth);return b(m),c&&oe(e,m),m},[b,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:i=>{let c=i.key==="ArrowLeft"?24:i.key==="ArrowRight"?-24:0;c!==0&&(i.preventDefault(),w(n+c,!0))},onPointerCancel:i=>{let c=a.current;c&&(a.current=null,delete i.currentTarget.dataset.resizing,t.current&&delete t.current.dataset.dragResizing,document.documentElement.style.transition=c.pageTransition,w(c.startWidth,!1))},onPointerDown:i=>{i.button!==0&&i.pointerType==="mouse"||(i.preventDefault(),i.currentTarget.setPointerCapture(i.pointerId),i.currentTarget.dataset.resizing="true",a.current={currentWidth:n,pageTransition:document.documentElement.style.transition,startWidth:n,startX:i.clientX},document.documentElement.style.transition="none",t.current&&(t.current.dataset.dragResizing="true"))},onPointerMove:i=>{let c=a.current;c&&(c.currentWidth=w(c.startWidth+(c.startX-i.clientX),!1))},onPointerUp:i=>{let c=a.current;c&&(a.current=null,delete i.currentTarget.dataset.resizing,t.current&&delete t.current.dataset.dragResizing,i.currentTarget.releasePointerCapture(i.pointerId),document.documentElement.style.transition=c.pageTransition,oe(e,c.currentWidth))}})}function et(){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 tt(){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 ye(e,{generateConversationTitle:t=!0}={}){let n=performance.now(),o=Date.now(),a=e.trim();return a?{...t?{}:{generateConversationTitle:!1},messageId:crypto.randomUUID(),prompt:a,startedAt:n,startedAtWallClock:o,submitted:!0}:null}var P=new Map,X=new Map,nt=10080*60*1e3,Y=new Map;function ve(e){return`heroui-agent:shell-draft:${e}:composer-draft:v1`}function ae(e,t){try{let n=ve(e);t.trim()?localStorage.setItem(n,JSON.stringify({prompt:t,savedAt:Date.now()})):localStorage.removeItem(n)}catch{}}function ot(e){let t=ve(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<=nt)return n.prompt;localStorage.removeItem(t)}catch{}return""}function q(e,t){if(!t.prompt.trim()&&!t.submitted){P.delete(e),ae(e,"");return}P.set(e,t),t.submitted||ae(e,t.prompt)}function ie(e){let t=P.get(e);if(t)return t;let n=ot(e);return n?{prompt:n,submitted:!1}:void 0}function Te(e,t,n){let o=P.get(e);!o?.submitted||o.messageId!==t||o.firstFeedbackPaintedAt!==void 0||P.set(e,{...o,firstFeedbackPaintedAt:n})}function Ft(e){let t=ie(e);return P.delete(e),ae(e,""),t}function D(e,t,n){t?Y.set(e,[n?.selectionStart??0,n?.selectionEnd??0,n?.selectionDirection??"none"]):Y.delete(e)}function we(e,t){let n=Y.get(e);if(!n||!t)return;t.focus({preventScroll:!0});let o=Math.min(n[0],t.value.length),a=Math.min(n[1],t.value.length);t.setSelectionRange(o,a,n[2]),Y.set(e,[o,a,n[2]])}function xe(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 Bt(e,t){t.length===0?X.delete(e):X.set(e,t)}function rt(e){return X.get(e)??[]}function Ut(e){let t=rt(e);return X.delete(e),t}function Se(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function at(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 it(e){let t=getComputedStyle(e);return Se(t.paddingTop)+Se(t.paddingBottom)}function st(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 a=e.scrollHeight;return e.style.height=t,e.style.minHeight=n,e.style.maxHeight=o,a}function lt(e){if(e.value.includes(`
1
+ import{b as de,e as ue,f as me}from"./chunk-4JEZZR5J.js";var xt="0.2.0-beta.17",pe="https://api.heroui.pro";import{jsx as Ge,jsxs as Ke}from"react/jsx-runtime";function Et({indicator:e,label:t="Loading agent\u2026"}){return Ke("div",{"aria-live":"polite",className:"ha-agent-loading",role:"status",children:[e,Ge("span",{children:t})]})}import{jsx as ge,jsxs as Ve}from"react/jsx-runtime";function V({children:e,shortcut:t}){return Ve("span",{"aria-hidden":"true",className:"ha-control-tooltip",children:[ge("span",{children:e}),t?ge("kbd",{className:"ha-control-tooltip__shortcut",children:t}):null]})}import{ChevronsCollapseUpRight as Ye,ChevronsExpandUpRight as qe}from"@gravity-ui/icons";import{useCallback as Ae,useEffect as $,useEffectEvent as je,useLayoutEffect as Ze,useRef as re,useState as z}from"react";function he(e){return`heroui-agent:sidebar-width:${e}`}function ne(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 fe(e,t){let n=Number.NaN;try{n=Number(localStorage.getItem(he(e))??Number.NaN)}catch{}return ne(Number.isFinite(n)?n:420,t)}function oe(e,t){try{localStorage.setItem(he(e),String(Math.round(t)))}catch{}}import{jsx as d,jsxs as R}from"react/jsx-runtime";function Je(e,t){return e===!1?!1:e===void 0||e===!0||!(t instanceof Element)?!0:e(t)}function It({actionsSlot:e,agentId:t,children:n,defaultExpanded:o=!1,expandable:a=!0,expandedSidebarSlot:b,expandedTitle:w,historySlot:i,keepMounted:c=!1,name:m,onClose:k,onNewConversation:H,open:f,shouldCloseOnInteractOutside:y,showBetaBadge:L=!1,viewMode:p}){let x=re(null),O=re(0),[_,M]=z(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:null),N=je(k),[v,Q]=z(o),F=_!==null,S=_??!1,s=p==="floating",g=!s&&!S,h=S||g&&v,[ee,ce]=z(!1),Le=!S&&a,B=g&&v&&b;return Ze(()=>{let r=window.matchMedia?.("(max-width: 639px)");if(!r)return;let A=()=>M(r.matches);return A(),r.addEventListener?.("change",A),()=>r.removeEventListener?.("change",A)},[]),$(()=>{if(!ee)return;let r=x.current;if(!r)return;let A=()=>ce(!1),E=U=>{let{propertyName:u,target:T}=U;T===r&&(u!=="width"&&u!=="height"||A())},te=window.setTimeout(A,600);return r.addEventListener("transitionend",E),()=>{window.clearTimeout(te),r.removeEventListener("transitionend",E)}},[ee]),$(()=>{if(!f||!F)return;let r=x.current;if(!r)return;let A=document.activeElement instanceof HTMLElement?document.activeElement:null;r.open||(h&&typeof r.showModal=="function"?r.showModal():!h&&typeof r.show=="function"?r.show():r.open=!0);let E;if(h){let u=document.documentElement,T=window.scrollX,I=window.scrollY,W=u.style.overflow,G=document.body.style.overflow,K=document.body.style.position,Fe=document.body.style.top,Be=document.body.style.left,Ue=document.body.style.right,We=document.body.style.width;u.style.overflow="hidden",document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`${-I}px`,document.body.style.left=`${-T}px`,document.body.style.right="0",document.body.style.width="100%",E=()=>{u.style.overflow=W,document.body.style.overflow=G,document.body.style.position=K,document.body.style.top=Fe,document.body.style.left=Be,document.body.style.right=Ue,document.body.style.width=We,window.scrollTo(T,I)}}let te=r.querySelector("button,textarea,input,[tabindex]:not([tabindex='-1'])");r.contains(document.activeElement)||te?.focus();let U=u=>{if(!h&&u.key==="Escape"){if(be(r)){O.current=Date.now(),u.preventDefault(),u.stopPropagation();return}u.preventDefault(),N();return}if(!h||u.key!=="Tab")return;let T=Array.from(r.querySelectorAll("button:not(:disabled),textarea:not(:disabled),input:not(:disabled),[tabindex]:not([tabindex='-1'])"));if(T.length===0)return;let I=T[0],W=T[T.length-1],G=r.getRootNode(),K=G instanceof ShadowRoot?G.activeElement:document.activeElement;u.shiftKey&&K===I?(u.preventDefault(),W.focus()):!u.shiftKey&&K===W&&(u.preventDefault(),I.focus())};return r.addEventListener("keydown",U),()=>{r.removeEventListener("keydown",U),typeof r.close=="function"?r.close():r.open=!1,E?.(),document.activeElement===document.body&&A?.focus()}},[h,f,F]),$(()=>{if(!f||!s||h)return;let r=x.current;if(!r)return;let A=E=>{E.composedPath().includes(r)||Je(y,E.target)&&N()};return document.addEventListener("click",A,!0),()=>document.removeEventListener("click",A,!0)},[h,s,f,y]),!f&&!c?null:R("dialog",{ref:x,"aria-label":m,"aria-modal":h,className:"ha-panel","data-agent-overlay-root":"","data-expanded":!S&&v?"true":void 0,"data-expanded-sidebar":B?"true":void 0,"data-resizing":ee?"true":void 0,hidden:!f,onCancel:r=>{if(r.preventDefault(),Date.now()-O.current<350||be(x.current)){O.current=Date.now();return}k()},children:[g&&!v?d(Qe,{agentId:t,panelRef:x}):null,B?d("aside",{"aria-label":"Chat history",className:"ha-expanded-sidebar",children:b}):null,R("div",{className:"ha-panel-main",children:[R("header",{className:"ha-header",children:[R("div",{className:"ha-header-title",children:[B?d("span",{className:"ha-session-title ha-expanded-chat-title",children:w??m}):i??d("strong",{children:m}),L?d("span",{className:"ha-beta-badge",children:"Beta"}):null]}),R("div",{className:"ha-header-actions",children:[B?null:e??(H?d("button",{"aria-label":"New chat",className:"ha-icon-button ha-new-chat-button",type:"button",onClick:H,children:d(tt,{})}):null),Le?d("button",{"aria-expanded":v,"aria-label":v?"Collapse assistant":"Expand assistant",className:"ha-expand-button ha-icon-button",type:"button",onClick:()=>{ce(!0),Q(r=>!r)},children:v?d(Ye,{"aria-hidden":"true"}):d(qe,{"aria-hidden":"true"})}):null,R("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:k,children:[d(et,{}),d(V,{shortcut:"ESC",children:"Close assistant"})]})]})]}),n,d("div",{className:"ha-overlay-portal","data-agent-overlay-portal":""})]})]})}function be(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 Qe({agentId:e,panelRef:t}){let[n,o]=z(420),a=re(null),b=Ae(i=>{let c=t.current,m=c?.getRootNode();(m instanceof ShadowRoot?m.host:c?.closest("[data-heroui-agent]"))?.style.setProperty("--ha-sidebar-width",`${i}px`),window.innerWidth>=640&&(document.documentElement.style.marginRight=`${Math.min(i,window.innerWidth)}px`),o(i)},[t]);$(()=>{o(fe(e,window.innerWidth))},[e]);let w=Ae((i,c)=>{let m=ne(i,window.innerWidth);return b(m),c&&oe(e,m),m},[b,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:i=>{let c=i.key==="ArrowLeft"?24:i.key==="ArrowRight"?-24:0;c!==0&&(i.preventDefault(),w(n+c,!0))},onPointerCancel:i=>{let c=a.current;c&&(a.current=null,delete i.currentTarget.dataset.resizing,t.current&&delete t.current.dataset.dragResizing,document.documentElement.style.transition=c.pageTransition,w(c.startWidth,!1))},onPointerDown:i=>{i.button!==0&&i.pointerType==="mouse"||(i.preventDefault(),i.currentTarget.setPointerCapture(i.pointerId),i.currentTarget.dataset.resizing="true",a.current={currentWidth:n,pageTransition:document.documentElement.style.transition,startWidth:n,startX:i.clientX},document.documentElement.style.transition="none",t.current&&(t.current.dataset.dragResizing="true"))},onPointerMove:i=>{let c=a.current;c&&(c.currentWidth=w(c.startWidth+(c.startX-i.clientX),!1))},onPointerUp:i=>{let c=a.current;c&&(a.current=null,delete i.currentTarget.dataset.resizing,t.current&&delete t.current.dataset.dragResizing,i.currentTarget.releasePointerCapture(i.pointerId),document.documentElement.style.transition=c.pageTransition,oe(e,c.currentWidth))}})}function et(){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 tt(){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 ye(e,{generateConversationTitle:t=!0}={}){let n=performance.now(),o=Date.now(),a=e.trim();return a?{...t?{}:{generateConversationTitle:!1},messageId:crypto.randomUUID(),prompt:a,startedAt:n,startedAtWallClock:o,submitted:!0}:null}var P=new Map,X=new Map,nt=10080*60*1e3,Y=new Map;function ve(e){return`heroui-agent:shell-draft:${e}:composer-draft:v1`}function ae(e,t){try{let n=ve(e);t.trim()?localStorage.setItem(n,JSON.stringify({prompt:t,savedAt:Date.now()})):localStorage.removeItem(n)}catch{}}function ot(e){let t=ve(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<=nt)return n.prompt;localStorage.removeItem(t)}catch{}return""}function q(e,t){if(!t.prompt.trim()&&!t.submitted){P.delete(e),ae(e,"");return}P.set(e,t),t.submitted||ae(e,t.prompt)}function ie(e){let t=P.get(e);if(t)return t;let n=ot(e);return n?{prompt:n,submitted:!1}:void 0}function Te(e,t,n){let o=P.get(e);!o?.submitted||o.messageId!==t||o.firstFeedbackPaintedAt!==void 0||P.set(e,{...o,firstFeedbackPaintedAt:n})}function Ft(e){let t=ie(e);return P.delete(e),ae(e,""),t}function D(e,t,n){t?Y.set(e,[n?.selectionStart??0,n?.selectionEnd??0,n?.selectionDirection??"none"]):Y.delete(e)}function we(e,t){let n=Y.get(e);if(!n||!t)return;t.focus({preventScroll:!0});let o=Math.min(n[0],t.value.length),a=Math.min(n[1],t.value.length);t.setSelectionRange(o,a,n[2]),Y.set(e,[o,a,n[2]])}function xe(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 Bt(e,t){t.length===0?X.delete(e):X.set(e,t)}function rt(e){return X.get(e)??[]}function Ut(e){let t=rt(e);return X.delete(e),t}function Se(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}function at(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 it(e){let t=getComputedStyle(e);return Se(t.paddingTop)+Se(t.paddingBottom)}function st(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 a=e.scrollHeight;return e.style.height=t,e.style.minHeight=n,e.style.maxHeight=o,a}function lt(e){if(e.value.includes(`
2
2
  `))return!0;if(e.clientWidth===0)return!1;let t=st(e),n=it(e),o=at(e);return Math.max(0,t-n)>o*1.5}function se(e,{hasAttachments:t=!1,maxHeight:n=120}={}){if(!e)return!1;let o=e.value.length>0;return t||o&&lt(e)?(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,n)}px`,!0):(e.style.height="auto",!1)}import{jsx as le,jsxs as Ee}from"react/jsx-runtime";var ct="https://heroui.pro/?utm_source=heroui-agent&utm_medium=referral&utm_campaign=powered-by-hero";function Ce(){return Ee("a",{"aria-label":"Powered by HeroUI Pro (opens in a new tab)",className:"ha-powered-by",href:ct,rel:"noopener noreferrer",target:"_blank",children:[le("span",{children:"Powered by"}),Ee("svg",{"aria-hidden":"true",className:"ha-powered-by-logo",fill:"none",viewBox:"0 0 140 44",children:[le("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"}),le("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 ke=new Set(["ask","auto","full"]);function j(e){return ke.has(e)?e:"auto"}function $t(e,t){return`${e}:permission-mode:${t}:v1`}function zt(e,t){return`${e}:active-permission-mode:${t}:v1`}function Xt(e){try{let t=localStorage.getItem(e);return t!==null&&ke.has(t)?j(t):void 0}catch{return}}function Yt(e,t){try{localStorage.setItem(e,t)}catch{}}function qt(e){try{localStorage.removeItem(e)}catch{}}function jt(e,t){let n=j(t);if(n==="auto")return e;let o=n==="ask";return e.map(a=>!!a.needsApproval===o?a:{...a,needsApproval:o})}function Me(e){return`heroui-agent:anonymous:${e}`}function dt(e){return e instanceof Error?e:new Error("Auth token request failed")}var Ne=class{constructor(t,n){this.agentId=t;this.getAuthToken=n}cached=null;failure=null;generation=0;pending=null;clear(){this.generation+=1,this.cached=null,this.failure=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;if(!this.pending&&this.failure&&Date.now()<this.failure.retryAt)throw this.failure.error;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,this.failure=null,o.token)}catch(o){throw t===this.generation&&(this.failure={error:dt(o),retryAt:Date.now()+5e3}),o}finally{this.pending===n&&(this.pending=null)}}async subjectHash(){let t=await this.get(),n=ut(t),o=typeof n.sub=="string"?n.sub:"anonymous",a=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${this.agentId}:${o}`));return Array.from(new Uint8Array(a),b=>b.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 ut(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 mt={"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"},Z=Object.freeze(Object.keys(mt)),Qt=Z.join(","),pt=new Set(Z);function Re(e){return pt.has(e.trim().toLowerCase())}import{useId as gt}from"react";import{jsx as Pe,jsxs as ht}from"react/jsx-runtime";function He({children:e,className:t,...n}){let o=`ha-shimmer-${gt().replaceAll(":","")}`,a={"--_ha-firefox-mask":`-moz-element(#${o})`};return ht("span",{...n,className:`ha-shimmer${t?` ${t}`:""}`,children:[Pe("span",{className:"ha-shimmer__text",id:o,children:e}),Pe("span",{inert:!0,"aria-hidden":"true",className:"ha-shimmer__highlight",style:a,children:e})]})}import{useEffect as ft,useLayoutEffect as Oe,useRef as At,useState as J}from"react";import{Fragment as _e,jsx as l,jsxs as C}from"react/jsx-runtime";function un({agentId:e,composerConnecting:t=!1,composerControlsAvailable:n,composerControlsRevealed:o,composerEndSlot:a,composerFooterSlot:b,composerStartSlot:w,greeting:i,onComposerControlsReveal:c,onIntent:m,placeholder:k,suggestedPrompts:H}){let[f]=J(()=>ie(e)),[y,L]=J(()=>f?.submitted?"":f?.prompt??""),[p,x]=J(()=>f?.submitted?f:null),[O,_]=J(!1),M=At(null),N=n??!!(w||a),v=o??(N&&O),Q=s=>{D(e,!0,s.currentTarget),_(N),N&&c?.(),m()},F=s=>{let g=s.currentTarget.querySelector(".ha-composer");g&&xe(g,s.relatedTarget)||(_(!1),D(e,!1))};Oe(()=>{we(e,M.current),se(M.current)},[e]),ft(()=>{p||q(e,{prompt:y,submitted:!1})},[y,e,p]),Oe(()=>{if(!p)return;let s=requestAnimationFrame(g=>{Te(e,p.messageId,g)});return()=>cancelAnimationFrame(s)},[e,p]);let S=(s,g=!0)=>{if(p)return;let h=ye(s,{generateConversationTitle:g});h&&(x(h),L(""),M.current.style.height="auto",q(e,h),m())};return C(_e,{children:[l("div",{className:"ha-conversation",children:l("div",{"aria-live":"polite",className:"ha-messages",role:"log",children:p?C(_e,{children:[l("div",{className:"ha-message","data-role":"user",children:l("div",{className:"ha-bubble",children:l("div",{className:"ha-message-content",children:l("p",{className:"ha-message-text",children:p.prompt})})})}),l("div",{className:"ha-message","data-role":"assistant","data-stream-anchor":"true","data-turn-feedback-id":p.messageId,children:l("div",{className:"ha-message-body",children:l("div",{"aria-label":"Working on your request\u2026",className:"ha-progress ha-activity-status ha-progress-shimmer",role:"status",children:l(He,{"aria-hidden":"true",children:"Thinking\u2026"})})})})]}):C("div",{className:"ha-empty",children:[l("h2",{children:i}),l("p",{children:"Live answers with charts, metrics, and tables."})]})})}),C("form",{className:"ha-composer-wrap",onBlur:F,onSubmit:s=>{s.preventDefault(),S(y)},children:[!p&&H.length>0?l("div",{"aria-label":"Suggested prompts",className:"ha-suggestions",role:"group",children:H.map(s=>C("button",{className:"ha-suggestion",type:"button",onClick:()=>S(s,!1),children:[l("span",{children:s}),l(yt,{})]},s))}):null,C("div",{className:"@container ha-composer","data-connecting":t||void 0,"data-controls-revealed":v||void 0,children:[w,l("textarea",{ref:M,"aria-label":"Message the assistant",placeholder:k,readOnly:!!p,rows:1,value:y,onFocus:Q,onSelect:s=>D(e,!0,s.currentTarget),onChange:s=>{let g=s.currentTarget.value;q(e,{prompt:g,submitted:!1}),D(e,!0,s.currentTarget),L(g),se(s.currentTarget),m()},onKeyDown:s=>{s.key!=="Enter"||s.shiftKey||(s.preventDefault(),S(y))}}),a,C("button",{"aria-label":"Send message",className:"ha-send",disabled:!y.trim()||!!p,type:"submit",children:[l(bt,{}),l(V,{shortcut:"\u21B5",children:"Send message"})]})]}),l("div",{className:"ha-composer-footer","data-revealed":!!b||void 0,children:l("div",{className:"ha-composer-footer-content",children:b})}),l(Ce,{})]})]})}function bt(){return l("svg",{"aria-hidden":"true",fill:"none",height:"18",viewBox:"0 0 18 18",width:"18",children:l("path",{d:"M9 14.5V3.5m0 0L4.5 8M9 3.5 13.5 8",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.6"})})}function yt(){return l("svg",{"aria-hidden":"true",fill:"none",height:"16",viewBox:"0 0 16 16",width:"16",children:l("path",{d:"M5 11 11 5m0 0H6m5 0v5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5"})})}var vt={animation:"fadeIn",duration:160,easing:"ease-out",sep:"word",stagger:18};function Ie(e){return typeof e=="number"?Number.isFinite(e)?`${Math.round(e)}px`:void 0:e?.trim()||void 0}function Tt(e){let t=Ie(e?.initialWidth),n=Ie(e?.initialHeight);return{...t?{"--ha-panel-width":t}:{},...n?{"--ha-panel-height":n}:{}}}function De(e){return e===void 0||!Number.isFinite(e)?24:Math.min(Math.max(Math.round(e),0),200)}function wt(e){if(e===void 0)return[...Z];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();Re(o)&&t.add(o)}return[...t]}function bn(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=wt(e.composer?.attachments),n=typeof e.composer?.disclaimer=="string"&&e.composer.disclaimer.trim().slice(0,240)||void 0;return{apiBaseUrl:(e._api?.baseUrl??pe).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:de(e.appearance?.theme?.designTheme),...n?{composerDisclaimer:n}:{},agentId:e.agentId,...e.appearance?.shouldCloseOnInteractOutside!==void 0?{shouldCloseOnInteractOutside:e.appearance.shouldCloseOnInteractOutside}:{},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??vt,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:Tt(e.appearance?.panel),permissionDefaultMode:j(e.permissions?.defaultMode),permissionShowPicker:e.permissions?.showPicker===!0,preload:e.preload??!0,reopenOnRefresh:e.reopenOnRefresh??!1,showBetaBadge:e.showBetaBadge??!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:De(e.appearance.launcher.offset.x),y:De(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:{...me(e.appearance?.theme),...ue(e.appearance?.launcher?.background)},tools:e.tools??[],viewMode:e.appearance?.viewMode??"floating",webSearch:e.capabilities?.webSearch??!1}}export{Ne as a,xt as b,pe as c,Et as d,V as e,fe as f,It as g,mt as h,Z as i,Re as j,ye as k,q as l,ie as m,Ft as n,D as o,we as p,xe as q,Bt as r,rt as s,Ut as t,se as u,Ce as v,He as w,un as x,$t as y,zt as z,Xt as A,Yt as B,qt as C,jt as D,vt as E,bn as F};
@@ -1,2 +1,2 @@
1
- import{F as rn,a as qe,c as je,d as ze,f as fe,g as Ke,j as Je,k as Ze,l as en,o as me,q as nn,r as tn,x as on}from"./chunk-366EZBW3.js";import{a as Xe}from"./chunk-6ZJJN322.js";import{d as Ye,e as Qe}from"./chunk-UHHKMESI.js";import{useCallback as b,useEffect as C,useEffectEvent as yt,useLayoutEffect as kn,useMemo as Ce,useRef as E,useState as p,useSyncExternalStore as Tn}from"react";import{createRoot as wt}from"react-dom/client";import{SparklesFill as Jn}from"@gravity-ui/icons";import{jsx as Xn}from"react/jsx-runtime";function sn(e){return Xn(Jn,{...e})}import{jsx as pe}from"react/jsx-runtime";function Yn(e){return/\.svg(?:[?#]|$)/i.test(e)||/^data:image\/svg\+xml[;,]/i.test(e)}function an(e){return`url("${e.replace(/["\\\n\r]/g,encodeURIComponent)}")`}function cn({icon:e}){return e?Yn(e)?pe("span",{"aria-hidden":"true",className:"ha-launcher__icon ha-launcher__icon--tinted",style:{WebkitMaskImage:an(e),maskImage:an(e)}}):pe("img",{alt:"",className:"ha-launcher__icon",src:e}):pe(sn,{})}function ln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function un(e,n){if(n===void 0)return e;if(!ln(e)||!ln(n))return n;let t={...e};for(let[r,a]of Object.entries(n))a!==void 0&&(t[r]=r in e?un(e[r],a):a);return t}function dn(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,showBetaBadge:e.showBetaBadge,startScreen:e.startScreen},r=un(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,showBetaBadge:n.showBetaBadge,startScreen:n.startScreen});return{...n,...r}}function fn(e){return!!e.appearance?.theme?.typography?.fontFamily?.trim()}var mn=1,c=Symbol("invalid");function G(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function k(e){if(e!==void 0)return typeof e=="string"?e:c}function S(e){if(e!==void 0)return typeof e=="boolean"?e:c}function ge(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 pn(e){if(e===void 0)return;if(typeof e=="string")return e;if(!G(e))return c;let n=k(e.dark),t=k(e.light);return n===c||t===c?c:{...n===void 0?{}:{dark:n},...t===void 0?{}:{light:t}}}function Qn(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 Zn(e){if(e!==void 0)return!Array.isArray(e)||e.some(n=>typeof n!="string")?c:e}function w(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 v(e){return e===c?void 0:e}var et=["accent","background","foreground","overlay","surface","surfaceSecondary","tooltip"];function nt(e){return w(e,{launcher:n=>n===void 0?void 0:w(n,{background:pn,icon:k,position:M(["bottom-left","bottom-right"]),style:Qn}),panel:n=>n===void 0?void 0:w(n,{expandable:S,expanded:S,initialHeight:t=>t===void 0||typeof t=="string"?t:ge(t),initialWidth:t=>t===void 0||typeof t=="string"?t:ge(t)}),theme:n=>n===void 0?void 0:w(n,{colorScheme:M(["dark","light","system"]),colors:t=>t===void 0?void 0:w(t,Object.fromEntries(et.map(r=>[r,pn]))),designTheme:M(["base","brutalism","glass","mouve"]),radius:M(["pill","round","sharp","soft"]),typography:t=>t===void 0?void 0:w(t,{baseSize:ge,fontFamily:k})}),viewMode:M(["floating","sidebar"])})}function tt(e){return w(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"&&Je(r));return t.length===n.length?t:c},defaultModel:k,dictation:S,disclaimer:n=>n===!1?!1:k(n),modelPicker:S,placeholder:k})}function ot(e){return w(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 rt(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!==mn)return null;let n=e.revision;if(typeof n!="string"||!n)return null;let t=v(nt(e.appearance)),r=v(w(e.capabilities,{imageSearch:S,newsSearch:S,webSearch:S})),a=v(tt(e.composer)),l=v(ot(e.markdown)),f=v(w(e.permissions,{defaultMode:M(["ask","auto","full"]),showPicker:S})),u=v(rt(e.responseActions)),m=v(S(e.showBetaBadge)),I=v(w(e.startScreen,{greeting:k,promptShortcuts:S,prompts:Zn})),h=v(w(e.webfont,{familyName:N=>typeof N=="string"&&N?N:c,fontFaceUrl:k,stylesheetUrl:k}));return{...t?{appearance:t}:{},...r?{capabilities:r}:{},...a?{composer:a}:{},...l?{markdown:l}:{},...f?{permissions:f}:{},...u===void 0?{}:{responseActions:u},...m===void 0?{}:{showBetaBadge:m},...I?{startScreen:I}:{},...h?{webfont:h}:{},revision:n,version:mn}}function he(e){return`heroui-agent:config:${e}`}var gn=1;function hn(e){try{let n=window.localStorage.getItem(he(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===gn&&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 ye(e,n,t=Date.now()){try{let r={cacheVersion:gn,cachedAt:t,config:n};window.localStorage.setItem(he(e),JSON.stringify(r))}catch{}}function yn(e){try{window.localStorage.removeItem(he(e))}catch{}}async function wn(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 st,Microphone as it,Plus as at,ShieldCheck as ct}from"@gravity-ui/icons";import{useEffect as lt,useRef as ut}from"react";import{Fragment as Rn,jsx as g,jsxs as we}from"react/jsx-runtime";var dt={ask:"Ask for approval",auto:"Approve for me",full:"Full access"};function Cn({onFileDialogActiveChange:e,onIntent:n,options:t}){return{end:g(mt,{options:t}),footer:t.composerDisclaimer?g("p",{className:"ha-footnote",children:Xe(t.composerDisclaimer)}):null,start:t.composerAttachmentContentTypes.length>0?g(ft,{accept:t.composerAttachmentAccept,agentId:t.agentId,onFileDialogActiveChange:e,onIntent:n}):null}}function ft({accept:e,agentId:n,onFileDialogActiveChange:t,onIntent:r}){let a=ut(null);return lt(()=>{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]),we(Rn,{children:[g("input",{ref:a,multiple:!0,accept:e,"aria-label":"Choose files to attach",className:"ha-file-input",type:"file",onChange:l=>{tn(n,Array.from(l.currentTarget.files??[])),l.currentTarget.value="",t(!1),r()}}),g("button",{"aria-label":"Attach files",className:"ha-attach",type:"button",onClick:()=>{t(!0),a.current?.click()},children:g(at,{"aria-hidden":"true"})})]})}function mt({options:e}){let n=e.composerDefaultModel??Ye,t=Qe.find(r=>r.id===n)?.label??n;return we(Rn,{children:[e.permissionShowPicker&&e.tools.length>0?g(bn,{icon:g(ct,{"aria-hidden":"true",className:"aui-permission-picker__trigger-icon"}),kind:"permission",label:dt[e.permissionDefaultMode],tone:e.permissionDefaultMode==="full"?"warning":void 0}):null,e.composerModelPicker?g(bn,{kind:"model",label:t}):null,e.composerDictation?g("button",{disabled:!0,"aria-label":"Dictate message",className:"ha-dictation",type:"button",children:g(it,{"aria-hidden":"true"})}):null]})}function bn({icon:e,kind:n,label:t,tone:r}){let a=`aui-${n}-picker`;return g("div",{className:`${a} ha-${n}-picker`,"data-tone":r,children:we("button",{disabled:!0,"aria-label":n==="model"?"AI model":"Tool permissions",className:`${a}__trigger ha-shell-picker-trigger`,type:"button",children:[e,g("span",{className:`${a}__value`,children:t}),g(st,{"aria-hidden":"true",className:`${a}__indicator`})]})})}var pt=[".woff2",".woff",".ttf",".otf",".eot"];function gt(e){return`heroui-agent-font-${e.familyName.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`}function ht(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 An(e,n){try{let t=new URL(e);if(t.protocol!=="https:")return!1;if(!n)return!0;let r=t.pathname.toLowerCase();return pt.some(a=>r.endsWith(a))}catch{return!1}}function Sn(e){if(!e||typeof document>"u")return()=>{};let n=gt(e);if(document.getElementById(n))return()=>{};if(e.stylesheetUrl&&An(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&&An(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('${ht(e.fontFaceUrl)}');`,"}"].join(`
2
- `),document.head.append(t),()=>t.remove()}return()=>{}}import{Fragment as On,jsx as P,jsxs as Nn}from"react/jsx-runtime";var bt=600,Ct=5*6e4,Rt="heroui-agent:open:";function Re(e){return`${Rt}${e}`}function At(e){if(typeof window>"u")return!1;try{return window.sessionStorage.getItem(Re(e))==="true"}catch{return!1}}function be(e,n){try{n?window.sessionStorage.setItem(Re(e),"true"):window.sessionStorage.removeItem(Re(e))}catch{}}var In;function vn(){return In??=import(/* webpackPrefetch: true */"./embed-runtime-C4BZ5BCN.js").then(e=>e.default),In}var D=new Map,Ae=new Set;function Mn(e){return e?D.get(e):[...D.values()][D.size-1]}function En(){for(let e of Ae)e()}function St(e){return Ae.add(e),()=>Ae.delete(e)}function kt(e){let n=window.matchMedia?.("(prefers-color-scheme: dark)");return n?.addEventListener?.("change",e),()=>n?.removeEventListener?.("change",e)}function It(){return window.matchMedia?.("(prefers-color-scheme: dark)").matches===!0}function x(e,n,...t){let r=Mn(e);if(!r){console.warn("HeroUI Agent is not mounted yet. Add <HeroUIAgent /> to your layout.");return}let a=r[n];a(...t)}function vt(e,n,t){let[r]=p(()=>!t||typeof window>"u"?null:hn(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<=Ct;return{config:u?r.config:null,presentationReady:u}});return C(()=>{if(!t)return;let f=new AbortController,u=!0,m=h=>{l(N=>N.presentationReady?N:{config:h,presentationReady:!0})},I=window.setTimeout(()=>{u&&(f.abort(),m(r?.config??null))},bt);return wn(n,e,{...r?.config.revision?{revision:r.config.revision}:{},signal:f.signal}).then(h=>{if(!(!u||f.signal.aborted)){if(h.status==="ok"){ye(e,h.config),m(h.config);return}if(h.status==="not-modified"){r&&ye(e,r.config),m(r?.config??null);return}if(h.status==="missing"){yn(e),m(null);return}m(r?.config??null)}}).finally(()=>{!u||f.signal.aborted||window.clearTimeout(I)}),()=>{u=!1,f.abort(),window.clearTimeout(I)}},[n,r,t,e]),t?a:{config:null,presentationReady:!0}}function co(e){let n=b(()=>Mn(e)?.ready??!1,[e]),t=Tn(St,n,()=>!1);return Ce(()=>({hide:()=>x(e,"hide"),newConversation:r=>x(e,"newConversation",r),preload:()=>x(e,"preload"),ready:t,refreshAuth:()=>x(e,"refreshAuth"),show:()=>x(e,"show"),shutdown:()=>x(e,"shutdown"),toggle:()=>x(e,"toggle")}),[e,t])}function lo(e){let n=`${e.agentId}\0${e._api?.baseUrl??""}\0${e.remoteConfig!==!1}`;return P(Et,{...e},n)}function Et(e){let{_api:n,agentId:t,appearance:r,capabilities:a,componentExports:l,composer:f,context:u,getAuthToken:m,markdown:I,onFeedback:h,onReady:N,permissions:Pn,preload:_n,remoteConfig:Un=!0,reopenOnRefresh:Se,responseActions:Ln,showLauncher:xn,startNewConversationOnOpen:Fn,startScreen:$n,tools:ke}=e,q=I?.plugins,ee=r?.shouldCloseOnInteractOutside,Hn=(n?.baseUrl??je).replace(/\/$/,""),{config:Ie,presentationReady:F}=vt(t,Hn,Un),ve=JSON.stringify({_api:n,appearance:r?{...r,shouldCloseOnInteractOutside:void 0}:void 0,capabilities:a,componentExports:l,composer:f,markdown:I?{...I,plugins:void 0}:void 0,permissions:Pn,preload:_n,remote:Ie,reopenOnRefresh:Se,responseActions:Ln,showLauncher:xn,startNewConversationOnOpen:Fn,startScreen:$n}),o=Ce(()=>{let{remote:s,...i}=JSON.parse(ve),d=dn(s,{...i,agentId:t,getAuthToken:m,...ee!==void 0?{appearance:{...i.appearance,shouldCloseOnInteractOutside:ee}}:{}});return rn({...d,context:u,markdown:d.markdown?{...d.markdown,plugins:q}:q?{plugins:q}:void 0,onFeedback:h,tools:ke})},[u,m,q,h,t,ve,ee,ke]),j=Ce(()=>new qe(t,m),[t,m]),Ee=fn(e),Ne=Ie?.webfont;C(()=>{if(!Ee)return Sn(Ne)},[Ee,Ne]);let[z]=p(()=>Se===!0&&At(t)),[ne,V]=p(z),[_,Bn]=p(1),[Oe,Te]=p(1),[Me,Pe]=p(!1),[K,Dn]=p(z||o.startNewConversationOnOpen?null:void 0),[O,Vn]=p(null),[J,Wn]=p(null),[_e,Gn]=p(!1),[te,oe]=p(!1),[qn,Ue]=p(null),re=E(1),Le=E(null),se=E(!1),ie=E(null),xe=E(null),$=E(z),ae=E(null),X=E(null),ce=E([]),jn=Tn(kt,It,()=>!1),le=o.designTheme==="base"?null:`${o.designTheme}-${o.colorScheme==="system"?jn?"dark":"light":o.colorScheme}`,U=F&&qn===_&&J!==null,y=F&&ne,[Y,zn]=p(z||o.preload),R=b(()=>zn(!0),[]),[W,H]=p(!1),[Fe,$e]=p(!1),ue=b(()=>H(!0),[]);C(()=>{if(!W||!O)return;let s=()=>{queueMicrotask(()=>{let i=O.querySelector(".ha-composer:not([hidden] *)");i&&nn(i,document.activeElement)||H(!1)})};return O.addEventListener("focusout",s),()=>O.removeEventListener("focusout",s)},[W,O]),C(()=>{Y&&j.get().catch(()=>{})},[Y,j]),C(()=>{o.reopenOnRefresh?be(o.agentId,ne):be(o.agentId,!1)},[ne,o.agentId,o.reopenOnRefresh]),C(()=>{if(!Y)return;if(!F){vn().catch(()=>{});return}let s=!0;return vn().then(i=>{s&&Wn(()=>i)}).catch(()=>{}),()=>{s=!1}},[F,Y]),C(()=>{if(!y||o.viewMode!=="sidebar"||window.innerWidth<640)return;let s=document.documentElement,i=s.style.marginRight,d=s.style.transition,A=window.matchMedia("(prefers-reduced-motion: reduce)").matches,de=Math.min(fe(o.agentId,window.innerWidth),window.innerWidth);return A||(s.style.transition=[d,"margin-right .28s cubic-bezier(.2,.8,.2,1)"].filter(Boolean).join(", ")),s.style.marginRight=`${de}px`,()=>{s.style.marginRight=i,window.setTimeout(()=>{s.style.transition=d},300)}},[y,o.agentId,o.viewMode]),C(()=>{let s=document.createElement("div"),i=document.createElement("div");s.dataset.herouiAgent=o.agentId,i.className="ha-root",ae.current=s,ie.current=i,X.current=wt(i),s.append(i),document.body.append(s);let d=!0;return queueMicrotask(()=>{d&&Vn(i)}),()=>{d=!1,me(o.agentId,!1);let A=X.current;ie.current=null,ae.current=null,X.current=null,ce.current=[],queueMicrotask(()=>{A?.unmount(),s.remove()})}},[o.agentId]),kn(()=>{let s=ie.current,i=ae.current;if(!s||!i)return;s.className=le?`ha-root ${le}`:"ha-root",s.dataset.theme=o.colorScheme,s.dataset.viewMode=o.viewMode,s.dataset.position=o.launcherPosition,i.dataset.open=y?"true":"false",i.dataset.viewMode=o.viewMode,i.dataset.position=o.launcherPosition,o.launcherOffset?(i.style.setProperty("--ha-launcher-x",`${o.launcherOffset.x}px`),i.style.setProperty("--ha-launcher-y",`${o.launcherOffset.y}px`)):(i.style.removeProperty("--ha-launcher-x"),i.style.removeProperty("--ha-launcher-y")),o.viewMode==="sidebar"&&i.style.setProperty("--ha-sidebar-width",`${fe(o.agentId,window.innerWidth)}px`);let d={...o.themeStyle,...o.panelStyle};for(let A of ce.current)A in d||s.style.removeProperty(A);for(let[A,de]of Object.entries(d))s.style.setProperty(A,de);ce.current=Object.keys(d)},[le,y,o.colorScheme,o.agentId,o.launcherOffset,o.launcherPosition,o.panelStyle,o.themeStyle,o.viewMode,O]);let T=b(s=>{me(o.agentId,!1),$e(!1),Ue(null),Dn(s);let i=re.current+1;re.current=i,Bn(i)},[o.agentId]),He=b(s=>{re.current===s&&(Gn(!0),Ue(s))},[]),Kn=yt(()=>N?.());C(()=>{!U||xe.current===_||(xe.current=_,Kn())},[_,U]);let L=b(()=>{$.current=!1,se.current=!0,V(!1),H(!1),T(o.startNewConversationOnOpen?null:void 0)},[o.startNewConversationOnOpen,T]);C(()=>{y||!U||!se.current||(se.current=!1,requestAnimationFrame(()=>Le.current?.focus()))},[y,U]);let B=b(()=>{$.current=!0,V(!0),R()},[R]),Be=R,Q=b(s=>{let i=s?Ze(s):null;i&&en(o.agentId,i),$.current=!0,V(!0),H(!1),R(),T(null)},[o.agentId,T,R]),De=b(s=>{$.current=!0,V(!0),H(!1),R(),T(s)},[T,R]),Ve=b(()=>{y||$.current?L():B()},[L,y,B]),We=b(()=>{oe(!1),Pe(!1),Te(s=>s+1)},[]),Ge=b(()=>{let s=[`heroui-agent:anonymous:${o.agentId}`,`heroui-agent:conversation:${o.agentId}:`,`heroui-agent:history:${o.agentId}:`];for(let i=localStorage.length-1;i>=0;i-=1){let d=localStorage.key(i);d&&s.some(A=>d.startsWith(A))&&localStorage.removeItem(d)}$.current=!1,oe(!1),V(!1),H(!1),be(o.agentId,!1),Pe(!0),Te(i=>i+1),T(),window.setTimeout(()=>{import("./composer-draft-NSKK65F3.js").then(({clearAgentComposerDraftsForProject:i})=>i(o.agentId)).catch(()=>{})},0)},[o.agentId,T]);return C(()=>{let s={hide:L,newConversation:Q,preload:Be,ready:U,refreshAuth:We,show:B,shutdown:Ge,toggle:Ve};return D.set(o.agentId,s),En(),()=>{D.get(o.agentId)===s&&(D.delete(o.agentId),En())}},[L,Q,o.agentId,Be,U,We,B,Ge,Ve]),kn(()=>{let s=X.current;if(!O||!s)return;let i=Cn({onFileDialogActiveChange:$e,onIntent:R,options:o});s.render(Nn(On,{children:[F&&o.showLauncher&&!y?Nn("button",{ref:Le,"aria-expanded":!1,"aria-haspopup":"dialog",className:"ha-launcher",style:o.launcherStyle,type:"button","aria-label":te?"Open data assistant, unread messages":"Open data assistant",onClick:B,children:[P(cn,{icon:o.launcherIcon}),te?P("span",{"aria-hidden":"true",className:"ha-launcher__unread"}):null]}):null,J&&!Fe?P(J,{composerControlsRevealed:W,conversationEpoch:_,identityEpoch:Oe,identityReset:Me,open:y,options:o,requestedConversationId:K,shellComposerEndSlot:i.end,shellComposerFooterSlot:i.footer,showReadyLoader:!_e&&K!==null,tokenManager:j,onClose:L,onComposerControlsReveal:ue,onNewConversation:Q,onReady:He,onSelectConversation:De,onUnreadChange:oe}):P(Ke,{agentId:o.agentId,shouldCloseOnInteractOutside:o.shouldCloseOnInteractOutside,defaultExpanded:o.panelExpanded,expandable:o.panelExpandable,historySlot:P(On,{}),name:"Data assistant",open:y,showBetaBadge:o.showBetaBadge,viewMode:o.viewMode,onClose:L,children:K===null?P(on,{composerConnecting:!0,agentId:o.agentId,composerControlsAvailable:o.composerControlsAvailable,composerControlsRevealed:W,composerEndSlot:i.end,composerFooterSlot:i.footer,composerStartSlot:i.start,greeting:o.greeting,placeholder:o.composerPlaceholder,suggestedPrompts:o.suggestedPrompts??[],onComposerControlsReveal:ue,onIntent:R},`shell-${_}`):P(ze,{})})]}))},[J,W,Fe,_,He,te,_e,L,Oe,Me,y,Q,o,O,U,F,K,R,ue,De,B,j]),null}export{co as a,lo as b};
1
+ import{F as rn,a as qe,c as je,d as ze,f as fe,g as Ke,j as Je,k as Ze,l as en,o as me,q as nn,r as tn,x as on}from"./chunk-EJIPFUZ2.js";import{a as Xe}from"./chunk-6ZJJN322.js";import{d as Ye,e as Qe}from"./chunk-UHHKMESI.js";import{useCallback as b,useEffect as C,useEffectEvent as yt,useLayoutEffect as kn,useMemo as Ce,useRef as E,useState as p,useSyncExternalStore as Tn}from"react";import{createRoot as wt}from"react-dom/client";import{SparklesFill as Jn}from"@gravity-ui/icons";import{jsx as Xn}from"react/jsx-runtime";function sn(e){return Xn(Jn,{...e})}import{jsx as pe}from"react/jsx-runtime";function Yn(e){return/\.svg(?:[?#]|$)/i.test(e)||/^data:image\/svg\+xml[;,]/i.test(e)}function an(e){return`url("${e.replace(/["\\\n\r]/g,encodeURIComponent)}")`}function cn({icon:e}){return e?Yn(e)?pe("span",{"aria-hidden":"true",className:"ha-launcher__icon ha-launcher__icon--tinted",style:{WebkitMaskImage:an(e),maskImage:an(e)}}):pe("img",{alt:"",className:"ha-launcher__icon",src:e}):pe(sn,{})}function ln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function un(e,n){if(n===void 0)return e;if(!ln(e)||!ln(n))return n;let t={...e};for(let[r,a]of Object.entries(n))a!==void 0&&(t[r]=r in e?un(e[r],a):a);return t}function dn(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,showBetaBadge:e.showBetaBadge,startScreen:e.startScreen},r=un(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,showBetaBadge:n.showBetaBadge,startScreen:n.startScreen});return{...n,...r}}function fn(e){return!!e.appearance?.theme?.typography?.fontFamily?.trim()}var mn=1,c=Symbol("invalid");function G(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function k(e){if(e!==void 0)return typeof e=="string"?e:c}function S(e){if(e!==void 0)return typeof e=="boolean"?e:c}function ge(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 pn(e){if(e===void 0)return;if(typeof e=="string")return e;if(!G(e))return c;let n=k(e.dark),t=k(e.light);return n===c||t===c?c:{...n===void 0?{}:{dark:n},...t===void 0?{}:{light:t}}}function Qn(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 Zn(e){if(e!==void 0)return!Array.isArray(e)||e.some(n=>typeof n!="string")?c:e}function w(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 v(e){return e===c?void 0:e}var et=["accent","background","foreground","overlay","surface","surfaceSecondary","tooltip"];function nt(e){return w(e,{launcher:n=>n===void 0?void 0:w(n,{background:pn,icon:k,position:M(["bottom-left","bottom-right"]),style:Qn}),panel:n=>n===void 0?void 0:w(n,{expandable:S,expanded:S,initialHeight:t=>t===void 0||typeof t=="string"?t:ge(t),initialWidth:t=>t===void 0||typeof t=="string"?t:ge(t)}),theme:n=>n===void 0?void 0:w(n,{colorScheme:M(["dark","light","system"]),colors:t=>t===void 0?void 0:w(t,Object.fromEntries(et.map(r=>[r,pn]))),designTheme:M(["base","brutalism","glass","mouve"]),radius:M(["pill","round","sharp","soft"]),typography:t=>t===void 0?void 0:w(t,{baseSize:ge,fontFamily:k})}),viewMode:M(["floating","sidebar"])})}function tt(e){return w(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"&&Je(r));return t.length===n.length?t:c},defaultModel:k,dictation:S,disclaimer:n=>n===!1?!1:k(n),modelPicker:S,placeholder:k})}function ot(e){return w(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 rt(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!==mn)return null;let n=e.revision;if(typeof n!="string"||!n)return null;let t=v(nt(e.appearance)),r=v(w(e.capabilities,{imageSearch:S,newsSearch:S,webSearch:S})),a=v(tt(e.composer)),l=v(ot(e.markdown)),f=v(w(e.permissions,{defaultMode:M(["ask","auto","full"]),showPicker:S})),u=v(rt(e.responseActions)),m=v(S(e.showBetaBadge)),I=v(w(e.startScreen,{greeting:k,promptShortcuts:S,prompts:Zn})),h=v(w(e.webfont,{familyName:N=>typeof N=="string"&&N?N:c,fontFaceUrl:k,stylesheetUrl:k}));return{...t?{appearance:t}:{},...r?{capabilities:r}:{},...a?{composer:a}:{},...l?{markdown:l}:{},...f?{permissions:f}:{},...u===void 0?{}:{responseActions:u},...m===void 0?{}:{showBetaBadge:m},...I?{startScreen:I}:{},...h?{webfont:h}:{},revision:n,version:mn}}function he(e){return`heroui-agent:config:${e}`}var gn=1;function hn(e){try{let n=window.localStorage.getItem(he(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===gn&&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 ye(e,n,t=Date.now()){try{let r={cacheVersion:gn,cachedAt:t,config:n};window.localStorage.setItem(he(e),JSON.stringify(r))}catch{}}function yn(e){try{window.localStorage.removeItem(he(e))}catch{}}async function wn(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 st,Microphone as it,Plus as at,ShieldCheck as ct}from"@gravity-ui/icons";import{useEffect as lt,useRef as ut}from"react";import{Fragment as Rn,jsx as g,jsxs as we}from"react/jsx-runtime";var dt={ask:"Ask for approval",auto:"Approve for me",full:"Full access"};function Cn({onFileDialogActiveChange:e,onIntent:n,options:t}){return{end:g(mt,{options:t}),footer:t.composerDisclaimer?g("p",{className:"ha-footnote",children:Xe(t.composerDisclaimer)}):null,start:t.composerAttachmentContentTypes.length>0?g(ft,{accept:t.composerAttachmentAccept,agentId:t.agentId,onFileDialogActiveChange:e,onIntent:n}):null}}function ft({accept:e,agentId:n,onFileDialogActiveChange:t,onIntent:r}){let a=ut(null);return lt(()=>{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]),we(Rn,{children:[g("input",{ref:a,multiple:!0,accept:e,"aria-label":"Choose files to attach",className:"ha-file-input",type:"file",onChange:l=>{tn(n,Array.from(l.currentTarget.files??[])),l.currentTarget.value="",t(!1),r()}}),g("button",{"aria-label":"Attach files",className:"ha-attach",type:"button",onClick:()=>{t(!0),a.current?.click()},children:g(at,{"aria-hidden":"true"})})]})}function mt({options:e}){let n=e.composerDefaultModel??Ye,t=Qe.find(r=>r.id===n)?.label??n;return we(Rn,{children:[e.permissionShowPicker&&e.tools.length>0?g(bn,{icon:g(ct,{"aria-hidden":"true",className:"aui-permission-picker__trigger-icon"}),kind:"permission",label:dt[e.permissionDefaultMode],tone:e.permissionDefaultMode==="full"?"warning":void 0}):null,e.composerModelPicker?g(bn,{kind:"model",label:t}):null,e.composerDictation?g("button",{disabled:!0,"aria-label":"Dictate message",className:"ha-dictation",type:"button",children:g(it,{"aria-hidden":"true"})}):null]})}function bn({icon:e,kind:n,label:t,tone:r}){let a=`aui-${n}-picker`;return g("div",{className:`${a} ha-${n}-picker`,"data-tone":r,children:we("button",{disabled:!0,"aria-label":n==="model"?"AI model":"Tool permissions",className:`${a}__trigger ha-shell-picker-trigger`,type:"button",children:[e,g("span",{className:`${a}__value`,children:t}),g(st,{"aria-hidden":"true",className:`${a}__indicator`})]})})}var pt=[".woff2",".woff",".ttf",".otf",".eot"];function gt(e){return`heroui-agent-font-${e.familyName.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`}function ht(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 An(e,n){try{let t=new URL(e);if(t.protocol!=="https:")return!1;if(!n)return!0;let r=t.pathname.toLowerCase();return pt.some(a=>r.endsWith(a))}catch{return!1}}function Sn(e){if(!e||typeof document>"u")return()=>{};let n=gt(e);if(document.getElementById(n))return()=>{};if(e.stylesheetUrl&&An(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&&An(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('${ht(e.fontFaceUrl)}');`,"}"].join(`
2
+ `),document.head.append(t),()=>t.remove()}return()=>{}}import{Fragment as On,jsx as P,jsxs as Nn}from"react/jsx-runtime";var bt=600,Ct=5*6e4,Rt="heroui-agent:open:";function Re(e){return`${Rt}${e}`}function At(e){if(typeof window>"u")return!1;try{return window.sessionStorage.getItem(Re(e))==="true"}catch{return!1}}function be(e,n){try{n?window.sessionStorage.setItem(Re(e),"true"):window.sessionStorage.removeItem(Re(e))}catch{}}var In;function vn(){return In??=import(/* webpackPrefetch: true */"./embed-runtime-C3OD4K6Y.js").then(e=>e.default),In}var D=new Map,Ae=new Set;function Mn(e){return e?D.get(e):[...D.values()][D.size-1]}function En(){for(let e of Ae)e()}function St(e){return Ae.add(e),()=>Ae.delete(e)}function kt(e){let n=window.matchMedia?.("(prefers-color-scheme: dark)");return n?.addEventListener?.("change",e),()=>n?.removeEventListener?.("change",e)}function It(){return window.matchMedia?.("(prefers-color-scheme: dark)").matches===!0}function x(e,n,...t){let r=Mn(e);if(!r){console.warn("HeroUI Agent is not mounted yet. Add <HeroUIAgent /> to your layout.");return}let a=r[n];a(...t)}function vt(e,n,t){let[r]=p(()=>!t||typeof window>"u"?null:hn(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<=Ct;return{config:u?r.config:null,presentationReady:u}});return C(()=>{if(!t)return;let f=new AbortController,u=!0,m=h=>{l(N=>N.presentationReady?N:{config:h,presentationReady:!0})},I=window.setTimeout(()=>{u&&(f.abort(),m(r?.config??null))},bt);return wn(n,e,{...r?.config.revision?{revision:r.config.revision}:{},signal:f.signal}).then(h=>{if(!(!u||f.signal.aborted)){if(h.status==="ok"){ye(e,h.config),m(h.config);return}if(h.status==="not-modified"){r&&ye(e,r.config),m(r?.config??null);return}if(h.status==="missing"){yn(e),m(null);return}m(r?.config??null)}}).finally(()=>{!u||f.signal.aborted||window.clearTimeout(I)}),()=>{u=!1,f.abort(),window.clearTimeout(I)}},[n,r,t,e]),t?a:{config:null,presentationReady:!0}}function co(e){let n=b(()=>Mn(e)?.ready??!1,[e]),t=Tn(St,n,()=>!1);return Ce(()=>({hide:()=>x(e,"hide"),newConversation:r=>x(e,"newConversation",r),preload:()=>x(e,"preload"),ready:t,refreshAuth:()=>x(e,"refreshAuth"),show:()=>x(e,"show"),shutdown:()=>x(e,"shutdown"),toggle:()=>x(e,"toggle")}),[e,t])}function lo(e){let n=`${e.agentId}\0${e._api?.baseUrl??""}\0${e.remoteConfig!==!1}`;return P(Et,{...e},n)}function Et(e){let{_api:n,agentId:t,appearance:r,capabilities:a,componentExports:l,composer:f,context:u,getAuthToken:m,markdown:I,onFeedback:h,onReady:N,permissions:Pn,preload:_n,remoteConfig:Un=!0,reopenOnRefresh:Se,responseActions:Ln,showLauncher:xn,startNewConversationOnOpen:Fn,startScreen:$n,tools:ke}=e,q=I?.plugins,ee=r?.shouldCloseOnInteractOutside,Hn=(n?.baseUrl??je).replace(/\/$/,""),{config:Ie,presentationReady:F}=vt(t,Hn,Un),ve=JSON.stringify({_api:n,appearance:r?{...r,shouldCloseOnInteractOutside:void 0}:void 0,capabilities:a,componentExports:l,composer:f,markdown:I?{...I,plugins:void 0}:void 0,permissions:Pn,preload:_n,remote:Ie,reopenOnRefresh:Se,responseActions:Ln,showLauncher:xn,startNewConversationOnOpen:Fn,startScreen:$n}),o=Ce(()=>{let{remote:s,...i}=JSON.parse(ve),d=dn(s,{...i,agentId:t,getAuthToken:m,...ee!==void 0?{appearance:{...i.appearance,shouldCloseOnInteractOutside:ee}}:{}});return rn({...d,context:u,markdown:d.markdown?{...d.markdown,plugins:q}:q?{plugins:q}:void 0,onFeedback:h,tools:ke})},[u,m,q,h,t,ve,ee,ke]),j=Ce(()=>new qe(t,m),[t,m]),Ee=fn(e),Ne=Ie?.webfont;C(()=>{if(!Ee)return Sn(Ne)},[Ee,Ne]);let[z]=p(()=>Se===!0&&At(t)),[ne,V]=p(z),[_,Bn]=p(1),[Oe,Te]=p(1),[Me,Pe]=p(!1),[K,Dn]=p(z||o.startNewConversationOnOpen?null:void 0),[O,Vn]=p(null),[J,Wn]=p(null),[_e,Gn]=p(!1),[te,oe]=p(!1),[qn,Ue]=p(null),re=E(1),Le=E(null),se=E(!1),ie=E(null),xe=E(null),$=E(z),ae=E(null),X=E(null),ce=E([]),jn=Tn(kt,It,()=>!1),le=o.designTheme==="base"?null:`${o.designTheme}-${o.colorScheme==="system"?jn?"dark":"light":o.colorScheme}`,U=F&&qn===_&&J!==null,y=F&&ne,[Y,zn]=p(z||o.preload),R=b(()=>zn(!0),[]),[W,H]=p(!1),[Fe,$e]=p(!1),ue=b(()=>H(!0),[]);C(()=>{if(!W||!O)return;let s=()=>{queueMicrotask(()=>{let i=O.querySelector(".ha-composer:not([hidden] *)");i&&nn(i,document.activeElement)||H(!1)})};return O.addEventListener("focusout",s),()=>O.removeEventListener("focusout",s)},[W,O]),C(()=>{Y&&j.get().catch(()=>{})},[Y,j]),C(()=>{o.reopenOnRefresh?be(o.agentId,ne):be(o.agentId,!1)},[ne,o.agentId,o.reopenOnRefresh]),C(()=>{if(!Y)return;if(!F){vn().catch(()=>{});return}let s=!0;return vn().then(i=>{s&&Wn(()=>i)}).catch(()=>{}),()=>{s=!1}},[F,Y]),C(()=>{if(!y||o.viewMode!=="sidebar"||window.innerWidth<640)return;let s=document.documentElement,i=s.style.marginRight,d=s.style.transition,A=window.matchMedia("(prefers-reduced-motion: reduce)").matches,de=Math.min(fe(o.agentId,window.innerWidth),window.innerWidth);return A||(s.style.transition=[d,"margin-right .28s cubic-bezier(.2,.8,.2,1)"].filter(Boolean).join(", ")),s.style.marginRight=`${de}px`,()=>{s.style.marginRight=i,window.setTimeout(()=>{s.style.transition=d},300)}},[y,o.agentId,o.viewMode]),C(()=>{let s=document.createElement("div"),i=document.createElement("div");s.dataset.herouiAgent=o.agentId,i.className="ha-root",ae.current=s,ie.current=i,X.current=wt(i),s.append(i),document.body.append(s);let d=!0;return queueMicrotask(()=>{d&&Vn(i)}),()=>{d=!1,me(o.agentId,!1);let A=X.current;ie.current=null,ae.current=null,X.current=null,ce.current=[],queueMicrotask(()=>{A?.unmount(),s.remove()})}},[o.agentId]),kn(()=>{let s=ie.current,i=ae.current;if(!s||!i)return;s.className=le?`ha-root ${le}`:"ha-root",s.dataset.theme=o.colorScheme,s.dataset.viewMode=o.viewMode,s.dataset.position=o.launcherPosition,i.dataset.open=y?"true":"false",i.dataset.viewMode=o.viewMode,i.dataset.position=o.launcherPosition,o.launcherOffset?(i.style.setProperty("--ha-launcher-x",`${o.launcherOffset.x}px`),i.style.setProperty("--ha-launcher-y",`${o.launcherOffset.y}px`)):(i.style.removeProperty("--ha-launcher-x"),i.style.removeProperty("--ha-launcher-y")),o.viewMode==="sidebar"&&i.style.setProperty("--ha-sidebar-width",`${fe(o.agentId,window.innerWidth)}px`);let d={...o.themeStyle,...o.panelStyle};for(let A of ce.current)A in d||s.style.removeProperty(A);for(let[A,de]of Object.entries(d))s.style.setProperty(A,de);ce.current=Object.keys(d)},[le,y,o.colorScheme,o.agentId,o.launcherOffset,o.launcherPosition,o.panelStyle,o.themeStyle,o.viewMode,O]);let T=b(s=>{me(o.agentId,!1),$e(!1),Ue(null),Dn(s);let i=re.current+1;re.current=i,Bn(i)},[o.agentId]),He=b(s=>{re.current===s&&(Gn(!0),Ue(s))},[]),Kn=yt(()=>N?.());C(()=>{!U||xe.current===_||(xe.current=_,Kn())},[_,U]);let L=b(()=>{$.current=!1,se.current=!0,V(!1),H(!1),T(o.startNewConversationOnOpen?null:void 0)},[o.startNewConversationOnOpen,T]);C(()=>{y||!U||!se.current||(se.current=!1,requestAnimationFrame(()=>Le.current?.focus()))},[y,U]);let B=b(()=>{$.current=!0,V(!0),R()},[R]),Be=R,Q=b(s=>{let i=s?Ze(s):null;i&&en(o.agentId,i),$.current=!0,V(!0),H(!1),R(),T(null)},[o.agentId,T,R]),De=b(s=>{$.current=!0,V(!0),H(!1),R(),T(s)},[T,R]),Ve=b(()=>{y||$.current?L():B()},[L,y,B]),We=b(()=>{oe(!1),Pe(!1),Te(s=>s+1)},[]),Ge=b(()=>{let s=[`heroui-agent:anonymous:${o.agentId}`,`heroui-agent:conversation:${o.agentId}:`,`heroui-agent:history:${o.agentId}:`];for(let i=localStorage.length-1;i>=0;i-=1){let d=localStorage.key(i);d&&s.some(A=>d.startsWith(A))&&localStorage.removeItem(d)}$.current=!1,oe(!1),V(!1),H(!1),be(o.agentId,!1),Pe(!0),Te(i=>i+1),T(),window.setTimeout(()=>{import("./composer-draft-NSKK65F3.js").then(({clearAgentComposerDraftsForProject:i})=>i(o.agentId)).catch(()=>{})},0)},[o.agentId,T]);return C(()=>{let s={hide:L,newConversation:Q,preload:Be,ready:U,refreshAuth:We,show:B,shutdown:Ge,toggle:Ve};return D.set(o.agentId,s),En(),()=>{D.get(o.agentId)===s&&(D.delete(o.agentId),En())}},[L,Q,o.agentId,Be,U,We,B,Ge,Ve]),kn(()=>{let s=X.current;if(!O||!s)return;let i=Cn({onFileDialogActiveChange:$e,onIntent:R,options:o});s.render(Nn(On,{children:[F&&o.showLauncher&&!y?Nn("button",{ref:Le,"aria-expanded":!1,"aria-haspopup":"dialog",className:"ha-launcher",style:o.launcherStyle,type:"button","aria-label":te?"Open data assistant, unread messages":"Open data assistant",onClick:B,children:[P(cn,{icon:o.launcherIcon}),te?P("span",{"aria-hidden":"true",className:"ha-launcher__unread"}):null]}):null,J&&!Fe?P(J,{composerControlsRevealed:W,conversationEpoch:_,identityEpoch:Oe,identityReset:Me,open:y,options:o,requestedConversationId:K,shellComposerEndSlot:i.end,shellComposerFooterSlot:i.footer,showReadyLoader:!_e&&K!==null,tokenManager:j,onClose:L,onComposerControlsReveal:ue,onNewConversation:Q,onReady:He,onSelectConversation:De,onUnreadChange:oe}):P(Ke,{agentId:o.agentId,shouldCloseOnInteractOutside:o.shouldCloseOnInteractOutside,defaultExpanded:o.panelExpanded,expandable:o.panelExpandable,historySlot:P(On,{}),name:"Data assistant",open:y,showBetaBadge:o.showBetaBadge,viewMode:o.viewMode,onClose:L,children:K===null?P(on,{composerConnecting:!0,agentId:o.agentId,composerControlsAvailable:o.composerControlsAvailable,composerControlsRevealed:W,composerEndSlot:i.end,composerFooterSlot:i.footer,composerStartSlot:i.start,greeting:o.greeting,placeholder:o.composerPlaceholder,suggestedPrompts:o.suggestedPrompts??[],onComposerControlsReveal:ue,onIntent:R},`shell-${_}`):P(ze,{})})]}))},[J,W,Fe,_,He,te,_e,L,Oe,Me,y,Q,o,O,U,F,K,R,ue,De,B,j]),null}export{co as a,lo as b};
@@ -1183,7 +1183,7 @@ declare const clientToolsSchema: z.ZodArray<z.ZodObject<{
1183
1183
  type ClientToolManifestEntry = z.infer<typeof clientToolManifestEntrySchema>;
1184
1184
 
1185
1185
  declare const HEROUI_AGENT_PROTOCOL_VERSION: 6;
1186
- declare const HEROUI_AGENT_SDK_VERSION: "0.2.0-beta.16";
1186
+ declare const HEROUI_AGENT_SDK_VERSION: "0.2.0-beta.17";
1187
1187
  /** Production Agent API origin used when hosts omit `_api.baseUrl` / `apiBaseUrl`. */
1188
1188
  declare const HEROUI_AGENT_API_BASE_URL: "https://api.heroui.pro";
1189
1189
 
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 P(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function v(t){if(t!==void 0)return typeof t=="string"?t:u}function S(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 O(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(!P(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(!P(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||!P(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 E(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:O(["bottom-left","bottom-right"]),style:yt}),panel:n=>n===void 0?void 0:x(n,{expandable:S,expanded:S,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:O(["dark","light","system"]),colors:a=>a===void 0?void 0:x(a,Object.fromEntries(bt.map(i=>[i,Ce]))),designTheme:O(["base","brutalism","glass","mouve"]),radius:O(["pill","round","sharp","soft"]),typography:a=>a===void 0?void 0:x(a,{baseSize:Y,fontFamily:v})}),viewMode:O(["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:S,disclaimer:n=>n===!1?!1:v(n),modelPicker:S,placeholder:v})}function kt(t){return x(t,{animated:n=>{if(n===void 0||n===!1)return n;if(!P(n))return u;let a=O(["blurIn","fadeIn","slideUp"])(n.animation);return a===u||a===void 0?u:{...n,animation:a}},caret:n=>n===!1?!1:O(["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(!P(t)||t.version!==ye)return null;let n=t.revision;if(typeof n!="string"||!n)return null;let a=E(xt(t.appearance)),i=E(x(t.capabilities,{imageSearch:S,newsSearch:S,webSearch:S})),l=E(At(t.composer)),d=E(kt(t.markdown)),f=E(x(t.permissions,{defaultMode:O(["ask","auto","full"]),showPicker:S})),h=E(It(t.responseActions)),U=E(S(t.showBetaBadge)),b=E(x(t.startScreen,{greeting:v,promptShortcuts:S,prompts:Ct})),_=E(x(t.webfont,{familyName:z=>typeof z=="string"&&z?z: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},...U===void 0?{}:{showBetaBadge:U},...b?{startScreen:b}:{},..._?{webfont:_}:{},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),j=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()]),L=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(L).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(L).min(1).max(50),format:C.optional(),labelKey:c,valueKey:c}),Rt=s.extend({colors:Ie.optional(),data:e.array(L).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(L).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(L).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,_=d,z=f,ue=h;(z>Math.min(b,ue)||_<Math.max(b,ue)||z>_)&&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(L).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]})}),Gt=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"]})})),Mt=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(U=>d(U,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:j,start:j}).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:j.optional(),kind:e.literal("date-picker"),max:j.optional(),min:j.optional()}),e.object({...A,defaultValue:jt.optional(),kind:e.literal("date-range-picker"),max:j.optional(),min:j.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"]),R=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}),V=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:V.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)}),B=e.enum(["accent","danger","default","muted","success","warning"]),Ft=e.object({actions:e.array(y).max(3).optional(),badge:e.object({label:r,tone:B.optional()}).optional(),description:r.optional(),id:m,image:e.object({alt:r,src:V}),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:R.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:B.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:Gt,heatmap:Ut,image:s.extend({images:e.array(e.object({alt:r,aspectRatio:e.enum(["landscape","portrait","square","wide"]).optional(),caption:r.optional(),src:V})).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:R.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:R.optional(),id:m,imageAlt:r.optional(),imageUrl:V.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:R.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(L).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:R.optional(),label:r,tone:B.optional(),value:e.string().trim().min(1).max(500)})).max(12),image:e.object({alt:r,src:V}).optional(),kind:e.literal("record-card"),layout:_t.optional(),status:e.object({label:r,tone:B.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:R.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:Mt,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(L).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:B.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,Gn=o.rideStatus,Mn=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,D=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 Ge(t){return Ne.has(t.kind)}function Me(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(D),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:R.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:R.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:B.optional(),variant:e.enum(["soft","solid"]).optional()}),Fe=T.extend({kind:e.literal("icon"),name:R,size:e.enum(["lg","md","sm"]).optional(),tone:B.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)||Ge(n)&&We(Me(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&&lt(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 Ge(t)?Me(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 U=(b,_)=>{if(f+=1,h=Math.max(h,_),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),!(_>J))for(let z of eo(b))U(z,_+1)};for(let b of t)U(b,i);h>J&&n.addIssue({code:"custom",message:`Composed UI trees can nest at most ${J} levels deep.`}),f>D&&n.addIssue({code:"custom",message:`Composed UI trees can contain at most ${D} 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}),N=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:N(D)}),"channel-message":jn,"code-block":Sn,col:et.extend({children:N(D)}),"comparison-list":un,"composed-chart":Qt,"create-event":On,dashboard:_e.extend({children:N(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:N(D)}),heading:Ve,heatmap:sn,icon:Fe,image:Cn,"item-card":Ye.extend({left:N(4).optional().describe("Leading slot nodes."),middle:N(8).describe("Primary flexible slot nodes."),right:N(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":Mn,"radar-chart":nn,"radial-chart":on,rating:He,"record-card":Rn,"ride-status":Gn,row:Qe.extend({children:N(D)}),"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:N(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 G}from"zod";var ro=["callMcpTool","composeUI","executeSandbox","getComponentSchema","renderComponent","searchKnowledge","searchMcpTools","searchWeb"],io="mcp_",so=20,lo=16*1024,po=G.object({description:G.string().trim().min(1).max(1e3),inputSchema:G.record(G.string(),G.unknown()),name:G.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:G.boolean().optional()}),Xo=G.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 K=6,dt="0.2.0-beta.16",Qo="https://api.heroui.pro";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()}),oa=p.object({anonymousId:me.optional(),identity:go,profile:ho.optional()}),aa=p.object({expiresAt:p.number().int().positive(),token:p.string().trim().min(1)}),ra=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)}),ia={embed:"embed",preview:"preview"},sa=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})]),ma=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.7-flash","anthropic/claude-sonnet-5","anthropic/claude-opus-4.8"],Co={"google/gemini-3.5-flash":"google/gemini-3.7-flash","google/gemini-3.6-flash":"google/gemini-3.7-flash"};function de(t){return Co[t]??t}var da="google/gemini-3.7-flash",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.7-flash",label:"Gemini 3.7 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 ua(t){return typeof t=="string"&&xo.has(t)}function ga(t){let n=t?de(t):void 0;return bo.find(a=>a.id===n)?.tier??"light"}import{z as gt}from"zod";var Ca=gt.preprocess(t=>typeof t=="string"?de(t):t,gt.enum(ce));var xa="heroui-agent:runtime-timing",Aa="heroui_agent_turn_admitted",ka="getTurnAdmissionStatuses",Ia=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(),wa=g.object({conversationId:g.string().uuid(),event:g.enum(Ao),properties:So.default({})}).strict(),_a=g.enum(To);export{ia 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,D as COMPOSED_UI_MAX_NODES,da as DEFAULT_AGENT_PICKER_MODEL_ID,Qo as HEROUI_AGENT_API_BASE_URL,_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,K as HEROUI_AGENT_PROTOCOL_VERSION,ye as HEROUI_AGENT_REMOTE_CONFIG_VERSION,xa as HEROUI_AGENT_RUNTIME_TIMING_EVENT,dt as HEROUI_AGENT_SDK_VERSION,Eo as HEROUI_AGENT_TEXT_ATTACHMENT_CONTENT_TYPES,Ia as HEROUI_AGENT_TURN_ADMISSION_STATUS_MAX_IDS,ka as HEROUI_AGENT_TURN_ADMISSION_STATUS_METHOD,Aa 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,aa as agentAuthTokenSchema,Tt as agentIconNames,R as agentIconSchema,me as agentIdentityIdSchema,Ca as agentModelIdSchema,sa as agentProjectConfigSchema,yo as agentSourceSchema,ma as agentSourcesSchema,co as agentSurfaceVariantSchema,mo as agentThemeSchema,ra 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,oa 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,ga as getAgentModelTier,Me as getAgentUIContainerChildren,rt as gridComponentSchema,Ve as headingComponentSchema,sn as heatmapComponentSchema,So as heroUIAgentEmbedEventPropertiesSchema,wa as heroUIAgentEmbedEventSchema,_a as heroUIAgentTurnErrorCodeSchema,Fe as iconComponentSchema,Cn as imageComponentSchema,ua as isAgentModelId,Ge 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,Mn 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,Gn 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 G}from"zod";var ro=["callMcpTool","composeUI","executeSandbox","getComponentSchema","renderComponent","searchKnowledge","searchMcpTools","searchWeb"],io="mcp_",so=20,lo=16*1024,po=G.object({description:G.string().trim().min(1).max(1e3),inputSchema:G.record(G.string(),G.unknown()),name:G.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:G.boolean().optional()}),Xo=G.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 K=6,dt="0.2.0-beta.17",Qo="https://api.heroui.pro";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()}),oa=p.object({anonymousId:me.optional(),identity:go,profile:ho.optional()}),aa=p.object({expiresAt:p.number().int().positive(),token:p.string().trim().min(1)}),ra=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)}),ia={embed:"embed",preview:"preview"},sa=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})]),ma=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.7-flash","anthropic/claude-sonnet-5","anthropic/claude-opus-4.8"],Co={"google/gemini-3.5-flash":"google/gemini-3.7-flash","google/gemini-3.6-flash":"google/gemini-3.7-flash"};function de(t){return Co[t]??t}var da="google/gemini-3.7-flash",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.7-flash",label:"Gemini 3.7 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 ua(t){return typeof t=="string"&&xo.has(t)}function ga(t){let n=t?de(t):void 0;return bo.find(a=>a.id===n)?.tier??"light"}import{z as gt}from"zod";var Ca=gt.preprocess(t=>typeof t=="string"?de(t):t,gt.enum(ce));var xa="heroui-agent:runtime-timing",Aa="heroui_agent_turn_admitted",ka="getTurnAdmissionStatuses",Ia=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(),wa=g.object({conversationId:g.string().uuid(),event:g.enum(Ao),properties:So.default({})}).strict(),_a=g.enum(To);export{ia 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,D as COMPOSED_UI_MAX_NODES,da as DEFAULT_AGENT_PICKER_MODEL_ID,Qo as HEROUI_AGENT_API_BASE_URL,_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,K as HEROUI_AGENT_PROTOCOL_VERSION,ye as HEROUI_AGENT_REMOTE_CONFIG_VERSION,xa as HEROUI_AGENT_RUNTIME_TIMING_EVENT,dt as HEROUI_AGENT_SDK_VERSION,Eo as HEROUI_AGENT_TEXT_ATTACHMENT_CONTENT_TYPES,Ia as HEROUI_AGENT_TURN_ADMISSION_STATUS_MAX_IDS,ka as HEROUI_AGENT_TURN_ADMISSION_STATUS_METHOD,Aa 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,aa as agentAuthTokenSchema,Tt as agentIconNames,R as agentIconSchema,me as agentIdentityIdSchema,Ca as agentModelIdSchema,sa as agentProjectConfigSchema,yo as agentSourceSchema,ma as agentSourcesSchema,co as agentSurfaceVariantSchema,mo as agentThemeSchema,ra 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,oa 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,ga as getAgentModelTier,Me as getAgentUIContainerChildren,rt as gridComponentSchema,Ve as headingComponentSchema,sn as heatmapComponentSchema,So as heroUIAgentEmbedEventPropertiesSchema,wa as heroUIAgentEmbedEventSchema,_a as heroUIAgentTurnErrorCodeSchema,Fe as iconComponentSchema,Cn as imageComponentSchema,ua as isAgentModelId,Ge 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,Mn 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,Gn 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,d as Ho}from"./chunk-CLHBM3HQ.js";import{a as Ha,c as Sn}from"./chunk-S6OIAJSC.js";import{a as me}from"./chunk-CR3H7AVI.js";import{A as Rr,B as Mr,C as _o,D as bn,E as La,b as We,d as Ca,e as $n,g as Aa,h as Ta,i as Eo,j as Po,m as Ea,n as Pa,o as Kn,p as Ia,q as xa,r as ka,s as ko,t as Na,u as _a,v as Oa,w as tn,x as Da,y as Tr,z as No}from"./chunk-366EZBW3.js";import{a as Io}from"./chunk-6ZJJN322.js";import{b as ba,c as Ar,d as Sa}from"./chunk-64RI74L5.js";import{c as Ra,d as Ma,e as xo,f as wa}from"./chunk-UHHKMESI.js";import{a as Ua,b as Ba,c as Fa,d as Lo}from"./chunk-7KCGPNEN.js";import"./chunk-4JEZZR5J.js";import{a as Bo,b as $a,c as Ka,d as wr}from"./chunk-RNNGE7KM.js";import{a as Va,b as Uo}from"./chunk-PZJ4NC3J.js";import{useAgentChat as Ng}from"@cloudflare/ai-chat/react";import{ArrowUp as _g,ArrowUpRight as Og,Microphone as Uc,Plus as Bc,StopFill as Oc,Xmark as Dg}from"@gravity-ui/icons";function Mt(e){return!!(e&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e))}function Fo(e,t){return e===null?null:typeof e=="string"?Mt(e)?e:null:Mt(t)?t:null}var Er=30,qa=52;function Vo(e){try{let t=JSON.parse(localStorage.getItem(e)??"[]");return Pr(t)}catch{return[]}}function Pr(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object"&&"id"in t&&typeof t.id=="string"&&Mt(t.id)&&"title"in t&&typeof t.title=="string"&&"updatedAt"in t&&typeof t.updatedAt=="number")).sort((t,n)=>n.updatedAt-t.updatedAt).slice(0,Er):[]}function $o(e,t){let n=new Map(e.map(r=>[r.id,r]));for(let r of t){let o=n.get(r.id);(!o||r.updatedAt>=o.updatedAt)&&n.set(r.id,r)}return[...n.values()].sort((r,o)=>o.updatedAt-r.updatedAt).slice(0,Er)}function Nt(e,t){localStorage.setItem(e,JSON.stringify(t.slice(0,Er)))}function qn(e,t,n,r,{replaceTitle:o=!1}={}){if(!n)return e;let s=e.find(d=>d.id===t);return[{id:t,title:o?n:s?.title??n,updatedAt:r},...e.filter(d=>d.id!==t)].sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,Er)}function Ir(e){let t=e?.find(r=>r.role==="user"),n=t?.parts.filter(r=>r.type==="text").map(r=>r.text??"").join(" ");return n?.trim()?qo(n):t?"Attachment":null}function Ko(e,t){return e?qo(e):t[0]?.name||"Attachment"}function qo(e){let t=e.replace(/\s+/g," ").trim();return t.length>qa?`${t.slice(0,qa-1).trimEnd()}\u2026`:t}function Go(e){let t=new Date;t.setHours(0,0,0,0);let n=t.getTime(),r=n-8640*60*1e3,o=[{items:[],label:"Today"},{items:[],label:"Previous 7 days"},{items:[],label:"Older"}];for(let s of e)s.updatedAt>=n?o[0].items.push(s):s.updatedAt>=r?o[1].items.push(s):o[2].items.push(s);return o.filter(s=>s.items.length>0)}import{Disclosure as Cn}from"@heroui/react";import{jsx as Fe,jsxs as nn}from"react/jsx-runtime";function vu(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase().replace(/^\w/,t=>t.toUpperCase())}function bu(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=Object.entries(e);return t.length===0||t.some(([,n])=>typeof n=="object")?null:t.map(([n,r])=>[vu(n),String(r)])}function Ga({approveLabel:e="Allow",className:t,denyLabel:n="Deny",hint:r="Waiting for your approval",icon:o,input:s,onApprove:i,onDeny:d,title:l,...c}){let m=bu(s),p=s!=null&&(typeof s!="object"||Object.keys(s).length>0);return nn("section",{"aria-label":l,className:me("aui-approval",t),"data-slot":"agent-ui-approval",...c,children:[nn("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,nn("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?nn(Cn,{defaultExpanded:!0,className:"aui-approval__disclosure",children:[Fe(Cn.Heading,{children:nn(Cn.Trigger,{className:"aui-approval__disclosure-trigger",children:["Review action details",Fe(Cn.Indicator,{})]})}),Fe(Cn.Content,{children:Fe(Cn.Body,{children:m?Fe("dl",{className:"aui-approval__details","data-slot":"agent-ui-approval-details",children:m.map(([S,u])=>nn("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,nn("div",{className:"aui-approval__actions","data-slot":"agent-ui-approval-actions",children:[Fe(Oo,{size:"md",variant:"tertiary",onClick:d,children:n}),Fe(Oo,{size:"md",variant:"primary",onClick:i,children:e})]})]})}import{Description as Mu,Label as wu,ListBox as Qo,Select as Qn}from"@heroui/react";import{useCallback as Eu,useEffect as Pu,useRef as za,useState as Wa}from"react";import{useId as Su}from"react";import{jsx as G,jsxs as Gn}from"react/jsx-runtime";function Qa({className:e,provider:t}){let n=t?.toLowerCase();return n==="openai"?G(Cu,{className:e,"data-provider":"openai"}):n==="google"?G(Au,{className:e,"data-provider":"google"}):n==="anthropic"?G(Tu,{className:e,"data-provider":"anthropic"}):n==="moonshot ai"?G(Ru,{className:e,"data-provider":"moonshot-ai"}):null}function Cu(e){return G("svg",{"aria-hidden":"true",fill:"currentColor",focusable:"false",role:"presentation",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",...e,children:G("path",{d:"M22.282 9.821a5.985 5.985 0 0 0-.516-4.911 6.046 6.046 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.182a5.985 5.985 0 0 0-3.998 2.9 6.046 6.046 0 0 0 .743 7.096 5.98 5.98 0 0 0 .511 4.911 6.051 6.051 0 0 0 6.515 2.9A5.985 5.985 0 0 0 13.26 24a6.056 6.056 0 0 0 5.772-4.206 5.99 5.99 0 0 0 3.997-2.9 6.056 6.056 0 0 0-.747-7.073m-9.022 12.608a4.476 4.476 0 0 1-2.877-1.041l.142-.08 4.778-2.758a.795.795 0 0 0 .393-.682v-6.737l2.02 1.169a.07.07 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494M3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085 4.783 2.758a.77.77 0 0 0 .781 0l5.843-3.368v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.141-1.646M2.341 7.896a4.485 4.485 0 0 1 2.365-1.973V11.6a.766.766 0 0 0 .388.677l5.814 3.354-2.02 1.169a.08.08 0 0 1-.071 0l-4.83-2.787A4.504 4.504 0 0 1 2.34 7.872zm16.596 3.856-5.833-3.388L15.119 7.2a.08.08 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.104v-5.677a.79.79 0 0 0-.407-.667m2.011-3.023-.142-.085-4.773-2.782a.776.776 0 0 0-.786 0L9.409 9.23V6.897a.07.07 0 0 1 .028-.061l4.83-2.787a4.499 4.499 0 0 1 6.68 4.66zM8.307 12.863l-2.02-1.164a.08.08 0 0 1-.038-.056V6.074a4.499 4.499 0 0 1 7.376-3.453l-.142.08-4.778 2.758a.795.795 0 0 0-.393.682zm1.098-2.365 2.602-1.5 2.607 1.5v2.999l-2.598 1.5-2.607-1.5Z"})})}function Au(e){let t=Su().replace(/:/g,""),n=`${t}-gemini-shape`,r=`${t}-gemini-mask`,o=`${t}-gemini-yellow-blur`,s=`${t}-gemini-red-blur`,i=`${t}-gemini-green-blur`,d=`${t}-gemini-blue-blur`,l=`${t}-gemini-gold-blur`,c=`${t}-gemini-cyan-blur`,m=`${t}-gemini-violet-blur`,p=`${t}-gemini-coral-blur`,S=`${t}-gemini-lemon-blur`;return Gn("svg",{"aria-hidden":"true",fill:"none",focusable:"false",role:"presentation",viewBox:"0 0 32 32",xmlns:"http://www.w3.org/2000/svg",...e,children:[G("path",{d:"M0 0h32v32H0z",fill:"none"}),G("defs",{children:G("path",{d:"M57.067 28.61q-7.396-3.184-12.945-8.732q-5.547-5.546-8.732-12.944a38.4 38.4 0 0 1-1.97-5.824A1.464 1.464 0 0 0 32 .001c-.671 0-1.255.458-1.419 1.11a38.4 38.4 0 0 1-1.971 5.823q-3.186 7.397-8.732 12.944q-5.548 5.548-12.945 8.732a38.4 38.4 0 0 1-5.824 1.972A1.464 1.464 0 0 0 0 32c0 .67.458 1.255 1.11 1.418a38.4 38.4 0 0 1 5.823 1.972q7.396 3.184 12.945 8.732q5.55 5.546 8.732 12.944a38.4 38.4 0 0 1 1.971 5.824c.164.65.749 1.11 1.419 1.11s1.255-.458 1.419-1.11a38.4 38.4 0 0 1 1.971-5.823q3.185-7.395 8.732-12.944q5.548-5.548 12.945-8.732a38.4 38.4 0 0 1 5.824-1.972A1.464 1.464 0 0 0 64 32.001c0-.672-.458-1.255-1.11-1.42a38.4 38.4 0 0 1-5.823-1.97",fill:"#fff",id:n})}),Gn("g",{fill:"none",children:[Gn("g",{mask:`url(#${r})`,transform:"translate(2 2)scale(.4375)",children:[G("use",{href:`#${n}`}),G("g",{filter:`url(#${o})`,children:G("ellipse",{cx:"14.208",cy:"16.716",fill:"#ffe432",rx:"14.208",ry:"16.716",transform:"rotate(19.552 -43.96 -16.268)"})}),G("g",{filter:`url(#${s})`,children:G("ellipse",{cx:"27.054",cy:"2.551",fill:"#fc413d",rx:"18.394",ry:"18.799"})}),G("g",{filter:`url(#${i})`,children:G("ellipse",{cx:"19.224",cy:"24.904",fill:"#00b95c",rx:"19.224",ry:"24.904",transform:"rotate(-2.799 667.58 51.694)"})}),G("g",{filter:`url(#${i})`,children:G("ellipse",{cx:"18.843",cy:"20.744",fill:"#00b95c",rx:"18.843",ry:"20.744",transform:"rotate(-31.317 81.174 36.482)"})}),G("g",{filter:`url(#${d})`,children:G("ellipse",{cx:"66.462",cy:"24.977",fill:"#3186ff",rx:"18.093",ry:"17.423"})}),G("g",{filter:`url(#${l})`,children:G("ellipse",{cx:"20.929",cy:"22.075",fill:"#fbbc04",rx:"20.929",ry:"22.075",transform:"rotate(37.251 9.618 -7.898)"})}),G("g",{filter:`url(#${c})`,children:G("ellipse",{cx:"24.131",cy:"22.292",fill:"#3186ff",rx:"24.131",ry:"22.292",transform:"rotate(34.51 19.317 63.957)"})}),G("g",{filter:`url(#${m})`,children:G("path",{d:"M54.226-2.304c2.794 3.799-.797 11.184-8.02 16.497c-7.222 5.312-15.342 6.539-18.136 2.74S28.866 5.75 36.09.436c7.223-5.312 15.343-6.539 18.136-2.74",fill:"#749bff"})}),G("g",{filter:`url(#${p})`,children:G("ellipse",{cx:"27.585",cy:"17.148",fill:"#fc413d",rx:"27.585",ry:"17.148",transform:"rotate(-42.847 5.973 20.37)"})}),G("g",{filter:`url(#${S})`,children:G("ellipse",{cx:"14.782",cy:"8.596",fill:"#ffee48",rx:"14.782",ry:"8.596",transform:"rotate(35.592 -44.338 25.191)"})})]}),Gn("defs",{children:[G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"42.756",id:o,width:"38.868",x:"-19.618",y:"12.903",children:G("feGaussianBlur",{stdDeviation:"2.46"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"85.162",id:s,width:"84.353",x:"-15.122",y:"-40.03",children:G("feGaussianBlur",{stdDeviation:"11.891"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"90.22",id:i,width:"78.916",x:"-20.768",y:"11.483",children:G("feGaussianBlur",{stdDeviation:"10.109"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"73.27",id:d,width:"74.611",x:"29.156",y:"-11.658",children:G("feGaussianBlur",{stdDeviation:"9.606"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"78.151",id:l,width:"77.538",x:"-38.291",y:"-16.269",children:G("feGaussianBlur",{stdDeviation:"8.706"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"76.898",id:c,width:"78.218",x:"7.78",y:"-6.098",children:G("feGaussianBlur",{stdDeviation:"7.775"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"51.479",id:m,width:"55.879",x:"13.208",y:"-18.425",children:G("feGaussianBlur",{stdDeviation:"6.957"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"68.674",id:p,width:"70.203",x:"-15.474",y:"-31.027",children:G("feGaussianBlur",{stdDeviation:"5.876"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"51.261",id:S,width:"55.137",x:"-14.173",y:"20.474",children:G("feGaussianBlur",{stdDeviation:"7.273"})}),G("mask",{height:"64",id:r,maskUnits:"userSpaceOnUse",width:"64",x:"0",y:"0",children:G("use",{href:`#${n}`})})]})]})]})}function Tu(e){return G("svg",{"aria-hidden":"true",fill:"none",focusable:"false",role:"presentation",viewBox:"0 0 256 257",xmlns:"http://www.w3.org/2000/svg",...e,children:G("path",{d:"m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0l10.63 1.426 4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999z",fill:"#d97757"})})}function Ru(e){return Gn("svg",{"aria-hidden":"true",clipRule:"evenodd",fillRule:"evenodd",focusable:"false",role:"presentation",strokeLinejoin:"round",strokeMiterlimit:2,viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",...e,children:[G("path",{d:"M503 114.333v280c0 60.711-49.29 110-110 110H113c-60.711 0-110-49.289-110-110v-280c0-60.71 49.289-110 110-110h280c60.71 0 110 49.29 110 110z"}),G("path",{d:"M342.065 189.759c1.886-2.42 3.541-4.63 5.289-6.77.81-1.007.74-1.771-.046-2.824-7.58-9.965-8.298-21.028-3.935-32.254 3.275-8.448 10.52-12.406 19.373-13.25 5.52-.521 10.936.046 15.959 2.73 6.596 3.53 10.438 8.912 11.688 16.341.995 5.926.81 11.712-.868 17.452-2.974 10.161-10.277 15.427-20.287 16.758-8.31 1.11-16.734 1.25-25.113 1.817-.648.046-1.308 0-2.06 0z",fill:"#027aff"}),G("path",{d:"M321.512 144.254h-50.064l-39.637 90.384h-56.036v-89.99H131v232.868h44.787v-98.103h78.973c13.598 0 26.015-7.927 31.744-20.252v118.355h44.787v-98.103c0-23.342-18.239-42.97-41.523-44.671v-.116h-24.593a45.577 45.577 0 0026.884-24.534l29.453-65.838z",fill:"#fff"})]})}import{jsx as ft,jsxs as zn}from"react/jsx-runtime";function Iu({description:e,provider:t}){return t?e?`${t} \xB7 ${e}`:t:e}function xr({"aria-label":e="AI model",className:t,isDisabled:n=!1,onChange:r,options:o,placement:s="top start",value:i}){let[d,l]=Wa(!1),[c,m]=Wa(),p=za(0),S=za(null),u=n||o.length===0,h=o.find(C=>C.id===i),x=Eu(C=>{S.current=C,C?.setAttribute("aria-keyshortcuts","Control+Shift+M"),m(Sn(C))},[]),w=C=>{!C&&Date.now()-p.current<350||l(C)};return Pu(()=>{if(u)return;let C=O=>{O.defaultPrevented||O.isComposing||O.repeat||!O.ctrlKey||!O.shiftKey||O.altKey||O.metaKey||O.key.toLowerCase()!=="m"||(O.preventDefault(),S.current?.focus(),l(!0))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[u]),zn(Qn,{"aria-label":e,className:me("aui-model-picker",t),isDisabled:u,isOpen:d,value:i,onOpenChange:w,onChange:C=>{C!=null&&r(C),l(!1)},children:[zn(Qn.Trigger,{ref:x,className:"aui-model-picker__trigger","data-shortcut":"\u2303\u21E7M","data-slot":"agent-ui-model-picker-trigger","data-tooltip":"Select model",onPointerDown:()=>{p.current=Date.now()},children:[ft(Qn.Value,{className:"aui-model-picker__value",children:h?.label??i}),ft(Qn.Indicator,{className:"aui-model-picker__indicator"}),zn("span",{"aria-hidden":"true",className:"aui-picker-tooltip",children:[ft("span",{children:"Select model"}),ft("kbd",{className:"aui-picker-tooltip__shortcut",children:"\u2303\u21E7M"})]})]}),ft(Qn.Popover,{className:"aui-model-picker__popover",placement:s,UNSTABLE_portalContainer:c,children:ft(Qo,{"aria-label":`${e} options`,className:"aui-model-picker__list",children:o.map(C=>{let O=Iu(C);return zn(Qo.Item,{className:"aui-model-picker__option","data-description":O,id:C.id,textValue:C.label,children:[ft(Qa,{className:"aui-model-picker__option-icon",provider:C.provider}),zn("span",{className:"aui-model-picker__option-copy",children:[ft(wu,{className:"aui-model-picker__option-label",children:C.label}),O?ft(Mu,{className:"aui-model-picker__option-description",title:O,children:O}):null]}),ft(Qo.ItemIndicator,{className:"aui-model-picker__option-indicator"})]},C.id)})})})]})}import{Hand as xu,LockOpen as ku,ShieldCheck as Ja}from"@gravity-ui/icons";import{Description as Nu,Label as _u,ListBox as zo,Select as Wn}from"@heroui/react";import{useCallback as Ou,useEffect as Du,useRef as ja,useState as Ya}from"react";import{jsx as ot,jsxs as jn}from"react/jsx-runtime";var Xa=[{description:"Ask before every client tool action.",icon:xu,id:"ask",label:"Ask for approval"},{description:"Only ask for actions marked as needing approval.",icon:Ja,id:"auto",label:"Approve for me"},{description:"Run client tools without asking for approval.",icon:ku,id:"full",label:"Full access"}];function kr({"aria-label":e="Tool permissions",className:t,isDisabled:n=!1,onChange:r,value:o}){let[s,i]=Ya(!1),[d,l]=Ya(),c=ja(0),m=ja(null),p=Xa.find(h=>h.id===o),S=Ou(h=>{m.current=h,h?.setAttribute("aria-keyshortcuts","Control+Shift+P"),l(Sn(h))},[]),u=h=>{!h&&Date.now()-c.current<350||i(h)};return Du(()=>{if(n)return;let h=x=>{x.defaultPrevented||x.isComposing||x.repeat||!x.ctrlKey||!x.shiftKey||x.altKey||x.metaKey||x.key.toLowerCase()!=="p"||(x.preventDefault(),m.current?.focus(),i(!0))};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[n]),jn(Wn,{"aria-label":e,className:me("aui-permission-picker",t),"data-tone":o==="full"?"warning":void 0,isDisabled:n,isOpen:s,value:o,onOpenChange:u,onChange:h=>{h!=null&&r(h),i(!1)},children:[jn(Wn.Trigger,{ref:S,className:"aui-permission-picker__trigger","data-shortcut":"\u2303\u21E7P","data-slot":"agent-ui-permission-picker-trigger","data-tooltip":"Change permissions",onPointerDown:()=>{c.current=Date.now()},children:[ot(Ja,{"aria-hidden":"true",className:"aui-permission-picker__trigger-icon"}),ot(Wn.Value,{className:"aui-permission-picker__value",children:p?.label??o}),ot(Wn.Indicator,{className:"aui-permission-picker__indicator"}),jn("span",{"aria-hidden":"true",className:"aui-picker-tooltip",children:[ot("span",{children:"Change permissions"}),ot("kbd",{className:"aui-picker-tooltip__shortcut",children:"\u2303\u21E7P"})]})]}),ot(Wn.Popover,{className:"aui-permission-picker__popover",placement:"top start",UNSTABLE_portalContainer:d,children:ot(zo,{"aria-label":`${e} options`,className:"aui-permission-picker__list",children:Xa.map(h=>{let x=h.icon;return jn(zo.Item,{className:"aui-permission-picker__option","data-description":h.description,"data-tone":h.id==="full"?"warning":void 0,id:h.id,textValue:h.label,children:[ot(x,{"aria-hidden":"true",className:"aui-permission-picker__option-icon"}),jn("span",{className:"aui-permission-picker__option-copy",children:[ot(_u,{className:"aui-permission-picker__option-label",children:h.label}),ot(Nu,{className:"aui-permission-picker__option-description",title:h.description,children:h.description})]}),ot(zo.ItemIndicator,{className:"aui-permission-picker__option-indicator"})]},h.id)})})})]})}import{useEffect as Wo,useRef as An}from"react";import{jsx as ei}from"react/jsx-runtime";var Lu=40,Za=2;function Nr(e,t,n){return Math.min(n,Math.max(t,e))}function Hu(e){let t=Nr(Math.round(e),32,32768);return 2**Math.round(Math.log2(t))}function Uu(e){return e instanceof Error?e:new Error("Unable to access the microphone.")}function Bu(){let e=window;return e.AudioContext??e.webkitAudioContext}function Fu(e){e?.getTracks().forEach(t=>t.stop())}function Vu(e){if(!(!e||e.state==="closed"))try{e.close().catch(()=>{})}catch{}}function $u(e,t,n,r,o){let s=Math.min(r/2,o/2);if(typeof e.roundRect!="function"){e.fillRect(t,n,r,o);return}e.beginPath(),e.roundRect(t,n,r,o,s),e.fill()}function jo({active:e=!1,"aria-label":t,barGap:n=2,barWidth:r=2,className:o,deviceId:s,fadeEdges:i=!0,fadeWidth:d=20,fftSize:l=256,height:c=Lu,onError:m,onStreamEnd:p,onStreamReady:S,role:u,sensitivity:h=1.15,smoothingTimeConstant:x=.82,stream:w,style:C,...O}){let _=An(null),k=An({onError:m,onStreamEnd:p,onStreamReady:S}),L=An(null),$=An(null),X=An(null),b=An([]);Wo(()=>{k.current={onError:m,onStreamEnd:p,onStreamReady:S}},[m,p,S]),Wo(()=>{if(!e||w===null){_.current=null;return}let M,T=!1,P=!1,z=!1,ie=w===void 0,j,F=w,K=Se=>{try{j?.disconnect()}catch{}j=void 0,_.current?.context===M&&(_.current=null),Vu(M),M=void 0,ie&&Fu(F),F=void 0,Se&&P&&!z&&(z=!0,k.current.onStreamEnd?.())};return(async()=>{try{let Se=Bu();if(!Se)throw new Error("Live audio analysis is not supported in this browser.");if(!F){if(!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone capture is not supported in this browser.");F=await navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,...s?{deviceId:{exact:s}}:{},echoCancellation:!0,noiseSuppression:!0}})}if(T){K(!1);return}M=new Se;let H=M.createAnalyser();if(H.fftSize=Hu(l),H.smoothingTimeConstant=Nr(x,0,1),j=M.createMediaStreamSource(F),j.connect(H),M.state==="suspended"&&await M.resume(),T){K(!1);return}_.current=H,X.current=new Uint8Array(H.frequencyBinCount),P=!0,k.current.onStreamReady?.(F)}catch(Se){K(!1),T||k.current.onError?.(Uu(Se))}})(),()=>{T=!0,K(!0)}},[e,s,l,w,x]),Wo(()=>{let M=L.current,T=$.current;if(!M||!T)return;let P=M.getContext("2d");if(!P)return;let z=0,ie=getComputedStyle(M).color||"#000",j=0,F=0,K=0,ye=D=>{if(K<=0||F<=0)return;D-j>500&&(ie=getComputedStyle(M).color||ie,j=D),P.clearRect(0,0,K,F),P.fillStyle=ie;let N=Math.max(1,r),Y=Math.max(0,n),re=N+Y,oe=Math.max(1,Math.floor((K+Y)/re)),Me=Math.ceil(oe/2),qe=_.current;b.current.length!==Me&&(b.current=Array.from({length:Me},()=>0));let it=b.current;if(e&&qe){let de=X.current;(!de||de.length!==qe.frequencyBinCount)&&(de=new Uint8Array(qe.frequencyBinCount),X.current=de),qe.getByteFrequencyData(de);let Oe=Math.max(1,Math.floor(de.length*.025)),bt=Math.max(Oe+1,Math.floor(de.length*.46)),lt=Nr(h,0,4);for(let ge=0;ge<Me;ge+=1){let Pt=Me<=1?0:ge/(Me-1),qt=Math.min(de.length-1,Math.round(Oe+Pt*(bt-Oe))),It=Math.pow((de[qt]??0)/255*lt,.72);it[ge]=Nr((it[ge]??0)*.56+It*.44,0,1)}}else it.fill(0);let dn=Math.max(Za,F*.84),kn=F/2,Et=oe*N+(oe-1)*Y,Je=(K-Et)/2;for(let de=0;de<oe;de+=1){let Oe=Me-1-Math.min(de,oe-1-de),bt=e?it[Oe]??0:0,lt=Math.max(Za,bt*dn),ge=Je+de*re,Pt=kn-lt/2;P.globalAlpha=e?.38+bt*.62:.2,$u(P,ge,Pt,N,lt)}P.globalAlpha=1},Se=()=>{let D=T.getBoundingClientRect(),N=Math.max(1,window.devicePixelRatio||1),Y=getComputedStyle(M).color||ie;K=Math.max(0,D.width),F=Math.max(0,D.height),M.width=Math.max(1,Math.round(K*N)),M.height=Math.max(1,Math.round(F*N)),M.style.width=`${K}px`,M.style.height=`${F}px`,P.setTransform(N,0,0,N,0,0),ie=Y,ye(performance.now())},H=D=>{ye(D),z=requestAnimationFrame(H)};Se();let B;return typeof ResizeObserver>"u"?window.addEventListener("resize",Se):(B=new ResizeObserver(Se),B.observe(T)),e&&(z=requestAnimationFrame(H)),()=>{z&&cancelAnimationFrame(z),B?.disconnect(),window.removeEventListener("resize",Se)}},[e,n,r,h]);let f=typeof c=="number"?`${Math.max(1,c)}px`:c,v={...C,height:f},R=`${Math.max(0,d)}px`,y=`linear-gradient(90deg, transparent 0, #000 min(${R}, 20%), #000 calc(100% - min(${R}, 20%)), transparent 100%)`;return ei("div",{...O,ref:$,"aria-label":t??(e?"Live microphone waveform":"Microphone waveform"),className:me("aui-voice-live-waveform",o),"data-active":e||void 0,"data-fade-edges":i||void 0,"data-slot":"agent-ui-voice-live-waveform",role:u??"img",style:v,children:ei("canvas",{ref:L,"aria-hidden":"true",className:"aui-voice-live-waveform__canvas",style:i?{WebkitMaskImage:y,maskImage:y}:void 0})})}import{useCallback as Ve,useEffect as ti,useRef as $e,useState as _r,useSyncExternalStore as Ku}from"react";var Lr={"audio-capture":"No microphone was found. Check your audio input and try again.","bad-grammar":"Speech recognition could not understand the requested grammar.",language:"Speech recognition is not available for this language.","language-not-supported":"Speech recognition is not available for this language.",network:"Speech recognition lost its network connection. Try again.","no-speech":"No speech was detected. Try again when you are ready.","not-allowed":"Voice dictation was blocked. Check microphone and speech recognition permissions and try again.","service-not-allowed":"Speech recognition is blocked by your browser settings."},ri="Microphone access is blocked for this page. Allow microphone access and try again.",qu="Microphone access is enabled, but speech recognition is blocked in this browser or embedded preview.",Xo="Voice dictation is not supported in this browser.",oi="Voice recording stopped unexpectedly. Try again.",Gu=["audio/webm;codecs=opus","audio/mp4","audio/webm","audio/ogg;codecs=opus"],Qu=/\s+/g;function Dr(e,t){let n=t.trim().replace(Qu," ");return n?!e||/\s$/.test(e)||/^[,.;:!?)]/.test(n)?`${e}${n}`:`${e} ${n}`:e}function Hr(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0,n=t%60,r=Math.floor(t/60),o=r%60,s=Math.floor(r/60),i=String(n).padStart(2,"0");return s>0?`${s}:${String(o).padStart(2,"0")}:${i}`:`${o}:${i}`}function Jo(e,t,n="unknown"){if(e==="not-allowed"){if(n==="denied")return ri;if(n==="granted")return qu}return Lr[e]??(t?.trim()||"Voice dictation stopped unexpectedly.")}async function zu(){if(typeof navigator>"u"||!navigator.permissions?.query)return"unknown";try{return(await navigator.permissions.query({name:"microphone"})).state}catch{return"unknown"}}function si(){if(typeof window>"u")return;let e=window;return e.SpeechRecognition??e.webkitSpeechRecognition}function Wu(){return!!si()}function ni(){return typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof MediaRecorder<"u"}function ju(){if(!(typeof MediaRecorder>"u"||typeof MediaRecorder.isTypeSupported!="function"))return Gu.find(e=>MediaRecorder.isTypeSupported(e))}function Or(e){e?.getTracks().forEach(t=>t.stop())}function Yo(e){if(typeof DOMException<"u"&&e instanceof DOMException){if(e.name==="NotAllowedError"||e.name==="SecurityError")return ri;if(e.name==="NotFoundError"||e.name==="DevicesNotFoundError")return Lr["audio-capture"]}return e instanceof Error&&e.message.trim()?e.message:"Microphone access could not be started."}function Yu(e){return e.error??new Error(oi)}function Xu(){return()=>{}}function Zo({language:e,onValueChange:t,transcribe:n,value:r}){let[o,s]=_r("idle"),[i,d]=_r(0),[l,c]=_r(null),[m,p]=_r(null),S=Ve(()=>n?ni():Wu(),[n]),u=Ku(Xu,S,()=>!1),h=$e("idle"),x=$e(r),w=$e(null),C=$e(e),O=$e(t),_=$e(null),k=$e(null),L=$e(0),$=$e(0),X=$e(n),b=$e(null),f=$e(new Map),v=$e(r);ti(()=>{C.current=e,O.current=t,X.current=n,v.current=r},[e,t,n,r]);let R=Ve(H=>{h.current=H,s(H)},[]),y=Ve(()=>{w.current!==null&&(clearInterval(w.current),w.current=null)},[]),M=Ve(()=>{y(),$.current=Date.now(),d(0),w.current=setInterval(()=>{d(Math.floor((Date.now()-$.current)/1e3))},250)},[y]),T=Ve(H=>{H.onend=null,H.onerror=null,H.onresult=null,H.onstart=null},[]),P=Ve(H=>{H.ondataavailable=null,H.onerror=null,H.onstop=null},[]),z=Ve((H,B)=>{if(P(H.recorder),B&&H.recorder.state!=="inactive")try{H.recorder.stop()}catch{}Or(H.stream)},[P]),ie=Ve(async H=>{if(L.current!==H.session||_.current!==H){z(H,!1);return}_.current=null,P(H.recorder),Or(H.stream),p(null),y(),R("transcribing");let B=H.recorder.mimeType||H.chunks[0]?.type||"audio/webm",D=new Blob(H.chunks,{type:B}),N=X.current;if(!N||D.size===0){R("idle"),c(D.size===0?Lr["no-speech"]:oi);return}let Y=new AbortController;b.current=Y;try{let re=await N(D,{...C.current?{language:C.current}:{},signal:Y.signal});if(L.current!==H.session||Y.signal.aborted)return;if(!re.trim()){c(Lr["no-speech"]);return}O.current(Dr(x.current,re)),c(null)}catch(re){if(L.current!==H.session||Y.signal.aborted)return;c(re instanceof Error&&re.message.trim()?re.message:"Voice transcription could not be completed. Try again.")}finally{b.current===Y&&(b.current=null),L.current===H.session&&R("idle")}},[P,z,y,R]),j=Ve(()=>{L.current+=1,y(),b.current?.abort(),b.current=null,c(null),p(null),R("idle");let H=_.current,B=k.current;if(_.current=null,k.current=null,f.current.clear(),H&&z(H,!0),!!B){T(B);try{B.abort()}catch{}}},[T,z,y,R]),F=Ve(()=>{if(h.current==="transcribing"){j();return}let H=_.current;if(H){y(),R("transcribing");try{H.recorder.stop()}catch(D){L.current+=1,_.current=null,z(H,!1),p(null),R("idle"),c(D instanceof Error?D.message:"Voice recording could not be stopped cleanly.")}return}if(h.current==="recording"){j();return}let B=k.current;if(B){y();try{B.stop()}catch(D){R("idle"),L.current+=1,k.current=null,f.current.clear(),T(B);try{B.abort()}catch{}c(D instanceof Error?D.message:"Voice dictation could not be stopped cleanly.")}}},[j,T,z,y,R]),K=Ve(async()=>{if(!ni()){c(Xo);return}let H=L.current+1;L.current=H,x.current=v.current,c(null),d(0),p(null),R("recording");let B;try{B=await navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0}})}catch(Y){if(L.current!==H)return;R("idle"),c(Yo(Y));return}if(L.current!==H){Or(B);return}let D;try{let Y=ju();D=Y?new MediaRecorder(B,{mimeType:Y}):new MediaRecorder(B)}catch(Y){if(Or(B),L.current!==H)return;R("idle"),c(Yo(Y));return}let N={chunks:[],recorder:D,session:H,stream:B};D.ondataavailable=Y=>{Y.data.size>0&&N.chunks.push(Y.data)},D.onerror=Y=>{L.current!==H||_.current!==N||(L.current+=1,_.current=null,y(),z(N,!0),p(null),R("idle"),c(Yu(Y).message))},D.onstop=()=>{ie(N)},_.current=N,p(B);try{D.start(1e3),M()}catch(Y){L.current+=1,_.current=null,z(N,!1),p(null),R("idle"),c(Yo(Y))}},[z,ie,M,y,R]),ye=Ve(()=>{let H=si();if(!H){c(Xo);return}let B;try{B=new H}catch(N){c(N instanceof Error?N.message:"Voice dictation could not be started.");return}let D=L.current+1;L.current=D,x.current=v.current,f.current=new Map,B.continuous=!0,B.interimResults=!0,B.maxAlternatives=1,C.current&&(B.lang=C.current),B.onstart=()=>{L.current===D&&(R("recognizing"),M())},B.onresult=N=>{if(L.current!==D)return;let Y=Math.max(0,N.resultIndex);for(let oe of f.current.keys())oe>=Y&&f.current.delete(oe);for(let oe=Y;oe<N.results.length;oe+=1){let qe=N.results[oe]?.[0]?.transcript;typeof qe=="string"&&f.current.set(oe,qe)}let re=Array.from(f.current.entries()).sort(([oe],[Me])=>oe-Me).map(([,oe])=>oe).reduce(Dr,"");O.current(Dr(x.current,re))},B.onerror=N=>{if(L.current!==D)return;y(),R("idle"),f.current.clear(),L.current+=1;let Y=L.current;N.error!=="aborted"&&(N.error==="not-allowed"?zu().then(re=>{L.current===Y&&c(Jo(N.error,N.message,re))}):c(Jo(N.error,N.message))),k.current===B&&(k.current=null,T(B))},B.onend=()=>{L.current===D&&(y(),R("idle"),k.current===B&&(k.current=null,T(B)))},k.current=B,c(null),d(0),R("recognizing");try{B.start()}catch(N){T(B),k.current=null,y(),R("idle"),c(N instanceof Error?N.message:"Voice dictation could not be started.")}},[T,M,y,R]),Se=Ve(()=>{h.current!=="idle"||k.current||_.current||b.current||(X.current?K():ye())},[ye,K]);return ti(()=>()=>{L.current+=1,y(),b.current?.abort(),b.current=null;let H=_.current,B=k.current;if(_.current=null,k.current=null,H&&z(H,!0),!!B){T(B);try{B.abort()}catch{}}},[T,z,y]),{cancel:j,elapsedSeconds:i,error:l,isActive:o!=="idle",isRecording:o==="recording",isSupported:u,isTranscribing:o==="transcribing",start:Se,stop:F,stream:m}}import{Spinner as Lg}from"@heroui/react/spinner";import{isTerminalCloseEvent as Hg}from"agents/client";import{useAgent as Ug}from"agents/react";import{Suspense as Bg,useCallback as W,useEffect as be,useEffectEvent as $t,useId as Fg,useLayoutEffect as Kt,useMemo as Ae,useRef as ue,useState as ee}from"react";import{z as te}from"zod";var Ju=te.enum(["light","dark","system"]),Zu=te.enum(["outline","plain","surface","surface-secondary"]),ed=new Set(["[object object]","0","anonymous","distinct_id","distinctid","email","false","guest","id","nan","none","not_authenticated","null","true","undefined"]),es=te.string().trim().min(1).max(200).refine(e=>!ed.has(e.toLowerCase()),{message:"Identity id is reserved"}),td=te.discriminatedUnion("type",[te.object({id:es,type:te.literal("anonymous")}),te.object({id:es,type:te.literal("user")})]),nd=te.object({avatarUrl:te.string().trim().pipe(te.url()).optional(),email:te.string().trim().max(320).pipe(te.email()).optional(),name:te.string().trim().max(120).optional()}),Ff=te.object({anonymousId:es.optional(),identity:td,profile:nd.optional()}),Vf=te.object({expiresAt:te.number().int().positive(),token:te.string().trim().min(1)}),$f=te.object({agentId:te.string().trim().min(1).max(100),apiKeyId:te.string().trim().min(1).max(100),aud:te.literal("heroui-agent"),exp:te.number().int().positive(),iat:te.number().int().positive(),iss:te.literal("https://api.heroui.com"),jti:te.uuid(),protocolVersion:te.literal(6),sub:te.string().trim().min(1).max(200)});var Ur=te.object({agentId:te.string(),minimumProtocolVersion:te.literal(6),name:te.string().trim().min(1).max(120),protocolVersion:te.literal(6),sdkVersion:te.string().default(We),suggestedPrompts:te.array(te.string().trim().min(1).max(160)).max(5),surfaceVariant:Zu.default("plain"),theme:Ju});var rd="understanding your request";function od(e){let t=e.replace(/\r\n?/g,`
1
+ "use client";import{a as Oo,b as Do,d as Ho}from"./chunk-CLHBM3HQ.js";import{a as Ha,c as Sn}from"./chunk-S6OIAJSC.js";import{a as me}from"./chunk-CR3H7AVI.js";import{A as Rr,B as Mr,C as _o,D as bn,E as La,b as We,d as Ca,e as $n,g as Aa,h as Ta,i as Eo,j as Po,m as Ea,n as Pa,o as Kn,p as Ia,q as xa,r as ka,s as ko,t as Na,u as _a,v as Oa,w as tn,x as Da,y as Tr,z as No}from"./chunk-EJIPFUZ2.js";import{a as Io}from"./chunk-6ZJJN322.js";import{b as ba,c as Ar,d as Sa}from"./chunk-64RI74L5.js";import{c as Ra,d as Ma,e as xo,f as wa}from"./chunk-UHHKMESI.js";import{a as Ua,b as Ba,c as Fa,d as Lo}from"./chunk-7KCGPNEN.js";import"./chunk-4JEZZR5J.js";import{a as Bo,b as $a,c as Ka,d as wr}from"./chunk-RNNGE7KM.js";import{a as Va,b as Uo}from"./chunk-PZJ4NC3J.js";import{useAgentChat as Ng}from"@cloudflare/ai-chat/react";import{ArrowUp as _g,ArrowUpRight as Og,Microphone as Uc,Plus as Bc,StopFill as Oc,Xmark as Dg}from"@gravity-ui/icons";function Mt(e){return!!(e&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e))}function Fo(e,t){return e===null?null:typeof e=="string"?Mt(e)?e:null:Mt(t)?t:null}var Er=30,qa=52;function Vo(e){try{let t=JSON.parse(localStorage.getItem(e)??"[]");return Pr(t)}catch{return[]}}function Pr(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object"&&"id"in t&&typeof t.id=="string"&&Mt(t.id)&&"title"in t&&typeof t.title=="string"&&"updatedAt"in t&&typeof t.updatedAt=="number")).sort((t,n)=>n.updatedAt-t.updatedAt).slice(0,Er):[]}function $o(e,t){let n=new Map(e.map(r=>[r.id,r]));for(let r of t){let o=n.get(r.id);(!o||r.updatedAt>=o.updatedAt)&&n.set(r.id,r)}return[...n.values()].sort((r,o)=>o.updatedAt-r.updatedAt).slice(0,Er)}function Nt(e,t){localStorage.setItem(e,JSON.stringify(t.slice(0,Er)))}function qn(e,t,n,r,{replaceTitle:o=!1}={}){if(!n)return e;let s=e.find(d=>d.id===t);return[{id:t,title:o?n:s?.title??n,updatedAt:r},...e.filter(d=>d.id!==t)].sort((d,l)=>l.updatedAt-d.updatedAt).slice(0,Er)}function Ir(e){let t=e?.find(r=>r.role==="user"),n=t?.parts.filter(r=>r.type==="text").map(r=>r.text??"").join(" ");return n?.trim()?qo(n):t?"Attachment":null}function Ko(e,t){return e?qo(e):t[0]?.name||"Attachment"}function qo(e){let t=e.replace(/\s+/g," ").trim();return t.length>qa?`${t.slice(0,qa-1).trimEnd()}\u2026`:t}function Go(e){let t=new Date;t.setHours(0,0,0,0);let n=t.getTime(),r=n-8640*60*1e3,o=[{items:[],label:"Today"},{items:[],label:"Previous 7 days"},{items:[],label:"Older"}];for(let s of e)s.updatedAt>=n?o[0].items.push(s):s.updatedAt>=r?o[1].items.push(s):o[2].items.push(s);return o.filter(s=>s.items.length>0)}import{Disclosure as Cn}from"@heroui/react";import{jsx as Fe,jsxs as nn}from"react/jsx-runtime";function vu(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase().replace(/^\w/,t=>t.toUpperCase())}function bu(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=Object.entries(e);return t.length===0||t.some(([,n])=>typeof n=="object")?null:t.map(([n,r])=>[vu(n),String(r)])}function Ga({approveLabel:e="Allow",className:t,denyLabel:n="Deny",hint:r="Waiting for your approval",icon:o,input:s,onApprove:i,onDeny:d,title:l,...c}){let m=bu(s),p=s!=null&&(typeof s!="object"||Object.keys(s).length>0);return nn("section",{"aria-label":l,className:me("aui-approval",t),"data-slot":"agent-ui-approval",...c,children:[nn("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,nn("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?nn(Cn,{defaultExpanded:!0,className:"aui-approval__disclosure",children:[Fe(Cn.Heading,{children:nn(Cn.Trigger,{className:"aui-approval__disclosure-trigger",children:["Review action details",Fe(Cn.Indicator,{})]})}),Fe(Cn.Content,{children:Fe(Cn.Body,{children:m?Fe("dl",{className:"aui-approval__details","data-slot":"agent-ui-approval-details",children:m.map(([S,u])=>nn("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,nn("div",{className:"aui-approval__actions","data-slot":"agent-ui-approval-actions",children:[Fe(Oo,{size:"md",variant:"tertiary",onClick:d,children:n}),Fe(Oo,{size:"md",variant:"primary",onClick:i,children:e})]})]})}import{Description as Mu,Label as wu,ListBox as Qo,Select as Qn}from"@heroui/react";import{useCallback as Eu,useEffect as Pu,useRef as za,useState as Wa}from"react";import{useId as Su}from"react";import{jsx as G,jsxs as Gn}from"react/jsx-runtime";function Qa({className:e,provider:t}){let n=t?.toLowerCase();return n==="openai"?G(Cu,{className:e,"data-provider":"openai"}):n==="google"?G(Au,{className:e,"data-provider":"google"}):n==="anthropic"?G(Tu,{className:e,"data-provider":"anthropic"}):n==="moonshot ai"?G(Ru,{className:e,"data-provider":"moonshot-ai"}):null}function Cu(e){return G("svg",{"aria-hidden":"true",fill:"currentColor",focusable:"false",role:"presentation",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",...e,children:G("path",{d:"M22.282 9.821a5.985 5.985 0 0 0-.516-4.911 6.046 6.046 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.182a5.985 5.985 0 0 0-3.998 2.9 6.046 6.046 0 0 0 .743 7.096 5.98 5.98 0 0 0 .511 4.911 6.051 6.051 0 0 0 6.515 2.9A5.985 5.985 0 0 0 13.26 24a6.056 6.056 0 0 0 5.772-4.206 5.99 5.99 0 0 0 3.997-2.9 6.056 6.056 0 0 0-.747-7.073m-9.022 12.608a4.476 4.476 0 0 1-2.877-1.041l.142-.08 4.778-2.758a.795.795 0 0 0 .393-.682v-6.737l2.02 1.169a.07.07 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494M3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085 4.783 2.758a.77.77 0 0 0 .781 0l5.843-3.368v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.141-1.646M2.341 7.896a4.485 4.485 0 0 1 2.365-1.973V11.6a.766.766 0 0 0 .388.677l5.814 3.354-2.02 1.169a.08.08 0 0 1-.071 0l-4.83-2.787A4.504 4.504 0 0 1 2.34 7.872zm16.596 3.856-5.833-3.388L15.119 7.2a.08.08 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.104v-5.677a.79.79 0 0 0-.407-.667m2.011-3.023-.142-.085-4.773-2.782a.776.776 0 0 0-.786 0L9.409 9.23V6.897a.07.07 0 0 1 .028-.061l4.83-2.787a4.499 4.499 0 0 1 6.68 4.66zM8.307 12.863l-2.02-1.164a.08.08 0 0 1-.038-.056V6.074a4.499 4.499 0 0 1 7.376-3.453l-.142.08-4.778 2.758a.795.795 0 0 0-.393.682zm1.098-2.365 2.602-1.5 2.607 1.5v2.999l-2.598 1.5-2.607-1.5Z"})})}function Au(e){let t=Su().replace(/:/g,""),n=`${t}-gemini-shape`,r=`${t}-gemini-mask`,o=`${t}-gemini-yellow-blur`,s=`${t}-gemini-red-blur`,i=`${t}-gemini-green-blur`,d=`${t}-gemini-blue-blur`,l=`${t}-gemini-gold-blur`,c=`${t}-gemini-cyan-blur`,m=`${t}-gemini-violet-blur`,p=`${t}-gemini-coral-blur`,S=`${t}-gemini-lemon-blur`;return Gn("svg",{"aria-hidden":"true",fill:"none",focusable:"false",role:"presentation",viewBox:"0 0 32 32",xmlns:"http://www.w3.org/2000/svg",...e,children:[G("path",{d:"M0 0h32v32H0z",fill:"none"}),G("defs",{children:G("path",{d:"M57.067 28.61q-7.396-3.184-12.945-8.732q-5.547-5.546-8.732-12.944a38.4 38.4 0 0 1-1.97-5.824A1.464 1.464 0 0 0 32 .001c-.671 0-1.255.458-1.419 1.11a38.4 38.4 0 0 1-1.971 5.823q-3.186 7.397-8.732 12.944q-5.548 5.548-12.945 8.732a38.4 38.4 0 0 1-5.824 1.972A1.464 1.464 0 0 0 0 32c0 .67.458 1.255 1.11 1.418a38.4 38.4 0 0 1 5.823 1.972q7.396 3.184 12.945 8.732q5.55 5.546 8.732 12.944a38.4 38.4 0 0 1 1.971 5.824c.164.65.749 1.11 1.419 1.11s1.255-.458 1.419-1.11a38.4 38.4 0 0 1 1.971-5.823q3.185-7.395 8.732-12.944q5.548-5.548 12.945-8.732a38.4 38.4 0 0 1 5.824-1.972A1.464 1.464 0 0 0 64 32.001c0-.672-.458-1.255-1.11-1.42a38.4 38.4 0 0 1-5.823-1.97",fill:"#fff",id:n})}),Gn("g",{fill:"none",children:[Gn("g",{mask:`url(#${r})`,transform:"translate(2 2)scale(.4375)",children:[G("use",{href:`#${n}`}),G("g",{filter:`url(#${o})`,children:G("ellipse",{cx:"14.208",cy:"16.716",fill:"#ffe432",rx:"14.208",ry:"16.716",transform:"rotate(19.552 -43.96 -16.268)"})}),G("g",{filter:`url(#${s})`,children:G("ellipse",{cx:"27.054",cy:"2.551",fill:"#fc413d",rx:"18.394",ry:"18.799"})}),G("g",{filter:`url(#${i})`,children:G("ellipse",{cx:"19.224",cy:"24.904",fill:"#00b95c",rx:"19.224",ry:"24.904",transform:"rotate(-2.799 667.58 51.694)"})}),G("g",{filter:`url(#${i})`,children:G("ellipse",{cx:"18.843",cy:"20.744",fill:"#00b95c",rx:"18.843",ry:"20.744",transform:"rotate(-31.317 81.174 36.482)"})}),G("g",{filter:`url(#${d})`,children:G("ellipse",{cx:"66.462",cy:"24.977",fill:"#3186ff",rx:"18.093",ry:"17.423"})}),G("g",{filter:`url(#${l})`,children:G("ellipse",{cx:"20.929",cy:"22.075",fill:"#fbbc04",rx:"20.929",ry:"22.075",transform:"rotate(37.251 9.618 -7.898)"})}),G("g",{filter:`url(#${c})`,children:G("ellipse",{cx:"24.131",cy:"22.292",fill:"#3186ff",rx:"24.131",ry:"22.292",transform:"rotate(34.51 19.317 63.957)"})}),G("g",{filter:`url(#${m})`,children:G("path",{d:"M54.226-2.304c2.794 3.799-.797 11.184-8.02 16.497c-7.222 5.312-15.342 6.539-18.136 2.74S28.866 5.75 36.09.436c7.223-5.312 15.343-6.539 18.136-2.74",fill:"#749bff"})}),G("g",{filter:`url(#${p})`,children:G("ellipse",{cx:"27.585",cy:"17.148",fill:"#fc413d",rx:"27.585",ry:"17.148",transform:"rotate(-42.847 5.973 20.37)"})}),G("g",{filter:`url(#${S})`,children:G("ellipse",{cx:"14.782",cy:"8.596",fill:"#ffee48",rx:"14.782",ry:"8.596",transform:"rotate(35.592 -44.338 25.191)"})})]}),Gn("defs",{children:[G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"42.756",id:o,width:"38.868",x:"-19.618",y:"12.903",children:G("feGaussianBlur",{stdDeviation:"2.46"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"85.162",id:s,width:"84.353",x:"-15.122",y:"-40.03",children:G("feGaussianBlur",{stdDeviation:"11.891"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"90.22",id:i,width:"78.916",x:"-20.768",y:"11.483",children:G("feGaussianBlur",{stdDeviation:"10.109"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"73.27",id:d,width:"74.611",x:"29.156",y:"-11.658",children:G("feGaussianBlur",{stdDeviation:"9.606"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"78.151",id:l,width:"77.538",x:"-38.291",y:"-16.269",children:G("feGaussianBlur",{stdDeviation:"8.706"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"76.898",id:c,width:"78.218",x:"7.78",y:"-6.098",children:G("feGaussianBlur",{stdDeviation:"7.775"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"51.479",id:m,width:"55.879",x:"13.208",y:"-18.425",children:G("feGaussianBlur",{stdDeviation:"6.957"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"68.674",id:p,width:"70.203",x:"-15.474",y:"-31.027",children:G("feGaussianBlur",{stdDeviation:"5.876"})}),G("filter",{colorInterpolationFilters:"sRGB",filterUnits:"userSpaceOnUse",height:"51.261",id:S,width:"55.137",x:"-14.173",y:"20.474",children:G("feGaussianBlur",{stdDeviation:"7.273"})}),G("mask",{height:"64",id:r,maskUnits:"userSpaceOnUse",width:"64",x:"0",y:"0",children:G("use",{href:`#${n}`})})]})]})]})}function Tu(e){return G("svg",{"aria-hidden":"true",fill:"none",focusable:"false",role:"presentation",viewBox:"0 0 256 257",xmlns:"http://www.w3.org/2000/svg",...e,children:G("path",{d:"m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0l10.63 1.426 4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999z",fill:"#d97757"})})}function Ru(e){return Gn("svg",{"aria-hidden":"true",clipRule:"evenodd",fillRule:"evenodd",focusable:"false",role:"presentation",strokeLinejoin:"round",strokeMiterlimit:2,viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",...e,children:[G("path",{d:"M503 114.333v280c0 60.711-49.29 110-110 110H113c-60.711 0-110-49.289-110-110v-280c0-60.71 49.289-110 110-110h280c60.71 0 110 49.29 110 110z"}),G("path",{d:"M342.065 189.759c1.886-2.42 3.541-4.63 5.289-6.77.81-1.007.74-1.771-.046-2.824-7.58-9.965-8.298-21.028-3.935-32.254 3.275-8.448 10.52-12.406 19.373-13.25 5.52-.521 10.936.046 15.959 2.73 6.596 3.53 10.438 8.912 11.688 16.341.995 5.926.81 11.712-.868 17.452-2.974 10.161-10.277 15.427-20.287 16.758-8.31 1.11-16.734 1.25-25.113 1.817-.648.046-1.308 0-2.06 0z",fill:"#027aff"}),G("path",{d:"M321.512 144.254h-50.064l-39.637 90.384h-56.036v-89.99H131v232.868h44.787v-98.103h78.973c13.598 0 26.015-7.927 31.744-20.252v118.355h44.787v-98.103c0-23.342-18.239-42.97-41.523-44.671v-.116h-24.593a45.577 45.577 0 0026.884-24.534l29.453-65.838z",fill:"#fff"})]})}import{jsx as ft,jsxs as zn}from"react/jsx-runtime";function Iu({description:e,provider:t}){return t?e?`${t} \xB7 ${e}`:t:e}function xr({"aria-label":e="AI model",className:t,isDisabled:n=!1,onChange:r,options:o,placement:s="top start",value:i}){let[d,l]=Wa(!1),[c,m]=Wa(),p=za(0),S=za(null),u=n||o.length===0,h=o.find(C=>C.id===i),x=Eu(C=>{S.current=C,C?.setAttribute("aria-keyshortcuts","Control+Shift+M"),m(Sn(C))},[]),w=C=>{!C&&Date.now()-p.current<350||l(C)};return Pu(()=>{if(u)return;let C=O=>{O.defaultPrevented||O.isComposing||O.repeat||!O.ctrlKey||!O.shiftKey||O.altKey||O.metaKey||O.key.toLowerCase()!=="m"||(O.preventDefault(),S.current?.focus(),l(!0))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[u]),zn(Qn,{"aria-label":e,className:me("aui-model-picker",t),isDisabled:u,isOpen:d,value:i,onOpenChange:w,onChange:C=>{C!=null&&r(C),l(!1)},children:[zn(Qn.Trigger,{ref:x,className:"aui-model-picker__trigger","data-shortcut":"\u2303\u21E7M","data-slot":"agent-ui-model-picker-trigger","data-tooltip":"Select model",onPointerDown:()=>{p.current=Date.now()},children:[ft(Qn.Value,{className:"aui-model-picker__value",children:h?.label??i}),ft(Qn.Indicator,{className:"aui-model-picker__indicator"}),zn("span",{"aria-hidden":"true",className:"aui-picker-tooltip",children:[ft("span",{children:"Select model"}),ft("kbd",{className:"aui-picker-tooltip__shortcut",children:"\u2303\u21E7M"})]})]}),ft(Qn.Popover,{className:"aui-model-picker__popover",placement:s,UNSTABLE_portalContainer:c,children:ft(Qo,{"aria-label":`${e} options`,className:"aui-model-picker__list",children:o.map(C=>{let O=Iu(C);return zn(Qo.Item,{className:"aui-model-picker__option","data-description":O,id:C.id,textValue:C.label,children:[ft(Qa,{className:"aui-model-picker__option-icon",provider:C.provider}),zn("span",{className:"aui-model-picker__option-copy",children:[ft(wu,{className:"aui-model-picker__option-label",children:C.label}),O?ft(Mu,{className:"aui-model-picker__option-description",title:O,children:O}):null]}),ft(Qo.ItemIndicator,{className:"aui-model-picker__option-indicator"})]},C.id)})})})]})}import{Hand as xu,LockOpen as ku,ShieldCheck as Ja}from"@gravity-ui/icons";import{Description as Nu,Label as _u,ListBox as zo,Select as Wn}from"@heroui/react";import{useCallback as Ou,useEffect as Du,useRef as ja,useState as Ya}from"react";import{jsx as ot,jsxs as jn}from"react/jsx-runtime";var Xa=[{description:"Ask before every client tool action.",icon:xu,id:"ask",label:"Ask for approval"},{description:"Only ask for actions marked as needing approval.",icon:Ja,id:"auto",label:"Approve for me"},{description:"Run client tools without asking for approval.",icon:ku,id:"full",label:"Full access"}];function kr({"aria-label":e="Tool permissions",className:t,isDisabled:n=!1,onChange:r,value:o}){let[s,i]=Ya(!1),[d,l]=Ya(),c=ja(0),m=ja(null),p=Xa.find(h=>h.id===o),S=Ou(h=>{m.current=h,h?.setAttribute("aria-keyshortcuts","Control+Shift+P"),l(Sn(h))},[]),u=h=>{!h&&Date.now()-c.current<350||i(h)};return Du(()=>{if(n)return;let h=x=>{x.defaultPrevented||x.isComposing||x.repeat||!x.ctrlKey||!x.shiftKey||x.altKey||x.metaKey||x.key.toLowerCase()!=="p"||(x.preventDefault(),m.current?.focus(),i(!0))};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[n]),jn(Wn,{"aria-label":e,className:me("aui-permission-picker",t),"data-tone":o==="full"?"warning":void 0,isDisabled:n,isOpen:s,value:o,onOpenChange:u,onChange:h=>{h!=null&&r(h),i(!1)},children:[jn(Wn.Trigger,{ref:S,className:"aui-permission-picker__trigger","data-shortcut":"\u2303\u21E7P","data-slot":"agent-ui-permission-picker-trigger","data-tooltip":"Change permissions",onPointerDown:()=>{c.current=Date.now()},children:[ot(Ja,{"aria-hidden":"true",className:"aui-permission-picker__trigger-icon"}),ot(Wn.Value,{className:"aui-permission-picker__value",children:p?.label??o}),ot(Wn.Indicator,{className:"aui-permission-picker__indicator"}),jn("span",{"aria-hidden":"true",className:"aui-picker-tooltip",children:[ot("span",{children:"Change permissions"}),ot("kbd",{className:"aui-picker-tooltip__shortcut",children:"\u2303\u21E7P"})]})]}),ot(Wn.Popover,{className:"aui-permission-picker__popover",placement:"top start",UNSTABLE_portalContainer:d,children:ot(zo,{"aria-label":`${e} options`,className:"aui-permission-picker__list",children:Xa.map(h=>{let x=h.icon;return jn(zo.Item,{className:"aui-permission-picker__option","data-description":h.description,"data-tone":h.id==="full"?"warning":void 0,id:h.id,textValue:h.label,children:[ot(x,{"aria-hidden":"true",className:"aui-permission-picker__option-icon"}),jn("span",{className:"aui-permission-picker__option-copy",children:[ot(_u,{className:"aui-permission-picker__option-label",children:h.label}),ot(Nu,{className:"aui-permission-picker__option-description",title:h.description,children:h.description})]}),ot(zo.ItemIndicator,{className:"aui-permission-picker__option-indicator"})]},h.id)})})})]})}import{useEffect as Wo,useRef as An}from"react";import{jsx as ei}from"react/jsx-runtime";var Lu=40,Za=2;function Nr(e,t,n){return Math.min(n,Math.max(t,e))}function Hu(e){let t=Nr(Math.round(e),32,32768);return 2**Math.round(Math.log2(t))}function Uu(e){return e instanceof Error?e:new Error("Unable to access the microphone.")}function Bu(){let e=window;return e.AudioContext??e.webkitAudioContext}function Fu(e){e?.getTracks().forEach(t=>t.stop())}function Vu(e){if(!(!e||e.state==="closed"))try{e.close().catch(()=>{})}catch{}}function $u(e,t,n,r,o){let s=Math.min(r/2,o/2);if(typeof e.roundRect!="function"){e.fillRect(t,n,r,o);return}e.beginPath(),e.roundRect(t,n,r,o,s),e.fill()}function jo({active:e=!1,"aria-label":t,barGap:n=2,barWidth:r=2,className:o,deviceId:s,fadeEdges:i=!0,fadeWidth:d=20,fftSize:l=256,height:c=Lu,onError:m,onStreamEnd:p,onStreamReady:S,role:u,sensitivity:h=1.15,smoothingTimeConstant:x=.82,stream:w,style:C,...O}){let _=An(null),k=An({onError:m,onStreamEnd:p,onStreamReady:S}),L=An(null),$=An(null),X=An(null),b=An([]);Wo(()=>{k.current={onError:m,onStreamEnd:p,onStreamReady:S}},[m,p,S]),Wo(()=>{if(!e||w===null){_.current=null;return}let M,T=!1,P=!1,z=!1,ie=w===void 0,j,F=w,K=Se=>{try{j?.disconnect()}catch{}j=void 0,_.current?.context===M&&(_.current=null),Vu(M),M=void 0,ie&&Fu(F),F=void 0,Se&&P&&!z&&(z=!0,k.current.onStreamEnd?.())};return(async()=>{try{let Se=Bu();if(!Se)throw new Error("Live audio analysis is not supported in this browser.");if(!F){if(!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone capture is not supported in this browser.");F=await navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,...s?{deviceId:{exact:s}}:{},echoCancellation:!0,noiseSuppression:!0}})}if(T){K(!1);return}M=new Se;let H=M.createAnalyser();if(H.fftSize=Hu(l),H.smoothingTimeConstant=Nr(x,0,1),j=M.createMediaStreamSource(F),j.connect(H),M.state==="suspended"&&await M.resume(),T){K(!1);return}_.current=H,X.current=new Uint8Array(H.frequencyBinCount),P=!0,k.current.onStreamReady?.(F)}catch(Se){K(!1),T||k.current.onError?.(Uu(Se))}})(),()=>{T=!0,K(!0)}},[e,s,l,w,x]),Wo(()=>{let M=L.current,T=$.current;if(!M||!T)return;let P=M.getContext("2d");if(!P)return;let z=0,ie=getComputedStyle(M).color||"#000",j=0,F=0,K=0,ye=D=>{if(K<=0||F<=0)return;D-j>500&&(ie=getComputedStyle(M).color||ie,j=D),P.clearRect(0,0,K,F),P.fillStyle=ie;let N=Math.max(1,r),Y=Math.max(0,n),re=N+Y,oe=Math.max(1,Math.floor((K+Y)/re)),Me=Math.ceil(oe/2),qe=_.current;b.current.length!==Me&&(b.current=Array.from({length:Me},()=>0));let it=b.current;if(e&&qe){let de=X.current;(!de||de.length!==qe.frequencyBinCount)&&(de=new Uint8Array(qe.frequencyBinCount),X.current=de),qe.getByteFrequencyData(de);let Oe=Math.max(1,Math.floor(de.length*.025)),bt=Math.max(Oe+1,Math.floor(de.length*.46)),lt=Nr(h,0,4);for(let ge=0;ge<Me;ge+=1){let Pt=Me<=1?0:ge/(Me-1),qt=Math.min(de.length-1,Math.round(Oe+Pt*(bt-Oe))),It=Math.pow((de[qt]??0)/255*lt,.72);it[ge]=Nr((it[ge]??0)*.56+It*.44,0,1)}}else it.fill(0);let dn=Math.max(Za,F*.84),kn=F/2,Et=oe*N+(oe-1)*Y,Je=(K-Et)/2;for(let de=0;de<oe;de+=1){let Oe=Me-1-Math.min(de,oe-1-de),bt=e?it[Oe]??0:0,lt=Math.max(Za,bt*dn),ge=Je+de*re,Pt=kn-lt/2;P.globalAlpha=e?.38+bt*.62:.2,$u(P,ge,Pt,N,lt)}P.globalAlpha=1},Se=()=>{let D=T.getBoundingClientRect(),N=Math.max(1,window.devicePixelRatio||1),Y=getComputedStyle(M).color||ie;K=Math.max(0,D.width),F=Math.max(0,D.height),M.width=Math.max(1,Math.round(K*N)),M.height=Math.max(1,Math.round(F*N)),M.style.width=`${K}px`,M.style.height=`${F}px`,P.setTransform(N,0,0,N,0,0),ie=Y,ye(performance.now())},H=D=>{ye(D),z=requestAnimationFrame(H)};Se();let B;return typeof ResizeObserver>"u"?window.addEventListener("resize",Se):(B=new ResizeObserver(Se),B.observe(T)),e&&(z=requestAnimationFrame(H)),()=>{z&&cancelAnimationFrame(z),B?.disconnect(),window.removeEventListener("resize",Se)}},[e,n,r,h]);let f=typeof c=="number"?`${Math.max(1,c)}px`:c,v={...C,height:f},R=`${Math.max(0,d)}px`,y=`linear-gradient(90deg, transparent 0, #000 min(${R}, 20%), #000 calc(100% - min(${R}, 20%)), transparent 100%)`;return ei("div",{...O,ref:$,"aria-label":t??(e?"Live microphone waveform":"Microphone waveform"),className:me("aui-voice-live-waveform",o),"data-active":e||void 0,"data-fade-edges":i||void 0,"data-slot":"agent-ui-voice-live-waveform",role:u??"img",style:v,children:ei("canvas",{ref:L,"aria-hidden":"true",className:"aui-voice-live-waveform__canvas",style:i?{WebkitMaskImage:y,maskImage:y}:void 0})})}import{useCallback as Ve,useEffect as ti,useRef as $e,useState as _r,useSyncExternalStore as Ku}from"react";var Lr={"audio-capture":"No microphone was found. Check your audio input and try again.","bad-grammar":"Speech recognition could not understand the requested grammar.",language:"Speech recognition is not available for this language.","language-not-supported":"Speech recognition is not available for this language.",network:"Speech recognition lost its network connection. Try again.","no-speech":"No speech was detected. Try again when you are ready.","not-allowed":"Voice dictation was blocked. Check microphone and speech recognition permissions and try again.","service-not-allowed":"Speech recognition is blocked by your browser settings."},ri="Microphone access is blocked for this page. Allow microphone access and try again.",qu="Microphone access is enabled, but speech recognition is blocked in this browser or embedded preview.",Xo="Voice dictation is not supported in this browser.",oi="Voice recording stopped unexpectedly. Try again.",Gu=["audio/webm;codecs=opus","audio/mp4","audio/webm","audio/ogg;codecs=opus"],Qu=/\s+/g;function Dr(e,t){let n=t.trim().replace(Qu," ");return n?!e||/\s$/.test(e)||/^[,.;:!?)]/.test(n)?`${e}${n}`:`${e} ${n}`:e}function Hr(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0,n=t%60,r=Math.floor(t/60),o=r%60,s=Math.floor(r/60),i=String(n).padStart(2,"0");return s>0?`${s}:${String(o).padStart(2,"0")}:${i}`:`${o}:${i}`}function Jo(e,t,n="unknown"){if(e==="not-allowed"){if(n==="denied")return ri;if(n==="granted")return qu}return Lr[e]??(t?.trim()||"Voice dictation stopped unexpectedly.")}async function zu(){if(typeof navigator>"u"||!navigator.permissions?.query)return"unknown";try{return(await navigator.permissions.query({name:"microphone"})).state}catch{return"unknown"}}function si(){if(typeof window>"u")return;let e=window;return e.SpeechRecognition??e.webkitSpeechRecognition}function Wu(){return!!si()}function ni(){return typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof MediaRecorder<"u"}function ju(){if(!(typeof MediaRecorder>"u"||typeof MediaRecorder.isTypeSupported!="function"))return Gu.find(e=>MediaRecorder.isTypeSupported(e))}function Or(e){e?.getTracks().forEach(t=>t.stop())}function Yo(e){if(typeof DOMException<"u"&&e instanceof DOMException){if(e.name==="NotAllowedError"||e.name==="SecurityError")return ri;if(e.name==="NotFoundError"||e.name==="DevicesNotFoundError")return Lr["audio-capture"]}return e instanceof Error&&e.message.trim()?e.message:"Microphone access could not be started."}function Yu(e){return e.error??new Error(oi)}function Xu(){return()=>{}}function Zo({language:e,onValueChange:t,transcribe:n,value:r}){let[o,s]=_r("idle"),[i,d]=_r(0),[l,c]=_r(null),[m,p]=_r(null),S=Ve(()=>n?ni():Wu(),[n]),u=Ku(Xu,S,()=>!1),h=$e("idle"),x=$e(r),w=$e(null),C=$e(e),O=$e(t),_=$e(null),k=$e(null),L=$e(0),$=$e(0),X=$e(n),b=$e(null),f=$e(new Map),v=$e(r);ti(()=>{C.current=e,O.current=t,X.current=n,v.current=r},[e,t,n,r]);let R=Ve(H=>{h.current=H,s(H)},[]),y=Ve(()=>{w.current!==null&&(clearInterval(w.current),w.current=null)},[]),M=Ve(()=>{y(),$.current=Date.now(),d(0),w.current=setInterval(()=>{d(Math.floor((Date.now()-$.current)/1e3))},250)},[y]),T=Ve(H=>{H.onend=null,H.onerror=null,H.onresult=null,H.onstart=null},[]),P=Ve(H=>{H.ondataavailable=null,H.onerror=null,H.onstop=null},[]),z=Ve((H,B)=>{if(P(H.recorder),B&&H.recorder.state!=="inactive")try{H.recorder.stop()}catch{}Or(H.stream)},[P]),ie=Ve(async H=>{if(L.current!==H.session||_.current!==H){z(H,!1);return}_.current=null,P(H.recorder),Or(H.stream),p(null),y(),R("transcribing");let B=H.recorder.mimeType||H.chunks[0]?.type||"audio/webm",D=new Blob(H.chunks,{type:B}),N=X.current;if(!N||D.size===0){R("idle"),c(D.size===0?Lr["no-speech"]:oi);return}let Y=new AbortController;b.current=Y;try{let re=await N(D,{...C.current?{language:C.current}:{},signal:Y.signal});if(L.current!==H.session||Y.signal.aborted)return;if(!re.trim()){c(Lr["no-speech"]);return}O.current(Dr(x.current,re)),c(null)}catch(re){if(L.current!==H.session||Y.signal.aborted)return;c(re instanceof Error&&re.message.trim()?re.message:"Voice transcription could not be completed. Try again.")}finally{b.current===Y&&(b.current=null),L.current===H.session&&R("idle")}},[P,z,y,R]),j=Ve(()=>{L.current+=1,y(),b.current?.abort(),b.current=null,c(null),p(null),R("idle");let H=_.current,B=k.current;if(_.current=null,k.current=null,f.current.clear(),H&&z(H,!0),!!B){T(B);try{B.abort()}catch{}}},[T,z,y,R]),F=Ve(()=>{if(h.current==="transcribing"){j();return}let H=_.current;if(H){y(),R("transcribing");try{H.recorder.stop()}catch(D){L.current+=1,_.current=null,z(H,!1),p(null),R("idle"),c(D instanceof Error?D.message:"Voice recording could not be stopped cleanly.")}return}if(h.current==="recording"){j();return}let B=k.current;if(B){y();try{B.stop()}catch(D){R("idle"),L.current+=1,k.current=null,f.current.clear(),T(B);try{B.abort()}catch{}c(D instanceof Error?D.message:"Voice dictation could not be stopped cleanly.")}}},[j,T,z,y,R]),K=Ve(async()=>{if(!ni()){c(Xo);return}let H=L.current+1;L.current=H,x.current=v.current,c(null),d(0),p(null),R("recording");let B;try{B=await navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0}})}catch(Y){if(L.current!==H)return;R("idle"),c(Yo(Y));return}if(L.current!==H){Or(B);return}let D;try{let Y=ju();D=Y?new MediaRecorder(B,{mimeType:Y}):new MediaRecorder(B)}catch(Y){if(Or(B),L.current!==H)return;R("idle"),c(Yo(Y));return}let N={chunks:[],recorder:D,session:H,stream:B};D.ondataavailable=Y=>{Y.data.size>0&&N.chunks.push(Y.data)},D.onerror=Y=>{L.current!==H||_.current!==N||(L.current+=1,_.current=null,y(),z(N,!0),p(null),R("idle"),c(Yu(Y).message))},D.onstop=()=>{ie(N)},_.current=N,p(B);try{D.start(1e3),M()}catch(Y){L.current+=1,_.current=null,z(N,!1),p(null),R("idle"),c(Yo(Y))}},[z,ie,M,y,R]),ye=Ve(()=>{let H=si();if(!H){c(Xo);return}let B;try{B=new H}catch(N){c(N instanceof Error?N.message:"Voice dictation could not be started.");return}let D=L.current+1;L.current=D,x.current=v.current,f.current=new Map,B.continuous=!0,B.interimResults=!0,B.maxAlternatives=1,C.current&&(B.lang=C.current),B.onstart=()=>{L.current===D&&(R("recognizing"),M())},B.onresult=N=>{if(L.current!==D)return;let Y=Math.max(0,N.resultIndex);for(let oe of f.current.keys())oe>=Y&&f.current.delete(oe);for(let oe=Y;oe<N.results.length;oe+=1){let qe=N.results[oe]?.[0]?.transcript;typeof qe=="string"&&f.current.set(oe,qe)}let re=Array.from(f.current.entries()).sort(([oe],[Me])=>oe-Me).map(([,oe])=>oe).reduce(Dr,"");O.current(Dr(x.current,re))},B.onerror=N=>{if(L.current!==D)return;y(),R("idle"),f.current.clear(),L.current+=1;let Y=L.current;N.error!=="aborted"&&(N.error==="not-allowed"?zu().then(re=>{L.current===Y&&c(Jo(N.error,N.message,re))}):c(Jo(N.error,N.message))),k.current===B&&(k.current=null,T(B))},B.onend=()=>{L.current===D&&(y(),R("idle"),k.current===B&&(k.current=null,T(B)))},k.current=B,c(null),d(0),R("recognizing");try{B.start()}catch(N){T(B),k.current=null,y(),R("idle"),c(N instanceof Error?N.message:"Voice dictation could not be started.")}},[T,M,y,R]),Se=Ve(()=>{h.current!=="idle"||k.current||_.current||b.current||(X.current?K():ye())},[ye,K]);return ti(()=>()=>{L.current+=1,y(),b.current?.abort(),b.current=null;let H=_.current,B=k.current;if(_.current=null,k.current=null,H&&z(H,!0),!!B){T(B);try{B.abort()}catch{}}},[T,z,y]),{cancel:j,elapsedSeconds:i,error:l,isActive:o!=="idle",isRecording:o==="recording",isSupported:u,isTranscribing:o==="transcribing",start:Se,stop:F,stream:m}}import{Spinner as Lg}from"@heroui/react/spinner";import{isTerminalCloseEvent as Hg}from"agents/client";import{useAgent as Ug}from"agents/react";import{Suspense as Bg,useCallback as W,useEffect as be,useEffectEvent as $t,useId as Fg,useLayoutEffect as Kt,useMemo as Ae,useRef as ue,useState as ee}from"react";import{z as te}from"zod";var Ju=te.enum(["light","dark","system"]),Zu=te.enum(["outline","plain","surface","surface-secondary"]),ed=new Set(["[object object]","0","anonymous","distinct_id","distinctid","email","false","guest","id","nan","none","not_authenticated","null","true","undefined"]),es=te.string().trim().min(1).max(200).refine(e=>!ed.has(e.toLowerCase()),{message:"Identity id is reserved"}),td=te.discriminatedUnion("type",[te.object({id:es,type:te.literal("anonymous")}),te.object({id:es,type:te.literal("user")})]),nd=te.object({avatarUrl:te.string().trim().pipe(te.url()).optional(),email:te.string().trim().max(320).pipe(te.email()).optional(),name:te.string().trim().max(120).optional()}),Ff=te.object({anonymousId:es.optional(),identity:td,profile:nd.optional()}),Vf=te.object({expiresAt:te.number().int().positive(),token:te.string().trim().min(1)}),$f=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 k=ad(c.text,s);if(!k)continue;r.push({active:n.isStreaming===!0&&c.state!=="done",detail:k.detail,detailVisibility:"always",id:`${e.id}-reasoning-${l}`,kind:"thinking",label:k.label,messagePartIndex:l,stateKnown:c.state!==void 0,...r.length===0&&i?{title:i}:{}}),s+=1;continue}if(c.type==="data-activity"){let k=c.data.label.trim(),L=c.data.title?.trim();if(L&&!i){i=L;let $=r[0];$&&!$.title&&(r[0]={...$,title:L})}if(ld(k,c.data.stage)||L&&ts(k)===ts(L))continue;if(k&&o.has(k)){let $=r.findIndex(b=>b.label===k),X=r[$];L&&X&&!X.title&&(r[$]={...X,title:L})}else k&&(o.add(k),r.push({active:!1,detail:c.data.detail,id:c.id??`${e.id}-activity-${l}`,kind:c.data.kind??Br(k),label:k,messagePartIndex:l,sources:c.data.sources,stateKnown:!1,...L||r.length===0&&i?{title:L??i}:{}}));continue}let m=ai(c);if(!m)continue;let p=c,S=ii(m),u=S&&e.parts.slice(l+1).some(k=>{let L=ai(k);return L!==null&&ii(L)&&k.state==="output-available"});if(S&&p.state==="output-error"&&(n.isStreaming||u))continue;let h=m==="searchWeb"?id(p):null,x=S?"Building your data view":m==="executeSandbox"?"Analyzing your data":m==="getComponentSchema"?"Preparing your data view":h?`Searching the web for \u201C${h}\u201D`:t.get(m)?.displayName??ud(m),C=p.state==="output-denied"||!!(p.output&&typeof p.output=="object"&&"rejected"in p.output&&p.output.rejected)?h?`Skipped web search for \u201C${h}\u201D`:`Skipped ${x}`:p.state==="output-error"?h?`Couldn\u2019t search the web for \u201C${h}\u201D`:`Couldn\u2019t complete ${x}`:x,O=["input-available","input-streaming","approval-requested","approval-responded"].includes(p.state),_=r.findIndex(k=>k.label===C);if(_>=0){let k=r[_];k&&(r[_]={...k,active:O,messagePartIndex:l,stateKnown:!0,...!k.title&&i?{title:i}:{}});continue}o.add(C),r.push({active:O,id:p.toolCallId||`${e.id}-tool-${l}`,kind:S?"chart":m==="executeSandbox"?"code":m==="getComponentSchema"?"thinking":Br(C),label:C,messagePartIndex:l,stateKnown:!0,...r.length===0&&i?{title:i}:{}})}if(!n.isStreaming||r.length===0||r.some(l=>l.active))return r;let d=r.length-1;return r[d]?.stateKnown?r:r.map((l,c)=>({...l,active:c===d}))}var dd={accepted:"Thinking\u2026",generating:"Writing the answer\u2026",preparing:"Preparing the answer\u2026",recovering:"Recovering your answer\u2026","running-server-tool":"Running tools\u2026","waiting-client-tool":"Waiting for a browser action\u2026"},pd=new Set(["accepted","preparing","generating","waiting-client-tool","running-server-tool","recovering"]);function md(e){return e.type==="dynamic-tool"&&e.toolName?e.toolName:e.type.startsWith("tool-")?e.type.slice(5):null}function Yn(e){return e?dd[e]:null}function ci({clientToolNames:e,isLocalPending:t,isRecovering:n,isStreaming:r,messages:o,status:s}){if(n)return"recovering";let i=o.findLast(d=>d.role==="assistant");if(i){for(let l=i.parts.length-1;l>=0;l-=1){let c=i.parts[l],m=md(c);if(m&&["input-streaming","input-available","approval-requested","approval-responded"].includes(c.state??""))return e.has(m)?"waiting-client-tool":"running-server-tool";if(c.type==="data-activity"||c.type==="data-progress"){let p=c.data?.stage;if(typeof p=="string"&&pd.has(p))return p}}let d=i.parts.some(l=>l.type==="text"&&l.text.trim().length>0||l.type==="data-component");if(r&&d)return"generating"}return r||s==="streaming"?"preparing":t||s==="submitted"?"accepted":null}import{ChartColumn as _d,CircleCheck as Od,Code as Dd,Database as Ld,Globe as hi,Magnifier as Hd,Wrench as Ud}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 gd,useState as fd}from"react";import{jsx as Fr,jsxs as yd}from"react/jsx-runtime";var hd=280;function Vr({animateOnMount:e=!0,children:t,className:n,...r}){let[o,s]=fd(()=>({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 gd(()=>{if(!d)return;let l=window.setTimeout(()=>{s(c=>c.current.id===i?{...c,previous:null}:c)},hd);return()=>window.clearTimeout(l)},[i,d]),yd("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 vd,Heading as Tn,Link as bd,Paragraph as Sd,Separator as Cd,Table as _t}from"@heroui/react";import{Children as ui,Suspense as di,isValidElement as pi,lazy as Ad,memo as Td,useMemo as Rd}from"react";import{jsx as fe,jsxs as xd}from"react/jsx-runtime";var Md=Ad(()=>import("streamdown").then(e=>({default:e.Streamdown})));function wd(e){return e?.match(/language-([^\s]+)/)?.[1]??"plaintext"}function Ed(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 Pd({children:e}){let t=os(e,"thead"),n=os(e,"tbody"),r=os(t?.props.children,"tr"),o=rs(r),s=rs(n);return fe(_t,{"data-slot":"markdown-table",variant:"secondary",children:fe(_t.ScrollContainer,{children:xd(_t.Content,{"aria-label":"Markdown table",children:[fe(_t.Header,{children:o.map((i,d)=>fe(_t.Column,{id:`column-${d}`,isRowHeader:d===0,children:i.props.children},String(i.key)))}),fe(_t.Body,{children:s.map((i,d)=>fe(_t.Row,{id:`row-${d}`,children:rs(i).map(l=>fe(_t.Cell,{children:l.props.children},String(l.key)))},String(i.key)))})]})})})}function Id(e,t){function n({children:o,className:s,node:i}){let d=wd(s),l=String(o??"").replace(/\n$/,""),c=Ed(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(vd,{className:s,"data-slot":"markdown-inline-code",children:o})}return{a:({children:o,className:s,href:i})=>fe(bd,{className:s,href:i,rel:"noreferrer",target:"_blank",children:o}),code:n,h1:({children:o,className:s})=>fe(Tn,{className:s,level:1,children:o}),h2:({children:o,className:s})=>fe(Tn,{className:s,level:2,children:o}),h3:({children:o,className:s})=>fe(Tn,{className:s,level:3,children:o}),h4:({children:o,className:s})=>fe(Tn,{className:s,level:4,children:o}),h5:({children:o,className:s})=>fe(Tn,{className:s,level:5,children:o}),h6:({children:o,className:s})=>fe(Tn,{className:s,level:6,children:o}),hr:({className:o})=>fe(Cd,{className:o,"data-slot":"markdown-separator",variant:"tertiary"}),inlineCode:r,p:({children:o,className:s})=>fe(Sd,{className:s,"data-slot":"markdown-paragraph",size:"sm",children:o}),table:Pd}}var $r=Td(function({animated:t=La,caret:n="block",children:r,isStreaming:o=!1,plugins:s}){let i=Rd(()=>Id(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(Md,{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 Nd(e,t=1){let n=e.scrollTop>t,r=e.scrollTop+e.clientHeight+t<e.scrollHeight;return n&&r?"both":n?"top":r?"bottom":"none"}function mi(e,t){delete e.dataset.topScroll,delete e.dataset.bottomScroll,delete e.dataset.topBottomScroll,t==="both"?e.dataset.topBottomScroll="true":t==="top"?e.dataset.topScroll="true":t==="bottom"&&(e.dataset.bottomScroll="true")}function rn(e,t=1){kd(()=>{let n=e.current;if(!n)return;let r=null,o=null,s=()=>{r!==null&&cancelAnimationFrame(r),r=requestAnimationFrame(()=>{r=null;let l=Nd(n,t);l!==o&&(o=l,mi(n,l))})};s(),n.addEventListener("scroll",s,{passive:!0});let i=typeof ResizeObserver>"u"?null:new ResizeObserver(s),d=typeof MutationObserver>"u"?null:new MutationObserver(s);return i?.observe(n),d?.observe(n,{characterData:!0,childList:!0,subtree:!0}),()=>{n.removeEventListener("scroll",s),i?.disconnect(),d?.disconnect(),r!==null&&cancelAnimationFrame(r),mi(n,"none")}},[t,e])}import{jsx as ne,jsxs as ht}from"react/jsx-runtime";var Bd=24,Fd=160,Vd=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<=Bd},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 $d(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"?Fd:Vd,d=window.setTimeout(()=>{n(l=>l.isStreaming===e&&l.phase===r?{...l,phase:s}:l)},i);return()=>window.clearTimeout(d)},[e,r]),r}var Kd={browse:hi,chart:_d,code:Dd,data:Ld,search:Hd,thinking:Ud},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 ht("span",{className:"ha-activity-icon","data-state":e?"active":"complete",children:[ne("span",{"aria-hidden":"true",className:"ha-activity-icon-state ha-activity-icon-state--active",children:ne("span",{className:"ha-activity-spinner"})}),ne("span",{"aria-hidden":"true",className:"ha-activity-icon-state ha-activity-icon-state--complete",children:ne(Od,{})})]})}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 Gd({detail:e,isDetailActive:t,isLabelActive:n,isTurnActive:r,label:o,markdownAnimation:s,markdownPlugins:i}){let[d,l]=as(()=>({isDetailActive:t,isExpanded:t})),c=d.isExpanded;d.isDetailActive!==t&&(c=t,l({isDetailActive:t,isExpanded:c}));let m=ss(null);return rn(m),vi(m,e,t&&r,c),ht(je,{className:"ha-activity-step-disclosure",isExpanded:c,onExpandedChange:p=>l({isDetailActive:t,isExpanded:p}),children:[ne(je.Heading,{children:ht(je.Trigger,{className:"ha-activity-step-trigger",children:[ne(bi,{active:n,label:o}),ne(je.Indicator,{className:"ha-activity-step-chevron"})]})}),ne(je.Content,{className:"ha-activity-step-disclosure-content",children:ne(je.Body,{className:"ha-activity-detail",children:ne("div",{ref:m,className:"ha-activity-detail-inner",children:ne($r,{animated:s,caret:!1,isStreaming:t?r:!1,plugins:i,children:e})})})})]})}function Qd(e){let t=Math.max(1,Math.round(e/1e3)),n=Math.floor(t/3600),r=Math.floor(t%3600/60),o=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${o}s`:`${o}s`}function qr({ariaLabel:e,label:t}){return ne("div",{className:"ha-progress ha-activity-status",children:ne(Vr,{"aria-label":e,className:"ha-progress-shimmer",role:"status",children:t})})}function Si({completedAt:e,defaultOpen:t=!1,hasResponseStarted:n=!1,isStreaming:r,items:o,markdownAnimation:s,markdownPlugins:i,startedAt:d}){let l=r&&!n,c=$d(r),[m,p]=as(null),S=ss(null),u=o.findLastIndex(y=>y.active),h=o.length-1,x=l?u>=0?u:h:-1,w=o.map((y,M)=>({...y,active:M===x})),C=qd(w),O=m===null&&!t&&!r&&(c==="fading"||c==="collapsing"),k=m??(t||c==="expanded"||c==="fading"),L=m!==null||t?k?"expanded":"collapsed":c,$=d!==void 0&&e!==void 0&&!r?Math.max(0,e-d):null,X=$===null?"Activity":`Worked for ${Qd($)}`,b=r||O?C.title:$===null?"Activity":X,f=C.kind,v=Kd[f],R=w.map(y=>`${y.id}:${y.active?1:0}:${y.detail??""}:${y.sources?.map(M=>M.label).join(",")}`).join("|");return rn(S),vi(S,R,r,k),ht(je,{className:"ha-activity","data-complete":r?void 0:"true","data-phase":L,isExpanded:k,onExpandedChange:p,children:[ne(je.Heading,{children:ht(je.Trigger,{className:"ha-activity-trigger",children:[ne("span",{"aria-hidden":"true",className:"ha-activity-summary-icon",children:ne("span",{children:ne(v,{})},f)}),r||O?ne(Vr,{className:"ha-activity-summary-label ha-progress ha-progress-shimmer",role:"status",children:b}):ne("span",{className:"ha-activity-summary-label ha-activity-summary-label--complete ha-progress",children:b}),ne(je.Indicator,{className:"ha-activity-chevron"})]})}),ne(je.Content,{className:"ha-activity-disclosure-content",children:ne(je.Body,{children:ne("div",{ref:S,className:"ha-activity-panel",children:ht("ol",{"aria-label":"Thinking steps",children:[w.map((y,M)=>ht("li",{"aria-current":y.active?"step":void 0,className:"ha-activity-item","data-active":y.active||void 0,"data-state":y.active?"active":"complete",children:[ne(fi,{active:y.active}),ht("div",{className:"ha-activity-content",children:[y.detail&&(y.active||y.detailVisibility==="always")?ne(Gd,{detail:y.detail,isDetailActive:l?o[M]?.active===!0:!1,isLabelActive:y.active,isTurnActive:r,label:y.label,markdownAnimation:s,markdownPlugins:i}):ne(bi,{active:y.active,label:y.label}),y.sources?.length?ne("span",{"aria-label":"Sources",className:"ha-activity-sources",children:y.sources.map(T=>ht("span",{className:"ha-activity-source",children:[ne(hi,{"aria-hidden":"true"}),T.label]},T.label))}):null]})]},y.id)),r?null:ht("li",{className:"ha-activity-item","data-complete":"true","data-state":"complete",children:[ne(fi,{active:!1}),ne("div",{className:"ha-activity-content",children:ne("span",{className:"ha-activity-step-label",children:"Final response ready"})})]})]})})})})]})}import{z as ep}from"zod";import{z as Ot}from"zod";var zd=["callMcpTool","composeUI","executeSandbox","getComponentSchema","renderComponent","searchKnowledge","searchMcpTools","searchWeb"],Wd="mcp_",jd=20,Yd=16*1024,Xd=Ot.object({description:Ot.string().trim().min(1).max(1e3),inputSchema:Ot.record(Ot.string(),Ot.unknown()),name:Ot.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).refine(e=>!zd.includes(e)&&!e.toLowerCase().startsWith(Wd),"Client tool name is reserved by the HeroUI Agent runtime"),needsApproval:Ot.boolean().optional()}),Ci=Ot.array(Xd).max(jd).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>Yd&&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)}),Jd=Ye.string().trim().max(2048).refine(e=>{try{return["http:","https:"].includes(new URL(e).protocol)}catch{return!1}}),Zd=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:Jd})]),Ti=Ye.object({items:Ye.array(Zd).min(1).max(16)});function tp(e){return ba(e.parameters)?ep.toJSONSchema(e.parameters):e.parameters}function Dt(e){return Ci.parse(e.map(t=>({description:t.description,inputSchema:tp(t),name:t.name,...t.needsApproval?{needsApproval:!0}:{}})))}var Rn=class extends Error{constructor(){super("The assistant configuration changed and must be bootstrapped again"),this.name="AgentRuntimeRevisionStaleError"}},Xn=class extends Error{retryable;status;constructor(t){super("Could not refresh the assistant connection"),this.name="AgentRuntimeTicketError",this.status=t,this.retryable=t===408||t===429||t>=500}},Gr=class extends Error{code;status;constructor(t,n){super("Could not bootstrap the assistant conversation"),this.name="AgentConversationBootstrapError",this.code=n,this.status=t}},np=250,rp=2e3,wi=new Set(["CONVERSATION_LEASE_CONFLICT","SETTLEMENT_ACKNOWLEDGEMENT_PENDING"]),op=15e3,Ri=3e4;function Ei(e){return e instanceof Gr&&e.status===409&&wi.has(e.code)}function sp(e){return e===408||e===429||e>=500}function ap(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 ip(e,t){return new Promise((n,r)=>{if(t.aborted){r(t.reason);return}let o=()=>{globalThis.clearTimeout(s),r(t.reason)},s=globalThis.setTimeout(()=>{t.removeEventListener("abort",o),n()},e);t.addEventListener("abort",o,{once:!0})})}function Pi(e){return{clientTools:Dt(e.tools),imageSearch:e.imageSearch,...e.composerDefaultModel?{modelId:e.composerDefaultModel}:{},newsSearch:e.newsSearch,webSearch:e.webSearch}}function Ii(e){return JSON.stringify(Pi(e))}function Qr(e,t=!1){return{Authorization:`Bearer ${e}`,...t?{"Content-Type":"application/json"}:{},"X-HeroUI-Agent-Protocol-Version":String(6),"X-HeroUI-Agent-SDK-Version":We}}async function Jn(e,t,n={}){let r=async()=>{let s=new Headers(n.headers);return s.set("Authorization",`Bearer ${await e.get()}`),s.set("X-HeroUI-Agent-Protocol-Version",String(6)),s.set("X-HeroUI-Agent-SDK-Version",We),fetch(t,{...n,headers:s})},o=await r();return o.status===401&&(e.clear(),o=await r()),o}function Mi(e){if(typeof e!="string"||!e)return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}var lp=/^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"||!lp.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 cp(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 up(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return xi(t.runtime??t)}async function ki(e,t,n){let r=new AbortController,o=Date.now()+Ri,s=globalThis.setTimeout(()=>r.abort(new Error("Assistant conversation bootstrap request timed out")),Ri),i=np;try{for(;;){let d=await Jn(t,`${e.apiBaseUrl}/v1/conversations/${encodeURIComponent(n)}/bootstrap`,{body:JSON.stringify(Pi(e)),headers:{"Content-Type":"application/json"},method:"POST",signal:r.signal});if(!d.ok){let c=await d.json().catch(()=>null),m=typeof c?.code=="string"?c.code.toUpperCase():"";if(d.status===409&&wi.has(m))throw new Gr(d.status,m);if(!sp(d.status))return null;let p=Date.now(),S=ap(d.headers.get("Retry-After"),p)??i;if(p+S>=o)return null;await ip(S,r.signal),i=Math.min(i*2,rp);continue}let l=cp(await d.json().catch(()=>null));return l?.conversation.id!==n||l?.conversation.agentId!==e.agentId?null:l}}finally{globalThis.clearTimeout(s)}}async function Ni(e,t,n,r){let o=new AbortController,s=globalThis.setTimeout(()=>o.abort(new Error("Assistant connection ticket request timed out")),op);try{let i=await Jn(t,`${e.apiBaseUrl}/v1/conversations/${encodeURIComponent(n)}/runtime-ticket`,{body:JSON.stringify({runtimeRevision:String(r)}),headers:{"Content-Type":"application/json"},method:"POST",signal:o.signal}),d=await i.json().catch(()=>null);if(!i.ok){let c=typeof d?.code=="string"?d.code.toUpperCase():"";throw i.status===409||c.includes("STALE")&&c.includes("REVISION")?new Rn:new Xn(i.status)}let l=up(d);if(!l||l.runtimeRevision!==r||l.path!==`/v1/conversations/${encodeURIComponent(n)}/connect`)throw new Error("The assistant returned an invalid connection ticket");return l}finally{globalThis.clearTimeout(s)}}async function Ne(e,t,n,r,o={}){try{await fetch(`${e.apiBaseUrl}/v1/agents/${encodeURIComponent(e.agentId)}/events`,{body:JSON.stringify({conversationId:n,event:r,properties:{...o,protocolVersion:6,sdkVersion:We}}),headers:Qr(await t.get(),!0),keepalive:!0,method:"POST"})}catch{}}function Mn(e,t=Eo){let n=new Set(t),o=e.filter(s=>Po(s.type)&&n.has(s.type.trim().toLowerCase())&&s.size>0&&s.size<=10485760).slice(0,5);return e.length>5?{error:`You can attach up to ${5} files at a time.`,files:o}:e.some(s=>!Po(s.type)||!n.has(s.type.trim().toLowerCase()))?{error:dp(t),files:o}:e.some(s=>s.size===0)?{error:"Empty files cannot be attached.",files:o}:e.some(s=>s.size>10485760)?{error:"Each attachment must be 10 MB or smaller.",files:o}:{error:null,files:o}}async function Oi({acceptedContentTypes:e=Eo,apiBaseUrl:t,conversationId:n,files:r,tokenManager:o}){if(r.length===0)return[];let s=Mn(r,e);if(s.error||s.files.length!==r.length)throw new Error(s.error??"One or more attachments are not supported.");return Promise.all(r.map(i=>pp({apiBaseUrl:t,conversationId:n,file:i,tokenManager:o})))}function dp(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 pp({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 mp(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 mp(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 gp=64*1024,fp=15e3,hp=5*6e4,yp=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()]),vp=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 bp(e){return[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))].map(n=>n.toString(16).padStart(2,"0")).join("")}function Sp(e){return{error:e instanceof Error?e.message.slice(0,1e3):"The tool could not be executed"}}function Cp(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>gp?{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 Ap(e){return bp(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=hp,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 Ap(n),protocolVersion:6,toolCallId:d,toolName:l},p=o(),S;for(;S=yp.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}=Cp(await t(u)))}catch(C){x="failed",h=Sp(C)}let w;for(;;)try{w=vp.parse(await s.complete({...m,claimId:S.claimId,output:h,status:x}));break}catch(C){if(o()-p+250>r)throw C;await c(250)}return await i(w.output),"executed"}var cs=fp;var Tp=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;function Bi(e){return e.map(({description:t,inputSchema:n,name:r})=>({description:t,name:r,parameters:n}))}function Fi(e){return Object.fromEntries(Bi(e).map(({description:t,name:n,parameters:r})=>[n,{description:t,execute:()=>{throw new Error("HeroUI client tools execute through the approval-aware bridge")},parameters:r}]))}function Vi(e){try{let t=JSON.parse(e);return t.type!=="cf_agent_tool_approval"||t.approved!==!0||t.autoContinue!==!0?e:JSON.stringify({...t,autoContinue:!1})}catch{return e}}function us({clientSubmittedAt:e,clientTools:t,generateConversationTitle:n,imageSearch:r,modelId:o,newsSearch:s,pageContext:i,permissionMode:d,turnId:l,webSearch:c}){if(!Tp.test(l))throw new Error("HeroUI Agent turnId must be a UUID");if(!Number.isSafeInteger(e)||e<=0)throw new Error("HeroUI Agent clientSubmittedAt must be a positive timestamp");return{clientSubmittedAt:e,clientTools:Bi(t),...n===void 0?{}:{generateConversationTitle:n},imageSearch:r,...o?{modelId:o}:{},newsSearch:s,pageContext:i,permissionMode:d,protocolVersion:6,requestId:l,sdkVersion:We,turnId:l,webSearch:c}}function $i(e){return e.replace(/^\/+|\/+$/g,"")}function Ki(e){let t=new URL(e.baseUrl),n=$i(t.pathname),r=$i(e.path);if(!r)throw new Error("The assistant returned an invalid connection path");return{basePath:n||r,host:t.host,...n?{path:r}:{},protocol:t.protocol==="http:"?"ws":"wss"}}function qi(e,t){let n=e;return{next:async()=>{if(n){let r=n;return n=null,r}return t()},refresh:t}}function Gi(e){if(typeof e.data!="string")return null;try{let t=JSON.parse(e.data);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Qi(e,{fillComposer:t,setSelection:n,submitPrompt:r}){return e.type==="followup"?(r(e.prompt),!0):e.type==="submit"?(n({componentId:e.componentId,componentTitle:e.componentTitle,datum:{actionId:e.actionId,values:e.values}}),e.prompt&&t(e.prompt),!0):e.type==="tool"?(t(e.prompt??e.label),!0):!1}function Rp(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 Rp(o)}import{Xmark as Vp}from"@gravity-ui/icons";import{File as Mp,FileCode as wp,FileLetterP as Ep,FileLetterW as Pp,FileLetterX as Ip,FileText as xp,FileZipper as kp,MusicNote as Np,Picture as _p,Video as Op}from"@gravity-ui/icons";var Dp=new Set(["csv","ods","xls","xlsm","xlsx"]),Lp=new Set(["doc","docx","odt","rtf"]),Hp=new Set(["css","go","html","java","js","json","jsx","mdx","php","py","rb","rs","scss","sh","sql","swift","ts","tsx","xml","yaml","yml"]),Up=new Set(["7z","bz2","gz","rar","tar","tgz","zip"]),Bp=new Set(["log","md","text","txt"]);function Fp(e){let t=e.trim().toLowerCase(),n=t.lastIndexOf(".");return n>0?t.slice(n+1):""}function zr(e){let t=Fp(e.name),n=e.type.toLowerCase();return Dp.has(t)||n.includes("csv")||n.includes("excel")||n.includes("spreadsheet")?{Icon:Ip,kind:"spreadsheet",label:"Spreadsheet"}:t==="pdf"||n==="application/pdf"?{Icon:Ep,kind:"pdf",label:"PDF document"}:Lp.has(t)||n.includes("wordprocessingml")?{Icon:Pp,kind:"document",label:"Document"}:n.startsWith("image/")?{Icon:_p,kind:"image",label:"Image"}:n.startsWith("video/")?{Icon:Op,kind:"video",label:"Video"}:n.startsWith("audio/")?{Icon:Np,kind:"audio",label:"Audio"}:Up.has(t)||n.includes("zip")?{Icon:kp,kind:"archive",label:"Archive"}:Hp.has(t)?{Icon:wp,kind:"code",label:"Code file"}:Bp.has(t)||n.startsWith("text/")?{Icon:xp,kind:"text",label:"Text document"}:{Icon:Mp,kind:"file",label:"File"}}import{jsx as wn,jsxs as zi}from"react/jsx-runtime";function ps({file:e,onRemove:t}){let{Icon:n,kind:r,label:o}=zr(e);return zi("span",{className:"ha-attachment","data-kind":r,children:[wn("span",{"aria-hidden":"true",className:"ha-attachment-icon",children:wn(n,{})}),zi("span",{className:"ha-attachment-copy",children:[wn("span",{className:"ha-attachment-name",title:e.name,children:e.name}),wn("span",{className:"ha-attachment-type",children:o})]}),wn("button",{"aria-label":`Remove ${e.name}`,type:"button",onClick:t,children:wn(Vp,{"aria-hidden":"true"})})]})}import{Globe as $p,Xmark as Kp}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($p,{"aria-hidden":"true",className:"ha-chip-leading"}),Wi("span",{className:"ha-chip-title",title:t,children:["Ask about this: ",t]}),ms(Kp,{"aria-hidden":"true",className:"ha-chip-remove"})]})})}import{useCallback as Wr,useState as qp}from"react";import{jsx as Gp}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 Gp("div",{className:t,"data-controls-revealed":n,"data-dictating":r,"data-dragging":l||void 0,"data-expanded":o,onDragEnterCapture:m,onDragLeaveCapture:S,onDragOverCapture:p,onDropCapture:u,children:e})}var fs="Enter";var Xi="Control+Shift+D";function Ji(e){return!e.defaultPrevented&&!e.isComposing&&!e.repeat&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&e.key==="Enter"}function Zi(e){return!e.defaultPrevented&&!e.isComposing&&!e.repeat&&!e.altKey&&e.ctrlKey&&!e.metaKey&&e.shiftKey&&e.key.toLowerCase()==="d"}function el(e,t){if(e.defaultPrevented||e.isComposing||e.repeat||e.altKey||!e.ctrlKey||e.metaKey||e.shiftKey)return null;let n=Number(e.key);return!Number.isInteger(n)||n<1||n>Math.min(t,9)?null:n-1}function hs(){return{activeTurnIds:new Set,busyIds:new Set,completedIds:new Set}}function tl(e,t){let{activeConversationId:n,busy:r,conversationId:o,failed:s,turnActive:i}=t,d=e.activeTurnIds.has(o),l=new Set(e.activeTurnIds),c=new Set(e.busyIds),m=new Set(e.completedIds);return r?c.add(o):c.delete(o),i?l.add(o):r||l.delete(o),(r||n===o)&&m.delete(o),!r&&d&&!s&&n!==o&&m.add(o),{activeTurnIds:l,busyIds:c,completedIds:m}}function ys(e,t){if(!e.completedIds.has(t))return e;let n=new Set(e.completedIds);return n.delete(t),{...e,completedIds:n}}function nl(e,t){if(!e.activeTurnIds.has(t)&&!e.busyIds.has(t)&&!e.completedIds.has(t))return e;let n=new Set(e.activeTurnIds),r=new Set(e.busyIds),o=new Set(e.completedIds);return n.delete(t),r.delete(t),o.delete(t),{activeTurnIds:n,busyIds:r,completedIds:o}}function rl(e,t,n=()=>crypto.randomUUID()){return e?.conversationEpoch===t?e:{conversationEpoch:t,conversationId:n()}}function jr({conversationEpoch:e,optimisticTarget:t,requestedConversationId:n,storedConversationId:r}){return n===null&&t?.conversationEpoch===e&&Mt(t.conversationId)?t.conversationId:Fo(n,r)}function ol({conversationEpoch:e,optimisticTarget:t,readyConversationId:n,readyEpoch:r,requestedConversationId:o}){if(r!==e)return null;let s=o===null?t?.conversationEpoch===e?t.conversationId:null:typeof o=="string"?o:n;return n===s?n:null}import{jsx as vs}from"react/jsx-runtime";function Yr({agentId:e,composerControlsAvailable:t,composerControlsRevealed:n,composerEndSlot:r,composerFooterSlot:o,composerStartSlot:s,greeting:i,loadingLabel:d,onComposerControlsReveal:l,placeholder:c,showStartScreen:m,suggestedPrompts:p}){return m?vs(Da,{composerConnecting:!0,agentId:e,composerControlsAvailable:t,composerControlsRevealed:n,composerEndSlot:r,composerFooterSlot:o,composerStartSlot:s,greeting:i,placeholder:c,suggestedPrompts:p,onComposerControlsReveal:l,onIntent:()=>{}}):vs("div",{className:"ha-loading",children:vs(tn,{className:"ha-progress ha-progress-shimmer",children:d})})}function Qp(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=Qp(i.headers.get("Retry-After"),n());if(n()-s+d>t)return i;await o(d),i=await r()}return i}var Zn="Thinking\u2026";function al({activeStreamKey:e,activeTurnMessageId:t}){return e!==null&&t===null}function il({continuingAssistantMessageId:e,isActiveTurn:t,streamingAssistantMessageId:n,trackedActivityMessageId:r}){return t?n??r??e:null}function ll({hasActiveActivity:e,hasError:t,hasResponseStarted:n,isActiveTurn:r,messageCount:o,preferHomeWhileEmpty:s=!1,progress:i,runtimeStatus:d}){let l=o>0,c=!s&&!l&&(d==="pending"||d==="streaming"),m=!l&&!t&&!r&&!c;return e||n?{showHome:m,standaloneStatus:null}:r?{showHome:m,standaloneStatus:i??Zn}:c?{showHome:m,standaloneStatus:"Loading chat\u2026"}:{showHome:m,standaloneStatus:null}}import{jsx as zp}from"react/jsx-runtime";function cl({activeConversationId:e,children:t,routes:n}){return Object.values(n).map(r=>{let o=r.conversationId===e;return zp("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 em}from"@gravity-ui/icons";import{Button as tm}from"@heroui/react";import{useLayoutEffect as nm,useRef as rm}from"react";import{useCallback as Lt,useEffect as Wp,useLayoutEffect as jp,useRef as Ke,useState as Yp}from"react";var Ht=4,on=1,dl="--ha-active-turn-spacer-height",pl='[data-role="user"][data-stream-anchor="true"]',Xp={hasOverflow:!1,isAtBottom:!0};function er(e){let t=e.scrollHeight-e.clientHeight>Ht,n=!t||e.scrollHeight-Math.max(0,e.scrollTop)-e.clientHeight<=Ht;return{hasOverflow:t,isAtBottom:n}}function Jp({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 Zp(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]=Yp(Xp),w=Lt(b=>{x(f=>Zp(f,b)?f:b)},[]),C=Lt(b=>{t.current=0,b.style.removeProperty(dl)},[]),O=Lt(b=>{let f=c.current?b.querySelector(pl):null;if(!f)return t.current;let v=b.getBoundingClientRect(),y=f.getBoundingClientRect().top-v.top+b.scrollTop,M=b.scrollHeight-t.current,T=Number.parseFloat(window.getComputedStyle(b).paddingTop)||0,P=Jp({anchorTop:y,clientHeight:b.clientHeight,contentHeight:M,paddingTop:T});return Math.abs(P-t.current)>1&&(t.current=P,b.style.setProperty(dl,`${P}px`)),t.current},[]),_=Lt((b="smooth")=>{let f=e.current;if(!f)return;c.current=null,m.current=null,i.current=!1,p.current=!1,S.current=!1,u.current=!1,C(f),n.current=!0,r.current=!1,l.current=f.scrollTop,w({hasOverflow:er(f).hasOverflow,isAtBottom:!0});let v=f.scrollHeight,R=Math.max(0,v-f.clientHeight);s.current=Math.abs(Math.max(0,f.scrollTop)-R)>on,typeof f.scrollTo=="function"?f.scrollTo({behavior:ml(b),top:v}):f.scrollTop=v,l.current=Math.max(0,f.scrollTop)},[C,e,w]),k=Lt(b=>{if(!c.current)return null;let f=b.querySelector(pl);if(f){let v=Number.parseFloat(window.getComputedStyle(b).paddingTop)||0;m.current=Math.max(0,f.offsetTop-v)}return m.current},[]),L=Lt((b,f,v="auto")=>{let R=Math.max(0,b.scrollHeight-b.clientHeight),y=Math.min(f,R),M=ml(v),T=Math.abs(Math.max(0,b.scrollTop)-y)>on;i.current=M==="smooth"&&T,s.current=T,!T&&t.current>Ht&&(p.current=!0),l.current=b.scrollTop,w({hasOverflow:R>Ht,isAtBottom:R-y<=Ht}),typeof b.scrollTo=="function"?b.scrollTo({behavior:M,top:f}):(b.scrollTop=f,i.current=!1),l.current=Math.max(0,b.scrollTop)},[w]),$=Lt(()=>{let b=e.current;if(!b)return;O(b);let f=er(b),v=Math.max(0,b.scrollTop),R=v<l.current-on;if(l.current=v,R&&!f.isAtBottom){n.current=!1,r.current=!0,s.current=!1,i.current=!1,c.current=null,m.current=null,S.current=!1,w(f);return}!r.current&&(!f.hasOverflow||f.isAtBottom)&&(n.current=!0);let y=c.current!==null,M=k(b);if(y){if(r.current=!0,M!==null&&i.current){let T=Math.max(0,b.scrollHeight-b.clientHeight),P=Math.min(M,T);if(Math.abs(v-P)>on){w({hasOverflow:f.hasOverflow,isAtBottom:!0});return}s.current=!1,i.current=!1,p.current=t.current>Ht}if(M!==null&&S.current){S.current=!1,L(b,M,"smooth");return}n.current=!1,w(f);return}if(n.current&&!r.current){_("auto");return}w(f)},[k,e,_,L,w,O]),X=Lt(b=>{let f=e.current;if(!f||o.current===b)return;let v=o.current!==null;if(o.current=b,b)p.current=!1,d.current!==b?(d.current=b,c.current=b,m.current=null,S.current=!0,u.current=!1,r.current=!0,n.current=!0):(c.current=null,m.current=null,S.current=!1);else if(v){c.current=null,m.current=null,s.current=!1,i.current=!1,p.current=t.current>Ht,S.current=!1,r.current=!0;let R=er(f);n.current=!1,w(R)}},[e,w]);return jp(()=>{let b=e.current;b&&(l.current=b.scrollTop,$(),r.current=!0,n.current=!1)},[$,e]),Wp(()=>{let b=e.current;if(!b)return;let f=()=>{let F=Math.max(0,b.scrollTop);s.current&&typeof b.scrollTo=="function"&&b.scrollTo({behavior:"auto",top:F}),u.current=!0,n.current=!1,r.current=!0,s.current=!1,i.current=!1,c.current=null,m.current=null,S.current=!1,l.current=F,w(er(b))},v=F=>{F.deltaY<0&&f()},R=null,y=F=>{R=F.touches[0]?.clientY??null},M=F=>{let K=F.touches[0]?.clientY??null;R!==null&&K!==null&&K>R&&f(),R=K},T=()=>{let F=er(b),K=Math.max(0,b.scrollTop),ye=K<l.current-on,Se=K>l.current+on;if(l.current=K,u.current){F.isAtBottom&&Se&&!p.current?(u.current=!1,n.current=!0,r.current=!1):(n.current=!1,r.current=!0),w(F);return}if(p.current){s.current=!1,i.current=!1,n.current=!1,r.current=!0,w(F);return}if(s.current&&!ye){let H=k(b),B=Math.max(0,b.scrollHeight-b.clientHeight),D=Math.min(H??B,B),N=F.isAtBottom||Math.abs(K-D)<=on,Y=i.current;N&&(s.current=!1,i.current=!1,H!==null&&(p.current=t.current>Ht,r.current=!0,n.current=!1)),w(Y&&!N?{hasOverflow:F.hasOverflow,isAtBottom:!0}:H===null?r.current?F:{hasOverflow:F.hasOverflow,isAtBottom:n.current}:F);return}s.current=!1,i.current=!1,c.current=null,m.current=null,S.current=!1,n.current=F.isAtBottom,r.current=!F.isAtBottom,w(F)};b.addEventListener("scroll",T,{passive:!0}),b.addEventListener("touchmove",M,{passive:!0}),b.addEventListener("touchstart",y,{passive:!0}),b.addEventListener("wheel",v,{passive:!0});let P,z=new Set,ie=()=>{if(!P)return;let F=new Set(Array.from(b.children));for(let K of z)F.has(K)||(P.unobserve(K),z.delete(K));for(let K of F)z.has(K)||(P.observe(K),z.add(K))};typeof ResizeObserver<"u"&&(P=new ResizeObserver($),P.observe(b),ie());let j=typeof MutationObserver>"u"?void 0:new MutationObserver(F=>{F.some(K=>K.type==="childList"&&K.target===b)&&ie(),$()});return j?.observe(b,{characterData:!0,childList:!0,subtree:!0}),()=>{b.removeEventListener("scroll",T),b.removeEventListener("touchmove",M),b.removeEventListener("touchstart",y),b.removeEventListener("wheel",v),j&&j.disconnect(),P&&P.disconnect()}},[k,$,e,w]),{hasOverflow:h.hasOverflow,isAtBottom:h.isAtBottom,maintainScrollPosition:$,scrollToBottom:_,setPinnedStream:X}}import{jsx as Xr,jsxs as om}from"react/jsx-runtime";function fl({activityPhase:e=null,children:t,streamKey:n=null}){let r=rm(null),{hasOverflow:o,isAtBottom:s,maintainScrollPosition:i,scrollToBottom:d,setPinnedStream:l}=gl(r),c=o&&!s;return rn(r),nm(()=>{l(n),i()},[t,i,l,n]),om("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(tm,{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(em,{"aria-hidden":"true"})})})]})}import{Suspense as sm,lazy as am}from"react";var bs;function Ss(){return bs??=import("./component-renderer-XOCP6UFF.js").then(e=>({default:e.ComponentRenderer})),bs}function hl(){Ss().catch(()=>{bs=void 0})}import{jsx as yl}from"react/jsx-runtime";var im=am(Ss);function vl(e){return yl(sm,{fallback:null,children:yl(im,{...e})})}import{ArrowsRotateLeft as lm,Check as cm,Copy as um,ThumbsDown as dm,ThumbsUp as pm}from"@gravity-ui/icons";import{Button as Jr,Popover as Zr,TextArea as mm}from"@heroui/react";import{useCallback as gm,useEffect as fm,useRef as bl,useState as tr}from"react";import{Fragment as bm,jsx as Re,jsxs as nr}from"react/jsx-runtime";var hm=2e3,ym=1e3,vm=[{label:"Incorrect",value:"incorrect"},{label:"Off topic",value:"not_relevant"},{label:"Missing details",value:"incomplete"},{label:"Unclear",value:"unclear"},{label:"Missed instructions",value:"did_not_follow_instructions"},{label:"Other",value:"other"}];function Sl({actions:e,feedback:t,onCopy:n,onFeedback:r,onRetry:o}){let[s,i]=tr(!1),[d,l]=tr(!1),[c,m]=tr(""),[p,S]=tr([]),[u,h]=tr(),x=bl(null),w=bl(0),C=gm(f=>{h(f?.closest(".ha-panel")??void 0)},[]);fm(()=>()=>{x.current!==null&&window.clearTimeout(x.current)},[]);let O=e.includes("copy")&&n,_=e.includes("feedback")&&r,k=e.includes("retry")&&o;if(!O&&!_&&!k)return null;let L=()=>{n?.(),i(!0),x.current!==null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{i(!1),x.current=null},hm)},$=f=>{!f&&Date.now()-w.current<350||l(f)},X=f=>{S(v=>v.includes(f)?v.filter(R=>R!==f):[...v,f])},b=()=>{let f=c.trim();r?.("down",{...f?{comment:f}:{},reasons:p}),l(!1)};return nr("div",{"aria-label":"Message actions",className:"ha-message-actions",role:"group",children:[O?Re("button",{"aria-label":s?"Copied":"Copy response",className:"ha-message-action","data-copied":s||void 0,type:"button",onClick:L,children:Re("span",{className:"ha-message-action-icon",children:s?Re(cm,{"aria-hidden":"true"}):Re(um,{"aria-hidden":"true"})},s?"check":"copy")}):null,_?nr(bm,{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(pm,{"aria-hidden":"true"})}),nr(Zr,{isOpen:d,onOpenChange:$,children:[Re(Jr,{ref:C,isIconOnly:!0,"aria-label":"Bad response","aria-pressed":t==="down",className:"ha-message-action ha-feedback-trigger","data-open":d||void 0,"data-selected":t==="down"||void 0,size:"sm",variant:"ghost",onPointerDown:()=>{w.current=Date.now()},children:Re(dm,{"aria-hidden":"true"})}),Re(Zr.Content,{className:"ha-feedback-popover",offset:8,placement:"top start",UNSTABLE_portalContainer:u,children:nr(Zr.Dialog,{className:"ha-feedback-dialog",children:[Re(Zr.Heading,{className:"ha-feedback-heading",children:"Help us improve"}),Re("p",{className:"ha-feedback-description",children:"What could be better?"}),Re("div",{"aria-label":"Feedback reasons",className:"ha-feedback-reasons",role:"group",children:vm.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(mm,{fullWidth:!0,"aria-label":"Additional feedback",className:"ha-feedback-textarea",maxLength:ym,placeholder:"Add details (optional)",rows:3,value:c,variant:"secondary",onChange:f=>m(f.target.value)}),Re("p",{className:"ha-feedback-privacy",children:"Avoid sharing sensitive information."}),nr("div",{className:"ha-feedback-footer",children:[Re(Jr,{className:"ha-feedback-cancel",size:"sm",variant:"ghost",onPress:()=>l(!1),children:"Cancel"}),Re(Jr,{className:"ha-feedback-submit",size:"sm",variant:"primary",onPress:b,children:t==="down"?"Update":"Send"})]})]})})]})]}):null,k?Re("button",{"aria-label":"Retry response",className:"ha-message-action",type:"button",onClick:o,children:Re(lm,{"aria-hidden":"true"})}):null]})}import{jsx as En,jsxs as Cl}from"react/jsx-runtime";function Cs({file:e}){let t=e.filename?.trim()||"Attachment",n=e.mediaType?.trim()||"",{Icon:r,kind:o,label:s}=zr({name:t,type:n});return o==="image"?En("a",{"aria-label":`Open ${t}`,className:"ha-message-image",download:e.filename,href:e.url,rel:"noopener noreferrer",target:"_blank",title:t,children:En("span",{"aria-hidden":"true",style:{backgroundImage:`url(${JSON.stringify(e.url)})`}})}):Cl("a",{className:"ha-message-file","data-kind":o,download:e.filename,href:e.url,rel:"noopener noreferrer",target:"_blank",children:[En("span",{"aria-hidden":"true",className:"ha-message-file-icon",children:En(r,{})}),Cl("span",{className:"ha-message-file-copy",children:[En("span",{className:"ha-message-file-name",title:t,children:t}),En("span",{className:"ha-message-file-type",children:s})]})]})}function sn(){return{blockedMessageId:null,isPaused:!1,messages:[]}}function As(e,t,n="append"){return e.messages.some(r=>r.id===t.id)?e:{...e,messages:n==="prepend"?[t,...e.messages]:[...e.messages,t]}}function rr(e,t){return e.messages.findIndex(r=>r.id===t)===-1?e:{...e,blockedMessageId:e.blockedMessageId===t?null:e.blockedMessageId,messages:e.messages.filter(r=>r.id!==t)}}function Al(e,t,n,r){let o=e.messages.findIndex(m=>m.id===t),s=e.messages.findIndex(m=>m.id===n);if(o===-1||s===-1||o===s)return e;let i=[...e.messages],[d]=i.splice(o,1),c=i.findIndex(m=>m.id===n)+(r==="after"?1:0);return i.splice(c,0,d),i.every((m,p)=>m.id===e.messages[p]?.id)?e:{...e,messages:i}}function or(e,t){return e.isPaused===t?e:{...e,isPaused:t}}function yt(e,t){return e.blockedMessageId===t?e:{...e,blockedMessageId:t}}function Tl(e){let t=e.text.trim();return t||`${e.files.length} attachment${e.files.length===1?"":"s"}`}function vt(e){return e.deliveryStatus??"pending"}function Pn(e,t,n){let r=e.messages.findIndex(s=>s.id===t);if(r===-1||vt(e.messages[r])===n)return e;let o=[...e.messages];return o[r]={...o[r],deliveryStatus:n},{...e,messages:o}}var Sm="heroui-agent-message-outbox",Cm=1,Ut="conversation-outboxes",Am=":message-outbox:",an=new Map;function Ts(e,t){return`${e}${Am}${t}:v1`}async function Rl(e){await an.get(e)?.catch(()=>{});let t=await Ms();if(!t)return sn();try{let n=t.transaction(Ut,"readonly"),r=await Im(n.objectStore(Ut).get(e));return await ws(n),Tm(r,e)}catch{return sn()}finally{t.close()}}function Rs(e,t,n=Date.now()){return Pl(e,async()=>{let r=t.messages.length>0?await Rm(t):null,o=await Ms();if(!o)throw new Error("Durable message storage is unavailable");try{let s=o.transaction(Ut,"readwrite"),i=s.objectStore(Ut);t.messages.length===0?i.delete(e):i.put({key:e,savedAt:n,state:r}),await ws(s)}finally{o.close()}})}function Ml(e){return Pl(e,async()=>{let t=await Ms();if(t)try{let n=t.transaction(Ut,"readwrite");n.objectStore(Ut).delete(e),await ws(n)}finally{t.close()}})}function wl(e,t){let n=new Set(t.messages.map(o=>o.id)),r=[...e.messages.filter(o=>!n.has(o.id)),...t.messages];return{blockedMessageId:t.blockedMessageId??e.blockedMessageId,isPaused:t.isPaused||e.isPaused,messages:r}}function El(e,t){let n=e.messages.filter(o=>!t.has(o.id)).map(o=>vt(o)==="sending"?{...o,deliveryStatus:"pending"}:o),r=new Set(n.map(o=>o.id));return{...e,blockedMessageId:e.blockedMessageId&&r.has(e.blockedMessageId)?e.blockedMessageId:null,messages:n}}function Tm(e,t){if(!e||typeof e!="object")return sn();let n=e,r=n.state;if(n.key!==t||typeof n.savedAt!="number"||!r||typeof r!="object"||typeof r.isPaused!="boolean"||!Array.isArray(r.messages))return sn();let o=r.messages.map(wm).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 Rm(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(Mm))})))}}async function Mm(e){return{bytes:await e.arrayBuffer(),lastModified:e.lastModified,name:e.name,type:e.type}}function wm(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.id=="string"&&t.id.length>0&&typeof t.text=="string"&&Array.isArray(t.files)&&(t.generateConversationTitle===void 0||typeof t.generateConversationTitle=="boolean")&&(t.isInitialTurn===void 0||typeof t.isInitialTurn=="boolean")&&(t.deliveryStatus===void 0||t.deliveryStatus==="pending"||t.deliveryStatus==="sending"||t.deliveryStatus==="admitted")){let n=t.files.map(Em).filter(r=>r!==null);return n.length!==t.files.length?null:{...t,files:n}}return null}function Em(e){if(typeof File<"u"&&e instanceof File)return e;if(typeof File>"u"||!e||typeof e!="object")return null;let t=e;return!Pm(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 Pm(e){return Object.prototype.toString.call(e)==="[object ArrayBuffer]"}function Pl(e,t){let r=(an.get(e)??Promise.resolve()).catch(()=>{}).then(t);return an.set(e,r),r.then(()=>{an.get(e)===r&&an.delete(e)},()=>{an.get(e)===r&&an.delete(e)}),r}function Ms(){return typeof indexedDB>"u"?Promise.resolve(null):new Promise((e,t)=>{let n=indexedDB.open(Sm,Cm);n.onerror=()=>t(n.error??new Error("Unable to open message outbox")),n.onupgradeneeded=()=>{let r=n.result;r.objectStoreNames.contains(Ut)||r.createObjectStore(Ut,{keyPath:"key"})},n.onsuccess=()=>e(n.result)})}function Im(e){return new Promise((t,n)=>{e.onerror=()=>n(e.error??new Error("IndexedDB request failed")),e.onsuccess=()=>t(e.result)})}function ws(e){return new Promise((t,n)=>{e.onabort=()=>n(e.error??new Error("IndexedDB write aborted")),e.onerror=()=>n(e.error??new Error("IndexedDB transaction failed")),e.oncomplete=()=>t()})}function Il({hasChatError:e,hasPendingClientToolCalls:t,hasReadyClientToolContinuation:n,isLocalPending:r,isResuming:o,isRunning:s,recoveryError:i}){return o||s||t||r||n&&!i&&!e}function xl(e,t){return e.text?{files:t,text:e.text}:{files:t}}function kl(e){let t=e.text.trim();return t||`${e.files.length} attachment${e.files.length===1?"":"s"}`}function Nl({activeMessageId:e,authoritativeMessageCount:t,isNewChatStartScreen:n,queuedMessageCount:r}){return n&&t===0&&r===0&&e===null}function _l({authoritativeMessageCount:e,localTurn:t,queue:n}){return e>0?null:t??n.messages.find(o=>o.isInitialTurn&&vt(o)!=="admitted")??null}function Ol(e,t){return e.messages.filter(n=>vt(n)==="pending"&&(n.id!==t||e.isPaused||e.blockedMessageId===t))}function Dl({isClientTool:e,state:t}){return e&&(t==="input-streaming"||t==="input-available"||t==="approval-requested"||t==="approval-responded")}function Ll({activeMessageId:e,isBusy:t,isReordering:n=!1,queue:r}){return e||t||n||r.isPaused||r.blockedMessageId||r.messages.length===0||r.messages.some(o=>vt(o)==="sending")?null:r.messages.find(o=>vt(o)==="pending")??null}function Hl(e,t){return e.key!=="ArrowUp"||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||e.nativeEvent.isComposing||!t?.focusLastMessage()?!1:(e.preventDefault(),!0)}import{ArrowUp as xm,CircleExclamation as km,Clock as Nm,Grip as _m,Pencil as Om,TrashBin as Dm}from"@gravity-ui/icons";import{useImperativeHandle as Lm,useLayoutEffect as Hm,useRef as Es}from"react";import{useRef as eo,useState as to}from"react";function Ul({messages:e,onReorder:t,onReorderStateChange:n}){let r=eo(null),o=eo(null),s=eo(null),i=eo(null),[d,l]=to(""),[c,m]=to(null),[p,S]=to(null),[u,h]=to(null),x=v=>{o.current=v,S(v)},w=()=>{let v=r.current!==null;r.current=null,m(null),x(null),v&&n?.(s.current!==null)},C=(v,R,y)=>{let M=e.findIndex(P=>P.id===v)+1,T=e.findIndex(P=>P.id===R)+1;l(`Moved queued message ${M} ${y} queued message ${T}.`)},O=(v,R,y)=>{let M=e.findIndex(z=>z.id===v),T=e.findIndex(z=>z.id===R),P=y==="before"&&M===T-1||y==="after"&&M===T+1;M===-1||T===-1||M===T||P||(t(v,R,y),C(v,R,y))},_=(v,R)=>{e.length<2||v.pointerType==="mouse"&&v.button!==0||(v.currentTarget.setPointerCapture?.(v.pointerId),r.current={hasMoved:!1,messageId:R,pointerId:v.pointerId,startX:v.clientX,startY:v.clientY},s.current=null,h(null),m(R),x(null),n?.(!0))},k=v=>{let R=r.current;if(!R||R.pointerId!==v.pointerId||!R.hasMoved&&Math.hypot(v.clientX-R.startX,v.clientY-R.startY)<4)return;R.hasMoved=!0;let y=v.currentTarget.closest(".ha-message-queue"),M=0;if(y){let F=y.getBoundingClientRect(),K=28;v.clientY<F.top+K?M=-12:v.clientY>F.bottom-K&&(M=12)}let z=v.currentTarget.getRootNode().elementFromPoint?.(v.clientX,v.clientY)?.closest("[data-queue-message-id]"),ie=z?.dataset.queueMessageId,j=null;if(z&&ie&&ie!==R.messageId){let F=z.getBoundingClientRect(),K=v.clientY<F.top+F.height/2?"before":"after";j={messageId:ie,position:K}}if(y&&M!==0&&(y.scrollTop+=M),!j){x(null);return}o.current?.messageId===j.messageId&&o.current.position===j.position||x(j)},L=(v,R)=>{let y=r.current;if(!y||y.pointerId!==v.pointerId)return;v.currentTarget.hasPointerCapture?.(v.pointerId)&&v.currentTarget.releasePointerCapture?.(v.pointerId);let M=o.current;R&&y.hasMoved&&(i.current=y.messageId),R&&y.hasMoved&&M&&O(y.messageId,M.messageId,M.position),w()},$=(v,R,y)=>{let M=v.key==="ArrowUp"?-1:v.key==="ArrowDown"?1:0;if(!M)return;let T=e[y+M];T&&(v.preventDefault(),O(R,T.id,M===-1?"before":"after"))},X=v=>{let R=i.current===v;if(i.current=null,R)return;let y=s.current===v?null:v;s.current=y,h(y),n?.(r.current!==null||y!==null)},b=v=>{s.current===v&&(s.current=null,h(null),n?.(r.current!==null))};return{announcement:d,closePositionPicker:b,draggedMessageId:c,dropTarget:p,finishPointerDrag:L,handleReorderKeyDown:$,moveMessageToPosition:(v,R,y)=>{let M=e[y];if(!M||R===y){b(v);return}O(v,M.id,R<y?"after":"before"),b(v)},positionPickerMessageId:u,startPointerDrag:_,togglePositionPicker:X,updatePointerDrag:k}}import{jsx as Ie,jsxs as sr}from"react/jsx-runtime";function no(e,t){let n=e?.querySelectorAll("[data-queue-message-id]")[t];return n?(n.focus({preventScroll:!0}),n.scrollIntoView?.({block:"nearest"}),!0):!1}function Bl({blockedMessageId:e,isSendNowDisabled:t,messages:n,onEdit:r,onFocusComposer:o,onRemove:s,onReorder:i,onReorderStateChange:d,onSendNow:l,ref:c}){let m=Es(null),p=Es(null),S=Es(n),{announcement:u,closePositionPicker:h,draggedMessageId:x,dropTarget:w,finishPointerDrag:C,handleReorderKeyDown:O,moveMessageToPosition:_,positionPickerMessageId:k,startPointerDrag:L,togglePositionPicker:$,updatePointerDrag:X}=Ul({messages:n,onReorder:i,onReorderStateChange:d});if(Lm(c,()=>({focusLastMessage:()=>no(p.current,n.length-1)}),[n.length]),Hm(()=>{let f=S.current;S.current=n;let v=m.current;if(!v||n.some(M=>M.id===v))return;let R=f.findIndex(M=>M.id===v),y=Math.min(R,n.length-1);m.current=null,(R<0||!no(p.current,y))&&o()},[n,o]),n.length===0)return null;let b=(f,v)=>{if(f.target===f.currentTarget&&!(f.key!=="ArrowUp"&&f.key!=="ArrowDown")){if(f.preventDefault(),f.key==="ArrowUp"){no(p.current,v-1);return}no(p.current,v+1)||o()}};return sr("section",{"aria-label":"Queued messages",className:"ha-message-queue",children:[Ie("div",{className:"ha-message-queue-header",children:"Queued"}),Ie("ol",{ref:p,className:"ha-message-queue-list",children:n.map((f,v)=>{let R=e===f.id,y=v+1,M=R?`ha-queued-message-status-${f.id}`:void 0;return sr("li",{"aria-describedby":M,"aria-keyshortcuts":"ArrowUp ArrowDown",className:"ha-message-queue-item","data-blocked":R?"true":void 0,"data-dragging":x===f.id?"true":void 0,"data-queue-message-id":f.id,tabIndex:-1,title:R?"This message could not be sent":void 0,"data-drop-position":w?.messageId===f.id?w.position:void 0,onKeyDown:T=>b(T,v),onBlur:T=>{let P=T.relatedTarget;m.current===f.id&&(!P||!T.currentTarget.contains(P))&&(m.current=null)},onFocus:()=>{m.current=f.id},children:[Ie("button",{"aria-keyshortcuts":"ArrowUp ArrowDown","aria-label":`Reorder queued message ${y}`,className:"ha-message-queue-drag-handle",disabled:n.length<2,title:n.length>1?"Drag to reorder or click for options":void 0,type:"button",onClick:()=>$(f.id),onKeyDown:T=>O(T,f.id,v),onPointerCancel:T=>C(T,!1),onPointerDown:T=>L(T,f.id),onPointerMove:X,onPointerUp:T=>C(T,!0),children:Ie(_m,{"aria-hidden":"true"})}),k===f.id?Ie("select",{autoFocus:!0,"aria-label":`Move queued message ${y} to position`,className:"ha-message-queue-position-select",value:v,onBlur:()=>h(f.id),onChange:T=>_(f.id,v,Number(T.currentTarget.value)),children:n.map((T,P)=>sr("option",{value:P,children:["Position ",P+1,P===v?" (current)":""]},T.id))}):Ie("span",{"aria-hidden":"true",className:"ha-message-queue-icon",children:R?Ie(km,{"aria-hidden":"true"}):Ie(Nm,{"aria-hidden":"true"})}),sr("span",{className:"ha-message-queue-content",children:[Ie("span",{className:"ha-message-queue-preview",children:Tl(f)}),R?Ie("span",{className:"ha-message-queue-status",id:M,role:"status",children:"Could not send"}):null]}),sr("span",{className:"ha-message-queue-actions",children:[Ie("button",{"aria-label":`Send queued message ${y} now`,className:"ha-message-queue-action",disabled:t,title:"Send now",type:"button",onClick:()=>l(f.id),children:Ie(xm,{"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(Om,{"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(Dm,{"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 Gm,useContext as Qm,useMemo as zm}from"react";import{composeRenderProps as Wm}from"react-aria-components";import{mergeRefs as Um}from"@react-aria/utils";import{useControlledState as Bm}from"@react-stately/utils";import{createContext as Fm,useCallback as Xe,useContext as Vl,useEffect as Fl,useMemo as $l,useRef as ro,useState as Vm}from"react";import{OverlayArrow as $m,Popover as Km,composeRenderProps as Kl}from"react-aria-components";import{jsx as In}from"react/jsx-runtime";var Ps=Fm({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]=Bm(o,n,r),[l,c]=Vm(),m=ro(null),p=ro(!1),S=ro(void 0),u=ro(void 0),h=Xe(()=>{clearTimeout(S.current),clearTimeout(u.current)},[]);Fl(()=>h,[h]),Fl(()=>{if(!i)return;let _=k=>{k.key==="Escape"&&(d(!1),h())};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[h,i,d]);let x=Xe((_=!1)=>{h(),_||s<=0?d(!0):S.current=setTimeout(()=>d(!0),s)},[h,s,d]),w=Xe((_=!1)=>{h(),_||t<=0?d(!1):u.current=setTimeout(()=>d(!1),t)},[h,t,d]),C=Xe(()=>{clearTimeout(u.current)},[]),O=$l(()=>({handleCancelClose:C,handleClose:w,handleOpen:x,isOpen:i,isPointerInsideRef:p,portalContainer:l,setPortalContainer:c,triggerRef:m}),[C,w,x,i,l]);return In(Ps,{value:O,children:e})},ql=({children:e,className:t,onBlur:n,onFocus:r,onPointerEnter:o,onPointerLeave:s,ref:i,...d})=>{let{handleClose:l,handleOpen:c,isPointerInsideRef:m,setPortalContainer:p,triggerRef:S}=Vl(Ps),u=Xe(_=>{S.current=_,p(Sn(_))},[p,S]),h=$l(()=>Um(i,u),[i,u]),x=Xe(_=>{_.pointerType==="mouse"&&c(),o?.(_)},[c,o]),w=Xe(_=>{_.pointerType==="mouse"&&l(),s?.(_)},[l,s]),C=Xe(_=>{c(!0),r?.(_)},[c,r]),O=Xe(_=>{m.current||l(),n?.(_)},[l,m,n]);return In("span",{ref:h,className:me("aui-hover-card__trigger",t),"data-slot":"hover-card-trigger",onBlur:O,onFocus:C,onPointerEnter:x,onPointerLeave:w,...d,children:e})},Gl=({UNSTABLE_portalContainer:e,children:t,className:n,offset:r=8,onOpenChange:o,onPointerEnter:s,onPointerLeave:i,placement:d="top",...l})=>{let{handleCancelClose:c,handleClose:m,isOpen:p,isPointerInsideRef:S,portalContainer:u,triggerRef:h}=Vl(Ps),x=Xe(O=>{S.current=!0,c(),s?.(O)},[c,S,s]),w=Xe(O=>{S.current=!1,m(),i?.(O)},[m,S,i]),C=Xe(O=>{O||m(!0),o?.(O)},[m,o]);return In(Km,{isNonModal:!0,"data-slot":"hover-card-content",isOpen:p,offset:r,placement:d,triggerRef:h,UNSTABLE_portalContainer:e??u,className:Kl(n,O=>me("aui-hover-card__content",O)??""),onOpenChange:C,onPointerEnter:x,onPointerLeave:w,...l,children:O=>typeof t=="function"?t(O):t})},Ql=({children:e,className:t,...n})=>In($m,{"data-slot":"hover-card-arrow",className:Kl(t,r=>me("aui-hover-card__arrow",r)??""),...n,children:e??In("svg",{fill:"none",height:"12",viewBox:"0 0 12 12",width:"12",xmlns:"http://www.w3.org/2000/svg",children:In("path",{d:"M0 0C5.48483 8 6.5 8 12 0Z"})})});var ar=Object.assign(Is,{Arrow:Ql,Content:Gl,Root:Is,Trigger:ql});function zl(e){try{return new URL(e).hostname.replace(/^www\./,"")}catch{return e.split("/").pop()||e}}import{Fragment as xs,jsx as ae,jsxs as Bt}from"react/jsx-runtime";var jl=Gm({sourceType:"url"}),ir=()=>Qm(jl);function jm(e){return e.trim().charAt(0).toUpperCase()||"?"}var ks=({children:e,className:t,description:n,enablePreview:r,faviconUrl:o,href:s,locator:i,sourceType:d=s?"url":"document",title:l,...c})=>{let m=s?zl(s):void 0,S=r??(d==="url"&&!!s?!!(n||l):!!(n||i)),u=zm(()=>({description:n,domain:m,enablePreview:S,faviconUrl:o,href:s,locator:i,sourceType:d,title:l}),[n,m,S,o,s,i,d,l]),h=e??Bt(xs,{children:[ae(Ns,{}),S?ae(_s,{description:n,title:l}):null]}),x=ae("div",{className:me("aui-chat-source",t),"data-has-locator":i?"true":void 0,"data-slot":"chat-source","data-source-type":d,...c,children:h});return ae(jl,{value:u,children:S?ae(ar,{closeDelay:0,openDelay:150,children:x}):x})},Ns=({children:e,className:t,label:n,...r})=>{let{domain:o,enablePreview:s,href:i,locator:d,sourceType:l,title:c}=ir(),m=l==="url"&&i,p=e??n??(m?Bt(xs,{children:[ae(ao,{}),ae(so,{children:c??o}),d?ae(oo,{children:d}):null]}):Bt(xs,{children:[ae(io,{}),ae(so,{children:c}),d?ae(oo,{children:d}):null]}));if(m){let h=ae("a",{"aria-label":`Open source: ${c??o??i}`,className:"aui-chat-source__trigger-link",href:i,rel:"noopener noreferrer",target:"_blank",...r,children:p});return ae("span",{className:me("aui-chat-source__trigger",t),"data-slot":"chat-source-trigger",children:s?ae(ar.Trigger,{children:h}):h})}let S=[c,d].filter(Boolean).join(", ")||"Document",u=ae("span",{className:s?void 0:"aui-chat-source__trigger-link",...s?{}:r,children:p});return ae("span",{className:me("aui-chat-source__trigger",t),"data-slot":"chat-source-trigger",children:s?ae(ar.Trigger,{children:ae("button",{"aria-label":`Source: ${S}`,className:"aui-chat-source__trigger-link",type:"button",...r,children:p})}):u})},oo=({children:e,className:t,...n})=>{let{locator:r}=ir();return e??r?ae("span",{className:me("aui-chat-source__locator",t),"data-slot":"chat-source-locator",...n,children:e??r}):null},ao=({children:e,className:t,faviconUrl:n})=>{let{domain:r,faviconUrl:o,href:s,title:i}=ir(),d=i??r??s??"Source",l=n??o;if(e&&Wl.isValidElement(e)){let c=e;return Wl.cloneElement(c,{className:me("aui-chat-source__icon",t,c.props.className),"data-slot":"chat-source-icon"})}return Bt("span",{"aria-hidden":"true",className:me("aui-chat-source__icon",t),"data-slot":"chat-source-icon",children:[ae("span",{className:"aui-chat-source__icon-fallback",children:jm(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}=ir();return ae("span",{className:me("aui-chat-source__title",t),"data-slot":"chat-source-title",...n,children:e??o??r})},_s=({children:e,className:t,description:n,title:r,...o})=>{let{description:s,domain:i,enablePreview:d,href:l,locator:c,sourceType:m,title:p}=ir();if(!d)return null;let S=r??p,u=n??s,h=m==="url"&&l?Bt("a",{className:"aui-chat-source__preview-link",href:l,rel:"noopener noreferrer",target:"_blank",children:[Bt("div",{className:"aui-chat-source__preview-header",children:[ae(ao,{}),ae("span",{className:"aui-chat-source__preview-domain",children:i})]}),S?ae("div",{className:"aui-chat-source__preview-title",children:S}):null,u?ae("div",{className:"aui-chat-source__preview-description",children:u}):null]}):Bt("div",{className:"aui-chat-source__preview-link","data-source-type":"document",children:[Bt("div",{className:"aui-chat-source__preview-header",children:[ae(io,{}),ae("span",{className:"aui-chat-source__preview-domain",children:S??"Document"})]}),c?ae("div",{className:"aui-chat-source__preview-title",children:c}):null,u?ae("div",{className:"aui-chat-source__preview-description",children:u}):null]});return ae(ar.Content,{"data-slot":"chat-source-preview",offset:8,placement:"top",className:Wm(t,x=>me("aui-chat-source__preview",x)??""),...o,children:e??h})};import{Disclosure as xn}from"@heroui/react";import{composeRenderProps as Os}from"react-aria-components";import{jsx as Ft,jsxs as Ym}from"react/jsx-runtime";var Ds=({children:e,className:t,...n})=>Ft(xn,{"data-slot":"chat-sources",className:Os(t,r=>me("aui-chat-sources",r)??""),...n,children:e}),Yl=({children:e,className:t,...n})=>Ft(xn.Heading,{children:Ym(xn.Trigger,{"data-slot":"chat-sources-trigger",className:Os(t,r=>me("aui-chat-sources__trigger",r)??""),...n,children:[Ft("span",{className:"aui-chat-sources__trigger-label",children:e}),Ft(xn.Indicator,{className:"aui-chat-sources__indicator"})]})}),Xl=({children:e,className:t,...n})=>Ft(xn.Content,{"data-slot":"chat-sources-content",className:Os(t,r=>me("aui-chat-sources__content",r)??""),...n,children:Ft(xn.Body,{children:Ft("div",{className:"aui-chat-sources__content-body",children:e})})}),Jl=({children:e,className:t,role:n="list",...r})=>Ft("div",{className:me("aui-chat-sources__list",t),"data-slot":"chat-sources-list",role:n,...r,children:e});var Zl=Object.assign(ks,{DocumentIcon:io,Icon:ao,Locator:oo,Preview:_s,Root:ks,Title:so,Trigger:Ns}),lr=Object.assign(Ds,{Content:Xl,List:Jl,Root:Ds,Trigger:Yl});import{jsx as wt,jsxs as ec}from"react/jsx-runtime";function Xm(e){return`https://www.google.com/s2/favicons?domain_url=${encodeURIComponent(e)}&sz=64`}function tc({inList:e=!1,source:t}){let n="url"in t?t.url:void 0;return wt(Zl,{description:t.excerpt,faviconUrl:n?Xm(n):void 0,href:n,locator:t.locator,role:e?"listitem":void 0,sourceType:t.sourceType??"url",title:t.title})}function Jm({sources:e}){return wt(lr.List,{"aria-label":"Sources",children:e.map(t=>wt(tc,{inList:!0,source:t},t.sourceId))})}function nc({sources:e}){return e.length===0?null:e.length===1?wt("div",{"aria-label":"Sources",className:"ha-message-sources","data-count":"1",role:"group",children:wt(tc,{source:e[0]})}):ec(lr,{className:"ha-message-sources","data-count":e.length,children:[ec(lr.Trigger,{"aria-label":`${e.length} sources`,children:[wt("span",{className:"ha-sources-label",children:"Sources"}),wt("span",{"aria-hidden":"true",className:"ha-sources-count",children:e.length})]}),wt(lr.Content,{children:wt(Jm,{sources:e})})]})}function Zm(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=Zm(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 eg}from"@gravity-ui/icons";import{Button as tg}from"@heroui/react";import{jsx as sc}from"react/jsx-runtime";function ac({isDisabled:e=!1,onPress:t}){return sc(tg,{isIconOnly:!0,"aria-label":"New chat",className:"ha-icon-button ha-new-chat-button",isDisabled:e,size:"sm",variant:"ghost",onPress:t,children:sc(eg,{"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 ng=["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 ng){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 rg,Ellipsis as og,Pencil as sg,Plus as ag,TrashBin as ig}from"@gravity-ui/icons";import{Button as ln,Dropdown as cr,Input as lg,Label as dc,Modal as st,Popover as Ls,TextField as cg}from"@heroui/react";import{useCallback as ug,useRef as Hs,useState as Vt}from"react";import{Fragment as hc,jsx as Z,jsxs as Ce}from"react/jsx-runtime";var pc="rename",mc="delete",dg=80,gc=new Set;function Us({activeConversationId:e,busyConversationIds:t=gc,completedConversationIds:n=gc,groups:r,isNewConversationDisabled:o=!1,onDeleteConversation:s,onNewConversation:i,onRenameConversation:d,onSelectConversation:l,variant:c="popover"}){let[m,p]=Vt(!1),[S,u]=Vt(!1),[h,x]=Vt(null),[w,C]=Vt(null),[O,_]=Vt(""),[k,L]=Vt(null),[$,X]=Vt(!1),[b,f]=Vt(),v=Hs(0),R=Hs(0),y=Hs(null);rn(y);let T=r.flatMap(D=>D.items).find(D=>D.id===e)?.title??"New chat",P=ug(D=>{f(D??void 0)},[]),z=()=>{x(null),p(!1)},ie=D=>{!D&&Date.now()-v.current<350||(D||x(null),p(D))},j=(D,N)=>{!N&&Date.now()-R.current<350||x(N?D:null)},F=(D,N)=>{z(),C({item:D,type:N}),_(D.title),L(null),u(!0)},K=()=>{$||(L(null),u(!1))},ye=(D,N)=>{N===pc&&F(D,"rename"),N===mc&&!t.has(D.id)&&F(D,"delete")},Se=async()=>{if(!w||w.type!=="rename"||$)return;let D=O.trim();if(!D){L("Enter a name for this chat.");return}if(D===w.item.title){u(!1);return}X(!0),L(null);try{await d(w.item.id,D),C({...w,item:{...w.item,title:D}}),u(!1)}catch(N){L(N instanceof Error?N.message:"The chat could not be renamed")}finally{X(!1)}},H=async()=>{if(!(!w||w.type!=="delete"||$)){X(!0),L(null);try{await s(w.item.id),u(!1)}catch(D){L(D instanceof Error?D.message:"The chat could not be deleted")}finally{X(!1)}}},B=r.length?r.map(D=>Ce("section",{className:"ha-session-group",children:[Z("h3",{children:D.label}),Z("div",{className:"ha-session-list",children:D.items.map(N=>{let Y=N.id===e,re=t.has(N.id),oe=!re&&n.has(N.id);return Ce("div",{className:"ha-session-row","data-actions-open":h===N.id?"true":void 0,"data-active":Y||void 0,"data-completed":oe||void 0,children:[Ce("button",{"aria-current":Y?"page":void 0,className:"ha-session-select",type:"button","aria-label":oe?`${N.title}, new response available`:void 0,onClick:()=>{z(),Y||l(N.id)},children:[re?Z(tn,{className:"ha-session-title ha-session-shimmer",children:N.title}):Z("span",{className:"ha-session-title",children:N.title}),oe?Z("span",{"aria-hidden":"true",className:"ha-session-completed-dot"}):null]}),Ce(cr,{isOpen:h===N.id,onOpenChange:Me=>j(N.id,Me),children:[Z(ln,{isIconOnly:!0,"aria-label":`Chat actions for ${N.title}`,className:"ha-session-actions-trigger",size:"sm",variant:"ghost",onPointerDown:()=>{R.current=Date.now()},children:Z(og,{"aria-hidden":"true"})}),Z(cr.Popover,{className:"ha-session-actions-menu",placement:"bottom end",UNSTABLE_portalContainer:b,children:Ce(cr.Menu,{"aria-label":`Actions for ${N.title}`,onAction:Me=>ye(N,Me),children:[Ce(cr.Item,{id:pc,textValue:"Rename",children:[Z(sg,{"aria-hidden":"true"}),Z(dc,{children:"Rename"})]}),Ce(cr.Item,{id:mc,isDisabled:re,textValue:re?"Delete unavailable while responding":"Delete",variant:"danger",children:[Z(ig,{"aria-hidden":"true",className:"ha-session-delete-icon"}),Z(dc,{children:re?"Delete after response":"Delete"})]})]})})]})]},N.id)})})]},D.label)):Z("p",{className:"ha-session-empty",children:"Your recent chats will appear here."});return Ce("div",{"data-variant":c,className:c==="sidebar"?"ha-session-picker ha-session-sidebar":"ha-session-picker",children:[c==="sidebar"?Ce(hc,{children:[Ce("div",{className:"ha-session-sidebar-header",children:[Z("h2",{children:"Chats"}),Ce(ln,{fullWidth:!0,className:"ha-session-new-chat",isDisabled:o,size:"sm",variant:"tertiary",onPress:()=>{z(),i?.()},children:[Z(ag,{"aria-hidden":"true"}),"New chat"]})]}),Z("nav",{ref:y,"aria-label":"Recent chats",className:"ha-session-sidebar-history",children:B})]}):Ce(Ls,{isOpen:m,onOpenChange:ie,children:[Ce(ln,{"aria-label":"Choose a chat",className:"ha-session-trigger",size:"sm",variant:"ghost",onPointerDown:()=>{v.current=Date.now()},children:[Z("span",{className:"font-medium",children:T}),Z(rg,{"aria-hidden":"true"})]}),Z(Ls.Content,{isNonModal:!0,className:"ha-session-menu",placement:"bottom start",UNSTABLE_portalContainer:b,children:Z(Ls.Dialog,{"aria-label":"Chat history",className:"ha-session-history-dialog",children:B})})]}),Z(st.Backdrop,{className:"ha-session-modal-backdrop",isDismissable:!$,isKeyboardDismissDisabled:$,isOpen:S,UNSTABLE_portalContainer:b,onOpenChange:D=>{D||K()},children:Z(st.Container,{placement:"center",size:"sm",children:Z(st.Dialog,{className:"ha-session-modal",children:Z(pg,{dialog:w,isPending:$,mutationError:k,renameTitle:O,onClose:K,onDelete:H,onRename:Se,onRenameTitleChange:_})})})}),Z("div",{ref:P,className:"ha-session-portal","data-open":m||S||h?"true":void 0,onPointerDown:D=>{D.target?.closest(".ha-session-menu, .ha-session-actions-menu, .ha-session-modal-backdrop")||(m||h)&&z()}})]})}function pg({dialog:e,isPending:t,mutationError:n,onClose:r,onDelete:o,onRename:s,onRenameTitleChange:i,renameTitle:d}){return e?.type==="rename"?Ce("form",{onSubmit:l=>{l.preventDefault(),s()},children:[Z(st.Header,{children:Z(st.Heading,{children:"Rename chat"})}),Ce(st.Body,{children:[Z(cg,{autoFocus:!0,fullWidth:!0,"aria-label":"Chat name",isInvalid:!!n,name:"title",children:Z(lg,{maxLength:dg,value:d,variant:"secondary",onChange:l=>i(l.target.value)})}),Z(fc,{message:n})]}),Ce(st.Footer,{children:[Z(ln,{fullWidth:!0,isDisabled:t,type:"button",variant:"outline",onPress:r,children:"Cancel"}),Z(ln,{fullWidth:!0,isPending:t,type:"submit",children:t?"Saving\u2026":"Submit"})]})]}):e?.type!=="delete"?null:Ce(hc,{children:[Z(st.Header,{children:Z(st.Heading,{children:"Delete chat?"})}),Ce(st.Body,{children:[Ce("p",{children:["Are you sure you want to delete ",Ce("strong",{children:["\u201C",e.item.title,"\u201D"]}),"?"]}),Z(fc,{message:n})]}),Ce(st.Footer,{children:[Z(ln,{fullWidth:!0,isDisabled:t,variant:"outline",onPress:r,children:"Cancel"}),Z(ln,{fullWidth:!0,isPending:t,variant:"danger",onPress:()=>void o(),children:t?"Deleting\u2026":"Delete"})]})]})}function fc({message:e}){return e?Z("p",{className:"ha-session-modal-error",role:"alert",children:e}):null}import{useEffect as mg,useState as gg}from"react";import{jsx as yg}from"react/jsx-runtime";var lo=["Thinking\u2026","Analyzing request\u2026","Preparing next steps\u2026"],fg=1600,hg=5e3;function yc(){let[e,t]=gg(0);return mg(()=>{let n=e===lo.length-1,r=window.setTimeout(()=>{t(o=>(o+1)%lo.length)},n?hg:fg);return()=>window.clearTimeout(r)},[e]),yg(qr,{ariaLabel:"Working on your request\u2026",label:lo[e]??lo[0]})}function vc({now:e=()=>performance.now(),nowWallClock:t=()=>Date.now(),report:n,schedulePaint:r=o=>requestAnimationFrame(o)}){let o=new Map,s=null,i=(l,c)=>{o.has(l)||o.set(l,{painted:new Set,scheduled:new Set,startedAt:c?.startedAt??e(),startedAtWallClock:c?.startedAtWallClock??t()})},d=(l,c,m)=>{let p=o.get(l);!p||p.painted.has(c)||(p.scheduled.delete(c),p.painted.add(c),n({latencyMs:Math.max(0,Math.round(m-p.startedAt)),messageId:l,metric:c}))};return{activate(l){i(l),s=l},begin:i,complete(l){s===l&&(s=null)},getActiveMessageId(){return s},getStartedAtWallClock(l){return o.get(l)?.startedAtWallClock},markAfterPaint(l,c){let m=o.get(l);!m||m.painted.has(c)||m.scheduled.has(c)||(m.scheduled.add(c),r(()=>{d(l,c,e())}))},markPaintedAt(l,c,m){d(l,c,m)}}}function Bs(e,{hasActivity:t=!1,hasTransientData:n=!1}={}){if(!e||e.role!=="assistant")return{hasServerContent:!1,hasText:!1};let r=e.parts.some(s=>s.type==="text"&&s.text.trim().length>0),o=e.parts.some(s=>s.type==="file"||s.type==="data-component"||s.type==="data-sources");return{hasServerContent:r||o||t||n,hasText:r}}function bc({isPendingPart:e,messages:t,terminal:n}){if(n)return!1;let r=t.at(-1);return!!(r?.role==="assistant"&&r.parts.some(o=>e(o)))}function cn({attempt:e,currentAttempt:t,manualStopRequested:n,stalledStopRequested:r}){return e===t&&!n&&!r}async function Sc(e,t){return await e?.catch(()=>{}),t()}function Cc({hasPendingClientToolCalls:e,isAutoContinuationPending:t,isRecovering:n,isRunning:r,localPending:o,stalled:s}){return!s&&(r||e||o||t||n)}function Ac({hasActiveTurn:e,hasPendingClientToolCalls:t,isResuming:n,stalled:r}){return e&&!t&&!n&&!r}function Tc(e){let t=globalThis.setTimeout(e,12e4);return()=>globalThis.clearTimeout(t)}function Rc(e){let t=globalThis.setTimeout(e,12e4);return()=>globalThis.clearTimeout(t)}import{useCallback as vg,useEffect as ur,useRef as Mc,useState as wc}from"react";var bg=300;function Ec({attachments:e,draftKey:t,input:n,setAttachments:r,setInput:o}){let[s,i]=wc(null),[d,l]=wc(null),c=Mc(n),m=Mc(null);return ur(()=>{c.current=n},[n]),ur(()=>{let p=!1,S=Va(t);return queueMicrotask(()=>{p||(S&&o(u=>u||S),l(t))}),$a(t).then(u=>{p||(u.length>0&&r(h=>h.length>0?h:u),i(t))}),()=>{p=!0}},[t,r,o]),ur(()=>{if(d!==t)return;let p=()=>Uo(t,n);return m.current=window.setTimeout(p,bg),window.addEventListener("pagehide",p),()=>{m.current!==null&&window.clearTimeout(m.current),m.current=null,window.removeEventListener("pagehide",p)}},[t,n,d]),ur(()=>{if(d===t)return()=>Uo(t,c.current)},[t,d]),ur(()=>{s===t&&Ka(t,e)},[e,t,s]),vg(()=>{c.current="",m.current!==null&&window.clearTimeout(m.current),m.current=null,wr(t)},[t])}import{useCallback as Sg,useState as Cg}from"react";function Pc(e){return`${e}:model`}function Ag(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 Tg(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(Pc(e),t)}catch{}}function Fs(e,t){let[n,r]=Cg(()=>Ag(e)),o=n??t??Ma,s=Sg(i=>{r(i),Tg(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.",Rg="Voice transcription took too long. Try again.",Mg=3e4;function wg(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()},Mg);return{didTimeOut:()=>n,dispose:()=>{clearTimeout(o),e.removeEventListener("abort",r)},signal:t.signal}}function Eg(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 Pg(e,t){return{Authorization:`Bearer ${e}`,"Content-Type":t,"X-HeroUI-Agent-Protocol-Version":String(6),"X-HeroUI-Agent-SDK-Version":We}}function Ig(e){return e===413?"The recording is too long. Try a shorter message.":e===415?"This browser's recording format is not supported.":e===422?xc:e===429?"Voice dictation is busy. Wait a moment and try again.":Ic}async function kc({apiBaseUrl:e,audio:t,conversationId:n,language:r,signal:o,tokenManager:s}){let i=new URL(`${e}/v1/conversations/${encodeURIComponent(n)}/transcriptions`),d=wg(o);r?.trim()&&i.searchParams.set("language",r.trim());try{for(let l=0;l<2;l+=1){let c=await Eg(s.get(),d.signal),m=await fetch(i,{body:t,headers:Pg(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(Ig(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(Rg,{cause:l}):l}finally{d.dispose()}throw new Error(Ic)}import{Fragment as un,jsx as I,jsxs as Pe}from"react/jsx-runtime";var Dc=sn();async function Vg(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 $g({composerControlsRevealed:e,conversationEpoch:t,identityEpoch:n,identityReset:r,onClose:o,onComposerControlsReveal:s,onNewConversation:i,onReady:d,onSelectConversation:l,onUnreadChange:c,open:m,options:p,requestedConversationId:S,shellComposerEndSlot:u,shellComposerFooterSlot:h,showReadyLoader:x,tokenManager:w}){let[C,O]=ee(null),[_,k]=ee({}),L=ue(_),$=ue(C),[X,b]=ee(null),[f,v]=ee([]),[R,y]=ee(hs),M=ue(R),[T,P]=ee({}),[z,ie]=ee(0),j=C?_[C]??null:null;Kt(()=>{L.current=_,$.current=C},[C,_]);let F=W(E=>{k(U=>({...U,[E.conversationId]:E})),O(E.conversationId)},[]),K=W(E=>{k(U=>{let V=U[E];return V?.runtime?{...U,[E]:{...V,composerReady:!1,runtime:null}}:U}),$.current===E&&ie(U=>U+1)},[]),ye=W(E=>{let U=M.current,V=E(U);V!==U&&(M.current=V,y(V),c(V.completedIds.size>0))},[c]),Se=W((E,U)=>{ye(V=>tl(V,{...U,activeConversationId:m?$.current:null,conversationId:E}))},[ye,m]);be(()=>{!m||!C||ye(E=>ys(E,C))},[C,ye,m]);let H=W(E=>{ye(U=>ys(U,E)),l(E)},[ye,l]),B=W(()=>{$.current=null,O(null),b(null),i()},[i]),D=W((E,U)=>{P(V=>{let J=V[E]??Dc,se=U(J);return se===J?V:{...V,[E]:se}})},[]),N=ue(null),Y=ue(null),re=p.apiBaseUrl,oe=p.agentId,Me=$t(d),qe=W((E,U)=>{let V=ol({conversationEpoch:t,optimisticTarget:Y.current,readyConversationId:E,readyEpoch:U,requestedConversationId:S});V&&(k(J=>{let se=J[V];return!se||se.composerReady?J:{...J,[V]:{...se,composerReady:!0}}}),O(V),d(U))},[t,d,S]),at=Ae(()=>{try{return Dt(bn(p.tools,p.permissionDefaultMode)),p.permissionShowPicker&&Dt(bn(p.tools,"ask")),null}catch(E){return E instanceof Error?E.message:"The client tools could not be loaded"}},[p.permissionDefaultMode,p.permissionShowPicker,p.tools]),it=at?null:Ii(p),dn=$t(E=>ki(p,w,E)),kn=$t(E=>{Ne(p,w,E,"embed_loaded")}),Et=ue(n);Kt(()=>{if(Et.current===n)return;Et.current=n,N.current=null,Y.current=null,L.current={},$.current=null,k({}),O(null),v([]);let E=hs();M.current=E,y(E),P({}),r?w.reset():w.clear()},[n,r,w]),Kt(()=>{if(S!==null||at)return;let E=rl(Y.current,t);Y.current=E;let U=N.current;if(!U)return;let V=E.conversationId;localStorage.setItem(U.storageKey,V),b(null),v(J=>{let se=qn(J,V,Ir([]),Date.now());return Nt(U.historyKey,se),se}),k(J=>({...J,[V]:{composerReady:!1,config:U.config,conversationId:V,historyKey:U.historyKey,readyEpoch:t,runtime:null,showStartScreenWhileConnecting:!0,storageKey:U.storageKey}})),O(V)},[at,t,S]),be(()=>{let E=!1;if(at){b(at),O(null),Me(t);return}let U=N.current;if(U){let J=jr({conversationEpoch:t,optimisticTarget:Y.current,requestedConversationId:S,storedConversationId:localStorage.getItem(U.storageKey)}),se=J?L.current[J]:void 0;if(se?.runtime){b(null),k(ve=>({...ve,[se.conversationId]:{...se,readyEpoch:t}})),se.composerReady&&O(se.conversationId);return}}let V=jr({conversationEpoch:t,optimisticTarget:Y.current,requestedConversationId:S,storedConversationId:null});return b(null),O(V??(typeof S=="string"&&Mt(S)?S:null)),(async()=>{try{let J=await w.subjectHash(),se=`heroui-agent:conversation:${oe}:${J}`,ve=`heroui-agent:history:${oe}:${J}`,_e=jr({conversationEpoch:t,optimisticTarget:Y.current,requestedConversationId:S,storedConversationId:localStorage.getItem(se)})??crypto.randomUUID();localStorage.setItem(se,_e);let Ge=Vo(ve);E||v(Ge);let we=U?.config??lc(oe),Gt=we?null:Jn(w,`${re}/v1/agents/${encodeURIComponent(oe)}/config`),ut=Jn(w,`${re}/v1/agents/${encodeURIComponent(oe)}/conversations`).catch(()=>null),Nn=await dn(_e),pn=we??(Gt?await Vg(Gt):null);if(!pn||!Nn)throw new Error("The data assistant could not be loaded");we||cc(oe,pn);let De=Ge.find(dt=>dt.id===_e),_n=qn(Ge,_e,De?.title??Ir([]),De?.updatedAt??Date.now());if(_n!==Ge&&Nt(ve,_n),!E){N.current={config:pn,historyKey:ve,storageKey:se},v(_n);let dt=L.current[_e],le={composerReady:!1,config:pn,conversationId:_e,historyKey:ve,readyEpoch:t,runtime:Nn.runtime,showStartScreenWhileConnecting:dt?.showStartScreenWhileConnecting??S===null,storageKey:se};F(le)}ut.then(async dt=>{if(!dt?.ok)return;let le=Pr((await dt.json()).conversations);E||v(Qt=>{let On=$o(Qt,le);return Nt(ve,On),On})}),kn(_e)}catch(J){if(!E&&S===void 0&&Ei(J)){B();return}E||(b(J instanceof Error?J.message:"The data assistant could not be loaded"),Me(t))}})(),()=>{E=!0}},[re,F,it,at,t,n,oe,S,z,B,w]);let Je=W((E,U,V)=>{let J=N.current?.historyKey;J&&v(se=>{let ve=qn(se,E,U,Date.now(),V);return Nt(J,ve),ve})},[]),de=W(E=>{k(U=>{let V=U[E];return V?.showStartScreenWhileConnecting?{...U,[E]:{...V,showStartScreenWhileConnecting:!1}}:U})},[]),Oe=W(async(E,U)=>{let V=async()=>{let se=await w.get(),ve=new Headers(U.headers);for(let[Ge,we]of Object.entries(Qr(se)))ve.set(Ge,we);let _e=await fetch(`${re}/v1/conversations/${encodeURIComponent(E)}`,{...U,headers:ve});if(_e.status===401){w.clear();let Ge=await w.get(),we=new Headers(U.headers);for(let[Gt,ut]of Object.entries(Qr(Ge)))we.set(Gt,ut);_e=await fetch(`${re}/v1/conversations/${encodeURIComponent(E)}`,{...U,headers:we})}return _e},J=await V();if(U.method==="DELETE"&&J.status===409&&(J=await sl({initialResponse:J,request:V})),!J.ok)throw new Error(U.method==="DELETE"?"The chat could not be deleted":"The chat could not be renamed")},[re,w]),bt=W(async(E,U)=>{await Oe(E,{body:JSON.stringify({title:U}),headers:{"Content-Type":"application/json"},method:"PATCH"});let V=N.current?.historyKey;V&&v(J=>{let se=J.map(ve=>ve.id===E?{...ve,title:U}:ve);return Nt(V,se),se})},[Oe]),lt=W(async E=>{await Oe(E,{method:"DELETE"});let U=N.current;U&&(v(V=>{let J=V.filter(se=>se.id!==E);return Nt(U.historyKey,J),J}),localStorage.removeItem(Tr(U.storageKey,E)),localStorage.removeItem(No(U.storageKey,E)),wr(Bo(U.storageKey,E)),Ml(Ts(U.storageKey,E)),k(V=>{if(!(E in V))return V;let J={...V};return delete J[E],J}),ye(V=>nl(V,E)),P(V=>{if(!(E in V))return V;let J={...V};return delete J[E],J}),C===E&&B())},[C,ye,Oe,B]),ge=Ae(()=>{let E=p.suggestedPrompts;return E?.length?Object.fromEntries(Object.entries(_).map(([U,V])=>[U,{...V,config:{...V.config,suggestedPrompts:E}}])):_},[p.suggestedPrompts,_]),Pt=C?ge[C]?.config??null:null,qt=ue(null);be(()=>{!m||!j?.runtime||qt.current===j.conversationId||(qt.current=j.conversationId,Ne(p,w,j.conversationId,"opened"))},[m,p,j,w]);let It=at??X,dr=Ae(()=>Go(f),[f]),uo=f.find(E=>E.id===C)?.title??"New chat",St=N.current?"Loading chat\u2026":"Loading assistant\u2026",ct=S===null&&(!j||j.showStartScreenWhileConnecting);return I(un,{children:Pe(Aa,{keepMounted:!0,agentId:p.agentId,shouldCloseOnInteractOutside:p.shouldCloseOnInteractOutside,defaultExpanded:p.panelExpanded,expandable:!x&&p.panelExpandable,expandedTitle:uo,name:Pt?.name??"Data assistant",open:m,showBetaBadge:p.showBetaBadge,viewMode:p.viewMode,actionsSlot:x?I(un,{}):I(ac,{isDisabled:ct,onPress:B}),expandedSidebarSlot:x?void 0:I(Us,{activeConversationId:C,busyConversationIds:R.busyIds,completedConversationIds:R.completedIds,groups:dr,isNewConversationDisabled:ct,variant:"sidebar",onDeleteConversation:lt,onNewConversation:B,onRenameConversation:bt,onSelectConversation:H}),historySlot:x?I(un,{}):I(Us,{activeConversationId:C,busyConversationIds:R.busyIds,completedConversationIds:R.completedIds,groups:dr,onDeleteConversation:lt,onRenameConversation:bt,onSelectConversation:H}),onClose:o,onNewConversation:x?void 0:B,children:[It?I("div",{className:"ha-loading",role:"alert",children:It}):x?I(Ca,{indicator:I(Lg,{"aria-hidden":!0,color:"current",size:"md"})}):!j||!j.runtime||!Pt?ct&&j?I(Lc,{composerControlsRevealed:e,loadingLabel:St,options:p,route:j,onComposerControlsReveal:s},`pending-${t}`):I(Yr,{agentId:p.agentId,composerControlsAvailable:p.composerControlsAvailable,composerControlsRevealed:e,composerEndSlot:u,composerFooterSlot:h,greeting:p.greeting,loadingLabel:St,placeholder:p.composerPlaceholder,showStartScreen:ct,suggestedPrompts:p.suggestedPrompts??[],composerStartSlot:I(Fc,{agentId:p.agentId,options:p}),onComposerControlsReveal:s},`pending-${t}`):null,I("div",{className:"ha-runtime-content",hidden:!!It||x,children:I(cl,{activeConversationId:It?null:C,routes:ge,children:(E,U)=>I(Ha,{variant:E.config.surfaceVariant,children:E.runtime?I(Bg,{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:qe,onRuntimeRevisionStale:K,onConversationStarted:V=>{de(E.conversationId),Je(E.conversationId,V)},onConversationTitled:V=>Je(E.conversationId,V,{replaceTitle:!0})})}):null})})})]})})}function Lc({composerControlsRevealed:e,loadingLabel:t,onComposerControlsReveal:n,options:r,route:o}){return I(Yr,{showStartScreen:!0,agentId:r.agentId,composerControlsAvailable:r.composerControlsAvailable,composerControlsRevealed:e,composerStartSlot:I(Fc,{agentId:r.agentId,options:r}),greeting:r.greeting,loadingLabel:t,placeholder:r.composerPlaceholder,suggestedPrompts:r.suggestedPrompts??[],composerEndSlot:I(Kg,{conversationId:o.conversationId,options:r,storageKey:o.storageKey}),composerFooterSlot:r.composerDisclaimer?I("p",{className:"ha-footnote",children:Io(r.composerDisclaimer)}):null,onComposerControlsReveal:n})}function Fc({agentId:e,options:t}){let n=ue(null),[r,o]=ee(()=>ko(e)),[s,i]=ee(null),d=l=>{let c=Mn(l,t.composerAttachmentContentTypes);o(c.files),i(c.error),ka(e,c.files)};return t.composerAttachmentContentTypes.length===0?null:Pe(un,{children:[I("input",{ref:n,multiple:!0,accept:t.composerAttachmentAccept,"aria-label":"Choose files to attach",className:"ha-file-input",type:"file",onChange:l=>{d(Array.from(l.currentTarget.files??[])),l.currentTarget.value=""}}),r.length>0?I(Do,{"aria-label":"Selected attachments",className:"ha-attachments",offset:1,size:24,children:r.map(l=>I(ps,{file:l,onRemove:()=>d(r.filter(c=>c!==l))},`${l.name}-${l.size}-${l.lastModified}`))}):null,I("button",{"aria-label":"Attach files",className:"ha-attach",type:"button",onClick:()=>n.current?.click(),children:I(Bc,{"aria-hidden":"true"})}),s?I("span",{className:"ha-dictation-error",role:"alert",children:s}):null]})}function Kg({conversationId:e,options:t,storageKey:n}){let r=Tr(n,e),[o,s]=ee(()=>Rr(r)??t.permissionDefaultMode),{selectedModelId:i,setSelectedModelId:d}=Fs(n,t.composerDefaultModel),l=c=>{s(c),Mr(r,c)};return Pe(un,{children:[t.permissionShowPicker&&t.tools.length>0?I(kr,{"aria-label":"Tool permissions",className:"ha-permission-picker",value:o,onChange:l}):null,t.composerModelPicker?I(xr,{"aria-label":"AI model",className:"ha-model-picker",options:xo,placement:t.permissionShowPicker&&t.tools.length>0?"top":"top start",value:i,onChange:d}):null,t.composerDictation?Pe("button",{disabled:!0,"aria-label":"Dictate message",className:"ha-dictation",type:"button",children:[I(Uc,{"aria-hidden":"true"}),I($n,{children:"Dictate message"})]}):null]})}function 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:C}){let{selectedModelId:O,setSelectedModelId:_}=Fs(w,u.composerDefaultModel),k=No(w,o),L=Tr(w,o),$=u.composerAttachmentAccept,X=Ae(()=>({key:$}),[$]),[b,f]=ee(()=>({files:Mn(ko(u.agentId),u.composerAttachmentContentTypes).files,policy:X})),[v,R]=ee(()=>({error:null,policy:X})),y=Ae(()=>b.policy===X?b.files:[],[X,b]),M=v.policy===X?v.error:null,T=W(a=>{f(g=>{let A=g.policy===X?g.files:[],q=typeof a=="function"?a(A):a;return{files:Mn(q,u.composerAttachmentContentTypes).files,policy:X}})},[X,u.composerAttachmentContentTypes]),P=W(a=>R({error:a,policy:X}),[X]),[z,ie]=ee(()=>{let a=u.permissionShowPicker?Rr(k):void 0;return a?{modelId:void 0,permissionMode:a}:void 0}),[j,F]=ee({}),[K,ye]=ee({}),[Se,H]=ee(!1),[B]=ee(()=>Ea(u.agentId)),[D,N]=ee(()=>B?.submitted?"":B?.prompt??""),[Y,re]=ee(()=>B?.submitted?{files:y,id:B.messageId,text:B.prompt}:null),[oe,Me]=ee(()=>{let a=u.permissionShowPicker?Rr(L):void 0;return{configuredDefaultMode:u.permissionDefaultMode,selectedMode:a??u.permissionDefaultMode}}),[qe,at]=ee(!1),[it,dn]=ee(!0),[kn,Et]=ee(!1),[Je,de]=ee(!1),[Oe,bt]=ee(()=>new Set),[lt,ge]=ee(null),[Pt,qt]=ee(0),[It,dr]=ee(0),[uo,St]=ee(!1),[ct,E]=ee(!1),[U,V]=ee(null),[J,se]=ee({}),ve=W(a=>{u.permissionShowPicker?Mr(k,a.permissionMode):_o(k),ie(a)},[k,u.permissionShowPicker]),_e=oe.configuredDefaultMode===u.permissionDefaultMode?oe.selectedMode:u.permissionDefaultMode,Ge=W(a=>{Mr(L,a),Me({configuredDefaultMode:u.permissionDefaultMode,selectedMode:a})},[u.permissionDefaultMode,L]),we=u.permissionShowPicker?_e:u.permissionDefaultMode,Gt=u.permissionShowPicker?z?.permissionMode??we:u.permissionDefaultMode,ut=Ae(()=>bn(u.tools,Gt),[Gt,u.tools]),Nn=Ae(()=>Dt(ut),[ut]),pn=Ae(()=>Fi(Nn),[Nn]),De=Ae(()=>new Map(ut.map(a=>[a.name,a])),[ut]),_n=Ae(()=>new Set(ut.map(a=>a.name)),[ut]),dt=ue(new Set),le=ue(null),Qt=ue(new Set),On=ue(!1),Le=ue(s),po=ue(null),Ze=ue(!1),He=ue(!1),zt=ue(null),pr=ue(0),pt=ue(0),xt=ue(null),Wt=ue(null),mr=ue(null),mo=ue(new Set),go=ue(new Map),Dn=ue(()=>{}),$s=ue(null),Ks=ue(null),Ct=ue(null),Ee=Ae(()=>vc({report:({latencyMs:a,messageId:g,metric:A})=>{Ne(u,C,o,A,{latencyMs:a,latencyOrigin:"user_submit",messageId:g})}}),[o,u,C]),Vc=Ae(()=>Bo(w,o),[o,w]),Ln=Ae(()=>Ts(w,o),[o,w]),qs=Ec({attachments:y,draftKey:Vc,input:D,setAttachments:T,setInput:N}),$c=W((a,{language:g,signal:A})=>kc({apiBaseUrl:u.apiBaseUrl,audio:a,conversationId:o,...g?{language:g}:{},signal:A,tokenManager:C}),[o,u.apiBaseUrl,C]),{cancel:Qe,elapsedSeconds:fo,error:ho,isActive:ke,isRecording:Kc,isSupported:jt,isTranscribing:Hn,start:Gs,stop:Qs,stream:qc}=Zo({onValueChange:N,transcribe:$c,value:D}),yo=t||ke||y.length>0||M!==null||ho!==null,zs=W(()=>{u.composerControlsAvailable&&i()},[i,u.composerControlsAvailable]),Gc=a=>{Kn(u.agentId,!0,a.currentTarget),zs()},Qc=a=>{let g=a.currentTarget.querySelector(".ha-composer");g&&xa(g,a.relatedTarget)||Kn(u.agentId,!1)};be(()=>{Le.current=s},[s]),be(()=>{u.composerDictation||Qe()},[Qe,u.composerDictation]),be(()=>{e||Qe()},[e,Qe]);let mn=u.composerModelPicker?O:u.composerDefaultModel,gn=W(a=>{Le.current=a,m(o,()=>a)},[o,m]),et=W(async(a,{applyAfterPersist:g=!1}={})=>{let A=Le.current,q=a(A);if(q!==A){g?Le.current=q:gn(q);try{await Rs(Ln,q)}catch(ce){throw Le.current===q&&(g?Le.current=A:gn(A)),ce}g&&Le.current===q&&gn(q)}},[gn,Ln]),ze=W(a=>{et(a).catch(()=>{})},[et]),zc=W(a=>{Qt.current.add(a),et(g=>rr(Pn(g,a,"admitted"),a)).catch(()=>{})},[et]);be(()=>{let a=!1;return dn(!0),Rl(Ln).then(async g=>{if(a)return;let A=wl(g,Le.current),q=Qt.current,ce={...A,messages:A.messages.filter(he=>!q.has(he.id))};gn(ce),await Rs(Ln,ce)}).catch(()=>{}).finally(()=>{a||dn(!1)}),()=>{a=!0}},[gn,Ln]);let gr=W(()=>{Ze.current=!1,He.current=!1,xt.current=null,E(!1)},[]),Ws=W(a=>{cn({attempt:a,currentAttempt:pt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current})&&de(!1)},[]),{agent:Yt,connectionEpoch:fr,connectionError:mt,isHydrating:Wc,isReconnecting:js,retryConnection:jc}=zg({conversationId:o,onRuntimeRevisionStale:S,onTurnAdmitted:zc,options:u,runtime:h,tokenManager:C}),Yc=$t(p);Kt(()=>{Yc(o,r)},[e,r,o]),be(()=>{if(it||fr===0)return;let a=[];for(let q of Le.current.messages)vt(q)==="sending"&&a.push(q.id);if(a.length===0){Et(!1);return}let g=!1,A;return Et(!0),(async()=>{let q=[];for(let pe=0;pe<a.length;pe+=50)q.push(a.slice(pe,pe+50));let ce=async pe=>{let rt=await Promise.all(q.map(async gt=>({response:await Yt.call(Fa,[{protocolVersion:6,turnIds:gt}],{timeout:15e3}),turnIds:new Set(gt)}))),Be=new Set;for(let{response:gt,turnIds:wo}of rt){if(gt.protocolVersion!==6||!Array.isArray(gt.turns))throw new Error("Invalid turn admission status response");for(let vn of gt.turns)vn.status==="admitted"&&wo.has(vn.turnId)&&Be.add(vn.turnId)}return Be.size===a.length||pe>=4?Be:(await new Promise(gt=>window.setTimeout(gt,500)),ce(pe+1))},he;try{he=await ce(0)}catch{g||(A=window.setTimeout(()=>dr(pe=>pe+1),1e3));return}if(!g){for(let pe of he)Qt.current.add(pe);await et(pe=>El(pe,he))}})().catch(()=>{}).finally(()=>{g||Et(!1)}),()=>{g=!0,A!==void 0&&window.clearTimeout(A)}},[Yt,et,fr,it,It]);let Xc=Ae(()=>new Proxy(Yt,{get(a,g){if(g==="send")return q=>a.send(Vi(q));let A=Reflect.get(a,g,a);return typeof A=="function"?A.bind(a):A}}),[Yt]),Q=Ng({agent:Xc,cancelOnClientAbort:!1,experimental_throttle:60,getInitialMessages:null,onData:a=>{if(a.type!=="data-conversation-title"){let g=Ee.getActiveMessageId();g&&mo.current.add(g)}if(a.type==="data-progress"&&a.data&&typeof a.data=="object"&&"label"in a.data&&typeof a.data.label=="string"&&ge(a.data.label),a.type==="data-conversation-title"&&a.data&&typeof a.data=="object"&&"title"in a.data&&typeof a.data.title=="string"&&a.data.title.trim()&&c(a.data.title.trim()),a.type==="data-component"){let g=a.data&&typeof a.data=="object"&&"kind"in a.data?a.data:null;Ne(u,C,o,"component_rendered",{componentType:g?.kind})}a.type==="data-runtime-timing"&&uc(u.agentId,o,a.data)},onError:a=>{if(Ze.current||He.current){xt.current=null,de(!1),ge(null),queueMicrotask(()=>Dn.current());return}xt.current=a,de(!1),ge(null),Ne(u,C,o,"failure",{messageId:Ee.getActiveMessageId()??void 0,source:"cloudflare-chat"})},onFinish:({isError:a})=>{if(Ze.current||He.current){xt.current=null,de(!1),ge(null),queueMicrotask(()=>Dn.current());return}a&&!xt.current&&(xt.current=new Error("The request could not be completed")),de(!1),ge(null)},resume:!0,syncMessagesToServer:!1,tools:pn}),{clearError:Ys,setMessages:Xs}=Q;Kt(()=>{Dn.current=Ys},[Ys]);let At=Q.status==="submitted"||Q.status==="streaming"||Q.isStreaming,kt=uo||ct,Un=!kt&&Q.isToolContinuation,vo=!!(kt||Q.error||Q.connectionError||mt),Xt=Ae(()=>!vo&&(Oe.size>0||bc({isPendingPart:a=>{let g=a,A=Vs(g);return Dl({isClientTool:!!(A&&De.has(A)),state:g.state})},messages:Q.messages,terminal:vo})),[Q.messages,De,vo,Oe]),Ue=Cc({hasPendingClientToolCalls:Xt,isAutoContinuationPending:Un,isRecovering:Q.isRecovering,isRunning:At,localPending:Je,stalled:ct});be(()=>{if(Ue)return;let a=Ee.getActiveMessageId();a&&(Ee.complete(a),mo.current.delete(a),go.current.delete(a))},[Ue,Ee]);let Jt=!mt&&(Wc||js||it||kn),bo=Jt||Ue,So=kt||!!Q.error||!!Q.connectionError||!!mt,Tt=bo||So,Js=Il({hasChatError:!!(Q.error||Q.connectionError||mt),hasPendingClientToolCalls:Xt,hasReadyClientToolContinuation:Un,isLocalPending:Je,isResuming:Jt,isRunning:At,recoveryError:kt}),Zs=$t(l);be(()=>{z&&!At&&!Xt&&!Je&&!Jt&&!Un&&(_o(k),ie(void 0))},[z,k,Xt,Un,Jt,At,Je]),be(()=>{Zs(o,{busy:bo,failed:So,turnActive:Ue})},[So,o,Ue,bo]),be(()=>()=>{Zs(o,{busy:!1,failed:!0,turnActive:!1})},[o]);let Rt=Q.messages.at(-1),ea=At&&Rt?.role==="assistant"?Rt.id:null,Jc=Rt?.role==="assistant"&&(Xt||Un||Q.isRecovering)?Rt.id:null,Zt=il({continuingAssistantMessageId:Jc,isActiveTurn:Ue,streamingAssistantMessageId:ea,trackedActivityMessageId:Wt.current}),Co=Zt===Rt?.id?Rt:void 0,ta=!!(Co&&ns(Co,De,{isStreaming:!0}).length>0),Zc=Bs(Co).hasServerContent;be(()=>{if(Ue&&Zt){if(Wt.current===Zt)return;let A=mr.current??Date.now();Wt.current=Zt,F(q=>({...q,[Zt]:{startedAt:A}}));return}let a=Wt.current;if(Ue||!a)return;let g=Date.now();F(A=>{let q=A[a];return!q||q.completedAt?A:{...A,[a]:{...q,completedAt:g}}}),Wt.current=null,mr.current=null},[Zt,Ue]);let hr=W(async(a,g,A)=>{Q.addToolOutput({output:A,toolCallId:g,toolName:a})},[Q.addToolOutput]),Ao=W((a,g)=>{bt(A=>{if(A.has(a)===g)return A;let q=new Set(A);return g?q.add(a):q.delete(a),q})},[]),yr=W(async(a,g)=>{await Di({activeToolCallIds:dt.current,run:async()=>{Ao(g.toolCallId,!0),ge("Fetching live data\u2026");try{await Ui({conversationId:o,execute:A=>Hi({context:u.context,execution:A,input:g.input,tool:a}),input:g.input,rpc:{claim:A=>Yt.call("claimClientToolEffect",[A],{timeout:cs}),complete:A=>Yt.call("completeClientToolEffect",[A],{timeout:cs})},submitOutput:A=>hr(a.name,g.toolCallId,A),toolCallId:g.toolCallId,toolName:a.name}),ge("Analyzing the results\u2026")}finally{Ao(g.toolCallId,!1)}},toolCallId:g.toolCallId})},[Yt,o,u.context,Ao,hr]),eu=W((a,g,A)=>{let q=g.toolCallId;if(se(ce=>({...ce,[q]:A?"approved":"rejected"})),ge(A?"Applying your change\u2026":"Updating your request\u2026"),Ne(u,C,o,A?"action_approved":"action_declined"),g.approval?.id)Q.addToolApprovalResponse({approved:A,id:g.approval.id});else if(!A)hr(a,q,{reason:"The user declined this tool call",rejected:!0});else{se(ce=>({...ce,[q]:"rejected"}));return}if(A){let ce=De.get(a);ce&&yr(ce,g).catch(()=>{})}else dt.current.add(q)},[Q.addToolApprovalResponse,De,o,yr,u,hr,C]);be(()=>{for(let a of Q.messages)if(a.role==="assistant")for(let g of a.parts){let A=Vs(g);if(!A)continue;let q=De.get(A);!q||dt.current.has(g.toolCallId)||Li({approvalApproved:g.approval?.approved,decision:J[g.toolCallId],needsApproval:q.needsApproval===!0,state:g.state})&&yr(q,g).catch(()=>{})}},[Q.messages,De,fr,yr,J]);let To=W(a=>{H(_a(a,{hasAttachments:yo&&y.length>0}))},[y.length,yo]);Kt(()=>{To(Ct.current)},[D,ke,To]);let na=W(a=>{if(a.length===0)return;let g=Mn([...y,...a],u.composerAttachmentContentTypes);P(g.error),T(g.files)},[y,u.composerAttachmentContentTypes,P,T]),ra=W(()=>{Qe(),qs(),N(""),T([]),P(null),V(null)},[Qe,qs,P,T]),tu=W(()=>Ct.current?.focus(),[]),Ro=W(()=>{if(Hn){Qe(),requestAnimationFrame(()=>Ct.current?.focus());return}if(ke){Qs(),requestAnimationFrame(()=>Ct.current?.focus());return}Gs()},[Qe,ke,Hn,Gs,Qs]);be(()=>{if(!e||!u.composerDictation||!jt)return;let a=g=>{Zi(g)&&(g.preventDefault(),Ct.current?.focus({preventScroll:!0}),Ro())};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e,jt,u.composerDictation,Ro]),Kt(()=>{e&&Ia(u.agentId,Ct.current)},[e,u.agentId]);let oa=W(async a=>{let g=++pt.current,A=Q.messages,q=A.findLast(Be=>Be.role==="user")?.id,ce=A.findLast(Be=>Be.role==="assistant")?.id,he=u.permissionShowPicker?a.permissionMode??we:u.permissionDefaultMode,pe=Dt(bn(u.tools,he));ve({modelId:a.modelId,permissionMode:he}),Wt.current=null,go.current.set(a.id,ce),Ee.activate(a.id);let rt=Ee.getStartedAtWallClock(a.id)??Date.now();mr.current=rt,gr(),po.current={previousUserMessageId:q??null,scrollKey:crypto.randomUUID()},de(!0),St(!1),E(!1),ge(Yn("accepted")),d(Ko(a.text,a.files));try{let Be=await Hc(u,a.selection);if(!cn({attempt:g,currentAttempt:pt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;a.files.length>0&&ge("Uploading attachments\u2026");let gt=await Oi({acceptedContentTypes:u.composerAttachmentContentTypes,apiBaseUrl:u.apiBaseUrl,conversationId:o,files:a.files,tokenManager:C});if(!cn({attempt:g,currentAttempt:pt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;Ne(u,C,o,"message_sent",{messageId:a.id});let wo=us({clientSubmittedAt:rt,clientTools:pe,generateConversationTitle:a.generateConversationTitle,imageSearch:u.imageSearch,modelId:a.modelId,newsSearch:u.newsSearch,pageContext:Be,permissionMode:he,turnId:a.id,webSearch:u.webSearch});ge(Yn("accepted")),await Q.sendMessage(xl(a,gt),{body:wo});let vn=xt.current;if(vn)throw xt.current=null,vn}catch(Be){if(!cn({attempt:g,currentAttempt:pt.current,manualStopRequested:Ze.current,stalledStopRequested:He.current}))return;throw Be instanceof Error&&P(Be.message),Xs(A),Q.clearError(),St(!1),E(!1),de(!1),ge(null),Be}},[Q,ve,we,o,d,u,gr,P,Xs,C,Ee]),Bn=W((a,{resumeDrainAfter:g=!0}={})=>{le.current=a.id,oa(a).catch(()=>{le.current===a.id&&(le.current=null),Qt.current.has(a.id)||ze(A=>yt(Pn(As(A,{...a,deliveryStatus:"pending"},"prepend"),a.id,"pending"),a.id))}).finally(()=>{le.current===a.id&&(le.current=null),g&&qt(A=>A+1)})},[oa,ze]),en=W((a,g,A=g?.generateConversationTitle??!0)=>{let q=a.trim();if(!q&&y.length===0)return;let ce=!Tt&&!le.current&&Le.current.messages.length===0,he=Nl({activeMessageId:le.current,authoritativeMessageCount:Q.messages.length,isNewChatStartScreen:x,queuedMessageCount:Le.current.messages.length}),pe={files:y,...he&&!A?{generateConversationTitle:!1}:{},id:g?.messageId??crypto.randomUUID(),...he?{isInitialTurn:!0}:{},...mn?{modelId:mn}:{},permissionMode:we,selection:U,text:q};ce&&(pe.deliveryStatus="sending"),he&&re({files:pe.files,id:pe.id,text:pe.text}),Ee.begin(pe.id,g),g?.firstFeedbackPaintedAt!==void 0&&Ee.markPaintedAt(pe.id,"first_feedback_paint",g.firstFeedbackPaintedAt),ce&&(le.current=pe.id),et(rt=>or(As(rt,pe),!1),{applyAfterPersist:!0}).then(()=>{ra(),ce?Bn(pe):qt(rt=>rt+1)}).catch(rt=>{ce&&(le.current=null),he&&re(null),g&&N(q),P(rt instanceof Error?rt.message:"This message could not be saved before sending")})},[y,mn,we,et,Q.messages.length,Tt,ra,U,Bn,P,x,Ee]),fn=n.suggestedPrompts,nu=$t(a=>en(a.prompt,a));be(()=>{if(!e)return;Na(u.agentId);let a=Pa(u.agentId);a&&(a.submitted?nu(a):N(g=>g||a.prompt))},[e,u.agentId]),be(()=>{if(!e||!u.suggestedPromptShortcuts||Q.messages.length>0||fn.length===0)return;let a=g=>{let A=el(g,fn.length);if(A===null)return;let q=fn[A];q&&(g.preventDefault(),en(q,void 0,!1))};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e,Q.messages.length,u.suggestedPromptShortcuts,en,fn]);let sa=a=>{a.preventDefault(),en(D)},ru=$t(async a=>{try{await et(g=>Pn(g,a.id,"sending"))}catch(g){le.current===a.id&&(le.current=null),P(g instanceof Error?g.message:"This message could not be saved before sending"),ze(A=>yt(A,a.id));return}le.current===a.id&&Bn({...a,deliveryStatus:"sending"})}),ou=W(a=>{On.current=a,at(a)},[]);be(()=>{let a=Ll({activeMessageId:le.current,isBusy:Tt,isReordering:qe,queue:s});a&&(le.current=a.id,queueMicrotask(()=>{if(On.current){le.current===a.id&&(le.current=null);return}le.current===a.id&&ru(a)}))},[Tt,qe,s,Pt]);let su=W(a=>{re(g=>g?.id===a?null:g),ze(g=>rr(g,a))},[ze]),au=W((a,g,A)=>{ze(q=>Al(yt(q,null),a,g,A))},[ze]),iu=W(a=>{let g=Le.current.messages.find(A=>A.id===a);g&&(Qe(),N(g.text),T(g.files),g.modelId&&_(g.modelId),g.permissionMode&&Ge(g.permissionMode),V(g.selection),H(!0),re(A=>A?.id===a?null:A),ze(A=>rr(yt(A,null),a)),requestAnimationFrame(()=>Ct.current?.focus()))},[Qe,T,ze,Ge,_]),lu=W(a=>{if(Tt||le.current)return;let g=Le.current.messages.find(A=>A.id===a);g&&(le.current=g.id,et(A=>or(Pn(yt(A,null),a,"sending"),!0)).then(()=>{le.current===g.id&&Bn({...g,deliveryStatus:"sending"},{resumeDrainAfter:!1})}).catch(A=>{le.current===g.id&&(le.current=null),P(A instanceof Error?A.message:"This message could not be saved before sending")}))},[et,Tt,Bn,P]),aa=W(()=>{let a=le.current;pr.current+=1,pt.current+=1,Ze.current=!0,He.current=!1,le.current=null,re(null),ze(A=>or(a&&!Qt.current.has(a)?Pn(yt(A,null),a,"pending"):yt(A,null),!0)),de(!1),ge(null),St(!1),E(!1),Ne(u,C,o,"stopped");let g=Promise.resolve().then(()=>Q.stop()).catch(()=>{}).finally(()=>{zt.current===g&&(zt.current=null),Dn.current()});zt.current=g},[Q,o,u,ze,C]),cu=$t(()=>{if(Ze.current||He.current)return;let a=le.current;pr.current+=1,pt.current+=1,He.current=!0,le.current=null,ze(A=>or(a?rr(yt(A,null),a):yt(A,null),!0)),de(!1),ge(null),St(!1),E(!0),Ne(u,C,o,"turn_stalled",{messageId:a??void 0,source:"client-inactivity-watchdog"});let g=Promise.resolve().then(()=>Q.stop()).catch(()=>{}).finally(()=>{zt.current===g&&(zt.current=null),Dn.current(),He.current&&E(!0)});zt.current=g});be(()=>{if(Ac({hasActiveTurn:Ue,hasPendingClientToolCalls:Xt,isResuming:Jt,stalled:ct}))return Tc(cu)},[Q.isRecovering,Q.messages,Q.status,fr,Ue,Xt,Jt,Je,lt,ct]);let uu=W(a=>{if(Ne(u,C,o,`component_${a.type}`,{actionId:"actionId"in a?a.actionId:void 0,componentId:a.componentId,format:"format"in a?a.format:void 0,hasToolName:"toolName"in a}),a.type==="tool"){let g=Sa(De,a.toolName);if(g){(async()=>{try{let A=Ar(g,a.args),q=`component-action-${crypto.randomUUID()}`;await g.execute(A,u.context,{conversationId:o,idempotencyKey:`heroui-agent-component-action:${o}:${q}`,toolCallId:q})}catch{}})();return}}Qi(a,{fillComposer:g=>{Qe(),N(g),H(!0),requestAnimationFrame(()=>Ct.current?.focus())},setSelection:V,submitPrompt:en})},[Qe,De,o,u,en,C]),du=W(a=>{let g=a.parts.filter(A=>A.type==="text").map(A=>A.text).join(`
4
4
 
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as m,b as a}from"./chunk-ITIOK4RN.js";import"./chunk-366EZBW3.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-UHHKMESI.js";import{a as s}from"./chunk-7KCGPNEN.js";import{a as p}from"./chunk-4JEZZR5J.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};
1
+ import{a as m,b as a}from"./chunk-P76TTRPR.js";import"./chunk-EJIPFUZ2.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-UHHKMESI.js";import{a as s}from"./chunk-7KCGPNEN.js";import{a as p}from"./chunk-4JEZZR5J.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-ITIOK4RN.js";import"./chunk-366EZBW3.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-UHHKMESI.js";import{a as g}from"./chunk-7KCGPNEN.js";import"./chunk-4JEZZR5J.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};
1
+ import{a as i,b as p}from"./chunk-P76TTRPR.js";import"./chunk-EJIPFUZ2.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-UHHKMESI.js";import{a as g}from"./chunk-7KCGPNEN.js";import"./chunk-4JEZZR5J.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.16",u="https://api.heroui.pro";var d=e.enum(["light","dark","system"]),y=e.enum(["outline","plain","surface","surface-secondary"]),f=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=>!f.has(t.toLowerCase()),{message:"Identity id is reserved"}),I=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()}),g=e.object({anonymousId:c.optional(),identity:I,profile:S.optional()}),h=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 _=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:y.default("plain"),theme:d});var 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=g.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 l=(t.apiBaseUrl?.trim()||u).replace(/\/$/,""),r;try{r=await fetch(`${l}/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(A){throw new n("HeroUI Agent authentication is unavailable",503,{cause:A})}if(!r.ok)throw new n("HeroUI Agent authentication failed",r.status);let p=h.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};
1
+ import{z as e}from"zod";var m="0.2.0-beta.17",u="https://api.heroui.pro";var d=e.enum(["light","dark","system"]),y=e.enum(["outline","plain","surface","surface-secondary"]),f=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=>!f.has(t.toLowerCase()),{message:"Identity id is reserved"}),I=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()}),g=e.object({anonymousId:c.optional(),identity:I,profile:S.optional()}),h=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 _=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:y.default("plain"),theme:d});var 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=g.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 l=(t.apiBaseUrl?.trim()||u).replace(/\/$/,""),r;try{r=await fetch(`${l}/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(A){throw new n("HeroUI Agent authentication is unavailable",503,{cause:A})}if(!r.ok)throw new n("HeroUI Agent authentication failed",r.status);let p=h.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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heroui/agent",
3
- "version": "0.2.0-beta.16",
3
+ "version": "0.2.0-beta.17",
4
4
  "description": "Embed a hosted HeroUI Agent that turns application data into interactive UI.",
5
5
  "homepage": "https://heroui.pro/agents",
6
6
  "bugs": {
@@ -111,8 +111,8 @@
111
111
  "typescript": "5.9.3",
112
112
  "vitest": "4.1.0",
113
113
  "@heroui-pro/config": "0.0.0",
114
- "@heroui-pro/react": "1.0.0-beta.8",
115
114
  "@heroui/agent-ui": "0.0.0",
115
+ "@heroui-pro/react": "1.0.0-beta.8",
116
116
  "@heroui/agent-client": "0.0.0"
117
117
  },
118
118
  "scripts": {