@heroui/agent 0.2.0-beta.9 → 1.0.0-beta.2
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 +65 -0
- package/README.md +3 -3
- package/dist/chart-content-YGW25P3Z.js +1 -0
- package/dist/chunk-4JEZZR5J.js +1 -0
- package/dist/{chunk-BBB5EHDN.js → chunk-7CUSOLDM.js} +1 -1
- package/dist/chunk-CLHBM3HQ.js +1 -0
- package/dist/chunk-CN4UQBKO.js +2 -0
- package/dist/chunk-FOK4MNBE.js +2 -0
- package/dist/chunk-KQTLIOZ3.js +1 -0
- package/dist/chunk-M22IGTLZ.js +1 -0
- package/dist/chunk-MXXCR5SR.js +1 -0
- package/dist/chunk-OA7E6MEQ.js +1 -0
- package/dist/chunk-UHHKMESI.js +1 -0
- package/dist/component-renderer-KWBZJPBV.js +1 -0
- package/dist/contracts.d.ts +279 -9
- package/dist/contracts.js +2 -2
- package/dist/css/index.css +1 -1
- package/dist/embed-runtime-CLCMDESV.js +5 -0
- package/dist/{identity-3P8-17km.d.ts → identity-CAJPsGqJ.d.ts} +8 -2
- package/dist/index.d.ts +40 -7
- package/dist/index.js +1 -1
- package/dist/internal/models.js +1 -1
- package/dist/internal/theme.js +1 -1
- package/dist/model-picker-BSJRGXGB.js +1 -0
- package/dist/next.d.ts +1 -1
- package/dist/next.js +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.js +1 -1
- package/dist/shell-permission-picker-KIC3VEYJ.js +1 -0
- package/package.json +7 -6
- package/dist/chart-content-BBHQVMP4.js +0 -1
- package/dist/chunk-2XBFFSW2.js +0 -1
- package/dist/chunk-MXLGM4WV.js +0 -1
- package/dist/chunk-OA3TG5CS.js +0 -1
- package/dist/chunk-S6OIAJSC.js +0 -1
- package/dist/chunk-SUDHJNTJ.js +0 -2
- package/dist/chunk-WUAFMD7Z.js +0 -2
- package/dist/component-renderer-GG6JVRUG.js +0 -1
- package/dist/embed-runtime-GYXK7V6N.js +0 -5
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use client";import{a as ko,b as Ua,c as Ba,d as br}from"./chunk-RNNGE7KM.js";import{a as Ha,b as _o}from"./chunk-PZJ4NC3J.js";import{a as Po,b as Io,d as No}from"./chunk-CLHBM3HQ.js";import{a as _a,b as ka}from"./chunk-KQTLIOZ3.js";import{A as xa,B as yr,C as wo,D as vr,E as mn,F as Eo,G as gn,H as Na,b as je,d as ga,e as Vn,g as fa,h as ha,i as yo,j as vo,m as Sa,n as Ca,p as Co,q as $n,r as Aa,s as Ta,t as Ra,u as Ao,v as Ma,w as Ea,x as Pa,y as Ia,z as jt}from"./chunk-CN4UQBKO.js";import{a as bo}from"./chunk-6ZJJN322.js";import{b as pa,c as hr,d as ma}from"./chunk-64RI74L5.js";import{c as ya,d as va,e as So,f as ba}from"./chunk-UHHKMESI.js";import{a as Oa,b as Da,c as La,d as xo}from"./chunk-7KCGPNEN.js";import"./chunk-4JEZZR5J.js";import{a as To}from"./chunk-OA7E6MEQ.js";import{a as Ro,c as Mo}from"./chunk-M22IGTLZ.js";import{a as wa}from"./chunk-MXXCR5SR.js";import{a as fe}from"./chunk-CR3H7AVI.js";import{useAgentChat as sg}from"@cloudflare/ai-chat/react";import{ArrowUp as ag,ArrowUpRight as ig,Microphone as Il,Plus as xl,StopFill as Ml,Xmark as cg}from"@gravity-ui/icons";function Ct(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 Oo(e,t){return e===null?null:typeof e=="string"?Ct(e)?e:null:Ct(t)?t:null}var Sr=30,Fa=52;function Do(e){try{let t=JSON.parse(localStorage.getItem(e)??"[]");return Cr(t)}catch{return[]}}function Cr(e){return Array.isArray(e)?e.filter(t=>!!(t&&typeof t=="object"&&"id"in t&&typeof t.id=="string"&&Ct(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,Sr):[]}function Lo(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,Sr)}function Pt(e,t){localStorage.setItem(e,JSON.stringify(t.slice(0,Sr)))}function Qn(e,t,n,r,{replaceTitle:o=!1}={}){if(!n)return e;let s=e.find(p=>p.id===t);return[{id:t,title:o?n:s?.title??n,updatedAt:r},...e.filter(p=>p.id!==t)].sort((p,c)=>c.updatedAt-p.updatedAt).slice(0,Sr)}function Ar(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()?Uo(n):t?"Attachment":null}function Ho(e,t){return e?Uo(e):t[0]?.name||"Attachment"}function Uo(e){let t=e.replace(/\s+/g," ").trim();return t.length>Fa?`${t.slice(0,Fa-1).trimEnd()}\u2026`:t}function Bo(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 fn}from"@heroui/react";import{jsx as Ve,jsxs as Yt}from"react/jsx-runtime";function lu(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase().replace(/^\w/,t=>t.toUpperCase())}function uu(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])=>[lu(n),String(r)])}function Va({approveLabel:e="Allow",className:t,denyLabel:n="Deny",hint:r="Waiting for your approval",icon:o,input:s,onApprove:i,onDeny:p,title:c,...l}){let m=_a("component")??"surface",u=uu(s),C=s!=null&&(typeof s!="object"||Object.keys(s).length>0);return Yt("section",{"aria-label":c,className:fe("aui-approval",t),"data-slot":"agent-ui-approval","data-variant":m,...l,children:[Yt("div",{className:"aui-approval__heading","data-slot":"agent-ui-approval-heading",children:[o?Ve("span",{"aria-hidden":!0,className:"aui-approval__icon","data-slot":"agent-ui-approval-icon",children:o}):null,Yt("div",{className:"aui-approval__heading-text",children:[Ve("strong",{className:"aui-approval__title",children:c}),r?Ve("span",{className:"aui-approval__hint",children:r}):null]})]}),C?Yt(fn,{defaultExpanded:!0,className:"aui-approval__disclosure",children:[Ve(fn.Heading,{children:Yt(fn.Trigger,{className:"aui-approval__disclosure-trigger",children:["Review action details",Ve(fn.Indicator,{})]})}),Ve(fn.Content,{children:Ve(fn.Body,{children:u?Ve("dl",{className:"aui-approval__details","data-slot":"agent-ui-approval-details",children:u.map(([d,w])=>Yt("div",{className:"aui-approval__detail",children:[Ve("dt",{children:d}),Ve("dd",{children:w})]},d))}):Ve("pre",{className:"aui-approval__pre",children:JSON.stringify(s,null,2)})})})]}):null,Yt("div",{className:"aui-approval__actions","data-slot":"agent-ui-approval-actions",children:[Ve(Po,{size:"md",variant:"tertiary",onClick:p,children:n}),Ve(Po,{size:"md",variant:"primary",onClick:i,children:e})]})]})}import{useEffect as Fo,useRef as hn}from"react";import{jsx as Qa}from"react/jsx-runtime";var du=40,$a=2;function Tr(e,t,n){return Math.min(n,Math.max(t,e))}function pu(e){let t=Tr(Math.round(e),32,32768);return 2**Math.round(Math.log2(t))}function mu(e){return e instanceof Error?e:new Error("Unable to access the microphone.")}function gu(){let e=window;return e.AudioContext??e.webkitAudioContext}function fu(e){e?.getTracks().forEach(t=>t.stop())}function hu(e){if(!(!e||e.state==="closed"))try{e.close().catch(()=>{})}catch{}}function yu(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 Vo({active:e=!1,"aria-label":t,barGap:n=2,barWidth:r=2,className:o,deviceId:s,fadeEdges:i=!0,fadeWidth:p=20,fftSize:c=256,height:l=du,onError:m,onStreamEnd:u,onStreamReady:C,role:d,sensitivity:w=1.15,smoothingTimeConstant:k=.82,stream:M,style:P,...$}){let N=hn(null),I=hn({onError:m,onStreamEnd:u,onStreamReady:C}),O=hn(null),F=hn(null),ee=hn(null),y=hn([]);Fo(()=>{I.current={onError:m,onStreamEnd:u,onStreamReady:C}},[m,u,C]),Fo(()=>{if(!e||M===null){N.current=null;return}let T,S=!1,x=!1,Q=!1,X=M===void 0,j,U=M,q=ge=>{try{j?.disconnect()}catch{}j=void 0,N.current?.context===T&&(N.current=null),hu(T),T=void 0,X&&fu(U),U=void 0,ge&&x&&!Q&&(Q=!0,I.current.onStreamEnd?.())};return(async()=>{try{let ge=gu();if(!ge)throw new Error("Live audio analysis is not supported in this browser.");if(!U){if(!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone capture is not supported in this browser.");U=await navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,...s?{deviceId:{exact:s}}:{},echoCancellation:!0,noiseSuppression:!0}})}if(S){q(!1);return}T=new ge;let L=T.createAnalyser();if(L.fftSize=pu(c),L.smoothingTimeConstant=Tr(k,0,1),j=T.createMediaStreamSource(U),j.connect(L),T.state==="suspended"&&await T.resume(),S){q(!1);return}N.current=L,ee.current=new Uint8Array(L.frequencyBinCount),x=!0,I.current.onStreamReady?.(U)}catch(ge){q(!1),S||I.current.onError?.(mu(ge))}})(),()=>{S=!0,q(!0)}},[e,s,c,M,k]),Fo(()=>{let T=O.current,S=F.current;if(!T||!S)return;let x=T.getContext("2d");if(!x)return;let Q=0,X=getComputedStyle(T).color||"#000",j=0,U=0,q=0,pe=D=>{if(q<=0||U<=0)return;D-j>500&&(X=getComputedStyle(T).color||X,j=D),x.clearRect(0,0,q,U),x.fillStyle=X;let _=Math.max(1,r),W=Math.max(0,n),ne=_+W,ae=Math.max(1,Math.floor((q+W)/ne)),he=Math.ceil(ae/2),qe=N.current;y.current.length!==he&&(y.current=Array.from({length:he},()=>0));let ht=y.current;if(e&&qe){let ve=ee.current;(!ve||ve.length!==qe.frequencyBinCount)&&(ve=new Uint8Array(qe.frequencyBinCount),ee.current=ve),qe.getByteFrequencyData(ve);let Pe=Math.max(1,Math.floor(ve.length*.025)),Me=Math.max(Pe+1,Math.floor(ve.length*.46)),ct=Tr(w,0,4);for(let ze=0;ze<he;ze+=1){let yt=he<=1?0:ze/(he-1),Ce=Math.min(ve.length-1,Math.round(Pe+yt*(Me-Pe))),Rt=Math.pow((ve[Ce]??0)/255*ct,.72);ht[ze]=Tr((ht[ze]??0)*.56+Rt*.44,0,1)}}else ht.fill(0);let Mn=Math.max($a,U*.84),Bt=U/2,Ft=ae*_+(ae-1)*W,on=(q-Ft)/2;for(let ve=0;ve<ae;ve+=1){let Pe=he-1-Math.min(ve,ae-1-ve),Me=e?ht[Pe]??0:0,ct=Math.max($a,Me*Mn),ze=on+ve*ne,yt=Bt-ct/2;x.globalAlpha=e?.38+Me*.62:.2,yu(x,ze,yt,_,ct)}x.globalAlpha=1},ge=()=>{let D=S.getBoundingClientRect(),_=Math.max(1,window.devicePixelRatio||1),W=getComputedStyle(T).color||X;q=Math.max(0,D.width),U=Math.max(0,D.height),T.width=Math.max(1,Math.round(q*_)),T.height=Math.max(1,Math.round(U*_)),T.style.width=`${q}px`,T.style.height=`${U}px`,x.setTransform(_,0,0,_,0,0),X=W,pe(performance.now())},L=D=>{pe(D),Q=requestAnimationFrame(L)};ge();let V;return typeof ResizeObserver>"u"?window.addEventListener("resize",ge):(V=new ResizeObserver(ge),V.observe(S)),e&&(Q=requestAnimationFrame(L)),()=>{Q&&cancelAnimationFrame(Q),V?.disconnect(),window.removeEventListener("resize",ge)}},[e,n,r,w]);let f=typeof l=="number"?`${Math.max(1,l)}px`:l,h={...P,height:f},A=`${Math.max(0,p)}px`,b=`linear-gradient(90deg, transparent 0, #000 min(${A}, 20%), #000 calc(100% - min(${A}, 20%)), transparent 100%)`;return Qa("div",{...$,ref:F,"aria-label":t??(e?"Live microphone waveform":"Microphone waveform"),className:fe("aui-voice-live-waveform",o),"data-active":e||void 0,"data-fade-edges":i||void 0,"data-slot":"agent-ui-voice-live-waveform",role:d??"img",style:h,children:Qa("canvas",{ref:O,"aria-hidden":"true",className:"aui-voice-live-waveform__canvas",style:i?{WebkitMaskImage:b,maskImage:b}:void 0})})}import{useCallback as $e,useEffect as Ka,useRef as Qe,useState as Rr,useSyncExternalStore as vu}from"react";var Er={"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."},za="Microphone access is blocked for this page. Allow microphone access and try again.",bu="Microphone access is enabled, but speech recognition is blocked in this browser or embedded preview.",Qo="Voice dictation is not supported in this browser.",Ga="Voice recording stopped unexpectedly. Try again.",Su=["audio/webm;codecs=opus","audio/mp4","audio/webm","audio/ogg;codecs=opus"],Cu=/\s+/g;function wr(e,t){let n=t.trim().replace(Cu," ");return n?!e||/\s$/.test(e)||/^[,.;:!?)]/.test(n)?`${e}${n}`:`${e} ${n}`:e}function Pr(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 Ko(e,t,n="unknown"){if(e==="not-allowed"){if(n==="denied")return za;if(n==="granted")return bu}return Er[e]??(t?.trim()||"Voice dictation stopped unexpectedly.")}async function Au(){if(typeof navigator>"u"||!navigator.permissions?.query)return"unknown";try{return(await navigator.permissions.query({name:"microphone"})).state}catch{return"unknown"}}function Wa(){if(typeof window>"u")return;let e=window;return e.SpeechRecognition??e.webkitSpeechRecognition}function Tu(){return!!Wa()}function qa(){return typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof MediaRecorder<"u"}function Ru(){if(!(typeof MediaRecorder>"u"||typeof MediaRecorder.isTypeSupported!="function"))return Su.find(e=>MediaRecorder.isTypeSupported(e))}function Mr(e){e?.getTracks().forEach(t=>t.stop())}function $o(e){if(typeof DOMException<"u"&&e instanceof DOMException){if(e.name==="NotAllowedError"||e.name==="SecurityError")return za;if(e.name==="NotFoundError"||e.name==="DevicesNotFoundError")return Er["audio-capture"]}return e instanceof Error&&e.message.trim()?e.message:"Microphone access could not be started."}function Mu(e){return e.error??new Error(Ga)}function wu(){return()=>{}}function qo({language:e,onValueChange:t,transcribe:n,value:r}){let[o,s]=Rr("idle"),[i,p]=Rr(0),[c,l]=Rr(null),[m,u]=Rr(null),C=$e(()=>n?qa():Tu(),[n]),d=vu(wu,C,()=>!1),w=Qe("idle"),k=Qe(r),M=Qe(null),P=Qe(e),$=Qe(t),N=Qe(null),I=Qe(null),O=Qe(0),F=Qe(0),ee=Qe(n),y=Qe(null),f=Qe(new Map),h=Qe(r);Ka(()=>{P.current=e,$.current=t,ee.current=n,h.current=r},[e,t,n,r]);let A=$e(L=>{w.current=L,s(L)},[]),b=$e(()=>{M.current!==null&&(clearInterval(M.current),M.current=null)},[]),T=$e(()=>{b(),F.current=Date.now(),p(0),M.current=setInterval(()=>{p(Math.floor((Date.now()-F.current)/1e3))},250)},[b]),S=$e(L=>{L.onend=null,L.onerror=null,L.onresult=null,L.onstart=null},[]),x=$e(L=>{L.ondataavailable=null,L.onerror=null,L.onstop=null},[]),Q=$e((L,V)=>{if(x(L.recorder),V&&L.recorder.state!=="inactive")try{L.recorder.stop()}catch{}Mr(L.stream)},[x]),X=$e(async L=>{if(O.current!==L.session||N.current!==L){Q(L,!1);return}N.current=null,x(L.recorder),Mr(L.stream),u(null),b(),A("transcribing");let V=L.recorder.mimeType||L.chunks[0]?.type||"audio/webm",D=new Blob(L.chunks,{type:V}),_=ee.current;if(!_||D.size===0){A("idle"),l(D.size===0?Er["no-speech"]:Ga);return}let W=new AbortController;y.current=W;try{let ne=await _(D,{...P.current?{language:P.current}:{},signal:W.signal});if(O.current!==L.session||W.signal.aborted)return;if(!ne.trim()){l(Er["no-speech"]);return}$.current(wr(k.current,ne)),l(null)}catch(ne){if(O.current!==L.session||W.signal.aborted)return;l(ne instanceof Error&&ne.message.trim()?ne.message:"Voice transcription could not be completed. Try again.")}finally{y.current===W&&(y.current=null),O.current===L.session&&A("idle")}},[x,Q,b,A]),j=$e(()=>{O.current+=1,b(),y.current?.abort(),y.current=null,l(null),u(null),A("idle");let L=N.current,V=I.current;if(N.current=null,I.current=null,f.current.clear(),L&&Q(L,!0),!!V){S(V);try{V.abort()}catch{}}},[S,Q,b,A]),U=$e(()=>{if(w.current==="transcribing"){j();return}let L=N.current;if(L){b(),A("transcribing");try{L.recorder.stop()}catch(D){O.current+=1,N.current=null,Q(L,!1),u(null),A("idle"),l(D instanceof Error?D.message:"Voice recording could not be stopped cleanly.")}return}if(w.current==="recording"){j();return}let V=I.current;if(V){b();try{V.stop()}catch(D){A("idle"),O.current+=1,I.current=null,f.current.clear(),S(V);try{V.abort()}catch{}l(D instanceof Error?D.message:"Voice dictation could not be stopped cleanly.")}}},[j,S,Q,b,A]),q=$e(async()=>{if(!qa()){l(Qo);return}let L=O.current+1;O.current=L,k.current=h.current,l(null),p(0),u(null),A("recording");let V;try{V=await navigator.mediaDevices.getUserMedia({audio:{autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0}})}catch(W){if(O.current!==L)return;A("idle"),l($o(W));return}if(O.current!==L){Mr(V);return}let D;try{let W=Ru();D=W?new MediaRecorder(V,{mimeType:W}):new MediaRecorder(V)}catch(W){if(Mr(V),O.current!==L)return;A("idle"),l($o(W));return}let _={chunks:[],recorder:D,session:L,stream:V};D.ondataavailable=W=>{W.data.size>0&&_.chunks.push(W.data)},D.onerror=W=>{O.current!==L||N.current!==_||(O.current+=1,N.current=null,b(),Q(_,!0),u(null),A("idle"),l(Mu(W).message))},D.onstop=()=>{X(_)},N.current=_,u(V);try{D.start(1e3),T()}catch(W){O.current+=1,N.current=null,Q(_,!1),u(null),A("idle"),l($o(W))}},[Q,X,T,b,A]),pe=$e(()=>{let L=Wa();if(!L){l(Qo);return}let V;try{V=new L}catch(_){l(_ instanceof Error?_.message:"Voice dictation could not be started.");return}let D=O.current+1;O.current=D,k.current=h.current,f.current=new Map,V.continuous=!0,V.interimResults=!0,V.maxAlternatives=1,P.current&&(V.lang=P.current),V.onstart=()=>{O.current===D&&(A("recognizing"),T())},V.onresult=_=>{if(O.current!==D)return;let W=Math.max(0,_.resultIndex);for(let ae of f.current.keys())ae>=W&&f.current.delete(ae);for(let ae=W;ae<_.results.length;ae+=1){let qe=_.results[ae]?.[0]?.transcript;typeof qe=="string"&&f.current.set(ae,qe)}let ne=Array.from(f.current.entries()).sort(([ae],[he])=>ae-he).map(([,ae])=>ae).reduce(wr,"");$.current(wr(k.current,ne))},V.onerror=_=>{if(O.current!==D)return;b(),A("idle"),f.current.clear(),O.current+=1;let W=O.current;_.error!=="aborted"&&(_.error==="not-allowed"?Au().then(ne=>{O.current===W&&l(Ko(_.error,_.message,ne))}):l(Ko(_.error,_.message))),I.current===V&&(I.current=null,S(V))},V.onend=()=>{O.current===D&&(b(),A("idle"),I.current===V&&(I.current=null,S(V)))},I.current=V,l(null),p(0),A("recognizing");try{V.start()}catch(_){S(V),I.current=null,b(),A("idle"),l(_ instanceof Error?_.message:"Voice dictation could not be started.")}},[S,T,b,A]),ge=$e(()=>{w.current!=="idle"||I.current||N.current||y.current||(ee.current?q():pe())},[pe,q]);return Ka(()=>()=>{O.current+=1,b(),y.current?.abort(),y.current=null;let L=N.current,V=I.current;if(N.current=null,I.current=null,L&&Q(L,!0),!!V){S(V);try{V.abort()}catch{}}},[S,Q,b]),{cancel:j,elapsedSeconds:i,error:c,isActive:o!=="idle",isRecording:o==="recording",isSupported:d,isTranscribing:o==="transcribing",start:ge,stop:U,stream:m}}import{Spinner as lg}from"@heroui/react/spinner";import{isTerminalCloseEvent as ug}from"agents/client";import{useAgent as dg}from"agents/react";import{Suspense as pg,useCallback as G,useEffect as ye,useEffectEvent as Ut,useId as mg,useLayoutEffect as Tt,useMemo as Ae,useRef as ce,useState as J}from"react";import{z as te}from"zod";var Eu=te.enum(["light","dark","system"]),ja=te.enum(["outline","plain","surface","surface-secondary"]),Pu=new Set(["[object object]","0","anonymous","distinct_id","distinctid","email","false","guest","id","nan","none","not_authenticated","null","true","undefined"]),zo=te.string().trim().min(1).max(200).refine(e=>!Pu.has(e.toLowerCase()),{message:"Identity id is reserved"}),Iu=te.discriminatedUnion("type",[te.object({id:zo,type:te.literal("anonymous")}),te.object({id:zo,type:te.literal("user")})]),xu=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()}),zg=te.object({anonymousId:zo.optional(),identity:Iu,profile:xu.optional()}),Gg=te.object({expiresAt:te.number().int().positive(),token:te.string().trim().min(1)}),Wg=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 Ir=te.object({agentId:te.string(),componentSurfaceVariant:ja.default("surface"),minimumProtocolVersion:te.literal(6),name:te.string().trim().min(1).max(120),protocolVersion:te.literal(6),sdkVersion:te.string().default(je),suggestedPrompts:te.array(te.string().trim().min(1).max(160)).max(5),surfaceVariant:ja.default("surface-secondary"),theme:Eu});var Nu="understanding your request";function _u(e){let t=e.replace(/\r\n?/g,`
|
|
2
|
+
`).trim();if(!t)return null;if(t.length<=1600)return t;let n=t.slice(0,1601),r=n.lastIndexOf(" "),o=r>=1600*.8?r:1600;return`${n.slice(0,o).trimEnd()}\u2026`}function ku(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 Ou(e,t){let n=e.replace(/\r\n?/g,`
|
|
3
|
+
`).trim();if(!n)return null;let r=/^#{1,6}\s+([^\n]+)\n+([\s\S]+)$/u.exec(n),o=/^(?:\*\*([^*\n]+)\*\*|__([^_\n]+)__)([\s\S]+)$/u.exec(n),s=r?.[1]??o?.[1]??o?.[2],i=r?.[2]??o?.[3],p=s?ku(s):null,c=i?.replace(/^\s*(?:[|:—–-]\s*)?/u,"").trim(),l=_u(p&&c?c:n);return l?{detail:l,label:p??(t===0?"Thinking through your request":"Thinking through the next step")}:null}function Du(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 Go(e){return e.toLocaleLowerCase().replace(/[.…]+$/u,"").trim()}function Lu(e,t){return t!=="accepted"&&t!=="preparing"?!1:Go(e)===Nu}function Ya(e){return e.type==="dynamic-tool"&&e.toolName?e.toolName:e.type.startsWith("tool-")?e.type.slice(5):null}function Xa(e){return e==="renderComponent"||e==="composeUI"}var Hu={ai:"AI",api:"API",crm:"CRM",csv:"CSV",id:"ID",mcp:"MCP",sql:"SQL",ui:"UI",url:"URL"};function Uu(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").trim().split(/\s+/).map((n,r)=>{let o=Hu[n.toLowerCase()];return o||(r===0?n.replace(/^\w/,s=>s.toUpperCase()):n)}).join(" ")}function xr(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 Ja(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 Wo(e,t,n={}){if(e.role!=="assistant")return[];let r=[],o=new Set,s=0,i;for(let[c,l]of e.parts.entries()){if(l.type==="reasoning"){let I=Ou(l.text,s);if(!I)continue;r.push({active:n.isStreaming===!0&&l.state!=="done",detail:I.detail,detailVisibility:"always",id:`${e.id}-reasoning-${c}`,kind:"thinking",label:I.label,messagePartIndex:c,stateKnown:l.state!==void 0,...r.length===0&&i?{title:i}:{}}),s+=1;continue}if(l.type==="data-activity"){let I=l.data.label.trim(),O=l.data.title?.trim();if(O&&!i){i=O;let F=r[0];F&&!F.title&&(r[0]={...F,title:O})}if(Lu(I,l.data.stage)||O&&Go(I)===Go(O))continue;if(I&&o.has(I)){let F=r.findIndex(y=>y.label===I),ee=r[F];O&&ee&&!ee.title&&(r[F]={...ee,title:O})}else I&&(o.add(I),r.push({active:!1,detail:l.data.detail,id:l.id??`${e.id}-activity-${c}`,kind:l.data.kind??xr(I),label:I,messagePartIndex:c,sources:l.data.sources,stateKnown:!1,...O||r.length===0&&i?{title:O??i}:{}}));continue}let m=Ya(l);if(!m)continue;let u=l,C=Xa(m),d=C&&e.parts.slice(c+1).some(I=>{let O=Ya(I);return O!==null&&Xa(O)&&I.state==="output-available"});if(C&&u.state==="output-error"&&(n.isStreaming||d))continue;let w=m==="searchWeb"?Du(u):null,k=C?"Building your data view":m==="executeSandbox"?"Analyzing your data":m==="getComponentSchema"?"Preparing your data view":w?`Searching the web for \u201C${w}\u201D`:t.get(m)?.displayName??Uu(m),P=u.state==="output-denied"||!!(u.output&&typeof u.output=="object"&&"rejected"in u.output&&u.output.rejected)?w?`Skipped web search for \u201C${w}\u201D`:`Skipped ${k}`:u.state==="output-error"?w?`Couldn\u2019t search the web for \u201C${w}\u201D`:`Couldn\u2019t complete ${k}`:k,$=["input-available","input-streaming","approval-requested","approval-responded"].includes(u.state),N=r.findIndex(I=>I.label===P);if(N>=0){let I=r[N];I&&(r[N]={...I,active:$,messagePartIndex:c,stateKnown:!0,...!I.title&&i?{title:i}:{}});continue}o.add(P),r.push({active:$,id:u.toolCallId||`${e.id}-tool-${c}`,kind:C?"chart":m==="executeSandbox"?"code":m==="getComponentSchema"?"thinking":xr(P),label:P,messagePartIndex:c,stateKnown:!0,...r.length===0&&i?{title:i}:{}})}if(!n.isStreaming||r.length===0||r.some(c=>c.active))return r;let p=r.length-1;return r[p]?.stateKnown?r:r.map((c,l)=>({...c,active:l===p}))}var Bu={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"},Fu=new Set(["accepted","preparing","generating","waiting-client-tool","running-server-tool","recovering"]);function Vu(e){return e.type==="dynamic-tool"&&e.toolName?e.toolName:e.type.startsWith("tool-")?e.type.slice(5):null}function Kn(e){return e?Bu[e]:null}function Za({clientToolNames:e,isLocalPending:t,isRecovering:n,isStreaming:r,messages:o,status:s}){if(n)return"recovering";let i=o.findLast(p=>p.role==="assistant");if(i){for(let c=i.parts.length-1;c>=0;c-=1){let l=i.parts[c],m=Vu(l);if(m&&["input-streaming","input-available","approval-requested","approval-responded"].includes(l.state??""))return e.has(m)?"waiting-client-tool":"running-server-tool";if(l.type==="data-activity"||l.type==="data-progress"){let u=l.data?.stage;if(typeof u=="string"&&Fu.has(u))return u}}let p=i.parts.some(c=>c.type==="text"&&c.text.trim().length>0||c.type==="data-component");if(r&&p)return"generating"}return r||s==="streaming"?"preparing":t||s==="submitted"?"accepted":null}import{ChartColumn as id,CircleCheck as cd,Code as ld,Database as ud,Globe as ai,Magnifier as dd,Wrench as pd}from"@gravity-ui/icons";import{Disclosure as Ye}from"@heroui/react";import{useEffect as ii,useRef as Xo,useState as Jo}from"react";import{useEffect as $u,useState as Qu}from"react";import{jsx as Nr,jsxs as qu}from"react/jsx-runtime";var Ku=280;function _r({animateOnMount:e=!0,children:t,className:n,...r}){let[o,s]=Qu(()=>({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,p=o.previous;return $u(()=>{if(!p)return;let c=window.setTimeout(()=>{s(l=>l.current.id===i?{...l,previous:null}:l)},Ku);return()=>window.clearTimeout(c)},[i,p]),qu("span",{...r,"aria-label":r["aria-label"]??t,className:`ha-status-text${n?` ${n}`:""}`,"data-slot":"animated-text",children:[Nr("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:Nr(jt,{children:o.current.text})},o.current.id),o.previous?Nr("span",{"aria-hidden":"true",className:"ha-status-text__value ha-status-text__value--exiting","data-slot":"animated-text-previous-value",children:Nr(jt,{children:o.previous.text})},o.previous.id):null]})}import{Code as zu,Heading as yn,Link as Gu,Paragraph as Wu,Separator as ju,Table as It}from"@heroui/react";import{Children as ei,Suspense as ti,isValidElement as ni,lazy as Yu,memo as Xu,useMemo as Ju}from"react";import{jsx as de,jsxs as od}from"react/jsx-runtime";var Zu=Yu(()=>import("streamdown").then(e=>({default:e.Streamdown})));function ed(e){return e?.match(/language-([^\s]+)/)?.[1]??"plaintext"}function td(e,t){return e?.find(n=>Array.isArray(n.language)?n.language.includes(t):n.language===t)}function jo(e){return ei.toArray(e?.props.children).filter(t=>ni(t))}function Yo(e,t){return ei.toArray(e).find(n=>ni(n)&&n.props.node?.tagName===t)}function nd({children:e}){let t=Yo(e,"thead"),n=Yo(e,"tbody"),r=Yo(t?.props.children,"tr"),o=jo(r),s=jo(n);return de(It,{"data-slot":"markdown-table",variant:"secondary",children:de(It.ScrollContainer,{children:od(It.Content,{"aria-label":"Markdown table",children:[de(It.Header,{children:o.map((i,p)=>de(It.Column,{id:`column-${p}`,isRowHeader:p===0,children:i.props.children},String(i.key)))}),de(It.Body,{children:s.map((i,p)=>de(It.Row,{id:`row-${p}`,children:jo(i).map(c=>de(It.Cell,{children:c.props.children},String(c.key)))},String(i.key)))})]})})})}function rd(e,t){function n({children:o,className:s,node:i}){let p=ed(s),c=String(o??"").replace(/\n$/,""),l=td(e?.renderers,p);if(l){let m=l.component,u=i?.properties?.metastring;return de(ti,{fallback:de(No,{code:c,language:p}),children:de(m,{code:c,isIncomplete:t,language:p,meta:typeof u=="string"?u:void 0})})}return de(No,{code:c,language:p})}function r({children:o,className:s}){return de(zu,{className:s,"data-slot":"markdown-inline-code",children:o})}return{a:({children:o,className:s,href:i})=>de(Gu,{className:s,href:i,rel:"noreferrer",target:"_blank",children:o}),code:n,h1:({children:o,className:s})=>de(yn,{className:s,level:1,children:o}),h2:({children:o,className:s})=>de(yn,{className:s,level:2,children:o}),h3:({children:o,className:s})=>de(yn,{className:s,level:3,children:o}),h4:({children:o,className:s})=>de(yn,{className:s,level:4,children:o}),h5:({children:o,className:s})=>de(yn,{className:s,level:5,children:o}),h6:({children:o,className:s})=>de(yn,{className:s,level:6,children:o}),hr:({className:o})=>de(ju,{className:o,"data-slot":"markdown-separator",variant:"tertiary"}),inlineCode:r,p:({children:o,className:s})=>de(Wu,{className:s,"data-slot":"markdown-paragraph",size:"sm",children:o}),table:nd}}var kr=Xu(function({animated:t=Na,caret:n="block",children:r,isStreaming:o=!1,plugins:s}){let i=Ju(()=>rd(s,o),[o,s]);return de(ti,{fallback:de("div",{className:"ha-markdown","data-streaming":o?!0:void 0,children:de("p",{children:r})}),children:de("div",{className:"ha-markdown","data-streaming":o?!0:void 0,children:de(Zu,{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 sd}from"react";function ad(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 ri(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 Xt(e,t=1){sd(()=>{let n=e.current;if(!n)return;let r=null,o=null,s=()=>{r!==null&&cancelAnimationFrame(r),r=requestAnimationFrame(()=>{r=null;let c=ad(n,t);c!==o&&(o=c,ri(n,c))})};s(),n.addEventListener("scroll",s,{passive:!0});let i=typeof ResizeObserver>"u"?null:new ResizeObserver(s),p=typeof MutationObserver>"u"?null:new MutationObserver(s);return i?.observe(n),p?.observe(n,{characterData:!0,childList:!0,subtree:!0}),()=>{n.removeEventListener("scroll",s),i?.disconnect(),p?.disconnect(),r!==null&&cancelAnimationFrame(r),ri(n,"none")}},[t,e])}import{jsx as oe,jsxs as mt}from"react/jsx-runtime";var md=24,gd=160,fd=220;function ci(e,t,n,r){let o=Xo(!0);ii(()=>{let s=e.current;if(!s)return;let i,p=!1,c=()=>{let w=s.scrollHeight-s.scrollTop-s.clientHeight;o.current=w<=md},l=()=>{p||c()},m=()=>{p=!1,window.clearTimeout(i),requestAnimationFrame(c)},u=()=>{if(!r||!n||!o.current)return;let w=typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,k=s.scrollHeight;if(typeof s.scrollTo!="function"){s.scrollTop=k;return}p=!w,s.scrollTo({behavior:w?"auto":"smooth",top:k}),window.clearTimeout(i),i=window.setTimeout(()=>{p=!1,c()},360)};s.addEventListener("scroll",l,{passive:!0}),s.addEventListener("pointerdown",m,{passive:!0}),s.addEventListener("touchstart",m,{passive:!0}),s.addEventListener("wheel",m,{passive:!0}),u();let C=s.firstElementChild,d=C&&typeof ResizeObserver<"u"?new ResizeObserver(u):null;return C&&d?.observe(C),()=>{s.removeEventListener("scroll",l),s.removeEventListener("pointerdown",m),s.removeEventListener("touchstart",m),s.removeEventListener("wheel",m),d?.disconnect(),window.clearTimeout(i)}},[t,r,n,e])}function hd(e){let[t,n]=Jo(()=>({isStreaming:e,phase:e?"expanded":"collapsed"})),r=t.phase;return t.isStreaming!==e&&(r=e?"expanded":"fading",n({isStreaming:e,phase:r})),ii(()=>{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"?gd:fd,p=window.setTimeout(()=>{n(c=>c.isStreaming===e&&c.phase===r?{...c,phase:s}:c)},i);return()=>window.clearTimeout(p)},[e,r]),r}var yd={browse:ai,chart:id,code:ld,data:ud,search:dd,thinking:pd},oi="Working on your request";function Or(e){return e.toLocaleLowerCase().replace(/\s+/g," ").replace(/[.…!?:;,]+$/u,"").trim()}function vd(e){let t=e.find(p=>p.title?.trim()),n=t?.title?.trim(),r=e.find(p=>Or(p.label)!=="understanding your request")??e[0],o=t??r,s=o?.kind??xr(o?.label??n??""),i=new Set(e.map(p=>Or(p.label)));return n&&!i.has(Or(n))?{kind:s,title:n}:{kind:s,title:i.has(Or(oi))?"Making progress":oi}}function si({active:e}){return mt("span",{className:"ha-activity-icon","data-state":e?"active":"complete",children:[oe("span",{"aria-hidden":"true",className:"ha-activity-icon-state ha-activity-icon-state--active",children:oe("span",{className:"ha-activity-spinner"})}),oe("span",{"aria-hidden":"true",className:"ha-activity-icon-state ha-activity-icon-state--complete",children:oe(cd,{})})]})}function li({active:e,label:t}){return e?oe(_r,{className:"ha-activity-step-label ha-progress-shimmer",children:t}):oe("span",{className:"ha-activity-step-label",children:t})}function bd({detail:e,isDetailActive:t,isLabelActive:n,isTurnActive:r,label:o,markdownAnimation:s,markdownPlugins:i}){let[p,c]=Jo(()=>({isDetailActive:t,isExpanded:t})),l=p.isExpanded;p.isDetailActive!==t&&(l=t,c({isDetailActive:t,isExpanded:l}));let m=Xo(null);return Xt(m),ci(m,e,t&&r,l),mt(Ye,{className:"ha-activity-step-disclosure",isExpanded:l,onExpandedChange:u=>c({isDetailActive:t,isExpanded:u}),children:[oe(Ye.Heading,{children:mt(Ye.Trigger,{className:"ha-activity-step-trigger",children:[oe(li,{active:n,label:o}),oe(Ye.Indicator,{className:"ha-activity-step-chevron"})]})}),oe(Ye.Content,{className:"ha-activity-step-disclosure-content",children:oe(Ye.Body,{className:"ha-activity-detail",children:oe("div",{ref:m,className:"ha-activity-detail-inner",children:oe(kr,{animated:s,caret:!1,isStreaming:t?r:!1,plugins:i,children:e})})})})]})}function Sd(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 Dr({ariaLabel:e,label:t}){return oe("div",{className:"ha-progress ha-activity-status",children:oe(_r,{"aria-label":e,className:"ha-progress-shimmer",role:"status",children:t})})}function ui({completedAt:e,defaultOpen:t=!1,hasResponseStarted:n=!1,isStreaming:r,items:o,markdownAnimation:s,markdownPlugins:i,startedAt:p}){let c=r&&!n,l=hd(r),[m,u]=Jo(null),C=Xo(null),d=o.findLastIndex(b=>b.active),w=o.length-1,k=c?d>=0?d:w:-1,M=o.map((b,T)=>({...b,active:T===k})),P=vd(M),$=m===null&&!t&&!r&&(l==="fading"||l==="collapsing"),I=m??(t||l==="expanded"||l==="fading"),O=m!==null||t?I?"expanded":"collapsed":l,F=p!==void 0&&e!==void 0&&!r?Math.max(0,e-p):null,ee=F===null?"Activity":`Worked for ${Sd(F)}`,y=r||$?P.title:F===null?"Activity":ee,f=P.kind,h=yd[f],A=M.map(b=>`${b.id}:${b.active?1:0}:${b.detail??""}:${b.sources?.map(T=>T.label).join(",")}`).join("|");return Xt(C),ci(C,A,r,I),mt(Ye,{className:"ha-activity","data-complete":r?void 0:"true","data-phase":O,isExpanded:I,onExpandedChange:u,children:[oe(Ye.Heading,{children:mt(Ye.Trigger,{className:"ha-activity-trigger",children:[oe("span",{"aria-hidden":"true",className:"ha-activity-summary-icon",children:oe("span",{children:oe(h,{})},f)}),r||$?oe(_r,{className:"ha-activity-summary-label ha-progress ha-progress-shimmer",role:"status",children:y}):oe("span",{className:"ha-activity-summary-label ha-activity-summary-label--complete ha-progress",children:y}),oe(Ye.Indicator,{className:"ha-activity-chevron"})]})}),oe(Ye.Content,{className:"ha-activity-disclosure-content",children:oe(Ye.Body,{children:oe("div",{ref:C,className:"ha-activity-panel",children:mt("ol",{"aria-label":"Thinking steps",children:[M.map((b,T)=>mt("li",{"aria-current":b.active?"step":void 0,className:"ha-activity-item","data-active":b.active||void 0,"data-state":b.active?"active":"complete",children:[oe(si,{active:b.active}),mt("div",{className:"ha-activity-content",children:[b.detail&&(b.active||b.detailVisibility==="always")?oe(bd,{detail:b.detail,isDetailActive:c?o[T]?.active===!0:!1,isLabelActive:b.active,isTurnActive:r,label:b.label,markdownAnimation:s,markdownPlugins:i}):oe(li,{active:b.active,label:b.label}),b.sources?.length?oe("span",{"aria-label":"Sources",className:"ha-activity-sources",children:b.sources.map(S=>mt("span",{className:"ha-activity-source",children:[oe(ai,{"aria-hidden":"true"}),S.label]},S.label))}):null]})]},b.id)),r?null:mt("li",{className:"ha-activity-item","data-complete":"true","data-state":"complete",children:[oe(si,{active:!1}),oe("div",{className:"ha-activity-content",children:oe("span",{className:"ha-activity-step-label",children:"Final response ready"})})]})]})})})})]})}import{z as Pd}from"zod";import{z as xt}from"zod";var Cd=["callMcpTool","composeUI","executeSandbox","getComponentSchema","renderComponent","searchKnowledge","searchMcpTools","searchWeb"],Ad="mcp_",Td=20,Rd=16*1024,Md=xt.object({description:xt.string().trim().min(1).max(1e3),inputSchema:xt.record(xt.string(),xt.unknown()),name:xt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).refine(e=>!Cd.includes(e)&&!e.toLowerCase().startsWith(Ad),"Client tool name is reserved by the HeroUI Agent runtime"),needsApproval:xt.boolean().optional()}),di=xt.array(Md).max(Td).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>Rd&&t.addIssue({code:"custom",message:"Client tool manifest exceeds 16KB"})});import{z as Xe}from"zod";var pi=Xe.object({excerpt:Xe.string().trim().min(1).max(2e3).optional(),locator:Xe.string().trim().min(1).max(160).optional(),sourceId:Xe.string().trim().min(1).max(120)}),wd=Xe.string().trim().max(2048).refine(e=>{try{return["http:","https:"].includes(new URL(e).protocol)}catch{return!1}}),Ed=Xe.union([pi.extend({sourceType:Xe.literal("document"),title:Xe.string().trim().min(1).max(200)}),pi.extend({sourceType:Xe.literal("url").optional(),title:Xe.string().trim().min(1).max(200).optional(),url:wd})]),mi=Xe.object({items:Xe.array(Ed).min(1).max(16)});function Id(e){return pa(e.parameters)?Pd.toJSONSchema(e.parameters):e.parameters}function Nt(e){return di.parse(e.map(t=>({description:t.description,inputSchema:Id(t),name:t.name,...t.needsApproval?{needsApproval:!0}:{}})))}var vn=class extends Error{constructor(){super("The assistant configuration changed and must be bootstrapped again"),this.name="AgentRuntimeRevisionStaleError"}},qn=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}},Lr=class extends Error{code;status;constructor(t,n){super("Could not bootstrap the assistant conversation"),this.name="AgentConversationBootstrapError",this.code=n,this.status=t}},xd=250,Nd=2e3,hi=new Set(["CONVERSATION_LEASE_CONFLICT","SETTLEMENT_ACKNOWLEDGEMENT_PENDING"]),_d=15e3,gi=3e4;function yi(e){return e instanceof Lr&&e.status===409&&hi.has(e.code)}function kd(e){return e===408||e===429||e>=500}function Od(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 Dd(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 vi(e){return{clientTools:Nt(e.tools),imageSearch:e.imageSearch,...e.composerDefaultModel?{modelId:e.composerDefaultModel}:{},newsSearch:e.newsSearch,webSearch:e.webSearch}}function bi(e){return JSON.stringify(vi(e))}function Hr(e,t=!1){return{Authorization:`Bearer ${e}`,...t?{"Content-Type":"application/json"}:{},"X-HeroUI-Agent-Protocol-Version":String(6),"X-HeroUI-Agent-SDK-Version":je}}async function zn(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",je),fetch(t,{...n,headers:s})},o=await r();return o.status===401&&(e.clear(),o=await r()),o}function fi(e){if(typeof e!="string"||!e)return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}var Ld=/^sha256:[0-9a-f]{64}$/u;function Si(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||!fi(t.ticketExpiresAt)||!fi(t.connectionExpiresAt)||typeof t.runtimeRevision!="string"||!Ld.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 Hd(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,n=t.conversation,r=Si(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 Ud(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return Si(t.runtime??t)}async function Ci(e,t,n){let r=new AbortController,o=Date.now()+gi,s=globalThis.setTimeout(()=>r.abort(new Error("Assistant conversation bootstrap request timed out")),gi),i=xd;try{for(;;){let p=await zn(t,`${e.apiBaseUrl}/v1/conversations/${encodeURIComponent(n)}/bootstrap`,{body:JSON.stringify(vi(e)),headers:{"Content-Type":"application/json"},method:"POST",signal:r.signal});if(!p.ok){let l=await p.json().catch(()=>null),m=typeof l?.code=="string"?l.code.toUpperCase():"";if(p.status===409&&hi.has(m))throw new Lr(p.status,m);if(!kd(p.status))return null;let u=Date.now(),C=Od(p.headers.get("Retry-After"),u)??i;if(u+C>=o)return null;await Dd(C,r.signal),i=Math.min(i*2,Nd);continue}let c=Hd(await p.json().catch(()=>null));return c?.conversation.id!==n||c?.conversation.agentId!==e.agentId?null:c}}finally{globalThis.clearTimeout(s)}}async function Ai(e,t,n,r){let o=new AbortController,s=globalThis.setTimeout(()=>o.abort(new Error("Assistant connection ticket request timed out")),_d);try{let i=await zn(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}),p=await i.json().catch(()=>null);if(!i.ok){let l=typeof p?.code=="string"?p.code.toUpperCase():"";throw i.status===409||l.includes("STALE")&&l.includes("REVISION")?new vn:new qn(i.status)}let c=Ud(p);if(!c||c.runtimeRevision!==r||c.path!==`/v1/conversations/${encodeURIComponent(n)}/connect`)throw new Error("The assistant returned an invalid connection ticket");return c}finally{globalThis.clearTimeout(s)}}async function ke(e,t,n,r,o={}){try{await fetch(`${e.apiBaseUrl}/v1/agents/${encodeURIComponent(e.agentId)}/events`,{body:JSON.stringify({conversationId:n,event:r,properties:{...o,protocolVersion:6,sdkVersion:je}}),headers:Hr(await t.get(),!0),keepalive:!0,method:"POST"})}catch{}}function bn(e,t=yo){let n=new Set(t),o=e.filter(s=>vo(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=>!vo(s.type)||!n.has(s.type.trim().toLowerCase()))?{error:Bd(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 Ri({acceptedContentTypes:e=yo,apiBaseUrl:t,conversationId:n,files:r,tokenManager:o}){if(r.length===0)return[];let s=bn(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=>Fd({apiBaseUrl:t,conversationId:n,file:i,tokenManager:o})))}function Bd(e){if(e.length===0)return"File attachments are disabled for this agent.";let t=e.map(o=>{let s=ha[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 Fd({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(),p=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":je},method:"POST"});if(p.status===401&&s===0){r.clear();continue}if(!p.ok)throw new Error(await Vd(p));let c=await p.json().catch(()=>null);if(typeof c?.url!="string")throw new Error("The attachment upload returned an invalid response.");return{filename:n.name,mediaType:n.type,type:"file",url:c.url}}throw new Error("The attachment could not be uploaded. Try again.")}async function Vd(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 Ne}from"zod";var $d=64*1024,Qd=15e3,Kd=5*6e4,qd=Ne.discriminatedUnion("action",[Ne.object({action:Ne.literal("execute"),claimId:Ne.string().uuid(),idempotencyKey:Ne.string().trim().min(1).max(160)}).strict(),Ne.object({action:Ne.literal("replay"),idempotencyKey:Ne.string().trim().min(1).max(160),output:Ne.unknown()}).strict(),Ne.object({action:Ne.literal("wait"),idempotencyKey:Ne.string().trim().min(1).max(160),retryAfterMs:Ne.number().int().min(25).max(5e3)}).strict()]),zd=Ne.object({output:Ne.unknown(),status:Ne.enum(["completed","failed","interrupted"])}).strict();async function Mi({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 es(e){return Array.isArray(e)?`[${e.map(es).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${es(n)}`).join(",")}}`:JSON.stringify(e)??"undefined"}async function Gd(e){return[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)))].map(n=>n.toString(16).padStart(2,"0")).join("")}function Wd(e){return{error:e instanceof Error?e.message.slice(0,1e3):"The tool could not be executed"}}function jd(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>$d?{output:{error:"The client tool result exceeded the 64 KiB limit"},status:"failed"}:{output:JSON.parse(n),status:"completed"}}function wi({approvalApproved:e,decision:t,needsApproval:n,state:r}){return r==="approval-responded"?e===!0:r!=="input-available"?!1:!n||t==="approved"}async function Yd(e){return Gd(es(e))}function Ei({context:e,execution:t,input:n,tool:r}){return r.execute(hr(r,n),e,t)}async function Pi({conversationId:e,execute:t,input:n,maxWaitMs:r=Kd,now:o=Date.now,rpc:s,submitOutput:i,toolCallId:p,toolName:c,wait:l=m=>new Promise(u=>setTimeout(u,m))}){let m={inputHash:await Yd(n),protocolVersion:6,toolCallId:p,toolName:c},u=o(),C;for(;C=qd.parse(await s.claim(m)),C.action==="wait";){if(o()-u+C.retryAfterMs>r)throw new Error("Timed out waiting for the existing client tool execution");await l(C.retryAfterMs)}if(C.action==="replay")return await i(C.output),"replayed";let d={conversationId:e,idempotencyKey:C.idempotencyKey,toolCallId:p},w,k;try{({output:w,status:k}=jd(await t(d)))}catch(P){k="failed",w=Wd(P)}let M;for(;;)try{M=zd.parse(await s.complete({...m,claimId:C.claimId,output:w,status:k}));break}catch(P){if(o()-u+250>r)throw P;await l(250)}return await i(M.output),"executed"}var ts=Qd;var Xd=/^[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 Ii(e){return e.map(({description:t,inputSchema:n,name:r})=>({description:t,name:r,parameters:n}))}function xi(e){return Object.fromEntries(Ii(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 Ni(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 ns({clientSubmittedAt:e,clientTools:t,generateConversationTitle:n,imageSearch:r,modelId:o,newsSearch:s,pageContext:i,permissionMode:p,turnId:c,webSearch:l}){if(!Xd.test(c))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:Ii(t),...n===void 0?{}:{generateConversationTitle:n},imageSearch:r,...o?{modelId:o}:{},newsSearch:s,pageContext:i,permissionMode:p,protocolVersion:6,requestId:c,sdkVersion:je,turnId:c,webSearch:l}}function _i(e){return e.replace(/^\/+|\/+$/g,"")}function ki(e){let t=new URL(e.baseUrl),n=_i(t.pathname),r=_i(e.path);if(!r)throw new Error("The assistant returned an invalid connection path");return{basePath:n||r,host:t.host,...n?{path:r}:{},protocol:t.protocol==="http:"?"ws":"wss"}}function Oi(e,t){let n=e;return{next:async()=>{if(n){let r=n;return n=null,r}return t()},refresh:t}}function Di(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 Li(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 Jd(e){return e==="composeUI"||e==="renderComponent"}function rs(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 Jd(o)}import{Xmark as fp}from"@gravity-ui/icons";import{File as Zd,FileCode as ep,FileLetterP as tp,FileLetterW as np,FileLetterX as rp,FileText as op,FileZipper as sp,MusicNote as ap,Picture as ip,Video as cp}from"@gravity-ui/icons";var lp=new Set(["csv","ods","xls","xlsm","xlsx"]),up=new Set(["doc","docx","odt","rtf"]),dp=new Set(["css","go","html","java","js","json","jsx","mdx","php","py","rb","rs","scss","sh","sql","swift","ts","tsx","xml","yaml","yml"]),pp=new Set(["7z","bz2","gz","rar","tar","tgz","zip"]),mp=new Set(["log","md","text","txt"]);function gp(e){let t=e.trim().toLowerCase(),n=t.lastIndexOf(".");return n>0?t.slice(n+1):""}function Ur(e){let t=gp(e.name),n=e.type.toLowerCase();return lp.has(t)||n.includes("csv")||n.includes("excel")||n.includes("spreadsheet")?{Icon:rp,kind:"spreadsheet",label:"Spreadsheet"}:t==="pdf"||n==="application/pdf"?{Icon:tp,kind:"pdf",label:"PDF document"}:up.has(t)||n.includes("wordprocessingml")?{Icon:np,kind:"document",label:"Document"}:n.startsWith("image/")?{Icon:ip,kind:"image",label:"Image"}:n.startsWith("video/")?{Icon:cp,kind:"video",label:"Video"}:n.startsWith("audio/")?{Icon:ap,kind:"audio",label:"Audio"}:pp.has(t)||n.includes("zip")?{Icon:sp,kind:"archive",label:"Archive"}:dp.has(t)?{Icon:ep,kind:"code",label:"Code file"}:mp.has(t)||n.startsWith("text/")?{Icon:op,kind:"text",label:"Text document"}:{Icon:Zd,kind:"file",label:"File"}}import{jsx as Sn,jsxs as Hi}from"react/jsx-runtime";function os({file:e,onRemove:t}){let{Icon:n,kind:r,label:o}=Ur(e);return Hi("span",{className:"ha-attachment","data-kind":r,children:[Sn("span",{"aria-hidden":"true",className:"ha-attachment-icon",children:Sn(n,{})}),Hi("span",{className:"ha-attachment-copy",children:[Sn("span",{className:"ha-attachment-name",title:e.name,children:e.name}),Sn("span",{className:"ha-attachment-type",children:o})]}),Sn("button",{"aria-label":`Remove ${e.name}`,type:"button",onClick:t,children:Sn(fp,{"aria-hidden":"true"})})]})}import{Globe as hp,Xmark as yp}from"@gravity-ui/icons";import{jsx as ss,jsxs as Ui}from"react/jsx-runtime";function Bi({onRemove:e,title:t}){return ss("div",{className:"ha-context",children:Ui("button",{"aria-label":`Remove Ask about this: ${t}`,className:"ha-chip",type:"button",onClick:e,children:[ss(hp,{"aria-hidden":"true",className:"ha-chip-leading"}),Ui("span",{className:"ha-chip-title",title:t,children:["Ask about this: ",t]}),ss(yp,{"aria-hidden":"true",className:"ha-chip-remove"})]})})}import{useCallback as Br,useState as vp}from"react";import{jsx as bp}from"react/jsx-runtime";function as(e){return e.dataTransfer?.types?.includes("Files")??!1}function Fi({children:e,className:t,"data-controls-revealed":n,"data-dictating":r,"data-expanded":o,disabled:s=!1,onFileIntent:i,onFilesSelected:p}){let[c,l]=vp(!1),m=Br(w=>{as(w)&&(i?.(),!s&&(w.preventDefault(),l(!0)))},[s,i]),u=Br(w=>{s||!as(w)||(w.preventDefault(),w.dataTransfer.dropEffect="copy",l(!0))},[s]),C=Br(w=>{let k=w.relatedTarget;k&&w.currentTarget.contains(k)||l(!1)},[]),d=Br(w=>{as(w)&&(i?.(),w.preventDefault(),l(!1),!(s||w.dataTransfer.files.length===0)&&p(Array.from(w.dataTransfer.files)))},[s,i,p]);return bp("div",{className:t,"data-controls-revealed":n,"data-dictating":r,"data-dragging":c||void 0,"data-expanded":o,onDragEnterCapture:m,onDragLeaveCapture:C,onDragOverCapture:u,onDropCapture:d,children:e})}var is="Enter";var Vi="Control+Shift+D";function $i(e){return!e.defaultPrevented&&!e.isComposing&&!e.repeat&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&e.key==="Enter"}function Qi(e){return!e.defaultPrevented&&!e.isComposing&&!e.repeat&&!e.altKey&&e.ctrlKey&&!e.metaKey&&e.shiftKey&&e.key.toLowerCase()==="d"}function Ki(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 cs(){return{activeTurnIds:new Set,busyIds:new Set,completedIds:new Set}}function qi(e,t){let{activeConversationId:n,busy:r,conversationId:o,failed:s,turnActive:i}=t,p=e.activeTurnIds.has(o),c=new Set(e.activeTurnIds),l=new Set(e.busyIds),m=new Set(e.completedIds);return r?l.add(o):l.delete(o),i?c.add(o):r||c.delete(o),(r||n===o)&&m.delete(o),!r&&p&&!s&&n!==o&&m.add(o),{activeTurnIds:c,busyIds:l,completedIds:m}}function ls(e,t){if(!e.completedIds.has(t))return e;let n=new Set(e.completedIds);return n.delete(t),{...e,completedIds:n}}function zi(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 Gi(e,t,n=()=>crypto.randomUUID()){return e?.conversationEpoch===t?e:{conversationEpoch:t,conversationId:n()}}function Fr({conversationEpoch:e,optimisticTarget:t,requestedConversationId:n,storedConversationId:r}){return n===null&&t?.conversationEpoch===e&&Ct(t.conversationId)?t.conversationId:Oo(n,r)}function Wi({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 us}from"react/jsx-runtime";function Vr({agentId:e,composerControlsAvailable:t,composerControlsRevealed:n,composerEndSlot:r,composerFooterSlot:o,composerStartSlot:s,greeting:i,loadingLabel:p,onComposerControlsReveal:c,placeholder:l,showStartScreen:m,subtitle:u,suggestedPrompts:C}){return m?us(xa,{composerConnecting:!0,agentId:e,composerControlsAvailable:t,composerControlsRevealed:n,composerEndSlot:r,composerFooterSlot:o,composerStartSlot:s,greeting:i,placeholder:l,subtitle:u,suggestedPrompts:C,onComposerControlsReveal:c,onIntent:()=>{}}):us("div",{className:"ha-loading",children:us(jt,{className:"ha-progress ha-progress-shimmer",children:p})})}function Sp(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 ji({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 p=Sp(i.headers.get("Retry-After"),n());if(n()-s+p>t)return i;await o(p),i=await r()}return i}var Gn="Thinking\u2026";function Yi({activeStreamKey:e,activeTurnMessageId:t}){return e!==null&&t===null}function Xi({continuingAssistantMessageId:e,isActiveTurn:t,streamingAssistantMessageId:n,trackedActivityMessageId:r}){return t?n??r??e:null}function Ji({hasActiveActivity:e,hasError:t,hasResponseStarted:n,isActiveTurn:r,messageCount:o,preferHomeWhileEmpty:s=!1,progress:i,runtimeStatus:p}){let c=o>0,l=!s&&!c&&(p==="pending"||p==="streaming"),m=!c&&!t&&!r&&!l;return e||n?{showHome:m,standaloneStatus:null}:r?{showHome:m,standaloneStatus:i??Gn}:l?{showHome:m,standaloneStatus:"Loading chat\u2026"}:{showHome:m,standaloneStatus:null}}import{jsx as Cp}from"react/jsx-runtime";function Zi({activeConversationId:e,children:t,routes:n}){return Object.values(n).map(r=>{let o=r.conversationId===e;return Cp("div",{className:"ha-conversation-route","data-active":o||void 0,"data-conversation-route":r.conversationId,hidden:!o,children:t(r,o)},r.conversationId)})}function ec({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 Pp}from"@gravity-ui/icons";import{Button as Ip}from"@heroui/react";import{useLayoutEffect as xp,useRef as Np}from"react";import{useCallback as _t,useEffect as Ap,useLayoutEffect as Tp,useRef as Ke,useState as Rp}from"react";var kt=4,Jt=1,tc="--ha-active-turn-spacer-height",nc='[data-role="user"][data-stream-anchor="true"]',Mp={hasOverflow:!1,isAtBottom:!0};function Wn(e){let t=e.scrollHeight-e.clientHeight>kt,n=!t||e.scrollHeight-Math.max(0,e.scrollTop)-e.clientHeight<=kt;return{hasOverflow:t,isAtBottom:n}}function wp({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 Ep(e,t){return e.hasOverflow===t.hasOverflow&&e.isAtBottom===t.isAtBottom}function rc(e){return e==="smooth"&&!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"smooth":"auto"}function oc(e){let t=Ke(0),n=Ke(!0),r=Ke(!1),o=Ke(null),s=Ke(!1),i=Ke(!1),p=Ke(null),c=Ke(0),l=Ke(null),m=Ke(null),u=Ke(!1),C=Ke(!1),d=Ke(!1),[w,k]=Rp(Mp),M=_t(y=>{k(f=>Ep(f,y)?f:y)},[]),P=_t(y=>{t.current=0,y.style.removeProperty(tc)},[]),$=_t(y=>{let f=l.current?y.querySelector(nc):null;if(!f)return t.current;let h=y.getBoundingClientRect(),b=f.getBoundingClientRect().top-h.top+y.scrollTop,T=y.scrollHeight-t.current,S=Number.parseFloat(window.getComputedStyle(y).paddingTop)||0,x=wp({anchorTop:b,clientHeight:y.clientHeight,contentHeight:T,paddingTop:S});return Math.abs(x-t.current)>1&&(t.current=x,y.style.setProperty(tc,`${x}px`)),t.current},[]),N=_t((y="smooth")=>{let f=e.current;if(!f)return;l.current=null,m.current=null,i.current=!1,u.current=!1,C.current=!1,d.current=!1,P(f),n.current=!0,r.current=!1,c.current=f.scrollTop,M({hasOverflow:Wn(f).hasOverflow,isAtBottom:!0});let h=f.scrollHeight,A=Math.max(0,h-f.clientHeight);s.current=Math.abs(Math.max(0,f.scrollTop)-A)>Jt,typeof f.scrollTo=="function"?f.scrollTo({behavior:rc(y),top:h}):f.scrollTop=h,c.current=Math.max(0,f.scrollTop)},[P,e,M]),I=_t(y=>{if(!l.current)return null;let f=y.querySelector(nc);if(f){let h=Number.parseFloat(window.getComputedStyle(y).paddingTop)||0;m.current=Math.max(0,f.offsetTop-h)}return m.current},[]),O=_t((y,f,h="auto")=>{let A=Math.max(0,y.scrollHeight-y.clientHeight),b=Math.min(f,A),T=rc(h),S=Math.abs(Math.max(0,y.scrollTop)-b)>Jt;i.current=T==="smooth"&&S,s.current=S,!S&&t.current>kt&&(u.current=!0),c.current=y.scrollTop,M({hasOverflow:A>kt,isAtBottom:A-b<=kt}),typeof y.scrollTo=="function"?y.scrollTo({behavior:T,top:f}):(y.scrollTop=f,i.current=!1),c.current=Math.max(0,y.scrollTop)},[M]),F=_t(()=>{let y=e.current;if(!y)return;$(y);let f=Wn(y),h=Math.max(0,y.scrollTop),A=h<c.current-Jt;if(c.current=h,A&&!f.isAtBottom){n.current=!1,r.current=!0,s.current=!1,i.current=!1,l.current=null,m.current=null,C.current=!1,M(f);return}!r.current&&(!f.hasOverflow||f.isAtBottom)&&(n.current=!0);let b=l.current!==null,T=I(y);if(b){if(r.current=!0,T!==null&&i.current){let S=Math.max(0,y.scrollHeight-y.clientHeight),x=Math.min(T,S);if(Math.abs(h-x)>Jt){M({hasOverflow:f.hasOverflow,isAtBottom:!0});return}s.current=!1,i.current=!1,u.current=t.current>kt}if(T!==null&&C.current){C.current=!1,O(y,T,"smooth");return}n.current=!1,M(f);return}if(n.current&&!r.current){N("auto");return}M(f)},[I,e,N,O,M,$]),ee=_t(y=>{let f=e.current;if(!f||o.current===y)return;let h=o.current!==null;if(o.current=y,y)u.current=!1,p.current!==y?(p.current=y,l.current=y,m.current=null,C.current=!0,d.current=!1,r.current=!0,n.current=!0):(l.current=null,m.current=null,C.current=!1);else if(h){l.current=null,m.current=null,s.current=!1,i.current=!1,u.current=t.current>kt,C.current=!1,r.current=!0;let A=Wn(f);n.current=!1,M(A)}},[e,M]);return Tp(()=>{let y=e.current;y&&(c.current=y.scrollTop,F(),r.current=!0,n.current=!1)},[F,e]),Ap(()=>{let y=e.current;if(!y)return;let f=()=>{let U=Math.max(0,y.scrollTop);s.current&&typeof y.scrollTo=="function"&&y.scrollTo({behavior:"auto",top:U}),d.current=!0,n.current=!1,r.current=!0,s.current=!1,i.current=!1,l.current=null,m.current=null,C.current=!1,c.current=U,M(Wn(y))},h=U=>{U.deltaY<0&&f()},A=null,b=U=>{A=U.touches[0]?.clientY??null},T=U=>{let q=U.touches[0]?.clientY??null;A!==null&&q!==null&&q>A&&f(),A=q},S=()=>{let U=Wn(y),q=Math.max(0,y.scrollTop),pe=q<c.current-Jt,ge=q>c.current+Jt;if(c.current=q,d.current){U.isAtBottom&&ge&&!u.current?(d.current=!1,n.current=!0,r.current=!1):(n.current=!1,r.current=!0),M(U);return}if(u.current){s.current=!1,i.current=!1,n.current=!1,r.current=!0,M(U);return}if(s.current&&!pe){let L=I(y),V=Math.max(0,y.scrollHeight-y.clientHeight),D=Math.min(L??V,V),_=U.isAtBottom||Math.abs(q-D)<=Jt,W=i.current;_&&(s.current=!1,i.current=!1,L!==null&&(u.current=t.current>kt,r.current=!0,n.current=!1)),M(W&&!_?{hasOverflow:U.hasOverflow,isAtBottom:!0}:L===null?r.current?U:{hasOverflow:U.hasOverflow,isAtBottom:n.current}:U);return}s.current=!1,i.current=!1,l.current=null,m.current=null,C.current=!1,n.current=U.isAtBottom,r.current=!U.isAtBottom,M(U)};y.addEventListener("scroll",S,{passive:!0}),y.addEventListener("touchmove",T,{passive:!0}),y.addEventListener("touchstart",b,{passive:!0}),y.addEventListener("wheel",h,{passive:!0});let x,Q=new Set,X=()=>{if(!x)return;let U=new Set(Array.from(y.children));for(let q of Q)U.has(q)||(x.unobserve(q),Q.delete(q));for(let q of U)Q.has(q)||(x.observe(q),Q.add(q))};typeof ResizeObserver<"u"&&(x=new ResizeObserver(F),x.observe(y),X());let j=typeof MutationObserver>"u"?void 0:new MutationObserver(U=>{U.some(q=>q.type==="childList"&&q.target===y)&&X(),F()});return j?.observe(y,{characterData:!0,childList:!0,subtree:!0}),()=>{y.removeEventListener("scroll",S),y.removeEventListener("touchmove",T),y.removeEventListener("touchstart",b),y.removeEventListener("wheel",h),j&&j.disconnect(),x&&x.disconnect()}},[I,F,e,M]),{hasOverflow:w.hasOverflow,isAtBottom:w.isAtBottom,maintainScrollPosition:F,scrollToBottom:N,setPinnedStream:ee}}import{jsx as $r,jsxs as _p}from"react/jsx-runtime";function sc({activityPhase:e=null,children:t,streamKey:n=null}){let r=Np(null),{hasOverflow:o,isAtBottom:s,maintainScrollPosition:i,scrollToBottom:p,setPinnedStream:c}=oc(r),l=o&&!s;return Xt(r),xp(()=>{c(n),i()},[t,i,c,n]),_p("div",{className:"ha-conversation","data-activity-phase":e??void 0,children:[$r("div",{ref:r,"aria-live":"polite",className:"ha-messages",role:"log",children:t}),$r("div",{"aria-hidden":l?void 0:!0,className:"ha-scroll-button-container","data-state":l?"visible":"hidden",children:$r(Ip,{isIconOnly:!0,"aria-hidden":l?void 0:!0,"aria-label":"Scroll to bottom",className:"ha-scroll-button",isDisabled:!l,size:"sm",variant:"secondary",onPress:()=>p("smooth"),children:$r(Pp,{"aria-hidden":"true"})})})]})}import{Suspense as kp,lazy as Op}from"react";var ds;function ps(){return ds??=import("./component-renderer-KWBZJPBV.js").then(e=>({default:e.ComponentRenderer})),ds}function ac(){ps().catch(()=>{ds=void 0})}import{jsx as ic}from"react/jsx-runtime";var Dp=Op(ps);function cc(e){return ic(kp,{fallback:null,children:ic(Dp,{...e})})}import{ArrowsRotateLeft as Lp,Check as Hp,Copy as Up,ThumbsDown as Bp,ThumbsUp as Fp}from"@gravity-ui/icons";import{Button as Qr,Popover as Kr,TextArea as Vp}from"@heroui/react";import{useCallback as $p,useEffect as Qp,useRef as lc,useState as jn}from"react";import{Fragment as Gp,jsx as Re,jsxs as Yn}from"react/jsx-runtime";var Kp=2e3,qp=1e3,zp=[{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 uc({actions:e,feedback:t,onCopy:n,onFeedback:r,onRetry:o}){let[s,i]=jn(!1),[p,c]=jn(!1),[l,m]=jn(""),[u,C]=jn([]),[d,w]=jn(),k=lc(null),M=lc(0),P=$p(f=>{w(f?.closest(".ha-panel")??void 0)},[]);Qp(()=>()=>{k.current!==null&&window.clearTimeout(k.current)},[]);let $=e.includes("copy")&&n,N=e.includes("feedback")&&r,I=e.includes("retry")&&o;if(!$&&!N&&!I)return null;let O=()=>{n?.(),i(!0),k.current!==null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{i(!1),k.current=null},Kp)},F=f=>{!f&&Date.now()-M.current<350||c(f)},ee=f=>{C(h=>h.includes(f)?h.filter(A=>A!==f):[...h,f])},y=()=>{let f=l.trim();r?.("down",{...f?{comment:f}:{},reasons:u}),c(!1)};return Yn("div",{"aria-label":"Message actions",className:"ha-message-actions",role:"group",children:[$?Re("button",{"aria-label":s?"Copied":"Copy response",className:"ha-message-action","data-copied":s||void 0,type:"button",onClick:O,children:Re("span",{className:"ha-message-action-icon",children:s?Re(Hp,{"aria-hidden":"true"}):Re(Up,{"aria-hidden":"true"})},s?"check":"copy")}):null,N?Yn(Gp,{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(Fp,{"aria-hidden":"true"})}),Yn(Kr,{isOpen:p,onOpenChange:F,children:[Re(Qr,{ref:P,isIconOnly:!0,"aria-label":"Bad response","aria-pressed":t==="down",className:"ha-message-action ha-feedback-trigger","data-open":p||void 0,"data-selected":t==="down"||void 0,size:"sm",variant:"ghost",onPointerDown:()=>{M.current=Date.now()},children:Re(Bp,{"aria-hidden":"true"})}),Re(Kr.Content,{className:"ha-feedback-popover",offset:8,placement:"top start",UNSTABLE_portalContainer:d,children:Yn(Kr.Dialog,{className:"ha-feedback-dialog",children:[Re(Kr.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:zp.map(f=>{let h=u.includes(f.value);return Re(Qr,{"aria-pressed":h,className:"ha-feedback-reason",size:"sm",variant:h?"secondary":"outline",onPress:()=>ee(f.value),children:f.label},f.value)})}),Re(Vp,{fullWidth:!0,"aria-label":"Additional feedback",className:"ha-feedback-textarea",maxLength:qp,placeholder:"Add details (optional)",rows:3,value:l,variant:"secondary",onChange:f=>m(f.target.value)}),Re("p",{className:"ha-feedback-privacy",children:"Avoid sharing sensitive information."}),Yn("div",{className:"ha-feedback-footer",children:[Re(Qr,{className:"ha-feedback-cancel",size:"sm",variant:"ghost",onPress:()=>c(!1),children:"Cancel"}),Re(Qr,{className:"ha-feedback-submit",size:"sm",variant:"primary",onPress:y,children:t==="down"?"Update":"Send"})]})]})})]})]}):null,I?Re("button",{"aria-label":"Retry response",className:"ha-message-action",type:"button",onClick:o,children:Re(Lp,{"aria-hidden":"true"})}):null]})}import{jsx as Cn,jsxs as dc}from"react/jsx-runtime";function ms({file:e}){let t=e.filename?.trim()||"Attachment",n=e.mediaType?.trim()||"",{Icon:r,kind:o,label:s}=Ur({name:t,type:n});return o==="image"?Cn("a",{"aria-label":`Open ${t}`,className:"ha-message-image",download:e.filename,href:e.url,rel:"noopener noreferrer",target:"_blank",title:t,children:Cn("span",{"aria-hidden":"true",style:{backgroundImage:`url(${JSON.stringify(e.url)})`}})}):dc("a",{className:"ha-message-file","data-kind":o,download:e.filename,href:e.url,rel:"noopener noreferrer",target:"_blank",children:[Cn("span",{"aria-hidden":"true",className:"ha-message-file-icon",children:Cn(r,{})}),dc("span",{className:"ha-message-file-copy",children:[Cn("span",{className:"ha-message-file-name",title:t,children:t}),Cn("span",{className:"ha-message-file-type",children:s})]})]})}function Zt(){return{blockedMessageId:null,isPaused:!1,messages:[]}}function gs(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 Xn(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 pc(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],[p]=i.splice(o,1),l=i.findIndex(m=>m.id===n)+(r==="after"?1:0);return i.splice(l,0,p),i.every((m,u)=>m.id===e.messages[u]?.id)?e:{...e,messages:i}}function Jn(e,t){return e.isPaused===t?e:{...e,isPaused:t}}function gt(e,t){return e.blockedMessageId===t?e:{...e,blockedMessageId:t}}function mc(e){let t=e.text.trim();return t||`${e.files.length} attachment${e.files.length===1?"":"s"}`}function ft(e){return e.deliveryStatus??"pending"}function An(e,t,n){let r=e.messages.findIndex(s=>s.id===t);if(r===-1||ft(e.messages[r])===n)return e;let o=[...e.messages];return o[r]={...o[r],deliveryStatus:n},{...e,messages:o}}var Wp="heroui-agent-message-outbox",jp=1,Ot="conversation-outboxes",Yp=":message-outbox:",en=new Map;function fs(e,t){return`${e}${Yp}${t}:v1`}async function gc(e){await en.get(e)?.catch(()=>{});let t=await ys();if(!t)return Zt();try{let n=t.transaction(Ot,"readonly"),r=await rm(n.objectStore(Ot).get(e));return await vs(n),Xp(r,e)}catch{return Zt()}finally{t.close()}}function hs(e,t,n=Date.now()){return vc(e,async()=>{let r=t.messages.length>0?await Jp(t):null,o=await ys();if(!o)throw new Error("Durable message storage is unavailable");try{let s=o.transaction(Ot,"readwrite"),i=s.objectStore(Ot);t.messages.length===0?i.delete(e):i.put({key:e,savedAt:n,state:r}),await vs(s)}finally{o.close()}})}function fc(e){return vc(e,async()=>{let t=await ys();if(t)try{let n=t.transaction(Ot,"readwrite");n.objectStore(Ot).delete(e),await vs(n)}finally{t.close()}})}function hc(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 yc(e,t){let n=e.messages.filter(o=>!t.has(o.id)).map(o=>ft(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 Xp(e,t){if(!e||typeof e!="object")return Zt();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 Zt();let o=r.messages.map(em).filter(i=>i!==null),s=new Set(o.map(i=>i.id));return{blockedMessageId:typeof r.blockedMessageId=="string"&&s.has(r.blockedMessageId)?r.blockedMessageId:null,isPaused:r.isPaused,messages:o}}async function Jp(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(Zp))})))}}async function Zp(e){return{bytes:await e.arrayBuffer(),lastModified:e.lastModified,name:e.name,type:e.type}}function em(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.id=="string"&&t.id.length>0&&typeof t.text=="string"&&Array.isArray(t.files)&&(t.generateConversationTitle===void 0||typeof t.generateConversationTitle=="boolean")&&(t.isInitialTurn===void 0||typeof t.isInitialTurn=="boolean")&&(t.deliveryStatus===void 0||t.deliveryStatus==="pending"||t.deliveryStatus==="sending"||t.deliveryStatus==="admitted")){let n=t.files.map(tm).filter(r=>r!==null);return n.length!==t.files.length?null:{...t,files:n}}return null}function tm(e){if(typeof File<"u"&&e instanceof File)return e;if(typeof File>"u"||!e||typeof e!="object")return null;let t=e;return!nm(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 nm(e){return Object.prototype.toString.call(e)==="[object ArrayBuffer]"}function vc(e,t){let r=(en.get(e)??Promise.resolve()).catch(()=>{}).then(t);return en.set(e,r),r.then(()=>{en.get(e)===r&&en.delete(e)},()=>{en.get(e)===r&&en.delete(e)}),r}function ys(){return typeof indexedDB>"u"?Promise.resolve(null):new Promise((e,t)=>{let n=indexedDB.open(Wp,jp);n.onerror=()=>t(n.error??new Error("Unable to open message outbox")),n.onupgradeneeded=()=>{let r=n.result;r.objectStoreNames.contains(Ot)||r.createObjectStore(Ot,{keyPath:"key"})},n.onsuccess=()=>e(n.result)})}function rm(e){return new Promise((t,n)=>{e.onerror=()=>n(e.error??new Error("IndexedDB request failed")),e.onsuccess=()=>t(e.result)})}function vs(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 bc({hasChatError:e,hasPendingClientToolCalls:t,hasReadyClientToolContinuation:n,isLocalPending:r,isResuming:o,isRunning:s,recoveryError:i}){return o||s||t||r||n&&!i&&!e}function Sc(e,t){return e.text?{files:t,text:e.text}:{files:t}}function Cc(e){let t=e.text.trim();return t||`${e.files.length} attachment${e.files.length===1?"":"s"}`}function Ac({activeMessageId:e,authoritativeMessageCount:t,isNewChatStartScreen:n,queuedMessageCount:r}){return n&&t===0&&r===0&&e===null}function Tc({authoritativeMessageCount:e,localTurn:t,queue:n}){return e>0?null:t??n.messages.find(o=>o.isInitialTurn&&ft(o)!=="admitted")??null}function Rc(e,t){return e.messages.filter(n=>ft(n)==="pending"&&(n.id!==t||e.isPaused||e.blockedMessageId===t))}function Mc({isClientTool:e,state:t}){return e&&(t==="input-streaming"||t==="input-available"||t==="approval-requested"||t==="approval-responded")}function wc({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=>ft(o)==="sending")?null:r.messages.find(o=>ft(o)==="pending")??null}function Ec(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 om,CircleExclamation as sm,Clock as am,Grip as im,Pencil as cm,TrashBin as lm}from"@gravity-ui/icons";import{useImperativeHandle as um,useLayoutEffect as dm,useRef as bs}from"react";import{useRef as qr,useState as zr}from"react";function Pc({messages:e,onReorder:t,onReorderStateChange:n}){let r=qr(null),o=qr(null),s=qr(null),i=qr(null),[p,c]=zr(""),[l,m]=zr(null),[u,C]=zr(null),[d,w]=zr(null),k=h=>{o.current=h,C(h)},M=()=>{let h=r.current!==null;r.current=null,m(null),k(null),h&&n?.(s.current!==null)},P=(h,A,b)=>{let T=e.findIndex(x=>x.id===h)+1,S=e.findIndex(x=>x.id===A)+1;c(`Moved queued message ${T} ${b} queued message ${S}.`)},$=(h,A,b)=>{let T=e.findIndex(Q=>Q.id===h),S=e.findIndex(Q=>Q.id===A),x=b==="before"&&T===S-1||b==="after"&&T===S+1;T===-1||S===-1||T===S||x||(t(h,A,b),P(h,A,b))},N=(h,A)=>{e.length<2||h.pointerType==="mouse"&&h.button!==0||(h.currentTarget.setPointerCapture?.(h.pointerId),r.current={hasMoved:!1,messageId:A,pointerId:h.pointerId,startX:h.clientX,startY:h.clientY},s.current=null,w(null),m(A),k(null),n?.(!0))},I=h=>{let A=r.current;if(!A||A.pointerId!==h.pointerId||!A.hasMoved&&Math.hypot(h.clientX-A.startX,h.clientY-A.startY)<4)return;A.hasMoved=!0;let b=h.currentTarget.closest(".ha-message-queue"),T=0;if(b){let U=b.getBoundingClientRect(),q=28;h.clientY<U.top+q?T=-12:h.clientY>U.bottom-q&&(T=12)}let Q=h.currentTarget.getRootNode().elementFromPoint?.(h.clientX,h.clientY)?.closest("[data-queue-message-id]"),X=Q?.dataset.queueMessageId,j=null;if(Q&&X&&X!==A.messageId){let U=Q.getBoundingClientRect(),q=h.clientY<U.top+U.height/2?"before":"after";j={messageId:X,position:q}}if(b&&T!==0&&(b.scrollTop+=T),!j){k(null);return}o.current?.messageId===j.messageId&&o.current.position===j.position||k(j)},O=(h,A)=>{let b=r.current;if(!b||b.pointerId!==h.pointerId)return;h.currentTarget.hasPointerCapture?.(h.pointerId)&&h.currentTarget.releasePointerCapture?.(h.pointerId);let T=o.current;A&&b.hasMoved&&(i.current=b.messageId),A&&b.hasMoved&&T&&$(b.messageId,T.messageId,T.position),M()},F=(h,A,b)=>{let T=h.key==="ArrowUp"?-1:h.key==="ArrowDown"?1:0;if(!T)return;let S=e[b+T];S&&(h.preventDefault(),$(A,S.id,T===-1?"before":"after"))},ee=h=>{let A=i.current===h;if(i.current=null,A)return;let b=s.current===h?null:h;s.current=b,w(b),n?.(r.current!==null||b!==null)},y=h=>{s.current===h&&(s.current=null,w(null),n?.(r.current!==null))};return{announcement:p,closePositionPicker:y,draggedMessageId:l,dropTarget:u,finishPointerDrag:O,handleReorderKeyDown:F,moveMessageToPosition:(h,A,b)=>{let T=e[b];if(!T||A===b){y(h);return}$(h,T.id,A<b?"after":"before"),y(h)},positionPickerMessageId:d,startPointerDrag:N,togglePositionPicker:ee,updatePointerDrag:I}}import{jsx as xe,jsxs as Zn}from"react/jsx-runtime";function Gr(e,t){let n=e?.querySelectorAll("[data-queue-message-id]")[t];return n?(n.focus({preventScroll:!0}),n.scrollIntoView?.({block:"nearest"}),!0):!1}function Ic({blockedMessageId:e,isSendNowDisabled:t,messages:n,onEdit:r,onFocusComposer:o,onRemove:s,onReorder:i,onReorderStateChange:p,onSendNow:c,ref:l}){let m=bs(null),u=bs(null),C=bs(n),{announcement:d,closePositionPicker:w,draggedMessageId:k,dropTarget:M,finishPointerDrag:P,handleReorderKeyDown:$,moveMessageToPosition:N,positionPickerMessageId:I,startPointerDrag:O,togglePositionPicker:F,updatePointerDrag:ee}=Pc({messages:n,onReorder:i,onReorderStateChange:p});if(um(l,()=>({focusLastMessage:()=>Gr(u.current,n.length-1)}),[n.length]),dm(()=>{let f=C.current;C.current=n;let h=m.current;if(!h||n.some(T=>T.id===h))return;let A=f.findIndex(T=>T.id===h),b=Math.min(A,n.length-1);m.current=null,(A<0||!Gr(u.current,b))&&o()},[n,o]),n.length===0)return null;let y=(f,h)=>{if(f.target===f.currentTarget&&!(f.key!=="ArrowUp"&&f.key!=="ArrowDown")){if(f.preventDefault(),f.key==="ArrowUp"){Gr(u.current,h-1);return}Gr(u.current,h+1)||o()}};return Zn("section",{"aria-label":"Queued messages",className:"ha-message-queue",children:[xe("div",{className:"ha-message-queue-header",children:"Queued"}),xe("ol",{ref:u,className:"ha-message-queue-list",children:n.map((f,h)=>{let A=e===f.id,b=h+1,T=A?`ha-queued-message-status-${f.id}`:void 0;return Zn("li",{"aria-describedby":T,"aria-keyshortcuts":"ArrowUp ArrowDown",className:"ha-message-queue-item","data-blocked":A?"true":void 0,"data-dragging":k===f.id?"true":void 0,"data-queue-message-id":f.id,tabIndex:-1,title:A?"This message could not be sent":void 0,"data-drop-position":M?.messageId===f.id?M.position:void 0,onKeyDown:S=>y(S,h),onBlur:S=>{let x=S.relatedTarget;m.current===f.id&&(!x||!S.currentTarget.contains(x))&&(m.current=null)},onFocus:()=>{m.current=f.id},children:[xe("button",{"aria-keyshortcuts":"ArrowUp ArrowDown","aria-label":`Reorder queued message ${b}`,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(f.id),onKeyDown:S=>$(S,f.id,h),onPointerCancel:S=>P(S,!1),onPointerDown:S=>O(S,f.id),onPointerMove:ee,onPointerUp:S=>P(S,!0),children:xe(im,{"aria-hidden":"true"})}),I===f.id?xe("select",{autoFocus:!0,"aria-label":`Move queued message ${b} to position`,className:"ha-message-queue-position-select",value:h,onBlur:()=>w(f.id),onChange:S=>N(f.id,h,Number(S.currentTarget.value)),children:n.map((S,x)=>Zn("option",{value:x,children:["Position ",x+1,x===h?" (current)":""]},S.id))}):xe("span",{"aria-hidden":"true",className:"ha-message-queue-icon",children:A?xe(sm,{"aria-hidden":"true"}):xe(am,{"aria-hidden":"true"})}),Zn("span",{className:"ha-message-queue-content",children:[xe("span",{className:"ha-message-queue-preview",children:mc(f)}),A?xe("span",{className:"ha-message-queue-status",id:T,role:"status",children:"Could not send"}):null]}),Zn("span",{className:"ha-message-queue-actions",children:[xe("button",{"aria-label":`Send queued message ${b} now`,className:"ha-message-queue-action",disabled:t,title:"Send now",type:"button",onClick:()=>c(f.id),children:xe(om,{"aria-hidden":"true"})}),xe("button",{"aria-label":`Edit queued message ${b}`,className:"ha-message-queue-action",title:"Edit",type:"button",onClick:()=>r(f.id),children:xe(cm,{"aria-hidden":"true"})}),xe("button",{"aria-label":`Remove queued message ${b}`,className:"ha-message-queue-action",title:"Remove",type:"button",onClick:()=>s(f.id),children:xe(lm,{"aria-hidden":"true"})})]})]},f.id)})}),xe("span",{"aria-live":"polite",className:"ha-message-queue-announcement",role:"status",children:d})]})}import{FileText as vm}from"@gravity-ui/icons";import Uc,{createContext as bm,useContext as Sm,useMemo as Cm}from"react";import{composeRenderProps as Am}from"react-aria-components";import{mergeRefs as pm}from"@react-aria/utils";import{useControlledState as mm}from"@react-stately/utils";import{createContext as gm,useCallback as Je,useContext as Nc,useEffect as xc,useMemo as _c,useRef as Wr,useState as fm}from"react";import{OverlayArrow as hm,Popover as ym,composeRenderProps as kc}from"react-aria-components";import{jsx as Tn}from"react/jsx-runtime";var Ss=gm({handleCancelClose:()=>{},handleClose:()=>{},handleOpen:()=>{},isOpen:!1,isPointerInsideRef:{current:!1},setPortalContainer:()=>{},triggerRef:{current:null}}),Cs=({children:e,closeDelay:t=300,defaultOpen:n=!1,onOpenChange:r,open:o,openDelay:s=700})=>{let[i,p]=mm(o,n,r),[c,l]=fm(),m=Wr(null),u=Wr(!1),C=Wr(void 0),d=Wr(void 0),w=Je(()=>{clearTimeout(C.current),clearTimeout(d.current)},[]);xc(()=>w,[w]),xc(()=>{if(!i)return;let N=I=>{I.key==="Escape"&&(p(!1),w())};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[w,i,p]);let k=Je((N=!1)=>{w(),N||s<=0?p(!0):C.current=setTimeout(()=>p(!0),s)},[w,s,p]),M=Je((N=!1)=>{w(),N||t<=0?p(!1):d.current=setTimeout(()=>p(!1),t)},[w,t,p]),P=Je(()=>{clearTimeout(d.current)},[]),$=_c(()=>({handleCancelClose:P,handleClose:M,handleOpen:k,isOpen:i,isPointerInsideRef:u,portalContainer:c,setPortalContainer:l,triggerRef:m}),[P,M,k,i,c]);return Tn(Ss,{value:$,children:e})},Oc=({children:e,className:t,onBlur:n,onFocus:r,onPointerEnter:o,onPointerLeave:s,ref:i,...p})=>{let{handleClose:c,handleOpen:l,isPointerInsideRef:m,setPortalContainer:u,triggerRef:C}=Nc(Ss),d=Je(N=>{C.current=N,u(wa(N))},[u,C]),w=_c(()=>pm(i,d),[i,d]),k=Je(N=>{N.pointerType==="mouse"&&l(),o?.(N)},[l,o]),M=Je(N=>{N.pointerType==="mouse"&&c(),s?.(N)},[c,s]),P=Je(N=>{l(!0),r?.(N)},[l,r]),$=Je(N=>{m.current||c(),n?.(N)},[c,m,n]);return Tn("span",{ref:w,className:fe("aui-hover-card__trigger",t),"data-slot":"hover-card-trigger",onBlur:$,onFocus:P,onPointerEnter:k,onPointerLeave:M,...p,children:e})},Dc=({UNSTABLE_portalContainer:e,children:t,className:n,offset:r=8,onOpenChange:o,onPointerEnter:s,onPointerLeave:i,placement:p="top",...c})=>{let{handleCancelClose:l,handleClose:m,isOpen:u,isPointerInsideRef:C,portalContainer:d,triggerRef:w}=Nc(Ss),k=Je($=>{C.current=!0,l(),s?.($)},[l,C,s]),M=Je($=>{C.current=!1,m(),i?.($)},[m,C,i]),P=Je($=>{$||m(!0),o?.($)},[m,o]);return Tn(ym,{isNonModal:!0,"data-slot":"hover-card-content",isOpen:u,offset:r,placement:p,triggerRef:w,UNSTABLE_portalContainer:e??d,className:kc(n,$=>fe("aui-hover-card__content",$)??""),onOpenChange:P,onPointerEnter:k,onPointerLeave:M,...c,children:$=>typeof t=="function"?t($):t})},Lc=({children:e,className:t,...n})=>Tn(hm,{"data-slot":"hover-card-arrow",className:kc(t,r=>fe("aui-hover-card__arrow",r)??""),...n,children:e??Tn("svg",{fill:"none",height:"12",viewBox:"0 0 12 12",width:"12",xmlns:"http://www.w3.org/2000/svg",children:Tn("path",{d:"M0 0C5.48483 8 6.5 8 12 0Z"})})});var er=Object.assign(Cs,{Arrow:Lc,Content:Dc,Root:Cs,Trigger:Oc});function Hc(e){try{return new URL(e).hostname.replace(/^www\./,"")}catch{return e.split("/").pop()||e}}import{Fragment as As,jsx as se,jsxs as Dt}from"react/jsx-runtime";var Bc=bm({sourceType:"url"}),tr=()=>Sm(Bc);function Tm(e){return e.trim().charAt(0).toUpperCase()||"?"}var Ts=({children:e,className:t,description:n,enablePreview:r,faviconUrl:o,href:s,locator:i,sourceType:p=s?"url":"document",title:c,...l})=>{let m=s?Hc(s):void 0,C=r??(p==="url"&&!!s?!!(n||c):!!(n||i)),d=Cm(()=>({description:n,domain:m,enablePreview:C,faviconUrl:o,href:s,locator:i,sourceType:p,title:c}),[n,m,C,o,s,i,p,c]),w=e??Dt(As,{children:[se(Rs,{}),C?se(Ms,{description:n,title:c}):null]}),k=se("div",{className:fe("aui-chat-source",t),"data-has-locator":i?"true":void 0,"data-slot":"chat-source","data-source-type":p,...l,children:w});return se(Bc,{value:d,children:C?se(er,{closeDelay:0,openDelay:150,children:k}):k})},Rs=({children:e,className:t,label:n,...r})=>{let{domain:o,enablePreview:s,href:i,locator:p,sourceType:c,title:l}=tr(),m=c==="url"&&i,u=e??n??(m?Dt(As,{children:[se(Xr,{}),se(Yr,{children:l??o}),p?se(jr,{children:p}):null]}):Dt(As,{children:[se(Jr,{}),se(Yr,{children:l}),p?se(jr,{children:p}):null]}));if(m){let w=se("a",{"aria-label":`Open source: ${l??o??i}`,className:"aui-chat-source__trigger-link",href:i,rel:"noopener noreferrer",target:"_blank",...r,children:u});return se("span",{className:fe("aui-chat-source__trigger",t),"data-slot":"chat-source-trigger",children:s?se(er.Trigger,{children:w}):w})}let C=[l,p].filter(Boolean).join(", ")||"Document",d=se("span",{className:s?void 0:"aui-chat-source__trigger-link",...s?{}:r,children:u});return se("span",{className:fe("aui-chat-source__trigger",t),"data-slot":"chat-source-trigger",children:s?se(er.Trigger,{children:se("button",{"aria-label":`Source: ${C}`,className:"aui-chat-source__trigger-link",type:"button",...r,children:u})}):d})},jr=({children:e,className:t,...n})=>{let{locator:r}=tr();return e??r?se("span",{className:fe("aui-chat-source__locator",t),"data-slot":"chat-source-locator",...n,children:e??r}):null},Xr=({children:e,className:t,faviconUrl:n})=>{let{domain:r,faviconUrl:o,href:s,title:i}=tr(),p=i??r??s??"Source",c=n??o;if(e&&Uc.isValidElement(e)){let l=e;return Uc.cloneElement(l,{className:fe("aui-chat-source__icon",t,l.props.className),"data-slot":"chat-source-icon"})}return Dt("span",{"aria-hidden":"true",className:fe("aui-chat-source__icon",t),"data-slot":"chat-source-icon",children:[se("span",{className:"aui-chat-source__icon-fallback",children:Tm(p)}),c?se("img",{alt:"",className:"aui-chat-source__favicon","data-slot":"chat-source-favicon",decoding:"async",height:14,loading:"lazy",referrerPolicy:"no-referrer",src:c,width:14,onError:l=>{l.currentTarget.hidden=!0}}):null]})},Jr=({className:e})=>se(vm,{className:fe("aui-chat-source__document-icon",e),"data-slot":"chat-source-document-icon"}),Yr=({children:e,className:t,...n})=>{let{domain:r,title:o}=tr();return se("span",{className:fe("aui-chat-source__title",t),"data-slot":"chat-source-title",...n,children:e??o??r})},Ms=({children:e,className:t,description:n,title:r,...o})=>{let{description:s,domain:i,enablePreview:p,href:c,locator:l,sourceType:m,title:u}=tr();if(!p)return null;let C=r??u,d=n??s,w=m==="url"&&c?Dt("a",{className:"aui-chat-source__preview-link",href:c,rel:"noopener noreferrer",target:"_blank",children:[Dt("div",{className:"aui-chat-source__preview-header",children:[se(Xr,{}),se("span",{className:"aui-chat-source__preview-domain",children:i})]}),C?se("div",{className:"aui-chat-source__preview-title",children:C}):null,d?se("div",{className:"aui-chat-source__preview-description",children:d}):null]}):Dt("div",{className:"aui-chat-source__preview-link","data-source-type":"document",children:[Dt("div",{className:"aui-chat-source__preview-header",children:[se(Jr,{}),se("span",{className:"aui-chat-source__preview-domain",children:C??"Document"})]}),l?se("div",{className:"aui-chat-source__preview-title",children:l}):null,d?se("div",{className:"aui-chat-source__preview-description",children:d}):null]});return se(er.Content,{"data-slot":"chat-source-preview",offset:8,placement:"top",className:Am(t,k=>fe("aui-chat-source__preview",k)??""),...o,children:e??w})};import{Disclosure as Rn}from"@heroui/react";import{composeRenderProps as ws}from"react-aria-components";import{jsx as Lt,jsxs as Rm}from"react/jsx-runtime";var Es=({children:e,className:t,...n})=>Lt(Rn,{"data-slot":"chat-sources",className:ws(t,r=>fe("aui-chat-sources",r)??""),...n,children:e}),Fc=({children:e,className:t,...n})=>Lt(Rn.Heading,{children:Rm(Rn.Trigger,{"data-slot":"chat-sources-trigger",className:ws(t,r=>fe("aui-chat-sources__trigger",r)??""),...n,children:[Lt("span",{className:"aui-chat-sources__trigger-label",children:e}),Lt(Rn.Indicator,{className:"aui-chat-sources__indicator"})]})}),Vc=({children:e,className:t,...n})=>Lt(Rn.Content,{"data-slot":"chat-sources-content",className:ws(t,r=>fe("aui-chat-sources__content",r)??""),...n,children:Lt(Rn.Body,{children:Lt("div",{className:"aui-chat-sources__content-body",children:e})})}),$c=({children:e,className:t,role:n="list",...r})=>Lt("div",{className:fe("aui-chat-sources__list",t),"data-slot":"chat-sources-list",role:n,...r,children:e});var Qc=Object.assign(Ts,{DocumentIcon:Jr,Icon:Xr,Locator:jr,Preview:Ms,Root:Ts,Title:Yr,Trigger:Rs}),nr=Object.assign(Es,{Content:Vc,List:$c,Root:Es,Trigger:Fc});import{jsx as At,jsxs as Kc}from"react/jsx-runtime";function Mm(e){return`https://www.google.com/s2/favicons?domain_url=${encodeURIComponent(e)}&sz=64`}function qc({inList:e=!1,source:t}){let n="url"in t?t.url:void 0;return At(Qc,{description:t.excerpt,faviconUrl:n?Mm(n):void 0,href:n,locator:t.locator,role:e?"listitem":void 0,sourceType:t.sourceType??"url",title:t.title})}function wm({sources:e}){return At(nr.List,{"aria-label":"Sources",children:e.map(t=>At(qc,{inList:!0,source:t},t.sourceId))})}function zc({sources:e}){return e.length===0?null:e.length===1?At("div",{"aria-label":"Sources",className:"ha-message-sources","data-count":"1",role:"group",children:At(qc,{source:e[0]})}):Kc(nr,{className:"ha-message-sources","data-count":e.length,children:[Kc(nr.Trigger,{"aria-label":`${e.length} sources`,children:[At("span",{className:"ha-sources-label",children:"Sources"}),At("span",{"aria-hidden":"true",className:"ha-sources-count",children:e.length})]}),At(nr.Content,{children:At(wm,{sources:e})})]})}function Em(e){try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:(t.hash="",t.toString())}catch{return null}}function Gc(e){let t=new Map;for(let n of e){if(n.type!=="data-sources")continue;let r=mi.safeParse(n.data);if(r.success)for(let o of r.data.items){if("url"in o){let i=Em(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 Wc(e,{hasContent:t,isStreaming:n}){return n||!t?[]:e}import{Plus as Pm}from"@gravity-ui/icons";import{Button as Im}from"@heroui/react";import{jsx as jc}from"react/jsx-runtime";function Yc({isDisabled:e=!1,onPress:t}){return jc(Im,{isIconOnly:!0,"aria-label":"New chat",className:"ha-icon-button ha-new-chat-button",isDisabled:e,size:"sm",variant:"ghost",onPress:t,children:jc(Pm,{"aria-hidden":"true"})})}function Xc(e){return`heroui-agent:project-config:${e}`}function Jc(e){try{let t=window.localStorage.getItem(Xc(e));if(!t)return null;let n=Ir.safeParse(JSON.parse(t));return n.success?n.data:null}catch{return null}}function Zc(e,t){try{window.localStorage.setItem(Xc(e),JSON.stringify(t))}catch{}}var xm=["runtimeAdmittedAt","providerRequestedAt","providerFirstEventAt","firstSemanticTextAt","completedAt"];function el(e,t,n){if(!n||typeof n!="object"||Array.isArray(n)||typeof window>"u")return!1;let r=n,o={};for(let i of xm){let p=r[i];typeof p=="number"&&Number.isFinite(p)&&(o[i]=p)}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(Oa,{detail:s})),!0}import{ChevronDown as Nm,Ellipsis as _m,Pencil as km,Plus as Om,TrashBin as Dm}from"@gravity-ui/icons";import{Button as tn,Dropdown as rr,Input as Lm,Label as tl,Modal as at,Popover as Ps,TextField as Hm}from"@heroui/react";import{useCallback as Um,useRef as Is,useState as Ht}from"react";import{Fragment as al,jsx as Z,jsxs as Se}from"react/jsx-runtime";var nl="rename",rl="delete",Bm=80,ol=new Set;function xs({activeConversationId:e,busyConversationIds:t=ol,completedConversationIds:n=ol,groups:r,isNewConversationDisabled:o=!1,onDeleteConversation:s,onNewConversation:i,onRenameConversation:p,onSelectConversation:c,variant:l="popover"}){let[m,u]=Ht(!1),[C,d]=Ht(!1),[w,k]=Ht(null),[M,P]=Ht(null),[$,N]=Ht(""),[I,O]=Ht(null),[F,ee]=Ht(!1),[y,f]=Ht(),h=Is(0),A=Is(0),b=Is(null);Xt(b);let S=r.flatMap(D=>D.items).find(D=>D.id===e)?.title??"New chat",x=Um(D=>{f(D??void 0)},[]),Q=()=>{k(null),u(!1)},X=D=>{!D&&Date.now()-h.current<350||(D||k(null),u(D))},j=(D,_)=>{!_&&Date.now()-A.current<350||k(_?D:null)},U=(D,_)=>{Q(),P({item:D,type:_}),N(D.title),O(null),d(!0)},q=()=>{F||(O(null),d(!1))},pe=(D,_)=>{_===nl&&U(D,"rename"),_===rl&&!t.has(D.id)&&U(D,"delete")},ge=async()=>{if(!M||M.type!=="rename"||F)return;let D=$.trim();if(!D){O("Enter a name for this chat.");return}if(D===M.item.title){d(!1);return}ee(!0),O(null);try{await p(M.item.id,D),P({...M,item:{...M.item,title:D}}),d(!1)}catch(_){O(_ instanceof Error?_.message:"The chat could not be renamed")}finally{ee(!1)}},L=async()=>{if(!(!M||M.type!=="delete"||F)){ee(!0),O(null);try{await s(M.item.id),d(!1)}catch(D){O(D instanceof Error?D.message:"The chat could not be deleted")}finally{ee(!1)}}},V=r.length?r.map(D=>Se("section",{className:"ha-session-group",children:[Z("h3",{children:D.label}),Z("div",{className:"ha-session-list",children:D.items.map(_=>{let W=_.id===e,ne=t.has(_.id),ae=!ne&&n.has(_.id);return Se("div",{className:"ha-session-row","data-actions-open":w===_.id?"true":void 0,"data-active":W||void 0,"data-completed":ae||void 0,children:[Se("button",{"aria-current":W?"page":void 0,className:"ha-session-select",type:"button","aria-label":ae?`${_.title}, new response available`:void 0,onClick:()=>{Q(),W||c(_.id)},children:[ne?Z(jt,{className:"ha-session-title ha-session-shimmer",children:_.title}):Z("span",{className:"ha-session-title",children:_.title}),ae?Z("span",{"aria-hidden":"true",className:"ha-session-completed-dot"}):null]}),Se(rr,{isOpen:w===_.id,onOpenChange:he=>j(_.id,he),children:[Z(tn,{isIconOnly:!0,"aria-label":`Chat actions for ${_.title}`,className:"ha-session-actions-trigger",size:"sm",variant:"ghost",onPointerDown:()=>{A.current=Date.now()},children:Z(_m,{"aria-hidden":"true"})}),Z(rr.Popover,{className:"ha-session-actions-menu",placement:"bottom end",UNSTABLE_portalContainer:y,children:Se(rr.Menu,{"aria-label":`Actions for ${_.title}`,onAction:he=>pe(_,he),children:[Se(rr.Item,{id:nl,textValue:"Rename",children:[Z(km,{"aria-hidden":"true"}),Z(tl,{children:"Rename"})]}),Se(rr.Item,{id:rl,isDisabled:ne,textValue:ne?"Delete unavailable while responding":"Delete",variant:"danger",children:[Z(Dm,{"aria-hidden":"true",className:"ha-session-delete-icon"}),Z(tl,{children:ne?"Delete after response":"Delete"})]})]})})]})]},_.id)})})]},D.label)):Z("p",{className:"ha-session-empty",children:"Your recent chats will appear here."});return Se("div",{"data-variant":l,className:l==="sidebar"?"ha-session-picker ha-session-sidebar":"ha-session-picker",children:[l==="sidebar"?Se(al,{children:[Se("div",{className:"ha-session-sidebar-header",children:[Z("h2",{children:"Chats"}),Se(tn,{fullWidth:!0,className:"ha-session-new-chat",isDisabled:o,size:"sm",variant:"tertiary",onPress:()=>{Q(),i?.()},children:[Z(Om,{"aria-hidden":"true"}),"New chat"]})]}),Z("nav",{ref:b,"aria-label":"Recent chats",className:"ha-session-sidebar-history",children:V})]}):Se(Ps,{isOpen:m,onOpenChange:X,children:[Se(tn,{"aria-label":"Choose a chat",className:"ha-session-trigger",size:"sm",variant:"ghost",onPointerDown:()=>{h.current=Date.now()},children:[Z("span",{className:"font-medium",children:S}),Z(Nm,{"aria-hidden":"true"})]}),Z(Ps.Content,{isNonModal:!0,className:"ha-session-menu",placement:"bottom start",UNSTABLE_portalContainer:y,children:Z(Ps.Dialog,{"aria-label":"Chat history",className:"ha-session-history-dialog",children:V})})]}),Z(at.Backdrop,{className:"ha-session-modal-backdrop",isDismissable:!F,isKeyboardDismissDisabled:F,isOpen:C,UNSTABLE_portalContainer:y,onOpenChange:D=>{D||q()},children:Z(at.Container,{placement:"center",size:"sm",children:Z(at.Dialog,{className:"ha-session-modal",children:Z(Fm,{dialog:M,isPending:F,mutationError:I,renameTitle:$,onClose:q,onDelete:L,onRename:ge,onRenameTitleChange:N})})})}),Z("div",{ref:x,className:"ha-session-portal","data-open":m||C||w?"true":void 0,onPointerDown:D=>{D.target?.closest(".ha-session-menu, .ha-session-actions-menu, .ha-session-modal-backdrop")||(m||w)&&Q()}})]})}function Fm({dialog:e,isPending:t,mutationError:n,onClose:r,onDelete:o,onRename:s,onRenameTitleChange:i,renameTitle:p}){return e?.type==="rename"?Se("form",{onSubmit:c=>{c.preventDefault(),s()},children:[Z(at.Header,{children:Z(at.Heading,{children:"Rename chat"})}),Se(at.Body,{children:[Z(Hm,{autoFocus:!0,fullWidth:!0,"aria-label":"Chat name",isInvalid:!!n,name:"title",children:Z(Lm,{maxLength:Bm,value:p,variant:"secondary",onChange:c=>i(c.target.value)})}),Z(sl,{message:n})]}),Se(at.Footer,{children:[Z(tn,{fullWidth:!0,isDisabled:t,type:"button",variant:"outline",onPress:r,children:"Cancel"}),Z(tn,{fullWidth:!0,isPending:t,type:"submit",children:t?"Saving\u2026":"Submit"})]})]}):e?.type!=="delete"?null:Se(al,{children:[Z(at.Header,{children:Z(at.Heading,{children:"Delete chat?"})}),Se(at.Body,{children:[Se("p",{children:["Are you sure you want to delete ",Se("strong",{children:["\u201C",e.item.title,"\u201D"]}),"?"]}),Z(sl,{message:n})]}),Se(at.Footer,{children:[Z(tn,{fullWidth:!0,isDisabled:t,variant:"outline",onPress:r,children:"Cancel"}),Z(tn,{fullWidth:!0,isPending:t,variant:"danger",onPress:()=>void o(),children:t?"Deleting\u2026":"Delete"})]})]})}function sl({message:e}){return e?Z("p",{className:"ha-session-modal-error",role:"alert",children:e}):null}import{useEffect as Vm,useState as $m}from"react";import{jsx as qm}from"react/jsx-runtime";var Zr=["Thinking\u2026","Analyzing request\u2026","Preparing next steps\u2026"],Qm=1600,Km=5e3;function il(){let[e,t]=$m(0);return Vm(()=>{let n=e===Zr.length-1,r=window.setTimeout(()=>{t(o=>(o+1)%Zr.length)},n?Km:Qm);return()=>window.clearTimeout(r)},[e]),qm(Dr,{ariaLabel:"Working on your request\u2026",label:Zr[e]??Zr[0]})}function cl({now:e=()=>performance.now(),nowWallClock:t=()=>Date.now(),report:n,schedulePaint:r=o=>requestAnimationFrame(o)}){let o=new Map,s=null,i=(c,l)=>{o.has(c)||o.set(c,{painted:new Set,scheduled:new Set,startedAt:l?.startedAt??e(),startedAtWallClock:l?.startedAtWallClock??t()})},p=(c,l,m)=>{let u=o.get(c);!u||u.painted.has(l)||(u.scheduled.delete(l),u.painted.add(l),n({latencyMs:Math.max(0,Math.round(m-u.startedAt)),messageId:c,metric:l}))};return{activate(c){i(c),s=c},begin:i,complete(c){s===c&&(s=null)},getActiveMessageId(){return s},getStartedAtWallClock(c){return o.get(c)?.startedAtWallClock},markAfterPaint(c,l){let m=o.get(c);!m||m.painted.has(l)||m.scheduled.has(l)||(m.scheduled.add(l),r(()=>{p(c,l,e())}))},markPaintedAt(c,l,m){p(c,l,m)}}}function Ns(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 ll({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 nn({attempt:e,currentAttempt:t,manualStopRequested:n,stalledStopRequested:r}){return e===t&&!n&&!r}async function ul(e,t){return await e?.catch(()=>{}),t()}function dl({hasPendingClientToolCalls:e,isAutoContinuationPending:t,isRecovering:n,isRunning:r,localPending:o,stalled:s}){return!s&&(r||e||o||t||n)}function pl({hasActiveTurn:e,hasPendingClientToolCalls:t,isResuming:n,stalled:r}){return e&&!t&&!n&&!r}function ml(e){let t=globalThis.setTimeout(e,12e4);return()=>globalThis.clearTimeout(t)}function gl(e){let t=globalThis.setTimeout(e,12e4);return()=>globalThis.clearTimeout(t)}import{useCallback as zm,useEffect as or,useRef as fl,useState as hl}from"react";var Gm=300;function yl({attachments:e,draftKey:t,input:n,setAttachments:r,setInput:o}){let[s,i]=hl(null),[p,c]=hl(null),l=fl(n),m=fl(null);return or(()=>{l.current=n},[n]),or(()=>{let u=!1,C=Ha(t);return queueMicrotask(()=>{u||(C&&o(d=>d||C),c(t))}),Ua(t).then(d=>{u||(d.length>0&&r(w=>w.length>0?w:d),i(t))}),()=>{u=!0}},[t,r,o]),or(()=>{if(p!==t)return;let u=()=>_o(t,n);return m.current=window.setTimeout(u,Gm),window.addEventListener("pagehide",u),()=>{m.current!==null&&window.clearTimeout(m.current),m.current=null,window.removeEventListener("pagehide",u)}},[t,n,p]),or(()=>{if(p===t)return()=>_o(t,l.current)},[t,p]),or(()=>{s===t&&Ba(t,e)},[e,t,s]),zm(()=>{l.current="",m.current!==null&&window.clearTimeout(m.current),m.current=null,br(t)},[t])}import{useCallback as Wm,useState as jm}from"react";function bl(e){return`${e}:model`}function Ym(e){if(typeof window>"u")return;let t=bl(e);try{let n=window.localStorage.getItem(t);if(n===null)return;let r=ya(n);if(ba(r))return r!==n&&window.localStorage.setItem(t,r),r;window.localStorage.removeItem(t)}catch{}}function vl(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(bl(e),t)}catch{}}function _s(e,t,n){let[r,o]=jm(()=>n?(vl(e,n),n):Ym(e)),s=r??t??va,i=Wm(p=>{o(p),vl(e,p)},[e]);return{selectedModelId:s,setSelectedModelId:i}}var Sl="The recording could not be transcribed. Try again.",Cl="No speech was detected. Try again when you are ready.",Xm="Voice transcription took too long. Try again.",Jm=3e4;function Zm(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()},Jm);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 tg(e,t){return{Authorization:`Bearer ${e}`,"Content-Type":t,"X-HeroUI-Agent-Protocol-Version":String(6),"X-HeroUI-Agent-SDK-Version":je}}function ng(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?Cl:e===429?"Voice dictation is busy. Wait a moment and try again.":Sl}async function Al({apiBaseUrl:e,audio:t,conversationId:n,language:r,signal:o,tokenManager:s}){let i=new URL(`${e}/v1/conversations/${encodeURIComponent(n)}/transcriptions`),p=Zm(o);r?.trim()&&i.searchParams.set("language",r.trim());try{for(let c=0;c<2;c+=1){let l=await eg(s.get(),p.signal),m=await fetch(i,{body:t,headers:tg(l,t.type||"audio/webm"),method:"POST",signal:p.signal});if(m.status===401&&c===0){s.clear();continue}if(!m.ok)throw new Error(ng(m.status));let u=await m.json().catch(()=>null),C=typeof u?.text=="string"?u.text.trim():"";if(!C)throw new Error(Cl);return C}}catch(c){throw p.didTimeOut()&&!o.aborted?new Error(Xm,{cause:c}):c}finally{p.dispose()}throw new Error(Sl)}import{Fragment as rn,jsx as E,jsxs as Ee}from"react/jsx-runtime";var wl=Zt();async function gg(e){try{let t=await e;if(!t.ok)return null;let n=Ir.safeParse(await t.json());return n.success?n.data:null}catch{return null}}function ks(e){return e.type==="dynamic-tool"&&e.toolName?e.toolName:e.type.startsWith("tool-")?e.type.slice(5):null}function fg({composerControlsRevealed:e,conversationEpoch:t,identityEpoch:n,identityReset:r,onClose:o,onComposerControlsReveal:s,onNewConversation:i,onReady:p,onSelectConversation:c,onUnreadChange:l,open:m,options:u,requestedConversationId:C,shellComposerEndSlot:d,shellComposerFooterSlot:w,showReadyLoader:k,tokenManager:M}){let[P,$]=J(null),[N,I]=J({}),O=ce(N),F=ce(P),[ee,y]=J(null),[f,h]=J([]),[A,b]=J(cs),T=ce(A),[S,x]=J({}),[Q,X]=J(0),j=P?N[P]??null:null;Tt(()=>{O.current=N,F.current=P},[P,N]);let U=G(R=>{I(H=>({...H,[R.conversationId]:R})),$(R.conversationId)},[]),q=G(R=>{I(H=>{let B=H[R];return B?.runtime?{...H,[R]:{...B,composerReady:!1,runtime:null}}:H}),F.current===R&&X(H=>H+1)},[]),pe=G(R=>{let H=T.current,B=R(H);B!==H&&(T.current=B,b(B),l(B.completedIds.size>0))},[l]),ge=G((R,H)=>{pe(B=>qi(B,{...H,activeConversationId:m?F.current:null,conversationId:R}))},[pe,m]);ye(()=>{!m||!P||pe(R=>ls(R,P))},[P,pe,m]);let L=G(R=>{pe(H=>ls(H,R)),c(R)},[pe,c]),V=G(()=>{F.current=null,$(null),y(null),i()},[i]),D=G((R,H)=>{x(B=>{let Y=B[R]??wl,re=H(Y);return re===Y?B:{...B,[R]:re}})},[]),_=ce(null),W=ce(null),ne=u.apiBaseUrl,ae=u.agentId,he=Ut(p),qe=G((R,H)=>{let B=Wi({conversationEpoch:t,optimisticTarget:W.current,readyConversationId:R,readyEpoch:H,requestedConversationId:C});B&&(I(Y=>{let re=Y[B];return!re||re.composerReady?Y:{...Y,[B]:{...re,composerReady:!0}}}),$(B),p(H))},[t,p,C]),it=Ae(()=>{try{return Nt(gn(u.tools,u.permissionDefaultMode)),u.permissionShowPicker&&Nt(gn(u.tools,"ask")),null}catch(R){return R instanceof Error?R.message:"The client tools could not be loaded"}},[u.permissionDefaultMode,u.permissionShowPicker,u.tools]),ht=it?null:bi(u),Mn=Ut(R=>Ci(u,M,R)),Bt=Ut(R=>{ke(u,M,R,"embed_loaded")}),Ft=ce(n);Tt(()=>{if(Ft.current===n)return;Ft.current=n,_.current=null,W.current=null,O.current={},F.current=null,I({}),$(null),h([]);let R=cs();T.current=R,b(R),x({}),r?M.reset():M.clear()},[n,r,M]),Tt(()=>{if(C!==null||it)return;let R=Gi(W.current,t);W.current=R;let H=_.current;if(!H)return;let B=R.conversationId;localStorage.setItem(H.storageKey,B),y(null),h(Y=>{let re=Qn(Y,B,Ar([]),Date.now());return Pt(H.historyKey,re),re}),I(Y=>({...Y,[B]:{composerReady:!1,config:H.config,conversationId:B,historyKey:H.historyKey,readyEpoch:t,runtime:null,showStartScreenWhileConnecting:!0,storageKey:H.storageKey}})),$(B)},[it,t,C]),ye(()=>{let R=!1;if(it){y(it),$(null),he(t);return}let H=_.current;if(H){let Y=Fr({conversationEpoch:t,optimisticTarget:W.current,requestedConversationId:C,storedConversationId:localStorage.getItem(H.storageKey)}),re=Y?O.current[Y]:void 0;if(re?.runtime){y(null),I(be=>({...be,[re.conversationId]:{...re,readyEpoch:t}})),re.composerReady&&$(re.conversationId);return}}let B=Fr({conversationEpoch:t,optimisticTarget:W.current,requestedConversationId:C,storedConversationId:null});return y(null),$(B??(typeof C=="string"&&Ct(C)?C:null)),(async()=>{try{let Y=await M.subjectHash(),re=`heroui-agent:conversation:${ae}:${Y}`,be=`heroui-agent:history:${ae}:${Y}`,Oe=Fr({conversationEpoch:t,optimisticTarget:W.current,requestedConversationId:C,storedConversationId:localStorage.getItem(re)})??crypto.randomUUID();localStorage.setItem(re,Oe);let De=Do(be);R||h(De);let Ze=H?.config??Jc(ae),Mt=Ze?null:zn(M,`${ne}/v1/agents/${encodeURIComponent(ae)}/config`),Le=zn(M,`${ne}/v1/agents/${encodeURIComponent(ae)}/conversations`).catch(()=>null),En=await Mn(Oe),et=Ze??(Mt?await gg(Mt):null);if(!et||!En)throw new Error("The data assistant could not be loaded");Ze||Zc(ae,et);let Pn=De.find(Ie=>Ie.id===Oe),In=Qn(De,Oe,Pn?.title??Ar([]),Pn?.updatedAt??Date.now());if(In!==De&&Pt(be,In),!R){_.current={config:et,historyKey:be,storageKey:re},h(In);let Ie=O.current[Oe],xn={composerReady:!1,config:et,conversationId:Oe,historyKey:be,readyEpoch:t,runtime:En.runtime,showStartScreenWhileConnecting:Ie?.showStartScreenWhileConnecting??C===null,storageKey:re};U(xn)}Le.then(async Ie=>{if(!Ie?.ok)return;let xn=Cr((await Ie.json()).conversations);R||h(Nn=>{let le=Lo(Nn,xn);return Pt(be,le),le})}),Bt(Oe)}catch(Y){if(!R&&C===void 0&&yi(Y)){V();return}R||(y(Y instanceof Error?Y.message:"The data assistant could not be loaded"),he(t))}})(),()=>{R=!0}},[ne,U,ht,it,t,n,ae,C,Q,V,M]);let on=G((R,H,B)=>{let Y=_.current?.historyKey;Y&&h(re=>{let be=Qn(re,R,H,Date.now(),B);return Pt(Y,be),be})},[]),ve=G(R=>{I(H=>{let B=H[R];return B?.showStartScreenWhileConnecting?{...H,[R]:{...B,showStartScreenWhileConnecting:!1}}:H})},[]),Pe=G(async(R,H)=>{let B=async()=>{let re=await M.get(),be=new Headers(H.headers);for(let[De,Ze]of Object.entries(Hr(re)))be.set(De,Ze);let Oe=await fetch(`${ne}/v1/conversations/${encodeURIComponent(R)}`,{...H,headers:be});if(Oe.status===401){M.clear();let De=await M.get(),Ze=new Headers(H.headers);for(let[Mt,Le]of Object.entries(Hr(De)))Ze.set(Mt,Le);Oe=await fetch(`${ne}/v1/conversations/${encodeURIComponent(R)}`,{...H,headers:Ze})}return Oe},Y=await B();if(H.method==="DELETE"&&Y.status===409&&(Y=await ji({initialResponse:Y,request:B})),!Y.ok)throw new Error(H.method==="DELETE"?"The chat could not be deleted":"The chat could not be renamed")},[ne,M]),Me=G(async(R,H)=>{await Pe(R,{body:JSON.stringify({title:H}),headers:{"Content-Type":"application/json"},method:"PATCH"});let B=_.current?.historyKey;B&&h(Y=>{let re=Y.map(be=>be.id===R?{...be,title:H}:be);return Pt(B,re),re})},[Pe]),ct=G(async R=>{await Pe(R,{method:"DELETE"});let H=_.current;H&&(h(B=>{let Y=B.filter(re=>re.id!==R);return Pt(H.historyKey,Y),Y}),localStorage.removeItem(yr(H.storageKey,R)),localStorage.removeItem(wo(H.storageKey,R)),br(ko(H.storageKey,R)),fc(fs(H.storageKey,R)),I(B=>{if(!(R in B))return B;let Y={...B};return delete Y[R],Y}),pe(B=>zi(B,R)),x(B=>{if(!(R in B))return B;let Y={...B};return delete Y[R],Y}),P===R&&V())},[P,pe,Pe,V]),ze=Ae(()=>{let R=u.suggestedPrompts;return!R?.length&&!u.componentSurfaceVariant&&!u.surfaceVariant?N:Object.fromEntries(Object.entries(N).map(([H,B])=>[H,{...B,config:{...B.config,...R?.length?{suggestedPrompts:R}:{},...u.componentSurfaceVariant?{componentSurfaceVariant:u.componentSurfaceVariant}:{},...u.surfaceVariant?{surfaceVariant:u.surfaceVariant}:{}}}]))},[u.componentSurfaceVariant,u.suggestedPrompts,u.surfaceVariant,N]),yt=P?ze[P]?.config??null:null,Ce=ce(null);ye(()=>{!m||!j?.runtime||Ce.current===j.conversationId||(Ce.current=j.conversationId,ke(u,M,j.conversationId,"opened"))},[m,u,j,M]);let Rt=it??ee,wn=Ae(()=>Bo(f),[f]),to=f.find(R=>R.id===P)?.title??"New chat",sr=_.current?"Loading chat\u2026":"Loading assistant\u2026",sn=C===null&&(!j||j.showStartScreenWhileConnecting);return E(rn,{children:Ee(fa,{keepMounted:!0,agentId:u.agentId,shouldCloseOnInteractOutside:u.shouldCloseOnInteractOutside,defaultExpanded:u.panelExpanded,expandable:!k&&u.panelExpandable,expandedTitle:to,name:yt?.name??"Data assistant",open:m,showBetaBadge:u.showBetaBadge,viewMode:u.viewMode,actionsSlot:k?E(rn,{}):E(Yc,{isDisabled:sn,onPress:V}),expandedSidebarSlot:k?void 0:E(xs,{activeConversationId:P,busyConversationIds:A.busyIds,completedConversationIds:A.completedIds,groups:wn,isNewConversationDisabled:sn,variant:"sidebar",onDeleteConversation:ct,onNewConversation:V,onRenameConversation:Me,onSelectConversation:L}),historySlot:k?E(rn,{}):E(xs,{activeConversationId:P,busyConversationIds:A.busyIds,completedConversationIds:A.completedIds,groups:wn,onDeleteConversation:ct,onRenameConversation:Me,onSelectConversation:L}),onClose:o,onNewConversation:k?void 0:V,children:[Rt?E("div",{className:"ha-loading",role:"alert",children:Rt}):k?E(ga,{indicator:E(lg,{"aria-hidden":!0,color:"current",size:"md"})}):!j||!j.runtime||!yt?sn&&j?E(El,{composerControlsRevealed:e,loadingLabel:sr,options:u,route:j,onComposerControlsReveal:s},`pending-${t}`):E(Vr,{agentId:u.agentId,composerControlsAvailable:u.composerControlsAvailable,composerControlsRevealed:e,composerEndSlot:d,composerFooterSlot:w,greeting:u.greeting,loadingLabel:sr,placeholder:u.composerPlaceholder,showStartScreen:sn,subtitle:u.subtitle,suggestedPrompts:u.suggestedPrompts??[],composerStartSlot:E(Nl,{agentId:u.agentId,options:u}),onComposerControlsReveal:s},`pending-${t}`):null,E("div",{className:"ha-runtime-content",hidden:!!Rt||k,children:E(Zi,{activeConversationId:Rt?null:P,routes:ze,children:(R,H)=>E(ka,{componentVariant:R.config.componentSurfaceVariant,variant:R.config.surfaceVariant,children:R.runtime?E(pg,{fallback:H&&R.showStartScreenWhileConnecting?E(El,{composerControlsRevealed:e,loadingLabel:"Connecting chat\u2026",options:u,route:R,onComposerControlsReveal:s}):E(Vr,{agentId:u.agentId,composerControlsAvailable:u.composerControlsAvailable,composerControlsRevealed:e,greeting:u.greeting,loadingLabel:"Connecting chat\u2026",placeholder:u.composerPlaceholder,showStartScreen:!1,subtitle:u.subtitle,suggestedPrompts:u.suggestedPrompts??[],onComposerControlsReveal:s}),children:E(yg,{active:H,composerControlsRevealed:!!H&&e,config:R.config,conversationEpoch:R.readyEpoch,conversationId:R.conversationId,options:u,runtime:R.runtime,showStartScreenWhileHydrating:R.showStartScreenWhileConnecting,storageKey:R.storageKey,tokenManager:M,messageQueue:S[R.conversationId]??wl,onComposerControlsReveal:s,onConversationStatusChange:ge,onMessageQueueChange:D,onReady:qe,onRuntimeRevisionStale:q,onConversationStarted:B=>{ve(R.conversationId),on(R.conversationId,B)},onConversationTitled:B=>on(R.conversationId,B,{replaceTitle:!0})})}):null})})})]})})}function El({composerControlsRevealed:e,loadingLabel:t,onComposerControlsReveal:n,options:r,route:o}){return E(Vr,{showStartScreen:!0,agentId:r.agentId,composerControlsAvailable:r.composerControlsAvailable,composerControlsRevealed:e,composerStartSlot:E(Nl,{agentId:r.agentId,options:r}),greeting:r.greeting,loadingLabel:t,placeholder:r.composerPlaceholder,subtitle:r.subtitle,suggestedPrompts:r.suggestedPrompts??[],composerEndSlot:E(hg,{conversationId:o.conversationId,options:r,storageKey:o.storageKey}),composerFooterSlot:r.composerDisclaimer?E("p",{className:"ha-footnote",children:bo(r.composerDisclaimer)}):null,onComposerControlsReveal:n})}function Nl({agentId:e,options:t}){let n=ce(null),[r,o]=J(()=>Ao(e)),[s,i]=J(null),p=c=>{let l=bn(c,t.composerAttachmentContentTypes);o(l.files),i(l.error),Ra(e,l.files)};return t.composerAttachmentContentTypes.length===0?null:Ee(rn,{children:[E("input",{ref:n,multiple:!0,accept:t.composerAttachmentAccept,"aria-label":"Choose files to attach",className:"ha-file-input",type:"file",onChange:c=>{p(Array.from(c.currentTarget.files??[])),c.currentTarget.value=""}}),r.length>0?E(Io,{"aria-label":"Selected attachments",className:"ha-attachments",offset:1,size:24,children:r.map(c=>E(os,{file:c,onRemove:()=>p(r.filter(l=>l!==c))},`${c.name}-${c.size}-${c.lastModified}`))}):null,E("button",{"aria-label":"Attach files",className:"ha-attach",type:"button",onClick:()=>n.current?.click(),children:E(xl,{"aria-hidden":"true"})}),s?E("span",{className:"ha-dictation-error",role:"alert",children:s}):null]})}function hg({conversationId:e,options:t,storageKey:n}){let r=yr(n,e),[o]=J(()=>Co(t.agentId)),[s]=J(()=>Mo(t.agentId)),[i,p]=J(()=>{let u=s??vr(r)??t.permissionDefaultMode;return s&&mn(r,s),u}),{selectedModelId:c,setSelectedModelId:l}=_s(n,t.composerDefaultModel,o),m=u=>{p(u),mn(r,u)};return Ee(rn,{children:[t.permissionShowPicker&&t.tools.length>0?E(Ro,{"aria-label":"Tool permissions",className:"ha-permission-picker",value:i,onChange:m}):null,t.composerModelPicker?E(To,{"aria-label":"AI model",className:"ha-model-picker",options:So,placement:t.permissionShowPicker&&t.tools.length>0?"top":"top start",value:c,onChange:l}):null,t.composerDictation?Ee("button",{disabled:!0,"aria-label":"Dictate message",className:"ha-dictation",type:"button",children:[E(Il,{"aria-hidden":"true"}),E(Vn,{children:"Dictate message"})]}):null]})}function yg({active:e,composerControlsRevealed:t,config:n,conversationEpoch:r,conversationId:o,messageQueue:s,onComposerControlsReveal:i,onConversationStarted:p,onConversationStatusChange:c,onConversationTitled:l,onMessageQueueChange:m,onReady:u,onRuntimeRevisionStale:C,options:d,runtime:w,showStartScreenWhileHydrating:k,storageKey:M,tokenManager:P}){let[$]=J(()=>Co(d.agentId)),[N]=J(()=>Mo(d.agentId)),{selectedModelId:I,setSelectedModelId:O}=_s(M,d.composerDefaultModel,$),F=wo(M,o),ee=yr(M,o),y=d.composerAttachmentAccept,f=Ae(()=>({key:y}),[y]),[h,A]=J(()=>({files:bn(Ao(d.agentId),d.composerAttachmentContentTypes).files,policy:f})),[b,T]=J(()=>({error:null,policy:f})),S=Ae(()=>h.policy===f?h.files:[],[f,h]),x=b.policy===f?b.error:null,Q=G(a=>{A(g=>{let v=g.policy===f?g.files:[],K=typeof a=="function"?a(v):a;return{files:bn(K,d.composerAttachmentContentTypes).files,policy:f}})},[f,d.composerAttachmentContentTypes]),X=G(a=>T({error:a,policy:f}),[f]),[j,U]=J(()=>{let a=d.permissionShowPicker?vr(F):void 0;return a?{modelId:void 0,permissionMode:a}:void 0}),[q,pe]=J({}),[ge,L]=J({}),[V,D]=J(!1),[_]=J(()=>Sa(d.agentId)),[W,ne]=J(()=>_?.submitted?"":_?.prompt??""),[ae,he]=J(()=>_?.submitted?{files:S,id:_.messageId,text:_.prompt}:null),[qe,it]=J(()=>{let a=d.permissionShowPicker?vr(ee):void 0;return N&&mn(ee,N),{configuredDefaultMode:d.permissionDefaultMode,selectedMode:N??a??d.permissionDefaultMode}}),[ht,Mn]=J(!1),[Bt,Ft]=J(!0),[on,ve]=J(!1),[Pe,Me]=J(!1),[ct,ze]=J(()=>new Set),[yt,Ce]=J(null),[Rt,wn]=J(0),[to,sr]=J(0),[sn,R]=J(!1),[H,B]=J(!1),[Y,re]=J(null),[be,Oe]=J({}),De=G(a=>{d.permissionShowPicker?mn(F,a.permissionMode):Eo(F),U(a)},[F,d.permissionShowPicker]),Ze=qe.configuredDefaultMode===d.permissionDefaultMode?qe.selectedMode:d.permissionDefaultMode,Mt=G(a=>{mn(ee,a),it({configuredDefaultMode:d.permissionDefaultMode,selectedMode:a})},[d.permissionDefaultMode,ee]),Le=d.permissionShowPicker?Ze:d.permissionDefaultMode,En=d.permissionShowPicker?j?.permissionMode??Le:d.permissionDefaultMode,et=Ae(()=>gn(d.tools,En),[En,d.tools]),Pn=Ae(()=>Nt(et),[et]),In=Ae(()=>xi(Pn),[Pn]),Ie=Ae(()=>new Map(et.map(a=>[a.name,a])),[et]),xn=Ae(()=>new Set(et.map(a=>a.name)),[et]),Nn=ce(new Set),le=ce(null),_n=ce(new Set),Os=ce(!1),He=ce(s),no=ce(null),tt=ce(!1),Ue=ce(!1),Vt=ce(null),ar=ce(0),lt=ce(0),wt=ce(null),$t=ce(null),ir=ce(null),ro=ce(new Set),oo=ce(new Map),kn=ce(()=>{}),Ds=ce(null),Ls=ce(null),ut=ce(null),we=Ae(()=>cl({report:({latencyMs:a,messageId:g,metric:v})=>{ke(d,P,o,v,{latencyMs:a,latencyOrigin:"user_submit",messageId:g})}}),[o,d,P]),_l=Ae(()=>ko(M,o),[o,M]),On=Ae(()=>fs(M,o),[o,M]),Hs=yl({attachments:S,draftKey:_l,input:W,setAttachments:Q,setInput:ne}),kl=G((a,{language:g,signal:v})=>Al({apiBaseUrl:d.apiBaseUrl,audio:a,conversationId:o,...g?{language:g}:{},signal:v,tokenManager:P}),[o,d.apiBaseUrl,P]),{cancel:Ge,elapsedSeconds:so,error:ao,isActive:_e,isRecording:Ol,isSupported:Qt,isTranscribing:Dn,start:Us,stop:Bs,stream:Dl}=qo({onValueChange:ne,transcribe:kl,value:W}),io=t||V||_e||S.length>0||x!==null||ao!==null,Fs=G(()=>{d.composerControlsAvailable&&i()},[i,d.composerControlsAvailable]),Ll=a=>{$n(d.agentId,!0,a.currentTarget),Fs()},Hl=a=>{let g=a.currentTarget.querySelector(".ha-composer");g&&Ta(g,a.relatedTarget)||$n(d.agentId,!1)};ye(()=>{He.current=s},[s]),ye(()=>{d.composerDictation||Ge()},[Ge,d.composerDictation]),ye(()=>{e||Ge()},[e,Ge]);let an=d.composerModelPicker?I:d.composerDefaultModel,cn=G(a=>{He.current=a,m(o,()=>a)},[o,m]),nt=G(async(a,{applyAfterPersist:g=!1}={})=>{let v=He.current,K=a(v);if(K!==v){g?He.current=K:cn(K);try{await hs(On,K)}catch(ie){throw He.current===K&&(g?He.current=v:cn(v)),ie}g&&He.current===K&&cn(K)}},[cn,On]),We=G(a=>{nt(a).catch(()=>{})},[nt]),Ul=G(a=>{_n.current.add(a),nt(g=>Xn(An(g,a,"admitted"),a)).catch(()=>{})},[nt]);ye(()=>{let a=!1;return Ft(!0),gc(On).then(async g=>{if(a)return;let v=hc(g,He.current),K=_n.current,ie={...v,messages:v.messages.filter(me=>!K.has(me.id))};cn(ie),await hs(On,ie)}).catch(()=>{}).finally(()=>{a||Ft(!1)}),()=>{a=!0}},[cn,On]);let cr=G(()=>{tt.current=!1,Ue.current=!1,wt.current=null,B(!1)},[]),Vs=G(a=>{nn({attempt:a,currentAttempt:lt.current,manualStopRequested:tt.current,stalledStopRequested:Ue.current})&&Me(!1)},[]),{agent:Kt,connectionEpoch:lr,connectionError:dt,isHydrating:Bl,isReconnecting:$s,retryConnection:Fl}=Sg({conversationId:o,onRuntimeRevisionStale:C,onTurnAdmitted:Ul,options:d,runtime:w,tokenManager:P}),Vl=Ut(u);Tt(()=>{Vl(o,r)},[e,r,o]),ye(()=>{if(Bt||lr===0)return;let a=[];for(let K of He.current.messages)ft(K)==="sending"&&a.push(K.id);if(a.length===0){ve(!1);return}let g=!1,v;return ve(!0),(async()=>{let K=[];for(let ue=0;ue<a.length;ue+=50)K.push(a.slice(ue,ue+50));let ie=async ue=>{let st=await Promise.all(K.map(async pt=>({response:await Kt.call(La,[{protocolVersion:6,turnIds:pt}],{timeout:15e3}),turnIds:new Set(pt)}))),Fe=new Set;for(let{response:pt,turnIds:ho}of st){if(pt.protocolVersion!==6||!Array.isArray(pt.turns))throw new Error("Invalid turn admission status response");for(let pn of pt.turns)pn.status==="admitted"&&ho.has(pn.turnId)&&Fe.add(pn.turnId)}return Fe.size===a.length||ue>=4?Fe:(await new Promise(pt=>window.setTimeout(pt,500)),ie(ue+1))},me;try{me=await ie(0)}catch{g||(v=window.setTimeout(()=>sr(ue=>ue+1),1e3));return}if(!g){for(let ue of me)_n.current.add(ue);await nt(ue=>yc(ue,me))}})().catch(()=>{}).finally(()=>{g||ve(!1)}),()=>{g=!0,v!==void 0&&window.clearTimeout(v)}},[Kt,nt,lr,Bt,to]);let $l=Ae(()=>new Proxy(Kt,{get(a,g){if(g==="send")return K=>a.send(Ni(K));let v=Reflect.get(a,g,a);return typeof v=="function"?v.bind(a):v}}),[Kt]),z=sg({agent:$l,cancelOnClientAbort:!1,experimental_throttle:60,getInitialMessages:null,onData:a=>{if(a.type!=="data-conversation-title"){let g=we.getActiveMessageId();g&&ro.current.add(g)}if(a.type==="data-progress"&&a.data&&typeof a.data=="object"&&"label"in a.data&&typeof a.data.label=="string"&&Ce(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()&&l(a.data.title.trim()),a.type==="data-component"){let g=a.data&&typeof a.data=="object"&&"kind"in a.data?a.data:null;ke(d,P,o,"component_rendered",{componentType:g?.kind})}a.type==="data-runtime-timing"&&el(d.agentId,o,a.data)},onError:a=>{if(tt.current||Ue.current){wt.current=null,Me(!1),Ce(null),queueMicrotask(()=>kn.current());return}wt.current=a,Me(!1),Ce(null),ke(d,P,o,"failure",{messageId:we.getActiveMessageId()??void 0,source:"cloudflare-chat"})},onFinish:({isError:a})=>{if(tt.current||Ue.current){wt.current=null,Me(!1),Ce(null),queueMicrotask(()=>kn.current());return}a&&!wt.current&&(wt.current=new Error("The request could not be completed")),Me(!1),Ce(null)},resume:!0,syncMessagesToServer:!1,tools:In}),{clearError:Qs,setMessages:Ks}=z;Tt(()=>{kn.current=Qs},[Qs]);let vt=z.status==="submitted"||z.status==="streaming"||z.isStreaming,Et=sn||H,Ln=!Et&&z.isToolContinuation,co=!!(Et||z.error||z.connectionError||dt),qt=Ae(()=>!co&&(ct.size>0||ll({isPendingPart:a=>{let g=a,v=ks(g);return Mc({isClientTool:!!(v&&Ie.has(v)),state:g.state})},messages:z.messages,terminal:co})),[z.messages,Ie,co,ct]),Be=dl({hasPendingClientToolCalls:qt,isAutoContinuationPending:Ln,isRecovering:z.isRecovering,isRunning:vt,localPending:Pe,stalled:H});ye(()=>{if(Be)return;let a=we.getActiveMessageId();a&&(we.complete(a),ro.current.delete(a),oo.current.delete(a))},[Be,we]);let zt=!dt&&(Bl||$s||Bt||on),lo=zt||Be,uo=Et||!!z.error||!!z.connectionError||!!dt,bt=lo||uo,qs=bc({hasChatError:!!(z.error||z.connectionError||dt),hasPendingClientToolCalls:qt,hasReadyClientToolContinuation:Ln,isLocalPending:Pe,isResuming:zt,isRunning:vt,recoveryError:Et}),zs=Ut(c);ye(()=>{j&&!vt&&!qt&&!Pe&&!zt&&!Ln&&(Eo(F),U(void 0))},[j,F,qt,Ln,zt,vt,Pe]),ye(()=>{zs(o,{busy:lo,failed:uo,turnActive:Be})},[uo,o,Be,lo]),ye(()=>()=>{zs(o,{busy:!1,failed:!0,turnActive:!1})},[o]);let St=z.messages.at(-1),Gs=vt&&St?.role==="assistant"?St.id:null,Ql=St?.role==="assistant"&&(qt||Ln||z.isRecovering)?St.id:null,Gt=Xi({continuingAssistantMessageId:Ql,isActiveTurn:Be,streamingAssistantMessageId:Gs,trackedActivityMessageId:$t.current}),po=Gt===St?.id?St:void 0,Ws=!!(po&&Wo(po,Ie,{isStreaming:!0}).length>0),Kl=Ns(po).hasServerContent;ye(()=>{if(Be&&Gt){if($t.current===Gt)return;let v=ir.current??Date.now();$t.current=Gt,pe(K=>({...K,[Gt]:{startedAt:v}}));return}let a=$t.current;if(Be||!a)return;let g=Date.now();pe(v=>{let K=v[a];return!K||K.completedAt?v:{...v,[a]:{...K,completedAt:g}}}),$t.current=null,ir.current=null},[Gt,Be]);let ur=G(async(a,g,v)=>{z.addToolOutput({output:v,toolCallId:g,toolName:a})},[z.addToolOutput]),mo=G((a,g)=>{ze(v=>{if(v.has(a)===g)return v;let K=new Set(v);return g?K.add(a):K.delete(a),K})},[]),dr=G(async(a,g)=>{await Mi({activeToolCallIds:Nn.current,run:async()=>{mo(g.toolCallId,!0),Ce("Fetching live data\u2026");try{await Pi({conversationId:o,execute:v=>Ei({context:d.context,execution:v,input:g.input,tool:a}),input:g.input,rpc:{claim:v=>Kt.call("claimClientToolEffect",[v],{timeout:ts}),complete:v=>Kt.call("completeClientToolEffect",[v],{timeout:ts})},submitOutput:v=>ur(a.name,g.toolCallId,v),toolCallId:g.toolCallId,toolName:a.name}),Ce("Analyzing the results\u2026")}finally{mo(g.toolCallId,!1)}},toolCallId:g.toolCallId})},[Kt,o,d.context,mo,ur]),ql=G((a,g,v)=>{let K=g.toolCallId;if(Oe(ie=>({...ie,[K]:v?"approved":"rejected"})),Ce(v?"Applying your change\u2026":"Updating your request\u2026"),ke(d,P,o,v?"action_approved":"action_declined"),g.approval?.id)z.addToolApprovalResponse({approved:v,id:g.approval.id});else if(!v)ur(a,K,{reason:"The user declined this tool call",rejected:!0});else{Oe(ie=>({...ie,[K]:"rejected"}));return}if(v){let ie=Ie.get(a);ie&&dr(ie,g).catch(()=>{})}else Nn.current.add(K)},[z.addToolApprovalResponse,Ie,o,dr,d,ur,P]);ye(()=>{for(let a of z.messages)if(a.role==="assistant")for(let g of a.parts){let v=ks(g);if(!v)continue;let K=Ie.get(v);!K||Nn.current.has(g.toolCallId)||wi({approvalApproved:g.approval?.approved,decision:be[g.toolCallId],needsApproval:K.needsApproval===!0,state:g.state})&&dr(K,g).catch(()=>{})}},[z.messages,Ie,lr,dr,be]);let Hn=G(a=>{D(Ea(a,{hasAttachments:io&&S.length>0}))},[S.length,io]);Tt(()=>{Hn(ut.current)},[W,_e,Hn]),Tt(()=>Pa(ut.current,Hn),[Hn]);let js=G(a=>{if(a.length===0)return;let g=bn([...S,...a],d.composerAttachmentContentTypes);X(g.error),Q(g.files)},[S,d.composerAttachmentContentTypes,X,Q]),Ys=G(()=>{Ge(),Hs(),ne(""),Q([]),X(null),re(null)},[Ge,Hs,X,Q]),zl=G(()=>ut.current?.focus(),[]),go=G(()=>{if(Dn){Ge(),requestAnimationFrame(()=>ut.current?.focus());return}if(_e){Bs(),requestAnimationFrame(()=>ut.current?.focus());return}Us()},[Ge,_e,Dn,Us,Bs]);ye(()=>{if(!e||!d.composerDictation||!Qt)return;let a=g=>{Qi(g)&&(g.preventDefault(),ut.current?.focus({preventScroll:!0}),go())};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e,Qt,d.composerDictation,go]),Tt(()=>{e&&Aa(d.agentId,ut.current)},[e,d.agentId]);let Xs=G(async a=>{let g=++lt.current,v=z.messages,K=v.findLast(Fe=>Fe.role==="user")?.id,ie=v.findLast(Fe=>Fe.role==="assistant")?.id,me=d.permissionShowPicker?a.permissionMode??Le:d.permissionDefaultMode,ue=Nt(gn(d.tools,me));De({modelId:a.modelId,permissionMode:me}),$t.current=null,oo.current.set(a.id,ie),we.activate(a.id);let st=we.getStartedAtWallClock(a.id)??Date.now();ir.current=st,cr(),no.current={previousUserMessageId:K??null,scrollKey:crypto.randomUUID()},Me(!0),R(!1),B(!1),Ce(Kn("accepted")),p(Ho(a.text,a.files));try{let Fe=await Pl(d,a.selection);if(!nn({attempt:g,currentAttempt:lt.current,manualStopRequested:tt.current,stalledStopRequested:Ue.current}))return;a.files.length>0&&Ce("Uploading attachments\u2026");let pt=await Ri({acceptedContentTypes:d.composerAttachmentContentTypes,apiBaseUrl:d.apiBaseUrl,conversationId:o,files:a.files,tokenManager:P});if(!nn({attempt:g,currentAttempt:lt.current,manualStopRequested:tt.current,stalledStopRequested:Ue.current}))return;ke(d,P,o,"message_sent",{messageId:a.id});let ho=ns({clientSubmittedAt:st,clientTools:ue,generateConversationTitle:a.generateConversationTitle,imageSearch:d.imageSearch,modelId:a.modelId,newsSearch:d.newsSearch,pageContext:Fe,permissionMode:me,turnId:a.id,webSearch:d.webSearch});Ce(Kn("accepted")),await z.sendMessage(Sc(a,pt),{body:ho});let pn=wt.current;if(pn)throw wt.current=null,pn}catch(Fe){if(!nn({attempt:g,currentAttempt:lt.current,manualStopRequested:tt.current,stalledStopRequested:Ue.current}))return;throw Fe instanceof Error&&X(Fe.message),Ks(v),z.clearError(),R(!1),B(!1),Me(!1),Ce(null),Fe}},[z,De,Le,o,p,d,cr,X,Ks,P,we]),Un=G((a,{resumeDrainAfter:g=!0}={})=>{le.current=a.id,Xs(a).catch(()=>{le.current===a.id&&(le.current=null),_n.current.has(a.id)||We(v=>gt(An(gs(v,{...a,deliveryStatus:"pending"},"prepend"),a.id,"pending"),a.id))}).finally(()=>{le.current===a.id&&(le.current=null),g&&wn(v=>v+1)})},[Xs,We]),Wt=G((a,g,v=g?.generateConversationTitle??!0)=>{let K=a.trim();if(!K&&S.length===0)return;let ie=!bt&&!le.current&&He.current.messages.length===0,me=Ac({activeMessageId:le.current,authoritativeMessageCount:z.messages.length,isNewChatStartScreen:k,queuedMessageCount:He.current.messages.length}),ue={files:S,...me&&!v?{generateConversationTitle:!1}:{},id:g?.messageId??crypto.randomUUID(),...me?{isInitialTurn:!0}:{},...an?{modelId:an}:{},permissionMode:Le,selection:Y,text:K};ie&&(ue.deliveryStatus="sending"),me&&he({files:ue.files,id:ue.id,text:ue.text}),we.begin(ue.id,g),g?.firstFeedbackPaintedAt!==void 0&&we.markPaintedAt(ue.id,"first_feedback_paint",g.firstFeedbackPaintedAt),ie&&(le.current=ue.id),nt(st=>Jn(gs(st,ue),!1),{applyAfterPersist:!0}).then(()=>{Ys(),ie?Un(ue):wn(st=>st+1)}).catch(st=>{ie&&(le.current=null),me&&he(null),g&&ne(K),X(st instanceof Error?st.message:"This message could not be saved before sending")})},[S,an,Le,nt,z.messages.length,bt,Ys,Y,Un,X,k,we]),ln=n.suggestedPrompts,Gl=Ut(a=>Wt(a.prompt,a));ye(()=>{if(!e)return;Ma(d.agentId);let a=Ca(d.agentId);a&&(a.submitted?Gl(a):ne(g=>g||a.prompt))},[e,d.agentId]),ye(()=>{if(!e||!d.suggestedPromptShortcuts||z.messages.length>0||ln.length===0)return;let a=g=>{let v=Ki(g,ln.length);if(v===null)return;let K=ln[v];K&&(g.preventDefault(),Wt(K,void 0,!1))};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e,z.messages.length,d.suggestedPromptShortcuts,Wt,ln]);let Js=a=>{a.preventDefault(),Wt(W)},Wl=Ut(async a=>{try{await nt(g=>An(g,a.id,"sending"))}catch(g){le.current===a.id&&(le.current=null),X(g instanceof Error?g.message:"This message could not be saved before sending"),We(v=>gt(v,a.id));return}le.current===a.id&&Un({...a,deliveryStatus:"sending"})}),jl=G(a=>{Os.current=a,Mn(a)},[]);ye(()=>{let a=wc({activeMessageId:le.current,isBusy:bt,isReordering:ht,queue:s});a&&(le.current=a.id,queueMicrotask(()=>{if(Os.current){le.current===a.id&&(le.current=null);return}le.current===a.id&&Wl(a)}))},[bt,ht,s,Rt]);let Yl=G(a=>{he(g=>g?.id===a?null:g),We(g=>Xn(g,a))},[We]),Xl=G((a,g,v)=>{We(K=>pc(gt(K,null),a,g,v))},[We]),Jl=G(a=>{let g=He.current.messages.find(v=>v.id===a);g&&(Ge(),ne(g.text),Q(g.files),g.modelId&&O(g.modelId),g.permissionMode&&Mt(g.permissionMode),re(g.selection),D(!0),he(v=>v?.id===a?null:v),We(v=>Xn(gt(v,null),a)),requestAnimationFrame(()=>ut.current?.focus()))},[Ge,Q,We,Mt,O]),Zl=G(a=>{if(bt||le.current)return;let g=He.current.messages.find(v=>v.id===a);g&&(le.current=g.id,nt(v=>Jn(An(gt(v,null),a,"sending"),!0)).then(()=>{le.current===g.id&&Un({...g,deliveryStatus:"sending"},{resumeDrainAfter:!1})}).catch(v=>{le.current===g.id&&(le.current=null),X(v instanceof Error?v.message:"This message could not be saved before sending")}))},[nt,bt,Un,X]),Zs=G(()=>{let a=le.current;ar.current+=1,lt.current+=1,tt.current=!0,Ue.current=!1,le.current=null,he(null),We(v=>Jn(a&&!_n.current.has(a)?An(gt(v,null),a,"pending"):gt(v,null),!0)),Me(!1),Ce(null),R(!1),B(!1),ke(d,P,o,"stopped");let g=Promise.resolve().then(()=>z.stop()).catch(()=>{}).finally(()=>{Vt.current===g&&(Vt.current=null),kn.current()});Vt.current=g},[z,o,d,We,P]),eu=Ut(()=>{if(tt.current||Ue.current)return;let a=le.current;ar.current+=1,lt.current+=1,Ue.current=!0,le.current=null,We(v=>Jn(a?Xn(gt(v,null),a):gt(v,null),!0)),Me(!1),Ce(null),R(!1),B(!0),ke(d,P,o,"turn_stalled",{messageId:a??void 0,source:"client-inactivity-watchdog"});let g=Promise.resolve().then(()=>z.stop()).catch(()=>{}).finally(()=>{Vt.current===g&&(Vt.current=null),kn.current(),Ue.current&&B(!0)});Vt.current=g});ye(()=>{if(pl({hasActiveTurn:Be,hasPendingClientToolCalls:qt,isResuming:zt,stalled:H}))return ml(eu)},[z.isRecovering,z.messages,z.status,lr,Be,qt,zt,Pe,yt,H]);let tu=G(a=>{if(ke(d,P,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=ma(Ie,a.toolName);if(g){(async()=>{try{let v=hr(g,a.args),K=`component-action-${crypto.randomUUID()}`;await g.execute(v,d.context,{conversationId:o,idempotencyKey:`heroui-agent-component-action:${o}:${K}`,toolCallId:K})}catch{}})();return}}Li(a,{fillComposer:g=>{Ge(),ne(g),D(!0),requestAnimationFrame(()=>ut.current?.focus())},setSelection:re,submitPrompt:Wt})},[Ge,Ie,o,d,Wt,P]),nu=G(a=>{let g=a.parts.filter(v=>v.type==="text").map(v=>v.text).join(`
|
|
4
|
+
|
|
5
|
+
`).trim();g&&(navigator.clipboard?.writeText(g).catch(()=>{}),ke(d,P,o,"message_copied",{messageId:a.id}))},[o,d,P]),ru=G((a,g,v)=>{let K=ge[a]===g&&!v;if(L(ie=>{let me={...ie};return K?delete me[a]:me[a]=g,me}),!K){let ie=v?.comment,me=v?.reasons??[];ke(d,P,o,g==="up"?"feedback_up":"feedback_down",{feedbackCommentLength:ie?.length??0,feedbackReasons:me,hasFeedbackComment:!!ie,messageId:a});try{Promise.resolve(d.onFeedback?.({...ie?{comment:ie}:{},conversationId:o,messageId:a,rating:g==="up"?"positive":"negative",reasons:me})).catch(()=>{})}catch{}}},[o,ge,d,P]),ea=G(()=>{let a=++ar.current;(async()=>{let g=Vt.current;if(!await ul(g,()=>ar.current===a))return;let v=++lt.current,K=Nt(gn(d.tools,Le)),ie=crypto.randomUUID(),me=Date.now();$t.current=null,ir.current=me,De({modelId:an,permissionMode:Le}),cr(),no.current=null,Me(!0),R(!1),B(!1),Ce(Kn("accepted")),ke(d,P,o,"retry");try{let ue=await Pl(d,Y);if(!nn({attempt:v,currentAttempt:lt.current,manualStopRequested:tt.current,stalledStopRequested:Ue.current}))return;await z.regenerate({body:ns({clientSubmittedAt:me,clientTools:K,imageSearch:d.imageSearch,modelId:an,newsSearch:d.newsSearch,pageContext:ue,permissionMode:Le,turnId:ie,webSearch:d.webSearch})})}catch{if(!nn({attempt:v,currentAttempt:lt.current,manualStopRequested:tt.current,stalledStopRequested:Ue.current}))return;R(!0)}finally{Vs(v)}})()},[De,z,an,Le,Vs,o,d,cr,Y,P]),ou=z.messages.findLast(a=>a.role==="assistant")?.id,rt=Tc({authoritativeMessageCount:z.messages.length,localTurn:ae,queue:s}),un=Ae(()=>rt?{id:rt.id,parts:[{text:Cc(rt),type:"text"}],role:"user"}:null,[rt]),Bn=Ae(()=>un?[un,...z.messages]:z.messages,[z.messages,un]),su=un!==null,pr=!!(rt&&!s.isPaused&&s.blockedMessageId!==rt.id),ta=!!(z.error||z.connectionError||Et||dt),na=Bn.findLast(a=>a.role==="user")?.id,{activeStreamKey:mr,activeTurnMessageId:ra}=ec({isActive:Be||pr,lastUserMessageId:na,pendingTurn:un&&pr?{previousUserMessageId:null,scrollKey:un.id}:no.current}),oa=Za({clientToolNames:xn,isLocalPending:Pe,isRecovering:z.isRecovering||$s,isStreaming:vt,messages:z.messages,status:z.status}),{showHome:sa,standaloneStatus:au}=Ji({hasActiveActivity:Ws,hasError:ta,hasResponseStarted:Kl,isActiveTurn:Be||pr,messageCount:Bn.length,preferHomeWhileEmpty:k,progress:pr?Gn:yt??Kn(oa),runtimeStatus:zt?"pending":"ready"}),aa=Yi({activeStreamKey:mr,activeTurnMessageId:ra}),ia=sa||aa&&Bn.length===0,ot=we.getActiveMessageId(),iu=ot?oo.current.get(ot):void 0,ca=ot&&St?.role==="assistant"&&St.id!==iu?St:void 0,Fn=Ns(ca,{hasActivity:!!(ca&&Ws),hasTransientData:!!(ot&&ro.current.has(ot))}),fo=su&&ta?null:au,gr=!aa&&fo&&(e||fo!==Gn)?fo:null,la=!!gr;Tt(()=>{if(e){for(let a of s.messages)we.markAfterPaint(a.id,"first_feedback_paint");rt&&we.markAfterPaint(rt.id,"first_feedback_paint"),ot&&((la||Fn.hasServerContent||z.error||z.connectionError||Et||dt)&&we.markAfterPaint(ot,"first_feedback_paint"),Fn.hasServerContent&&we.markAfterPaint(ot,"first_server_content_paint"),Fn.hasText&&we.markAfterPaint(ot,"first_text_paint"))}},[e,ot,z.connectionError,z.error,la,s.messages,rt,Et,dt,Fn.hasServerContent,Fn.hasText,we]);let cu=Ae(()=>Rc(s,rt?.id??null),[s,rt?.id]),fr=!!(W.trim()||S.length>0),ua=Dn?"Cancel transcription":_e?"Stop dictation":"Dictate message",da=Qt?ua:"Voice dictation is not supported in this browser",dn=vt&&!fr?"Stop answering":bt&&!(k&&Bn.length===0)?"Queue message":"Send message";return Ee(rn,{children:[Ee(sc,{activityPhase:oa,streamKey:mr,children:[ia?Ee("div",{className:"ha-empty",children:[E("h2",{children:d.greeting}),E("p",{children:d.subtitle})]}):Bn.map(a=>E(vg,{actions:d.messageActions,activityTiming:q[a.id],canRetry:a.id===ou&&!bt,clientTools:Ie,exportFormats:d.componentExportFormats,feedback:ge[a.id]??null,isActivityActive:a.id===Gt,isStreaming:a.id===Gs,markdownAnimation:d.markdownAnimation,markdownCaret:d.markdownCaret,markdownPlugins:d.markdownPlugins,message:a,toolDecisions:be,turnAnchor:a.id===ra&&mr!==null?"active":a.id===na?"latest":null,onAction:tu,onClientToolDecision:ql,onCopy:nu,onFeedback:ru,onRetry:ea,onSelect:re},a.id)),gr?E("div",{className:"ha-message","data-role":"assistant","data-stream-anchor":"true","data-turn-feedback-id":ot??void 0,children:E("div",{className:"ha-message-body",children:gr===Gn?E(il,{},mr??o):E(Dr,{label:gr})})}):null,z.error||z.connectionError||Et||dt?Ee("div",{className:"ha-error",role:"alert",children:[E("span",{children:dt?"The assistant connection could not be restored.":H?"The assistant stopped responding. Please retry.":"The request could not be completed."}),E("button",{type:"button",onClick:dt?Fl:ea,children:"Retry"})]}):null]}),Ee("form",{className:"ha-composer-wrap",onBlur:Hl,onSubmit:Js,children:[sa&&ln.length>0?E("div",{"aria-label":"Suggested prompts",className:"ha-suggestions",role:"group",children:ln.map((a,g)=>Ee("button",{className:"ha-suggestion",type:"button","aria-keyshortcuts":d.suggestedPromptShortcuts?`Control+${g+1}`:void 0,onClick:()=>Wt(a,void 0,!1),children:[E("span",{children:a}),d.suggestedPromptShortcuts?Ee("span",{"aria-hidden":"true",className:"ha-suggestion-shortcut",children:[E("kbd",{children:"Ctrl"}),E("kbd",{children:g+1})]}):E(ig,{"aria-hidden":"true"})]},a))}):null,Y?E(Bi,{title:Y.componentTitle,onRemove:()=>re(null)}):null,ia?null:E(Ic,{ref:Ls,blockedMessageId:s.blockedMessageId,isSendNowDisabled:bt,messages:cu,onEdit:Jl,onFocusComposer:zl,onRemove:Yl,onReorder:Xl,onReorderStateChange:jl,onSendNow:Zl}),Ee(Fi,{className:"@container ha-composer","data-controls-revealed":io||void 0,"data-dictating":_e||void 0,"data-expanded":_e||V?!0:void 0,disabled:d.composerAttachmentContentTypes.length===0,onFilesSelected:js,onFileIntent:d.composerAttachmentContentTypes.length>0?Fs:void 0,children:[E("textarea",{ref:ut,"aria-label":"Message the assistant",placeholder:d.composerPlaceholder,readOnly:_e,rows:1,value:W,onFocus:Ll,onSelect:a=>$n(d.agentId,!0,a.currentTarget),onChange:a=>{ne(a.currentTarget.value),$n(d.agentId,!0,a.currentTarget),Hn(a.currentTarget)},onKeyDown:a=>{if(!_e&&!Ec(a,Ls.current)&&$i(a.nativeEvent)){if(a.preventDefault(),vt&&!fr){Zs();return}Js(a)}}}),d.composerAttachmentContentTypes.length>0?E("input",{ref:Ds,multiple:!0,accept:d.composerAttachmentAccept,"aria-label":"Choose files to attach",className:"ha-file-input",type:"file",onChange:a=>{let g=Array.from(a.currentTarget.files??[]);js(g),a.currentTarget.value=""}}):null,S.length>0?E(Io,{"aria-label":"Selected attachments",className:"ha-attachments",offset:1,size:24,children:S.map(a=>E(os,{file:a,onRemove:()=>{X(null),Q(g=>g.filter(v=>v!==a))}},`${a.name}-${a.size}-${a.lastModified}`))}):null,d.composerAttachmentContentTypes.length>0?E("button",{"aria-label":"Attach files",className:"ha-attach",type:"button",onClick:()=>Ds.current?.click(),children:E(xl,{"aria-hidden":"true"})}):null,_e?E("div",{className:"ha-dictation-session",children:Dn?E("span",{className:"ha-dictation-status",role:"status",children:"Transcribing\u2026"}):Ee(rn,{children:[E(Vo,{active:Ol,"aria-hidden":"true",className:"ha-dictation-waveform",height:28,stream:Dl}),E("time",{"aria-label":`Recording duration ${Pr(so)}`,className:"ha-dictation-duration",dateTime:`PT${so}S`,children:Pr(so)})]})}):null,d.permissionShowPicker&&d.tools.length>0&&!_e?E(Ro,{"aria-label":"Tool permissions",className:"ha-permission-picker",isDisabled:qs,value:Ze,onChange:Mt}):null,d.composerModelPicker&&!_e?E(To,{"aria-label":"AI model",className:"ha-model-picker",isDisabled:qs,options:So,value:I,placement:d.permissionShowPicker&&d.tools.length>0?"top":"top start",onChange:O}):null,d.composerDictation?Ee("button",{"aria-keyshortcuts":Qt?Vi:void 0,"aria-label":ua,"aria-pressed":_e,className:"ha-dictation","data-shortcut":Qt?"\u2303\u21E7D":void 0,"data-tooltip":da,disabled:!Qt,type:"button",onClick:go,children:[Dn?E(cg,{"aria-hidden":"true"}):_e?E(Ml,{"aria-hidden":"true"}):E(Il,{"aria-hidden":"true"}),E(Vn,{shortcut:Qt?"\u2303\u21E7D":void 0,children:da})]}):null,x||d.composerDictation&&ao?E("span",{className:"ha-dictation-error",role:"alert",children:x??ao}):null,vt&&!fr?Ee("button",{"aria-keyshortcuts":is,"aria-label":dn,className:"ha-send","data-shortcut":"\u21B5","data-tooltip":dn,type:"button",onClick:Zs,children:[E(Ml,{"aria-hidden":"true"}),E(Vn,{shortcut:"\u21B5",children:dn})]}):Ee("button",{"aria-keyshortcuts":is,"aria-label":dn,className:"ha-send","data-shortcut":"\u21B5","data-tooltip":dn,disabled:!fr||_e,type:"submit",children:[E(ag,{"aria-hidden":"true"}),E(Vn,{shortcut:"\u21B5",children:dn})]})]}),E("div",{className:"ha-composer-footer","data-revealed":!!d.composerDisclaimer||void 0,children:E("div",{className:"ha-composer-footer-content",children:d.composerDisclaimer?E("p",{className:"ha-footnote",children:bo(d.composerDisclaimer)}):null})}),E(Ia,{})]})]})}function vg({actions:e,activityTiming:t,canRetry:n,clientTools:r,exportFormats:o,feedback:s,isActivityActive:i,isStreaming:p,markdownAnimation:c,markdownCaret:l,markdownPlugins:m,message:u,onAction:C,onClientToolDecision:d,onCopy:w,onFeedback:k,onRetry:M,onSelect:P,toolDecisions:$,turnAnchor:N}){let I=Wo(u,r,{isStreaming:i}),O=Gc(u.parts),F=u.parts.some(rs);ye(()=>{F&&ac()},[F]);let ee=p?u.parts.findLastIndex(S=>S.type==="text"):-1,y=u.role==="user"?u.parts.flatMap((S,x)=>S.type==="file"?[E(ms,{file:S},`${u.id}-attachment-${x}`)]:[]):[],{items:f,latestContentPartIndex:h}=u.parts.reduce((S,x,Q)=>{let X=q=>({items:[...S.items,q],latestContentPartIndex:Q});if(x.type==="text")return x.text.trim()?X(u.role==="assistant"?E(kr,{animated:c,caret:l,isStreaming:Q===ee,plugins:m,children:x.text},`${u.id}-text-${Q}`):E("p",{className:"ha-message-text",children:x.text},`${u.id}-text-${Q}`)):S;if(x.type==="file")return u.role==="user"?S:X(E(ms,{file:x},`${u.id}-file-${Q}`));if(x.type==="data-component")return X(E(cc,{component:x.data,exportFormats:o,onAction:C,onSelect:P},x.data.id));if(rs(x))return S;let j=ks(x),U=j?r.get(j):void 0;if(j&&U){let q=x;return q.state!=="approval-requested"||$[q.toolCallId]?S:X(E(bg,{decision:$[q.toolCallId],part:q,tool:U,onDecision:pe=>d(j,q,pe)},q.toolCallId))}return S},{items:[],latestContentPartIndex:-1}),A=Ja(I,{hasContent:f.length>0,latestContentPartIndex:h}),b=Wc(O,{hasContent:f.length>0,isStreaming:i});if(f.length===0&&y.length===0&&I.length===0&&b.length===0)return null;if(u.role==="user")return Ee("div",{className:"ha-message","data-role":"user","data-stream-anchor":N==="active"?!0:void 0,"data-turn-anchor":N?!0:void 0,children:[y.length>0?E("div",{"aria-label":"Message attachments",className:"ha-message-attachments",children:y}):null,f.length>0?E("div",{className:"ha-bubble",children:E("div",{className:"ha-message-content",children:f})}):null]});let T=u.parts.some(S=>S.type==="text"&&S.text.trim().length>0);return E("div",{className:"ha-message","data-role":"assistant","data-stream-anchor":i?!0:void 0,children:Ee("div",{className:"ha-message-body",children:[I.length>0?E(ui,{completedAt:t?.completedAt,hasResponseStarted:A,isStreaming:i,items:I,markdownAnimation:c,markdownPlugins:m,startedAt:t?.startedAt}):null,f.length>0?E("div",{className:"ha-message-content",children:f}):null,E(zc,{sources:b}),!i&&f.length>0&&e.length>0?E(uc,{actions:e,feedback:s,onCopy:T?()=>w(u):void 0,onFeedback:(S,x)=>k(u.id,S,x),onRetry:n?M:void 0}):null]})})}function bg({decision:e,onDecision:t,part:n,tool:r}){if(n.state!=="approval-requested"||e)return null;let o=r.icon;return E(Va,{"data-tool-status":"approval-requested",icon:o?E(o,{color:r.iconColor,size:16}):void 0,input:n.input,title:r.displayName??r.name,onApprove:()=>t(!0),onDeny:()=>t(!1)})}function Sg({conversationId:e,onRuntimeRevisionStale:t,onTurnAdmitted:n,options:r,runtime:o,tokenManager:s}){let i=Ae(()=>ki(o),[o]),p=r.apiBaseUrl,c=Ae(()=>Oi(o,()=>Ai({apiBaseUrl:p},s,e,o.runtimeRevision)),[p,e,o,s]),[l,m]=J(0),[u,C]=J(0),[d,w]=J(null),[k,M]=J(!0),[P,$]=J(!1),N=ce(null),I=ce(!1),O=mg(),F=G(()=>{let T=new Error("The assistant connection could not be restored");N.current=T,I.current=!1,w(T),M(!1),$(!1)},[]),ee=G(async()=>{try{return{ticket:(await c.next()).ticket}}catch(T){return T instanceof vn?(t(e),new Promise(()=>{})):(F(),{ticket:""})}},[e,F,t,c]),y=G(()=>{N.current=null,w(null),m(T=>T+1),$(!1),I.current&&(I.current=!1,ke(r,s,e,"reconnected"))},[e,r,s]),f=G(T=>{if(!N.current){if(ug(T)){F();return}I.current=!0,M(!0),$(!0)}},[F]),h=G(T=>{let S=Di(T),x=typeof S?.type=="string"?S.type:null;x===Da&&S?.protocolVersion===6&&typeof S.turnId=="string"&&n(S.turnId),(x==="cf_agent_chat_messages"||x==="cf_agent_stream_resume_none"||x==="cf_agent_stream_resuming"||x==="cf_agent_stream_pending"||x==="cf_agent_use_chat_response")&&(N.current=null,w(null),M(!1))},[n]),A=dg({agent:"HeroUIConversationAgent",basePath:i.basePath,cacheTtl:3600*1e3,enabled:N.current===null,host:i.host,name:e,...i.path?{path:i.path}:{},onClose:f,onConnectionError:F,onIdentityChange:()=>{},onMessage:h,onOpen:y,protocol:i.protocol,query:ee,queryDeps:[e,o.runtimeRevision,O,u]});ye(()=>{if(!(d||!k&&!P))return gl(F)},[l,d,F,k,P]);let b=G(()=>{N.current=null,I.current=!0,w(null),M(!0),$(!0),C(T=>T+1)},[]);return ye(()=>{if(d)return;let T=!1,S=null,x,Q=j=>{T||(x=window.setTimeout(()=>void X(),j))},X=async()=>{let j;try{j=await c.refresh()}catch(U){if(U instanceof vn){t(e);return}if(U instanceof qn&&!U.retryable){F();return}if(S??=Date.now(),Date.now()-S>=12e4){F();return}Q(15e3);return}try{await A.call("renewConnection",[j.ticket],{timeout:15e3}),S=null,Q(27e4)}catch{A.reconnect()}};return Q(27e4),()=>{T=!0,x!==void 0&&window.clearTimeout(x)}},[A,l,d,e,F,t,c]),{agent:A,connectionEpoch:l,connectionError:d,isHydrating:k,isReconnecting:P,retryConnection:b}}async function Pl(e,t){let n=await e.context?.page?.()??{},r=t?{...n,componentSelection:t}:n,o;try{o=JSON.stringify(r)}catch{throw new Error("HeroUI Agent page context must be JSON serializable")}if(new TextEncoder().encode(o).byteLength>16*1024)throw new Error("HeroUI Agent page context exceeds 16KB");return JSON.parse(o)}export{fg as default};
|
|
@@ -6,9 +6,9 @@ declare const agentThemeSchema: z.ZodEnum<{
|
|
|
6
6
|
system: "system";
|
|
7
7
|
}>;
|
|
8
8
|
declare const agentSurfaceVariantSchema: z.ZodEnum<{
|
|
9
|
-
surface: "surface";
|
|
10
9
|
outline: "outline";
|
|
11
10
|
plain: "plain";
|
|
11
|
+
surface: "surface";
|
|
12
12
|
"surface-secondary": "surface-secondary";
|
|
13
13
|
}>;
|
|
14
14
|
declare const agentIdentityIdSchema: z.ZodString;
|
|
@@ -66,15 +66,21 @@ declare const AGENT_CONVERSATION_SOURCE: {
|
|
|
66
66
|
type AgentConversationSource = (typeof AGENT_CONVERSATION_SOURCE)[keyof typeof AGENT_CONVERSATION_SOURCE];
|
|
67
67
|
declare const agentProjectConfigSchema: z.ZodObject<{
|
|
68
68
|
agentId: z.ZodString;
|
|
69
|
+
componentSurfaceVariant: z.ZodDefault<z.ZodEnum<{
|
|
70
|
+
outline: "outline";
|
|
71
|
+
plain: "plain";
|
|
72
|
+
surface: "surface";
|
|
73
|
+
"surface-secondary": "surface-secondary";
|
|
74
|
+
}>>;
|
|
69
75
|
minimumProtocolVersion: z.ZodLiteral<6>;
|
|
70
76
|
name: z.ZodString;
|
|
71
77
|
protocolVersion: z.ZodLiteral<6>;
|
|
72
78
|
sdkVersion: z.ZodDefault<z.ZodString>;
|
|
73
79
|
suggestedPrompts: z.ZodArray<z.ZodString>;
|
|
74
80
|
surfaceVariant: z.ZodDefault<z.ZodEnum<{
|
|
75
|
-
surface: "surface";
|
|
76
81
|
outline: "outline";
|
|
77
82
|
plain: "plain";
|
|
83
|
+
surface: "surface";
|
|
78
84
|
"surface-secondary": "surface-secondary";
|
|
79
85
|
}>>;
|
|
80
86
|
theme: z.ZodEnum<{
|
package/dist/index.d.ts
CHANGED
|
@@ -132,7 +132,7 @@ type AgentRuntimeTimingEventDetail = AgentRuntimeTiming & {
|
|
|
132
132
|
* `./models.schema`, which only server and contract consumers need.
|
|
133
133
|
*/
|
|
134
134
|
/** Model ids the hosted agent accepts from the browser picker. */
|
|
135
|
-
declare const AGENT_MODEL_IDS: readonly ["moonshotai/Kimi-K3", "openai/gpt-5.6-luna", "openai/gpt-5.6-terra", "openai/gpt-5.6-sol", "google/gemini-3.
|
|
135
|
+
declare const AGENT_MODEL_IDS: readonly ["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"];
|
|
136
136
|
type AgentModelId = (typeof AGENT_MODEL_IDS)[number];
|
|
137
137
|
/**
|
|
138
138
|
* Retired ids mapped to their replacement. Model ids are a public part of the
|
|
@@ -152,11 +152,11 @@ type AgentModelOption = {
|
|
|
152
152
|
tier: AgentModelTier;
|
|
153
153
|
};
|
|
154
154
|
/**
|
|
155
|
-
* Recommended default selected when the optional picker first opens.
|
|
155
|
+
* Recommended default selected when the optional picker first opens. Gemini 3.7 Flash
|
|
156
156
|
* matches the hosted runtime's baked-in default (`DEFAULT_CHAT_MODEL_IDS.herouiAgent`),
|
|
157
157
|
* so what users see in the picker is what actually runs by default.
|
|
158
158
|
*/
|
|
159
|
-
declare const DEFAULT_AGENT_PICKER_MODEL_ID = "
|
|
159
|
+
declare const DEFAULT_AGENT_PICKER_MODEL_ID = "google/gemini-3.7-flash";
|
|
160
160
|
/**
|
|
161
161
|
* Small, tool-capable model catalog for HeroUI Agent. These ids are the
|
|
162
162
|
* server-side allowlist as well as the browser picker source of truth.
|
|
@@ -187,8 +187,8 @@ declare const AGENT_MODEL_OPTIONS: readonly [{
|
|
|
187
187
|
readonly tier: "complex";
|
|
188
188
|
}, {
|
|
189
189
|
readonly description: "Fast multimodal analysis with a large context window";
|
|
190
|
-
readonly id: "google/gemini-3.
|
|
191
|
-
readonly label: "Gemini 3.
|
|
190
|
+
readonly id: "google/gemini-3.7-flash";
|
|
191
|
+
readonly label: "Gemini 3.7 Flash";
|
|
192
192
|
readonly provider: "Google";
|
|
193
193
|
readonly tier: "light";
|
|
194
194
|
}, {
|
|
@@ -311,6 +311,13 @@ type AgentSharedContext = {
|
|
|
311
311
|
page?: () => AgentContext | Promise<AgentContext>;
|
|
312
312
|
} & Record<string, unknown>;
|
|
313
313
|
type AgentViewMode = "floating" | "sidebar";
|
|
314
|
+
type AgentSurfaceVariant = "outline" | "plain" | "surface" | "surface-secondary";
|
|
315
|
+
/**
|
|
316
|
+
* Controls whether an outside interaction closes the floating panel. Matches React
|
|
317
|
+
* Aria Popover: `true` or omitted always closes; `false` never closes; a
|
|
318
|
+
* predicate receives the outside element and returns whether to close.
|
|
319
|
+
*/
|
|
320
|
+
type AgentShouldCloseOnInteractOutside = boolean | ((element: Element) => boolean);
|
|
314
321
|
type AgentMarkdownAnimation = boolean | AnimateOptions;
|
|
315
322
|
type AgentMarkdownCaret = "block" | "circle";
|
|
316
323
|
type AgentMarkdownRenderer = CustomRenderer;
|
|
@@ -442,16 +449,34 @@ type AgentPanelOptions = {
|
|
|
442
449
|
};
|
|
443
450
|
/** Visual presentation: view mode, theme, panel size, and launcher placement. */
|
|
444
451
|
type AgentAppearance = {
|
|
452
|
+
/** Surface treatment for approval, calendar, commerce, and other response cards. @default "surface" */
|
|
453
|
+
componentSurfaceVariant?: AgentSurfaceVariant;
|
|
445
454
|
/** Where the launcher button (and the floating panel) is anchored. */
|
|
446
455
|
launcher?: AgentLauncherOptions;
|
|
447
456
|
/** Size and expansion of the floating panel. */
|
|
448
457
|
panel?: AgentPanelOptions;
|
|
458
|
+
/**
|
|
459
|
+
* When the visitor interacts outside the floating panel, whether to close it.
|
|
460
|
+
* Only applies in `viewMode: "floating"`. `true` or omitted always closes;
|
|
461
|
+
* `false` never closes on outside interact; a predicate receives the outside
|
|
462
|
+
* element. Escape and the header close button are unchanged.
|
|
463
|
+
*/
|
|
464
|
+
shouldCloseOnInteractOutside?: AgentShouldCloseOnInteractOutside;
|
|
465
|
+
/** Surface treatment for charts, tables, maps, and other primary data surfaces. */
|
|
466
|
+
surfaceVariant?: AgentSurfaceVariant;
|
|
449
467
|
theme?: AgentThemeOptions;
|
|
450
468
|
/**
|
|
451
469
|
* How the chat opens: `"floating"` (default) is a floating rounded panel in
|
|
452
470
|
* the corner; `"sidebar"` docks full-height to the right edge of the page.
|
|
453
471
|
*/
|
|
454
472
|
viewMode?: AgentViewMode;
|
|
473
|
+
/**
|
|
474
|
+
* Stacking level of the Agent host. Set this when the Agent must sit below
|
|
475
|
+
* application-owned dialogs or above unusually high application chrome.
|
|
476
|
+
* This sets the public `--ha-z-index` CSS custom property.
|
|
477
|
+
* @default 40
|
|
478
|
+
*/
|
|
479
|
+
zIndex?: number;
|
|
455
480
|
};
|
|
456
481
|
/** Message composer settings. */
|
|
457
482
|
type AgentComposerOptions = {
|
|
@@ -490,6 +515,8 @@ type AgentStartScreenOptions = {
|
|
|
490
515
|
promptShortcuts?: boolean;
|
|
491
516
|
/** Up to five suggested prompts (each max 160 characters). */
|
|
492
517
|
prompts?: string[];
|
|
518
|
+
/** Supporting text shown below the greeting. Limited to 240 characters. */
|
|
519
|
+
subtitle?: string;
|
|
493
520
|
};
|
|
494
521
|
/** Internal — for HeroUI platform development only. */
|
|
495
522
|
type AgentApiOverrides = {
|
|
@@ -576,7 +603,7 @@ type HeroUIAgentProps = {
|
|
|
576
603
|
startNewConversationOnOpen?: boolean;
|
|
577
604
|
/**
|
|
578
605
|
* Apply the appearance saved for this project in the HeroUI dashboard —
|
|
579
|
-
* launcher icon, colors, typography, greeting, and suggested prompts —
|
|
606
|
+
* launcher icon, colors, typography, greeting, subtitle, and suggested prompts —
|
|
580
607
|
* without redeploying.
|
|
581
608
|
*
|
|
582
609
|
* Anything passed in code wins, field by field, so this only fills in what
|
|
@@ -598,6 +625,12 @@ type HeroUIAgentProps = {
|
|
|
598
625
|
* @default true
|
|
599
626
|
*/
|
|
600
627
|
showLauncher?: boolean;
|
|
628
|
+
/**
|
|
629
|
+
* Show a compact Beta chip in the open panel header, next to the assistant
|
|
630
|
+
* title. Useful while the agent is still stabilizing for end users.
|
|
631
|
+
* @default false
|
|
632
|
+
*/
|
|
633
|
+
showBetaBadge?: boolean;
|
|
601
634
|
startScreen?: AgentStartScreenOptions;
|
|
602
635
|
/**
|
|
603
636
|
* Client tools the agent can call in the user's browser. Define with
|
|
@@ -645,4 +678,4 @@ declare function useAgent(agentId?: string): AgentController;
|
|
|
645
678
|
*/
|
|
646
679
|
declare function HeroUIAgent(props: HeroUIAgentProps): react_jsx_runtime.JSX.Element;
|
|
647
680
|
|
|
648
|
-
export { AGENT_DESIGN_THEMES, AGENT_MODEL_IDS, AGENT_MODEL_OPTIONS, type AgentActivityPhase, type AgentApiOverrides, type AgentAppearance, type AgentAttachmentContentType, type AgentAuthToken, type AgentCapabilities, type AgentColorScheme, type AgentComponentExportFormat, type AgentComposerOptions, type AgentContext, type AgentController, type AgentDesignTheme, type AgentFeedbackReason, type AgentLauncherOptions, type AgentLauncherPosition, type AgentMarkdownAnimation, type AgentMarkdownCaret, type AgentMarkdownOptions, type AgentMarkdownPlugins, type AgentMarkdownRenderer, type AgentMarkdownRendererProps, type AgentMessageAction, type AgentModelId, type AgentModelOption, type AgentModelTier, type AgentPanelOptions, type AgentPermissionMode, type AgentPermissionOptions, type AgentRadius, type AgentResponseFeedback, type AgentRuntimeTiming, type AgentRuntimeTimingEventDetail, type AgentSharedContext, type AgentStartScreenOptions, type AgentThemeColor, type AgentThemeColors, type AgentThemeOptions, type AgentTypography, type AgentViewMode, type ClientTool, type ClientToolExecutionContext, type ClientToolIconProps, type ClientToolRenderProps, type ClientToolStatus, DEFAULT_AGENT_PICKER_MODEL_ID, type GetAuthToken, type GetAuthTokenContext, HEROUI_AGENT_RUNTIME_TIMING_EVENT, HeroUIAgent, type HeroUIAgentProps, LEGACY_AGENT_MODEL_IDS, createToolHelper, getAgentModelTier, isAgentModelId, resolveAgentModelId, useAgent };
|
|
681
|
+
export { AGENT_DESIGN_THEMES, AGENT_MODEL_IDS, AGENT_MODEL_OPTIONS, type AgentActivityPhase, type AgentApiOverrides, type AgentAppearance, type AgentAttachmentContentType, type AgentAuthToken, type AgentCapabilities, type AgentColorScheme, type AgentComponentExportFormat, type AgentComposerOptions, type AgentContext, type AgentController, type AgentDesignTheme, type AgentFeedbackReason, type AgentLauncherOptions, type AgentLauncherPosition, type AgentMarkdownAnimation, type AgentMarkdownCaret, type AgentMarkdownOptions, type AgentMarkdownPlugins, type AgentMarkdownRenderer, type AgentMarkdownRendererProps, type AgentMessageAction, type AgentModelId, type AgentModelOption, type AgentModelTier, type AgentPanelOptions, type AgentPermissionMode, type AgentPermissionOptions, type AgentRadius, type AgentResponseFeedback, type AgentRuntimeTiming, type AgentRuntimeTimingEventDetail, type AgentSharedContext, type AgentStartScreenOptions, type AgentSurfaceVariant, type AgentThemeColor, type AgentThemeColors, type AgentThemeOptions, type AgentTypography, type AgentViewMode, type ClientTool, type ClientToolExecutionContext, type ClientToolIconProps, type ClientToolRenderProps, type ClientToolStatus, DEFAULT_AGENT_PICKER_MODEL_ID, type GetAuthToken, type GetAuthTokenContext, HEROUI_AGENT_RUNTIME_TIMING_EVENT, HeroUIAgent, type HeroUIAgentProps, LEGACY_AGENT_MODEL_IDS, createToolHelper, getAgentModelTier, isAgentModelId, resolveAgentModelId, useAgent };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a
|
|
1
|
+
import{a,b as m}from"./chunk-FOK4MNBE.js";import"./chunk-CN4UQBKO.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,m as HeroUIAgent,n as LEGACY_AGENT_MODEL_IDS,e as createToolHelper,i as getAgentModelTier,g as isAgentModelId,o as resolveAgentModelId,a as useAgent};
|
package/dist/internal/models.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g}from"../chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g}from"../chunk-UHHKMESI.js";export{a as AGENT_MODEL_IDS,e as AGENT_MODEL_OPTIONS,d as DEFAULT_AGENT_PICKER_MODEL_ID,b as LEGACY_AGENT_MODEL_IDS,g as getAgentModelTier,f as isAgentModelId,c as resolveAgentModelId};
|
package/dist/internal/theme.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f}from"../chunk-
|
|
1
|
+
import{a,b,c,d,e,f}from"../chunk-4JEZZR5J.js";export{c as ACCENT_FOREGROUND_CSS,a as AGENT_DESIGN_THEMES,d as LAUNCHER_FOREGROUND_CSS,e as buildLauncherStyle,f as buildThemeStyle,b as resolveAgentDesignTheme};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./chunk-OA7E6MEQ.js";import"./chunk-MXXCR5SR.js";import"./chunk-CR3H7AVI.js";export{a as ModelPicker};
|
package/dist/next.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { AGENT_MODEL_IDS, AGENT_MODEL_OPTIONS, AgentActivityPhase, AgentAttachmentContentType, AgentAuthToken, AgentComposerOptions, AgentContext, AgentController, AgentFeedbackReason, AgentMarkdownAnimation, AgentMarkdownCaret, AgentMarkdownOptions, AgentMarkdownPlugins, AgentMarkdownRenderer, AgentMarkdownRendererProps, AgentModelId, AgentModelOption, AgentModelTier, AgentPermissionMode, AgentPermissionOptions, AgentResponseFeedback, AgentRuntimeTiming, AgentRuntimeTimingEventDetail, AgentSharedContext, ClientTool, ClientToolExecutionContext, ClientToolIconProps, ClientToolRenderProps, ClientToolStatus, DEFAULT_AGENT_PICKER_MODEL_ID, GetAuthToken, GetAuthTokenContext, HEROUI_AGENT_RUNTIME_TIMING_EVENT, HeroUIAgent, HeroUIAgentProps, createToolHelper, getAgentModelTier, isAgentModelId, useAgent } from './index.js';
|
|
1
|
+
export { AGENT_MODEL_IDS, AGENT_MODEL_OPTIONS, AgentActivityPhase, AgentAttachmentContentType, AgentAuthToken, AgentComposerOptions, AgentContext, AgentController, AgentFeedbackReason, AgentMarkdownAnimation, AgentMarkdownCaret, AgentMarkdownOptions, AgentMarkdownPlugins, AgentMarkdownRenderer, AgentMarkdownRendererProps, AgentModelId, AgentModelOption, AgentModelTier, AgentPermissionMode, AgentPermissionOptions, AgentResponseFeedback, AgentRuntimeTiming, AgentRuntimeTimingEventDetail, AgentSharedContext, AgentSurfaceVariant, ClientTool, ClientToolExecutionContext, ClientToolIconProps, ClientToolRenderProps, ClientToolStatus, DEFAULT_AGENT_PICKER_MODEL_ID, GetAuthToken, GetAuthTokenContext, HEROUI_AGENT_RUNTIME_TIMING_EVENT, HeroUIAgent, HeroUIAgentProps, createToolHelper, getAgentModelTier, isAgentModelId, useAgent } from './index.js';
|
|
2
2
|
import 'react';
|
|
3
3
|
import 'react/jsx-runtime';
|
|
4
4
|
import 'zod';
|
package/dist/next.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as i,b as p}from"./chunk-
|
|
1
|
+
import{a as i,b as p}from"./chunk-FOK4MNBE.js";import"./chunk-CN4UQBKO.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.d.ts
CHANGED