@runtypelabs/persona 4.29.0 → 4.29.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/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/approval-ui.cjs +3 -3
- package/dist/approval-ui.d.cts +1 -1
- package/dist/approval-ui.d.ts +1 -1
- package/dist/approval-ui.js +3 -3
- package/dist/artifacts-ui.d.cts +2 -2
- package/dist/artifacts-ui.d.ts +2 -2
- package/dist/chunk-B1-_pp-Y.js +4 -0
- package/dist/chunk-B2HCRERn.js +9 -0
- package/dist/chunk-Bm2-bemv.js +1 -0
- package/dist/chunk-BvhTpG6k.js +1 -0
- package/dist/{chunk-DjOvgFsn.js → chunk-Car1mORT.js} +1 -1
- package/dist/chunk-D5B629Mj.js +1 -0
- package/dist/chunk-DO9_WSpy.js +1 -0
- package/dist/chunk-DTDHeUsG.js +1 -0
- package/dist/chunk-DjFpGFGA.js +1 -0
- package/dist/chunk-DrpuvY5W.js +1 -0
- package/dist/{chunk-dRBlrLd7.js → chunk-DtmtfIkd.js} +1 -1
- package/dist/client-history.js +1 -1
- package/dist/client-stream.js +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/{composer-input-D3sB8_P_.d.cts → composer-input-C3Xh1Qzj.d.cts} +1 -1
- package/dist/{composer-input-D3sB8_P_.d.ts → composer-input-C3Xh1Qzj.d.ts} +1 -1
- package/dist/{context-mention-manager-D2qxE5op.d.cts → context-mention-manager-BsEiGObk.d.cts} +1 -1
- package/dist/{context-mention-manager-D2qxE5op.d.ts → context-mention-manager-BsEiGObk.d.ts} +1 -1
- package/dist/context-mentions-inline.d.cts +2 -2
- package/dist/context-mentions-inline.d.ts +2 -2
- package/dist/context-mentions.d.cts +3 -3
- package/dist/context-mentions.d.ts +3 -3
- package/dist/{defaults-Dsw66XqE.d.cts → defaults-DN-L67ak.d.cts} +1 -1
- package/dist/{defaults-Dsw66XqE.d.ts → defaults-DN-L67ak.d.ts} +1 -1
- package/dist/event-stream-view.d.cts +1 -1
- package/dist/event-stream-view.d.ts +1 -1
- package/dist/{fallback-speech-engine-DJpJcWAk.d.cts → fallback-speech-engine-Cph8FTux.d.cts} +1 -1
- package/dist/{fallback-speech-engine-DJpJcWAk.d.ts → fallback-speech-engine-Cph8FTux.d.ts} +1 -1
- package/dist/forms-ui.d.cts +2 -2
- package/dist/forms-ui.d.ts +2 -2
- package/dist/history-view.d.cts +1 -1
- package/dist/history-view.d.ts +1 -1
- package/dist/index.cjs +56 -56
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.global.js +2 -3
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +42 -42
- package/dist/index.js.map +1 -1
- package/dist/{markdown-parsers-loader-CCY7T4Up.d.cts → markdown-parsers-loader-C4Xze-Jw.d.cts} +1 -1
- package/dist/{markdown-parsers-loader-CCY7T4Up.d.ts → markdown-parsers-loader-C4Xze-Jw.d.ts} +1 -1
- package/dist/{preview-DKKpfTo7.d.cts → preview-m9QlqsZi.d.cts} +2 -2
- package/dist/{preview-DKKpfTo7.d.ts → preview-m9QlqsZi.d.ts} +2 -2
- package/dist/{session-DleMr9dZ.d.ts → session-BtvvmWnw.d.cts} +21 -9
- package/dist/{session-DleMr9dZ.d.cts → session-BtvvmWnw.d.ts} +21 -9
- package/dist/session-actions.js +1 -1
- package/dist/session-reconnect.cjs +1 -1
- package/dist/session-reconnect.d.cts +8 -2
- package/dist/session-reconnect.d.ts +8 -2
- package/dist/session-reconnect.js +1 -1
- package/dist/smart-dom-reader.d.cts +1 -1
- package/dist/smart-dom-reader.d.ts +1 -1
- package/dist/theme-editor-preview.cjs +62 -62
- package/dist/theme-editor-preview.d.cts +1 -1
- package/dist/theme-editor-preview.d.ts +1 -1
- package/dist/theme-editor-preview.js +41 -41
- package/dist/theme-editor.d.cts +2 -2
- package/dist/theme-editor.d.ts +2 -2
- package/dist/theme-reference.d.cts +2 -2
- package/dist/theme-reference.d.ts +2 -2
- package/dist/{types-oAZ1VReS.d.cts → types-DL-oBHE1.d.cts} +41 -3
- package/dist/{types-oAZ1VReS.d.ts → types-DL-oBHE1.d.ts} +41 -3
- package/dist/voice-client-tools.d.cts +1 -1
- package/dist/voice-client-tools.d.ts +1 -1
- package/dist/voice-runtime.cjs +3 -3
- package/dist/voice-runtime.d.cts +10 -4
- package/dist/voice-runtime.d.ts +10 -4
- package/dist/voice-runtime.js +5 -5
- package/dist/voice-worklet-player.d.cts +2 -2
- package/dist/voice-worklet-player.d.ts +2 -2
- package/dist/{webmcp-runtime-entry-Deg0NfmB.d.cts → webmcp-runtime-entry-T6SU_TlL.d.cts} +1 -1
- package/dist/{webmcp-runtime-entry-Deg0NfmB.d.ts → webmcp-runtime-entry-T6SU_TlL.d.ts} +1 -1
- package/dist/webmcp-runtime.d.cts +1 -1
- package/dist/webmcp-runtime.d.ts +1 -1
- package/dist/widget.css +1 -1
- package/package.json +1 -1
- package/src/client-approve.test.ts +17 -1
- package/src/client-resume.ts +15 -3
- package/src/client.interrupt.test.ts +21 -0
- package/src/client.ts +24 -4
- package/src/components/activity-row.ts +3 -2
- package/src/components/approval-actions.test.ts +8 -0
- package/src/components/approval-actions.ts +6 -2
- package/src/components/approval-bubble.test.ts +14 -0
- package/src/components/approval-bubble.ts +8 -1
- package/src/components/tool-bubble.ts +8 -5
- package/src/generated/runtype-openapi-contract.ts +7 -1
- package/src/resume-dedupe-local-only.test.ts +273 -0
- package/src/runtime/persist-state.test.ts +86 -0
- package/src/session-actions.ts +20 -6
- package/src/session-reconnect.ts +18 -1
- package/src/session.restored-browser-tools.test.ts +272 -0
- package/src/session.test.ts +23 -0
- package/src/session.ts +211 -46
- package/src/session.voice.test.ts +169 -0
- package/src/styles/widget.css +4 -2
- package/src/types.ts +37 -2
- package/src/ui.restored-browser-tools.test.ts +128 -0
- package/src/ui.scroll.test.ts +7 -2
- package/src/ui.stream-replay.test.ts +86 -0
- package/src/ui.streaming-coalescing.test.ts +183 -0
- package/src/ui.ts +152 -124
- package/src/ui.typing-indicator.test.ts +21 -0
- package/src/utils/formatting.test.ts +9 -1
- package/src/utils/formatting.ts +4 -0
- package/src/utils/local-only-message.ts +15 -0
- package/src/utils/message-fingerprint.test.ts +9 -0
- package/src/utils/message-fingerprint.ts +18 -5
- package/src/utils/morph.ts +10 -0
- package/src/utils/restored-browser-state.ts +50 -0
- package/src/utils/storage.ts +12 -1
- package/src/utils/voice-prior-tool-results.ts +37 -0
- package/src/voice/runtype-voice-provider.ts +13 -8
- package/src/voice/session-voice-wiring.ts +1 -2
- package/src/voice/voice-delegation.ts +10 -3
- package/src/voice/voice.test.ts +38 -2
- package/dist/chunk-B6zZsT6F.js +0 -1
- package/dist/chunk-CIVsNcrk.js +0 -1
- package/dist/chunk-CKdlNyzM.js +0 -9
- package/dist/chunk-DbhxjyOB.js +0 -4
- package/dist/chunk-DsdqLStH.js +0 -1
- package/dist/chunk-GIqbL2Eg.js +0 -1
package/dist/index.js
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
import{Marked as e,Marked as t}from"marked";import n,{default as r}from"dompurify";import{Activity as i,ArrowDown as a,ArrowLeft as o,ArrowRight as s,ArrowUp as c,ArrowUpRight as l,AtSign as u,Ban as d,Bell as f,Bookmark as p,Bot as m,Building as h,Calendar as g,CalendarDays as _,Camera as v,ChartColumn as y,Check as b,ChevronDown as x,ChevronLeft as S,ChevronRight as C,ChevronUp as w,Circle as T,CircleCheck as E,CircleX as D,Clipboard as O,ClipboardCopy as k,Clock as ee,CodeXml as A,Copy as te,CreditCard as ne,DollarSign as re,Download as ie,Ellipsis as ae,EllipsisVertical as oe,ExternalLink as j,Eye as se,EyeOff as ce,File as le,FileCode as ue,FileSpreadsheet as de,FileText as fe,Files as pe,Film as M,Flag as me,Folder as he,FolderOpen as ge,Funnel as _e,Gift as ve,Globe as ye,Hash as N,Headphones as be,Heart as P,History as xe,House as Se,Image as Ce,ImagePlus as we,Info as Te,Key as Ee,Lightbulb as De,Link as Oe,Loader as ke,LoaderCircle as Ae,Lock as je,Mail as Me,MapPin as Ne,Maximize as Pe,Menu as Fe,MessageCircle as Ie,MessageSquare as Le,Mic as Re,Minimize as ze,Minus as Be,Monitor as Ve,Moon as He,Package as Ue,PanelLeft as We,Paperclip as Ge,Pause as Ke,PenLine as qe,Pencil as Je,Percent as Ye,Phone as Xe,Play as Ze,Plus as Qe,Quote as $e,Receipt as et,RefreshCw as tt,RotateCw as nt,Save as F,Search as I,Send as rt,Settings as it,Share as L,Shield as R,ShieldAlert as z,ShieldCheck as at,ShieldX as ot,ShoppingBag as st,ShoppingCart as B,Smartphone as V,Sparkles as ct,Square as lt,Star as ut,Store as dt,Sun as ft,Tag as pt,ThumbsDown as mt,ThumbsUp as ht,Timer as H,Trash as gt,Trash2 as _t,TriangleAlert as vt,Truck as yt,Upload as bt,User as xt,Volume2 as St,VolumeX as Ct,Wallet as wt,X as Tt,Zap as U}from"lucide";import{ARR as Et,OBJ as Dt,STR as Ot,parse as kt}from"partial-json";import{Idiomorph as At}from"idiomorph";var jt=Object.defineProperty,W=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},Mt=(e,t)=>{let n={};for(var r in e)jt(n,r,{get:e[r],enumerable:!0});return t||jt(n,Symbol.toStringTag,{value:`Module`}),n},Nt,Pt=W((()=>{Nt=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,r=null,i=null,a=null;return{setLoader:e=>{r=e,n&&(i=null,a=null)},load:()=>i?Promise.resolve(i):a||(a=(r??t)().then(e=>(i=e,e)).catch(e=>{throw a=null,e}),a),provide:e=>{i=e},getSync:()=>i}}})),Ft=/* @__PURE__ */ Mt({DOMPurify:()=>r,Marked:()=>t}),It=W((()=>{}));Pt();const{setLoader:Lt,load:Rt,provide:zt,getSync:Bt}=Nt({fallbackImport:()=>Promise.resolve().then(()=>(It(),Ft))}),Vt=/* @__PURE__ */ new Set,Ht=()=>{let e=[...Vt];Vt.clear();for(let t of e)try{t()}catch{}},Ut=()=>{let e=Bt();return e?Promise.resolve(e):Rt().then(e=>(Ht(),e))},Wt=e=>Bt()?()=>{}:(Vt.add(e),()=>{Vt.delete(e)}),Gt=e=>{zt(e),Ht()},Kt=Bt;Gt({Marked:e,DOMPurify:n});const qt={user:xt,mail:Me,phone:Xe,calendar:g,clock:ee,building:h,"map-pin":Ne,lock:je,key:Ee,"credit-card":ne,hash:N,globe:ye,link:Oe,"circle-check":E,"circle-x":D,"triangle-alert":vt,info:Te,ban:d,shield:R,house:Se,"pen-line":qe,save:F,share:L,funnel:_e,settings:it,"rotate-cw":nt,"shopping-cart":B,"shopping-bag":st,package:Ue,truck:yt,tag:pt,gift:ve,receipt:et,wallet:wt,store:dt,"dollar-sign":re,percent:Ye,play:Ze,pause:Ke,"volume-x":Ct,camera:v,image:Ce,film:M,headphones:be,"message-circle":Ie,bell:f,heart:P,"eye-off":ce,bookmark:p,"calendar-days":_,timer:H,folder:he,"folder-open":ge,files:pe,"chart-column":y,sparkles:ct,zap:U,sun:ft,moon:He,flag:me,lightbulb:De,monitor:Ve,smartphone:V};var Jt,Yt=W((()=>{Jt=(e,t=24,n=`currentColor`,r=2)=>{if(!Array.isArray(e))return null;let i=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return i.setAttribute(`width`,String(t)),i.setAttribute(`height`,String(t)),i.setAttribute(`viewBox`,`0 0 24 24`),i.setAttribute(`fill`,`none`),i.setAttribute(`stroke`,n),i.setAttribute(`stroke-width`,String(r)),i.setAttribute(`stroke-linecap`,`round`),i.setAttribute(`stroke-linejoin`,`round`),i.setAttribute(`aria-hidden`,`true`),e.forEach(e=>{if(!Array.isArray(e)||e.length<2)return;let t=e[0],n=e[1];if(!n)return;let r=document.createElementNS(`http://www.w3.org/2000/svg`,t);Object.entries(n).forEach(([e,t])=>{e!==`stroke`&&r.setAttribute(e,String(t))}),i.appendChild(r)}),i}})),Xt,Zt,Qt,$t=W((()=>{Pt(),{setLoader:Xt,load:Zt}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/icons-extra`)}),Qt=Zt})),en,tn,nn,rn,an,on,sn,cn,ln,un,dn,fn,G,pn,K,mn=W((()=>{Yt(),$t(),en={activity:i,"arrow-down":a,"arrow-up":c,"arrow-up-right":l,bot:m,"chevron-down":x,"chevron-up":w,"chevron-right":C,"chevron-left":S,check:b,clipboard:O,"clipboard-copy":k,"code-xml":A,copy:te,file:le,"file-code":ue,"file-spreadsheet":de,"file-text":fe,"image-plus":we,loader:ke,"loader-circle":Ae,mic:Re,paperclip:Ge,quote:$e,"refresh-cw":tt,search:I,send:rt,"shield-alert":z,"shield-check":at,"shield-x":ot,square:lt,"thumbs-down":mt,"thumbs-up":ht,upload:bt,"volume-2":St,x:Tt,"at-sign":u,"arrow-left":o,"arrow-right":s,"external-link":j,ellipsis:ae,"ellipsis-vertical":oe,menu:Fe,"panel-left":We,plus:Qe,minus:Be,pencil:Je,trash:gt,"trash-2":_t,download:ie,maximize:Pe,minimize:ze,"message-square":Le,star:ut,eye:se,history:xe},tn=/* @__PURE__ */ `user.mail.phone.calendar.clock.building.map-pin.lock.key.credit-card.hash.globe.link.circle-check.circle-x.triangle-alert.info.ban.shield.house.pen-line.save.share.funnel.settings.rotate-cw.shopping-cart.shopping-bag.package.truck.tag.gift.receipt.wallet.store.dollar-sign.percent.play.pause.volume-x.camera.image.film.headphones.message-circle.bell.heart.eye-off.bookmark.calendar-days.timer.folder.folder-open.files.chart-column.sparkles.zap.sun.moon.flag.lightbulb.monitor.smartphone`.split(`.`),nn=new Map(Object.entries(en)),rn=/* @__PURE__ */ new Set,an=!1,on=/* @__PURE__ */ new Set,sn=e=>{let t=[...on];e&&on.clear();for(let e of t)try{e()}catch{}},cn=e=>an?()=>{}:(on.add(e),()=>{on.delete(e)}),ln=()=>{let e=0;for(let t of[...rn]){let n=nn.get(t.name);if(!n)continue;rn.delete(t),e++;let r=Jt(n,t.size,t.color,t.strokeWidth);if(r)for(t.el.removeAttribute(`data-persona-icon-pending`);r.firstChild;)t.el.appendChild(r.firstChild)}return e},un=e=>{for(let[t,n]of Object.entries(e))nn.set(t,n);ln()>0&&!an&&sn(!1)},dn=e=>{if(!an){for(let[t,n]of Object.entries(e))nn.has(t)||nn.set(t,n);an=!0,ln(),sn(!0)}},fn=!1,G=()=>{Qt().then(e=>{if(!an){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))nn.has(t)||nn.set(t,n);an=!0,ln(),sn(!0)}}).catch(e=>{fn=!0,console.warn(`[Persona] Failed to load the icons-extra chunk`,e)})},pn=(e,t,n)=>{let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`width`,String(e)),r.setAttribute(`height`,String(e)),r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,t),r.setAttribute(`stroke-width`,String(n)),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`data-persona-icon-pending`,`true`),r},K=(e,t=24,n=`currentColor`,r=2)=>{let i=nn.get(e);if(i)return Jt(i,t,n,r);if(tn.includes(e)){fn&&=!1;let i=pn(t,n,r);if(rn.size>=500){let e=rn.values().next().value;e&&rn.delete(e)}return rn.add({el:i,name:e,size:t,color:n,strokeWidth:r}),G(),i}return console.warn(`Lucide icon "${e}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null}}));mn(),dn(qt);function hn(e){if(e.length===0)return`0:empty`;let t=e.map(e=>[e.name,e.description??``,e.parametersSchema?JSON.stringify(e.parametersSchema):``,e.origin??``,e.annotations?JSON.stringify(e.annotations):``].join(``)).sort();return`${e.length}:${_n(t.join(``))}`}function gn(e,t){let n=3735928559^t,r=1103547991^t;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function _n(e){return`${gn(e,0).toString(36)}.${gn(e,2654435761).toString(36)}`}var vn,yn,bn,xn,Sn,Cn,wn,Tn,En=W((()=>{vn=`webmcp:`,yn=/* @__PURE__ */ new Map,bn=e=>{yn.clear();for(let t of e){let e=t.title?.trim();e&&yn.set(t.name,e)}},xn=e=>yn.get(Cn(e)),Sn=null,Cn=e=>e.startsWith(`webmcp:`)?e.slice(7):e,wn=e=>e.startsWith(vn),Tn=()=>Sn?Sn():import(`@mcp-b/webmcp-polyfill`)}));function Dn(e){return e===`card`?`collapsed`:e}function On(e){return e.split(`;`,1)[0].trim().toLowerCase()}function kn(e,t){if(!e)return;let n=Object.entries(e);for(let[e,r]of n)if(On(e)===t)return{mode:Dn(r),selector:On(e)};let r=`${t.split(`/`,1)[0]}/*`;for(let[e,t]of n)if(On(e)===r)return{mode:Dn(t),selector:r}}function An(e,t){let n=e?.display,r=typeof n==`string`?{default:n}:n??{};if(t.file&&r.files){if(typeof r.files==`string`)return{mode:Dn(r.files),matchedBy:{type:`files`}};let e=t.file.mimeType?On(t.file.mimeType):void 0,n=e?kn(r.files.byMediaType,e):void 0;if(e&&n)return{mode:n.mode,matchedBy:{type:`mediaType`,mediaType:e,selector:n.selector}};if(r.files.default)return{mode:Dn(r.files.default),matchedBy:{type:`files`}}}let i=r.byKind?.[t.artifactType];if(i)return{mode:Dn(i),matchedBy:{type:`kind`,kind:t.artifactType,configuredBy:`byKind`}};let a=r.byType?.[t.artifactType];if(a)return{mode:Dn(a),matchedBy:{type:`kind`,kind:t.artifactType,configuredBy:`byType`}};let o=t.presentation?.preferredMode;return o?{mode:Dn(o),matchedBy:{type:`preferredMode`}}:r.default?{mode:Dn(r.default),matchedBy:{type:`default`}}:{mode:`panel`,matchedBy:{type:`personaDefault`}}}function jn(e,t){return An(e,t).mode}function Mn(e,t){return JSON.stringify({component:e===`inline`?`PersonaArtifactInline`:`PersonaArtifactCard`,props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e===`inline`&&t.component?{component:t.component}:{},...e===`inline`&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown===void 0?{}:{markdown:t.markdown}}})}var Nn=W((()=>{})),Pn,Fn,In,Ln,Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn,$n,er=W((()=>{Pn=e=>e.replace(/\\n/g,`
|
|
2
|
-
`).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`),Fn=e=>{if(e===null)return`null`;if(e===void 0)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},In=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs===void 0?Math.max(0,t-n):e.durationMs)/1e3;return r<.1?`Thought for <0.1 seconds`:`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,``)} seconds`},Ln=e=>e.status===`complete`?In(e):e.status===`pending`?`Waiting`:``,Rn=(e,t)=>{let n=t?.durationMs??15e3,r=t?.chars??1200;return typeof e.durationMs==`number`?e.durationMs<n:(e.chunks??[]).join(``).length<r},zn=e=>{let t=(typeof e.duration==`number`?e.duration:typeof e.durationMs==`number`?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return t<.1?`Used tool for <0.1 seconds`:`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,``)} seconds`},Bn=e=>e.status===`complete`?zn(e):`Using tool...`,Vn=e=>{let t=e/1e3;return t<.1?`<0.1s`:t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,``)}s`},Hn=e=>{let t=typeof e.duration==`number`?e.duration:typeof e.durationMs==`number`?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Vn(t)},Un=e=>{let t=e.durationMs===void 0?Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())):e.durationMs;return Vn(t)},Wn=(e,t,n)=>{if(!t)return n;let r=e.name?.trim()||`tool`,i=Hn(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,i)},Gn=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],i=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,o;for(;(o=i.exec(n))!==null;)o.index>a&&Kn(r,n.slice(a,o.index),[]),o[1]===void 0?o[2]===void 0?o[3]!==void 0&&Kn(r,o[3],[`dim`]):Kn(r,o[2],[`italic`]):Kn(r,o[1],[`bold`]),a=o.index+o[0].length;return a<n.length&&Kn(r,n.slice(a),[]),r},Kn=(e,t,n)=>{let r=t.split(`{duration}`);for(let t=0;t<r.length;t++)r[t]&&e.push({text:r[t],styles:n}),t<r.length-1&&e.push({text:`{duration}`,styles:n,isDuration:!0})},qn=()=>{let e=null,t=0,n=e=>{let t=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/);if(t&&t[1])try{return t[1].replace(/\\n/g,`
|
|
1
|
+
import{Marked as e,Marked as t}from"marked";import n,{default as r}from"dompurify";import{Activity as i,ArrowDown as a,ArrowLeft as o,ArrowRight as s,ArrowUp as c,ArrowUpRight as l,AtSign as u,Ban as d,Bell as f,Bookmark as p,Bot as m,Building as h,Calendar as g,CalendarDays as _,Camera as v,ChartColumn as y,Check as b,ChevronDown as x,ChevronLeft as S,ChevronRight as C,ChevronUp as w,Circle as T,CircleCheck as E,CircleX as D,Clipboard as O,ClipboardCopy as k,Clock as ee,CodeXml as te,Copy as ne,CreditCard as re,DollarSign as ie,Download as ae,Ellipsis as oe,EllipsisVertical as A,ExternalLink as j,Eye as se,EyeOff as ce,File as le,FileCode as ue,FileSpreadsheet as de,FileText as fe,Files as pe,Film as M,Flag as me,Folder as he,FolderOpen as ge,Funnel as _e,Gift as ve,Globe as ye,Hash as N,Headphones as be,Heart as P,History as xe,House as Se,Image as Ce,ImagePlus as we,Info as Te,Key as Ee,Lightbulb as De,Link as Oe,Loader as ke,LoaderCircle as Ae,Lock as je,Mail as Me,MapPin as Ne,Maximize as Pe,Menu as Fe,MessageCircle as Ie,MessageSquare as Le,Mic as Re,Minimize as ze,Minus as Be,Monitor as Ve,Moon as He,Package as Ue,PanelLeft as We,Paperclip as Ge,Pause as Ke,PenLine as qe,Pencil as Je,Percent as Ye,Phone as Xe,Play as Ze,Plus as Qe,Quote as $e,Receipt as et,RefreshCw as tt,RotateCw as nt,Save as F,Search as I,Send as rt,Settings as it,Share as L,Shield as R,ShieldAlert as z,ShieldCheck as at,ShieldX as ot,ShoppingBag as st,ShoppingCart as B,Smartphone as V,Sparkles as ct,Square as lt,Star as ut,Store as dt,Sun as ft,Tag as pt,ThumbsDown as mt,ThumbsUp as ht,Timer as H,Trash as gt,Trash2 as _t,TriangleAlert as vt,Truck as yt,Upload as bt,User as xt,Volume2 as St,VolumeX as Ct,Wallet as wt,X as Tt,Zap as U}from"lucide";import{ARR as Et,OBJ as Dt,STR as Ot,parse as kt}from"partial-json";import{Idiomorph as At}from"idiomorph";var jt=Object.defineProperty,W=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},Mt=(e,t)=>{let n={};for(var r in e)jt(n,r,{get:e[r],enumerable:!0});return t||jt(n,Symbol.toStringTag,{value:`Module`}),n},Nt,Pt=W((()=>{Nt=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,r=null,i=null,a=null;return{setLoader:e=>{r=e,n&&(i=null,a=null)},load:()=>i?Promise.resolve(i):a||(a=(r??t)().then(e=>(i=e,e)).catch(e=>{throw a=null,e}),a),provide:e=>{i=e},getSync:()=>i}}})),Ft=/* @__PURE__ */ Mt({DOMPurify:()=>r,Marked:()=>t}),It=W((()=>{}));Pt();const{setLoader:Lt,load:Rt,provide:zt,getSync:Bt}=Nt({fallbackImport:()=>Promise.resolve().then(()=>(It(),Ft))}),Vt=/* @__PURE__ */ new Set,Ht=()=>{let e=[...Vt];Vt.clear();for(let t of e)try{t()}catch{}},Ut=()=>{let e=Bt();return e?Promise.resolve(e):Rt().then(e=>(Ht(),e))},Wt=e=>Bt()?()=>{}:(Vt.add(e),()=>{Vt.delete(e)}),Gt=e=>{zt(e),Ht()},Kt=Bt;Gt({Marked:e,DOMPurify:n});const qt={user:xt,mail:Me,phone:Xe,calendar:g,clock:ee,building:h,"map-pin":Ne,lock:je,key:Ee,"credit-card":re,hash:N,globe:ye,link:Oe,"circle-check":E,"circle-x":D,"triangle-alert":vt,info:Te,ban:d,shield:R,house:Se,"pen-line":qe,save:F,share:L,funnel:_e,settings:it,"rotate-cw":nt,"shopping-cart":B,"shopping-bag":st,package:Ue,truck:yt,tag:pt,gift:ve,receipt:et,wallet:wt,store:dt,"dollar-sign":ie,percent:Ye,play:Ze,pause:Ke,"volume-x":Ct,camera:v,image:Ce,film:M,headphones:be,"message-circle":Ie,bell:f,heart:P,"eye-off":ce,bookmark:p,"calendar-days":_,timer:H,folder:he,"folder-open":ge,files:pe,"chart-column":y,sparkles:ct,zap:U,sun:ft,moon:He,flag:me,lightbulb:De,monitor:Ve,smartphone:V};var Jt,Yt=W((()=>{Jt=(e,t=24,n=`currentColor`,r=2)=>{if(!Array.isArray(e))return null;let i=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return i.setAttribute(`width`,String(t)),i.setAttribute(`height`,String(t)),i.setAttribute(`viewBox`,`0 0 24 24`),i.setAttribute(`fill`,`none`),i.setAttribute(`stroke`,n),i.setAttribute(`stroke-width`,String(r)),i.setAttribute(`stroke-linecap`,`round`),i.setAttribute(`stroke-linejoin`,`round`),i.setAttribute(`aria-hidden`,`true`),e.forEach(e=>{if(!Array.isArray(e)||e.length<2)return;let t=e[0],n=e[1];if(!n)return;let r=document.createElementNS(`http://www.w3.org/2000/svg`,t);Object.entries(n).forEach(([e,t])=>{e!==`stroke`&&r.setAttribute(e,String(t))}),i.appendChild(r)}),i}})),Xt,Zt,Qt,$t=W((()=>{Pt(),{setLoader:Xt,load:Zt}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/icons-extra`)}),Qt=Zt})),en,tn,nn,rn,an,on,sn,cn,ln,un,dn,fn,G,pn,K,mn=W((()=>{Yt(),$t(),en={activity:i,"arrow-down":a,"arrow-up":c,"arrow-up-right":l,bot:m,"chevron-down":x,"chevron-up":w,"chevron-right":C,"chevron-left":S,check:b,clipboard:O,"clipboard-copy":k,"code-xml":te,copy:ne,file:le,"file-code":ue,"file-spreadsheet":de,"file-text":fe,"image-plus":we,loader:ke,"loader-circle":Ae,mic:Re,paperclip:Ge,quote:$e,"refresh-cw":tt,search:I,send:rt,"shield-alert":z,"shield-check":at,"shield-x":ot,square:lt,"thumbs-down":mt,"thumbs-up":ht,upload:bt,"volume-2":St,x:Tt,"at-sign":u,"arrow-left":o,"arrow-right":s,"external-link":j,ellipsis:oe,"ellipsis-vertical":A,menu:Fe,"panel-left":We,plus:Qe,minus:Be,pencil:Je,trash:gt,"trash-2":_t,download:ae,maximize:Pe,minimize:ze,"message-square":Le,star:ut,eye:se,history:xe},tn=/* @__PURE__ */ `user.mail.phone.calendar.clock.building.map-pin.lock.key.credit-card.hash.globe.link.circle-check.circle-x.triangle-alert.info.ban.shield.house.pen-line.save.share.funnel.settings.rotate-cw.shopping-cart.shopping-bag.package.truck.tag.gift.receipt.wallet.store.dollar-sign.percent.play.pause.volume-x.camera.image.film.headphones.message-circle.bell.heart.eye-off.bookmark.calendar-days.timer.folder.folder-open.files.chart-column.sparkles.zap.sun.moon.flag.lightbulb.monitor.smartphone`.split(`.`),nn=new Map(Object.entries(en)),rn=/* @__PURE__ */ new Set,an=!1,on=/* @__PURE__ */ new Set,sn=e=>{let t=[...on];e&&on.clear();for(let e of t)try{e()}catch{}},cn=e=>an?()=>{}:(on.add(e),()=>{on.delete(e)}),ln=()=>{let e=0;for(let t of[...rn]){let n=nn.get(t.name);if(!n)continue;rn.delete(t),e++;let r=Jt(n,t.size,t.color,t.strokeWidth);if(r)for(t.el.removeAttribute(`data-persona-icon-pending`);r.firstChild;)t.el.appendChild(r.firstChild)}return e},un=e=>{for(let[t,n]of Object.entries(e))nn.set(t,n);ln()>0&&!an&&sn(!1)},dn=e=>{if(!an){for(let[t,n]of Object.entries(e))nn.has(t)||nn.set(t,n);an=!0,ln(),sn(!0)}},fn=!1,G=()=>{Qt().then(e=>{if(!an){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))nn.has(t)||nn.set(t,n);an=!0,ln(),sn(!0)}}).catch(e=>{fn=!0,console.warn(`[Persona] Failed to load the icons-extra chunk`,e)})},pn=(e,t,n)=>{let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`width`,String(e)),r.setAttribute(`height`,String(e)),r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,t),r.setAttribute(`stroke-width`,String(n)),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`data-persona-icon-pending`,`true`),r},K=(e,t=24,n=`currentColor`,r=2)=>{let i=nn.get(e);if(i)return Jt(i,t,n,r);if(tn.includes(e)){fn&&=!1;let i=pn(t,n,r);if(rn.size>=500){let e=rn.values().next().value;e&&rn.delete(e)}return rn.add({el:i,name:e,size:t,color:n,strokeWidth:r}),G(),i}return console.warn(`Lucide icon "${e}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null}}));mn(),dn(qt);function hn(e){if(e.length===0)return`0:empty`;let t=e.map(e=>[e.name,e.description??``,e.parametersSchema?JSON.stringify(e.parametersSchema):``,e.origin??``,e.annotations?JSON.stringify(e.annotations):``].join(``)).sort();return`${e.length}:${_n(t.join(``))}`}function gn(e,t){let n=3735928559^t,r=1103547991^t;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function _n(e){return`${gn(e,0).toString(36)}.${gn(e,2654435761).toString(36)}`}var vn,yn,bn,xn,Sn,Cn,wn,Tn,En=W((()=>{vn=`webmcp:`,yn=/* @__PURE__ */ new Map,bn=e=>{yn.clear();for(let t of e){let e=t.title?.trim();e&&yn.set(t.name,e)}},xn=e=>yn.get(Cn(e)),Sn=null,Cn=e=>e.startsWith(`webmcp:`)?e.slice(7):e,wn=e=>e.startsWith(vn),Tn=()=>Sn?Sn():import(`@mcp-b/webmcp-polyfill`)}));function Dn(e){return e===`card`?`collapsed`:e}function On(e){return e.split(`;`,1)[0].trim().toLowerCase()}function kn(e,t){if(!e)return;let n=Object.entries(e);for(let[e,r]of n)if(On(e)===t)return{mode:Dn(r),selector:On(e)};let r=`${t.split(`/`,1)[0]}/*`;for(let[e,t]of n)if(On(e)===r)return{mode:Dn(t),selector:r}}function An(e,t){let n=e?.display,r=typeof n==`string`?{default:n}:n??{};if(t.file&&r.files){if(typeof r.files==`string`)return{mode:Dn(r.files),matchedBy:{type:`files`}};let e=t.file.mimeType?On(t.file.mimeType):void 0,n=e?kn(r.files.byMediaType,e):void 0;if(e&&n)return{mode:n.mode,matchedBy:{type:`mediaType`,mediaType:e,selector:n.selector}};if(r.files.default)return{mode:Dn(r.files.default),matchedBy:{type:`files`}}}let i=r.byKind?.[t.artifactType];if(i)return{mode:Dn(i),matchedBy:{type:`kind`,kind:t.artifactType,configuredBy:`byKind`}};let a=r.byType?.[t.artifactType];if(a)return{mode:Dn(a),matchedBy:{type:`kind`,kind:t.artifactType,configuredBy:`byType`}};let o=t.presentation?.preferredMode;return o?{mode:Dn(o),matchedBy:{type:`preferredMode`}}:r.default?{mode:Dn(r.default),matchedBy:{type:`default`}}:{mode:`panel`,matchedBy:{type:`personaDefault`}}}function jn(e,t){return An(e,t).mode}function Mn(e,t){return JSON.stringify({component:e===`inline`?`PersonaArtifactInline`:`PersonaArtifactCard`,props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e===`inline`&&t.component?{component:t.component}:{},...e===`inline`&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown===void 0?{}:{markdown:t.markdown}}})}var Nn=W((()=>{})),Pn,Fn,In,Ln,Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn,$n,er=W((()=>{Pn=e=>e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`),Fn=e=>{if(e===null)return`null`;if(e===void 0)return``;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},In=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs===void 0?Math.max(0,t-n):e.durationMs)/1e3;return r<.1?`Thought for <0.1 seconds`:`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,``)} seconds`},Ln=e=>e.status===`complete`?In(e):e.status===`pending`?`Waiting`:``,Rn=(e,t)=>{let n=t?.durationMs??15e3,r=t?.chars??1200;return typeof e.durationMs==`number`?e.durationMs<n:(e.chunks??[]).join(``).length<r},zn=e=>{let t=(typeof e.duration==`number`?e.duration:typeof e.durationMs==`number`?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return t<.1?`Used tool for <0.1 seconds`:`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,``)} seconds`},Bn=e=>e.status===`complete`?zn(e):`Using tool...`,Vn=e=>{let t=e/1e3;return t<.1?`<0.1s`:t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,``)}s`},Hn=e=>{if(e.interrupted&&e.duration===void 0&&e.durationMs===void 0&&(e.startedAt===void 0||e.completedAt===void 0))return``;let t=typeof e.duration==`number`?e.duration:typeof e.durationMs==`number`?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Vn(t)},Un=e=>{let t=e.durationMs===void 0?Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())):e.durationMs;return Vn(t)},Wn=(e,t,n)=>{if(!t)return n;let r=e.name?.trim()||`tool`,i=Hn(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,i)},Gn=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],i=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,o;for(;(o=i.exec(n))!==null;)o.index>a&&Kn(r,n.slice(a,o.index),[]),o[1]===void 0?o[2]===void 0?o[3]!==void 0&&Kn(r,o[3],[`dim`]):Kn(r,o[2],[`italic`]):Kn(r,o[1],[`bold`]),a=o.index+o[0].length;return a<n.length&&Kn(r,n.slice(a),[]),r},Kn=(e,t,n)=>{let r=t.split(`{duration}`);for(let t=0;t<r.length;t++)r[t]&&e.push({text:r[t],styles:n}),t<r.length-1&&e.push({text:`{duration}`,styles:n,isDuration:!0})},qn=()=>{let e=null,t=0,n=e=>{let t=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/);if(t&&t[1])try{return t[1].replace(/\\n/g,`
|
|
3
3
|
`).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`)}catch{return t[1]}let n=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/);if(n&&n[1])try{return n[1].replace(/\\n/g,`
|
|
4
|
-
`).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`)}catch{return n[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e===null?null:{text:e,raw:r};let i=r.trim();if(!i.startsWith(`{`)&&!i.startsWith(`[`))return null;let a=n(r);return a!==null&&(e=a),t=r.length,e===null?null:{text:e,raw:r}},close:async()=>{}}},Jn=e=>{try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.text==`string`)return t.text}catch{return null}return null},Yn=()=>{let e={processChunk:e=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Xn=()=>{let e=qn();return{processChunk:async t=>{let n=t.trim();return!n.startsWith(`{`)&&!n.startsWith(`[`)?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Zn=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith(`{`)&&!r.startsWith(`[`))return null;if(n.length<=t)return e!==null||e===``?{text:e||``,raw:n}:null;try{let t=kt(n,Ot|Dt);t&&typeof t==`object`&&(t.component&&typeof t.component==`string`?e=typeof t.text==`string`?Pn(t.text):``:t.type===`init`&&t.form?e=``:typeof t.text==`string`&&(e=Pn(t.text)))}catch{}return t=n.length,e===null?null:{text:e,raw:n}},close:()=>{}}},Qn=e=>{let t=null,n=0,r=e||(e=>{if(!e||typeof e!=`object`)return null;let t=e=>typeof e==`string`?Pn(e):null;if(e.component&&typeof e.component==`string`)return typeof e.text==`string`?Pn(e.text):``;if(e.type===`init`&&e.form)return``;if(e.action)switch(e.action){case`nav_then_click`:return t(e.on_load_text)||t(e.text)||null;case`message`:case`message_and_click`:case`checkout`:return t(e.text)||null;default:return t(e.text)||t(e.display_text)||t(e.message)||null}return t(e.text)||t(e.display_text)||t(e.message)||t(e.content)||null});return{getExtractedText:()=>t,processChunk:e=>{let i=e.trim();if(!i.startsWith(`{`)&&!i.startsWith(`[`))return null;if(e.length<=n)return t===null?null:{text:t,raw:e};try{let n=kt(e,Ot|Dt),i=r(n);i!==null&&(t=i)}catch{}return n=e.length,{text:t||``,raw:e}},close:()=>{}}},$n=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith(`<`))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}}})),q,J,tr,Y=W((()=>{q=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},J=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[e,n]of Object.entries(t.attrs))r.setAttribute(e,n);if(t.style){let e=r.style,n=t.style;for(let t of Object.keys(n)){let r=n[t];r!=null&&(e[t]=r)}}let i=n.filter(e=>e!=null);return i.length>0&&r.append(...i),r},tr=(...e)=>e.filter(Boolean).join(` `)})),nr,rr,ir,ar,or,sr,cr,lr,ur,dr,fr,pr,mr,hr,gr,_r,vr,yr,br,X,xr,Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr,Nr,Pr,Fr,Ir,Lr,Rr,zr,Br,Vr,Hr,Ur,Wr,Gr,Kr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti=W((()=>{Y(),nr=`ask_user_question`,rr=`data-persona-ask-sheet-for`,ir=`Other`,ar=`Other…`,or=`Type your own answer here`,sr=`Send`,cr=`Next`,lr=`Back`,ur=`Submit all`,dr=`Skip`,fr=3,pr=`data-ask-current-index`,mr=`data-ask-question-count`,hr=`data-ask-answers`,gr=`data-ask-grouped`,_r=`data-ask-layout`,vr=e=>e.layout===`pills`?`pills`:`rows`,yr=e=>e.getAttribute(`data-ask-layout`)===`pills`?`pills`:`rows`,br=!1,X=e=>e.replace(/["\\]/g,`\\$&`),xr=e=>e.variant===`tool`&&!!e.toolCall&&e.toolCall.name===`ask_user_question`,Sr=e=>e?.features?.askUserQuestion??{},Cr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status===`complete`;if(t.args&&typeof t.args==`object`)return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let e=r.join(``),t=kt(e,Ot|Dt|Et);if(t&&typeof t==`object`)return{payload:t,complete:n}}catch{}return{payload:null,complete:n}},wr=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!br&&(br=!0,typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},Tr=e=>wr(e)[0]??null,Er=(e,t)=>wr(e)[t]??null,Dr=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty(`--persona-ask-sheet-bg`,n.sheetBackground),n.sheetBorder&&e.style.setProperty(`--persona-ask-sheet-border`,n.sheetBorder),n.sheetShadow&&e.style.setProperty(`--persona-ask-sheet-shadow`,n.sheetShadow),n.pillBackground&&e.style.setProperty(`--persona-ask-pill-bg`,n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty(`--persona-ask-pill-bg-selected`,n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty(`--persona-ask-pill-fg`,n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty(`--persona-ask-pill-fg-selected`,n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty(`--persona-ask-pill-radius`,n.pillBorderRadius),n.customInputBackground&&e.style.setProperty(`--persona-ask-input-bg`,n.customInputBackground))},Or=(e,t,n)=>{if(e!==`rows`)return null;let r=q(`span`,`persona-ask-row-affordance`);if(r.setAttribute(`aria-hidden`,`true`),t){let e=q(`span`,`persona-ask-row-check`);r.appendChild(e)}else{let e=q(`span`,`persona-ask-row-badge`);e.textContent=String(n+1),r.appendChild(e)}return r},kr=(e,t,n,r)=>{let i=q(`button`,n===`rows`?`persona-ask-pill persona-ask-row persona-pointer-events-auto`:`persona-ask-pill persona-pointer-events-auto`);if(i.type=`button`,i.setAttribute(`role`,r?`checkbox`:`button`),i.setAttribute(`aria-pressed`,`false`),i.setAttribute(`data-ask-user-action`,`pick`),i.setAttribute(`data-option-index`,String(t)),i.setAttribute(`data-option-label`,e.label),n===`rows`){let a=q(`span`,`persona-ask-row-content`),o=q(`span`,`persona-ask-row-label`);if(o.textContent=e.label,a.appendChild(o),e.description){let t=q(`span`,`persona-ask-row-description`);t.textContent=e.description,a.appendChild(t)}i.appendChild(a);let s=Or(n,r,t);s&&i.appendChild(s)}else i.textContent=e.label,e.description&&(i.title=e.description);return i},Ar=e=>{let t=q(`span`,e===`rows`?`persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none`:`persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none`);return t.setAttribute(`aria-hidden`,`true`),t},jr=(e,t,n,r)=>{let i=q(`div`,r===`rows`?`persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2`:`persona-ask-pills persona-flex persona-flex-wrap persona-gap-2`);i.setAttribute(`role`,`group`),i.setAttribute(`data-ask-pill-list`,`true`);let a=!!e?.multiSelect,o=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&typeof e.label==`string`&&e.label.length>0);if(o.length===0&&!n){for(let e=0;e<fr;e++)i.appendChild(Ar(r));return i}if(o.forEach((e,t)=>{i.appendChild(kr(e,t,r,a))}),e?.allowFreeText!==!1){let e=r===`rows`?ir:ar;if(r===`rows`){let n=q(`div`,`persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto`);n.setAttribute(`data-ask-user-action`,`focus-free-text`),n.setAttribute(`data-option-index`,String(o.length)),n.setAttribute(`data-ask-other-row`,`true`);let s=q(`span`,`persona-ask-row-content`),c=document.createElement(`input`);c.type=`text`,c.className=`persona-ask-row-input persona-flex-1 persona-pointer-events-auto`,c.placeholder=t.freeTextPlaceholder??or,c.setAttribute(`data-ask-free-text-input`,`true`),c.setAttribute(`aria-label`,t.freeTextLabel??e),s.appendChild(c),n.appendChild(s);let l=Or(r,a,o.length);l&&n.appendChild(l),i.appendChild(n)}else{let n=q(`button`,`persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto`);n.type=`button`,n.setAttribute(`data-ask-user-action`,`open-free-text`),n.textContent=t.freeTextLabel??e,i.appendChild(n)}}return i},Mr=(e,t)=>{let n=q(`div`,t===`rows`?`persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2`:`persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2`);n.setAttribute(`data-ask-free-text-row`,`true`);let r=document.createElement(`input`);if(r.type=`text`,r.className=`persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto`,r.placeholder=e.freeTextPlaceholder??or,r.setAttribute(`data-ask-free-text-input`,`true`),n.appendChild(r),t!==`rows`){let t=q(`button`,`persona-ask-free-text-submit persona-pointer-events-auto`);t.type=`button`,t.textContent=e.submitLabel??sr,t.setAttribute(`data-ask-user-action`,`submit-free-text`),n.appendChild(t)}return n},Nr=e=>{let t=q(`div`,`persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2`);t.setAttribute(`data-ask-multi-actions`,`true`);let n=q(`button`,`persona-ask-multi-submit persona-pointer-events-auto`);return n.type=`button`,n.textContent=e.submitLabel??sr,n.setAttribute(`data-ask-user-action`,`submit-multi`),n.disabled=!0,t.appendChild(n),t},Pr=(e,t,n)=>{let r=q(`div`,`persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2`);r.setAttribute(`data-ask-nav-row`,`true`);let i=q(`button`,`persona-ask-nav-back persona-pointer-events-auto`);i.type=`button`,i.textContent=n.backLabel??lr,i.setAttribute(`data-ask-user-action`,`back`),i.disabled=e===0,r.appendChild(i);let a=q(`div`,`persona-ask-nav-right persona-flex persona-items-center persona-gap-2`),o=q(`button`,`persona-ask-nav-skip persona-pointer-events-auto`);o.type=`button`,o.textContent=n.skipLabel??dr,o.setAttribute(`data-ask-user-action`,`skip`),a.appendChild(o);let s=q(`button`,`persona-ask-nav-next persona-pointer-events-auto`);s.type=`button`;let c=e===t-1;return s.textContent=c?n.submitAllLabel??ur:n.nextLabel??cr,s.setAttribute(`data-ask-user-action`,c?`submit-all`:`next`),s.disabled=!0,a.appendChild(s),r.appendChild(a),r},Fr=e=>{let t=e.getAttribute(hr);if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e==`object`?e:{}}catch{return{}}},Ir=(e,t)=>{e.setAttribute(hr,JSON.stringify(t))},Lr=e=>{let t=Number(e.getAttribute(`data-ask-current-index`)??`0`);return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Rr=(e,t)=>{e.setAttribute(pr,String(Math.max(0,Math.floor(t))))},zr=e=>{let t=Number(e.getAttribute(`data-ask-question-count`)??`1`);return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Br=e=>e.getAttribute(gr)===`true`,Vr=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!=`object`)return{};let r={};return t.forEach((e,t)=>{let i=typeof e?.question==`string`?e.question:``;if(i&&Object.prototype.hasOwnProperty.call(n,i)){let e=n[i];(typeof e==`string`||Array.isArray(e))&&(r[t]=e)}}),r},Hr=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!=`number`||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Ur=(e,t)=>{let{payload:n}=Cr(t),r=wr(n),i=Fr(e),a={},o=/* @__PURE__ */ new Set;return r.forEach((e,t)=>{let n=typeof e?.question==`string`?e.question:``;n&&(o.has(n)&&typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${n}"; later answer wins.`),o.add(n),Object.prototype.hasOwnProperty.call(i,t)&&(a[n]=i[t]))}),a},Wr=e=>{let t=Fr(e)[Lr(e)],n=/* @__PURE__ */ new Set;typeof t==`string`?n.add(t):Array.isArray(t)&&t.forEach(e=>n.add(e));let r=e.querySelectorAll(`[data-ask-user-action="pick"][data-option-label]`);r.forEach(e=>{let t=e.getAttribute(`data-option-label`)??``,r=n.has(t);e.setAttribute(`aria-pressed`,r?`true`:`false`),e.classList.toggle(`persona-ask-pill-selected`,r)});let i=new Set(Array.from(r).map(e=>e.getAttribute(`data-option-label`)??``)),a=e.querySelector(`[data-ask-free-text-input="true"]`);a&&(typeof t==`string`&&t.length>0&&!i.has(t)?(a.value=t,a.closest(`[data-ask-free-text-row="true"]`)?.classList.remove(`persona-hidden`)):a.value=``)},Gr=e=>{if(!Br(e))return;let t=Fr(e)[Lr(e)],n=typeof t==`string`&&t.length>0||Array.isArray(t)&&t.length>0,r=e.querySelector(`[data-ask-user-action="next"], [data-ask-user-action="submit-all"]`);r&&(r.disabled=!n);let i=e.querySelector(`[data-ask-user-action="submit-multi"]`);i&&(i.disabled=Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).length===0)},Kr=(e,t,n)=>{let r=Sr(n),i=yr(e),{payload:a,complete:o}=Cr(t),s=Br(e),c=Lr(e),l=zr(e),u=s?Er(a,c):Tr(a),d=!!u?.multiSelect,f=e.querySelector(`[data-ask-step-inline="true"]`);f&&(f.textContent=s?`${c+1}/${l}`:``);let p=e.querySelector(`[data-ask-stepper="true"]`);p&&p.remove();let m=e.querySelector(`[data-ask-question="true"]`);if(m){let e=typeof u?.question==`string`?u.question:``;m.textContent=e,m.classList.toggle(`persona-ask-question-skeleton`,!e&&!o)}let h=e.querySelector(`[data-ask-pill-list="true"]`);if(h){let e=jr(u,r,o,i);h.replaceWith(e)}if(i!==`rows`){let t=e.querySelector(`[data-ask-free-text-row="true"]`);t&&t.replaceWith(Mr(r,i))}let g=e.querySelector(`[data-ask-multi-actions="true"]`);!s&&d&&!g?e.appendChild(Nr(r)):(!d||s)&&g&&g.remove(),e.setAttribute(`data-multi-select`,d?`true`:`false`);let _=e.querySelector(`[data-ask-nav-row="true"]`);if(s){let t=Pr(c,l,r);_?_.replaceWith(t):e.appendChild(t)}else _&&_.remove();Wr(e),Gr(e)},qr=(e,t,n)=>{let r=Sr(t),i=vr(r),a=e.toolCall.id,o=wr(n),s=Math.max(1,o.length),c=s>1,l=Vr(e,o),u=c?Hr(e,s):0,d=q(`div`,[`persona-ask-sheet`,`persona-ask-sheet--${i}`,`persona-pointer-events-auto`,`persona-ask-sheet-enter`].join(` `));d.setAttribute(rr,a),d.setAttribute(`data-tool-call-id`,a),d.setAttribute(`data-message-id`,e.id),d.setAttribute(mr,String(s)),d.setAttribute(pr,String(u)),d.setAttribute(gr,c?`true`:`false`),d.setAttribute(_r,i),Ir(d,l),d.setAttribute(`role`,`group`),d.setAttribute(`aria-label`,`Suggested answers`),r.slideInMs!==void 0&&d.style.setProperty(`--persona-ask-sheet-duration`,`${r.slideInMs}ms`),Dr(d,r);let f=q(`div`,`persona-ask-sheet-header persona-flex persona-items-center persona-gap-3`),p=q(`div`,`persona-ask-sheet-question persona-flex-1`);p.setAttribute(`data-ask-question`,`true`),p.textContent=``,f.appendChild(p);let m=q(`span`,`persona-ask-sheet-step-inline`);m.setAttribute(`data-ask-step-inline`,`true`),m.textContent=``,f.appendChild(m),d.appendChild(f);let h=q(`div`,i===`rows`?`persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2`:`persona-ask-pills persona-flex persona-flex-wrap persona-gap-2`);return h.setAttribute(`data-ask-pill-list`,`true`),h.setAttribute(`role`,`group`),d.appendChild(h),i!==`rows`&&d.appendChild(Mr(r,i)),Kr(d,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>d.classList.remove(`persona-ask-sheet-enter`))}),d},Jr=(e,t,n)=>{let{payload:r}=Cr(t),i=Math.max(1,wr(r).length);i>zr(e)&&(e.setAttribute(mr,String(i)),i>1&&!Br(e)&&e.setAttribute(gr,`true`)),Kr(e,t,n)},Yr=(e,t)=>{let n=q(`div`,`persona-ask-stub persona-inline-flex persona-items-center persona-gap-2`);n.id=`bubble-${e.id}`,n.setAttribute(`data-message-id`,e.id),n.setAttribute(`data-bubble-type`,`ask-user-question`);let r=Sr(t);Dr(n,r);let i=q(`span`,`persona-ask-stub-label`),{complete:a}=Cr(e);return i.textContent=a?`Awaiting your response…`:`Preparing options…`,n.appendChild(i),n},Xr=(e,t,n)=>{if(!n||!xr(e)||Sr(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${rr}]`).forEach(e=>{e.getAttribute(rr)!==r&&e.remove()});let i=n.querySelector(`[${rr}="${X(r)}"]`);if(i){Jr(i,e,t);return}let{payload:a}=Cr(e),o=qr(e,t,a);n.appendChild(o)},Zr=(e,t)=>{if(!e)return;let n=t?`[${rr}="${X(t)}"]`:`[${rr}]`;e.querySelectorAll(n).forEach(e=>{e.classList.add(`persona-ask-sheet-leave`);let t=Number.parseInt(getComputedStyle(e).getPropertyValue(`--persona-ask-sheet-duration`)||`180`,10);setTimeout(()=>e.remove(),Number.isFinite(t)?t:180)})},Qr=e=>Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).map(e=>e.getAttribute(`data-option-label`)).filter(e=>typeof e==`string`&&e.length>0),$r=(e,t)=>{let n=Fr(e),r=Lr(e);typeof t==`string`&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Ir(e,n),Wr(e),Gr(e)},ei=(e,t,n,r)=>{let i=zr(e),a=Math.max(0,Math.min(i-1,r));Rr(e,a),Kr(e,t,n)}})),ni,ri,ii,ai,oi,si,ci,li,ui,di,fi=W((()=>{ni=`suggest_replies`,ri={type:`object`,properties:{suggestions:{type:`array`,minItems:1,maxItems:4,description:`1-4 short, distinct follow-up replies, phrased in the user's voice.`,items:{type:`object`,properties:{label:{type:`string`,minLength:1,maxLength:80},prompt:{type:`string`,minLength:1,maxLength:500},description:{type:`string`,minLength:1,maxLength:160}},required:[`label`],additionalProperties:!1}}},required:[`suggestions`],additionalProperties:!1},ii={name:ni,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:ri,origin:`sdk`,annotations:{readOnlyHint:!0}},ai=()=>({content:[{type:`text`,text:`Suggestions shown to the user.`}]}),oi=e=>e.variant===`tool`&&e.toolCall?.name===`suggest_replies`,si=e=>{let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let r=n.flatMap(e=>{if(typeof e==`string`){let t=e.trim();return t?[t]:[]}if(!e||typeof e!=`object`)return[];let t=e;if(typeof t.label!=`string`||!t.label.trim())return[];let n={label:t.label.trim()};return typeof t.prompt==`string`&&t.prompt.trim()&&(n.prompt=t.prompt.trim()),typeof t.description==`string`&&t.description.trim()&&(n.description=t.description.trim()),[n]});return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},ci=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return null;if(!oi(n))continue;let r=si(n.toolCall?.args);return r.length>0?r:null}return null},li=/* @__PURE__ */ new Set,ui=(e,t,n)=>{let r=`${e}:${t}:${n}`;li.has(r)||(li.add(r),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},di=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,r=e=>{let r=t?.[e],i=n?.[e];r!==void 0&&i!==void 0&&r!==i&&ui(e,i,r)};e&&(r(`enabled`),r(`expose`));let i=t?.enabled??n?.enabled??!0;return{enabled:i,expose:i?t?.expose??n?.expose??!1:!1}}})),pi,mi,hi,Z=W((()=>{ti(),fi(),pi={type:`object`,properties:{questions:{type:`array`,minItems:1,maxItems:8,description:`Questions to ask the user. Prefer a single question.`,items:{type:`object`,properties:{question:{type:`string`,description:`The complete question, ending with a question mark.`},header:{type:`string`,maxLength:12,description:`Short topic label, e.g. "Auth method".`},options:{type:`array`,minItems:2,maxItems:4,description:`2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.`,items:{type:`object`,properties:{label:{type:`string`,description:`Concise choice text (1-5 words).`},description:{type:`string`,description:`What the option means or implies.`}},required:[`label`],additionalProperties:!1}},multiSelect:{type:`boolean`,description:`Allow selecting multiple options. Default false.`},allowFreeText:{type:`boolean`,description:`Show a free-text input. Default true.`}},required:[`question`,`options`],additionalProperties:!1}}},required:[`questions`],additionalProperties:!1},mi={name:nr,description:`Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.`,parametersSchema:pi,origin:`sdk`,annotations:{readOnlyHint:!0}},hi=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(mi),di(e).expose&&t.push(ii),t}})),gi,_i,vi,yi=W((()=>{gi={idle:`Online`,connecting:`Connecting…`,connected:`Streaming…`,error:`Offline`,paused:`Connection lost…`,resuming:`Reconnecting…`},_i=1e5,vi=100001}));async function bi(e,t,n){let r={"Content-Type":`application/json`,...e.headers};e.getHeaders&&Object.assign(r,await e.getHeaders());let i={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},a=(t,n)=>fetch(`${e.clientApiBase()}${t}`,{method:`POST`,headers:r,body:JSON.stringify({...n,...i})}),o=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return a(o);let{sessionId:s}=await e.initSession(),c=await a(`/v1/client/approve`,{sessionId:s});if(c.status===404){let e=await c.clone().json().catch(()=>null);if(!e||e.error===`Not Found`)return a(o)}return c}async function xi(e,t,n,r){let i=e.isClientTokenMode(),a=i?e.getClientApiUrl(`resume`):`${e.config.apiUrl?.replace(/\/+$/,``)||`https://api.runtype.com`}/resume`,o,s=null;if(i){let t=await e.initSession();o=t.sessionId,t.durableRecovery?.enabled===!0&&(s=await e.readVisitorToken())}let c={"Content-Type":`application/json`,...s?{"X-Visitor-Token":s}:{},...e.headers};e.getHeaders&&Object.assign(c,await e.getHeaders());let l={executionId:t,toolOutputs:n,streamResponse:r?.streamResponse??!0,...r?.after?{after:r.after}:{}};if(o&&(l.sessionId=o),i&&o){let t=[...hi(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:n,commit:i}=await e.sendWithClientToolsDiff(o,t,t=>{let n={...l,...t};return e.debug&&console.debug(`[AgentWidgetClient] client token resume`,n),fetch(a,{method:`POST`,headers:c,body:JSON.stringify(n),signal:r?.signal})},{emptyMeansReplace:!0});return n.ok&&i(),n}return fetch(a,{method:`POST`,headers:c,body:JSON.stringify(l),signal:r?.signal})}var Si=W((()=>{Z(),yi()})),Ci=/* @__PURE__ */ Mt({preferFinalStructuredContent:()=>Ti,resolveApproval:()=>bi,resumeFlow:()=>xi,streamResponse:()=>Di});function wi(e){let t=e.toLowerCase(),n={"application/pdf":`pdf`,"application/json":`json`,"application/zip":`zip`,"text/plain":`txt`,"text/csv":`csv`,"text/markdown":`md`}[t];if(n)return`attachment.${n}`;let r=t.indexOf(`/`);if(r>0){let e=t.slice(r+1).split(`;`)[0]?.trim()??``;if(e&&e!==`octet-stream`&&/^[a-z0-9.+-]+$/i.test(e))return`attachment.${e}`}return`attachment`}function Ti(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let i=Oi(n);if(!Oi(r))return e;if(!i||r===n||r.startsWith(n))return t;let a=Jn(e);return Jn(t)!==null&&a===null?t:e}async function Ei(e,t,n,r,i,a,o){if(!e.parseSSEEvent)return!1;try{let s=await e.parseSSEEvent(t);if(s===null)return!1;let c=e=>{let t={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`assistant`,sequence:a(),...e!==void 0&&{partId:e}};return r.current=t,i(t),t},l=e=>r.current?r.current:c(e);if(s.text!==void 0){s.partId!==void 0&&o.current!==null&&s.partId!==o.current&&(r.current&&(r.current.streaming=!1,i(r.current)),c(s.partId)),s.partId!==void 0&&(o.current=s.partId);let e=l(s.partId);s.partId!==void 0&&!e.partId&&(e.partId=s.partId),e.content+=s.text,i(e)}return s.done&&(r.current&&(r.current.streaming=!1,i(r.current)),o.current=null,n({type:`status`,status:`idle`})),s.error&&(o.current=null,n({type:`error`,error:Error(s.error)})),!0}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] parseSSEEvent error:`,e),!1}}async function Di(e,t,n,r,i){let a=t.getReader(),o=new TextDecoder,s=``,c=Date.now(),l=0,u=()=>c+l++,d=e=>{let t=e.reasoning?{...e.reasoning,chunks:[...e.reasoning.chunks]}:void 0,n=e.toolCall?{...e.toolCall,chunks:e.toolCall.chunks?[...e.toolCall.chunks]:void 0}:void 0,r=e.tools?e.tools.map(e=>({...e,chunks:e.chunks?[...e.chunks]:void 0})):void 0;return{...e,reasoning:t,toolCall:n,tools:r}},f=e=>{if(e.role!==`assistant`||e.variant)return!0;let t=Array.isArray(e.contentParts)&&e.contentParts.length>0,n=typeof e.rawContent==`string`&&e.rawContent.trim()!==``;return typeof e.content==`string`&&e.content.trim()!==``||t||n||!!e.stopReason},p=e=>{f(e)&&n({type:`message`,message:d(e)})},m=null,h=null,g={current:null},_={current:null},v=null,y=``,b=/* @__PURE__ */ new Map,x=/* @__PURE__ */ new Map,S=/* @__PURE__ */ new Map,C=/* @__PURE__ */ new Map,w=/* @__PURE__ */ new Map,T=r,E=!1,D=()=>{if(m)return m;let e,t=``,n=v;return!E&&T?(e=T,E=!0,t=i??``):e=T&&n?`${T}_${n}`:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:e,role:`assistant`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u()},p(m),m},O=e=>{let t=C.get(e);if(t)return t;let n={id:`reason-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`reasoning`,sequence:u(),reasoning:{id:e,status:`streaming`,chunks:[]}};return C.set(e,n),p(n),n},k=/* @__PURE__ */ new Set,ee=/* @__PURE__ */ new Map,A=/* @__PURE__ */ new Set,te=/* @__PURE__ */ new Map,ne=e=>{if(!e)return!1;let t=e.replace(/_+/g,`_`).replace(/^_|_$/g,``);return t===`emit_artifact_markdown`||t===`emit_artifact_component`},re=e=>{let t=w.get(e);if(t)return t;let n={id:`tool-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`tool`,sequence:u(),toolCall:{id:e,status:`pending`}};return w.set(e,n),p(n),n},ie=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`){let t=Number(e);if(!Number.isNaN(t)&&Number.isFinite(t))return t;let n=Date.parse(e);if(!Number.isNaN(n))return n}return Date.now()},ae=e=>{if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)}catch{return String(e)}},oe=/* @__PURE__ */ new Map,j=/* @__PURE__ */ new Map,se=(e,t)=>{let n=ae(t),r=Ti(j.get(e.id),n);e.rawContent=r;let i=oe.get(e.id),a=t=>{let n=e.content??``;t.trim()!==``&&(n.trim().length===0||t.startsWith(n)||t.trimStart().startsWith(n.trim()))&&(e.content=t)},o=()=>{if(i){let e=i.close?.();e instanceof Promise&&e.catch(()=>{})}oe.delete(e.id),j.delete(e.id),e.streaming=!1,p(e)};if(!i){a(n),o();return}let s=Jn(r);if(s!==null&&s.trim()!==``){a(s),o();return}let c=e=>{let t=typeof e==`string`?e:e?.text??null;if(t!==null&&t.trim()!==``)return t;let r=i.getExtractedText();return r!==null&&r.trim()!==``?r:n},l;try{l=i.processChunk(r)}catch{a(n),o();return}l instanceof Promise?l.then(e=>{a(c(e)),o()}).catch(()=>{a(n),o()}):(a(c(l)),o())},ce=null,le=(t,n,r,i)=>{t.rawContent=n,oe.has(t.id)||oe.set(t.id,e.createStreamParser());let a=oe.get(t.id),o=n.trim().startsWith(`{`)||n.trim().startsWith(`[`);if(o&&j.set(t.id,n),a.__isPlainTextParser===!0){t.content=i===void 0?t.content+r:n,j.delete(t.id),oe.delete(t.id),t.rawContent=void 0,p(t);return}let s=a.processChunk(n);if(s instanceof Promise)s.then(e=>{let a=typeof e==`string`?e:e?.text??null;a!==null&&a.trim()!==``?(t.content=a,p(t)):!o&&!n.trim().startsWith(`<`)&&(t.content=i===void 0?t.content+r:n,j.delete(t.id),oe.delete(t.id),t.rawContent=void 0,p(t))}).catch(()=>{t.content=i===void 0?t.content+r:n,j.delete(t.id),oe.delete(t.id),t.rawContent=void 0,p(t)});else{let e=typeof s==`string`?s:s?.text??null;e!==null&&e.trim()!==``?(t.content=e,p(t)):!o&&!n.trim().startsWith(`<`)&&(t.content=i===void 0?t.content+r:n,j.delete(t.id),oe.delete(t.id),t.rawContent=void 0,p(t))}},ue=(e,t)=>{let n=t??e.content;if(n==null||n===``){e.streaming=!1,p(e);return}let r=j.get(e.id)??ae(n);e.rawContent=r;let i=oe.get(e.id),a=null,o=!1;if(i&&(a=i.getExtractedText(),a===null&&(a=Jn(r)),a===null)){let t=i.processChunk(r);t instanceof Promise?(o=!0,t.then(t=>{let n=typeof t==`string`?t:t?.text??null;n!==null&&(e.content=n,e.streaming=!1,oe.delete(e.id),j.delete(e.id),p(e))}).catch(()=>{})):a=typeof t==`string`?t:t?.text??null}if(!o){a!==null&&a.trim()!==``?e.content=a:j.has(e.id)||(e.content=ae(n));let t=oe.get(e.id);if(t){let n=t.close?.();n instanceof Promise&&n.catch(()=>{}),oe.delete(e.id)}j.delete(e.id),e.streaming=!1,p(e)}},de=(e,t,n)=>{let r=x.get(e);if(r)return r;let i={id:`nested-${t}-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u(),...n?{variant:n}:{},...n===`reasoning`?{reasoning:{id:e,status:`streaming`,chunks:[]}}:{},agentMetadata:{parentToolId:t}};return x.set(e,i),p(i),i},fe=[],pe,M=/* @__PURE__ */ new Map,me=0,he=`agent`,ge=!1,_e=null,ve=null,ye=e.config().iterationDisplay??`separate`;for(pe=()=>{for(let t=0;t<fe.length;t++){let r=fe[t];if(!ge&&he!==`flow`&&typeof r.stepType==`string`&&(he=`flow`),r.type===`reasoning_start`){let e=typeof r.id==`string`?r.id:null,t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){b.set(e,t),de(e,t,`reasoning`);continue}let n=r.id,i=O(n);i.reasoning=i.reasoning??{id:n,status:`streaming`,chunks:[]},i.reasoning.startedAt=i.reasoning.startedAt??Date.now(),i.reasoning.completedAt=void 0,i.reasoning.durationMs=void 0,(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),i.streaming=!0,i.reasoning.status=`streaming`,p(i)}else if(r.type===`reasoning_delta`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)&&x.has(e)){let t=x.get(e),n=r.delta;n&&t.reasoning&&(t.reasoning.chunks.push(String(n)),p(t));continue}let t=r.id,n=O(t);n.reasoning=n.reasoning??{id:t,status:`streaming`,chunks:[]},n.reasoning.startedAt=n.reasoning.startedAt??Date.now(),r.delta&&n.reasoning.chunks.push(r.delta),n.reasoning.status=`streaming`,n.streaming=!0,p(n)}else if(r.type===`reasoning_complete`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)&&x.has(e)){let t=x.get(e);if(t.reasoning){let e=typeof r.text==`string`?r.text:``;e&&t.reasoning.chunks.length===0&&t.reasoning.chunks.push(e),t.reasoning.status=`complete`,t.streaming=!1,p(t)}b.delete(e),x.delete(e);continue}let t=r.id,n=typeof r.text==`string`?r.text:``;!C.get(t)&&(n||r.scope===`loop`)&&O(t);let i=C.get(t);if(i?.reasoning){(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),n&&i.reasoning.chunks.length===0&&i.reasoning.chunks.push(n),i.reasoning.status=`complete`,i.reasoning.completedAt=Date.now();let e=i.reasoning.startedAt??Date.now();i.reasoning.durationMs=Math.max(0,(i.reasoning.completedAt??Date.now())-e),i.streaming=!1,p(i)}}else if(r.type===`tool_start`){m&&=(m.streaming=!1,p(m),null),typeof r.iteration==`number`&&(me=r.iteration);let e=r.toolCallId,t=r.toolName;if(ne(t)){k.add(e);continue}let n=re(e),i=n.toolCall??{id:e,status:`pending`};i.name=t??i.name,i.status=`running`,i.success=void 0,i.error=void 0,i.duration=void 0,r.parameters!==void 0&&(i.args=r.parameters),i.startedAt=i.startedAt??ie(r.startedAt),i.completedAt=void 0,i.durationMs=void 0,n.toolCall=i,n.streaming=!0,r.executionId&&(n.agentMetadata={executionId:r.executionId,iteration:r.iteration}),p(n)}else if(r.type===`tool_output_delta`){let e=r.toolCallId;if(k.has(e))continue;let t=re(e),n=t.toolCall??{id:e,status:`running`};n.startedAt=n.startedAt??Date.now();let i=r.delta;i&&(n.chunks=n.chunks??[],n.chunks.push(String(i))),n.status=`running`,t.toolCall=n,t.streaming=!0,r.executionId&&(t.agentMetadata=t.agentMetadata??{executionId:r.executionId,iteration:me}),p(t)}else if(r.type===`tool_complete`){let e=r.toolCallId;if(k.has(e)){k.delete(e);continue}let t=re(e),n=t.toolCall??{id:e,status:`running`};n.status=`complete`,r.result!==void 0&&(n.result=r.result),n.name=r.toolName??n.name,n.success=r.success,n.error=r.error,n.completedAt=Date.now();let i=r.executionTime;if(typeof i==`number`)n.durationMs=i,n.duration=i;else{let e=n.startedAt??Date.now();n.durationMs=Math.max(0,(n.completedAt??Date.now())-e)}t.toolCall=n,t.streaming=!1,r.executionId&&(t.agentMetadata=t.agentMetadata??{executionId:r.executionId,iteration:r.iteration??me}),p(t)}else if(r.type===`await`&&r.toolName){let e=typeof r.toolCallId==`string`&&r.toolCallId.length>0?r.toolCallId:void 0,t=e??r.toolId??`local-${u()}`,n=re(t),i=r.toolName,a=r.origin===`webmcp`&&!wn(i)?`webmcp:${i}`:i,o=wn(a),s=n.toolCall??{id:t,status:`pending`};s.name=a,s.args=r.parameters,s.status=o?`running`:`complete`,s.chunks=s.chunks??[],s.startedAt=s.startedAt??ie(r.awaitedAt),o?(s.completedAt=void 0,s.duration=void 0,s.durationMs=void 0):s.completedAt=s.completedAt??s.startedAt,n.toolCall=s,n.streaming=!1,n.agentMetadata={...n.agentMetadata,executionId:r.executionId??n.agentMetadata?.executionId,awaitingLocalTool:!0,...e?{webMcpToolCallId:e}:{}},p(n)}else if(r.type===`text_start`){let e=typeof r.id==`string`?r.id:null,t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){b.set(e,t);continue}let n=m;n&&(he===`flow`?(ue(n),ce=n):(n.streaming=!1,p(n)),m=null),v=typeof r.id==`string`?r.id:v,y=``}else if(r.type===`text_delta`){let e=typeof r.id==`string`?r.id:null,t=e?b.get(e):void 0;if(e&&t){let n=typeof r.delta==`string`?r.delta:``,i=(S.get(e)??``)+n;if(S.set(e,i),i.trim()===``)continue;let a=de(e,t);a.agentMetadata={...a.agentMetadata,executionId:r.executionId,parentToolId:t},le(a,i,n,void 0);continue}if(v=typeof r.id==`string`?r.id:v,he===`flow`){let e=typeof r.delta==`string`?r.delta:``;if(y+=e,y.trim()===``)continue;let t=D();t.agentMetadata={executionId:r.executionId,iteration:me},le(t,y,e,void 0),h=t;continue}let n=typeof r.delta==`string`?r.delta:``;y+=n;let i=D();i.agentMetadata={executionId:r.executionId,iteration:me,turnId:_e??void 0,agentName:ve?.agentName},le(i,y,n,void 0),h=i}else if(r.type===`text_complete`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)){let t=x.get(e);t&&ue(t),b.delete(e),S.delete(e),x.delete(e);continue}let t=m;t&&(he===`flow`?(ue(t),ce=t):((t.content??``)===``&&typeof r.text==`string`&&(t.content=r.text),t.streaming=!1,p(t)),m=null),v=null,y=``}else if(r.type===`step_complete`){if(r.stepType===`tool`)continue;if(r.success===!1){let e=r.error||`Step failed`;n({type:`error`,error:Error(e)});let t=m;t&&t.streaming&&(t.streaming=!1,p(t)),n({type:`status`,status:`idle`});continue}{let e=ce;ce=null;let t=r.stopReason,n=(r.result&&typeof r.result==`object`?r.result:null)?.response;if(e)t&&(e.stopReason=t),n==null?e.streaming!==!1&&(oe.delete(e.id),j.delete(e.id),e.streaming=!1,p(e)):se(e,n);else{let e=n!=null&&n!==``;if(e||t&&t!==`end_turn`&&t!==`unknown`){let r=D();t&&(r.stopReason=t),e?ue(r,n):(r.streaming=!1,p(r))}}continue}}else if(r.type===`execution_start`)he=r.kind===`flow`?`flow`:`agent`,ge=!0,he===`agent`&&(ve={executionId:r.executionId,agentId:r.agentId??`virtual`,agentName:r.agentName??``});else if(r.type===`turn_start`){let e=typeof r.iteration==`number`?r.iteration:me;if(e!==me){if(ye===`separate`&&e>1){let e=m;e&&(e.streaming=!1,p(e),m=null)}me=e}_e=typeof r.id==`string`?r.id:null,h=null}else if(r.type===`tool_input_delta`){let e=r.toolCallId;if(e){let t=w.get(e);t?.toolCall&&(t.toolCall.chunks=t.toolCall.chunks??[],t.toolCall.chunks.push(r.delta??``),p(t))}}else if(r.type===`tool_input_complete`){if(k.has(r.toolCallId))continue;let e=re(r.toolCallId),t=e.toolCall;t.args=r.parameters,t.name=r.toolName??t.name,p(e)}else if(r.type===`turn_complete`){let e=r.stopReason,t=m??h;if(e&&t!==null){let n=r.id;(!n||t.agentMetadata?.turnId===n)&&(t.stopReason=e,p(t))}_e===r.id&&(_e=null)}else if(r.type===`media_start`){let e=String(r.id);M.set(e,{mediaType:typeof r.mediaType==`string`?r.mediaType:void 0,toolCallId:r.toolCallId,parts:[]})}else if(r.type===`media_delta`){let e=M.get(String(r.id));e&&typeof r.delta==`string`&&e.parts.push(r.delta)}else if(r.type===`media_complete`){let e=String(r.id),t=M.get(e);M.delete(e);let n=(typeof r.mediaType==`string`?r.mediaType:void 0)??t?.mediaType??`application/octet-stream`,i=typeof r.data==`string`?r.data:void 0,a=typeof r.url==`string`?r.url:t&&t.parts.length>0?t.parts.join(``):void 0,o=null;if(i)o={type:`media`,data:i,mediaType:n};else if(a){let e=n.toLowerCase();o={type:e===`image`||e.startsWith(`image/`)?`image-url`:`file-url`,url:a,mediaType:n}}let s=r.toolCallId??t?.toolCallId,c=o?[o]:[],l=[];for(let e of c){if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.type==`string`?t.type:void 0,r=typeof t.mediaType==`string`?t.mediaType.toLowerCase():``,i=null,a=``;if(n===`media`){let e=typeof t.data==`string`?t.data:void 0;if(!e)continue;a=r.length>0?r:`application/octet-stream`,i=`data:${a};base64,${e}`}else if(n===`image-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else if(n===`file-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else continue;if(i){if(n===`image-url`||a.startsWith(`image/`))l.push({type:`image`,image:i,...a.includes(`/`)?{mimeType:a}:{}});else if(a.startsWith(`audio/`))l.push({type:`audio`,audio:i,mimeType:a});else if(a.startsWith(`video/`))l.push({type:`video`,video:i,mimeType:a});else{let e=a||`application/octet-stream`;l.push({type:`file`,data:i,mimeType:e,filename:wi(e)})}}}if(l.length>0){let e=u(),t=s,n={id:`agent-media-${typeof t==`string`&&t.length>0?`${t}-${e}`:String(e)}`,role:`assistant`,content:``,contentParts:l,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e,agentMetadata:{executionId:r.executionId,iteration:me}};p(n);let i=m;i&&(i.streaming=!1,p(i)),m=null,g.current=null}}else if(r.type===`execution_complete`){let e=m;e&&(r.kind===`flow`&&e.streaming!==!1?ue(e):(e.streaming=!1,p(e)),m=null),v=null,y=``,ce=null,n({type:`status`,status:`idle`,terminal:!0})}else if(r.type===`execution_error`){let e=typeof r.error==`string`?r.error:r.error?.message??`Execution error`;n({type:`error`,error:Error(e)})}else if(r.type!==`ping`){if(r.type===`approval_start`){let e=r.approvalId??`approval-${u()}`,t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:u(),approval:{id:e,status:`pending`,agentId:ve?.agentId??`virtual`,executionId:r.executionId??ve?.executionId??``,toolName:r.toolName??``,toolType:r.toolType,description:r.description??`Execute ${r.toolName??`tool`}`,...typeof r.reason==`string`&&r.reason?{reason:r.reason}:{},parameters:r.parameters,...typeof r.toolCallId==`string`&&r.toolCallId?{toolCallId:r.toolCallId}:{}}};p(t)}else if(r.type===`approval_complete`){let e=r.approvalId;if(e){let t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:u(),approval:{id:e,status:r.decision??`approved`,agentId:ve?.agentId??`virtual`,executionId:r.executionId??ve?.executionId??``,toolName:``,description:``,resolvedAt:Date.now()}};p(t)}}else if(r.type===`artifact_start`||r.type===`artifact_delta`||r.type===`artifact_update`||r.type===`artifact_complete`){if(r.type===`artifact_start`){let t=r.artifactType,i=String(r.id),a=typeof r.title==`string`?r.title:void 0,o=r.file,s;if(o&&typeof o==`object`&&!Array.isArray(o)&&typeof o.path==`string`&&typeof o.mimeType==`string`&&(s={path:o.path,mimeType:o.mimeType,...typeof o.language==`string`?{language:o.language}:{}}),n({type:`artifact_start`,id:i,artifactType:t,title:a,component:typeof r.component==`string`?r.component:void 0,...s?{file:s}:{}}),te.set(i,{markdown:``,title:a,file:s}),!A.has(i)){A.add(i);let n=jn(e.config().features?.artifacts,{artifactType:t,...s?{file:s}:{}}),o=typeof r.component==`string`?r.component:void 0,c={id:`artifact-ref-${i}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u(),rawContent:Mn(n,{artifactId:i,title:a,artifactType:t,status:`streaming`,...s?{file:s}:{},...o?{component:o}:{}})};ee.set(i,c),p(c)}}else if(r.type===`artifact_delta`){let e=String(r.id),t=typeof r.delta==`string`?r.delta:String(r.delta??``);n({type:`artifact_delta`,id:e,artDelta:t});let i=te.get(e);i&&(i.markdown+=t)}else if(r.type===`artifact_update`){let e=r.props&&typeof r.props==`object`&&!Array.isArray(r.props)?r.props:{};n({type:`artifact_update`,id:String(r.id),props:e,component:typeof r.component==`string`?r.component:void 0});let t=te.get(String(r.id));t&&(t.props={...t.props??{},...e})}else if(r.type===`artifact_complete`){let e=String(r.id);n({type:`artifact_complete`,id:e});let t=ee.get(e);if(t){t.streaming=!1;try{let n=JSON.parse(t.rawContent??`{}`);if(n.props){n.props.status=`complete`;let t=te.get(e);t?.markdown&&(n.props.markdown=t.markdown),t?.file&&(n.props.file=t.file),n.component===`PersonaArtifactInline`&&t?.props&&Object.keys(t.props).length>0&&(n.props.componentProps=t.props)}t.rawContent=JSON.stringify(n)}catch{}te.delete(e),p(t),ee.delete(e)}}}else if(r.type===`error`&&r.recoverable===!1&&r.error!=null&&r.error!==``){let e=typeof r.error==`string`?r.error:r.error?.message==null?`Execution error`:String(r.error.message);n({type:`error`,error:Error(e)});let t=m;t&&t.streaming&&(t.streaming=!1,p(t)),n({type:`status`,status:`idle`})}}}fe.length=0};;){let{done:t,value:r}=await a.read();if(t)break;s+=o.decode(r,{stream:!0});let i=s.split(`
|
|
4
|
+
`).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`)}catch{return n[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e===null?null:{text:e,raw:r};let i=r.trim();if(!i.startsWith(`{`)&&!i.startsWith(`[`))return null;let a=n(r);return a!==null&&(e=a),t=r.length,e===null?null:{text:e,raw:r}},close:async()=>{}}},Jn=e=>{try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.text==`string`)return t.text}catch{return null}return null},Yn=()=>{let e={processChunk:e=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Xn=()=>{let e=qn();return{processChunk:async t=>{let n=t.trim();return!n.startsWith(`{`)&&!n.startsWith(`[`)?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Zn=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith(`{`)&&!r.startsWith(`[`))return null;if(n.length<=t)return e!==null||e===``?{text:e||``,raw:n}:null;try{let t=kt(n,Ot|Dt);t&&typeof t==`object`&&(t.component&&typeof t.component==`string`?e=typeof t.text==`string`?Pn(t.text):``:t.type===`init`&&t.form?e=``:typeof t.text==`string`&&(e=Pn(t.text)))}catch{}return t=n.length,e===null?null:{text:e,raw:n}},close:()=>{}}},Qn=e=>{let t=null,n=0,r=e||(e=>{if(!e||typeof e!=`object`)return null;let t=e=>typeof e==`string`?Pn(e):null;if(e.component&&typeof e.component==`string`)return typeof e.text==`string`?Pn(e.text):``;if(e.type===`init`&&e.form)return``;if(e.action)switch(e.action){case`nav_then_click`:return t(e.on_load_text)||t(e.text)||null;case`message`:case`message_and_click`:case`checkout`:return t(e.text)||null;default:return t(e.text)||t(e.display_text)||t(e.message)||null}return t(e.text)||t(e.display_text)||t(e.message)||t(e.content)||null});return{getExtractedText:()=>t,processChunk:e=>{let i=e.trim();if(!i.startsWith(`{`)&&!i.startsWith(`[`))return null;if(e.length<=n)return t===null?null:{text:t,raw:e};try{let n=kt(e,Ot|Dt),i=r(n);i!==null&&(t=i)}catch{}return n=e.length,{text:t||``,raw:e}},close:()=>{}}},$n=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith(`<`))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}}})),q,J,tr,Y=W((()=>{q=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},J=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[e,n]of Object.entries(t.attrs))r.setAttribute(e,n);if(t.style){let e=r.style,n=t.style;for(let t of Object.keys(n)){let r=n[t];r!=null&&(e[t]=r)}}let i=n.filter(e=>e!=null);return i.length>0&&r.append(...i),r},tr=(...e)=>e.filter(Boolean).join(` `)})),nr,rr,ir,ar,or,sr,cr,lr,ur,dr,fr,pr,mr,hr,gr,_r,vr,yr,br,X,xr,Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr,Nr,Pr,Fr,Ir,Lr,Rr,zr,Br,Vr,Hr,Ur,Wr,Gr,Kr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti=W((()=>{Y(),nr=`ask_user_question`,rr=`data-persona-ask-sheet-for`,ir=`Other`,ar=`Other…`,or=`Type your own answer here`,sr=`Send`,cr=`Next`,lr=`Back`,ur=`Submit all`,dr=`Skip`,fr=3,pr=`data-ask-current-index`,mr=`data-ask-question-count`,hr=`data-ask-answers`,gr=`data-ask-grouped`,_r=`data-ask-layout`,vr=e=>e.layout===`pills`?`pills`:`rows`,yr=e=>e.getAttribute(`data-ask-layout`)===`pills`?`pills`:`rows`,br=!1,X=e=>e.replace(/["\\]/g,`\\$&`),xr=e=>e.variant===`tool`&&!!e.toolCall&&e.toolCall.name===`ask_user_question`,Sr=e=>e?.features?.askUserQuestion??{},Cr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status===`complete`;if(t.args&&typeof t.args==`object`)return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let e=r.join(``),t=kt(e,Ot|Dt|Et);if(t&&typeof t==`object`)return{payload:t,complete:n}}catch{}return{payload:null,complete:n}},wr=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!br&&(br=!0,typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},Tr=e=>wr(e)[0]??null,Er=(e,t)=>wr(e)[t]??null,Dr=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty(`--persona-ask-sheet-bg`,n.sheetBackground),n.sheetBorder&&e.style.setProperty(`--persona-ask-sheet-border`,n.sheetBorder),n.sheetShadow&&e.style.setProperty(`--persona-ask-sheet-shadow`,n.sheetShadow),n.pillBackground&&e.style.setProperty(`--persona-ask-pill-bg`,n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty(`--persona-ask-pill-bg-selected`,n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty(`--persona-ask-pill-fg`,n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty(`--persona-ask-pill-fg-selected`,n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty(`--persona-ask-pill-radius`,n.pillBorderRadius),n.customInputBackground&&e.style.setProperty(`--persona-ask-input-bg`,n.customInputBackground))},Or=(e,t,n)=>{if(e!==`rows`)return null;let r=q(`span`,`persona-ask-row-affordance`);if(r.setAttribute(`aria-hidden`,`true`),t){let e=q(`span`,`persona-ask-row-check`);r.appendChild(e)}else{let e=q(`span`,`persona-ask-row-badge`);e.textContent=String(n+1),r.appendChild(e)}return r},kr=(e,t,n,r)=>{let i=q(`button`,n===`rows`?`persona-ask-pill persona-ask-row persona-pointer-events-auto`:`persona-ask-pill persona-pointer-events-auto`);if(i.type=`button`,i.setAttribute(`role`,r?`checkbox`:`button`),i.setAttribute(`aria-pressed`,`false`),i.setAttribute(`data-ask-user-action`,`pick`),i.setAttribute(`data-option-index`,String(t)),i.setAttribute(`data-option-label`,e.label),n===`rows`){let a=q(`span`,`persona-ask-row-content`),o=q(`span`,`persona-ask-row-label`);if(o.textContent=e.label,a.appendChild(o),e.description){let t=q(`span`,`persona-ask-row-description`);t.textContent=e.description,a.appendChild(t)}i.appendChild(a);let s=Or(n,r,t);s&&i.appendChild(s)}else i.textContent=e.label,e.description&&(i.title=e.description);return i},Ar=e=>{let t=q(`span`,e===`rows`?`persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none`:`persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none`);return t.setAttribute(`aria-hidden`,`true`),t},jr=(e,t,n,r)=>{let i=q(`div`,r===`rows`?`persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2`:`persona-ask-pills persona-flex persona-flex-wrap persona-gap-2`);i.setAttribute(`role`,`group`),i.setAttribute(`data-ask-pill-list`,`true`);let a=!!e?.multiSelect,o=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&typeof e.label==`string`&&e.label.length>0);if(o.length===0&&!n){for(let e=0;e<fr;e++)i.appendChild(Ar(r));return i}if(o.forEach((e,t)=>{i.appendChild(kr(e,t,r,a))}),e?.allowFreeText!==!1){let e=r===`rows`?ir:ar;if(r===`rows`){let n=q(`div`,`persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto`);n.setAttribute(`data-ask-user-action`,`focus-free-text`),n.setAttribute(`data-option-index`,String(o.length)),n.setAttribute(`data-ask-other-row`,`true`);let s=q(`span`,`persona-ask-row-content`),c=document.createElement(`input`);c.type=`text`,c.className=`persona-ask-row-input persona-flex-1 persona-pointer-events-auto`,c.placeholder=t.freeTextPlaceholder??or,c.setAttribute(`data-ask-free-text-input`,`true`),c.setAttribute(`aria-label`,t.freeTextLabel??e),s.appendChild(c),n.appendChild(s);let l=Or(r,a,o.length);l&&n.appendChild(l),i.appendChild(n)}else{let n=q(`button`,`persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto`);n.type=`button`,n.setAttribute(`data-ask-user-action`,`open-free-text`),n.textContent=t.freeTextLabel??e,i.appendChild(n)}}return i},Mr=(e,t)=>{let n=q(`div`,t===`rows`?`persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2`:`persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2`);n.setAttribute(`data-ask-free-text-row`,`true`);let r=document.createElement(`input`);if(r.type=`text`,r.className=`persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto`,r.placeholder=e.freeTextPlaceholder??or,r.setAttribute(`data-ask-free-text-input`,`true`),n.appendChild(r),t!==`rows`){let t=q(`button`,`persona-ask-free-text-submit persona-pointer-events-auto`);t.type=`button`,t.textContent=e.submitLabel??sr,t.setAttribute(`data-ask-user-action`,`submit-free-text`),n.appendChild(t)}return n},Nr=e=>{let t=q(`div`,`persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2`);t.setAttribute(`data-ask-multi-actions`,`true`);let n=q(`button`,`persona-ask-multi-submit persona-pointer-events-auto`);return n.type=`button`,n.textContent=e.submitLabel??sr,n.setAttribute(`data-ask-user-action`,`submit-multi`),n.disabled=!0,t.appendChild(n),t},Pr=(e,t,n)=>{let r=q(`div`,`persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2`);r.setAttribute(`data-ask-nav-row`,`true`);let i=q(`button`,`persona-ask-nav-back persona-pointer-events-auto`);i.type=`button`,i.textContent=n.backLabel??lr,i.setAttribute(`data-ask-user-action`,`back`),i.disabled=e===0,r.appendChild(i);let a=q(`div`,`persona-ask-nav-right persona-flex persona-items-center persona-gap-2`),o=q(`button`,`persona-ask-nav-skip persona-pointer-events-auto`);o.type=`button`,o.textContent=n.skipLabel??dr,o.setAttribute(`data-ask-user-action`,`skip`),a.appendChild(o);let s=q(`button`,`persona-ask-nav-next persona-pointer-events-auto`);s.type=`button`;let c=e===t-1;return s.textContent=c?n.submitAllLabel??ur:n.nextLabel??cr,s.setAttribute(`data-ask-user-action`,c?`submit-all`:`next`),s.disabled=!0,a.appendChild(s),r.appendChild(a),r},Fr=e=>{let t=e.getAttribute(hr);if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e==`object`?e:{}}catch{return{}}},Ir=(e,t)=>{e.setAttribute(hr,JSON.stringify(t))},Lr=e=>{let t=Number(e.getAttribute(`data-ask-current-index`)??`0`);return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Rr=(e,t)=>{e.setAttribute(pr,String(Math.max(0,Math.floor(t))))},zr=e=>{let t=Number(e.getAttribute(`data-ask-question-count`)??`1`);return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Br=e=>e.getAttribute(gr)===`true`,Vr=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!=`object`)return{};let r={};return t.forEach((e,t)=>{let i=typeof e?.question==`string`?e.question:``;if(i&&Object.prototype.hasOwnProperty.call(n,i)){let e=n[i];(typeof e==`string`||Array.isArray(e))&&(r[t]=e)}}),r},Hr=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!=`number`||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Ur=(e,t)=>{let{payload:n}=Cr(t),r=wr(n),i=Fr(e),a={},o=/* @__PURE__ */ new Set;return r.forEach((e,t)=>{let n=typeof e?.question==`string`?e.question:``;n&&(o.has(n)&&typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${n}"; later answer wins.`),o.add(n),Object.prototype.hasOwnProperty.call(i,t)&&(a[n]=i[t]))}),a},Wr=e=>{let t=Fr(e)[Lr(e)],n=/* @__PURE__ */ new Set;typeof t==`string`?n.add(t):Array.isArray(t)&&t.forEach(e=>n.add(e));let r=e.querySelectorAll(`[data-ask-user-action="pick"][data-option-label]`);r.forEach(e=>{let t=e.getAttribute(`data-option-label`)??``,r=n.has(t);e.setAttribute(`aria-pressed`,r?`true`:`false`),e.classList.toggle(`persona-ask-pill-selected`,r)});let i=new Set(Array.from(r).map(e=>e.getAttribute(`data-option-label`)??``)),a=e.querySelector(`[data-ask-free-text-input="true"]`);a&&(typeof t==`string`&&t.length>0&&!i.has(t)?(a.value=t,a.closest(`[data-ask-free-text-row="true"]`)?.classList.remove(`persona-hidden`)):a.value=``)},Gr=e=>{if(!Br(e))return;let t=Fr(e)[Lr(e)],n=typeof t==`string`&&t.length>0||Array.isArray(t)&&t.length>0,r=e.querySelector(`[data-ask-user-action="next"], [data-ask-user-action="submit-all"]`);r&&(r.disabled=!n);let i=e.querySelector(`[data-ask-user-action="submit-multi"]`);i&&(i.disabled=Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).length===0)},Kr=(e,t,n)=>{let r=Sr(n),i=yr(e),{payload:a,complete:o}=Cr(t),s=Br(e),c=Lr(e),l=zr(e),u=s?Er(a,c):Tr(a),d=!!u?.multiSelect,f=e.querySelector(`[data-ask-step-inline="true"]`);f&&(f.textContent=s?`${c+1}/${l}`:``);let p=e.querySelector(`[data-ask-stepper="true"]`);p&&p.remove();let m=e.querySelector(`[data-ask-question="true"]`);if(m){let e=typeof u?.question==`string`?u.question:``;m.textContent=e,m.classList.toggle(`persona-ask-question-skeleton`,!e&&!o)}let h=e.querySelector(`[data-ask-pill-list="true"]`);if(h){let e=jr(u,r,o,i);h.replaceWith(e)}if(i!==`rows`){let t=e.querySelector(`[data-ask-free-text-row="true"]`);t&&t.replaceWith(Mr(r,i))}let g=e.querySelector(`[data-ask-multi-actions="true"]`);!s&&d&&!g?e.appendChild(Nr(r)):(!d||s)&&g&&g.remove(),e.setAttribute(`data-multi-select`,d?`true`:`false`);let _=e.querySelector(`[data-ask-nav-row="true"]`);if(s){let t=Pr(c,l,r);_?_.replaceWith(t):e.appendChild(t)}else _&&_.remove();Wr(e),Gr(e)},qr=(e,t,n)=>{let r=Sr(t),i=vr(r),a=e.toolCall.id,o=wr(n),s=Math.max(1,o.length),c=s>1,l=Vr(e,o),u=c?Hr(e,s):0,d=q(`div`,[`persona-ask-sheet`,`persona-ask-sheet--${i}`,`persona-pointer-events-auto`,`persona-ask-sheet-enter`].join(` `));d.setAttribute(rr,a),d.setAttribute(`data-tool-call-id`,a),d.setAttribute(`data-message-id`,e.id),d.setAttribute(mr,String(s)),d.setAttribute(pr,String(u)),d.setAttribute(gr,c?`true`:`false`),d.setAttribute(_r,i),Ir(d,l),d.setAttribute(`role`,`group`),d.setAttribute(`aria-label`,`Suggested answers`),r.slideInMs!==void 0&&d.style.setProperty(`--persona-ask-sheet-duration`,`${r.slideInMs}ms`),Dr(d,r);let f=q(`div`,`persona-ask-sheet-header persona-flex persona-items-center persona-gap-3`),p=q(`div`,`persona-ask-sheet-question persona-flex-1`);p.setAttribute(`data-ask-question`,`true`),p.textContent=``,f.appendChild(p);let m=q(`span`,`persona-ask-sheet-step-inline`);m.setAttribute(`data-ask-step-inline`,`true`),m.textContent=``,f.appendChild(m),d.appendChild(f);let h=q(`div`,i===`rows`?`persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2`:`persona-ask-pills persona-flex persona-flex-wrap persona-gap-2`);return h.setAttribute(`data-ask-pill-list`,`true`),h.setAttribute(`role`,`group`),d.appendChild(h),i!==`rows`&&d.appendChild(Mr(r,i)),Kr(d,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>d.classList.remove(`persona-ask-sheet-enter`))}),d},Jr=(e,t,n)=>{let{payload:r}=Cr(t),i=Math.max(1,wr(r).length);i>zr(e)&&(e.setAttribute(mr,String(i)),i>1&&!Br(e)&&e.setAttribute(gr,`true`)),Kr(e,t,n)},Yr=(e,t)=>{let n=q(`div`,`persona-ask-stub persona-inline-flex persona-items-center persona-gap-2`);n.id=`bubble-${e.id}`,n.setAttribute(`data-message-id`,e.id),n.setAttribute(`data-bubble-type`,`ask-user-question`);let r=Sr(t);Dr(n,r);let i=q(`span`,`persona-ask-stub-label`),{complete:a}=Cr(e);return i.textContent=a?`Awaiting your response…`:`Preparing options…`,n.appendChild(i),n},Xr=(e,t,n)=>{if(!n||!xr(e)||Sr(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${rr}]`).forEach(e=>{e.getAttribute(rr)!==r&&e.remove()});let i=n.querySelector(`[${rr}="${X(r)}"]`);if(i){Jr(i,e,t);return}let{payload:a}=Cr(e),o=qr(e,t,a);n.appendChild(o)},Zr=(e,t)=>{if(!e)return;let n=t?`[${rr}="${X(t)}"]`:`[${rr}]`;e.querySelectorAll(n).forEach(e=>{e.classList.add(`persona-ask-sheet-leave`);let t=Number.parseInt(getComputedStyle(e).getPropertyValue(`--persona-ask-sheet-duration`)||`180`,10);setTimeout(()=>e.remove(),Number.isFinite(t)?t:180)})},Qr=e=>Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).map(e=>e.getAttribute(`data-option-label`)).filter(e=>typeof e==`string`&&e.length>0),$r=(e,t)=>{let n=Fr(e),r=Lr(e);typeof t==`string`&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Ir(e,n),Wr(e),Gr(e)},ei=(e,t,n,r)=>{let i=zr(e),a=Math.max(0,Math.min(i-1,r));Rr(e,a),Kr(e,t,n)}})),ni,ri,ii,ai,oi,si,ci,li,ui,di,fi=W((()=>{ni=`suggest_replies`,ri={type:`object`,properties:{suggestions:{type:`array`,minItems:1,maxItems:4,description:`1-4 short, distinct follow-up replies, phrased in the user's voice.`,items:{type:`object`,properties:{label:{type:`string`,minLength:1,maxLength:80},prompt:{type:`string`,minLength:1,maxLength:500},description:{type:`string`,minLength:1,maxLength:160}},required:[`label`],additionalProperties:!1}}},required:[`suggestions`],additionalProperties:!1},ii={name:ni,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:ri,origin:`sdk`,annotations:{readOnlyHint:!0}},ai=()=>({content:[{type:`text`,text:`Suggestions shown to the user.`}]}),oi=e=>e.variant===`tool`&&e.toolCall?.name===`suggest_replies`,si=e=>{let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let r=n.flatMap(e=>{if(typeof e==`string`){let t=e.trim();return t?[t]:[]}if(!e||typeof e!=`object`)return[];let t=e;if(typeof t.label!=`string`||!t.label.trim())return[];let n={label:t.label.trim()};return typeof t.prompt==`string`&&t.prompt.trim()&&(n.prompt=t.prompt.trim()),typeof t.description==`string`&&t.description.trim()&&(n.description=t.description.trim()),[n]});return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},ci=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return null;if(!oi(n))continue;let r=si(n.toolCall?.args);return r.length>0?r:null}return null},li=/* @__PURE__ */ new Set,ui=(e,t,n)=>{let r=`${e}:${t}:${n}`;li.has(r)||(li.add(r),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},di=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,r=e=>{let r=t?.[e],i=n?.[e];r!==void 0&&i!==void 0&&r!==i&&ui(e,i,r)};e&&(r(`enabled`),r(`expose`));let i=t?.enabled??n?.enabled??!0;return{enabled:i,expose:i?t?.expose??n?.expose??!1:!1}}})),pi,mi,hi,Z=W((()=>{ti(),fi(),pi={type:`object`,properties:{questions:{type:`array`,minItems:1,maxItems:8,description:`Questions to ask the user. Prefer a single question.`,items:{type:`object`,properties:{question:{type:`string`,description:`The complete question, ending with a question mark.`},header:{type:`string`,maxLength:12,description:`Short topic label, e.g. "Auth method".`},options:{type:`array`,minItems:2,maxItems:4,description:`2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.`,items:{type:`object`,properties:{label:{type:`string`,description:`Concise choice text (1-5 words).`},description:{type:`string`,description:`What the option means or implies.`}},required:[`label`],additionalProperties:!1}},multiSelect:{type:`boolean`,description:`Allow selecting multiple options. Default false.`},allowFreeText:{type:`boolean`,description:`Show a free-text input. Default true.`}},required:[`question`,`options`],additionalProperties:!1}}},required:[`questions`],additionalProperties:!1},mi={name:nr,description:`Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.`,parametersSchema:pi,origin:`sdk`,annotations:{readOnlyHint:!0}},hi=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(mi),di(e).expose&&t.push(ii),t}})),gi,_i,vi,yi=W((()=>{gi={idle:`Online`,connecting:`Connecting…`,connected:`Streaming…`,error:`Offline`,paused:`Connection lost…`,resuming:`Reconnecting…`},_i=1e5,vi=100001}));async function bi(e,t,n,r){let i={"Content-Type":`application/json`,...e.headers};e.getHeaders&&Object.assign(i,await e.getHeaders());let a={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},o=(t,n)=>fetch(`${e.clientApiBase()}${t}`,{method:`POST`,headers:i,body:JSON.stringify({...n,...a})}),s=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return o(s);let{sessionId:c}=await e.initSession(),l=await o(`/v1/client/approve`,{sessionId:c,...r?.assistantMessageId?{assistantMessageId:r.assistantMessageId}:{}});if(l.status===404){let e=await l.clone().json().catch(()=>null);if(!e||e.error===`Not Found`)return o(s)}return l}async function xi(e,t,n,r){let i=e.isClientTokenMode(),a=i?e.getClientApiUrl(`resume`):`${e.config.apiUrl?.replace(/\/+$/,``)||`https://api.runtype.com`}/resume`,o,s=null;if(i){let t=await e.initSession();o=t.sessionId,t.durableRecovery?.enabled===!0&&(s=await e.readVisitorToken())}let c={"Content-Type":`application/json`,...s?{"X-Visitor-Token":s}:{},...e.headers};e.getHeaders&&Object.assign(c,await e.getHeaders());let l={executionId:t,toolOutputs:n,streamResponse:r?.streamResponse??!0,...r?.after?{after:r.after}:{}};if(o&&(l.sessionId=o,r?.assistantMessageId&&(l.assistantMessageId=r.assistantMessageId)),i&&o){let t=[...hi(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:n,commit:i}=await e.sendWithClientToolsDiff(o,t,t=>{let n={...l,...t};return e.debug&&console.debug(`[AgentWidgetClient] client token resume`,n),fetch(a,{method:`POST`,headers:c,body:JSON.stringify(n),signal:r?.signal})},{emptyMeansReplace:!0});return n.ok&&i(),n}return fetch(a,{method:`POST`,headers:c,body:JSON.stringify(l),signal:r?.signal})}var Si=W((()=>{Z(),yi()})),Ci=/* @__PURE__ */ Mt({preferFinalStructuredContent:()=>Ti,resolveApproval:()=>bi,resumeFlow:()=>xi,streamResponse:()=>Di});function wi(e){let t=e.toLowerCase(),n={"application/pdf":`pdf`,"application/json":`json`,"application/zip":`zip`,"text/plain":`txt`,"text/csv":`csv`,"text/markdown":`md`}[t];if(n)return`attachment.${n}`;let r=t.indexOf(`/`);if(r>0){let e=t.slice(r+1).split(`;`)[0]?.trim()??``;if(e&&e!==`octet-stream`&&/^[a-z0-9.+-]+$/i.test(e))return`attachment.${e}`}return`attachment`}function Ti(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let i=Oi(n);if(!Oi(r))return e;if(!i||r===n||r.startsWith(n))return t;let a=Jn(e);return Jn(t)!==null&&a===null?t:e}async function Ei(e,t,n,r,i,a,o){if(!e.parseSSEEvent)return!1;try{let s=await e.parseSSEEvent(t);if(s===null)return!1;let c=e=>{let t={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`assistant`,sequence:a(),...e!==void 0&&{partId:e}};return r.current=t,i(t),t},l=e=>r.current?r.current:c(e);if(s.text!==void 0){s.partId!==void 0&&o.current!==null&&s.partId!==o.current&&(r.current&&(r.current.streaming=!1,i(r.current)),c(s.partId)),s.partId!==void 0&&(o.current=s.partId);let e=l(s.partId);s.partId!==void 0&&!e.partId&&(e.partId=s.partId),e.content+=s.text,i(e)}return s.done&&(r.current&&(r.current.streaming=!1,i(r.current)),o.current=null,n({type:`status`,status:`idle`})),s.error&&(o.current=null,n({type:`error`,error:Error(s.error)})),!0}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] parseSSEEvent error:`,e),!1}}async function Di(e,t,n,r,i){let a=t.getReader(),o=new TextDecoder,s=``,c=Date.now(),l=0,u=()=>c+l++,d=e=>{let t=e.reasoning?{...e.reasoning,chunks:[...e.reasoning.chunks]}:void 0,n=e.toolCall?{...e.toolCall,chunks:e.toolCall.chunks?[...e.toolCall.chunks]:void 0}:void 0,r=e.tools?e.tools.map(e=>({...e,chunks:e.chunks?[...e.chunks]:void 0})):void 0;return{...e,reasoning:t,toolCall:n,tools:r}},f=e=>{if(e.role!==`assistant`||e.variant)return!0;let t=Array.isArray(e.contentParts)&&e.contentParts.length>0,n=typeof e.rawContent==`string`&&e.rawContent.trim()!==``;return typeof e.content==`string`&&e.content.trim()!==``||t||n||!!e.stopReason},p=e=>{f(e)&&n({type:`message`,message:d(e)})},m=null,h=null,g={current:null},_={current:null},v=null,y=``,b=/* @__PURE__ */ new Map,x=/* @__PURE__ */ new Map,S=/* @__PURE__ */ new Map,C=/* @__PURE__ */ new Map,w=/* @__PURE__ */ new Map,T=r,E=!1,D=()=>{if(m)return m;let e,t=``,n=v;return!E&&T?(e=T,E=!0,t=i??``):e=T&&n?`${T}_${n}`:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:e,role:`assistant`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u()},p(m),m},O=e=>{let t=C.get(e);if(t)return t;let n={id:`reason-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`reasoning`,sequence:u(),reasoning:{id:e,status:`streaming`,chunks:[]}};return C.set(e,n),p(n),n},k=/* @__PURE__ */ new Set,ee=/* @__PURE__ */ new Map,te=/* @__PURE__ */ new Set,ne=/* @__PURE__ */ new Map,re=e=>{if(!e)return!1;let t=e.replace(/_+/g,`_`).replace(/^_|_$/g,``);return t===`emit_artifact_markdown`||t===`emit_artifact_component`},ie=e=>{let t=w.get(e);if(t)return t;let n={id:`tool-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`tool`,sequence:u(),toolCall:{id:e,status:`pending`}};return w.set(e,n),p(n),n},ae=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`){let t=Number(e);if(!Number.isNaN(t)&&Number.isFinite(t))return t;let n=Date.parse(e);if(!Number.isNaN(n))return n}return Date.now()},oe=e=>{if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)}catch{return String(e)}},A=/* @__PURE__ */ new Map,j=/* @__PURE__ */ new Map,se=(e,t)=>{let n=oe(t),r=Ti(j.get(e.id),n);e.rawContent=r;let i=A.get(e.id),a=t=>{let n=e.content??``;t.trim()!==``&&(n.trim().length===0||t.startsWith(n)||t.trimStart().startsWith(n.trim()))&&(e.content=t)},o=()=>{if(i){let e=i.close?.();e instanceof Promise&&e.catch(()=>{})}A.delete(e.id),j.delete(e.id),e.streaming=!1,p(e)};if(!i){a(n),o();return}let s=Jn(r);if(s!==null&&s.trim()!==``){a(s),o();return}let c=e=>{let t=typeof e==`string`?e:e?.text??null;if(t!==null&&t.trim()!==``)return t;let r=i.getExtractedText();return r!==null&&r.trim()!==``?r:n},l;try{l=i.processChunk(r)}catch{a(n),o();return}l instanceof Promise?l.then(e=>{a(c(e)),o()}).catch(()=>{a(n),o()}):(a(c(l)),o())},ce=null,le=(t,n,r,i)=>{t.rawContent=n,A.has(t.id)||A.set(t.id,e.createStreamParser());let a=A.get(t.id),o=n.trim().startsWith(`{`)||n.trim().startsWith(`[`);if(o&&j.set(t.id,n),a.__isPlainTextParser===!0){t.content=i===void 0?t.content+r:n,j.delete(t.id),A.delete(t.id),t.rawContent=void 0,p(t);return}let s=a.processChunk(n);if(s instanceof Promise)s.then(e=>{let a=typeof e==`string`?e:e?.text??null;a!==null&&a.trim()!==``?(t.content=a,p(t)):!o&&!n.trim().startsWith(`<`)&&(t.content=i===void 0?t.content+r:n,j.delete(t.id),A.delete(t.id),t.rawContent=void 0,p(t))}).catch(()=>{t.content=i===void 0?t.content+r:n,j.delete(t.id),A.delete(t.id),t.rawContent=void 0,p(t)});else{let e=typeof s==`string`?s:s?.text??null;e!==null&&e.trim()!==``?(t.content=e,p(t)):!o&&!n.trim().startsWith(`<`)&&(t.content=i===void 0?t.content+r:n,j.delete(t.id),A.delete(t.id),t.rawContent=void 0,p(t))}},ue=(e,t)=>{let n=t??e.content;if(n==null||n===``){e.streaming=!1,p(e);return}let r=j.get(e.id)??oe(n);e.rawContent=r;let i=A.get(e.id),a=null,o=!1;if(i&&(a=i.getExtractedText(),a===null&&(a=Jn(r)),a===null)){let t=i.processChunk(r);t instanceof Promise?(o=!0,t.then(t=>{let n=typeof t==`string`?t:t?.text??null;n!==null&&(e.content=n,e.streaming=!1,A.delete(e.id),j.delete(e.id),p(e))}).catch(()=>{})):a=typeof t==`string`?t:t?.text??null}if(!o){a!==null&&a.trim()!==``?e.content=a:j.has(e.id)||(e.content=oe(n));let t=A.get(e.id);if(t){let n=t.close?.();n instanceof Promise&&n.catch(()=>{}),A.delete(e.id)}j.delete(e.id),e.streaming=!1,p(e)}},de=(e,t,n)=>{let r=x.get(e);if(r)return r;let i={id:`nested-${t}-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u(),...n?{variant:n}:{},...n===`reasoning`?{reasoning:{id:e,status:`streaming`,chunks:[]}}:{},agentMetadata:{parentToolId:t}};return x.set(e,i),p(i),i},fe=[],pe,M=/* @__PURE__ */ new Map,me=0,he=`agent`,ge=!1,_e=null,ve=null,ye=e.config().iterationDisplay??`separate`;for(pe=()=>{for(let t=0;t<fe.length;t++){let r=fe[t];if(!ge&&he!==`flow`&&typeof r.stepType==`string`&&(he=`flow`),r.type===`reasoning_start`){let e=typeof r.id==`string`?r.id:null,t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){b.set(e,t),de(e,t,`reasoning`);continue}let n=r.id,i=O(n);i.reasoning=i.reasoning??{id:n,status:`streaming`,chunks:[]},i.reasoning.startedAt=i.reasoning.startedAt??Date.now(),i.reasoning.completedAt=void 0,i.reasoning.durationMs=void 0,(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),i.streaming=!0,i.reasoning.status=`streaming`,p(i)}else if(r.type===`reasoning_delta`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)&&x.has(e)){let t=x.get(e),n=r.delta;n&&t.reasoning&&(t.reasoning.chunks.push(String(n)),p(t));continue}let t=r.id,n=O(t);n.reasoning=n.reasoning??{id:t,status:`streaming`,chunks:[]},n.reasoning.startedAt=n.reasoning.startedAt??Date.now(),r.delta&&n.reasoning.chunks.push(r.delta),n.reasoning.status=`streaming`,n.streaming=!0,p(n)}else if(r.type===`reasoning_complete`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)&&x.has(e)){let t=x.get(e);if(t.reasoning){let e=typeof r.text==`string`?r.text:``;e&&t.reasoning.chunks.length===0&&t.reasoning.chunks.push(e),t.reasoning.status=`complete`,t.streaming=!1,p(t)}b.delete(e),x.delete(e);continue}let t=r.id,n=typeof r.text==`string`?r.text:``;!C.get(t)&&(n||r.scope===`loop`)&&O(t);let i=C.get(t);if(i?.reasoning){(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),n&&i.reasoning.chunks.length===0&&i.reasoning.chunks.push(n),i.reasoning.status=`complete`,i.reasoning.completedAt=Date.now();let e=i.reasoning.startedAt??Date.now();i.reasoning.durationMs=Math.max(0,(i.reasoning.completedAt??Date.now())-e),i.streaming=!1,p(i)}}else if(r.type===`tool_start`){m&&=(m.streaming=!1,p(m),null),typeof r.iteration==`number`&&(me=r.iteration);let e=r.toolCallId,t=r.toolName;if(re(t)){k.add(e);continue}let n=ie(e),i=n.toolCall??{id:e,status:`pending`};i.name=t??i.name,i.status=`running`,i.success=void 0,i.error=void 0,i.duration=void 0,r.parameters!==void 0&&(i.args=r.parameters),i.startedAt=i.startedAt??ae(r.startedAt),i.completedAt=void 0,i.durationMs=void 0,n.toolCall=i,n.streaming=!0,r.executionId&&(n.agentMetadata={executionId:r.executionId,iteration:r.iteration}),p(n)}else if(r.type===`tool_output_delta`){let e=r.toolCallId;if(k.has(e))continue;let t=ie(e),n=t.toolCall??{id:e,status:`running`};n.startedAt=n.startedAt??Date.now();let i=r.delta;i&&(n.chunks=n.chunks??[],n.chunks.push(String(i))),n.status=`running`,t.toolCall=n,t.streaming=!0,r.executionId&&(t.agentMetadata=t.agentMetadata??{executionId:r.executionId,iteration:me}),p(t)}else if(r.type===`tool_complete`){let e=r.toolCallId;if(k.has(e)){k.delete(e);continue}let t=ie(e),n=t.toolCall??{id:e,status:`running`};n.status=`complete`,r.result!==void 0&&(n.result=r.result),n.name=r.toolName??n.name,n.success=r.success,n.error=r.error,n.completedAt=Date.now();let i=r.executionTime;if(typeof i==`number`)n.durationMs=i,n.duration=i;else{let e=n.startedAt??Date.now();n.durationMs=Math.max(0,(n.completedAt??Date.now())-e)}t.toolCall=n,t.streaming=!1,r.executionId&&(t.agentMetadata=t.agentMetadata??{executionId:r.executionId,iteration:r.iteration??me}),p(t)}else if(r.type===`await`&&r.toolName){let e=typeof r.toolCallId==`string`&&r.toolCallId.length>0?r.toolCallId:void 0,t=e??r.toolId??`local-${u()}`,n=ie(t),i=r.toolName,a=r.origin===`webmcp`&&!wn(i)?`webmcp:${i}`:i,o=wn(a),s=n.toolCall??{id:t,status:`pending`};s.name=a,s.args=r.parameters,s.status=o?`running`:`complete`,s.chunks=s.chunks??[],s.startedAt=s.startedAt??ae(r.awaitedAt),o?(s.completedAt=void 0,s.duration=void 0,s.durationMs=void 0):s.completedAt=s.completedAt??s.startedAt,n.toolCall=s,n.streaming=!1,n.agentMetadata={...n.agentMetadata,executionId:r.executionId??n.agentMetadata?.executionId,awaitingLocalTool:!0,...e?{webMcpToolCallId:e}:{}},p(n)}else if(r.type===`text_start`){let e=typeof r.id==`string`?r.id:null,t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){b.set(e,t);continue}let n=m;n&&(he===`flow`?(ue(n),ce=n):(n.streaming=!1,p(n)),m=null),v=typeof r.id==`string`?r.id:v,y=``}else if(r.type===`text_delta`){let e=typeof r.id==`string`?r.id:null,t=e?b.get(e):void 0;if(e&&t){let n=typeof r.delta==`string`?r.delta:``,i=(S.get(e)??``)+n;if(S.set(e,i),i.trim()===``)continue;let a=de(e,t);a.agentMetadata={...a.agentMetadata,executionId:r.executionId,parentToolId:t},le(a,i,n,void 0);continue}if(v=typeof r.id==`string`?r.id:v,he===`flow`){let e=typeof r.delta==`string`?r.delta:``;if(y+=e,y.trim()===``)continue;let t=D();t.agentMetadata={executionId:r.executionId,iteration:me},le(t,y,e,void 0),h=t;continue}let n=typeof r.delta==`string`?r.delta:``;y+=n;let i=D();i.agentMetadata={executionId:r.executionId,iteration:me,turnId:_e??void 0,agentName:ve?.agentName},le(i,y,n,void 0),h=i}else if(r.type===`text_complete`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)){let t=x.get(e);t&&ue(t),b.delete(e),S.delete(e),x.delete(e);continue}let t=m;t&&(he===`flow`?(ue(t),ce=t):((t.content??``)===``&&typeof r.text==`string`&&(t.content=r.text),t.streaming=!1,p(t)),m=null),v=null,y=``}else if(r.type===`step_complete`){if(r.stepType===`tool`)continue;if(r.success===!1){let e=r.error||`Step failed`;n({type:`error`,error:Error(e)});let t=m;t&&t.streaming&&(t.streaming=!1,p(t)),n({type:`status`,status:`idle`});continue}{let e=ce;ce=null;let t=r.stopReason,n=(r.result&&typeof r.result==`object`?r.result:null)?.response;if(e)t&&(e.stopReason=t),n==null?e.streaming!==!1&&(A.delete(e.id),j.delete(e.id),e.streaming=!1,p(e)):se(e,n);else{let e=n!=null&&n!==``;if(e||t&&t!==`end_turn`&&t!==`unknown`){let r=D();t&&(r.stopReason=t),e?ue(r,n):(r.streaming=!1,p(r))}}continue}}else if(r.type===`execution_start`)he=r.kind===`flow`?`flow`:`agent`,ge=!0,he===`agent`&&(ve={executionId:r.executionId,agentId:r.agentId??`virtual`,agentName:r.agentName??``});else if(r.type===`turn_start`){let e=typeof r.iteration==`number`?r.iteration:me;if(e!==me){if(ye===`separate`&&e>1){let e=m;e&&(e.streaming=!1,p(e),m=null)}me=e}_e=typeof r.id==`string`?r.id:null,h=null}else if(r.type===`tool_input_delta`){let e=r.toolCallId;if(e){let t=w.get(e);t?.toolCall&&(t.toolCall.chunks=t.toolCall.chunks??[],t.toolCall.chunks.push(r.delta??``),p(t))}}else if(r.type===`tool_input_complete`){if(k.has(r.toolCallId))continue;let e=ie(r.toolCallId),t=e.toolCall;t.args=r.parameters,t.name=r.toolName??t.name,p(e)}else if(r.type===`turn_complete`){let e=r.stopReason,t=m??h;if(e&&t!==null){let n=r.id;(!n||t.agentMetadata?.turnId===n)&&(t.stopReason=e,p(t))}_e===r.id&&(_e=null)}else if(r.type===`media_start`){let e=String(r.id);M.set(e,{mediaType:typeof r.mediaType==`string`?r.mediaType:void 0,toolCallId:r.toolCallId,parts:[]})}else if(r.type===`media_delta`){let e=M.get(String(r.id));e&&typeof r.delta==`string`&&e.parts.push(r.delta)}else if(r.type===`media_complete`){let e=String(r.id),t=M.get(e);M.delete(e);let n=(typeof r.mediaType==`string`?r.mediaType:void 0)??t?.mediaType??`application/octet-stream`,i=typeof r.data==`string`?r.data:void 0,a=typeof r.url==`string`?r.url:t&&t.parts.length>0?t.parts.join(``):void 0,o=null;if(i)o={type:`media`,data:i,mediaType:n};else if(a){let e=n.toLowerCase();o={type:e===`image`||e.startsWith(`image/`)?`image-url`:`file-url`,url:a,mediaType:n}}let s=r.toolCallId??t?.toolCallId,c=o?[o]:[],l=[];for(let e of c){if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.type==`string`?t.type:void 0,r=typeof t.mediaType==`string`?t.mediaType.toLowerCase():``,i=null,a=``;if(n===`media`){let e=typeof t.data==`string`?t.data:void 0;if(!e)continue;a=r.length>0?r:`application/octet-stream`,i=`data:${a};base64,${e}`}else if(n===`image-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else if(n===`file-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else continue;if(i){if(n===`image-url`||a.startsWith(`image/`))l.push({type:`image`,image:i,...a.includes(`/`)?{mimeType:a}:{}});else if(a.startsWith(`audio/`))l.push({type:`audio`,audio:i,mimeType:a});else if(a.startsWith(`video/`))l.push({type:`video`,video:i,mimeType:a});else{let e=a||`application/octet-stream`;l.push({type:`file`,data:i,mimeType:e,filename:wi(e)})}}}if(l.length>0){let e=u(),t=s,n={id:`agent-media-${typeof t==`string`&&t.length>0?`${t}-${e}`:String(e)}`,role:`assistant`,content:``,contentParts:l,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e,agentMetadata:{executionId:r.executionId,iteration:me}};p(n);let i=m;i&&(i.streaming=!1,p(i)),m=null,g.current=null}}else if(r.type===`execution_complete`){let e=m;e&&(r.kind===`flow`&&e.streaming!==!1?ue(e):(e.streaming=!1,p(e)),m=null),v=null,y=``,ce=null,n({type:`status`,status:`idle`,terminal:!0})}else if(r.type===`execution_error`){let e=typeof r.error==`string`?r.error:r.error?.message??`Execution error`;n({type:`error`,error:Error(e)})}else if(r.type!==`ping`){if(r.type===`approval_start`){let e=r.approvalId??`approval-${u()}`,t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:u(),approval:{id:e,status:`pending`,agentId:ve?.agentId??`virtual`,executionId:r.executionId??ve?.executionId??``,toolName:r.toolName??``,toolType:r.toolType,description:r.description??`Execute ${r.toolName??`tool`}`,...typeof r.reason==`string`&&r.reason?{reason:r.reason}:{},parameters:r.parameters,...typeof r.toolCallId==`string`&&r.toolCallId?{toolCallId:r.toolCallId}:{}}};p(t)}else if(r.type===`approval_complete`){let e=r.approvalId;if(e){let t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:u(),approval:{id:e,status:r.decision??`approved`,agentId:ve?.agentId??`virtual`,executionId:r.executionId??ve?.executionId??``,toolName:``,description:``,resolvedAt:Date.now()}};p(t)}}else if(r.type===`artifact_start`||r.type===`artifact_delta`||r.type===`artifact_update`||r.type===`artifact_complete`){if(r.type===`artifact_start`){let t=r.artifactType,i=String(r.id),a=typeof r.title==`string`?r.title:void 0,o=r.file,s;if(o&&typeof o==`object`&&!Array.isArray(o)&&typeof o.path==`string`&&typeof o.mimeType==`string`&&(s={path:o.path,mimeType:o.mimeType,...typeof o.language==`string`?{language:o.language}:{}}),n({type:`artifact_start`,id:i,artifactType:t,title:a,component:typeof r.component==`string`?r.component:void 0,...s?{file:s}:{}}),ne.set(i,{markdown:``,title:a,file:s}),!te.has(i)){te.add(i);let n=jn(e.config().features?.artifacts,{artifactType:t,...s?{file:s}:{}}),o=typeof r.component==`string`?r.component:void 0,c={id:`artifact-ref-${i}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u(),rawContent:Mn(n,{artifactId:i,title:a,artifactType:t,status:`streaming`,...s?{file:s}:{},...o?{component:o}:{}})};ee.set(i,c),p(c)}}else if(r.type===`artifact_delta`){let e=String(r.id),t=typeof r.delta==`string`?r.delta:String(r.delta??``);n({type:`artifact_delta`,id:e,artDelta:t});let i=ne.get(e);i&&(i.markdown+=t)}else if(r.type===`artifact_update`){let e=r.props&&typeof r.props==`object`&&!Array.isArray(r.props)?r.props:{};n({type:`artifact_update`,id:String(r.id),props:e,component:typeof r.component==`string`?r.component:void 0});let t=ne.get(String(r.id));t&&(t.props={...t.props??{},...e})}else if(r.type===`artifact_complete`){let e=String(r.id);n({type:`artifact_complete`,id:e});let t=ee.get(e);if(t){t.streaming=!1;try{let n=JSON.parse(t.rawContent??`{}`);if(n.props){n.props.status=`complete`;let t=ne.get(e);t?.markdown&&(n.props.markdown=t.markdown),t?.file&&(n.props.file=t.file),n.component===`PersonaArtifactInline`&&t?.props&&Object.keys(t.props).length>0&&(n.props.componentProps=t.props)}t.rawContent=JSON.stringify(n)}catch{}ne.delete(e),p(t),ee.delete(e)}}}else if(r.type===`error`&&r.recoverable===!1&&r.error!=null&&r.error!==``){let e=typeof r.error==`string`?r.error:r.error?.message==null?`Execution error`:String(r.error.message);n({type:`error`,error:Error(e)});let t=m;t&&t.streaming&&(t.streaming=!1,p(t)),n({type:`status`,status:`idle`})}}}fe.length=0};;){let{done:t,value:r}=await a.read();if(t)break;s+=o.decode(r,{stream:!0});let i=s.split(`
|
|
5
5
|
|
|
6
6
|
`);s=i.pop()??``;for(let t of i){let r=t.split(`
|
|
7
|
-
`),i=`message`,a=``,o=null;for(let e of r)e.startsWith(`event:`)?i=e.replace(`event:`,``).trim():e.startsWith(`data:`)?a+=e.replace(`data:`,``).trim():e.startsWith(`id:`)&&(o=e.slice(3).trim());let s=()=>{o!==null&&o!==``&&n({type:`cursor`,id:o})};if(!a){s();continue}let c;try{c=JSON.parse(a)}catch(e){n({type:`error`,error:e instanceof Error?e:/* @__PURE__ */ Error(`Failed to parse chat stream payload`)});continue}let l=typeof c==`object`&&c&&!Array.isArray(c)?c:null,d=i===`message`?typeof l?.type==`string`?l.type:`message`:i;if(e.onSSEEvent?.(d,c),e.parseSSEEvent){g.current=m;let t=await Ei(e,c,n,g,p,u,_);if(g.current&&g.current!==m&&(m=g.current),t){s();continue}}l&&(fe.push({...l,type:d}),pe()),s()}}pe()}var Oi,Q=W((()=>{En(),Nn(),er(),Si(),Oi=e=>e.startsWith(`{`)||e.startsWith(`[`)||e.startsWith(`<`)}));Q(),Pt();const{setLoader:ki,load:Ai,provide:ji,getSync:Mi}=Nt({fallbackImport:()=>Promise.resolve().then(()=>(Q(),Ci))}),Ni=Ai,Pi=ji,Fi=Mi;Pi(Ci);var Ii=`4.29.0`,Li,Ri=W((()=>{Li=Ii})),zi=/* @__PURE__ */ Mt({deleteAllConversations:()=>ea,deleteConversation:()=>$i,finalizeDisplayProjections:()=>Qi,getConversation:()=>Zi,historyErrorFor:()=>Ki,listConversations:()=>Xi,readErrorCode:()=>Wi,recoverFromUnauthorized:()=>Gi,resetVisitor:()=>ta});function Bi(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function Vi(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function Hi(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`authentication_required`,`This browser is bound to a signed-in user and needs a fresh identity proof`);return n&&e.setHistoryIdentityStatus({state:`browser_only`,reason:`proof_unavailable_before_binding`}),null}async function Ui(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let i=await e.reinitWithProof(n);if(i.visitor?.identityStatus!==`admitted`||i.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,aa);return i}async function Wi(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function Gi(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,oa);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,sa);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,ca);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function Ki(e,t,n){let r=await Wi(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,aa);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,oa)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,sa):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,ca):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function qi(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`ignored`?new e.HistoryClientError(`identity_contract_violation`,`Server reported an ignored identity proof on a success response`):new e.HistoryClientError(`proof_not_admitted`,`The response did not acknowledge the identity proof this request sent`)}if(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function Ji(e,t,n){Yi(e);let r=n.trackIdentity!==!1,i=await e.initSession(),a=null;Vi(e,n.scope)===`verified-user`&&(a=await Hi(e,i,r),a&&(i=await Ui(e,i,a,r)));let o=e.historyInternals.visitorStore,s=!1;for(;;){let c=o?.revision()??0,l=await e.readVisitorToken();if(!l&&!n.visitorTokenOptional)throw new e.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let u=await fetch(Bi(e,t,{...n.query,sessionId:i.sessionId}),{method:n.method,headers:{"X-Persona-Version":Li,...l?{"X-Visitor-Token":l}:{},...a?{"X-Identity-Proof":a}:{},...n.body===void 0?{}:{"Content-Type":`application/json`}},...n.body===void 0?{}:{body:JSON.stringify(n.body)},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!s){s=!0,i=await Gi(e,await Wi(e,u),a,r);continue}if(!u.ok)throw await Ki(e,u,r);let d=u.headers.get(`X-History-Identity-Status`),f=await u.json().catch(()=>void 0);if(o&&o.revision()!==c)throw new e.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return qi(e,d,a!==null,r),f}}function Yi(e){if(!e.isClientTokenMode())throw Error(`Conversation history is only available in client token mode`);if(!e.isHistoryCapable())throw new e.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`)}async function Xi(e,t){let n=await Ji(e,`conversations`,{method:`GET`,query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit===void 0?{}:{limit:t.limit},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(ia),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function Zi(e,t,n){let r=await Ji(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:ia(r),messages:Array.isArray(r?.messages)?r.messages:[],nextMessageCursor:typeof r?.nextMessageCursor==`string`?r.nextMessageCursor:null,conversationRevision:typeof r?.conversationRevision==`string`?r.conversationRevision:null}}async function Qi(e,t,n){Yi(e);let r=0;for(let t of n){let n=t.displayContent.length;if(n>na)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${na} character limit`);r+=n}if(r>ra)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${ra} character limit`);await e.initSession();let i=e.historyInternals.visitorStore,a=i?.revision()??0,o=await Ji(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:`PATCH`,body:{messages:n},scope:`browser`,keepalive:r<=ra,trackIdentity:!1}),s=typeof o?.conversationRevision==`string`?o.conversationRevision:null;return s&&e.clientSession?.conversationId===t&&(i?.revision()??0)===a&&e.historyInternals.setStoredConversationRevision?.(s),{conversationRevision:s}}async function $i(e,t,n){let r=await Ji(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function ea(e,t){let n=await Ji(e,`conversations`,{method:`DELETE`,query:{...t?.targetId===void 0?{}:{targetId:t.targetId}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted==`number`?n.deleted:0}}async function ta(e){Yi(e),e.setHistoryIdentityStatus({state:`resetting`});try{await Ji(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var na,ra,ia,aa,oa,sa,ca,la=W((()=>{Ri(),na=32768,ra=49152,ia=e=>{let t=e??{},n=typeof t.targetId==`string`?t.targetId:null;return{id:typeof t.id==`string`?t.id:``,title:typeof t.title==`string`?t.title:``,targetId:n,preview:typeof t.preview==`string`?t.preview:null,messageCount:typeof t.messageCount==`number`?t.messageCount:0,createdAt:typeof t.createdAt==`string`?t.createdAt:``,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:``}},aa=`The identity proof was not admitted; account history is unavailable`,oa=`The identity proof was rejected`,sa=`The request carried no visitor credential`,ca=`The stored visitor belongs to a different signed-in user`}));la(),Pt();const{setLoader:ua,load:da,provide:fa}=Nt({fallbackImport:()=>Promise.resolve().then(()=>(la(),zi))}),pa=da;fa(zi);var ma,ha=W((()=>{ti(),ma=e=>{let{mount:t,overlay:n,sessionRef:r}=e,i=(e,i,a)=>{let o=i.trim();if(!o||!r.current)return;let s=e.getAttribute(`data-tool-call-id`)??``,c=a.source===`free-text`;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:answered`,{detail:{toolUseId:s,answer:o,answers:a.structured,values:a.values??(a.source===`multi`?o.split(`, `):[o]),isFreeText:c,source:a.source},bubbles:!0,composed:!0})),Zr(n,s);let l=r.current.getMessages().find(e=>e.toolCall?.id===s);l?.agentMetadata?.awaitingLocalTool?r.current.resolveAskUserQuestion(l,a.structured??o):r.current.sendMessage(o)},a=e=>{let t=r.current;if(!t)return;let n=e.getAttribute(`data-tool-call-id`)??``,i=t.getMessages().find(e=>e.toolCall?.id===n);i&&t.persistAskUserQuestionProgress(i,{answers:Ur(e,i),currentIndex:Lr(e)})},o=e=>Object.entries(e).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `),s=t=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let n=Lr(t);if(n>=zr(t)-1)return;let i=r.current?.getMessages().find(e=>e.toolCall?.id===t.getAttribute(`data-tool-call-id`));i&&(ei(t,i,e.config(),n+1),a(t))};return{click:c=>{let l=c.target.closest(`[data-ask-user-action]`);if(!l)return;let u=l.closest(`[data-persona-ask-sheet-for]`);if(!u)return;let d=l.getAttribute(`data-ask-user-action`);if(c.preventDefault(),c.stopPropagation(),d===`dismiss`){let e=u.getAttribute(`data-tool-call-id`)??``;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{toolUseId:e},bubbles:!0,composed:!0})),Zr(n,e);let i=r.current?.getMessages().find(t=>t.toolCall?.id===e);i?.agentMetadata?.awaitingLocalTool&&(r.current?.markAskUserQuestionResolved(i),r.current?.resolveAskUserQuestion(i,`(dismissed)`))}else if(d===`pick`){let e=l.getAttribute(`data-option-label`);if(!e)return;let t=u.getAttribute(`data-multi-select`)===`true`,n=Br(u);if(n&&t){let t=Fr(u)[Lr(u)],n=new Set(Array.isArray(t)?t:[]);n.has(e)?n.delete(e):n.add(e),$r(u,Array.from(n)),a(u);return}if(n){$r(u,e),a(u),s(u);return}if(t){let e=l.getAttribute(`aria-pressed`)===`true`;l.setAttribute(`aria-pressed`,e?`false`:`true`),l.classList.toggle(`persona-ask-pill-selected`,!e);let t=u.querySelector(`[data-ask-user-action="submit-multi"]`);t&&(t.disabled=Qr(u).length===0);return}i(u,e,{source:`pick`,values:[e]})}else if(d===`submit-multi`){let e=Qr(u);if(e.length===0)return;i(u,e.join(`, `),{source:`multi`,values:e})}else if(d===`open-free-text`){let e=u.querySelector(`[data-ask-free-text-row="true"]`);e&&(e.classList.remove(`persona-hidden`),e.querySelector(`[data-ask-free-text-input="true"]`)?.focus())}else if(d===`focus-free-text`)u.querySelector(`[data-ask-free-text-input="true"]`)?.focus();else if(d===`submit-free-text`){let e=u.querySelector(`[data-ask-free-text-input="true"]`)?.value??``;if(!e.trim())return;if(Br(u)){$r(u,e.trim()),a(u),s(u);return}i(u,e,{source:`free-text`})}else if(d===`next`||d===`back`){if(!r.current)return;let t=u.getAttribute(`data-tool-call-id`)??``,n=r.current.getMessages().find(e=>e.toolCall?.id===t);if(!n)return;let i=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;if(i){let e=Fr(u)[Lr(u)];(typeof e!=`string`||e!==i)&&$r(u,i)}let o=d===`next`?1:-1,s=Lr(u)+o;ei(u,n,e.config(),s),a(u)}else if(d===`submit-all`){if(!r.current)return;let e=u.getAttribute(`data-tool-call-id`)??``,t=r.current.getMessages().find(t=>t.toolCall?.id===e);if(!t)return;let n=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;n&&$r(u,n);let a=Ur(u,t);r.current.persistAskUserQuestionProgress(t,{answers:a,currentIndex:Lr(u)});let s=o(a);i(u,s||`(submitted)`,{source:`submit-all`,structured:a})}else if(d===`skip`){if(!r.current)return;let s=u.getAttribute(`data-tool-call-id`)??``,c=r.current.getMessages().find(e=>e.toolCall?.id===s);if(!c)return;let l=Br(u),d=Lr(u),f=d>=zr(u)-1;if(!l){t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{toolUseId:s},bubbles:!0,composed:!0})),Zr(n,s),c.agentMetadata?.awaitingLocalTool&&(r.current.markAskUserQuestionResolved(c),r.current.resolveAskUserQuestion(c,`(dismissed)`));return}$r(u,``);let p=u.querySelector(`[data-ask-free-text-input="true"]`);if(p&&(p.value=``),f){let e=Ur(u,c),t=o(e);i(u,t||`(skipped)`,{source:`submit-all`,structured:e});return}ei(u,c,e.config(),d+1),a(u)}},keydown:e=>{if(e.key!==`Enter`)return;let t=e.target;if(!t.matches?.(`[data-ask-free-text-input="true"]`))return;let n=t.closest(`[data-persona-ask-sheet-for]`);if(!n)return;e.preventDefault();let r=t.value;r.trim()&&(Br(n)?($r(n,r.trim()),a(n),s(n)):i(n,r,{source:`free-text`}))}}}}));function ga(e,t,n){if(n===`input-start`)return t===0;let r=t>0?e[t-1]:``;return n===`line-start`?r===``||r===`
|
|
7
|
+
`),i=`message`,a=``,o=null;for(let e of r)e.startsWith(`event:`)?i=e.replace(`event:`,``).trim():e.startsWith(`data:`)?a+=e.replace(`data:`,``).trim():e.startsWith(`id:`)&&(o=e.slice(3).trim());let s=()=>{o!==null&&o!==``&&n({type:`cursor`,id:o})};if(!a){s();continue}let c;try{c=JSON.parse(a)}catch(e){n({type:`error`,error:e instanceof Error?e:/* @__PURE__ */ Error(`Failed to parse chat stream payload`)});continue}let l=typeof c==`object`&&c&&!Array.isArray(c)?c:null,d=i===`message`?typeof l?.type==`string`?l.type:`message`:i;if(e.onSSEEvent?.(d,c),e.parseSSEEvent){g.current=m;let t=await Ei(e,c,n,g,p,u,_);if(g.current&&g.current!==m&&(m=g.current),t){s();continue}}l&&(fe.push({...l,type:d}),pe()),s()}}pe()}var Oi,Q=W((()=>{En(),Nn(),er(),Si(),Oi=e=>e.startsWith(`{`)||e.startsWith(`[`)||e.startsWith(`<`)}));Q(),Pt();const{setLoader:ki,load:Ai,provide:ji,getSync:Mi}=Nt({fallbackImport:()=>Promise.resolve().then(()=>(Q(),Ci))}),Ni=Ai,Pi=ji,Fi=Mi;Pi(Ci);var Ii=`4.29.2`,Li,Ri=W((()=>{Li=Ii})),zi=/* @__PURE__ */ Mt({deleteAllConversations:()=>ea,deleteConversation:()=>$i,finalizeDisplayProjections:()=>Qi,getConversation:()=>Zi,historyErrorFor:()=>Ki,listConversations:()=>Xi,readErrorCode:()=>Wi,recoverFromUnauthorized:()=>Gi,resetVisitor:()=>ta});function Bi(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function Vi(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function Hi(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`authentication_required`,`This browser is bound to a signed-in user and needs a fresh identity proof`);return n&&e.setHistoryIdentityStatus({state:`browser_only`,reason:`proof_unavailable_before_binding`}),null}async function Ui(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let i=await e.reinitWithProof(n);if(i.visitor?.identityStatus!==`admitted`||i.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,aa);return i}async function Wi(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function Gi(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,oa);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,sa);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,ca);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function Ki(e,t,n){let r=await Wi(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,aa);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,oa)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,sa):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,ca):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function qi(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`ignored`?new e.HistoryClientError(`identity_contract_violation`,`Server reported an ignored identity proof on a success response`):new e.HistoryClientError(`proof_not_admitted`,`The response did not acknowledge the identity proof this request sent`)}if(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function Ji(e,t,n){Yi(e);let r=n.trackIdentity!==!1,i=await e.initSession(),a=null;Vi(e,n.scope)===`verified-user`&&(a=await Hi(e,i,r),a&&(i=await Ui(e,i,a,r)));let o=e.historyInternals.visitorStore,s=!1;for(;;){let c=o?.revision()??0,l=await e.readVisitorToken();if(!l&&!n.visitorTokenOptional)throw new e.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let u=await fetch(Bi(e,t,{...n.query,sessionId:i.sessionId}),{method:n.method,headers:{"X-Persona-Version":Li,...l?{"X-Visitor-Token":l}:{},...a?{"X-Identity-Proof":a}:{},...n.body===void 0?{}:{"Content-Type":`application/json`}},...n.body===void 0?{}:{body:JSON.stringify(n.body)},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!s){s=!0,i=await Gi(e,await Wi(e,u),a,r);continue}if(!u.ok)throw await Ki(e,u,r);let d=u.headers.get(`X-History-Identity-Status`),f=await u.json().catch(()=>void 0);if(o&&o.revision()!==c)throw new e.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return qi(e,d,a!==null,r),f}}function Yi(e){if(!e.isClientTokenMode())throw Error(`Conversation history is only available in client token mode`);if(!e.isHistoryCapable())throw new e.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`)}async function Xi(e,t){let n=await Ji(e,`conversations`,{method:`GET`,query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit===void 0?{}:{limit:t.limit},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(ia),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function Zi(e,t,n){let r=await Ji(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:ia(r),messages:Array.isArray(r?.messages)?r.messages:[],nextMessageCursor:typeof r?.nextMessageCursor==`string`?r.nextMessageCursor:null,conversationRevision:typeof r?.conversationRevision==`string`?r.conversationRevision:null}}async function Qi(e,t,n){Yi(e);let r=0;for(let t of n){let n=t.displayContent.length;if(n>na)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${na} character limit`);r+=n}if(r>ra)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${ra} character limit`);await e.initSession();let i=e.historyInternals.visitorStore,a=i?.revision()??0,o=await Ji(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:`PATCH`,body:{messages:n},scope:`browser`,keepalive:r<=ra,trackIdentity:!1}),s=typeof o?.conversationRevision==`string`?o.conversationRevision:null;return s&&e.clientSession?.conversationId===t&&(i?.revision()??0)===a&&e.historyInternals.setStoredConversationRevision?.(s),{conversationRevision:s}}async function $i(e,t,n){let r=await Ji(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function ea(e,t){let n=await Ji(e,`conversations`,{method:`DELETE`,query:{...t?.targetId===void 0?{}:{targetId:t.targetId}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted==`number`?n.deleted:0}}async function ta(e){Yi(e),e.setHistoryIdentityStatus({state:`resetting`});try{await Ji(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var na,ra,ia,aa,oa,sa,ca,la=W((()=>{Ri(),na=32768,ra=49152,ia=e=>{let t=e??{},n=typeof t.targetId==`string`?t.targetId:null;return{id:typeof t.id==`string`?t.id:``,title:typeof t.title==`string`?t.title:``,targetId:n,preview:typeof t.preview==`string`?t.preview:null,messageCount:typeof t.messageCount==`number`?t.messageCount:0,createdAt:typeof t.createdAt==`string`?t.createdAt:``,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:``}},aa=`The identity proof was not admitted; account history is unavailable`,oa=`The identity proof was rejected`,sa=`The request carried no visitor credential`,ca=`The stored visitor belongs to a different signed-in user`}));la(),Pt();const{setLoader:ua,load:da,provide:fa}=Nt({fallbackImport:()=>Promise.resolve().then(()=>(la(),zi))}),pa=da;fa(zi);var ma,ha=W((()=>{ti(),ma=e=>{let{mount:t,overlay:n,sessionRef:r}=e,i=(e,i,a)=>{let o=i.trim();if(!o||!r.current)return;let s=e.getAttribute(`data-tool-call-id`)??``,c=a.source===`free-text`;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:answered`,{detail:{toolUseId:s,answer:o,answers:a.structured,values:a.values??(a.source===`multi`?o.split(`, `):[o]),isFreeText:c,source:a.source},bubbles:!0,composed:!0})),Zr(n,s);let l=r.current.getMessages().find(e=>e.toolCall?.id===s);l?.agentMetadata?.awaitingLocalTool?r.current.resolveAskUserQuestion(l,a.structured??o):r.current.sendMessage(o)},a=e=>{let t=r.current;if(!t)return;let n=e.getAttribute(`data-tool-call-id`)??``,i=t.getMessages().find(e=>e.toolCall?.id===n);i&&t.persistAskUserQuestionProgress(i,{answers:Ur(e,i),currentIndex:Lr(e)})},o=e=>Object.entries(e).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `),s=t=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let n=Lr(t);if(n>=zr(t)-1)return;let i=r.current?.getMessages().find(e=>e.toolCall?.id===t.getAttribute(`data-tool-call-id`));i&&(ei(t,i,e.config(),n+1),a(t))};return{click:c=>{let l=c.target.closest(`[data-ask-user-action]`);if(!l)return;let u=l.closest(`[data-persona-ask-sheet-for]`);if(!u)return;let d=l.getAttribute(`data-ask-user-action`);if(c.preventDefault(),c.stopPropagation(),d===`dismiss`){let e=u.getAttribute(`data-tool-call-id`)??``;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{toolUseId:e},bubbles:!0,composed:!0})),Zr(n,e);let i=r.current?.getMessages().find(t=>t.toolCall?.id===e);i?.agentMetadata?.awaitingLocalTool&&(r.current?.markAskUserQuestionResolved(i),r.current?.resolveAskUserQuestion(i,`(dismissed)`))}else if(d===`pick`){let e=l.getAttribute(`data-option-label`);if(!e)return;let t=u.getAttribute(`data-multi-select`)===`true`,n=Br(u);if(n&&t){let t=Fr(u)[Lr(u)],n=new Set(Array.isArray(t)?t:[]);n.has(e)?n.delete(e):n.add(e),$r(u,Array.from(n)),a(u);return}if(n){$r(u,e),a(u),s(u);return}if(t){let e=l.getAttribute(`aria-pressed`)===`true`;l.setAttribute(`aria-pressed`,e?`false`:`true`),l.classList.toggle(`persona-ask-pill-selected`,!e);let t=u.querySelector(`[data-ask-user-action="submit-multi"]`);t&&(t.disabled=Qr(u).length===0);return}i(u,e,{source:`pick`,values:[e]})}else if(d===`submit-multi`){let e=Qr(u);if(e.length===0)return;i(u,e.join(`, `),{source:`multi`,values:e})}else if(d===`open-free-text`){let e=u.querySelector(`[data-ask-free-text-row="true"]`);e&&(e.classList.remove(`persona-hidden`),e.querySelector(`[data-ask-free-text-input="true"]`)?.focus())}else if(d===`focus-free-text`)u.querySelector(`[data-ask-free-text-input="true"]`)?.focus();else if(d===`submit-free-text`){let e=u.querySelector(`[data-ask-free-text-input="true"]`)?.value??``;if(!e.trim())return;if(Br(u)){$r(u,e.trim()),a(u),s(u);return}i(u,e,{source:`free-text`})}else if(d===`next`||d===`back`){if(!r.current)return;let t=u.getAttribute(`data-tool-call-id`)??``,n=r.current.getMessages().find(e=>e.toolCall?.id===t);if(!n)return;let i=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;if(i){let e=Fr(u)[Lr(u)];(typeof e!=`string`||e!==i)&&$r(u,i)}let o=d===`next`?1:-1,s=Lr(u)+o;ei(u,n,e.config(),s),a(u)}else if(d===`submit-all`){if(!r.current)return;let e=u.getAttribute(`data-tool-call-id`)??``,t=r.current.getMessages().find(t=>t.toolCall?.id===e);if(!t)return;let n=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;n&&$r(u,n);let a=Ur(u,t);r.current.persistAskUserQuestionProgress(t,{answers:a,currentIndex:Lr(u)});let s=o(a);i(u,s||`(submitted)`,{source:`submit-all`,structured:a})}else if(d===`skip`){if(!r.current)return;let s=u.getAttribute(`data-tool-call-id`)??``,c=r.current.getMessages().find(e=>e.toolCall?.id===s);if(!c)return;let l=Br(u),d=Lr(u),f=d>=zr(u)-1;if(!l){t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{toolUseId:s},bubbles:!0,composed:!0})),Zr(n,s),c.agentMetadata?.awaitingLocalTool&&(r.current.markAskUserQuestionResolved(c),r.current.resolveAskUserQuestion(c,`(dismissed)`));return}$r(u,``);let p=u.querySelector(`[data-ask-free-text-input="true"]`);if(p&&(p.value=``),f){let e=Ur(u,c),t=o(e);i(u,t||`(skipped)`,{source:`submit-all`,structured:e});return}ei(u,c,e.config(),d+1),a(u)}},keydown:e=>{if(e.key!==`Enter`)return;let t=e.target;if(!t.matches?.(`[data-ask-free-text-input="true"]`))return;let n=t.closest(`[data-persona-ask-sheet-for]`);if(!n)return;e.preventDefault();let r=t.value;r.trim()&&(Br(n)?($r(n,r.trim()),a(n),s(n)):i(n,r,{source:`free-text`}))}}}}));function ga(e,t,n){if(n===`input-start`)return t===0;let r=t>0?e[t-1]:``;return n===`line-start`?r===``||r===`
|
|
8
8
|
`:r===``||ba.test(r)}function _a(e,t,n=`@`,r=`anywhere`,i=!1){if(!n||t<=0||t>e.length)return null;let a=t-1;for(;a>=0;){let o=e[a];if(o===n)return ga(e,a,r)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(o===`
|
|
9
|
-
`||o===``||!i&&ba.test(o))return null;a--}return null}function va(e,t,n){for(let r of n){let n=_a(e,t,r.trigger,r.position??`anywhere`,r.allowSpaces??!1);if(n)return{channel:r,match:n}}return null}function ya(e){return!e||e!==`insertFromPaste`&&e!==`insertFromDrop`}var ba,xa=W((()=>{ba=/\s/}));function Sa(e){return[{trigger:e.trigger??`@`,position:e.triggerPosition??`anywhere`,allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},...(e.triggers??[]).map(e=>({trigger:e.trigger,position:e.triggerPosition??`anywhere`,allowSpaces:e.allowSpaces??!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton===!0,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText}))]}var $=W((()=>{})),Ca=W((()=>{}));function wa(e){e.delayMs!==void 0&&(Aa=Na(e.delayMs)),e.skipDelayMs!==void 0&&(ja=Na(e.skipDelayMs))}function Ta(e){Ia.get(e)?.hide()}function Ea(e){Ia.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:r,hint:i,enabled:a=!0,gap:o=Da,viewportPadding:s=Oa}=e,c=()=>t.ownerDocument,l=()=>c().defaultView??window,u=null,d=null,f=null,p=null,m,h=!1,g=!1,_=!1,v=()=>(typeof r==`function`?r():r).trim(),y=()=>(typeof i==`function`?i():i??``).trim(),b=()=>Na(e.delayMs??Aa),x=()=>Na(e.skipDelayMs??ja),S=()=>{m!==void 0&&(l().clearTimeout(m),m=void 0)},C=()=>{S();let e=u!==null;p?.(),p=null,u?.remove(),u=null,d=null,f=null,e&&Fa(x())},w=()=>{if(!u)return;let e=c(),n=l(),r=t.getBoundingClientRect(),i=u.getBoundingClientRect(),a=e.documentElement.clientWidth||n.innerWidth,d=e.documentElement.clientHeight||n.innerHeight,f=a-s-i.width,p=r.left+r.width/2-i.width/2,m=Va(p,s,f),h=r.top-s,g=d-s-r.bottom,_=h>=i.height+o||h>=g?`top`:`bottom`,v=_===`top`?r.top-o-i.height:r.bottom+o,y=d-s-i.height,b=Va(v,s,y),x=r.left+r.width/2,S=Math.max(ka,i.width-ka),C=Va(x-m,ka,S);u.dataset.placement=_,u.style.left=`${m}px`,u.style.top=`${b}px`,u.style.setProperty(`--persona-tooltip-arrow-x`,`${C}px`)},T=()=>{if(_||!a||u||!t.isConnected||Ra(t))return;let e=v(),n=Ba(t);if(!e||!n)return;let r=c(),i=l();u=r.createElement(`div`),u.className=`persona-control-tooltip`,u.setAttribute(`role`,`tooltip`),u.dataset.state=`measuring`,u.style.zIndex=String(vi);let o=i.getComputedStyle?.(t);if(o){for(let e of Ha){let t=o.getPropertyValue(e).trim();t&&u.style.setProperty(e,t)}o.fontFamily&&(u.style.fontFamily=o.fontFamily)}d=r.createElement(`span`),d.className=`persona-control-tooltip__label`,d.textContent=e,u.appendChild(d);let s=y();s&&(f=r.createElement(`span`),f.className=`persona-control-tooltip__hint`,f.textContent=s,u.appendChild(f));let m=r.createElement(`span`);m.className=`persona-control-tooltip__arrow`,u.appendChild(m),n.appendChild(u),w(),u.dataset.state=`open`;let h=()=>{t.isConnected?(d&&(d.textContent=v()),f&&(f.textContent=y()),w()):C()};i.addEventListener(`scroll`,h,!0),i.addEventListener(`resize`,h);let g=t.getRootNode(),b=za(g)?g:r.documentElement,x=typeof MutationObserver>`u`?null:new MutationObserver(()=>{t.isConnected||C()});x?.observe(b,{childList:!0,subtree:!0}),p=()=>{i.removeEventListener(`scroll`,h,!0),i.removeEventListener(`resize`,h),x?.disconnect()}},E=e=>{_||u||(S(),e||b()<=0||Pa()?T():m=l().setTimeout(()=>{m=void 0,T()},b()))},D=()=>{h||g?E(g):C()},O=()=>{let e=l();e.matchMedia&&e.matchMedia(`(hover: none)`).matches||(h=!0,D())},k=()=>{h=!1,D()},ee=()=>{try{g=t.matches(`:focus-visible`)}catch{g=!0}D()},A=()=>{g=!1,D()},te=()=>{h=!1,g=!1,C()},ne=e=>{e.key===`Escape`&&te()};n.addEventListener(`mouseenter`,O),n.addEventListener(`mouseleave`,k),t.addEventListener(`focus`,ee),t.addEventListener(`blur`,A),t.addEventListener(`keydown`,ne),t.addEventListener(`click`,te);let re={get isOpen(){return u!==null},show:T,hide:C,reposition:w,destroy:()=>{_||(_=!0,C(),n.removeEventListener(`mouseenter`,O),n.removeEventListener(`mouseleave`,k),t.removeEventListener(`focus`,ee),t.removeEventListener(`blur`,A),t.removeEventListener(`keydown`,ne),t.removeEventListener(`click`,te),Ia.delete(t))}};return Ia.set(t,re),re}var Da,Oa,ka,Aa,ja,Ma,Na,Pa,Fa,Ia,La,Ra,za,Ba,Va,Ha,Ua=W((()=>{yi(),Ca(),Da=8,Oa=8,ka=10,Aa=200,ja=300,Ma=0,Na=e=>Math.max(0,e),Pa=()=>Date.now()<Ma,Fa=e=>{Ma=e>0?Date.now()+e:0},Ia=/* @__PURE__ */ new WeakMap,La=`data-persona-tooltip-suppressed`,Ra=e=>typeof e.closest==`function`&&e.closest(`[data-persona-tooltip-suppressed]`)!==null,za=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&`host`in e,Ba=e=>{let t=e.getRootNode?.();return za(t)?t:e.ownerDocument.body},Va=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),Ha=[...[`background`,`foreground`,`hint-fg`,`radius`,`font-size`,`padding`,`max-width`,`shadow`,`arrow-display`].map(e=>`--persona-tooltip-${e}`),`--persona-font-family`,`--persona-radius-sm`]})),Wa,Ga,Ka,qa=W((()=>{Wa=(e,t)=>e.visible!==!1&&(e.mode!==`transient`||t===`connecting`||t===`paused`||t===`resuming`||t===`error`),Ga=(e,t,n)=>{let r=t.mode===`transient`,i=e.hasAttribute(`data-persona-composer-reason`)||e.hasAttribute(`data-persona-composer-notice`);e.style.display=Wa(t,n)||r&&i&&t.visible!==!1?``:`none`,e.classList.toggle(`persona-mt-2`,!r),e.classList.toggle(`persona-mb-2`,r)},Ka=(e,t,n)=>{t.parentElement&&e.parentElement===t.parentElement&&(n.mode===`transient`?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))}}));function Ja(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=Ya(t)&&Ya(r)?Ja(t,r):r}return n}var Ya,Xa=W((()=>{Ya=e=>typeof e==`object`&&!!e&&!Array.isArray(e)}));function Za(e,t=``){return Object.entries(e).flatMap(([e,n])=>{let r=t?`${t}.${e}`:e;return ao(n)?Za(n,r):[r]})}function Qa(e,t){for(let n of t.split(`.`)){if(!ao(e)||!Object.prototype.hasOwnProperty.call(e,n))return`absent`;if(e=e[n],e===void 0)return`clear`}return`explicit`}function $a(e,t){return e?.[io]??t.filter(t=>Qa(e,t)===`explicit`)}function eo(e,t){return Object.defineProperty(e,io,{value:t,enumerable:!0,configurable:!0}),e}function to(e,t,n){return eo(e,$a(t,Za(n)))}function no(e,t,n){let r=t[io];if(r)return r;let i=new Set($a(e,n));for(let e of n){let n=Qa(t,e);n===`clear`&&i.delete(e),n===`explicit`&&i.add(e)}return[...i]}function ro(e,t,n){let r={...e};for(let e of t){if(n.includes(e))continue;let t=e.split(`.`),i=r;for(let e of t.slice(0,-1)){let t=i[e];if(!ao(t)){i=void 0;break}i[e]={...t},i=i[e]}i&&delete i[t[t.length-1]]}return r}var io,ao,oo=W((()=>{io=Symbol(`persona.defaultsProvenance`),ao=e=>typeof e==`object`&&!!e&&!Array.isArray(e)})),so,co,lo,uo,fo,po,mo,ho,go=W((()=>{so=Symbol(`persona.panelAliasProvenance`),co=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),lo=(e,t)=>co(e,t)&&e[t]!==void 0,uo=e=>({launcherWidth:lo(e?.launcher,`width`),legacyLauncherWidth:lo(e,`launcherWidth`),sidebarWidth:lo(e?.launcher,`sidebarWidth`),dockWidth:lo(e?.launcher?.dock,`width`)}),fo=e=>{let t=e?.[so];return t?{...t}:uo(e)},po=(e,t)=>(Object.defineProperty(e,so,{value:t,enumerable:!0,configurable:!0}),e),mo=(e,t)=>po(e,fo(t)),ho=(e,t)=>{let n=t[so];if(n)return{...n};let r=fo(e);return co(t,`launcherWidth`)&&(r.legacyLauncherWidth=t.launcherWidth!==void 0),co(t,`launcher`)&&t.launcher===void 0?(r.launcherWidth=!1,r.sidebarWidth=!1,r.dockWidth=!1,r):(co(t.launcher,`width`)&&(r.launcherWidth=t.launcher?.width!==void 0),co(t.launcher,`sidebarWidth`)&&(r.sidebarWidth=t.launcher?.sidebarWidth!==void 0),co(t.launcher,`dock`)&&t.launcher?.dock===void 0?r.dockWidth=!1:co(t.launcher?.dock,`width`)&&(r.dockWidth=t.launcher?.dock?.width!==void 0),r)}}));function _o(e){return e?.future?.v5Defaults===!0?`v5`:`v4`}function vo(e){let t=_o(e)===`v5`?jo:ko;return Ja(Oo,t)}function yo(e,t){if(e||t)return e?t?Ja(e,t):e:t}function bo(e){let t=vo(e);return e?to(mo({...t,...e,theme:yo(t.theme,e.theme),darkTheme:yo(t.darkTheme,e.darkTheme),launcher:{...t.launcher,...e.launcher,dock:{...t.launcher?.dock,...e.launcher?.dock},clearChat:{...t.launcher?.clearChat,...e.launcher?.clearChat}},...t.composer||e.composer?{composer:{...t.composer,...e.composer}}:{},tooltip:{...t.tooltip,...e.tooltip},copy:{...t.copy,...e.copy},sendButton:{...t.sendButton,...e.sendButton},statusIndicator:{...t.statusIndicator,...e.statusIndicator},voiceRecognition:{...t.voiceRecognition,...e.voiceRecognition},features:(()=>{let n=t.features?.artifacts,r=e.features?.artifacts,i=t.features?.scrollToBottom,a=e.features?.scrollToBottom,o=t.features?.scrollBehavior,s=e.features?.scrollBehavior,c=t.features?.streamAnimation,l=e.features?.streamAnimation,u=t.features?.askUserQuestion,d=e.features?.askUserQuestion,f=t.features?.history,p=e.features?.history,m=n===void 0&&r===void 0?void 0:{...n,...r,layout:{...n?.layout,...r?.layout}},h=i===void 0&&a===void 0?void 0:{...i,...a},g=o===void 0&&s===void 0?void 0:{...o,...s},_=c===void 0&&l===void 0?void 0:{...c,...l},v=u===void 0&&d===void 0?void 0:{...u,...d,styles:{...u?.styles,...d?.styles}},y=f===void 0&&p===void 0?void 0:{...f,...p,copy:{...f?.copy,...p?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...h===void 0?{}:{scrollToBottom:h},...g===void 0?{}:{scrollBehavior:g},...m===void 0?{}:{artifacts:m},..._===void 0?{}:{streamAnimation:_},...v===void 0?{}:{askUserQuestion:v},...y===void 0?{}:{history:y}}})(),suggestionChips:e.suggestionChips??t.suggestionChips,suggestionChipsConfig:{...t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...t.layout,...e.layout,header:{...t.layout?.header,...e.layout?.header},messages:{...t.layout?.messages,...e.layout?.messages,...t.layout?.messages?.user||e.layout?.messages?.user?{user:{...t.layout?.messages?.user,...e.layout?.messages?.user}}:{},...t.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...t.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...t.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...t.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...t.layout?.slots,...e.layout?.slots}},markdown:{...t.markdown,...e.markdown,options:{...t.markdown?.options,...e.markdown?.options}},messageActions:{...t.messageActions,...e.messageActions}},e),e,jo):to(mo(t),void 0,jo)}var xo,So,Co,wo,To,Eo,Do,Oo,ko,Ao,jo,Mo,No=W((()=>{Xa(),oo(),go(),Ca(),xo=`min(440px, calc(100vw - 24px))`,So=`440px`,Co=`40px`,wo=`How can I help...`,To={collapsedMode:`tool-call`,activePreview:!1,grouped:!1,groupedMode:`stack`,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},Eo={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},Do={enabled:!0,mountMode:`floating`,dock:{side:`right`,width:`420px`},title:`Chat Assistant`,subtitle:`Here to help you get answers fast`,agentIconText:`💬`,agentIconName:`bot`,headerIconName:`bot`,position:`bottom-right`,width:xo,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:`40px`,headerIconSize:Co,closeButtonPaddingX:`0px`,closeButtonPaddingY:`0px`,callToActionIconName:`arrow-up-right`,callToActionIconText:``,callToActionIconSize:`32px`,callToActionIconPadding:`5px`,callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:`transparent`,clearChat:{backgroundColor:`transparent`,borderColor:`transparent`,enabled:!0,placement:`inline`,iconName:`refresh-cw`,showTooltip:!0,tooltipText:`Clear chat`,paddingX:`0px`,paddingY:`0px`},headerIconHidden:!1,border:void 0,shadow:`0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)`},Oo={apiUrl:`https://api.runtype.com/api/chat/dispatch`,clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:`light`,tooltip:{delayMs:200,skipDelayMs:300},launcher:Do,copy:{inputPlaceholder:wo,sendButtonLabel:`Send`},sendButton:{borderWidth:`0px`,paddingX:`12px`,paddingY:`10px`,borderColor:void 0,useIcon:!0,iconText:`↑`,showTooltip:!0,tooltipText:`Send message`,iconName:`send`},statusIndicator:{visible:!0,idleText:`Online`,connectingText:`Connecting…`,connectedText:`Streaming…`,errorText:`Offline`},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:`mic`,borderWidth:`0px`,iconColor:void 0,backgroundColor:`transparent`,borderColor:`transparent`,recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:`transparent`,showTooltip:!0,tooltipText:`Start voice recognition`},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:`arrow-down`,label:``},scrollBehavior:{mode:`anchor-top`,anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:To,reasoningDisplay:Eo,streamAnimation:{type:`none`,placeholder:`none`,speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:`Other…`,freeTextPlaceholder:`Type your answer…`,submitLabel:`Send`},history:{enabled:!1,presentation:`panel`,showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:[`Show me what you can help with`,`Walk me through getting started`,`Answer a question about this page`],suggestionChipsConfig:{fontFamily:`sans-serif`,fontWeight:`500`,paddingX:`12px`,paddingY:`6px`},layout:{header:{layout:`default`,showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:`bubble`,avatar:{show:!1,position:`left`},timestamp:{show:!1,position:`below`},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:`hover`,align:`right`,layout:`pill-inside`},debug:!1},ko={},Ao={variant:`circle`,width:`min(400px, calc(100vw - 24px))`,headerIconSize:`20px`},jo={launcher:Ao,features:{toolCallDisplay:{variant:`row`,iconVisibility:`active`,autoExpand:!1,grouped:!0,groupedMode:`collapsible`,loadingAnimation:`shimmer`},reasoningDisplay:{variant:`row`,iconVisibility:`active`,autoExpand:!1,loadingAnimation:`shimmer`}},composer:{layout:`single-row`,placement:`overlay`},sendButton:{iconName:`arrow-up`},statusIndicator:{mode:`transient`},layout:{contentMaxWidth:`768px`,topFade:!0,header:{showSubtitle:!1},messages:{assistant:{width:`full`}}}},Mo=vo()}));function Po(e){return typeof e==`string`?[{type:`text`,text:e}]:e}function Fo(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Io(e){return typeof e!=`string`&&e.some(e=>e.type===`image`)}function Lo(e){return typeof e==`string`?[]:e.filter(e=>e.type===`image`)}function Ro(e){return{type:`text`,text:e}}function zo(e,t){return{type:`image`,image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Bo(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result;t({type:`image`,image:n,mimeType:e.type,alt:e.name})},r.onerror=()=>n(/* @__PURE__ */ Error(`Failed to read file`)),r.readAsDataURL(e)})}function Vo(e,t=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`],n=10485760){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(`, `)}`}}function Ho(e){return Xo.includes(e)||e.startsWith(`image/`)}function Uo(e){return Ho(e.type)}function Wo(e,t,n){return{type:`file`,data:e,mimeType:t,filename:n}}async function Go(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result;Uo(e)?t({type:`image`,image:n,mimeType:e.type,alt:e.name}):t({type:`file`,data:n,mimeType:e.type,filename:e.name})},r.onerror=()=>n(/* @__PURE__ */ Error(`Failed to read file`)),r.readAsDataURL(e)})}function Ko(e,t=Qo,n=10485760){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(`, `)}`}}function qo(e){let t=e.split(`.`);return t.length>1?t.pop().toLowerCase():``}function Jo(e,t){let n=qo(t).toUpperCase();return{"application/pdf":`PDF`,"text/plain":`TXT`,"text/markdown":`MD`,"text/csv":`CSV`,"application/msword":`DOC`,"application/vnd.openxmlformats-officedocument.wordprocessingml.document":`DOCX`,"application/vnd.ms-excel":`XLS`,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":`XLSX`,"application/json":`JSON`}[e]||n||`FILE`}var Yo,Xo,Zo,Qo,$o=W((()=>{Yo=`[Image]`,Xo=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/svg+xml`,`image/bmp`],Zo=[`application/pdf`,`text/plain`,`text/markdown`,`text/csv`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/json`],Qo=[...Xo,...Zo]}));function es(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let n=t.getComputedStyle(e).lineHeight;if(!n||!n.trim().endsWith(`px`))return 20;let r=parseFloat(n);return Number.isFinite(r)&&r>0?r:20}function ts(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:e>0?e:t}function ns(e,t){e.style.maxHeight=`${t*es(e)}px`,e.style.overflowY=`auto`}function rs(e){let t=e?.ownerDocument?.defaultView??(typeof window<`u`?window:null);if(!t||typeof t.matchMedia!=`function`)return!1;try{return t.matchMedia(`(pointer: coarse)`).matches===!0}catch{return!1}}function is(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function as(e,t){if(e.key!==`Enter`||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,r=t.submitKey??`enter`;return r===`none`?!1:r===`mod-enter`?n:n||!is(t)}function os(e){return(e.submitKey??`enter`)===`enter`?is(e)?`enter`:`send`:`enter`}function ss(e,t){e.setAttribute(`enterkeyhint`,os(t))}function cs(e,t){let n=t?.autocomplete;e.setAttribute(`autocomplete`,typeof n==`string`&&n?n:`off`);let r=(t,n)=>{n===void 0?e.removeAttribute(t):e.setAttribute(t,n)};r(`autocapitalize`,typeof t?.autocapitalize==`string`?t.autocapitalize:void 0),r(`spellcheck`,typeof t?.spellcheck==`boolean`?String(t.spellcheck):void 0),r(`inputmode`,typeof t?.inputmode==`string`&&t.inputmode?t.inputmode:void 0),r(`aria-label`,typeof t?.ariaLabel==`string`&&t.ariaLabel?t.ariaLabel:void 0)}function ls(e){return e===!0?{disabled:!0}:!e||typeof e!=`object`?{disabled:!1}:{disabled:!0,reason:typeof e.reason==`string`&&e.reason?e.reason:void 0}}var us=W((()=>{})),ds,fs,ps,ms,hs,gs,_s,vs,ys,bs,xs=W((()=>{qa(),Y(),mn(),No(),$o(),Ua(),us(),ds=`persona-composer-control`,fs=`persona-composer-control--glyph`,ps=(e,t,n)=>{let r=e.ownerDocument?.defaultView;if(!r)return;let i=r.getComputedStyle(e);for(let e of n){let n=i.getPropertyValue(e).trim();n?t.style.setProperty(e,n):t.style.removeProperty(e)}},ms=(e,t)=>{let n=q(`textarea`);n.setAttribute(`data-persona-composer-input`,``),n.placeholder=e?.copy?.inputPlaceholder??`How can I help...`,n.dir=`auto`,ss(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:rs(n)}),cs(n,e?.composer?.inputAttributes),n.className=`persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea`,n.rows=1,n.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,n.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`;let r=ts(e?.composer?.maxLines,t?.defaultMaxLines??3),i=`${r*20}px`;n.style.maxHeight=i,n.style.overflowY=`auto`;let a=()=>{let e=n.style.maxHeight;if(e!==i){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=r*es(n);return i=`${t}px`,n.style.maxHeight=i,t},o=()=>{n.addEventListener(`input`,()=>{n.style.height=`auto`;let e=Math.min(n.scrollHeight,a());n.style.height=`${e}px`})};return n.style.border=`none`,n.style.outline=`none`,n.style.borderWidth=`0`,n.style.borderStyle=`none`,n.style.borderColor=`transparent`,n.addEventListener(`focus`,()=>{n.style.border=`none`,n.style.outline=`none`,n.style.borderWidth=`0`,n.style.borderStyle=`none`,n.style.borderColor=`transparent`,n.style.boxShadow=`none`}),n.addEventListener(`blur`,()=>{n.style.border=`none`,n.style.outline=`none`}),{textarea:n,attachAutoResize:o}},hs=(e,t,n=`send`)=>{let r=J(`span`,{className:`persona-composer-glyph-stack`,attrs:{"data-mode":n,"data-persona-glyph-stack":``}});return e.setAttribute(`data-glyph`,`send`),t.setAttribute(`data-glyph`,`stop`),r.append(e,t),r},gs=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,r=t.iconText??`↑`,i=t.iconName,a=t.stopIconName??`square`,o=t.tooltipText??`Send message`,s=t.stopTooltipText??`Stop generating`,c=e?.copy?.sendButtonLabel??`Send`,l=e?.copy?.stopButtonLabel??`Stop`,u=t.showTooltip??!1,d=t.size,f=parseFloat(d??``)||40,p=t.backgroundColor,m=t.textColor,h=q(`div`,`persona-send-button-wrapper`),g=J(`button`,{className:tr(`persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer`,n?`persona-flex persona-items-center persona-justify-center ${ds}`:`persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold`,n&&!p&&`persona-bg-persona-primary`,!n&&!m&&`persona-text-white`),attrs:{type:`submit`,"data-persona-composer-submit":``,"data-persona-send-mode":`send`},style:{width:n?d:void 0,height:n?d:void 0,minWidth:n?d:void 0,minHeight:n?d:void 0,fontSize:n?`18px`:void 0,lineHeight:n?`1`:void 0,color:n?m||`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`:m||void 0,backgroundColor:n&&p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?`solid`:void 0,borderColor:t.borderColor||void 0,paddingLeft:n?`0`:t.paddingX||void 0,paddingRight:n?`0`:t.paddingX||void 0,paddingTop:n?`0`:t.paddingY||void 0,paddingBottom:n?`0`:t.paddingY||void 0}}),_=null,v=null,y=null;if(n){let e=parseFloat(t.iconSize??``)||Math.round(f*.5),n=t.iconStrokeWidth??2,o=m?.trim()||`currentColor`;if(i&&(_=K(i,e,o,n)),v=K(a,e,o,n),!t.iconSize)for(let t of[_,v])t&&(t.style.width=`var(--persona-components-composer-sendIconSize, ${e}px)`,t.style.height=`var(--persona-components-composer-sendIconSize, ${e}px)`);_&&v?(y=hs(_,v),g.appendChild(y)):_?g.appendChild(_):(g.textContent=r,v=null)}else g.textContent=c;g.setAttribute(`aria-label`,o),h.appendChild(g),Ea({anchor:g,trigger:h,text:()=>g.getAttribute(`aria-label`)??``,enabled:u});let b=`send`;return{button:g,wrapper:h,setMode:e=>{if(e===b)return;b=e;let t=e===`stop`?s:o;g.setAttribute(`aria-label`,t),g.setAttribute(`data-persona-send-mode`,e),n?(g.querySelector(`[data-persona-glyph-stack]`)??y)?.setAttribute(`data-mode`,e):g.textContent=e===`stop`?l:c},glyphStack:y}},_s=e=>{let t=e?.voiceRecognition??{};if(t.enabled!==!0)return null;let n=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),r=t.provider?.type===`runtype`,i=t.provider?.type===`custom`;if(!(n||r||i))return null;let a=t.iconName??`mic`,o=t.iconSize,s=parseFloat(o??``)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,l=t.iconColor??e?.sendButton?.textColor,u=q(`div`,`persona-send-button-wrapper`),d=J(`button`,{className:tr(`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer`,ds,!o&&`persona-composer-control--glyph`),attrs:{type:`button`,"data-persona-composer-mic":``,"data-state":`idle`,"aria-label":t.tooltipText??`Start voice recognition`},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:`18px`,lineHeight:`1`,color:l||`var(--persona-text, #111827)`,backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?`solid`:void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),f=K(a,s,l||`currentColor`,1.5);f?d.appendChild(f):d.textContent=`🎤`,u.appendChild(d);let p=t.tooltipText??`Start voice recognition`;return Ea({anchor:d,trigger:u,text:()=>d.getAttribute(`aria-label`)??p,enabled:t.showTooltip??!1}),{button:d,wrapper:u}},vs=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=q(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`);n.setAttribute(`data-persona-composer-attachment-previews`,``),n.style.display=`none`;let r=q(`input`);r.type=`file`,r.setAttribute(`data-persona-composer-attachment-input`,``),r.accept=(t.allowedTypes??Qo).join(`,`),r.multiple=(t.maxFiles??4)>1,r.style.display=`none`,r.setAttribute(`aria-label`,`Attach files`);let i=t.buttonIconName??`paperclip`,a=q(`div`,`persona-send-button-wrapper`),o=J(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${ds} ${fs}`,attrs:{type:`button`,"data-persona-composer-attachment-button":``,"aria-label":t.buttonTooltipText??`Attach file`},style:{fontSize:`18px`,lineHeight:`1`}}),s=K(i,24,`currentColor`,1.5);s?o.appendChild(s):o.textContent=`📎`,o.addEventListener(`click`,e=>{e.preventDefault(),r.click()}),a.appendChild(o);let c=t.buttonTooltipText??`Attach file`;return Ea({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??c}),{button:o,wrapper:a,input:r,previewsContainer:n}},ys=e=>{let t=e?.statusIndicator??{},n=t.align===`left`?`persona-text-left`:t.align===`center`?`persona-text-center`:`persona-text-right`,r=q(`div`,`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute(`data-persona-composer-status`,``),Ga(r,t,`idle`);let i=t.idleText??`Online`;if(t.idleLink){let e=q(`a`);e.href=t.idleLink,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=i,e.style.color=`inherit`,e.style.textDecoration=`none`,r.appendChild(e)}else r.textContent=i;return r},bs=()=>J(`div`,{className:`persona-mb-3 persona-flex persona-flex-wrap persona-gap-2`,attrs:{"data-persona-composer-suggestions":``}})}));function Ss(e){let{config:t,onOpen:n}=e,r=t.buttonIconName??`plus`,i=t.buttonTooltipText??`Add context`,a=q(`div`,`persona-send-button-wrapper`),o=J(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${ds} ${fs}`,attrs:{type:`button`,"data-persona-composer-mention-button":``,"aria-label":i,"aria-haspopup":`listbox`,"aria-expanded":`false`},style:{fontSize:`18px`,lineHeight:`1`}}),s=K(r,24,`currentColor`,1.5);return s?o.appendChild(s):o.textContent=`+`,o.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n()}),a.appendChild(o),Ea({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??i}),{button:o,wrapper:a}}var Cs=W((()=>{Y(),mn(),Ua(),xs()})),ws,Ts,Es,Ds=W((()=>{Pt(),{setLoader:ws,load:Ts}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/context-mentions`)}),Es=Ts})),Os,ks,As,js=W((()=>{Pt(),{setLoader:Os,load:ks}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/context-mentions-inline`),resetOnSetLoader:!0}),As=ks}));function Ms(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=J(`span`,{className:tr(`persona-mention-token`,t.readonly&&`persona-mention-token-readonly`),attrs:{"data-mention-source":e.sourceId,title:e.label,role:`img`,"aria-label":`${e.label} mention`}});e.color&&n.style.setProperty(`--persona-mention-token-accent`,e.color);let r=K(e.iconName??`at-sign`,13,`currentColor`,2);if(r){let e=q(`span`,`persona-mention-token-icon`);e.appendChild(r),n.appendChild(e)}return n.appendChild(J(`span`,{className:`persona-mention-token-label`,text:`@${e.label}`})),n}var Ns=W((()=>{Y(),mn()}));function Ps(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:r,createMentionButton:i}=e.deps??Fs,a=e.config.contextMentions;if(!a?.enabled)return null;let o=Sa(a).filter(e=>e.sources.length>0);if(o.length===0)return typeof console<`u`&&console.warn(`[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled.`),null;let s=o.filter(e=>e.sources.some(e=>typeof e.matchCommand==`function`)),c=e=>s.some(t=>t.trigger?t.position===`line-start`?e.split(`
|
|
9
|
+
`||o===``||!i&&ba.test(o))return null;a--}return null}function va(e,t,n){for(let r of n){let n=_a(e,t,r.trigger,r.position??`anywhere`,r.allowSpaces??!1);if(n)return{channel:r,match:n}}return null}function ya(e){return!e||e!==`insertFromPaste`&&e!==`insertFromDrop`}var ba,xa=W((()=>{ba=/\s/}));function Sa(e){return[{trigger:e.trigger??`@`,position:e.triggerPosition??`anywhere`,allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},...(e.triggers??[]).map(e=>({trigger:e.trigger,position:e.triggerPosition??`anywhere`,allowSpaces:e.allowSpaces??!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton===!0,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText}))]}var Ca=W((()=>{})),wa=W((()=>{}));function Ta(e){e.delayMs!==void 0&&(Aa=Na(e.delayMs)),e.skipDelayMs!==void 0&&(ja=Na(e.skipDelayMs))}function $(e){Ia.get(e)?.hide()}function Ea(e){Ia.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:r,hint:i,enabled:a=!0,gap:o=Da,viewportPadding:s=Oa}=e,c=()=>t.ownerDocument,l=()=>c().defaultView??window,u=null,d=null,f=null,p=null,m,h=!1,g=!1,_=!1,v=()=>(typeof r==`function`?r():r).trim(),y=()=>(typeof i==`function`?i():i??``).trim(),b=()=>Na(e.delayMs??Aa),x=()=>Na(e.skipDelayMs??ja),S=()=>{m!==void 0&&(l().clearTimeout(m),m=void 0)},C=()=>{S();let e=u!==null;p?.(),p=null,u?.remove(),u=null,d=null,f=null,e&&Fa(x())},w=()=>{if(!u)return;let e=c(),n=l(),r=t.getBoundingClientRect(),i=u.getBoundingClientRect(),a=e.documentElement.clientWidth||n.innerWidth,d=e.documentElement.clientHeight||n.innerHeight,f=a-s-i.width,p=r.left+r.width/2-i.width/2,m=Va(p,s,f),h=r.top-s,g=d-s-r.bottom,_=h>=i.height+o||h>=g?`top`:`bottom`,v=_===`top`?r.top-o-i.height:r.bottom+o,y=d-s-i.height,b=Va(v,s,y),x=r.left+r.width/2,S=Math.max(ka,i.width-ka),C=Va(x-m,ka,S);u.dataset.placement=_,u.style.left=`${m}px`,u.style.top=`${b}px`,u.style.setProperty(`--persona-tooltip-arrow-x`,`${C}px`)},T=()=>{if(_||!a||u||!t.isConnected||Ra(t))return;let e=v(),n=Ba(t);if(!e||!n)return;let r=c(),i=l();u=r.createElement(`div`),u.className=`persona-control-tooltip`,u.setAttribute(`role`,`tooltip`),u.dataset.state=`measuring`,u.style.zIndex=String(vi);let o=i.getComputedStyle?.(t);if(o){for(let e of Ha){let t=o.getPropertyValue(e).trim();t&&u.style.setProperty(e,t)}o.fontFamily&&(u.style.fontFamily=o.fontFamily)}d=r.createElement(`span`),d.className=`persona-control-tooltip__label`,d.textContent=e,u.appendChild(d);let s=y();s&&(f=r.createElement(`span`),f.className=`persona-control-tooltip__hint`,f.textContent=s,u.appendChild(f));let m=r.createElement(`span`);m.className=`persona-control-tooltip__arrow`,u.appendChild(m),n.appendChild(u),w(),u.dataset.state=`open`;let h=()=>{t.isConnected?(d&&(d.textContent=v()),f&&(f.textContent=y()),w()):C()};i.addEventListener(`scroll`,h,!0),i.addEventListener(`resize`,h);let g=t.getRootNode(),b=za(g)?g:r.documentElement,x=typeof MutationObserver>`u`?null:new MutationObserver(()=>{t.isConnected||C()});x?.observe(b,{childList:!0,subtree:!0}),p=()=>{i.removeEventListener(`scroll`,h,!0),i.removeEventListener(`resize`,h),x?.disconnect()}},E=e=>{_||u||(S(),e||b()<=0||Pa()?T():m=l().setTimeout(()=>{m=void 0,T()},b()))},D=()=>{h||g?E(g):C()},O=()=>{let e=l();e.matchMedia&&e.matchMedia(`(hover: none)`).matches||(h=!0,D())},k=()=>{h=!1,D()},ee=()=>{try{g=t.matches(`:focus-visible`)}catch{g=!0}D()},te=()=>{g=!1,D()},ne=()=>{h=!1,g=!1,C()},re=e=>{e.key===`Escape`&&ne()};n.addEventListener(`mouseenter`,O),n.addEventListener(`mouseleave`,k),t.addEventListener(`focus`,ee),t.addEventListener(`blur`,te),t.addEventListener(`keydown`,re),t.addEventListener(`click`,ne);let ie={get isOpen(){return u!==null},show:T,hide:C,reposition:w,destroy:()=>{_||(_=!0,C(),n.removeEventListener(`mouseenter`,O),n.removeEventListener(`mouseleave`,k),t.removeEventListener(`focus`,ee),t.removeEventListener(`blur`,te),t.removeEventListener(`keydown`,re),t.removeEventListener(`click`,ne),Ia.delete(t))}};return Ia.set(t,ie),ie}var Da,Oa,ka,Aa,ja,Ma,Na,Pa,Fa,Ia,La,Ra,za,Ba,Va,Ha,Ua=W((()=>{yi(),wa(),Da=8,Oa=8,ka=10,Aa=200,ja=300,Ma=0,Na=e=>Math.max(0,e),Pa=()=>Date.now()<Ma,Fa=e=>{Ma=e>0?Date.now()+e:0},Ia=/* @__PURE__ */ new WeakMap,La=`data-persona-tooltip-suppressed`,Ra=e=>typeof e.closest==`function`&&e.closest(`[data-persona-tooltip-suppressed]`)!==null,za=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&`host`in e,Ba=e=>{let t=e.getRootNode?.();return za(t)?t:e.ownerDocument.body},Va=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),Ha=[...[`background`,`foreground`,`hint-fg`,`radius`,`font-size`,`padding`,`max-width`,`shadow`,`arrow-display`].map(e=>`--persona-tooltip-${e}`),`--persona-font-family`,`--persona-radius-sm`]})),Wa,Ga,Ka,qa=W((()=>{Wa=(e,t)=>e.visible!==!1&&(e.mode!==`transient`||t===`connecting`||t===`paused`||t===`resuming`||t===`error`),Ga=(e,t,n)=>{let r=t.mode===`transient`,i=e.hasAttribute(`data-persona-composer-reason`)||e.hasAttribute(`data-persona-composer-notice`);e.style.display=Wa(t,n)||r&&i&&t.visible!==!1?``:`none`,e.classList.toggle(`persona-mt-2`,!r),e.classList.toggle(`persona-mb-2`,r)},Ka=(e,t,n)=>{t.parentElement&&e.parentElement===t.parentElement&&(n.mode===`transient`?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))}}));function Ja(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=Ya(t)&&Ya(r)?Ja(t,r):r}return n}var Ya,Xa=W((()=>{Ya=e=>typeof e==`object`&&!!e&&!Array.isArray(e)}));function Za(e,t=``){return Object.entries(e).flatMap(([e,n])=>{let r=t?`${t}.${e}`:e;return ao(n)?Za(n,r):[r]})}function Qa(e,t){for(let n of t.split(`.`)){if(!ao(e)||!Object.prototype.hasOwnProperty.call(e,n))return`absent`;if(e=e[n],e===void 0)return`clear`}return`explicit`}function $a(e,t){return e?.[io]??t.filter(t=>Qa(e,t)===`explicit`)}function eo(e,t){return Object.defineProperty(e,io,{value:t,enumerable:!0,configurable:!0}),e}function to(e,t,n){return eo(e,$a(t,Za(n)))}function no(e,t,n){let r=t[io];if(r)return r;let i=new Set($a(e,n));for(let e of n){let n=Qa(t,e);n===`clear`&&i.delete(e),n===`explicit`&&i.add(e)}return[...i]}function ro(e,t,n){let r={...e};for(let e of t){if(n.includes(e))continue;let t=e.split(`.`),i=r;for(let e of t.slice(0,-1)){let t=i[e];if(!ao(t)){i=void 0;break}i[e]={...t},i=i[e]}i&&delete i[t[t.length-1]]}return r}var io,ao,oo=W((()=>{io=Symbol(`persona.defaultsProvenance`),ao=e=>typeof e==`object`&&!!e&&!Array.isArray(e)})),so,co,lo,uo,fo,po,mo,ho,go=W((()=>{so=Symbol(`persona.panelAliasProvenance`),co=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),lo=(e,t)=>co(e,t)&&e[t]!==void 0,uo=e=>({launcherWidth:lo(e?.launcher,`width`),legacyLauncherWidth:lo(e,`launcherWidth`),sidebarWidth:lo(e?.launcher,`sidebarWidth`),dockWidth:lo(e?.launcher?.dock,`width`)}),fo=e=>{let t=e?.[so];return t?{...t}:uo(e)},po=(e,t)=>(Object.defineProperty(e,so,{value:t,enumerable:!0,configurable:!0}),e),mo=(e,t)=>po(e,fo(t)),ho=(e,t)=>{let n=t[so];if(n)return{...n};let r=fo(e);return co(t,`launcherWidth`)&&(r.legacyLauncherWidth=t.launcherWidth!==void 0),co(t,`launcher`)&&t.launcher===void 0?(r.launcherWidth=!1,r.sidebarWidth=!1,r.dockWidth=!1,r):(co(t.launcher,`width`)&&(r.launcherWidth=t.launcher?.width!==void 0),co(t.launcher,`sidebarWidth`)&&(r.sidebarWidth=t.launcher?.sidebarWidth!==void 0),co(t.launcher,`dock`)&&t.launcher?.dock===void 0?r.dockWidth=!1:co(t.launcher?.dock,`width`)&&(r.dockWidth=t.launcher?.dock?.width!==void 0),r)}}));function _o(e){return e?.future?.v5Defaults===!0?`v5`:`v4`}function vo(e){let t=_o(e)===`v5`?jo:ko;return Ja(Oo,t)}function yo(e,t){if(e||t)return e?t?Ja(e,t):e:t}function bo(e){let t=vo(e);return e?to(mo({...t,...e,theme:yo(t.theme,e.theme),darkTheme:yo(t.darkTheme,e.darkTheme),launcher:{...t.launcher,...e.launcher,dock:{...t.launcher?.dock,...e.launcher?.dock},clearChat:{...t.launcher?.clearChat,...e.launcher?.clearChat}},...t.composer||e.composer?{composer:{...t.composer,...e.composer}}:{},tooltip:{...t.tooltip,...e.tooltip},copy:{...t.copy,...e.copy},sendButton:{...t.sendButton,...e.sendButton},statusIndicator:{...t.statusIndicator,...e.statusIndicator},voiceRecognition:{...t.voiceRecognition,...e.voiceRecognition},features:(()=>{let n=t.features?.artifacts,r=e.features?.artifacts,i=t.features?.scrollToBottom,a=e.features?.scrollToBottom,o=t.features?.scrollBehavior,s=e.features?.scrollBehavior,c=t.features?.streamAnimation,l=e.features?.streamAnimation,u=t.features?.askUserQuestion,d=e.features?.askUserQuestion,f=t.features?.history,p=e.features?.history,m=n===void 0&&r===void 0?void 0:{...n,...r,layout:{...n?.layout,...r?.layout}},h=i===void 0&&a===void 0?void 0:{...i,...a},g=o===void 0&&s===void 0?void 0:{...o,...s},_=c===void 0&&l===void 0?void 0:{...c,...l},v=u===void 0&&d===void 0?void 0:{...u,...d,styles:{...u?.styles,...d?.styles}},y=f===void 0&&p===void 0?void 0:{...f,...p,copy:{...f?.copy,...p?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...h===void 0?{}:{scrollToBottom:h},...g===void 0?{}:{scrollBehavior:g},...m===void 0?{}:{artifacts:m},..._===void 0?{}:{streamAnimation:_},...v===void 0?{}:{askUserQuestion:v},...y===void 0?{}:{history:y}}})(),suggestionChips:e.suggestionChips??t.suggestionChips,suggestionChipsConfig:{...t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...t.layout,...e.layout,header:{...t.layout?.header,...e.layout?.header},messages:{...t.layout?.messages,...e.layout?.messages,...t.layout?.messages?.user||e.layout?.messages?.user?{user:{...t.layout?.messages?.user,...e.layout?.messages?.user}}:{},...t.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...t.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...t.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...t.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...t.layout?.slots,...e.layout?.slots}},markdown:{...t.markdown,...e.markdown,options:{...t.markdown?.options,...e.markdown?.options}},messageActions:{...t.messageActions,...e.messageActions}},e),e,jo):to(mo(t),void 0,jo)}var xo,So,Co,wo,To,Eo,Do,Oo,ko,Ao,jo,Mo,No=W((()=>{Xa(),oo(),go(),wa(),xo=`min(440px, calc(100vw - 24px))`,So=`440px`,Co=`40px`,wo=`How can I help...`,To={collapsedMode:`tool-call`,activePreview:!1,grouped:!1,groupedMode:`stack`,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},Eo={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},Do={enabled:!0,mountMode:`floating`,dock:{side:`right`,width:`420px`},title:`Chat Assistant`,subtitle:`Here to help you get answers fast`,agentIconText:`💬`,agentIconName:`bot`,headerIconName:`bot`,position:`bottom-right`,width:xo,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:`40px`,headerIconSize:Co,closeButtonPaddingX:`0px`,closeButtonPaddingY:`0px`,callToActionIconName:`arrow-up-right`,callToActionIconText:``,callToActionIconSize:`32px`,callToActionIconPadding:`5px`,callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:`transparent`,clearChat:{backgroundColor:`transparent`,borderColor:`transparent`,enabled:!0,placement:`inline`,iconName:`refresh-cw`,showTooltip:!0,tooltipText:`Clear chat`,paddingX:`0px`,paddingY:`0px`},headerIconHidden:!1,border:void 0,shadow:`0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)`},Oo={apiUrl:`https://api.runtype.com/api/chat/dispatch`,clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:`light`,tooltip:{delayMs:200,skipDelayMs:300},launcher:Do,copy:{inputPlaceholder:wo,sendButtonLabel:`Send`},sendButton:{borderWidth:`0px`,paddingX:`12px`,paddingY:`10px`,borderColor:void 0,useIcon:!0,iconText:`↑`,showTooltip:!0,tooltipText:`Send message`,iconName:`send`},statusIndicator:{visible:!0,idleText:`Online`,connectingText:`Connecting…`,connectedText:`Streaming…`,errorText:`Offline`},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:`mic`,borderWidth:`0px`,iconColor:void 0,backgroundColor:`transparent`,borderColor:`transparent`,recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:`transparent`,showTooltip:!0,tooltipText:`Start voice recognition`},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:`arrow-down`,label:``},scrollBehavior:{mode:`anchor-top`,anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:To,reasoningDisplay:Eo,streamAnimation:{type:`none`,placeholder:`none`,speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:`Other…`,freeTextPlaceholder:`Type your answer…`,submitLabel:`Send`},history:{enabled:!1,presentation:`panel`,showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:[`Show me what you can help with`,`Walk me through getting started`,`Answer a question about this page`],suggestionChipsConfig:{fontFamily:`sans-serif`,fontWeight:`500`,paddingX:`12px`,paddingY:`6px`},layout:{header:{layout:`default`,showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:`bubble`,avatar:{show:!1,position:`left`},timestamp:{show:!1,position:`below`},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:`hover`,align:`right`,layout:`pill-inside`},debug:!1},ko={},Ao={variant:`circle`,width:`min(400px, calc(100vw - 24px))`,headerIconSize:`20px`},jo={launcher:Ao,features:{toolCallDisplay:{variant:`row`,iconVisibility:`active`,autoExpand:!1,grouped:!0,groupedMode:`collapsible`,loadingAnimation:`shimmer`},reasoningDisplay:{variant:`row`,iconVisibility:`active`,autoExpand:!1,loadingAnimation:`shimmer`}},composer:{layout:`single-row`,placement:`overlay`},sendButton:{iconName:`arrow-up`},statusIndicator:{mode:`transient`},layout:{contentMaxWidth:`768px`,topFade:!0,header:{showSubtitle:!1},messages:{assistant:{width:`full`}}}},Mo=vo()}));function Po(e){return typeof e==`string`?[{type:`text`,text:e}]:e}function Fo(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Io(e){return typeof e!=`string`&&e.some(e=>e.type===`image`)}function Lo(e){return typeof e==`string`?[]:e.filter(e=>e.type===`image`)}function Ro(e){return{type:`text`,text:e}}function zo(e,t){return{type:`image`,image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Bo(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result;t({type:`image`,image:n,mimeType:e.type,alt:e.name})},r.onerror=()=>n(/* @__PURE__ */ Error(`Failed to read file`)),r.readAsDataURL(e)})}function Vo(e,t=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`],n=10485760){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(`, `)}`}}function Ho(e){return Xo.includes(e)||e.startsWith(`image/`)}function Uo(e){return Ho(e.type)}function Wo(e,t,n){return{type:`file`,data:e,mimeType:t,filename:n}}async function Go(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result;Uo(e)?t({type:`image`,image:n,mimeType:e.type,alt:e.name}):t({type:`file`,data:n,mimeType:e.type,filename:e.name})},r.onerror=()=>n(/* @__PURE__ */ Error(`Failed to read file`)),r.readAsDataURL(e)})}function Ko(e,t=Qo,n=10485760){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(`, `)}`}}function qo(e){let t=e.split(`.`);return t.length>1?t.pop().toLowerCase():``}function Jo(e,t){let n=qo(t).toUpperCase();return{"application/pdf":`PDF`,"text/plain":`TXT`,"text/markdown":`MD`,"text/csv":`CSV`,"application/msword":`DOC`,"application/vnd.openxmlformats-officedocument.wordprocessingml.document":`DOCX`,"application/vnd.ms-excel":`XLS`,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":`XLSX`,"application/json":`JSON`}[e]||n||`FILE`}var Yo,Xo,Zo,Qo,$o=W((()=>{Yo=`[Image]`,Xo=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/svg+xml`,`image/bmp`],Zo=[`application/pdf`,`text/plain`,`text/markdown`,`text/csv`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/json`],Qo=[...Xo,...Zo]}));function es(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let n=t.getComputedStyle(e).lineHeight;if(!n||!n.trim().endsWith(`px`))return 20;let r=parseFloat(n);return Number.isFinite(r)&&r>0?r:20}function ts(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:e>0?e:t}function ns(e,t){e.style.maxHeight=`${t*es(e)}px`,e.style.overflowY=`auto`}function rs(e){let t=e?.ownerDocument?.defaultView??(typeof window<`u`?window:null);if(!t||typeof t.matchMedia!=`function`)return!1;try{return t.matchMedia(`(pointer: coarse)`).matches===!0}catch{return!1}}function is(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function as(e,t){if(e.key!==`Enter`||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,r=t.submitKey??`enter`;return r===`none`?!1:r===`mod-enter`?n:n||!is(t)}function os(e){return(e.submitKey??`enter`)===`enter`?is(e)?`enter`:`send`:`enter`}function ss(e,t){e.setAttribute(`enterkeyhint`,os(t))}function cs(e,t){let n=t?.autocomplete;e.setAttribute(`autocomplete`,typeof n==`string`&&n?n:`off`);let r=(t,n)=>{n===void 0?e.removeAttribute(t):e.setAttribute(t,n)};r(`autocapitalize`,typeof t?.autocapitalize==`string`?t.autocapitalize:void 0),r(`spellcheck`,typeof t?.spellcheck==`boolean`?String(t.spellcheck):void 0),r(`inputmode`,typeof t?.inputmode==`string`&&t.inputmode?t.inputmode:void 0),r(`aria-label`,typeof t?.ariaLabel==`string`&&t.ariaLabel?t.ariaLabel:void 0)}function ls(e){return e===!0?{disabled:!0}:!e||typeof e!=`object`?{disabled:!1}:{disabled:!0,reason:typeof e.reason==`string`&&e.reason?e.reason:void 0}}var us=W((()=>{})),ds,fs,ps,ms,hs,gs,_s,vs,ys,bs,xs=W((()=>{qa(),Y(),mn(),No(),$o(),Ua(),us(),ds=`persona-composer-control`,fs=`persona-composer-control--glyph`,ps=(e,t,n)=>{let r=e.ownerDocument?.defaultView;if(!r)return;let i=r.getComputedStyle(e);for(let e of n){let n=i.getPropertyValue(e).trim();n?t.style.setProperty(e,n):t.style.removeProperty(e)}},ms=(e,t)=>{let n=q(`textarea`);n.setAttribute(`data-persona-composer-input`,``),n.placeholder=e?.copy?.inputPlaceholder??`How can I help...`,n.dir=`auto`,ss(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:rs(n)}),cs(n,e?.composer?.inputAttributes),n.className=`persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea`,n.rows=1,n.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,n.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`;let r=ts(e?.composer?.maxLines,t?.defaultMaxLines??3),i=`${r*20}px`;n.style.maxHeight=i,n.style.overflowY=`auto`;let a=()=>{let e=n.style.maxHeight;if(e!==i){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=r*es(n);return i=`${t}px`,n.style.maxHeight=i,t},o=()=>{n.addEventListener(`input`,()=>{n.style.height=`auto`;let e=Math.min(n.scrollHeight,a());n.style.height=`${e}px`})};return n.style.border=`none`,n.style.outline=`none`,n.style.borderWidth=`0`,n.style.borderStyle=`none`,n.style.borderColor=`transparent`,n.addEventListener(`focus`,()=>{n.style.border=`none`,n.style.outline=`none`,n.style.borderWidth=`0`,n.style.borderStyle=`none`,n.style.borderColor=`transparent`,n.style.boxShadow=`none`}),n.addEventListener(`blur`,()=>{n.style.border=`none`,n.style.outline=`none`}),{textarea:n,attachAutoResize:o}},hs=(e,t,n=`send`)=>{let r=J(`span`,{className:`persona-composer-glyph-stack`,attrs:{"data-mode":n,"data-persona-glyph-stack":``}});return e.setAttribute(`data-glyph`,`send`),t.setAttribute(`data-glyph`,`stop`),r.append(e,t),r},gs=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,r=t.iconText??`↑`,i=t.iconName,a=t.stopIconName??`square`,o=t.tooltipText??`Send message`,s=t.stopTooltipText??`Stop generating`,c=e?.copy?.sendButtonLabel??`Send`,l=e?.copy?.stopButtonLabel??`Stop`,u=t.showTooltip??!1,d=t.size,f=parseFloat(d??``)||40,p=t.backgroundColor,m=t.textColor,h=q(`div`,`persona-send-button-wrapper`),g=J(`button`,{className:tr(`persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer`,n?`persona-flex persona-items-center persona-justify-center ${ds}`:`persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold`,n&&!p&&`persona-bg-persona-primary`,!n&&!m&&`persona-text-white`),attrs:{type:`submit`,"data-persona-composer-submit":``,"data-persona-send-mode":`send`},style:{width:n?d:void 0,height:n?d:void 0,minWidth:n?d:void 0,minHeight:n?d:void 0,fontSize:n?`18px`:void 0,lineHeight:n?`1`:void 0,color:n?m||`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`:m||void 0,backgroundColor:n&&p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?`solid`:void 0,borderColor:t.borderColor||void 0,paddingLeft:n?`0`:t.paddingX||void 0,paddingRight:n?`0`:t.paddingX||void 0,paddingTop:n?`0`:t.paddingY||void 0,paddingBottom:n?`0`:t.paddingY||void 0}}),_=null,v=null,y=null;if(n){let e=parseFloat(t.iconSize??``)||Math.round(f*.5),n=t.iconStrokeWidth??2,o=m?.trim()||`currentColor`;if(i&&(_=K(i,e,o,n)),v=K(a,e,o,n),!t.iconSize)for(let t of[_,v])t&&(t.style.width=`var(--persona-components-composer-sendIconSize, ${e}px)`,t.style.height=`var(--persona-components-composer-sendIconSize, ${e}px)`);_&&v?(y=hs(_,v),g.appendChild(y)):_?g.appendChild(_):(g.textContent=r,v=null)}else g.textContent=c;g.setAttribute(`aria-label`,o),h.appendChild(g),Ea({anchor:g,trigger:h,text:()=>g.getAttribute(`aria-label`)??``,enabled:u});let b=`send`;return{button:g,wrapper:h,setMode:e=>{if(e===b)return;b=e;let t=e===`stop`?s:o;g.setAttribute(`aria-label`,t),g.setAttribute(`data-persona-send-mode`,e),n?(g.querySelector(`[data-persona-glyph-stack]`)??y)?.setAttribute(`data-mode`,e):g.textContent=e===`stop`?l:c},glyphStack:y}},_s=e=>{let t=e?.voiceRecognition??{};if(t.enabled!==!0)return null;let n=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),r=t.provider?.type===`runtype`,i=t.provider?.type===`custom`;if(!(n||r||i))return null;let a=t.iconName??`mic`,o=t.iconSize,s=parseFloat(o??``)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,l=t.iconColor??e?.sendButton?.textColor,u=q(`div`,`persona-send-button-wrapper`),d=J(`button`,{className:tr(`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer`,ds,!o&&`persona-composer-control--glyph`),attrs:{type:`button`,"data-persona-composer-mic":``,"data-state":`idle`,"aria-label":t.tooltipText??`Start voice recognition`},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:`18px`,lineHeight:`1`,color:l||`var(--persona-text, #111827)`,backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?`solid`:void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),f=K(a,s,l||`currentColor`,1.5);f?d.appendChild(f):d.textContent=`🎤`,u.appendChild(d);let p=t.tooltipText??`Start voice recognition`;return Ea({anchor:d,trigger:u,text:()=>d.getAttribute(`aria-label`)??p,enabled:t.showTooltip??!1}),{button:d,wrapper:u}},vs=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=q(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`);n.setAttribute(`data-persona-composer-attachment-previews`,``),n.style.display=`none`;let r=q(`input`);r.type=`file`,r.setAttribute(`data-persona-composer-attachment-input`,``),r.accept=(t.allowedTypes??Qo).join(`,`),r.multiple=(t.maxFiles??4)>1,r.style.display=`none`,r.setAttribute(`aria-label`,`Attach files`);let i=t.buttonIconName??`paperclip`,a=q(`div`,`persona-send-button-wrapper`),o=J(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${ds} ${fs}`,attrs:{type:`button`,"data-persona-composer-attachment-button":``,"aria-label":t.buttonTooltipText??`Attach file`},style:{fontSize:`18px`,lineHeight:`1`}}),s=K(i,24,`currentColor`,1.5);s?o.appendChild(s):o.textContent=`📎`,o.addEventListener(`click`,e=>{e.preventDefault(),r.click()}),a.appendChild(o);let c=t.buttonTooltipText??`Attach file`;return Ea({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??c}),{button:o,wrapper:a,input:r,previewsContainer:n}},ys=e=>{let t=e?.statusIndicator??{},n=t.align===`left`?`persona-text-left`:t.align===`center`?`persona-text-center`:`persona-text-right`,r=q(`div`,`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute(`data-persona-composer-status`,``),Ga(r,t,`idle`);let i=t.idleText??`Online`;if(t.idleLink){let e=q(`a`);e.href=t.idleLink,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=i,e.style.color=`inherit`,e.style.textDecoration=`none`,r.appendChild(e)}else r.textContent=i;return r},bs=()=>J(`div`,{className:`persona-mb-3 persona-flex persona-flex-wrap persona-gap-2`,attrs:{"data-persona-composer-suggestions":``}})}));function Ss(e){let{config:t,onOpen:n}=e,r=t.buttonIconName??`plus`,i=t.buttonTooltipText??`Add context`,a=q(`div`,`persona-send-button-wrapper`),o=J(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${ds} ${fs}`,attrs:{type:`button`,"data-persona-composer-mention-button":``,"aria-label":i,"aria-haspopup":`listbox`,"aria-expanded":`false`},style:{fontSize:`18px`,lineHeight:`1`}}),s=K(r,24,`currentColor`,1.5);return s?o.appendChild(s):o.textContent=`+`,o.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n()}),a.appendChild(o),Ea({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??i}),{button:o,wrapper:a}}var Cs=W((()=>{Y(),mn(),Ua(),xs()})),ws,Ts,Es,Ds=W((()=>{Pt(),{setLoader:ws,load:Ts}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/context-mentions`)}),Es=Ts})),Os,ks,As,js=W((()=>{Pt(),{setLoader:Os,load:ks}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/context-mentions-inline`),resetOnSetLoader:!0}),As=ks}));function Ms(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=J(`span`,{className:tr(`persona-mention-token`,t.readonly&&`persona-mention-token-readonly`),attrs:{"data-mention-source":e.sourceId,title:e.label,role:`img`,"aria-label":`${e.label} mention`}});e.color&&n.style.setProperty(`--persona-mention-token-accent`,e.color);let r=K(e.iconName??`at-sign`,13,`currentColor`,2);if(r){let e=q(`span`,`persona-mention-token-icon`);e.appendChild(r),n.appendChild(e)}return n.appendChild(J(`span`,{className:`persona-mention-token-label`,text:`@${e.label}`})),n}var Ns=W((()=>{Y(),mn()}));function Ps(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:r,createMentionButton:i}=e.deps??Fs,a=e.config.contextMentions;if(!a?.enabled)return null;let o=Sa(a).filter(e=>e.sources.length>0);if(o.length===0)return typeof console<`u`&&console.warn(`[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled.`),null;let s=o.filter(e=>e.sources.some(e=>typeof e.matchCommand==`function`)),c=e=>s.some(t=>t.trigger?t.position===`line-start`?e.split(`
|
|
10
10
|
`).some(e=>e.startsWith(t.trigger)):(t.position===`anywhere`?e:e.split(`
|
|
11
|
-
`)[0]).startsWith(t.trigger):!1),l=(e,t)=>{if(typeof window<`u`)try{window.dispatchEvent(new CustomEvent(`persona:mention:${e}`,{detail:t}))}catch{}},u=!e.chipRow,d=e.chipRow??J(`div`,{className:`persona-mention-context-row`,attrs:{"data-persona-mention-context-row":``}}),f=null,p=null,m=e.textarea,h=null,g=null,_=null,v=null,y=()=>{if(f)return Promise.resolve(f);if(p)return p;let n=t().then(t=>(t.setMentionIconRenderer(r),f=t.mountContextMentions({mentionConfig:a,textarea:e.textarea,composerInput:h??void 0,anchor:e.anchor,contextRow:d,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:S,emit:l}),f)).catch(e=>(typeof console<`u`&&console.warn(`[Persona] Failed to load context mentions runtime`,e),p===n&&(p=null),null));return p=n,n};a.display===`inline`&&n().then(t=>{let n=t.mountInlineComposer({textarea:e.textarea,renderToken:e=>Ms(e,{render:a.renderMentionToken}),onMentionRemoved:e=>f?.untrackMention(e)});h=n.input,g=n.destroy;let r=m;r.replaceWith(n.element),m=n.element,v={next:n.element,prev:r},_?.(n.element,r),f?f.rebindComposer(n.input):p&&p.then(e=>e?.rebindComposer(n.input))}).catch(e=>{typeof console<`u`&&console.warn(`[Persona] Failed to load inline mention composer`,e)});let b=[],x=/* @__PURE__ */ new Map;for(let e of o){if(!e.showButton)continue;let t=i({config:{...a,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},onOpen:()=>{y().then(t=>t?.openMenu(e.trigger))}});b.push(t),x.set(e.trigger,t.button)}let S=(e,t,n)=>{let r=x.get(t);r&&(r.setAttribute(`aria-expanded`,e?`true`:`false`),e?r.setAttribute(`aria-controls`,n):r.removeAttribute(`aria-controls`))};return{affordanceButtons:b.map(e=>e.wrapper),contextRow:d,handleInput:e=>{if(f){f.handleInput();return}if(!ya(e))return;let t=m,n=t.selectionStart??0;va(t.value,n,o)&&y().then(e=>e?.handleInput())},handleKeydown:e=>{if(f?.isMenuOpen())return f.handleKeydown(e);if(e.key===`Backspace`&&f?.hasMentions()&&!v){let t=m,n=t.selectionStart===0&&t.selectionEnd===0;if((t.value.length===0||n)&&f.removeLastChip())return e.preventDefault(),!0}return!1},isMenuOpen:()=>f?.isMenuOpen()??!1,hasMentions:()=>f?.hasMentions()??!1,getMentionRefs:()=>f?.getMentionRefs()??[],collectForSubmit:()=>f?.collectForSubmit()??null,takeInlineCommand:async e=>c(e)?(f??await y())?.dispatchInlineCommand(e)??null:null,clear:()=>f?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:e=>{_=e,v&&e(v.next,v.prev)},destroy:()=>{f?.destroy(),g?.();for(let e of b)e.wrapper.remove();u&&d.remove()}}}var Fs,Is=W((()=>{Y(),xa(),$(),Cs(),Ds(),mn(),js(),Ns(),Fs={loadContextMentions:()=>Es(),loadContextMentionsInline:()=>As(),renderLucideIcon:(...e)=>K(...e),createMentionButton:(...e)=>Ss(...e)}})),Ls=/* @__PURE__ */ Mt({createAskUserSheetHandlers:()=>ma,createContextMentionOrchestrator:()=>Ps}),Rs=W((()=>{ha(),Is()}));Rs(),Pt();const{setLoader:zs,load:Bs,provide:Vs,getSync:Hs}=Nt({fallbackImport:()=>Promise.resolve().then(()=>(Rs(),Ls))}),Us=Bs,Ws=Vs,Gs=Hs;Ws(Ls);var Ks=/* @__PURE__ */ Mt({resolveApproval:()=>qs,resolveAskUserQuestion:()=>Js,resolveWebMcpToolCall:()=>ec,resolveWebMcpToolCallBatch:()=>$s});async function qs(e,t,n,r){let i=`approval-${t.id}`,a=`approval-error-${t.id}`,o={};e.s.approvalTokens.set(i,o);let s={...t,status:n,resolvedAt:Date.now()},c=e.s.messages.find(e=>e.id===i),l={id:i,role:`assistant`,content:``,createdAt:c?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),...c?.sequence===void 0?{}:{sequence:c.sequence},streaming:!1,variant:`approval`,approval:s};e.s.upsertMessage(l),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let u=e.s.config.approval,d=u&&typeof u==`object`?u.onDecision:void 0;try{let c;if(c=d?await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):await e.s.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let r=null;if(c instanceof Response){if(!c.ok){let n=await c.json().catch(()=>null),r=n?.message??n?.error??`Approval request failed: ${c.status}`,u=n?.code===`APPROVAL_ALREADY_RESOLVED`||c.status===404&&/no paused execution/i.test(String(n?.error)),d=e.s.messages.find(e=>e.id===i);throw e.s.approvalTokens.get(i)===o&&d?.approval?.resolvedAt===s.resolvedAt&&(e.s.upsertMessage({...l,approval:u?{...s,status:`timeout`}:t}),u&&e.settleApprovalPausedToolCall(i),e.s.upsertMessage({id:a,role:`assistant`,content:r,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})),Error(r)}r=c.body}else c instanceof ReadableStream&&(r=c);e.s.approvalTokens.get(i)===o&&e.s.messages.some(e=>e.id===a)&&(e.s.messages=e.s.messages.filter(e=>e.id!==a),e.s.callbacks.onMessagesChanged([...e.s.messages])),r?await e.s.connectStream(r,{allowReentry:!0}):(n===`denied`&&(e.settleApprovalPausedToolCall(i),e.appendMessage({id:`denial-${t.id}`,role:`assistant`,content:`Tool execution was denied by user.`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})),e.setStreaming(!1),e.s.abortController=null)}else e.setStreaming(!1),e.s.abortController=null}catch(t){let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));e.setStreaming(!1),e.s.abortController=null,n||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}finally{e.s.approvalTokens.get(i)===o&&e.s.approvalTokens.delete(i)}}async function Js(e,t,n){if(e.s.messages.find(e=>e.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,i=t.toolCall?.name;if(!r||!i){e.s.callbacks.onError?.(/* @__PURE__ */ Error(`resolveAskUserQuestion: message is missing executionId or toolCall.name`));return}let a=typeof n==`string`?void 0:n;if(a===void 0&&typeof n==`string`){let e=t.toolCall?.args,r=Array.isArray(e?.questions)?e.questions:[];if(r.length===1){let e=typeof r[0]?.question==`string`?r[0].question:``;e&&(a={[e]:n})}}e.s.markAskUserQuestionResolved(t,a),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let o=t.toolCall.id,s=t.toolCall?.args,c=Array.isArray(s?.questions)?s.questions:[];if(c.length===0){let t=typeof n==`string`?n:Object.entries(n).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `);e.appendMessage({id:`ask-user-answer-${o}`,role:`user`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})}else{let t=a??{};c.forEach((n,r)=>{let i=typeof n?.question==`string`?n.question:``;if(!i)return;let a=t[i],s=Array.isArray(a)?a.join(`, `):typeof a==`string`?a:``;e.appendMessage({id:`ask-user-q-${o}-${r}`,role:`assistant`,content:i,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()}),e.appendMessage({id:`ask-user-a-${o}-${r}`,role:`user`,content:s||`*Skipped*`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})})}try{let t=await e.s.client.resumeFlow(r,{[i]:n},{after:e.resumeAfter(r)});if(!t.ok){let e=await t.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${t.status}`)}t.body?await e.s.connectStream(t.body,{allowReentry:!0}):(e.setStreaming(!1),e.s.abortController=null)}catch(t){let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));e.setStreaming(!1),e.s.abortController=null,n||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}}function Ys(e,t){let n=[e.s.messages.find(e=>e.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let e of n)if(typeof e==`number`&&Number.isFinite(e))return e;return Date.now()}function Xs(e,t){return t.toolCall?.name===`suggest_replies`&&(e.s.messages.find(e=>e.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function Zs(e,t){let n=Ys(e,t);return e.s.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:`running`,startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}function Qs(e,t,n,r,i=Date.now(),a){e.s.messages.some(e=>e.id===t.id)&&e.s.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:`complete`,result:n,startedAt:r,completedAt:i,duration:void 0,durationMs:Math.max(0,i-r)}:t.toolCall})}async function $s(e,t,n){let r=[],i=new AbortController;e.s.webMcpResolveControllers.add(i),e.setStreaming(!0);let a=async n=>{let a=n.toolCall?.name,o=n.toolCall?.id;if(!a||!o)return null;let s=`${t}:${o}`;if(e.s.webMcpInflightKeys.has(s)||e.s.webMcpResolvedKeys.has(s)||Xs(e,n))return null;e.s.webMcpInflightKeys.add(s),r.push(s);let c=Zs(e,n),l=n.agentMetadata?.webMcpToolCallId??a;if(a===`suggest_replies`)return{dedupeKey:s,resumeKey:l,output:ai(),toolMessage:n,startedAt:c,completedAt:Date.now()};let u=e.s.client.executeWebMcpToolCall(a,n.toolCall?.args,i.signal),d;if(!u)d={isError:!0,content:[{type:`text`,text:`WebMCP not enabled on this widget.`}]};else try{d=await u}catch(t){let r=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));return r||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t))),Qs(e,n,nc(r?`Aborted by cancel()`:rc(t)),c),e.s.webMcpInflightKeys.delete(s),null}return i.signal.aborted?(Qs(e,n,nc(`Aborted by cancel()`),c),e.s.webMcpInflightKeys.delete(s),null):{dedupeKey:s,resumeKey:l,output:d,toolMessage:n,startedAt:c,completedAt:Date.now()}},o;if(e.s.config.webmcp?.execution===`sequential`){o=[];for(let e of n)o.push(await a(e))}else o=await Promise.all(n.map(a));let s=[];try{if(s=o.filter(e=>e!==null),s.length===0)return;let n={};for(let e of s)n[e.resumeKey]=e.output;let r=await e.s.client.resumeFlow(t,n,{signal:i.signal,after:e.resumeAfter(t)});if(!r.ok){let e=await r.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${r.status}`)}let a=s[0].dedupeKey;for(let t of s){e.s.webMcpResolvedKeys.add(t.dedupeKey);let n=t.toolMessage.toolCall?.name,r=t.toolMessage.agentMetadata?.webMcpToolCallId;Qs(e,t.toolMessage,t.output,t.startedAt,t.completedAt,{...n===`suggest_replies`?{suggestRepliesResolved:!0}:{},...n&&r?{clientToolAnswer:{toolCallId:r,toolName:n,args:t.toolMessage.toolCall?.args,result:t.output,batch:a}}:{}})}r.body&&await e.s.connectStream(r.body,{allowReentry:!0})}catch(t){if(!(t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`))))e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)));else for(let t of s)Qs(e,t.toolMessage,nc(`Aborted by cancel()`),t.startedAt)}finally{for(let t of r)e.s.webMcpInflightKeys.delete(t);e.s.webMcpResolveControllers.delete(i),e.s.webMcpResolveControllers.size===0&&!e.s.abortController&&e.setStreaming(!1)}}async function ec(e,t){let n=t.agentMetadata?.executionId,r=t.toolCall?.name,i=t.toolCall?.id;if(!n){e.s.callbacks.onError?.(/* @__PURE__ */ Error(`WebMCP await missing executionId: dispatch left paused.`));return}if(!r)return;if(!i){let t=`${n}:__no_tool_id__:${r}`;if(e.s.webMcpInflightKeys.has(t)||e.s.webMcpResolvedKeys.has(t))return;e.s.webMcpInflightKeys.add(t);try{await tc(e,n,r,{isError:!0,content:[{type:`text`,text:`WebMCP await missing toolCall.id: cannot execute the page tool.`}]}),e.s.webMcpResolvedKeys.add(t)}catch(t){e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}finally{e.s.webMcpInflightKeys.delete(t)}return}let a=`${n}:${i}`;if(!(e.s.webMcpInflightKeys.has(a)||e.s.webMcpResolvedKeys.has(a)||Xs(e,t)))return $s(e,n,[t])}async function tc(e,t,n,r,i){let a=await e.s.client.resumeFlow(t,{[n]:r},{signal:i?.signal,after:e.resumeAfter(t)});if(!a.ok){let e=await a.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${a.status}`)}i?.onHttpOk?.(),a.body?await e.s.connectStream(a.body,{allowReentry:!0}):e.s.webMcpResolveControllers.size===0&&(e.setStreaming(!1),e.s.abortController=null)}var nc,rc,ic=W((()=>{fi(),nc=e=>({isError:!0,content:[{type:`text`,text:e}]}),rc=(e,t=`WebMCP tool execution failed.`)=>e instanceof Error&&e.message?e.message:typeof e==`string`&&e?e:t}));ic(),Pt();const{setLoader:ac,load:oc,provide:sc,getSync:cc}=Nt({fallbackImport:()=>Promise.resolve().then(()=>(ic(),Ks))}),lc=oc,uc=sc,dc=cc;uc(Ks);function fc(e){if(!e)return mc;let t={...mc};for(let n of pc){let r=e[n];typeof r==`string`&&r.length>0&&(t[n]=r)}return t}var pc,mc,hc=W((()=>{pc=/* @__PURE__ */ `viewTitle.openHistoryLabel.openHistoryBusyLabel.newConversationLabel.expandLabel.collapseLabel.resizeLabel.showEarlierMessagesLabel.openConversationLoadingLabel.openConversationErrorTitle.openConversationRetryLabel.openConversationBackLabel.confirmCancelLabel.deleteConversationConfirmTitle.deleteConversationConfirm.deleteConversationConfirmLabel.clearHistoryConfirmTitle.clearHistoryConfirm.clearHistoryVerifiedConfirm.clearHistoryConfirmLabel.resetIdentityConfirmTitle.resetIdentityConfirm.resetIdentityConfirmLabel.conversationDeletedNotice.identityResetNotice.identityResetUnconfirmedNotice`.split(`.`),mc={viewTitle:`Messages`,openHistoryLabel:`Messages`,openHistoryBusyLabel:`Messages, available once the reply finishes`,newConversationLabel:`New conversation`,expandLabel:`Expand conversation list`,collapseLabel:`Collapse conversation list`,resizeLabel:`Resize conversation list`,showEarlierMessagesLabel:`Show earlier messages`,openConversationLoadingLabel:`Loading conversation`,openConversationErrorTitle:`Could not open the conversation.`,openConversationRetryLabel:`Try again`,openConversationBackLabel:`Back to messages`,confirmCancelLabel:`Cancel`,deleteConversationConfirmTitle:`Delete conversation`,deleteConversationConfirm:`Delete this conversation? This cannot be undone.`,deleteConversationConfirmLabel:`Delete`,clearHistoryConfirmTitle:`Delete all conversations`,clearHistoryConfirm:`Delete all conversations for this assistant on this browser? This cannot be undone.`,clearHistoryVerifiedConfirm:`Delete all conversations for this assistant and signed-in user? This cannot be undone.`,clearHistoryConfirmLabel:`Delete all`,resetIdentityConfirmTitle:`Forget this device`,resetIdentityConfirm:`Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.`,resetIdentityConfirmLabel:`Forget this device`,conversationDeletedNotice:`That conversation was deleted. You are now in a new conversation.`,identityResetNotice:`This device was forgotten.`,identityResetUnconfirmedNotice:`This device was cleared here, but the server could not confirm it.`}}));function gc(e){let{plugins:t,config:n}=e,r=!1,i=!1,a=!1,o=!1,s=null,c=[],l=()=>{for(let e of c.splice(0))try{e()}catch(e){_c(`renderHistoryView cleanup`,e)}},u=(e,n)=>{for(let r of t){let t=r[e];if(t)try{let e=t(n);if(e)return e}catch(t){_c(e,t)}}return null},d=()=>({presentation:e.getPresentation(),config:n}),f={header:t=>o?u(`renderHistoryHeader`,Object.freeze({...d(),returnSurface:e.getReturnSurface(),identityStatus:vc(t.identityStatus),pendingAction:bc(t.pendingAction),copy:vc(t.copy),actions:Object.freeze({close:h.close,startNewConversation:h.startNewConversation}),defaultRenderer:t.defaultRenderer})):null,conversation:e=>o?u(`renderHistoryConversation`,Object.freeze({...d(),conversation:yc(e.conversation),active:e.active,pending:e.pending,open:e.open,requestDelete:e.requestDelete,defaultRenderer:e.defaultRenderer})):null,state:e=>o?u(`renderHistoryState`,Object.freeze({...d(),state:vc(e.state),identityStatus:vc(e.identityStatus),copy:vc(e.copy),...e.retry?{retry:e.retry}:{},...e.startNewConversation?{startNewConversation:e.startNewConversation}:{},defaultRenderer:e.defaultRenderer})):null},p=t.flatMap(t=>(t.railSections??[]).map(t=>({...t,placement:t.placement??`above-conversations`,items:[],render:n=>t.render(Object.freeze({collapsed:n,presentation:e.getPresentation(),actions:h}))}))),m=e.createView({slots:f,renderDom:!1,onModelChange:()=>y(),railSections:p}),h=Object.freeze({...m.operations,close:e.close}),g=()=>(o=!0,m.setDomRenderEnabled(!0),m.element),_=t=>Object.freeze({conversations:Object.freeze(t.conversations.map(yc)),activeConversationId:t.activeConversationId,state:vc(t.state),pendingAction:bc(t.pendingAction),identityStatus:vc(t.identityStatus),nextCursor:t.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:vc(m.copy),actions:h,defaultRenderer:g,requestRender:()=>y(),onCleanup:e=>{c.push(e)}}),v=()=>{o=!1;let e=null;for(let n of t)if(n.renderHistoryView){try{e=n.renderHistoryView(_(m.getModel()))}catch(t){_c(`renderHistoryView`,t),e=null}if(e)break}let n=!e||e.contains(m.element);return o=n,m.setDomRenderEnabled(n),e??m.element};function y(){if(!(!a||r||i)){i=!0;try{l();let t=v();if(t===s)return;let n=s;s=t,e.onElementChanged(t,n)}finally{i=!1}}}return a=!0,y(),{view:m,get element(){return s??m.element},requestRender:y,dispose:()=>{r=!0,l()}}}var _c,vc,yc,bc,xc=W((()=>{_c=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},vc=e=>Object.freeze({...e}),yc=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),bc=e=>e?vc(e):null})),Sc,Cc,wc,Tc,Ec,Dc,Oc,kc,Ac,jc,Mc,Nc,Pc=W((()=>{Sc=null,Cc=()=>{if(Sc!==null)return Sc;if(typeof navigator>`u`)return!1;let e=navigator.userAgentData?.platform??navigator.platform??``;return/mac|iphone|ipad|ipod/i.test(e)},wc=`ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space`,Tc=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Ec=e=>{let t=e.toLowerCase().split(`+`).map(e=>e.trim()),n=t.pop(),r={key:n,mod:!1,shift:!1,alt:!1};for(let n of t)if(n===`mod`||n===`cmd`||n===`ctrl`)r.mod=!0;else if(n===`shift`)r.shift=!0;else if(n===`alt`||n===`option`)r.alt=!0;else return Tc(`unknown modifier in`,e),null;return!r.mod||r.shift&&r.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Tc(`unsupported`,e),null):(n===`space`&&(r.key=` `),r)},Dc=e=>wc.split(` `).find(t=>t.toLowerCase()===e)??(e===` `?`Space`:e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),Oc=(e,t)=>{let n=Ec(e);if(!n)return``;let r=Cc(),i=Dc(n.key);if(!t&&r)return`${n.alt?`⌥`:``}${n.shift?`⇧`:``}⌘${i}`;let a=[t?r?`Meta`:`Control`:`Ctrl`];return n.alt&&a.push(`Alt`),n.shift&&a.push(`Shift`),a.push(i),a.join(`+`)},kc=e=>Oc(e,!1),Ac=e=>Oc(e,!0),jc=(e,t)=>t.key?.toLowerCase()===e.key&&(Cc()?t.metaKey:t.ctrlKey)===e.mod&&!(Cc()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Mc=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`||e.isContentEditable},Nc=e=>{let t=/* @__PURE__ */ new Map,n=e?.ownerDocument??(typeof document<`u`?document:null),r=(t,n)=>{if((t.scope??`widget`)===`page`)return!0;if(!e)return!1;let r=n.composedPath?.();return r?.length?r.includes(e):e.contains(n.target)},i=e=>{if(e.isComposing||!t.size)return;let n=e.composedPath?.()[0]??e.target;for(let i of t.values())if(jc(i.parsed,e)&&i.when?.()!==!1&&r(i,e)&&(i.allowInInput||!Mc(n))){e.preventDefault();try{i.run(e)}catch(e){Tc(`${i.id} threw on`,i.combo),console.warn(e)}return}};return n?.addEventListener(`keydown`,i),{register(e){let n=Ec(e.combo);if(!n)return()=>{};let r=`${n.mod?`m`:``}${n.shift?`s`:``}${n.alt?`a`:``}${n.key}`,i=t.get(r);return i?(Tc(`${i.id} already owns`,e.combo),()=>{}):(t.set(r,{...e,parsed:n}),e.element?.setAttribute(`aria-keyshortcuts`,Ac(e.combo)),()=>{t.get(r)?.id===e.id&&t.delete(r),e.element?.removeAttribute(`aria-keyshortcuts`)})},destroy(){t.clear(),n?.removeEventListener(`keydown`,i)}}}}));function Fc(e){if(typeof e!=`string`||e===``)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Ic(e){return typeof e==`string`?e:void 0}function Lc(e){if(typeof e!=`object`||!e)return null;let t=e;switch(t.type){case`text`:return typeof t.text==`string`?Ro(t.text):null;case`image`:return typeof t.image==`string`?zo(t.image,{mimeType:Ic(t.mimeType),alt:Ic(t.alt)}):null;case`file`:return typeof t.data==`string`&&typeof t.mimeType==`string`&&typeof t.filename==`string`?Wo(t.data,t.mimeType,t.filename):null;case`audio`:return typeof t.audio==`string`?{type:`audio`,audio:t.audio,...Ic(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case`video`:return typeof t.video==`string`?{type:`video`,video:t.video,...Ic(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function Rc(e,t){let n=Fc(t),r=e.map(e=>Fc(e.timestamp)),i=Array(e.length),a=0;for(;a<r.length;){let e=r[a];if(e!==null){i[a]=e,a+=1;continue}let t=a;for(;t+1<r.length&&r[t+1]===null;)t+=1;let o=t-a+1,s=a>0?i[a-1]:null,c=t+1<r.length?r[t+1]:null,l=c!==null&&n!==null?Math.min(c,n):c??n;for(let e=0;e<o;e+=1)i[a+e]=l===null?s===null?Uc+e:s+e+1:l-(o-e);a=t+1}return i.map(e=>new Date(e).toISOString())}function zc(e,t){let n=Rc(e,t?.beforeCreatedAt),r=[];return e.forEach((e,t)=>{if(typeof e?.id!=`string`||e.id===``||!Hc.includes(e.role))return;let i=e.role,a=n[t];if(e.displayAvailable===!1)r.push({id:e.id,role:i,content:``,createdAt:a,agentMetadata:{historyDisplayUnavailable:!0}});else if(typeof e.displayContent==`string`)r.push({id:e.id,role:i,content:e.displayContent,createdAt:a});else if(typeof e.content==`string`)r.push({id:e.id,role:i,content:e.content,createdAt:a});else if(Array.isArray(e.content)){let t=e.content.map(Lc).filter(e=>e!==null),n=Fo(t);r.push({id:e.id,role:i,content:n||(Io(t)?`[Image]`:``),createdAt:a,...t.length>0&&{contentParts:t}})}else r.push({id:e.id,role:i,content:``,createdAt:a})}),r}function Bc(e){let t=e.content;if(typeof t!=`string`||t===``)return;let n=e.contentParts??e.llmContent??e.rawContent??t;if(typeof n!=`string`||n!==t)return t}function Vc(e,t){let n=/* @__PURE__ */ new Map;for(let t of e)n.set(t.id,t);for(let e of t)n.set(e.id,e);return[...n.values()].sort((e,t)=>{let n=new Date(e.createdAt).getTime(),r=new Date(t.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(r)&&n!==r)return n-r;let i=e.sequence??0,a=t.sequence??0;return i===a?e.id.localeCompare(t.id):i-a})}var Hc,Uc,Wc=W((()=>{$o(),Hc=[`user`,`assistant`,`system`],Uc=0}));function Gc(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let t=qc.get(e.code)??`unavailable`;return new n(t,Yc(t),{...e.retryAfterSeconds===void 0?{}:{retryAfterSeconds:e.retryAfterSeconds}})}return new n(`unavailable`,Yc(`unavailable`))}function Kc(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,r=e.getIdentityProofConfigured()?[`browser`,`verified-user`]:[`browser`],i={scopes:r},a=e=>{if(!r.includes(e))throw new t(`unsupported_scope`,Yc(`unsupported_scope`))},o=async(t,n)=>{a(t);try{return await n()}catch(t){throw Gc(t,e.errors)}},s=t=>{let n=!1;return{conversationId:t.session.conversationId??``,conversationRevision:t.session.conversationRevision??``,async commit(){n||(n=!0,t.commit(),await e.onActivationCommitted(t.session))},discard(){n||(n=!0,t.discard())}}};return{capabilities:i,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(e){return n().subscribeHistoryIdentityStatus(e)},subscribeAvailability(e){return n().subscribeHistoryAvailability(e)},async list(e){return o(e.context.scope,async()=>{let t=await n().listConversations({...e.cursor?{cursor:e.cursor}:{},...e.limit===void 0?{}:{limit:e.limit},...e.targetId?{targetId:e.targetId}:{},scope:e.context.scope});return{items:t.data,nextCursor:t.nextCursor}})},async getPage(e,t){return o(t.context.scope,async()=>{let r=await n().getConversation(e,{...t.cursor?{messageCursor:t.cursor}:{},scope:t.context.scope}),i=zc(r.messages,{...t.beforeCreatedAt?{beforeCreatedAt:t.beforeCreatedAt}:{}});return{summary:r.summary,messages:Vc([],i),conversationRevision:r.conversationRevision??``,nextCursor:r.nextMessageCursor}})},async prepareOpen(e,t){return o(t.context.scope,async()=>s(await n().prepareConversationSession(e)))},async prepareStartNew(e){return o(e.context.scope,async()=>s(await n().prepareNewConversationSession()))},async delete(e,t){await o(t.context.scope,()=>n().deleteConversation(e,{scope:t.context.scope}))},async deleteAll(e){return o(e.context.scope,()=>n().deleteAllConversations({...e.targetId===void 0?{}:{targetId:e.targetId},scope:e.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var qc,Jc,Yc,Xc=W((()=>{Wc(),qc=/* @__PURE__ */ new Map([[`not_found`,`not_found`],[`conversation_deleted`,`not_found`],[`rate_limited`,`rate_limited`],[`authentication_required`,`authentication_required`],[`invalid_identity_proof`,`authentication_required`],[`visitor_identity_mismatch`,`authentication_required`],[`visitor_required`,`authentication_required`],[`identity_provider_failed`,`identity_provider_failed`],[`proof_not_admitted`,`proof_not_admitted`],[`identity_contract_violation`,`proof_not_admitted`],[`unauthorized`,`authentication_failed`],[`visitor_token_missing`,`authentication_failed`],[`conversation_credential_missing`,`authentication_failed`]]),Jc=/* @__PURE__ */ new Map([[`not_found`,`That conversation is no longer available.`],[`rate_limited`,`Too many history requests.`],[`authentication_failed`,`History access was not authorized.`],[`authentication_required`,`Sign in again to view account history.`],[`identity_provider_failed`,`The identity provider did not respond.`],[`proof_not_admitted`,`Account history is not available for this configuration.`],[`unsupported_scope`,`This history scope is not supported.`],[`unavailable`,`Conversation history is unavailable right now.`]]),Yc=e=>Jc.get(e)??`Conversation history is unavailable right now.`})),Zc=/* @__PURE__ */ Mt({createHistoryShell:()=>Qc}),Qc,$c=W((()=>{hc(),xc(),Y(),Pc(),yi(),Xc(),Qc=e=>{let t=fc(e.config.features?.history?.copy),n=null,r=!1,i=null,a=null,o=`conversation`,s=null,c=null,l=null,u=null,d=0,f=null,p=null,m=null,h=`persona-history-${Math.random().toString(36).slice(2,8)}`,g=()=>e.historyFeatureEnabled()&&!!n&&!r,_=()=>{let t=e.session.getStatus();return e.isStreaming||t===`paused`||t===`resuming`},v=()=>{let t=e.config.features?.history?.scope;if(t)return t;let r=e.config.getIdentityProof?`verified-user`:`browser`,i=n?.capabilities.scopes;return!i||i.includes(r)?r:i[0]??r},y=()=>a?.scope??v(),b=()=>e.session.getClientSession()?.targetId??null,x=e=>`${e.state}:${`reason`in e?e.reason:``}`,S=t=>{let n=x(t);n!==u&&(u=n,e.eventBus.emit(`history:identityStatusChanged`,{status:t,timestamp:Date.now()}))},C=null,w=null,T=()=>{if(!e.historyFeatureEnabled())return null;let t=e.getHistoryProviderFactory();if(t)return t();let n=e.config.features?.history?.provider;return n?typeof n==`function`?(C!==n&&(C=n,w=n()),w):n:e.session.isClientTokenMode()?Kc({errors:e.historyErrors,client:e.session.getClient(),getIdentityProofConfigured:()=>typeof e.config.getIdentityProof==`function`,onActivationCommitted:t=>e.session.bindActivatedSession(t),getClient:()=>e.session.getClient()}):null},E=()=>{p?.(),p=null,m?.(),m=null,r=!1,n=T();let t={...e.historyInternals};n?t.historyProvider=n:delete t.historyProvider,e.historyInternals=t,e.session.setHistoryInternals(e.historyInternals),n&&(p=n.subscribeAvailability?.(e=>{r=!e,e||H({restoreFocus:!1}),Ut()})??null,m=n.subscribeIdentityStatus(e=>S(e)),u=x(n.getIdentityStatus()))},D=()=>{let t=e.config.features?.history?.presentation??`panel`;if(t===`panel`||t===`auto`&&e.launcherEnabled&&!e.isDockedMountMode(e.config))return`panel`;let n=e.artifactSplitRoot??e.container;return(n.getBoundingClientRect().width||n.clientWidth)>=720?`rail`:`panel`},O=(e,t)=>{t?(e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`inert`,``)):(e.removeAttribute(`aria-hidden`),e.removeAttribute(`inert`))},k=`data-persona-history-suppressed`,ee=null,A=null,te=null,ne=null,re=null,ie=``,ae=()=>e.header===re?ie:e.config.layout?.showHeader===!1?`none`:``,oe=()=>e.historyPresentation===`panel`&&!!te&&ne===te.element&&e.config.layout?.showHeader!==!1&&ae()!==`none`,j=()=>{for(let t of Array.from(e.header.children))t!==ee&&t.setAttribute(k,``)},se=()=>{for(let t of Array.from(e.container.querySelectorAll(`[${k}]`)))t.removeAttribute(k)},ce=()=>{let t=te;if(!t)return;if(Array.from(e.header.children).some(e=>e!==ee&&!e.hasAttribute(k))){A&&A!==e.header&&(A.style.removeProperty(`min-height`),A=null);let t=e.header.offsetHeight;t>0&&(e.header.style.minHeight=`${t}px`,A=e.header)}ee||=q(`div`,`persona-history-header-host`),t.setHeaderPlacement(`external`);let n=t.getHeaderElement();n.parentNode!==ee&&ee.replaceChildren(n),ee.parentNode!==e.header&&e.header.appendChild(ee),j()},le=()=>{A&&=(A.style.removeProperty(`min-height`),null),ee&&(te?.setHeaderPlacement(`inline`),ee.remove(),ee=null,se())},ue=null,de=()=>{ue&&(e.body.style.display=`none`,O(e.body,!0),e.footer.hidden=!0,O(e.footer,!0),oe()?(ce(),e.header.style.display=ae(),O(e.header,!1)):(le(),e.header.style.display=`none`,O(e.header,!0)))};e.reapplyHistoryHostChrome=de;let fe=t=>{let n=e.body.style.display,r=e.footer.hidden,i=e.footer,a=e.header,o=e.header.style.display;re=a,ie=o,ue=()=>{ue=null,le(),re=null,e.body.style.display=n,O(e.body,!1),i.hidden=r,O(i,!1),e.footer!==i&&(e.footer.hidden=!1,O(e.footer,!1)),a.style.display=o,O(a,!1),e.header!==a&&(e.header.style.display=e.config.layout?.showHeader===!1?`none`:``,O(e.header,!1))},e.footer.parentNode?.insertBefore(t,e.footer),de()},pe=null,M=null,me=null,he=null,ge=()=>[e.header,e.panelElements.closeButtonWrapper,e.panelElements.clearChatButtonWrapper,e.body,e.footer],_e=()=>e.config.features?.history?.rail?.collapsible!==!1,ve=()=>e.config.features?.history?.rail?.side===`right`?`right`:`left`,ye=e=>Math.min(400,Math.max(200,Math.round(e))),N=()=>e.config.features?.history?.rail?.resizable===!0,be,P=()=>{if(be===void 0&&(be=null,e.config.persistState!==!1))try{let t=Number(window.localStorage.getItem(`${e.currentKeyPrefix()}rail-width`));t&&(be=t)}catch{}return be},xe=()=>ye(P()??e.config.features?.history?.rail?.width??260),Se=t=>{if(be=t,e.config.persistState!==!1)try{window.localStorage.setItem(`${e.currentKeyPrefix()}rail-width`,String(t))}catch{}},Ce=()=>_e()&&e.config.features?.history?.rail?.collapsedBehavior===`overlay`,we=!1,Te=e=>{let t=q(`img`);return t.src=e,t.alt=``,t.setAttribute(`aria-hidden`,`true`),t},Ee=()=>{let t=e.config.features?.history?.rail?.brand;if(!t)return;let n=!1,r;return i=>{if(t.render)try{return t.render({collapsed:i})??null}catch(e){return n||(n=!0,console.warn(`[persona] history rail brand threw`,e)),null}return r===void 0&&(r=t.iconUrl?Te(t.iconUrl):t.icon?e.renderLucideIcon(t.icon,20):null),r?r.cloneNode(!0):null}},De=()=>e.config.features?.history?.rail?.sections?.map(t=>{let n=!1,r=e=>{n||(n=!0,console.warn(`[persona] history rail section threw`,t.id,e))};return{id:t.id,title:t.title,placement:t.placement??`above-conversations`,items:t.items.map(t=>{let n;return{id:t.id,label:t.label,badge:t.badge,iconNode:()=>{if(n!==void 0)return n;try{n=t.renderIcon?t.renderIcon()??null:t.iconUrl?Te(t.iconUrl):t.icon?e.renderLucideIcon(t.icon,20):null}catch(e){r(e),n=null}return n},onSelect:()=>{try{t.onSelect()}catch(e){r(e)}}}})}})??[],Oe=e=>{let t=De();for(let n of e)t.some(e=>e.id===n.id)?console.warn(`[persona] duplicate history rail section id`,n.id):t.push(n);return t.length?t:void 0},ke=null,Ae=()=>`${e.currentKeyPrefix()}rail-collapsed`,je=()=>{if(ke===null&&(ke=e.config.features?.history?.rail?.defaultCollapsed===!0,e.config.persistState!==!1))try{let e=window.localStorage.getItem(Ae());e&&(ke=e===`1`)}catch{}return ke},Me=t=>{if(ke=t,e.config.persistState!==!1)try{window.localStorage.setItem(Ae(),t?`1`:`0`)}catch{}},Ne=()=>e.historyPresentation===`rail`&&_e()&&!Ce()&&je(),Pe=()=>{},Fe=()=>{Ce()?Pe():(Me(!je()),i?.view.setCollapsed(Ne()),e.applyRailChrome(),e.repinAnchoredMessage())},Ie=()=>{let t=e.config.features?.history?.rail?.collapseShortcut;return!t||!Ec(t)?null:{combo:t,hint:kc(t),aria:Ac(t)}},Le=`var(--persona-history-overlay-margin,8px)`,Re=null,ze=null,Be=0,Ve=null,He=null,Ue=!1,We=0,Ge=()=>window.matchMedia?.(`(pointer: coarse)`).matches===!0,Ke=()=>g()&&Ce()&&(e.historyPresentation??D())===`rail`,qe=()=>e.historyVisible&&!we,Je=()=>{He!==null&&clearTimeout(He),He=null},Ye=()=>{e.loadHistoryView().catch(()=>{})},Xe=()=>{Je(),we&&(He=setTimeout(()=>{He=null,!Ue&&we&&(Ve?.contains(document.activeElement)||H({restoreFocus:!1}))},300))},Ze=(e,t)=>{let n=Ve?.getBoundingClientRect();if(!n)return!1;let r=Re?.getBoundingClientRect(),i=r?Math.min(r.top,n.top):n.top;return e>=n.left&&e<=n.right&&t>=i&&t<=n.bottom||!!r&&e>=r.left&&e<=r.right&&t>=r.top&&t<=r.bottom},Qe=e=>{we&&(Ue=Ze(e.clientX,e.clientY),Ue?Je():He===null&&Xe())},$e=t=>{!e.historyVisible&&Ke()&&(we=!0,mt({invoker:Re,keyboard:t?.keyboard===!0}).then(()=>{e.historyVisible?!Ue&&document.activeElement!==Re&&H():we=!1}))},et=()=>{let e=ne?.querySelector(`[data-persona-history-focus="collapse"]`);e&&(e.setAttribute(`aria-label`,we?t.expandLabel:t.collapseLabel),e.setAttribute(`aria-expanded`,we?`false`:`true`))},tt=()=>{Me(!1);let t=i;if(!we||!t){mt({invoker:Re});return}let n=document.activeElement===Re;we=!1,ct(),t.element.remove(),ut(t.element),et(),n&&pt(),e.repinAnchoredMessage(),Ut()},nt=()=>{Me(!0),H()};Pe=()=>{!e.historyVisible||we?tt():nt()};let F=()=>{let n=Ie(),r=e.createHeaderIconButton({ariaLabel:t.expandLabel,iconName:`panel-left`,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`,extraClassName:`persona-rail-trigger`,tooltip:!1,attrs:{"data-persona-rail-trigger":``,"aria-controls":h,...n?{"aria-keyshortcuts":n.aria}:{}}}),i=r.button;i.addEventListener(`mouseenter`,()=>{Ue=!0,Je(),!(Ge()||Date.now()<We)&&$e()}),i.addEventListener(`mouseleave`,()=>{Ue=!1,We=0,Xe()}),i.addEventListener(`focus`,()=>{e.historyVisible||Ye()}),i.addEventListener(`click`,t=>{g()&&(t.detail!==0&&Ge()&&!e.historyVisible?$e():tt())}),Re=i,ze=r.wrapper},I=()=>{if(ze&&!ze.isConnected&&(ze=null,Re=null),!Ke()){ze?.remove(),ze=null,Re=null;return}Re||F();let n=ze,r=Re;if(!n||!r)return;let i=ve()===`right`?null:e.header.firstChild;(i??e.header.lastChild)!==n&&e.header.insertBefore(n,i),n.style.display=qe()||Be>0?`none`:``,r.setAttribute(`aria-label`,t.expandLabel),r.setAttribute(`aria-expanded`,e.historyVisible?`true`:`false`),Ve&&e.applyRailChrome()},rt=e=>{if(!we)return;let t=e.target;t instanceof Node&&(Ve?.contains(t)||ze?.contains(t)||t instanceof Element&&t.closest(`.persona-dropdown-menu,[role="alertdialog"]`)||H({restoreFocus:!1}))};document.addEventListener(`pointerdown`,rt,!0),e.destroyCallbacks.push(()=>{document.removeEventListener(`pointerdown`,rt,!0),document.removeEventListener(`pointermove`,Qe),L?.(),Je()});let it=null,L=null,R=t=>{Se(ye(t)),e.applyRailChrome(),e.repinAnchoredMessage()},z=()=>{let t=q(`div`,`persona-rail-resizer`);return t.tabIndex=0,t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-valuemin`,`200`),t.setAttribute(`aria-valuemax`,`400`),t.addEventListener(`pointerdown`,n=>{let r=M;if(!r||n.button!==0)return;n.preventDefault(),L?.();let i=n.clientX,a=r.getBoundingClientRect().width||xe(),o=ve()===`right`?-1:1,s=a,c=e.mount.ownerDocument;r.style.transition=`none`;let l=e=>{s=ye(a+o*(e.clientX-i)),r.style.flex=`0 0 ${s}px`,t.setAttribute(`aria-valuenow`,String(s))},u=()=>{L=null,c.removeEventListener(`pointermove`,l),c.removeEventListener(`pointerup`,u),c.removeEventListener(`pointercancel`,u),r.style.removeProperty(`transition`);try{t.releasePointerCapture(n.pointerId)}catch{}R(s)};L=u,c.addEventListener(`pointermove`,l),c.addEventListener(`pointerup`,u),c.addEventListener(`pointercancel`,u);try{t.setPointerCapture(n.pointerId)}catch{}}),t.addEventListener(`keydown`,e=>{let t=ve()===`right`?-16:16,n=xe(),r=e.key===`ArrowRight`?n+t:e.key===`ArrowLeft`?n-t:e.key===`Home`?200:e.key===`End`?400:null;r!==null&&(e.preventDefault(),R(r))}),t},at=(e,n)=>{if(!N()||Ne()){L?.(),it?.remove();return}let r=it??z();it=r,r.setAttribute(`aria-label`,t.resizeLabel),r.setAttribute(`aria-valuenow`,String(xe())),r.nextElementSibling!==n&&e.insertBefore(r,n)};e.applyRailChrome=()=>{i?.view.setRailSide(ve());let t=ve()===`right`,n=Ve;if(n){let r=Re?Re.getBoundingClientRect().bottom-e.container.getBoundingClientRect().top:0;n.style.top=`calc(${Math.max(0,Math.round(r))}px + ${Le})`,n.style.width=`${xe()}px`,n.style.left=t?``:Le,n.style.right=t?Le:``}let r=M,a=pe,o=me;if(!r||!a||!o)return;r.style.flex=`0 0 ${Ne()?52:xe()}px`;let s=`1px solid var(--persona-divider,#e5e7eb)`;r.style.borderRight=t?``:s,r.style.borderLeft=t?s:``;let c=t?o:r;a.firstElementChild!==c&&a.append(c,t?r:o),at(a,t?r:o)};let ot=t=>{if(he&&M){he.replaceWith(t),he=null,e.applyRailChrome();return}let n=q(`div`,`persona-history-rail-shell`);n.style.cssText=`display:flex;flex-direction:row;flex:1 1 auto;min-height:0`;let r=q(`div`,`persona-history-rail-conversation`);r.style.cssText=`display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative`;let i=q(`div`,`persona-history-rail-host`);i.style.cssText=`display:flex;min-height:0;overflow:hidden`,e.container.insertBefore(n,e.header.parentNode===e.container?e.header:e.body);for(let t of ge())t?.parentNode===e.container&&r.appendChild(t);n.append(i,r),i.appendChild(t),pe=n,M=i,me=r,e.applyRailChrome()},st=()=>{if(pe)return;let t=q(`div`,`persona-history-rail-placeholder`);t.style.cssText=`flex:1 1 auto;min-height:0`,he=t,ot(t),e.repinAnchoredMessage()},B=()=>{he&&(ct(),e.repinAnchoredMessage())},V=t=>{let n=q(`div`,`persona-history-rail-overlay`);n.style.cssText=`position:absolute;bottom:${Le};display:flex;overflow:hidden;z-index:${vi-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,e.container.style.position=`relative`,e.container.appendChild(n),n.appendChild(t),document.addEventListener(`pointermove`,Qe),Ve=n,e.applyRailChrome(),et()},ct=()=>{ue?.(),Ve&&=(Ue&&(We=Date.now()+150),document.removeEventListener(`pointermove`,Qe),Ve.remove(),null);let t=pe;if(t){L?.();for(let n of ge())n&&t.contains(n)&&e.container.insertBefore(n,t);t.remove(),pe=null,M=null,me=null,he=null}},lt=e=>{ne=e,e.id=h,e.style.flex=`1 1 auto`,e.style.minHeight=`0`},ut=t=>{lt(t),(e.historyPresentation!==`rail`||we)&&B(),e.historyPresentation===`rail`?we?V(t):ot(t):fe(t)},dt=()=>{if(I(),Bt(),!e.historyVisible||!i)return;let t=D();if(t===e.historyPresentation)return;let n=document.activeElement,r=n instanceof HTMLElement&&(i.element.contains(n)||ee?.contains(n)===!0)?n:null;ct(),i.element.remove(),i.view.setHeaderPlacement(`inline`),e.historyPresentation=t,i.view.setPresentation(t),i.view.setCollapsed(Ne()),i.requestRender(),i.element.isConnected||ut(i.element),r?.isConnected?r.focus():pt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),Ut()},ft=(e,t)=>ee?.querySelector(t)??e.querySelector(t),pt=()=>{let e=i?.element??ne;if(!e)return;let t=ft(e,`[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]`);if(t){t.focus();return}let n=ft(e,`.persona-history-title`)??e;n.tabIndex=-1,n.focus()},mt=async r=>{if(!g()||e.historyVisible)return;let l=n;if(!l)return;if(!we&&Ke()&&je()){I();return}ht();let u=++d;o=r?.returnSurface??`conversation`,s=r?.invoker??c;let f=Ke()&&!we;f&&(Be+=1,I(),st());let p;try{p=await e.loadHistoryView()}catch{e.announceHistory(t.openHistoryLabel),f&&(--Be,u===d&&(B(),I()));return}if(f&&--Be,u!==d||e.historyVisible)return;a={scope:v()},e.historyPresentation=D(),e.historyVisible=!0;let m=e.historyPresentation===`panel`&&e.config.layout?.showHeader!==!1&&e.header.style.display!==`none`?`external`:`inline`,h=e.config.features?.history?.rowAvatar,_=Ie(),y=_?{hint:_.hint,aria:_.aria}:null,x={provider:l,context:a,targetId:b(),presentation:e.historyPresentation,collapsible:_e(),collapsed:Ne(),railSide:ve(),renderRailHeader:e.config.features?.history?.rail?.renderHeader,railBrand:Ee(),onToggleCollapse:Fe,...y?{collapseShortcut:y}:{},headerPlacement:m,showScopeStatus:e.config.features?.history?.showScopeStatus!==!1,showDelete:e.config.features?.history?.showDelete!==!1,showDeleteAll:e.config.features?.history?.showDeleteAll!==!1,...e.config.features?.history?.listActions?.length?{listActions:e.config.features.history.listActions}:{},rowAvatar:h===!1?!1:typeof h==`string`?h:e.config.launcher?.iconUrl,activeConversationId:e.session.getActiveConversationId(),...e.config.features?.history?.grouping?{grouping:e.config.features.history.grouping}:{},...e.config.features?.history?.copy?{copy:e.config.features.history.copy}:{},...e.config.features?.history?.pageSize===void 0?{}:{pageSize:e.config.features.history.pageSize},onSelect:e=>Dt(e,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:t=>e.setActiveConversationSummary(t),attachTooltip:e.attachTooltip,onStartNew:()=>Ot({focusComposer:!0}),onClose:()=>H(),onRequestDeleteConversation:e=>Pt(e),onRequestClearHistory:()=>Ft(),...l.resetDevice?{onRequestResetIdentity:()=>It()}:{}};i=gc({plugins:e.plugins,config:e.config,getPresentation:()=>e.historyPresentation??`panel`,getReturnSurface:()=>o,close:()=>H(),createView:({slots:t,renderDom:n,onModelChange:r,railSections:i})=>(te=p.createHistoryView({...x,railSections:Oe(i),slots:t,renderDom:n,onModelChange:r,onAnnounce:e.announceHistory}),te),onElementChanged:(e,t)=>{if(!t?.isConnected)return ut(e);lt(e),t.replaceWith(e),de()}}),i.view.setNewConversationRequired(e.historySessionState.recovery===`new_conversation_required`),r?.focus!==!1&&(e.historyPresentation!==`rail`||r?.keyboard===!0)&&pt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),Ut(),e.eventBus.emit(`history:opened`,{presentation:e.historyPresentation,returnSurface:o,timestamp:Date.now()})},ht=()=>{},H=t=>{if(!e.historyVisible)return;d+=1;let n=o,r=s,l=i,u=t?.restoreFocus!==!1;e.historyVisible=!1;let f=!1,p=null,m=()=>{if(!f){if(f=!0,ht=()=>{},p!==null&&clearTimeout(p),we=!1,Je(),ct(),l?.dispose(),l?.view.destroy(),l?.element.remove(),i===l&&(i=null,te=null,ne=null,e.historyPresentation=null,a=null,s=null),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),Ut(),u){let t=r??c;t?.isConnected?t.focus():e.maybeFocusInput()}e.eventBus.emit(`history:closed`,{returnSurface:n,timestamp:Date.now()})}},h=l&&l.element===l.view.element?l.view.playExit():null;h?(ht=m,p=setTimeout(m,250),h.then(m)):m()},gt=t=>{if(t.key===`Escape`&&e.historyVisible&&i){if(e.historyPresentation===`rail`){let e=t.target;if(!(e instanceof Node)||!(i.element.contains(e)||we&&ze?.contains(e)===!0))return}t.preventDefault(),t.stopPropagation(),H()}};e.container.addEventListener(`keydown`,gt),e.destroyCallbacks.push(()=>e.container.removeEventListener(`keydown`,gt));let _t=0,vt=null,yt=()=>{vt&&clearTimeout(vt),vt=null};e.destroyCallbacks.push(yt);let bt=()=>{yt();let t=e.conversationOpenPendingEl;t&&(e.conversationOpenTakeover=!0,t.hidden=!1,e.messagesWrapper.style.display=`none`,e.updateWelcome())},xt=()=>{_t+=1,yt(),e.conversationOpenPendingEl&&(e.conversationOpenPendingEl.remove(),e.conversationOpenPendingEl=null,e.conversationOpenTakeover=!1,e.messagesWrapper.style.removeProperty(`display`),O(e.footer,!1),e.updateWelcome())},St=()=>{try{if(window.matchMedia?.(`(prefers-reduced-motion: reduce)`)?.matches)return;e.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:`ease-out`})}catch{}},Ct=(e,t)=>J(`div`,{className:tr(`persona-conversation-loading-bubble`,t&&`persona-conversation-loading-bubble--trailing`),attrs:{"aria-hidden":`true`},style:{width:e}}),wt=()=>J(`div`,{className:`persona-conversation-loading-body`},Ct(`58%`,!1),Ct(`72%`,!0),Ct(`44%`,!1)),Tt=t=>{e.conversationOpenPendingEl?.remove(),e.conversationOpenPendingEl=t,t.hidden=!e.conversationOpenTakeover,e.body.insertBefore(t,e.messagesWrapper),yt(),e.conversationOpenTakeover||(vt=setTimeout(bt,250)),O(e.footer,!0)},U=()=>{let n={config:e.config,streaming:!1,location:`conversation-open`,defaultRenderer:wt},r=null,i=e.plugins.find(e=>e.renderLoadingIndicator);i?.renderLoadingIndicator&&(r=i.renderLoadingIndicator(n)),r===null&&e.config.loadingIndicator?.render&&(r=e.config.loadingIndicator.render(n)),Tt(J(`div`,{className:`persona-conversation-loading`,attrs:{role:`status`,"aria-label":t.openConversationLoadingLabel}},r??wt()))},Et=n=>{let r=()=>{Dt(n,{focusComposer:!0}).catch(()=>{})},i=g()?()=>{xt(),mt()}:void 0,a=(e,t)=>{let n=J(`button`,{className:`persona-conversation-loading-error-action`,attrs:{type:`button`},text:e});return n.addEventListener(`click`,t),n},o=()=>J(`div`,{className:`persona-conversation-loading-error-body`},J(`p`,{className:`persona-conversation-loading-error-title`,text:t.openConversationErrorTitle}),J(`div`,{className:`persona-conversation-loading-error-actions`},a(t.openConversationRetryLabel,r),i?a(t.openConversationBackLabel,i):null)),s=Object.freeze({conversationId:n,config:e.config,copy:Object.freeze({title:t.openConversationErrorTitle,retryLabel:t.openConversationRetryLabel,backLabel:t.openConversationBackLabel}),retry:r,...i?{back:i}:{},defaultRenderer:o}),c=null;for(let t of e.plugins)if(t.renderHistoryOpenError){try{c=t.renderHistoryOpenError(s)}catch(e){console.warn(`[persona] renderHistoryOpenError threw`,e),c=null}if(c)break}Tt(J(`div`,{className:`persona-conversation-loading-error`,attrs:{role:`alert`}},c??o())),bt()};e.eventBus.on(`history:closed`,()=>{e.conversationOpenPendingEl&&O(e.footer,!0)});let Dt=async(t,{focusComposer:n=!1}={})=>{let r=y(),a=!!i;i?.view.setActiveConversationId(t),xt();let o=_t;U(),e.historyVisible&&(e.historyPresentation===`panel`||we)&&H({restoreFocus:!1}),e.suppressScrollSend=!0;try{await e.session.openConversation(t,{scope:r})}catch(e){throw o===_t&&Et(t),e}finally{e.suppressScrollSend=!1}o===_t&&(xt(),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.restoreScrollPosition()||e.jumpToBottomInstant(),St(),Rt(),a||e.setActiveConversationSummary(null),e.eventBus.emit(`history:conversationOpened`,{conversationId:t,title:e.activeConversationTitle,scope:r,timestamp:Date.now()}),n&&e.maybeFocusInput())},Ot=async({focusComposer:t=!1}={})=>{xt(),await e.session.startNewConversation({scope:y()}),e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.jumpToBottomInstant(),Rt();let n=e.session.getActiveConversationId();i?.view.setActiveConversationId(n),e.eventBus.emit(`history:conversationStarted`,{conversationId:n,timestamp:Date.now()}),e.historyVisible&&(e.historyPresentation===`panel`||we)&&H({restoreFocus:!1}),t&&e.maybeFocusInput()},kt=async(t,n)=>{let r=await e.session.updateConversation(t,{...n,...n.title===void 0?{}:{title:n.title.trim()}});return i?.view.applyConversationSummary(r),!i&&t===e.session.getActiveConversationId()&&e.setActiveConversationSummary(r),r},At=async t=>{let n=y(),r=e.session.getActiveConversationId()===t;await e.session.deleteConversation(t,{scope:n}),i?.view.removeConversationSummary(t),r&&(e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Rt()),e.eventBus.emit(`history:conversationDeleted`,{conversationId:t,scope:n,wasActive:r,timestamp:Date.now()})},jt=async t=>{let n=t?.scope??y(),r=t?.allTargets?null:t?.targetId??b(),i=await e.session.clearConversationHistory({...r?{targetId:r}:{},scope:n});return e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Rt(),e.eventBus.emit(`history:cleared`,{deleted:i.deleted,scope:n,targetId:r,timestamp:Date.now()}),i},W=async()=>{if(!n?.resetDevice)throw Error(`[Persona] resetHistoryIdentity() requires a history provider that can reset this device`);let r=!1;try{r=(await e.session.resetHistoryDevice()).remoteRevocationConfirmed}finally{e.setActiveConversationSummary(null),e.session.clearArtifacts(),e.messageCache.clear(),e.lastAppliedMessages=null,e.config.clearStoredSessionId?.(),e.config.clearStoredConversationId?.(),e.persistentMetadata={},e.actionManager.syncFromMetadata();let t=e.storageAdapter;t?.clear&&e.runStorageMutation(()=>t.clear(),`[AgentWidget] Failed to clear storage adapter:`),e.resetAnchorState(),e.resumeAutoScroll(),Rt(),H({restoreFocus:!1}),e.maybeFocusInput(),e.open||e.launcherSurfaceInstance?.launcher.element.focus()}return e.announceHistory(r?t.identityResetNotice:t.identityResetUnconfirmedNotice),e.eventBus.emit(`history:identityReset`,{remoteRevocationConfirmed:r,timestamp:Date.now()}),{remoteRevocationConfirmed:r}},Mt=()=>e.artifactSplitRoot?e.panel:e.container,Nt=async t=>{let n=await e.loadHistoryView().catch(()=>null);return typeof n?.showHistoryConfirm==`function`?n.showHistoryConfirm(t):window.confirm(`${t.title}\n\n${t.description}`)},Pt=async e=>await Nt({host:Mt(),title:t.deleteConversationConfirmTitle,description:t.deleteConversationConfirm,confirmLabel:t.deleteConversationConfirmLabel,cancelLabel:t.confirmCancelLabel})?(await At(e),`deleted`):`cancelled`,Ft=async()=>{let e=y()===`verified-user`;return await Nt({host:Mt(),title:t.clearHistoryConfirmTitle,description:e?t.clearHistoryVerifiedConfirm:t.clearHistoryConfirm,confirmLabel:t.clearHistoryConfirmLabel,cancelLabel:t.confirmCancelLabel})?(await jt(),`cleared`):`cancelled`},It=async()=>{if(!await Nt({host:Mt(),title:t.resetIdentityConfirmTitle,description:t.resetIdentityConfirm,confirmLabel:t.resetIdentityConfirmLabel,cancelLabel:t.confirmCancelLabel}))return{outcome:`cancelled`};let{remoteRevocationConfirmed:e}=await W();return{outcome:`reset`,remoteRevocationConfirmed:e}},Lt=q(`button`,`persona-history-earlier`);Lt.type=`button`,Lt.textContent=t.showEarlierMessagesLabel,Lt.setAttribute(`data-persona-history-earlier`,``),Object.assign(Lt.style,{alignSelf:`center`,minHeight:`44px`,padding:`0 16px`,borderRadius:`999px`,border:`1px solid var(--persona-border, rgba(0,0,0,0.12))`,background:`transparent`,color:`inherit`,font:`inherit`,cursor:`pointer`,flexShrink:`0`});let Rt=()=>{g()&&e.historySessionState.nextMessageCursor&&e.session.getActiveConversationId()?(Lt.textContent=t.showEarlierMessagesLabel,Lt.parentNode!==e.body&&e.body.insertBefore(Lt,e.body.firstChild)):Lt.remove()};Lt.addEventListener(`click`,()=>{let t=e.session.getActiveConversationId(),n=e.historySessionState.nextMessageCursor;if(!t||!n||Lt.disabled)return;Lt.disabled=!0;let r=e.body.scrollHeight,i=e.body.scrollTop;e.session.loadOlderMessages(t,n,{scope:y()}).then(()=>{e.body.scrollTop=i+(e.body.scrollHeight-r),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Lt.disabled=!1,Rt()})});let zt=()=>{let n=e.createHeaderIconButton({ariaLabel:t.openHistoryLabel,iconName:`history`,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`,extraClassName:`persona-history-toggle`,attrs:{"data-persona-history-toggle":``}});return n.button.addEventListener(`click`,t=>{g()&&!_()&&(e.historyVisible?H():mt({invoker:n.button,keyboard:t.detail===0}))}),n},Bt=()=>{if(!g()){l?.remove(),c=null,l=null;return}if(l&&!l.isConnected&&(c=null,l=null),!c&&e.header){let t=zt();c=t.button,l=t.wrapper;let n=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;n?.parentNode&&e.header.contains(n)?n.parentNode.insertBefore(l,n):e.header.appendChild(l)}if(!c||!l)return;let n=Ke()||e.historyVisible&&e.historyPresentation===`rail`;if(l.style.display=n?`none`:``,n){document.activeElement===c&&pt();return}let r=_();c.disabled=r,c.setAttribute(`aria-disabled`,r?`true`:`false`);let i=r?t.openHistoryBusyLabel:t.openHistoryLabel;c.setAttribute(`aria-label`,i),(e.config.features?.history?.presentation??`panel`)===`panel`?(c.removeAttribute(`aria-expanded`),c.removeAttribute(`aria-controls`)):(c.setAttribute(`aria-expanded`,e.historyVisible?`true`:`false`),c.setAttribute(`aria-controls`,h))},Vt=!1,Ht=()=>{let n=e.panelElements.clearChatButton;n&&(g()?(Vt||=(f=n.getAttribute(`aria-label`)??``,!0),n.setAttribute(`aria-label`,t.newConversationLabel),n.removeAttribute(`title`)):Vt&&(Vt=!1,f&&n.setAttribute(`aria-label`,f)))},Ut=()=>{t=fc(e.config.features?.history?.copy),Bt(),I(),Ht(),Rt()};return e.historyChromeSync=Ut,E(),Ut(),e.destroyCallbacks.push(()=>{p?.(),m?.(),d+=1,ht(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:g,historyScope:v,installHistoryProvider:E,syncHistoryChromeImpl:Ut,syncHistoryPresentation:dt,syncEarlierMessagesPill:Rt,openHistory:mt,closeHistory:H,openHistoryConversation:Dt,startNewConversation:Ot,updateHistoryConversation:kt,deleteHistoryConversation:At,requestDeleteConversation:Pt,clearConversationHistory:jt,resetHistoryIdentity:W,railCollapseShortcut:Ie,railCollapsible:_e,railTriggerApplies:Ke,railOverlayMode:Ce,toggleRailCollapsed:Fe,toggleRailPinned:()=>Pe(),get historyProvider(){return n},get historySurface(){return i},get railShell(){return pe},get railHost(){return M},get railColumn(){return me}}}}));$c(),Pt();const{setLoader:el,load:tl,provide:nl,getSync:rl}=Nt({fallbackImport:()=>Promise.resolve().then(()=>($c(),Zc))}),il=tl,al=nl,ol=rl;al(Zc),Y(),Yt();const sl=[`persona-w-full`,`persona-rounded-2xl`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-text-persona-primary`,`persona-shadow-sm`,`persona-overflow-hidden`,`persona-px-0`,`persona-py-0`],cl=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),ll=(e,t)=>{let n=q(`div`,[`persona-message-bubble`,e,...sl].join(` `));return n.id=`bubble-${t}`,n.setAttribute(`data-message-id`,t),n},ul=e=>{let t=q(`button`,e.expandable?`persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none`:`persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none`);return t.type=`button`,e.expandable&&(t.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),t.setAttribute(`data-expand-header`,`true`)),t.setAttribute(`data-bubble-type`,e.bubbleType),t},dl=(e,t,n)=>{e.innerHTML=``;let r=Jt(t?w:x,16,n,2);r?e.appendChild(r):e.textContent=t?`Hide`:`Show`},fl=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let r=q(`div`,`persona-flex persona-items-center`);dl(r,n.expanded,n.iconColor);let i=q(`div`,n.metaGap?`persona-flex persona-items-center persona-gap-2 persona-ml-auto`:`persona-flex persona-items-center persona-ml-auto`);return i.append(r),e.append(t,i),r},pl=e=>{let t=q(`div`,`persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted`);if(t.setAttribute(`data-persona-collapsed-preview`,e.previewKind),t.style.display=`none`,t.style.whiteSpace=`pre-wrap`,!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let n=e.renderPreview?.();cl(t,n)||(t.textContent=e.previewText),t.style.display=``}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},ml=e=>{e.header.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),e.toggleIcon&&dl(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?``:`none`,e.collapsedPreview.style.display=e.expanded?`none`:e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?``:`none`},hl=(e,t,n)=>{let r=n.stateSet.has(e),i=t.querySelector(`button[data-expand-header="true"]`),a=t.querySelector(`.persona-border-t`),o=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!i||!a)return;i.setAttribute(`aria-expanded`,r?`true`:`false`);let s=i.querySelector(`.persona-ml-auto`)?.querySelector(`:scope > .persona-flex.persona-items-center`);s&&dl(s,r,n.iconColor),a.style.display=r?``:`none`,o&&(o.style.display=r?`none`:o.textContent||o.childNodes.length?``:`none`)};Yt(),No(),Y(),mn();function gl(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return{...e,features:{...e?.features,[n]:{...t===`tool`?To:Eo,...e?.future?.v5Defaults===!0?jo.features?.[n]:{},...e?.features?.[n]}}}}function _l(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return e?.features?.[n]?.variant??(e?.future?.v5Defaults?`row`:`card`)}function vl(e){let t=Math.max(0,Math.floor((e??0)/1e3));return t<1?`a moment`:t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function yl(e,t,n,r){if(_l(n,r)!==`row`)return e;e.className=`persona-message-bubble persona-${r}-bubble persona-activity-row`,e.dataset.activityKind=r,r===`tool`&&n.toolCall?.shadow===void 0&&(e.style.boxShadow=`var(--persona-tool-bubble-shadow, none)`);let i=e.querySelector(`:scope > button`);if(!i)return e;i.className=`persona-activity-header`;let a=r===`tool`?t.toolCall:t.reasoning,o=a?.status!==`complete`,s=t.approval?.status??t.toolCall?.approvalStatus,c=s===`denied`?`denied`:s===`pending`?`awaiting-approval`:t.toolCall?.success===!1?`error`:o?a?.status===`pending`?`pending`:`running`:`done`;e.dataset.activityState=c;let l=q(`span`,`persona-activity-icon`);l.dataset.activityIcon=c;let u={pending:`circle`,running:`loader-circle`,done:`check`,error:`x`,denied:`x`,"awaiting-approval":`clock`},d=r===`reasoning`?n.features?.reasoningDisplay?.iconName:void 0,f=d?K(d,16,`currentColor`,2):c===`pending`?Jt(T,16,`currentColor`,2):c===`awaiting-approval`?Jt(ee,16,`currentColor`,2):K(u[c],16,`currentColor`,2);f&&l.appendChild(f),i.querySelector(`.persona-reasoning-header-icon`)?.remove();let p=r===`tool`?`toolCallDisplay`:`reasoningDisplay`,m=n.features?.[p]?.iconVisibility??(n.future?.v5Defaults?`active`:`always`);if((m===`always`||m===`active`&&c!==`done`)&&i.prepend(l),r===`tool`&&a){let e=q(`span`,`persona-activity-duration`);o&&a.startedAt&&e.setAttribute(`data-tool-elapsed`,String(a.startedAt));let n=(r===`tool`?t.toolCall?.duration:void 0)??a.durationMs??(a.completedAt!==void 0&&a.startedAt!==void 0?a.completedAt-a.startedAt:void 0);e.textContent=n===void 0?``:vl(n),i.appendChild(e)}i.querySelector(`:scope > div:not(.persona-ml-auto)`)?.classList.add(`persona-activity-label`),i.querySelector(`.persona-ml-auto`)?.classList.add(`persona-activity-chevron`);let h=e.querySelector(`:scope > .persona-border-t`);return h?.classList.add(`persona-activity-body`),h&&(h.id=`activity-details-${t.id}`,i.setAttribute(`aria-controls`,h.id)),e}function bl(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map,a=e=>{clearTimeout(i.get(e)),i.delete(e)};return{observe(a,o,s,c={}){let l=o===`tool`?a.toolCall:a.reasoning;if(l&&!n.has(a.id)&&(!t.has(a.id)&&l.status!==`complete`&&l.chunks?.some(Boolean)&&(t.add(a.id),c.autoExpand!==!1&&s.add(a.id)),t.has(a.id)&&l.status===`complete`&&!r.has(a.id))){if(r.add(a.id),c.autoCollapseDelay===!1)return;i.set(a.id,setTimeout(()=>{i.delete(a.id),s.delete(a.id),e(a.id,o)},c.autoCollapseDelay??1e3))}},manual(e){n.add(e),a(e)},prune(e){for(let i of/* @__PURE__ */ new Set([...t,...n,...r]))e.has(i)||(a(i),t.delete(i),n.delete(i),r.delete(i))},clear(){for(let e of i.keys())a(e);t.clear(),n.clear(),r.clear()}}}function xl(e,t,n,r){let i=q(`div`,``);i.id=`bubble-${e.id}`,i.dataset.messageId=e.id;let a=q(`button`,``);a.type=`button`,a.dataset.expandHeader=`true`,a.dataset.bubbleType=`tool`,a.setAttribute(`aria-expanded`,String(n));let o=q(`div`,``);typeof r==`string`?o.textContent=r:o.appendChild(r),fl(a,o,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||`currentColor`,metaGap:!0});let s=q(`div`,`persona-border-t`);return s.id=`activity-details-${e.id}`,s.style.display=n?``:`none`,a.setAttribute(`aria-controls`,s.id),i.append(a,s),yl(i,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:`row`}}},`tool`),i.dataset.personaToolGroup=`true`,t.features?.toolCallDisplay?.loadingAnimation===`shimmer`&&(i.dataset.activityGroupShimmer=`true`),{bubble:i,body:s}}function Sl(e,t){let n=e.voiceRecognition,r=t.voiceRecognition;return n?.enabled===!0!=(r?.enabled===!0)||n?.provider?.type!==r?.provider?.type||n?.provider?.custom!==r?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==r?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(r?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function Cl(e){return e?.type===`runtype`||e?.type===`custom`}const wl=()=>typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window);function Tl(e){try{if(e?.type===`custom`&&e.custom){let t=e.custom,n=typeof t==`function`?t():t;return!!n&&typeof n.startListening==`function`}return e?.type===`runtype`&&e.runtype?!0:wl()}catch{return!1}}const El=e=>{if(!e)return;let t={},n=e;if(n.heading){let e=n.heading;t.heading=(t,n,r)=>e({type:`heading`,raw:r,depth:n,text:t,tokens:[]})}if(n.code){let e=n.code;t.code=(t,n,r)=>e({type:`code`,raw:``,text:t,lang:n,escaped:r})}if(n.blockquote){let e=n.blockquote;t.blockquote=t=>e({type:`blockquote`,raw:``,text:t,tokens:[]})}if(n.table){let e=n.table;t.table=(t,n)=>e({type:`table`,raw:``,header:[],rows:[],align:[],headerHtml:t,bodyHtml:n})}if(n.link){let e=n.link;t.link=(t,n,r)=>e({type:`link`,raw:``,href:t,title:n??null,text:r,tokens:[]})}if(n.image){let e=n.image;t.image=(t,n,r)=>e({type:`image`,raw:``,href:t,title:n??null,text:r})}if(n.list){let e=n.list;t.list=(t,n,r)=>e({type:`list`,raw:``,ordered:n,start:r,loose:!1,items:[],itemsHtml:t})}if(n.listitem){let e=n.listitem;t.listitem=(t,n,r)=>e({type:`list_item`,raw:``,task:n,checked:r,loose:!1,text:t,tokens:[]})}if(n.paragraph){let e=n.paragraph;t.paragraph=t=>e({type:`paragraph`,raw:``,text:t,tokens:[]})}if(n.codespan){let e=n.codespan;t.codespan=t=>e({type:`codespan`,raw:``,text:t})}if(n.strong){let e=n.strong;t.strong=t=>e({type:`strong`,raw:``,text:t,tokens:[]})}if(n.em){let e=n.em;t.em=t=>e({type:`em`,raw:``,text:t,tokens:[]})}if(n.del){let e=n.del;t.del=t=>e({type:`del`,raw:``,text:t,tokens:[]})}if(n.html){let e=n.html;t.html=t=>e({type:`html`,raw:t,text:t})}if(n.text){let e=n.text;t.text=t=>e({type:`text`,raw:t,text:t})}if(n.checkbox){let e=n.checkbox;t.checkbox=t=>e({checked:t})}return n.hr&&(t.hr=n.hr),n.br&&(t.br=n.br),t},Dl=e=>{let t=null;return n=>{let r=Kt();if(!r)return jl(n);if(!t){let{Marked:n}=r,i=e?.markedOptions;t=new n({gfm:i?.gfm??!0,breaks:i?.breaks??!0,pedantic:i?.pedantic,silent:i?.silent});let a=El(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},Ol=e=>e?Dl({markedOptions:e.options,renderer:e.renderer}):Dl(),kl=Dl(),Al=e=>kl(e),jl=e=>e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`),Ml=e=>e.replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`),Nl=e=>`%%FORM_PLACEHOLDER_${e}%%`,Pl=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,n)=>{try{let e=JSON.parse(n.trim());if(e&&typeof e==`object`&&e.component===`form`&&e.type){let n=Nl(t.length);return t.push({token:n,type:String(e.type)}),n}}catch{return e}return e}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,n)=>{let r=Nl(t.length);return t.push({token:r,type:n}),r}),n},Fl=e=>{let t=Ol(e);return e=>{let n=[],r=Pl(e,n),i=t(r);return n.forEach(({token:e,type:t})=>{let n=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`g`),r=`<div class="persona-form-directive" data-tv-form="${Ml(t)}"></div>`;i=i.replace(n,r)}),i}},Il=e=>{let t=[],n=Pl(e,t),r=Al(n);return t.forEach(({token:e,type:t})=>{let n=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`g`),i=`<div class="persona-form-directive" data-tv-form="${Ml(t)}"></div>`;r=r.replace(n,i)}),r},Ll={ALLOWED_TAGS:/* @__PURE__ */ `h1.h2.h3.h4.h5.h6.p.br.hr.div.span.ul.ol.li.dl.dt.dd.strong.em.b.i.u.s.del.ins.mark.small.sub.sup.abbr.kbd.var.samp.code.a.img.blockquote.pre.details.summary.table.thead.tbody.tfoot.tr.th.td.caption.colgroup.col.input.label.select.option.textarea.button`.split(`.`),ALLOWED_ATTR:/* @__PURE__ */ `href.src.alt.title.target.rel.loading.width.height.colspan.rowspan.scope.class.id.type.name.value.placeholder.disabled.checked.for.aria-label.aria-hidden.aria-expanded.role.tabindex.data-tv-form.data-message-id.data-persona-component-directive.data-preserve-animation.data-persona-instance`.split(`.`)},Rl=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,zl=()=>{let e=null;return t=>{let n=Kt();if(!n)return jl(t);if(!e){let{DOMPurify:t}=n;e=t(typeof window<`u`?window:void 0),e.addHook(`uponSanitizeAttribute`,(e,t)=>{if(t.attrName===`src`||t.attrName===`href`){let e=t.attrValue;e.toLowerCase().startsWith(`data:`)&&!Rl.test(e)&&(t.attrValue=``,t.keepAttr=!1)}})}return e.sanitize(t,Ll)}},Bl=e=>e===!1?null:typeof e==`function`?e:zl(),Vl=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Hl=e=>e.includes(`|`),Ul=e=>{let t=e.trim();return t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&(t=t.slice(0,-1)),t.split(`|`).map(e=>e.trim())},Wl=e=>`| ${e.join(` | `)} |`,Gl=e=>`| ${Array.from({length:e},()=>`---`).join(` | `)} |`,Kl=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>``)),ql=e=>{if(!e||!e.includes(`|`))return e;let t=e.split(`
|
|
12
|
-
`),n=!1;for(let e=0;e<t.length-1;e++){let r=t[e],i=t[e+1];if(!
|
|
13
|
-
`):e},Jl=`var(--persona-md-table-scroll-fade, 24px)`,Yl=/* @__PURE__ */ new WeakSet;function Xl(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(`persona-table-scroll`))return;let t=document.createElement(`div`);t.className=`persona-table-scroll`,e.replaceWith(t),t.appendChild(e)})}function Zl(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute(`data-persona-scroll-x`);return}e.setAttribute(`data-persona-scroll-x`,``);let n=getComputedStyle(e).direction===`rtl`?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty(`--persona-fade-l`,n<=1?`0px`:Jl),e.style.setProperty(`--persona-fade-r`,r<=1?`0px`:Jl)}function Ql(e){Yl.has(e)||(Yl.add(e),e.addEventListener(`scroll`,e=>{let t=e.target;t?.classList?.contains(`persona-table-scroll`)&&Zl(t)},!0)),e.querySelectorAll(`.persona-table-scroll`).forEach(Zl)}Pt();const{setLoader:$l,load:eu}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/webmcp-runtime`)}),tu=eu;Pt();const{setLoader:nu,load:ru}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/voice-client-tools`)}),iu=ru;function au(e){return e.startsWith(`agent_`)?{kind:`agentId`,agentId:e}:e.startsWith(`flow_`)?{kind:`flowId`,flowId:e}:null}function ou(e,t){let n=e.trim();if(!n)throw Error("[Persona] `target` is empty.");let r=n.indexOf(`:`);if(r>0){let e=n.slice(0,r),i=n.slice(r+1);if(e===`runtype`){let e=au(i);if(e)return e;throw Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let a=t?.[e];if(!a)throw Error(`[Persona] No target provider registered for "${e}". Add a \`targetProviders.${e}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:`payload`,payload:a(i).payload}}let i=au(n);if(i)return i;let a=t?.default;if(a)return{kind:`payload`,payload:a(n).payload};throw Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function su(){return`msg_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function cu(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function lu(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function uu(){return`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}const du=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),fu=e=>typeof e==`object`&&!!e&&!Array.isArray(e),pu=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=du(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:fu(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},mu=(e,t)=>{let n=[],r=[],i=[],a=``,o,s=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let c of e){let e=pu(c);if(e){let t=c.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==o)&&s(),r.length===0&&(a=c.createdAt,o=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let l=t(c);l&&(s(),n.push(l))}return s(),n};En(),Z(),er(),Ri(),Wc(),yi();var hu=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryClientError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};const gu=e=>`reason`in e?e.reason:void 0,_u=(e,t)=>e instanceof hu&&e.code===t,vu=e=>!e.voiceCaption&&!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),yu=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),bu=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function xu(e){switch(e){case`json`:return Zn;case`regex-json`:return Xn;case`xml`:return $n;default:return Yn}}var Su=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;constructor(e={},t={}){if(this.config=e,this.historyInternals=t,this.#l=null,this.clientSession=null,this.#u=null,this.#d=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null,this.#p=!1,this.#m=!1,this.#h=!1,this.#g=null,this.#_=/* @__PURE__ */ new Set,this.#v=/* @__PURE__ */ new Set,this.webMcpBridge=null,this.#y=null,this.#H=null,this.#W=null,e.target&&(e.agentId||e.flowId||e.agent))throw Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??`https://api.runtype.com/v1/dispatch`,this.#t={"Content-Type":`application/json`,"X-Persona-Version":Li,...e.headers},this.debug=!!e.debug,this.#n=e.streamParser??xu(e.parserType),this.#r=e.contextProviders??[],this.#i=e.requestMiddleware,this.#a=e.customFetch,this.#o=e.parseSSEEvent,this.#s=e.getHeaders,e.webmcp?.enabled===!0&&(this.#y=this.#x(e.webmcp))}#x(e){return tu().then(t=>{let n=new t.WebMcpBridge(e,{recordToolDisplayTitles:bn,getToolDisplayTitle:xn,loadPolyfill:Tn});return this.#b!==void 0&&n.setConfirmHandler(this.#b),this.webMcpBridge=n,n}).catch(e=>(this.#y=null,console.warn(`[Persona] Failed to load the WebMCP runtime chunk`,e),null))}#S(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled===!0?(this.#y||=this.#x(this.config.webmcp),this.#y):Promise.resolve(null)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#c=e}setWebMcpConfirmHandler(e){this.#b=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}getVoiceClientTools(){if(this.config.webmcp?.enabled!==!0)return null;let e=()=>this.#S(),t={open:async e=>(await iu()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await(await e())?.snapshotForDispatch()??[];return{tools:t,fingerprint:hn(t)}},onChange:t=>{let n=null,r=!1;return e().then(e=>{e&&!r&&(n=e.watchToolChanges(t))}),()=>{r=!0,n?.()}},execute:async(t,n,r)=>{let i=await e();return i?i.executeVoiceToolCall(t,n,r):{status:`failed`,error:{message:`WebMCP runtime failed to load.`}}}};return t}executeWebMcpToolCall(e,t,n){return this.config.webmcp?.enabled===!0?this.#S().then(r=>r?r.executeToolCall(e,t,n):{isError:!0,content:[{type:`text`,text:`WebMCP runtime failed to load.`}]}):null}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#C(){let{agentId:e,flowId:t,target:n,targetProviders:r}=this.config;if(!n)return{agentId:e,flowId:t};let i=ou(n,r);return i.kind===`agentId`?{agentId:i.agentId}:i.kind===`flowId`?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.#C().agentId)}#w(){return this.config.apiUrl?.replace(/\/+$/,``).replace(/\/v1\/dispatch$/,``)||`https://api.runtype.com`}#T(e){return`${this.#w()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),n=!1;for(;;){let r=t.conversationId,i=await this.readVisitorToken();if(t.durableRecovery?.enabled!==!0||!r||!i)throw new hu(`visitor_token_missing`,`Durable recovery is not enabled for this client session`);let a=`${this.#w()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,o=new URLSearchParams({sessionId:t.sessionId,after:e.after}),s=await fetch(`${a}?${o}`,{method:`GET`,headers:{"X-Persona-Version":Li,"X-Visitor-Token":i},signal:e.signal});if(s.status===401&&!n){n=!0;let e=await pa();t=await e.recoverFromUnauthorized(this.#G(),await e.readErrorCode(this.#G(),s),null,!0)}else{if(!s.ok)throw await(await pa()).historyErrorFor(this.#G(),s,!0);return s}}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#u||e&&/* @__PURE__ */ new Date<e.expiresAt||this.#d===e?null:(this.#d=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw Error(`initSession() only available in client token mode`);if(this.clientSession&&/* @__PURE__ */ new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#u)return this.#u;let e=this.#u=this.#N().then(t=>this.#u===e?(this.clientSession=t,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#u===e&&(this.#u=null)});return e}#E(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#p}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#D(){if(!this.#p){this.#j({state:`unavailable`,reason:`history_disabled`}),this.#p=!0,!this.#m&&typeof console<`u`&&(this.#m=!0,console.warn(`[Persona] Visitor history is disabled for this surface; continuing without it.`)),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#v])e(!1)}}getHistoryIdentityStatus(){return this.#g??this.#O()}subscribeHistoryIdentityStatus(e){return this.#_.add(e),()=>{this.#_.delete(e)}}subscribeHistoryAvailability(e){return this.#v.add(e),this.#p&&e(!1),()=>{this.#v.delete(e)}}#O(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#p?{state:`unavailable`,reason:`history_disabled`}:this.#k():{state:`unavailable`,reason:`ineligible_mode`}}#k(){let e=this.#g;return e?.state===`browser_only`?e:this.#A()}#A(){return this.config.features?.history?.scope===`browser`?{state:`browser_only`,reason:`configured_browser_scope`}:this.config.getIdentityProof?{state:`browser_only`,reason:`proof_unavailable_before_binding`}:{state:`browser_only`,reason:`no_identity_provider`}}#j(e){let t=this.getHistoryIdentityStatus(),n=t.state===e.state&&gu(t)===gu(e);if(this.#g=e,!n){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#_])t(e)}}async#M(e){let t=this.#E()&&!e.omitVisitorFields,n=!e.omitVisitorFields,r=null;(t||n)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let i=this.#C(),a=i.agentId??i.flowId,o=t||e.durableResume?e.conversationId:void 0,s={token:this.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(t||n)&&r?{visitorToken:r}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...o?{conversationId:o}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let c=await fetch(this.#T(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":Li},body:JSON.stringify(s),signal:e.signal});if(!c.ok){let n=await c.json().catch(()=>({error:`Session initialization failed`}));if(t&&c.status===403&&n.error===`visitor_history_disabled`){if(this.#D(),o)throw new hu(`history_disabled`,`Visitor history is disabled for this surface`);return this.#M({...e,omitVisitorFields:!0})}throw c.status===403&&n.error===`durable_recovery_disabled`?new hu(`history_disabled`,`Durable recovery is disabled for this surface`):(t||e.durableResume)&&c.status===401&&n.error===`visitor_required`?new hu(`visitor_required`,`Visitor credential no longer resolves`):o&&c.status===404?new hu(`not_found`,`Conversation not found`):c.status===401?Error(`Invalid client token: ${n.hint||n.error}`):c.status===403?Error(`Origin not allowed: ${n.hint||n.error}`):Error(n.error||`Failed to initialize session`)}let l=await c.json();return l.visitor?.token&&await this.historyInternals.visitorStore?.set(l.visitor.token),{sessionId:l.sessionId,expiresAt:new Date(l.expiresAt),flow:l.flow,...l.conversationId?{conversationId:l.conversationId}:{},...l.targetId?{targetId:l.targetId}:{},...l.conversationRevision?{conversationRevision:l.conversationRevision}:{},...l.durableRecovery?{durableRecovery:l.durableRecovery}:{},...l.visitor?{visitor:l.visitor}:{},config:{welcomeMessage:l.config.welcomeMessage,placeholder:l.config.placeholder,theme:l.config.theme}}}async#N(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,t=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#E()&&!t)return this.#P(e,!1);let n=await this.readVisitorToken();if(e&&n)try{let n=await this.#M({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#R(n,e,!1)}catch(n){if(!_u(n,`not_found`)&&!_u(n,`visitor_required`)&&!_u(n,`history_disabled`))throw n;return t&&this.historyInternals.setStoredResumableHandle?.(null),this.#P(e,!0)}return this.#P(e,!1)}async#P(e,t){let n=this.historyInternals.visitorStore;return n&&!await this.readVisitorToken()?n.withFirstInitLock(()=>this.#F(e,t)):this.#F(e,t)}async#F(e,t){let n=this.config.getStoredSessionId?.()||null,r=await this.#M({storedSessionId:n}),i=await this.#L(r);return this.#R(i,e,t)}async#I(e){let t=this.config.getStoredSessionId?.()||null,n=this.config.getStoredConversationId?.()||null,r=await this.#M({storedSessionId:t,identityProof:e}),i=this.#R(r,n,!1);return this.clientSession=i,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint(),i}async#L(e){if(!e.visitor?.token||this.#h||!this.#E()&&e.durableRecovery?.enabled!==!0)return e;this.#h=!0;try{return await this.#M({storedSessionId:e.sessionId})}catch{return e}finally{this.#h=!1}}#R(e,t,n){let r=e.conversationId;return r&&t&&(n||r!==t)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#z(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#d=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw Error(`prepareConversationSession() only available in client token mode`);if(!this.#E())throw new hu(`history_disabled`,`Visitor history is disabled for this surface`);await this.historyInternals.historyBootstrapReady;let n=t?.proof??null;if(!await this.readVisitorToken()&&!n)throw new hu(`conversation_credential_missing`,`Reopening a conversation requires a stored visitor token or an identity proof`);let r=await this.#M({conversationId:e,identityProof:n});return this.#z(r)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error(`prepareNewConversationSession() only available in client token mode`);await this.historyInternals.historyBootstrapReady;let e=await this.#M({});return this.#z(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#E()&&this.#j(this.#A())}clearClientSession(){this.clientSession=null,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null}#B(){return`${this.#w()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw Error(`sendFeedback() only available in client token mode`);if(!this.getClientSession())throw Error(`No active session. Please initialize session first.`);if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let t={...e,...this.config.clientToken&&{token:this.config.clientToken}},n=await fetch(this.#B(),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":Li},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:`Feedback submission failed`}));throw n.status===401?(this.clientSession=null,this.#d=!1,this.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async submitMessageFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`csat`,rating:e,comment:t})}async submitNPSFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`nps`,rating:e,comment:t})}async#V(e){e?.throwIfAborted();let t=this.config.identityProvider;if(t===void 0)return;let n=this.config.getIdentityProof;if(!t.trim()||!n)throw Error(`Chat identity requires identityProvider and getIdentityProof.`);let r,i;try{let t=Promise.resolve().then(()=>n());r=e?await Promise.race([t,new Promise((t,n)=>{i=()=>n(e.reason),e.addEventListener(`abort`,i,{once:!0}),e.aborted&&i()})]):await t}catch{throw e?.throwIfAborted(),Error(`The identity proof provider failed.`)}finally{i&&e?.removeEventListener(`abort`,i)}if(typeof r!=`string`||!r.trim())throw Error(`A fresh identity proof is required to send this message.`);return{provider:t,token:r}}#H;#U(){let e=this;return this.#H??={get config(){return e.config},headers:this.#t,getHeaders:this.#s,debug:this.debug,clientApiBase:()=>e.#w(),getClientApiUrl:t=>e.#T(t),getWebMcpBridge:()=>e.#S(),sendWithClientToolsDiff:(t,n,r,i)=>e.#Y(t,n,r,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#W;#G(){let e=this;return this.#W??={HistoryClientError:hu,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#w(),setHistoryIdentityStatus:t=>e.#j(t),browserOnlyStatus:()=>e.#k(),derivedBrowserOnly:()=>e.#A(),reinitWithProof:t=>e.#I(t),isHistoryCapable:()=>e.#E(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await pa()).listConversations(this.#G(),e)}async getConversation(e,t){return(await pa()).getConversation(this.#G(),e,t)}async finalizeDisplayProjections(e,t){return(await pa()).finalizeDisplayProjections(this.#G(),e,t)}async deleteConversation(e,t){return(await pa()).deleteConversation(this.#G(),e,t)}async deleteAllConversations(e){return(await pa()).deleteAllConversations(this.#G(),e)}async resetVisitor(){return(await pa()).resetVisitor(this.#G())}async dispatch(e,t){return e.signal?.throwIfAborted(),Ni().catch(()=>{}),this.isClientTokenMode()?this.#K(e,t):this.isAgentMode()?this.#J(e,t):this.#q(e,t)}async#K(e,t){let n=uu();this.#l=n;let r=()=>this.#l===n,i=e=>{r()&&t(e)};t({type:`status`,status:`connecting`});try{let t=()=>{if(e.signal?.throwIfAborted(),!r())throw new DOMException(`Turn superseded`,`AbortError`)},a=this.clientSession??await this.initSession();t();let o=async()=>{t();let n=a,r=n.durableRecovery?.enabled===!0;if(r&&(!n.conversationId||!await this.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);t();let i=await this.#M({...r||this.#E()?{conversationId:n.conversationId,durableResume:r}:{storedSessionId:n.sessionId},signal:e.signal});if(t(),n.conversationId&&i.conversationId!==n.conversationId||r&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);a=this.#R(i,n.conversationId??null,!1),this.clientSession=a,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(a)};Date.now()>=a.expiresAt.getTime()-6e4&&await o();let s=await this.#te(e.messages),c=s.metadata?Object.fromEntries(Object.entries(s.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,l=this.#E(),u={sessionId:a.sessionId,messages:e.messages.filter(vu).map(e=>{let t=l?Bc(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...c&&Object.keys(c).length>0&&{metadata:c},...s.inputs&&Object.keys(s.inputs).length>0&&{inputs:s.inputs},...s.context&&{context:s.context},turnId:n,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0}}},d=async()=>{t();let n=a.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return t(),this.#Y(a.sessionId,s.clientTools,async r=>{t();let i=await this.#V(e.signal);t();let o={...u,sessionId:a.sessionId,...r,...i&&{identityProof:i}};return this.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...o,...i&&{identityProof:{provider:i.provider,token:`[REDACTED]`}}}),fetch(this.#T(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":Li,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(o),signal:e.signal})})},f=await d();if(t(),f.response.status===401){let e=await f.response.clone().json().catch(()=>null);t(),e?.error===`Session not found or expired`&&(await o(),f=await d(),t())}let{response:p,commit:m}=f;if(!p.ok){let e=await p.json().catch(()=>({error:`Chat request failed`}));if(p.status===401&&e.error===`invalid_identity_proof`){let e=new hu(`invalid_identity_proof`,`The identity proof was rejected`);throw i({type:`error`,error:e}),e}if(p.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw i({type:`error`,error:e}),e}if(p.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw i({type:`error`,error:t}),t}if(p.status===410&&e.error===`conversation_deleted`){let e=new hu(`conversation_deleted`,`This conversation was deleted`);throw i({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw i({type:`error`,error:t}),t}if(!p.body){let e=/* @__PURE__ */ Error(`No response body received`);throw i({type:`error`,error:e}),e}m(),i({type:`status`,status:`connected`});try{await this.#ne(p.body,i,e.assistantMessageId)}finally{i({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof hu)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&i({type:`error`,error:t}),t}}async#q(e,t){t({type:`status`,status:`connecting`});let n=await this.#te(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t)}finally{t({type:`status`,status:`idle`})}}async#J(e,t){t({type:`status`,status:`connecting`});let n=await this.#ee(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t,e.assistantMessageId)}finally{t({type:`status`,status:`idle`})}}async processStream(e,t,n,r){t({type:`status`,status:`connected`});try{await this.#ne(e,t,n,r)}finally{t({type:`status`,status:`idle`})}}async resolveApproval(e,t){return(await Ni()).resolveApproval(this.#U(),e,t)}async#Y(e,t,n,r){let i=!!(t&&t.length>0),a=i?hn(t):void 0,o=this.clientToolsFingerprintSessionId===e,s=i&&o&&this.lastSentClientToolsFingerprint===a,c=!i&&r?.emptyMeansReplace===!0&&this.#f===e,l=!1,u;for(let e=0;u=await n({...i&&(l||!s)&&t?{clientTools:t}:{},...c?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&e===0&&i&&(await u.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)l=!0,this.lastSentClientToolsFingerprint=null;return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,i?this.#f=e:c&&(this.#f=null)}}}async resumeFlow(e,t,n){return(await Ni()).resumeFlow(this.#U(),e,t,n)}#X(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#Z(e){let t={};this.#r.length&&await Promise.all(this.#r.map(async n=>{try{let r=await n({messages:e,config:this.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#X(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#Q(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#$(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}async#ee(e,t){let n=this.#C().agentId;if(!this.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=mu(yu(e),e=>vu(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?bu(e):null),i=this.#Q(t),a={agent:this.#$(this.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.config.agentOptions}};i&&(a.composerOptions=i);let o=[...hi(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let s=await this.#Z(e);return s&&(a.context=s),a}async#te(e,t){let n=mu(yu(e),e=>vu(e)?bu(e):null),r=this.#C(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...hi(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#Z(e);o&&(i.context=o);let s=this.#Q(t);if(s&&(i.composerOptions=s),this.#i)try{let e=await this.#i({payload:{...i},config:this.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}async#ne(e,t,n,r){let{streamResponse:i}=Fi()??await Ni();return i({config:()=>this.config,createStreamParser:this.#n,parseSSEEvent:this.#o,onSSEEvent:(e,t)=>this.#c?.(e,t)},e,t,n,r)}},Cu=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryProviderError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};function wu(e){return e instanceof Cu}function Tu(e){let t=0;for(let n of e.split(`
|
|
14
|
-
`)){let e=/^ {0,3}(`+)/.exec(n);e&&e[1].length>t&&(t=e[1].length)}return t}function
|
|
11
|
+
`)[0]).startsWith(t.trigger):!1),l=(e,t)=>{if(typeof window<`u`)try{window.dispatchEvent(new CustomEvent(`persona:mention:${e}`,{detail:t}))}catch{}},u=!e.chipRow,d=e.chipRow??J(`div`,{className:`persona-mention-context-row`,attrs:{"data-persona-mention-context-row":``}}),f=null,p=null,m=e.textarea,h=null,g=null,_=null,v=null,y=()=>{if(f)return Promise.resolve(f);if(p)return p;let n=t().then(t=>(t.setMentionIconRenderer(r),f=t.mountContextMentions({mentionConfig:a,textarea:e.textarea,composerInput:h??void 0,anchor:e.anchor,contextRow:d,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:S,emit:l}),f)).catch(e=>(typeof console<`u`&&console.warn(`[Persona] Failed to load context mentions runtime`,e),p===n&&(p=null),null));return p=n,n};a.display===`inline`&&n().then(t=>{let n=t.mountInlineComposer({textarea:e.textarea,renderToken:e=>Ms(e,{render:a.renderMentionToken}),onMentionRemoved:e=>f?.untrackMention(e)});h=n.input,g=n.destroy;let r=m;r.replaceWith(n.element),m=n.element,v={next:n.element,prev:r},_?.(n.element,r),f?f.rebindComposer(n.input):p&&p.then(e=>e?.rebindComposer(n.input))}).catch(e=>{typeof console<`u`&&console.warn(`[Persona] Failed to load inline mention composer`,e)});let b=[],x=/* @__PURE__ */ new Map;for(let e of o){if(!e.showButton)continue;let t=i({config:{...a,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},onOpen:()=>{y().then(t=>t?.openMenu(e.trigger))}});b.push(t),x.set(e.trigger,t.button)}let S=(e,t,n)=>{let r=x.get(t);r&&(r.setAttribute(`aria-expanded`,e?`true`:`false`),e?r.setAttribute(`aria-controls`,n):r.removeAttribute(`aria-controls`))};return{affordanceButtons:b.map(e=>e.wrapper),contextRow:d,handleInput:e=>{if(f){f.handleInput();return}if(!ya(e))return;let t=m,n=t.selectionStart??0;va(t.value,n,o)&&y().then(e=>e?.handleInput())},handleKeydown:e=>{if(f?.isMenuOpen())return f.handleKeydown(e);if(e.key===`Backspace`&&f?.hasMentions()&&!v){let t=m,n=t.selectionStart===0&&t.selectionEnd===0;if((t.value.length===0||n)&&f.removeLastChip())return e.preventDefault(),!0}return!1},isMenuOpen:()=>f?.isMenuOpen()??!1,hasMentions:()=>f?.hasMentions()??!1,getMentionRefs:()=>f?.getMentionRefs()??[],collectForSubmit:()=>f?.collectForSubmit()??null,takeInlineCommand:async e=>c(e)?(f??await y())?.dispatchInlineCommand(e)??null:null,clear:()=>f?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:e=>{_=e,v&&e(v.next,v.prev)},destroy:()=>{f?.destroy(),g?.();for(let e of b)e.wrapper.remove();u&&d.remove()}}}var Fs,Is=W((()=>{Y(),xa(),Ca(),Cs(),Ds(),mn(),js(),Ns(),Fs={loadContextMentions:()=>Es(),loadContextMentionsInline:()=>As(),renderLucideIcon:(...e)=>K(...e),createMentionButton:(...e)=>Ss(...e)}})),Ls=/* @__PURE__ */ Mt({createAskUserSheetHandlers:()=>ma,createContextMentionOrchestrator:()=>Ps}),Rs=W((()=>{ha(),Is()}));Rs(),Pt();const{setLoader:zs,load:Bs,provide:Vs,getSync:Hs}=Nt({fallbackImport:()=>Promise.resolve().then(()=>(Rs(),Ls))}),Us=Bs,Ws=Vs,Gs=Hs;Ws(Ls);function Ks(){return`msg_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function qs(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function Js(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function Ys(){return`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}var Xs=W((()=>{})),Zs=/* @__PURE__ */ Mt({resolveApproval:()=>Qs,resolveAskUserQuestion:()=>$s,resolveWebMcpToolCall:()=>ac,resolveWebMcpToolCallBatch:()=>ic});async function Qs(e,t,n,r){let i=`approval-${t.id}`,a=`approval-error-${t.id}`,o=Js(),s={};e.s.approvalTokens.set(i,s);let c={...t,status:n,resolvedAt:Date.now()},l=e.s.messages.find(e=>e.id===i),u={id:i,role:`assistant`,content:``,createdAt:l?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),...l?.sequence===void 0?{}:{sequence:l.sequence},streaming:!1,variant:`approval`,approval:c};e.s.upsertMessage(u),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let d=e.s.config.approval,f=d&&typeof d==`object`?d.onDecision:void 0;try{let l;if(l=f?await f({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):await e.s.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n,{assistantMessageId:o}),l){let r=null;if(l instanceof Response){if(!l.ok){let n=await l.json().catch(()=>null),r=n?.message??n?.error??`Approval request failed: ${l.status}`,o=n?.code===`APPROVAL_ALREADY_RESOLVED`||l.status===404&&/no paused execution/i.test(String(n?.error)),d=e.s.messages.find(e=>e.id===i);throw e.s.approvalTokens.get(i)===s&&d?.approval?.resolvedAt===c.resolvedAt&&(e.s.upsertMessage({...u,approval:o?{...c,status:`timeout`}:t}),o&&e.settleApprovalPausedToolCall(i),e.s.upsertMessage({id:a,role:`assistant`,content:r,localOnly:!0,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})),Error(r)}r=l.body}else l instanceof ReadableStream&&(r=l);e.s.approvalTokens.get(i)===s&&e.s.messages.some(e=>e.id===a)&&(e.s.messages=e.s.messages.filter(e=>e.id!==a),e.s.callbacks.onMessagesChanged([...e.s.messages])),r?await e.s.connectStream(r,{allowReentry:!0,assistantMessageId:o}):(n===`denied`&&(e.settleApprovalPausedToolCall(i),e.appendMessage({id:`denial-${t.id}`,role:`assistant`,content:`Tool execution was denied by user.`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})),e.setStreaming(!1),e.s.abortController=null)}else e.setStreaming(!1),e.s.abortController=null}catch(t){let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));e.setStreaming(!1),e.s.abortController=null,n||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}finally{e.s.approvalTokens.get(i)===s&&e.s.approvalTokens.delete(i)}}async function $s(e,t,n){if(e.s.messages.find(e=>e.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,i=t.toolCall?.name;if(!r||!i){e.s.callbacks.onError?.(/* @__PURE__ */ Error(`resolveAskUserQuestion: message is missing executionId or toolCall.name`));return}let a=typeof n==`string`?void 0:n;if(a===void 0&&typeof n==`string`){let e=t.toolCall?.args,r=Array.isArray(e?.questions)?e.questions:[];if(r.length===1){let e=typeof r[0]?.question==`string`?r[0].question:``;e&&(a={[e]:n})}}e.s.markAskUserQuestionResolved(t,a),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let o=t.toolCall.id,s=t.toolCall?.args,c=Array.isArray(s?.questions)?s.questions:[];if(c.length===0){let t=typeof n==`string`?n:Object.entries(n).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `);e.appendMessage({id:`ask-user-answer-${o}`,role:`user`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})}else{let t=a??{};c.forEach((n,r)=>{let i=typeof n?.question==`string`?n.question:``;if(!i)return;let a=t[i],s=Array.isArray(a)?a.join(`, `):typeof a==`string`?a:``;e.appendMessage({id:`ask-user-q-${o}-${r}`,role:`assistant`,content:i,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()}),e.appendMessage({id:`ask-user-a-${o}-${r}`,role:`user`,content:s||`*Skipped*`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})})}try{let t=Js(),a=await e.s.client.resumeFlow(r,{[i]:n},{after:e.resumeAfter(r),assistantMessageId:t});if(!a.ok){let e=await a.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${a.status}`)}a.body?await e.s.connectStream(a.body,{allowReentry:!0,assistantMessageId:t}):(e.setStreaming(!1),e.s.abortController=null)}catch(t){let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));e.setStreaming(!1),e.s.abortController=null,n||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}}function ec(e,t){let n=[e.s.messages.find(e=>e.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let e of n)if(typeof e==`number`&&Number.isFinite(e))return e;return Date.now()}function tc(e,t){return t.toolCall?.name===`suggest_replies`&&(e.s.messages.find(e=>e.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function nc(e,t){let n=ec(e,t);return e.s.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:`running`,startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}function rc(e,t,n,r,i=Date.now(),a){e.s.messages.some(e=>e.id===t.id)&&e.s.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:`complete`,result:n,startedAt:r,completedAt:i,duration:void 0,durationMs:Math.max(0,i-r)}:t.toolCall})}async function ic(e,t,n){let r=[],i=new AbortController;e.s.webMcpResolveControllers.add(i),e.setStreaming(!0);let a=async n=>{let a=n.toolCall?.name,o=n.toolCall?.id;if(!a||!o)return null;let s=`${t}:${o}`;if(e.s.webMcpInflightKeys.has(s)||e.s.webMcpResolvedKeys.has(s)||tc(e,n))return null;e.s.webMcpInflightKeys.add(s),r.push(s);let c=nc(e,n),l=n.agentMetadata?.webMcpToolCallId??a;if(a===`suggest_replies`)return{dedupeKey:s,resumeKey:l,output:ai(),toolMessage:n,startedAt:c,completedAt:Date.now()};let u=e.s.client.executeWebMcpToolCall(a,n.toolCall?.args,i.signal),d;if(!u)d={isError:!0,content:[{type:`text`,text:`WebMCP not enabled on this widget.`}]};else try{d=await u}catch(t){let r=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));return r||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t))),rc(e,n,sc(r?`Aborted by cancel()`:cc(t)),c),e.s.webMcpInflightKeys.delete(s),null}return i.signal.aborted?(rc(e,n,sc(`Aborted by cancel()`),c),e.s.webMcpInflightKeys.delete(s),null):{dedupeKey:s,resumeKey:l,output:d,toolMessage:n,startedAt:c,completedAt:Date.now()}},o;if(e.s.config.webmcp?.execution===`sequential`){o=[];for(let e of n)o.push(await a(e))}else o=await Promise.all(n.map(a));let s=[];try{if(s=o.filter(e=>e!==null),s.length===0)return;let n={};for(let e of s)n[e.resumeKey]=e.output;let r=Js(),a=await e.s.client.resumeFlow(t,n,{signal:i.signal,after:e.resumeAfter(t),assistantMessageId:r});if(!a.ok){let e=await a.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${a.status}`)}let c=s[0].dedupeKey;for(let t of s){e.s.webMcpResolvedKeys.add(t.dedupeKey);let n=t.toolMessage.toolCall?.name,r=t.toolMessage.agentMetadata?.webMcpToolCallId;rc(e,t.toolMessage,t.output,t.startedAt,t.completedAt,{...n===`suggest_replies`?{suggestRepliesResolved:!0}:{},...n&&r?{clientToolAnswer:{toolCallId:r,toolName:n,args:t.toolMessage.toolCall?.args,result:t.output,batch:c}}:{}})}a.body&&await e.s.connectStream(a.body,{allowReentry:!0,assistantMessageId:r})}catch(t){if(!(t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`))))e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)));else for(let t of s)rc(e,t.toolMessage,sc(`Aborted by cancel()`),t.startedAt)}finally{for(let t of r)e.s.webMcpInflightKeys.delete(t);e.s.webMcpResolveControllers.delete(i),e.s.webMcpResolveControllers.size===0&&!e.s.abortController&&e.setStreaming(!1)}}async function ac(e,t){let n=t.agentMetadata?.executionId,r=t.toolCall?.name,i=t.toolCall?.id;if(!n){e.s.callbacks.onError?.(/* @__PURE__ */ Error(`WebMCP await missing executionId: dispatch left paused.`));return}if(!r)return;if(!i){let t=`${n}:__no_tool_id__:${r}`;if(e.s.webMcpInflightKeys.has(t)||e.s.webMcpResolvedKeys.has(t))return;e.s.webMcpInflightKeys.add(t);try{await oc(e,n,r,{isError:!0,content:[{type:`text`,text:`WebMCP await missing toolCall.id: cannot execute the page tool.`}]}),e.s.webMcpResolvedKeys.add(t)}catch(t){e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}finally{e.s.webMcpInflightKeys.delete(t)}return}let a=`${n}:${i}`;if(!(e.s.webMcpInflightKeys.has(a)||e.s.webMcpResolvedKeys.has(a)||tc(e,t)))return ic(e,n,[t])}async function oc(e,t,n,r,i){let a=Js(),o=await e.s.client.resumeFlow(t,{[n]:r},{signal:i?.signal,after:e.resumeAfter(t),assistantMessageId:a});if(!o.ok){let e=await o.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${o.status}`)}i?.onHttpOk?.(),o.body?await e.s.connectStream(o.body,{allowReentry:!0,assistantMessageId:a}):e.s.webMcpResolveControllers.size===0&&(e.setStreaming(!1),e.s.abortController=null)}var sc,cc,lc=W((()=>{Xs(),fi(),sc=e=>({isError:!0,content:[{type:`text`,text:e}]}),cc=(e,t=`WebMCP tool execution failed.`)=>e instanceof Error&&e.message?e.message:typeof e==`string`&&e?e:t}));lc(),Pt();const{setLoader:uc,load:dc,provide:fc,getSync:pc}=Nt({fallbackImport:()=>Promise.resolve().then(()=>(lc(),Zs))}),mc=dc,hc=fc,gc=pc;hc(Zs);function _c(e){if(!e)return yc;let t={...yc};for(let n of vc){let r=e[n];typeof r==`string`&&r.length>0&&(t[n]=r)}return t}var vc,yc,bc=W((()=>{vc=/* @__PURE__ */ `viewTitle.openHistoryLabel.openHistoryBusyLabel.newConversationLabel.expandLabel.collapseLabel.resizeLabel.showEarlierMessagesLabel.openConversationLoadingLabel.openConversationErrorTitle.openConversationRetryLabel.openConversationBackLabel.confirmCancelLabel.deleteConversationConfirmTitle.deleteConversationConfirm.deleteConversationConfirmLabel.clearHistoryConfirmTitle.clearHistoryConfirm.clearHistoryVerifiedConfirm.clearHistoryConfirmLabel.resetIdentityConfirmTitle.resetIdentityConfirm.resetIdentityConfirmLabel.conversationDeletedNotice.identityResetNotice.identityResetUnconfirmedNotice`.split(`.`),yc={viewTitle:`Messages`,openHistoryLabel:`Messages`,openHistoryBusyLabel:`Messages, available once the reply finishes`,newConversationLabel:`New conversation`,expandLabel:`Expand conversation list`,collapseLabel:`Collapse conversation list`,resizeLabel:`Resize conversation list`,showEarlierMessagesLabel:`Show earlier messages`,openConversationLoadingLabel:`Loading conversation`,openConversationErrorTitle:`Could not open the conversation.`,openConversationRetryLabel:`Try again`,openConversationBackLabel:`Back to messages`,confirmCancelLabel:`Cancel`,deleteConversationConfirmTitle:`Delete conversation`,deleteConversationConfirm:`Delete this conversation? This cannot be undone.`,deleteConversationConfirmLabel:`Delete`,clearHistoryConfirmTitle:`Delete all conversations`,clearHistoryConfirm:`Delete all conversations for this assistant on this browser? This cannot be undone.`,clearHistoryVerifiedConfirm:`Delete all conversations for this assistant and signed-in user? This cannot be undone.`,clearHistoryConfirmLabel:`Delete all`,resetIdentityConfirmTitle:`Forget this device`,resetIdentityConfirm:`Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.`,resetIdentityConfirmLabel:`Forget this device`,conversationDeletedNotice:`That conversation was deleted. You are now in a new conversation.`,identityResetNotice:`This device was forgotten.`,identityResetUnconfirmedNotice:`This device was cleared here, but the server could not confirm it.`}}));function xc(e){let{plugins:t,config:n}=e,r=!1,i=!1,a=!1,o=!1,s=null,c=[],l=()=>{for(let e of c.splice(0))try{e()}catch(e){Sc(`renderHistoryView cleanup`,e)}},u=(e,n)=>{for(let r of t){let t=r[e];if(t)try{let e=t(n);if(e)return e}catch(t){Sc(e,t)}}return null},d=()=>({presentation:e.getPresentation(),config:n}),f={header:t=>o?u(`renderHistoryHeader`,Object.freeze({...d(),returnSurface:e.getReturnSurface(),identityStatus:Cc(t.identityStatus),pendingAction:Tc(t.pendingAction),copy:Cc(t.copy),actions:Object.freeze({close:h.close,startNewConversation:h.startNewConversation}),defaultRenderer:t.defaultRenderer})):null,conversation:e=>o?u(`renderHistoryConversation`,Object.freeze({...d(),conversation:wc(e.conversation),active:e.active,pending:e.pending,open:e.open,requestDelete:e.requestDelete,defaultRenderer:e.defaultRenderer})):null,state:e=>o?u(`renderHistoryState`,Object.freeze({...d(),state:Cc(e.state),identityStatus:Cc(e.identityStatus),copy:Cc(e.copy),...e.retry?{retry:e.retry}:{},...e.startNewConversation?{startNewConversation:e.startNewConversation}:{},defaultRenderer:e.defaultRenderer})):null},p=t.flatMap(t=>(t.railSections??[]).map(t=>({...t,placement:t.placement??`above-conversations`,items:[],render:n=>t.render(Object.freeze({collapsed:n,presentation:e.getPresentation(),actions:h}))}))),m=e.createView({slots:f,renderDom:!1,onModelChange:()=>y(),railSections:p}),h=Object.freeze({...m.operations,close:e.close}),g=()=>(o=!0,m.setDomRenderEnabled(!0),m.element),_=t=>Object.freeze({conversations:Object.freeze(t.conversations.map(wc)),activeConversationId:t.activeConversationId,state:Cc(t.state),pendingAction:Tc(t.pendingAction),identityStatus:Cc(t.identityStatus),nextCursor:t.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:Cc(m.copy),actions:h,defaultRenderer:g,requestRender:()=>y(),onCleanup:e=>{c.push(e)}}),v=()=>{o=!1;let e=null;for(let n of t)if(n.renderHistoryView){try{e=n.renderHistoryView(_(m.getModel()))}catch(t){Sc(`renderHistoryView`,t),e=null}if(e)break}let n=!e||e.contains(m.element);return o=n,m.setDomRenderEnabled(n),e??m.element};function y(){if(!(!a||r||i)){i=!0;try{l();let t=v();if(t===s)return;let n=s;s=t,e.onElementChanged(t,n)}finally{i=!1}}}return a=!0,y(),{view:m,get element(){return s??m.element},requestRender:y,dispose:()=>{r=!0,l()}}}var Sc,Cc,wc,Tc,Ec=W((()=>{Sc=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},Cc=e=>Object.freeze({...e}),wc=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),Tc=e=>e?Cc(e):null})),Dc,Oc,kc,Ac,jc,Mc,Nc,Pc,Fc,Ic,Lc,Rc,zc=W((()=>{Dc=null,Oc=()=>{if(Dc!==null)return Dc;if(typeof navigator>`u`)return!1;let e=navigator.userAgentData?.platform??navigator.platform??``;return/mac|iphone|ipad|ipod/i.test(e)},kc=`ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space`,Ac=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},jc=e=>{let t=e.toLowerCase().split(`+`).map(e=>e.trim()),n=t.pop(),r={key:n,mod:!1,shift:!1,alt:!1};for(let n of t)if(n===`mod`||n===`cmd`||n===`ctrl`)r.mod=!0;else if(n===`shift`)r.shift=!0;else if(n===`alt`||n===`option`)r.alt=!0;else return Ac(`unknown modifier in`,e),null;return!r.mod||r.shift&&r.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Ac(`unsupported`,e),null):(n===`space`&&(r.key=` `),r)},Mc=e=>kc.split(` `).find(t=>t.toLowerCase()===e)??(e===` `?`Space`:e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),Nc=(e,t)=>{let n=jc(e);if(!n)return``;let r=Oc(),i=Mc(n.key);if(!t&&r)return`${n.alt?`⌥`:``}${n.shift?`⇧`:``}⌘${i}`;let a=[t?r?`Meta`:`Control`:`Ctrl`];return n.alt&&a.push(`Alt`),n.shift&&a.push(`Shift`),a.push(i),a.join(`+`)},Pc=e=>Nc(e,!1),Fc=e=>Nc(e,!0),Ic=(e,t)=>t.key?.toLowerCase()===e.key&&(Oc()?t.metaKey:t.ctrlKey)===e.mod&&!(Oc()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Lc=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`||e.isContentEditable},Rc=e=>{let t=/* @__PURE__ */ new Map,n=e?.ownerDocument??(typeof document<`u`?document:null),r=(t,n)=>{if((t.scope??`widget`)===`page`)return!0;if(!e)return!1;let r=n.composedPath?.();return r?.length?r.includes(e):e.contains(n.target)},i=e=>{if(e.isComposing||!t.size)return;let n=e.composedPath?.()[0]??e.target;for(let i of t.values())if(Ic(i.parsed,e)&&i.when?.()!==!1&&r(i,e)&&(i.allowInInput||!Lc(n))){e.preventDefault();try{i.run(e)}catch(e){Ac(`${i.id} threw on`,i.combo),console.warn(e)}return}};return n?.addEventListener(`keydown`,i),{register(e){let n=jc(e.combo);if(!n)return()=>{};let r=`${n.mod?`m`:``}${n.shift?`s`:``}${n.alt?`a`:``}${n.key}`,i=t.get(r);return i?(Ac(`${i.id} already owns`,e.combo),()=>{}):(t.set(r,{...e,parsed:n}),e.element?.setAttribute(`aria-keyshortcuts`,Fc(e.combo)),()=>{t.get(r)?.id===e.id&&t.delete(r),e.element?.removeAttribute(`aria-keyshortcuts`)})},destroy(){t.clear(),n?.removeEventListener(`keydown`,i)}}}}));function Bc(e){if(typeof e!=`string`||e===``)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Vc(e){return typeof e==`string`?e:void 0}function Hc(e){if(typeof e!=`object`||!e)return null;let t=e;switch(t.type){case`text`:return typeof t.text==`string`?Ro(t.text):null;case`image`:return typeof t.image==`string`?zo(t.image,{mimeType:Vc(t.mimeType),alt:Vc(t.alt)}):null;case`file`:return typeof t.data==`string`&&typeof t.mimeType==`string`&&typeof t.filename==`string`?Wo(t.data,t.mimeType,t.filename):null;case`audio`:return typeof t.audio==`string`?{type:`audio`,audio:t.audio,...Vc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case`video`:return typeof t.video==`string`?{type:`video`,video:t.video,...Vc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function Uc(e,t){let n=Bc(t),r=e.map(e=>Bc(e.timestamp)),i=Array(e.length),a=0;for(;a<r.length;){let e=r[a];if(e!==null){i[a]=e,a+=1;continue}let t=a;for(;t+1<r.length&&r[t+1]===null;)t+=1;let o=t-a+1,s=a>0?i[a-1]:null,c=t+1<r.length?r[t+1]:null,l=c!==null&&n!==null?Math.min(c,n):c??n;for(let e=0;e<o;e+=1)i[a+e]=l===null?s===null?Jc+e:s+e+1:l-(o-e);a=t+1}return i.map(e=>new Date(e).toISOString())}function Wc(e,t){let n=Uc(e,t?.beforeCreatedAt),r=[];return e.forEach((e,t)=>{if(typeof e?.id!=`string`||e.id===``||!qc.includes(e.role))return;let i=e.role,a=n[t];if(e.displayAvailable===!1)r.push({id:e.id,role:i,content:``,createdAt:a,agentMetadata:{historyDisplayUnavailable:!0}});else if(typeof e.displayContent==`string`)r.push({id:e.id,role:i,content:e.displayContent,createdAt:a});else if(typeof e.content==`string`)r.push({id:e.id,role:i,content:e.content,createdAt:a});else if(Array.isArray(e.content)){let t=e.content.map(Hc).filter(e=>e!==null),n=Fo(t);r.push({id:e.id,role:i,content:n||(Io(t)?`[Image]`:``),createdAt:a,...t.length>0&&{contentParts:t}})}else r.push({id:e.id,role:i,content:``,createdAt:a})}),r}function Gc(e){let t=e.content;if(typeof t!=`string`||t===``)return;let n=e.contentParts??e.llmContent??e.rawContent??t;if(typeof n!=`string`||n!==t)return t}function Kc(e,t){let n=/* @__PURE__ */ new Map;for(let t of e)n.set(t.id,t);for(let e of t)n.set(e.id,e);return[...n.values()].sort((e,t)=>{let n=new Date(e.createdAt).getTime(),r=new Date(t.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(r)&&n!==r)return n-r;let i=e.sequence??0,a=t.sequence??0;return i===a?e.id.localeCompare(t.id):i-a})}var qc,Jc,Yc=W((()=>{$o(),qc=[`user`,`assistant`,`system`],Jc=0}));function Xc(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let t=Qc.get(e.code)??`unavailable`;return new n(t,el(t),{...e.retryAfterSeconds===void 0?{}:{retryAfterSeconds:e.retryAfterSeconds}})}return new n(`unavailable`,el(`unavailable`))}function Zc(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,r=e.getIdentityProofConfigured()?[`browser`,`verified-user`]:[`browser`],i={scopes:r},a=e=>{if(!r.includes(e))throw new t(`unsupported_scope`,el(`unsupported_scope`))},o=async(t,n)=>{a(t);try{return await n()}catch(t){throw Xc(t,e.errors)}},s=t=>{let n=!1;return{conversationId:t.session.conversationId??``,conversationRevision:t.session.conversationRevision??``,async commit(){n||(n=!0,t.commit(),await e.onActivationCommitted(t.session))},discard(){n||(n=!0,t.discard())}}};return{capabilities:i,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(e){return n().subscribeHistoryIdentityStatus(e)},subscribeAvailability(e){return n().subscribeHistoryAvailability(e)},async list(e){return o(e.context.scope,async()=>{let t=await n().listConversations({...e.cursor?{cursor:e.cursor}:{},...e.limit===void 0?{}:{limit:e.limit},...e.targetId?{targetId:e.targetId}:{},scope:e.context.scope});return{items:t.data,nextCursor:t.nextCursor}})},async getPage(e,t){return o(t.context.scope,async()=>{let r=await n().getConversation(e,{...t.cursor?{messageCursor:t.cursor}:{},scope:t.context.scope}),i=Wc(r.messages,{...t.beforeCreatedAt?{beforeCreatedAt:t.beforeCreatedAt}:{}});return{summary:r.summary,messages:Kc([],i),conversationRevision:r.conversationRevision??``,nextCursor:r.nextMessageCursor}})},async prepareOpen(e,t){return o(t.context.scope,async()=>s(await n().prepareConversationSession(e)))},async prepareStartNew(e){return o(e.context.scope,async()=>s(await n().prepareNewConversationSession()))},async delete(e,t){await o(t.context.scope,()=>n().deleteConversation(e,{scope:t.context.scope}))},async deleteAll(e){return o(e.context.scope,()=>n().deleteAllConversations({...e.targetId===void 0?{}:{targetId:e.targetId},scope:e.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var Qc,$c,el,tl=W((()=>{Yc(),Qc=/* @__PURE__ */ new Map([[`not_found`,`not_found`],[`conversation_deleted`,`not_found`],[`rate_limited`,`rate_limited`],[`authentication_required`,`authentication_required`],[`invalid_identity_proof`,`authentication_required`],[`visitor_identity_mismatch`,`authentication_required`],[`visitor_required`,`authentication_required`],[`identity_provider_failed`,`identity_provider_failed`],[`proof_not_admitted`,`proof_not_admitted`],[`identity_contract_violation`,`proof_not_admitted`],[`unauthorized`,`authentication_failed`],[`visitor_token_missing`,`authentication_failed`],[`conversation_credential_missing`,`authentication_failed`]]),$c=/* @__PURE__ */ new Map([[`not_found`,`That conversation is no longer available.`],[`rate_limited`,`Too many history requests.`],[`authentication_failed`,`History access was not authorized.`],[`authentication_required`,`Sign in again to view account history.`],[`identity_provider_failed`,`The identity provider did not respond.`],[`proof_not_admitted`,`Account history is not available for this configuration.`],[`unsupported_scope`,`This history scope is not supported.`],[`unavailable`,`Conversation history is unavailable right now.`]]),el=e=>$c.get(e)??`Conversation history is unavailable right now.`})),nl=/* @__PURE__ */ Mt({createHistoryShell:()=>rl}),rl,il=W((()=>{bc(),Ec(),Y(),zc(),yi(),tl(),rl=e=>{let t=_c(e.config.features?.history?.copy),n=null,r=!1,i=null,a=null,o=`conversation`,s=null,c=null,l=null,u=null,d=0,f=null,p=null,m=null,h=`persona-history-${Math.random().toString(36).slice(2,8)}`,g=()=>e.historyFeatureEnabled()&&!!n&&!r,_=()=>{let t=e.session.getStatus();return e.isStreaming||t===`paused`||t===`resuming`},v=()=>{let t=e.config.features?.history?.scope;if(t)return t;let r=e.config.getIdentityProof?`verified-user`:`browser`,i=n?.capabilities.scopes;return!i||i.includes(r)?r:i[0]??r},y=()=>a?.scope??v(),b=()=>e.session.getClientSession()?.targetId??null,x=e=>`${e.state}:${`reason`in e?e.reason:``}`,S=t=>{let n=x(t);n!==u&&(u=n,e.eventBus.emit(`history:identityStatusChanged`,{status:t,timestamp:Date.now()}))},C=null,w=null,T=()=>{if(!e.historyFeatureEnabled())return null;let t=e.getHistoryProviderFactory();if(t)return t();let n=e.config.features?.history?.provider;return n?typeof n==`function`?(C!==n&&(C=n,w=n()),w):n:e.session.isClientTokenMode()?Zc({errors:e.historyErrors,client:e.session.getClient(),getIdentityProofConfigured:()=>typeof e.config.getIdentityProof==`function`,onActivationCommitted:t=>e.session.bindActivatedSession(t),getClient:()=>e.session.getClient()}):null},E=()=>{p?.(),p=null,m?.(),m=null,r=!1,n=T();let t={...e.historyInternals};n?t.historyProvider=n:delete t.historyProvider,e.historyInternals=t,e.session.setHistoryInternals(e.historyInternals),n&&(p=n.subscribeAvailability?.(e=>{r=!e,e||H({restoreFocus:!1}),Ut()})??null,m=n.subscribeIdentityStatus(e=>S(e)),u=x(n.getIdentityStatus()))},D=()=>{let t=e.config.features?.history?.presentation??`panel`;if(t===`panel`||t===`auto`&&e.launcherEnabled&&!e.isDockedMountMode(e.config))return`panel`;let n=e.artifactSplitRoot??e.container;return(n.getBoundingClientRect().width||n.clientWidth)>=720?`rail`:`panel`},O=(e,t)=>{t?(e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`inert`,``)):(e.removeAttribute(`aria-hidden`),e.removeAttribute(`inert`))},k=`data-persona-history-suppressed`,ee=null,te=null,ne=null,re=null,ie=null,ae=``,oe=()=>e.header===ie?ae:e.config.layout?.showHeader===!1?`none`:``,A=()=>e.historyPresentation===`panel`&&!!ne&&re===ne.element&&e.config.layout?.showHeader!==!1&&oe()!==`none`,j=()=>{for(let t of Array.from(e.header.children))t!==ee&&t.setAttribute(k,``)},se=()=>{for(let t of Array.from(e.container.querySelectorAll(`[${k}]`)))t.removeAttribute(k)},ce=()=>{let t=ne;if(!t)return;if(Array.from(e.header.children).some(e=>e!==ee&&!e.hasAttribute(k))){te&&te!==e.header&&(te.style.removeProperty(`min-height`),te=null);let t=e.header.offsetHeight;t>0&&(e.header.style.minHeight=`${t}px`,te=e.header)}ee||=q(`div`,`persona-history-header-host`),t.setHeaderPlacement(`external`);let n=t.getHeaderElement();n.parentNode!==ee&&ee.replaceChildren(n),ee.parentNode!==e.header&&e.header.appendChild(ee),j()},le=()=>{te&&=(te.style.removeProperty(`min-height`),null),ee&&(ne?.setHeaderPlacement(`inline`),ee.remove(),ee=null,se())},ue=null,de=()=>{ue&&(e.body.style.display=`none`,O(e.body,!0),e.footer.hidden=!0,O(e.footer,!0),A()?(ce(),e.header.style.display=oe(),O(e.header,!1)):(le(),e.header.style.display=`none`,O(e.header,!0)))};e.reapplyHistoryHostChrome=de;let fe=t=>{let n=e.body.style.display,r=e.footer.hidden,i=e.footer,a=e.header,o=e.header.style.display;ie=a,ae=o,ue=()=>{ue=null,le(),ie=null,e.body.style.display=n,O(e.body,!1),i.hidden=r,O(i,!1),e.footer!==i&&(e.footer.hidden=!1,O(e.footer,!1)),a.style.display=o,O(a,!1),e.header!==a&&(e.header.style.display=e.config.layout?.showHeader===!1?`none`:``,O(e.header,!1))},e.footer.parentNode?.insertBefore(t,e.footer),de()},pe=null,M=null,me=null,he=null,ge=()=>[e.header,e.panelElements.closeButtonWrapper,e.panelElements.clearChatButtonWrapper,e.body,e.footer],_e=()=>e.config.features?.history?.rail?.collapsible!==!1,ve=()=>e.config.features?.history?.rail?.side===`right`?`right`:`left`,ye=e=>Math.min(400,Math.max(200,Math.round(e))),N=()=>e.config.features?.history?.rail?.resizable===!0,be,P=()=>{if(be===void 0&&(be=null,e.config.persistState!==!1))try{let t=Number(window.localStorage.getItem(`${e.currentKeyPrefix()}rail-width`));t&&(be=t)}catch{}return be},xe=()=>ye(P()??e.config.features?.history?.rail?.width??260),Se=t=>{if(be=t,e.config.persistState!==!1)try{window.localStorage.setItem(`${e.currentKeyPrefix()}rail-width`,String(t))}catch{}},Ce=()=>_e()&&e.config.features?.history?.rail?.collapsedBehavior===`overlay`,we=!1,Te=e=>{let t=q(`img`);return t.src=e,t.alt=``,t.setAttribute(`aria-hidden`,`true`),t},Ee=()=>{let t=e.config.features?.history?.rail?.brand;if(!t)return;let n=!1,r;return i=>{if(t.render)try{return t.render({collapsed:i})??null}catch(e){return n||(n=!0,console.warn(`[persona] history rail brand threw`,e)),null}return r===void 0&&(r=t.iconUrl?Te(t.iconUrl):t.icon?e.renderLucideIcon(t.icon,20):null),r?r.cloneNode(!0):null}},De=()=>e.config.features?.history?.rail?.sections?.map(t=>{let n=!1,r=e=>{n||(n=!0,console.warn(`[persona] history rail section threw`,t.id,e))};return{id:t.id,title:t.title,placement:t.placement??`above-conversations`,items:t.items.map(t=>{let n;return{id:t.id,label:t.label,badge:t.badge,iconNode:()=>{if(n!==void 0)return n;try{n=t.renderIcon?t.renderIcon()??null:t.iconUrl?Te(t.iconUrl):t.icon?e.renderLucideIcon(t.icon,20):null}catch(e){r(e),n=null}return n},onSelect:()=>{try{t.onSelect()}catch(e){r(e)}}}})}})??[],Oe=e=>{let t=De();for(let n of e)t.some(e=>e.id===n.id)?console.warn(`[persona] duplicate history rail section id`,n.id):t.push(n);return t.length?t:void 0},ke=null,Ae=()=>`${e.currentKeyPrefix()}rail-collapsed`,je=()=>{if(ke===null&&(ke=e.config.features?.history?.rail?.defaultCollapsed===!0,e.config.persistState!==!1))try{let e=window.localStorage.getItem(Ae());e&&(ke=e===`1`)}catch{}return ke},Me=t=>{if(ke=t,e.config.persistState!==!1)try{window.localStorage.setItem(Ae(),t?`1`:`0`)}catch{}},Ne=()=>e.historyPresentation===`rail`&&_e()&&!Ce()&&je(),Pe=()=>{},Fe=()=>{Ce()?Pe():(Me(!je()),i?.view.setCollapsed(Ne()),e.applyRailChrome(),e.repinAnchoredMessage())},Ie=()=>{let t=e.config.features?.history?.rail?.collapseShortcut;return!t||!jc(t)?null:{combo:t,hint:Pc(t),aria:Fc(t)}},Le=`var(--persona-history-overlay-margin,8px)`,Re=null,ze=null,Be=0,Ve=null,He=null,Ue=!1,We=0,Ge=()=>window.matchMedia?.(`(pointer: coarse)`).matches===!0,Ke=()=>g()&&Ce()&&(e.historyPresentation??D())===`rail`,qe=()=>e.historyVisible&&!we,Je=()=>{He!==null&&clearTimeout(He),He=null},Ye=()=>{e.loadHistoryView().catch(()=>{})},Xe=()=>{Je(),we&&(He=setTimeout(()=>{He=null,!Ue&&we&&(Ve?.contains(document.activeElement)||H({restoreFocus:!1}))},300))},Ze=(e,t)=>{let n=Ve?.getBoundingClientRect();if(!n)return!1;let r=Re?.getBoundingClientRect(),i=r?Math.min(r.top,n.top):n.top;return e>=n.left&&e<=n.right&&t>=i&&t<=n.bottom||!!r&&e>=r.left&&e<=r.right&&t>=r.top&&t<=r.bottom},Qe=e=>{we&&(Ue=Ze(e.clientX,e.clientY),Ue?Je():He===null&&Xe())},$e=t=>{!e.historyVisible&&Ke()&&(we=!0,mt({invoker:Re,keyboard:t?.keyboard===!0}).then(()=>{e.historyVisible?!Ue&&document.activeElement!==Re&&H():we=!1}))},et=()=>{let e=re?.querySelector(`[data-persona-history-focus="collapse"]`);e&&(e.setAttribute(`aria-label`,we?t.expandLabel:t.collapseLabel),e.setAttribute(`aria-expanded`,we?`false`:`true`))},tt=()=>{Me(!1);let t=i;if(!we||!t){mt({invoker:Re});return}let n=document.activeElement===Re;we=!1,ct(),t.element.remove(),ut(t.element),et(),n&&pt(),e.repinAnchoredMessage(),Ut()},nt=()=>{Me(!0),H()};Pe=()=>{!e.historyVisible||we?tt():nt()};let F=()=>{let n=Ie(),r=e.createHeaderIconButton({ariaLabel:t.expandLabel,iconName:`panel-left`,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`,extraClassName:`persona-rail-trigger`,tooltip:!1,attrs:{"data-persona-rail-trigger":``,"aria-controls":h,...n?{"aria-keyshortcuts":n.aria}:{}}}),i=r.button;i.addEventListener(`mouseenter`,()=>{Ue=!0,Je(),!(Ge()||Date.now()<We)&&$e()}),i.addEventListener(`mouseleave`,()=>{Ue=!1,We=0,Xe()}),i.addEventListener(`focus`,()=>{e.historyVisible||Ye()}),i.addEventListener(`click`,t=>{g()&&(t.detail!==0&&Ge()&&!e.historyVisible?$e():tt())}),Re=i,ze=r.wrapper},I=()=>{if(ze&&!ze.isConnected&&(ze=null,Re=null),!Ke()){ze?.remove(),ze=null,Re=null;return}Re||F();let n=ze,r=Re;if(!n||!r)return;let i=ve()===`right`?null:e.header.firstChild;(i??e.header.lastChild)!==n&&e.header.insertBefore(n,i),n.style.display=qe()||Be>0?`none`:``,r.setAttribute(`aria-label`,t.expandLabel),r.setAttribute(`aria-expanded`,e.historyVisible?`true`:`false`),Ve&&e.applyRailChrome()},rt=e=>{if(!we)return;let t=e.target;t instanceof Node&&(Ve?.contains(t)||ze?.contains(t)||t instanceof Element&&t.closest(`.persona-dropdown-menu,[role="alertdialog"]`)||H({restoreFocus:!1}))};document.addEventListener(`pointerdown`,rt,!0),e.destroyCallbacks.push(()=>{document.removeEventListener(`pointerdown`,rt,!0),document.removeEventListener(`pointermove`,Qe),L?.(),Je()});let it=null,L=null,R=t=>{Se(ye(t)),e.applyRailChrome(),e.repinAnchoredMessage()},z=()=>{let t=q(`div`,`persona-rail-resizer`);return t.tabIndex=0,t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-valuemin`,`200`),t.setAttribute(`aria-valuemax`,`400`),t.addEventListener(`pointerdown`,n=>{let r=M;if(!r||n.button!==0)return;n.preventDefault(),L?.();let i=n.clientX,a=r.getBoundingClientRect().width||xe(),o=ve()===`right`?-1:1,s=a,c=e.mount.ownerDocument;r.style.transition=`none`;let l=e=>{s=ye(a+o*(e.clientX-i)),r.style.flex=`0 0 ${s}px`,t.setAttribute(`aria-valuenow`,String(s))},u=()=>{L=null,c.removeEventListener(`pointermove`,l),c.removeEventListener(`pointerup`,u),c.removeEventListener(`pointercancel`,u),r.style.removeProperty(`transition`);try{t.releasePointerCapture(n.pointerId)}catch{}R(s)};L=u,c.addEventListener(`pointermove`,l),c.addEventListener(`pointerup`,u),c.addEventListener(`pointercancel`,u);try{t.setPointerCapture(n.pointerId)}catch{}}),t.addEventListener(`keydown`,e=>{let t=ve()===`right`?-16:16,n=xe(),r=e.key===`ArrowRight`?n+t:e.key===`ArrowLeft`?n-t:e.key===`Home`?200:e.key===`End`?400:null;r!==null&&(e.preventDefault(),R(r))}),t},at=(e,n)=>{if(!N()||Ne()){L?.(),it?.remove();return}let r=it??z();it=r,r.setAttribute(`aria-label`,t.resizeLabel),r.setAttribute(`aria-valuenow`,String(xe())),r.nextElementSibling!==n&&e.insertBefore(r,n)};e.applyRailChrome=()=>{i?.view.setRailSide(ve());let t=ve()===`right`,n=Ve;if(n){let r=Re?Re.getBoundingClientRect().bottom-e.container.getBoundingClientRect().top:0;n.style.top=`calc(${Math.max(0,Math.round(r))}px + ${Le})`,n.style.width=`${xe()}px`,n.style.left=t?``:Le,n.style.right=t?Le:``}let r=M,a=pe,o=me;if(!r||!a||!o)return;r.style.flex=`0 0 ${Ne()?52:xe()}px`;let s=`1px solid var(--persona-divider,#e5e7eb)`;r.style.borderRight=t?``:s,r.style.borderLeft=t?s:``;let c=t?o:r;a.firstElementChild!==c&&a.append(c,t?r:o),at(a,t?r:o)};let ot=t=>{if(he&&M){he.replaceWith(t),he=null,e.applyRailChrome();return}let n=q(`div`,`persona-history-rail-shell`);n.style.cssText=`display:flex;flex-direction:row;flex:1 1 auto;min-height:0`;let r=q(`div`,`persona-history-rail-conversation`);r.style.cssText=`display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative`;let i=q(`div`,`persona-history-rail-host`);i.style.cssText=`display:flex;min-height:0;overflow:hidden`,e.container.insertBefore(n,e.header.parentNode===e.container?e.header:e.body);for(let t of ge())t?.parentNode===e.container&&r.appendChild(t);n.append(i,r),i.appendChild(t),pe=n,M=i,me=r,e.applyRailChrome()},st=()=>{if(pe)return;let t=q(`div`,`persona-history-rail-placeholder`);t.style.cssText=`flex:1 1 auto;min-height:0`,he=t,ot(t),e.repinAnchoredMessage()},B=()=>{he&&(ct(),e.repinAnchoredMessage())},V=t=>{let n=q(`div`,`persona-history-rail-overlay`);n.style.cssText=`position:absolute;bottom:${Le};display:flex;overflow:hidden;z-index:${vi-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,e.container.style.position=`relative`,e.container.appendChild(n),n.appendChild(t),document.addEventListener(`pointermove`,Qe),Ve=n,e.applyRailChrome(),et()},ct=()=>{ue?.(),Ve&&=(Ue&&(We=Date.now()+150),document.removeEventListener(`pointermove`,Qe),Ve.remove(),null);let t=pe;if(t){L?.();for(let n of ge())n&&t.contains(n)&&e.container.insertBefore(n,t);t.remove(),pe=null,M=null,me=null,he=null}},lt=e=>{re=e,e.id=h,e.style.flex=`1 1 auto`,e.style.minHeight=`0`},ut=t=>{lt(t),(e.historyPresentation!==`rail`||we)&&B(),e.historyPresentation===`rail`?we?V(t):ot(t):fe(t)},dt=()=>{if(I(),Bt(),!e.historyVisible||!i)return;let t=D();if(t===e.historyPresentation)return;let n=document.activeElement,r=n instanceof HTMLElement&&(i.element.contains(n)||ee?.contains(n)===!0)?n:null;ct(),i.element.remove(),i.view.setHeaderPlacement(`inline`),e.historyPresentation=t,i.view.setPresentation(t),i.view.setCollapsed(Ne()),i.requestRender(),i.element.isConnected||ut(i.element),r?.isConnected?r.focus():pt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),Ut()},ft=(e,t)=>ee?.querySelector(t)??e.querySelector(t),pt=()=>{let e=i?.element??re;if(!e)return;let t=ft(e,`[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]`);if(t){t.focus();return}let n=ft(e,`.persona-history-title`)??e;n.tabIndex=-1,n.focus()},mt=async r=>{if(!g()||e.historyVisible)return;let l=n;if(!l)return;if(!we&&Ke()&&je()){I();return}ht();let u=++d;o=r?.returnSurface??`conversation`,s=r?.invoker??c;let f=Ke()&&!we;f&&(Be+=1,I(),st());let p;try{p=await e.loadHistoryView()}catch{e.announceHistory(t.openHistoryLabel),f&&(--Be,u===d&&(B(),I()));return}if(f&&--Be,u!==d||e.historyVisible)return;a={scope:v()},e.historyPresentation=D(),e.historyVisible=!0;let m=e.historyPresentation===`panel`&&e.config.layout?.showHeader!==!1&&e.header.style.display!==`none`?`external`:`inline`,h=e.config.features?.history?.rowAvatar,_=Ie(),y=_?{hint:_.hint,aria:_.aria}:null,x={provider:l,context:a,targetId:b(),presentation:e.historyPresentation,collapsible:_e(),collapsed:Ne(),railSide:ve(),renderRailHeader:e.config.features?.history?.rail?.renderHeader,railBrand:Ee(),onToggleCollapse:Fe,...y?{collapseShortcut:y}:{},headerPlacement:m,showScopeStatus:e.config.features?.history?.showScopeStatus!==!1,showDelete:e.config.features?.history?.showDelete!==!1,showDeleteAll:e.config.features?.history?.showDeleteAll!==!1,...e.config.features?.history?.listActions?.length?{listActions:e.config.features.history.listActions}:{},rowAvatar:h===!1?!1:typeof h==`string`?h:e.config.launcher?.iconUrl,activeConversationId:e.session.getActiveConversationId(),...e.config.features?.history?.grouping?{grouping:e.config.features.history.grouping}:{},...e.config.features?.history?.copy?{copy:e.config.features.history.copy}:{},...e.config.features?.history?.pageSize===void 0?{}:{pageSize:e.config.features.history.pageSize},onSelect:e=>Dt(e,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:t=>e.setActiveConversationSummary(t),attachTooltip:e.attachTooltip,onStartNew:()=>Ot({focusComposer:!0}),onClose:()=>H(),onRequestDeleteConversation:e=>Pt(e),onRequestClearHistory:()=>Ft(),...l.resetDevice?{onRequestResetIdentity:()=>It()}:{}};i=xc({plugins:e.plugins,config:e.config,getPresentation:()=>e.historyPresentation??`panel`,getReturnSurface:()=>o,close:()=>H(),createView:({slots:t,renderDom:n,onModelChange:r,railSections:i})=>(ne=p.createHistoryView({...x,railSections:Oe(i),slots:t,renderDom:n,onModelChange:r,onAnnounce:e.announceHistory}),ne),onElementChanged:(e,t)=>{if(!t?.isConnected)return ut(e);lt(e),t.replaceWith(e),de()}}),i.view.setNewConversationRequired(e.historySessionState.recovery===`new_conversation_required`),r?.focus!==!1&&(e.historyPresentation!==`rail`||r?.keyboard===!0)&&pt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),Ut(),e.eventBus.emit(`history:opened`,{presentation:e.historyPresentation,returnSurface:o,timestamp:Date.now()})},ht=()=>{},H=t=>{if(!e.historyVisible)return;d+=1;let n=o,r=s,l=i,u=t?.restoreFocus!==!1;e.historyVisible=!1;let f=!1,p=null,m=()=>{if(!f){if(f=!0,ht=()=>{},p!==null&&clearTimeout(p),we=!1,Je(),ct(),l?.dispose(),l?.view.destroy(),l?.element.remove(),i===l&&(i=null,ne=null,re=null,e.historyPresentation=null,a=null,s=null),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),Ut(),u){let t=r??c;t?.isConnected?t.focus():e.maybeFocusInput()}e.eventBus.emit(`history:closed`,{returnSurface:n,timestamp:Date.now()})}},h=l&&l.element===l.view.element?l.view.playExit():null;h?(ht=m,p=setTimeout(m,250),h.then(m)):m()},gt=t=>{if(t.key===`Escape`&&e.historyVisible&&i){if(e.historyPresentation===`rail`){let e=t.target;if(!(e instanceof Node)||!(i.element.contains(e)||we&&ze?.contains(e)===!0))return}t.preventDefault(),t.stopPropagation(),H()}};e.container.addEventListener(`keydown`,gt),e.destroyCallbacks.push(()=>e.container.removeEventListener(`keydown`,gt));let _t=0,vt=null,yt=()=>{vt&&clearTimeout(vt),vt=null};e.destroyCallbacks.push(yt);let bt=()=>{yt();let t=e.conversationOpenPendingEl;t&&(e.conversationOpenTakeover=!0,t.hidden=!1,e.messagesWrapper.style.display=`none`,e.updateWelcome())},xt=()=>{_t+=1,yt(),e.conversationOpenPendingEl&&(e.conversationOpenPendingEl.remove(),e.conversationOpenPendingEl=null,e.conversationOpenTakeover=!1,e.messagesWrapper.style.removeProperty(`display`),O(e.footer,!1),e.updateWelcome())},St=()=>{try{if(window.matchMedia?.(`(prefers-reduced-motion: reduce)`)?.matches)return;e.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:`ease-out`})}catch{}},Ct=(e,t)=>J(`div`,{className:tr(`persona-conversation-loading-bubble`,t&&`persona-conversation-loading-bubble--trailing`),attrs:{"aria-hidden":`true`},style:{width:e}}),wt=()=>J(`div`,{className:`persona-conversation-loading-body`},Ct(`58%`,!1),Ct(`72%`,!0),Ct(`44%`,!1)),Tt=t=>{e.conversationOpenPendingEl?.remove(),e.conversationOpenPendingEl=t,t.hidden=!e.conversationOpenTakeover,e.body.insertBefore(t,e.messagesWrapper),yt(),e.conversationOpenTakeover||(vt=setTimeout(bt,250)),O(e.footer,!0)},U=()=>{let n={config:e.config,streaming:!1,location:`conversation-open`,defaultRenderer:wt},r=null,i=e.plugins.find(e=>e.renderLoadingIndicator);i?.renderLoadingIndicator&&(r=i.renderLoadingIndicator(n)),r===null&&e.config.loadingIndicator?.render&&(r=e.config.loadingIndicator.render(n)),Tt(J(`div`,{className:`persona-conversation-loading`,attrs:{role:`status`,"aria-label":t.openConversationLoadingLabel}},r??wt()))},Et=n=>{let r=()=>{Dt(n,{focusComposer:!0}).catch(()=>{})},i=g()?()=>{xt(),mt()}:void 0,a=(e,t)=>{let n=J(`button`,{className:`persona-conversation-loading-error-action`,attrs:{type:`button`},text:e});return n.addEventListener(`click`,t),n},o=()=>J(`div`,{className:`persona-conversation-loading-error-body`},J(`p`,{className:`persona-conversation-loading-error-title`,text:t.openConversationErrorTitle}),J(`div`,{className:`persona-conversation-loading-error-actions`},a(t.openConversationRetryLabel,r),i?a(t.openConversationBackLabel,i):null)),s=Object.freeze({conversationId:n,config:e.config,copy:Object.freeze({title:t.openConversationErrorTitle,retryLabel:t.openConversationRetryLabel,backLabel:t.openConversationBackLabel}),retry:r,...i?{back:i}:{},defaultRenderer:o}),c=null;for(let t of e.plugins)if(t.renderHistoryOpenError){try{c=t.renderHistoryOpenError(s)}catch(e){console.warn(`[persona] renderHistoryOpenError threw`,e),c=null}if(c)break}Tt(J(`div`,{className:`persona-conversation-loading-error`,attrs:{role:`alert`}},c??o())),bt()};e.eventBus.on(`history:closed`,()=>{e.conversationOpenPendingEl&&O(e.footer,!0)});let Dt=async(t,{focusComposer:n=!1}={})=>{let r=y(),a=!!i;i?.view.setActiveConversationId(t),xt();let o=_t;U(),e.historyVisible&&(e.historyPresentation===`panel`||we)&&H({restoreFocus:!1}),e.suppressScrollSend=!0;try{await e.session.openConversation(t,{scope:r})}catch(e){throw o===_t&&Et(t),e}finally{e.suppressScrollSend=!1}o===_t&&(xt(),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.restoreScrollPosition()||e.jumpToBottomInstant(),St(),Rt(),a||e.setActiveConversationSummary(null),e.eventBus.emit(`history:conversationOpened`,{conversationId:t,title:e.activeConversationTitle,scope:r,timestamp:Date.now()}),n&&e.maybeFocusInput())},Ot=async({focusComposer:t=!1}={})=>{xt(),await e.session.startNewConversation({scope:y()}),e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.jumpToBottomInstant(),Rt();let n=e.session.getActiveConversationId();i?.view.setActiveConversationId(n),e.eventBus.emit(`history:conversationStarted`,{conversationId:n,timestamp:Date.now()}),e.historyVisible&&(e.historyPresentation===`panel`||we)&&H({restoreFocus:!1}),t&&e.maybeFocusInput()},kt=async(t,n)=>{let r=await e.session.updateConversation(t,{...n,...n.title===void 0?{}:{title:n.title.trim()}});return i?.view.applyConversationSummary(r),!i&&t===e.session.getActiveConversationId()&&e.setActiveConversationSummary(r),r},At=async t=>{let n=y(),r=e.session.getActiveConversationId()===t;await e.session.deleteConversation(t,{scope:n}),i?.view.removeConversationSummary(t),r&&(e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Rt()),e.eventBus.emit(`history:conversationDeleted`,{conversationId:t,scope:n,wasActive:r,timestamp:Date.now()})},jt=async t=>{let n=t?.scope??y(),r=t?.allTargets?null:t?.targetId??b(),i=await e.session.clearConversationHistory({...r?{targetId:r}:{},scope:n});return e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Rt(),e.eventBus.emit(`history:cleared`,{deleted:i.deleted,scope:n,targetId:r,timestamp:Date.now()}),i},W=async()=>{if(!n?.resetDevice)throw Error(`[Persona] resetHistoryIdentity() requires a history provider that can reset this device`);let r=!1;try{r=(await e.session.resetHistoryDevice()).remoteRevocationConfirmed}finally{e.setActiveConversationSummary(null),e.session.clearArtifacts(),e.messageCache.clear(),e.lastAppliedMessages=null,e.config.clearStoredSessionId?.(),e.config.clearStoredConversationId?.(),e.persistentMetadata={},e.actionManager.syncFromMetadata();let t=e.storageAdapter;t?.clear&&e.runStorageMutation(()=>t.clear(),`[AgentWidget] Failed to clear storage adapter:`),e.resetAnchorState(),e.resumeAutoScroll(),Rt(),H({restoreFocus:!1}),e.maybeFocusInput(),e.open||e.launcherSurfaceInstance?.launcher.element.focus()}return e.announceHistory(r?t.identityResetNotice:t.identityResetUnconfirmedNotice),e.eventBus.emit(`history:identityReset`,{remoteRevocationConfirmed:r,timestamp:Date.now()}),{remoteRevocationConfirmed:r}},Mt=()=>e.artifactSplitRoot?e.panel:e.container,Nt=async t=>{let n=await e.loadHistoryView().catch(()=>null);return typeof n?.showHistoryConfirm==`function`?n.showHistoryConfirm(t):window.confirm(`${t.title}\n\n${t.description}`)},Pt=async e=>await Nt({host:Mt(),title:t.deleteConversationConfirmTitle,description:t.deleteConversationConfirm,confirmLabel:t.deleteConversationConfirmLabel,cancelLabel:t.confirmCancelLabel})?(await At(e),`deleted`):`cancelled`,Ft=async()=>{let e=y()===`verified-user`;return await Nt({host:Mt(),title:t.clearHistoryConfirmTitle,description:e?t.clearHistoryVerifiedConfirm:t.clearHistoryConfirm,confirmLabel:t.clearHistoryConfirmLabel,cancelLabel:t.confirmCancelLabel})?(await jt(),`cleared`):`cancelled`},It=async()=>{if(!await Nt({host:Mt(),title:t.resetIdentityConfirmTitle,description:t.resetIdentityConfirm,confirmLabel:t.resetIdentityConfirmLabel,cancelLabel:t.confirmCancelLabel}))return{outcome:`cancelled`};let{remoteRevocationConfirmed:e}=await W();return{outcome:`reset`,remoteRevocationConfirmed:e}},Lt=q(`button`,`persona-history-earlier`);Lt.type=`button`,Lt.textContent=t.showEarlierMessagesLabel,Lt.setAttribute(`data-persona-history-earlier`,``),Object.assign(Lt.style,{alignSelf:`center`,minHeight:`44px`,padding:`0 16px`,borderRadius:`999px`,border:`1px solid var(--persona-border, rgba(0,0,0,0.12))`,background:`transparent`,color:`inherit`,font:`inherit`,cursor:`pointer`,flexShrink:`0`});let Rt=()=>{g()&&e.historySessionState.nextMessageCursor&&e.session.getActiveConversationId()?(Lt.textContent=t.showEarlierMessagesLabel,Lt.parentNode!==e.body&&e.body.insertBefore(Lt,e.body.firstChild)):Lt.remove()};Lt.addEventListener(`click`,()=>{let t=e.session.getActiveConversationId(),n=e.historySessionState.nextMessageCursor;if(!t||!n||Lt.disabled)return;Lt.disabled=!0;let r=e.body.scrollHeight,i=e.body.scrollTop;e.session.loadOlderMessages(t,n,{scope:y()}).then(()=>{e.body.scrollTop=i+(e.body.scrollHeight-r),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Lt.disabled=!1,Rt()})});let zt=()=>{let n=e.createHeaderIconButton({ariaLabel:t.openHistoryLabel,iconName:`history`,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`,extraClassName:`persona-history-toggle`,attrs:{"data-persona-history-toggle":``}});return n.button.addEventListener(`click`,t=>{g()&&!_()&&(e.historyVisible?H():mt({invoker:n.button,keyboard:t.detail===0}))}),n},Bt=()=>{if(!g()){l?.remove(),c=null,l=null;return}if(l&&!l.isConnected&&(c=null,l=null),!c&&e.header){let t=zt();c=t.button,l=t.wrapper;let n=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;n?.parentNode&&e.header.contains(n)?n.parentNode.insertBefore(l,n):e.header.appendChild(l)}if(!c||!l)return;let n=Ke()||e.historyVisible&&e.historyPresentation===`rail`;if(l.style.display=n?`none`:``,n){document.activeElement===c&&pt();return}let r=_();c.disabled=r,c.setAttribute(`aria-disabled`,r?`true`:`false`);let i=r?t.openHistoryBusyLabel:t.openHistoryLabel;c.setAttribute(`aria-label`,i),(e.config.features?.history?.presentation??`panel`)===`panel`?(c.removeAttribute(`aria-expanded`),c.removeAttribute(`aria-controls`)):(c.setAttribute(`aria-expanded`,e.historyVisible?`true`:`false`),c.setAttribute(`aria-controls`,h))},Vt=!1,Ht=()=>{let n=e.panelElements.clearChatButton;n&&(g()?(Vt||=(f=n.getAttribute(`aria-label`)??``,!0),n.setAttribute(`aria-label`,t.newConversationLabel),n.removeAttribute(`title`)):Vt&&(Vt=!1,f&&n.setAttribute(`aria-label`,f)))},Ut=()=>{t=_c(e.config.features?.history?.copy),Bt(),I(),Ht(),Rt()};return e.historyChromeSync=Ut,E(),Ut(),e.destroyCallbacks.push(()=>{p?.(),m?.(),d+=1,ht(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:g,historyScope:v,installHistoryProvider:E,syncHistoryChromeImpl:Ut,syncHistoryPresentation:dt,syncEarlierMessagesPill:Rt,openHistory:mt,closeHistory:H,openHistoryConversation:Dt,startNewConversation:Ot,updateHistoryConversation:kt,deleteHistoryConversation:At,requestDeleteConversation:Pt,clearConversationHistory:jt,resetHistoryIdentity:W,railCollapseShortcut:Ie,railCollapsible:_e,railTriggerApplies:Ke,railOverlayMode:Ce,toggleRailCollapsed:Fe,toggleRailPinned:()=>Pe(),get historyProvider(){return n},get historySurface(){return i},get railShell(){return pe},get railHost(){return M},get railColumn(){return me}}}}));il(),Pt();const{setLoader:al,load:ol,provide:sl,getSync:cl}=Nt({fallbackImport:()=>Promise.resolve().then(()=>(il(),nl))}),ll=ol,ul=sl,dl=cl;ul(nl),En();function fl(e){return e.toolType===`webmcp`&&!e.executionId}function pl(e){let t=e.approval,n=t?.status===`pending`&&fl(t),r=!1,i=t=>!t.name||!wn(t.name)||(r=!0,!(t.status!==`complete`||e.agentMetadata?.awaitingLocalTool===!0&&t.result===void 0&&t.success===void 0))?t:{...t,status:`complete`,interrupted:!0,success:!1,error:`The chat restarted and this browser tool was interrupted. Request a fresh proposal to try again.`,approvalStatus:t.approvalStatus===`pending`?`timeout`:t.approvalStatus,startedAt:t.completedAt===void 0?void 0:t.startedAt},a=e.toolCall?i(e.toolCall):void 0,o=e.tools?.map(i);return{...e,streaming:r||n?!1:e.streaming,...n?{approval:{...t,status:`timeout`,interrupted:!0}}:{},...a?{toolCall:a}:{},...o?{tools:o}:{},...r&&e.agentMetadata?.awaitingLocalTool?{agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1}}:{}}}Y(),Yt();const ml=[`persona-w-full`,`persona-rounded-2xl`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-text-persona-primary`,`persona-shadow-sm`,`persona-overflow-hidden`,`persona-px-0`,`persona-py-0`],hl=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),gl=(e,t)=>{let n=q(`div`,[`persona-message-bubble`,e,...ml].join(` `));return n.id=`bubble-${t}`,n.setAttribute(`data-message-id`,t),n},_l=e=>{let t=q(`button`,e.expandable?`persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none`:`persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none`);return t.type=`button`,e.expandable&&(t.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),t.setAttribute(`data-expand-header`,`true`)),t.setAttribute(`data-bubble-type`,e.bubbleType),t},vl=(e,t,n)=>{e.innerHTML=``;let r=Jt(t?w:x,16,n,2);r?e.appendChild(r):e.textContent=t?`Hide`:`Show`},yl=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let r=q(`div`,`persona-flex persona-items-center`);vl(r,n.expanded,n.iconColor);let i=q(`div`,n.metaGap?`persona-flex persona-items-center persona-gap-2 persona-ml-auto`:`persona-flex persona-items-center persona-ml-auto`);return i.append(r),e.append(t,i),r},bl=e=>{let t=q(`div`,`persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted`);if(t.setAttribute(`data-persona-collapsed-preview`,e.previewKind),t.style.display=`none`,t.style.whiteSpace=`pre-wrap`,!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let n=e.renderPreview?.();hl(t,n)||(t.textContent=e.previewText),t.style.display=``}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},xl=e=>{e.header.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),e.toggleIcon&&vl(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?``:`none`,e.collapsedPreview.style.display=e.expanded?`none`:e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?``:`none`},Sl=(e,t,n)=>{let r=n.stateSet.has(e),i=t.querySelector(`button[data-expand-header="true"]`),a=t.querySelector(`.persona-border-t`),o=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!i||!a)return;i.setAttribute(`aria-expanded`,r?`true`:`false`);let s=i.querySelector(`.persona-ml-auto`)?.querySelector(`:scope > .persona-flex.persona-items-center`);s&&vl(s,r,n.iconColor),a.style.display=r?``:`none`,o&&(o.style.display=r?`none`:o.textContent||o.childNodes.length?``:`none`)};Yt(),No(),Y(),mn();function Cl(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return{...e,features:{...e?.features,[n]:{...t===`tool`?To:Eo,...e?.future?.v5Defaults===!0?jo.features?.[n]:{},...e?.features?.[n]}}}}function wl(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return e?.features?.[n]?.variant??(e?.future?.v5Defaults?`row`:`card`)}function Tl(e){let t=Math.max(0,Math.floor((e??0)/1e3));return t<1?`a moment`:t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function El(e,t,n,r){if(wl(n,r)!==`row`)return e;e.className=`persona-message-bubble persona-${r}-bubble persona-activity-row`,e.dataset.activityKind=r,r===`tool`&&n.toolCall?.shadow===void 0&&(e.style.boxShadow=`var(--persona-tool-bubble-shadow, none)`);let i=e.querySelector(`:scope > button`);if(!i)return e;i.className=`persona-activity-header`;let a=r===`tool`?t.toolCall:t.reasoning,o=a?.status!==`complete`,s=t.approval?.status??t.toolCall?.approvalStatus,c=t.toolCall?.interrupted?`interrupted`:s===`denied`?`denied`:s===`pending`?`awaiting-approval`:t.toolCall?.success===!1?`error`:o?a?.status===`pending`?`pending`:`running`:`done`;e.dataset.activityState=c;let l=q(`span`,`persona-activity-icon`);l.dataset.activityIcon=c;let u={pending:`circle`,running:`loader-circle`,done:`check`,error:`x`,denied:`x`,interrupted:`x`,"awaiting-approval":`clock`},d=r===`reasoning`?n.features?.reasoningDisplay?.iconName:void 0,f=d?K(d,16,`currentColor`,2):c===`pending`?Jt(T,16,`currentColor`,2):c===`awaiting-approval`?Jt(ee,16,`currentColor`,2):K(u[c],16,`currentColor`,2);f&&l.appendChild(f),i.querySelector(`.persona-reasoning-header-icon`)?.remove();let p=r===`tool`?`toolCallDisplay`:`reasoningDisplay`,m=n.features?.[p]?.iconVisibility??(n.future?.v5Defaults?`active`:`always`);if((m===`always`||m===`active`&&c!==`done`)&&i.prepend(l),r===`tool`&&a){let e=q(`span`,`persona-activity-duration`);o&&a.startedAt&&e.setAttribute(`data-tool-elapsed`,String(a.startedAt));let n=(r===`tool`?t.toolCall?.duration:void 0)??a.durationMs??(a.completedAt!==void 0&&a.startedAt!==void 0?a.completedAt-a.startedAt:void 0);e.textContent=n===void 0?``:Tl(n),i.appendChild(e)}i.querySelector(`:scope > div:not(.persona-ml-auto)`)?.classList.add(`persona-activity-label`),i.querySelector(`.persona-ml-auto`)?.classList.add(`persona-activity-chevron`);let h=e.querySelector(`:scope > .persona-border-t`);return h?.classList.add(`persona-activity-body`),h&&(h.id=`activity-details-${t.id}`,i.setAttribute(`aria-controls`,h.id)),e}function Dl(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map,a=e=>{clearTimeout(i.get(e)),i.delete(e)};return{observe(a,o,s,c={}){let l=o===`tool`?a.toolCall:a.reasoning;if(l&&!n.has(a.id)&&(!t.has(a.id)&&l.status!==`complete`&&l.chunks?.some(Boolean)&&(t.add(a.id),c.autoExpand!==!1&&s.add(a.id)),t.has(a.id)&&l.status===`complete`&&!r.has(a.id))){if(r.add(a.id),c.autoCollapseDelay===!1)return;i.set(a.id,setTimeout(()=>{i.delete(a.id),s.delete(a.id),e(a.id,o)},c.autoCollapseDelay??1e3))}},manual(e){n.add(e),a(e)},prune(e){for(let i of/* @__PURE__ */ new Set([...t,...n,...r]))e.has(i)||(a(i),t.delete(i),n.delete(i),r.delete(i))},clear(){for(let e of i.keys())a(e);t.clear(),n.clear(),r.clear()}}}function Ol(e,t,n,r){let i=q(`div`,``);i.id=`bubble-${e.id}`,i.dataset.messageId=e.id;let a=q(`button`,``);a.type=`button`,a.dataset.expandHeader=`true`,a.dataset.bubbleType=`tool`,a.setAttribute(`aria-expanded`,String(n));let o=q(`div`,``);typeof r==`string`?o.textContent=r:o.appendChild(r),yl(a,o,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||`currentColor`,metaGap:!0});let s=q(`div`,`persona-border-t`);return s.id=`activity-details-${e.id}`,s.style.display=n?``:`none`,a.setAttribute(`aria-controls`,s.id),i.append(a,s),El(i,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:`row`}}},`tool`),i.dataset.personaToolGroup=`true`,t.features?.toolCallDisplay?.loadingAnimation===`shimmer`&&(i.dataset.activityGroupShimmer=`true`),{bubble:i,body:s}}function kl(e,t){let n=e.voiceRecognition,r=t.voiceRecognition;return n?.enabled===!0!=(r?.enabled===!0)||n?.provider?.type!==r?.provider?.type||n?.provider?.custom!==r?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==r?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(r?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function Al(e){return e?.type===`runtype`||e?.type===`custom`}const jl=()=>typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window);function Ml(e){try{if(e?.type===`custom`&&e.custom){let t=e.custom,n=typeof t==`function`?t():t;return!!n&&typeof n.startListening==`function`}return e?.type===`runtype`&&e.runtype?!0:jl()}catch{return!1}}const Nl=e=>{if(!e)return;let t={},n=e;if(n.heading){let e=n.heading;t.heading=(t,n,r)=>e({type:`heading`,raw:r,depth:n,text:t,tokens:[]})}if(n.code){let e=n.code;t.code=(t,n,r)=>e({type:`code`,raw:``,text:t,lang:n,escaped:r})}if(n.blockquote){let e=n.blockquote;t.blockquote=t=>e({type:`blockquote`,raw:``,text:t,tokens:[]})}if(n.table){let e=n.table;t.table=(t,n)=>e({type:`table`,raw:``,header:[],rows:[],align:[],headerHtml:t,bodyHtml:n})}if(n.link){let e=n.link;t.link=(t,n,r)=>e({type:`link`,raw:``,href:t,title:n??null,text:r,tokens:[]})}if(n.image){let e=n.image;t.image=(t,n,r)=>e({type:`image`,raw:``,href:t,title:n??null,text:r})}if(n.list){let e=n.list;t.list=(t,n,r)=>e({type:`list`,raw:``,ordered:n,start:r,loose:!1,items:[],itemsHtml:t})}if(n.listitem){let e=n.listitem;t.listitem=(t,n,r)=>e({type:`list_item`,raw:``,task:n,checked:r,loose:!1,text:t,tokens:[]})}if(n.paragraph){let e=n.paragraph;t.paragraph=t=>e({type:`paragraph`,raw:``,text:t,tokens:[]})}if(n.codespan){let e=n.codespan;t.codespan=t=>e({type:`codespan`,raw:``,text:t})}if(n.strong){let e=n.strong;t.strong=t=>e({type:`strong`,raw:``,text:t,tokens:[]})}if(n.em){let e=n.em;t.em=t=>e({type:`em`,raw:``,text:t,tokens:[]})}if(n.del){let e=n.del;t.del=t=>e({type:`del`,raw:``,text:t,tokens:[]})}if(n.html){let e=n.html;t.html=t=>e({type:`html`,raw:t,text:t})}if(n.text){let e=n.text;t.text=t=>e({type:`text`,raw:t,text:t})}if(n.checkbox){let e=n.checkbox;t.checkbox=t=>e({checked:t})}return n.hr&&(t.hr=n.hr),n.br&&(t.br=n.br),t},Pl=e=>{let t=null;return n=>{let r=Kt();if(!r)return Rl(n);if(!t){let{Marked:n}=r,i=e?.markedOptions;t=new n({gfm:i?.gfm??!0,breaks:i?.breaks??!0,pedantic:i?.pedantic,silent:i?.silent});let a=Nl(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},Fl=e=>e?Pl({markedOptions:e.options,renderer:e.renderer}):Pl(),Il=Pl(),Ll=e=>Il(e),Rl=e=>e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`),zl=e=>e.replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`),Bl=e=>`%%FORM_PLACEHOLDER_${e}%%`,Vl=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,n)=>{try{let e=JSON.parse(n.trim());if(e&&typeof e==`object`&&e.component===`form`&&e.type){let n=Bl(t.length);return t.push({token:n,type:String(e.type)}),n}}catch{return e}return e}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,n)=>{let r=Bl(t.length);return t.push({token:r,type:n}),r}),n},Hl=e=>{let t=Fl(e);return e=>{let n=[],r=Vl(e,n),i=t(r);return n.forEach(({token:e,type:t})=>{let n=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`g`),r=`<div class="persona-form-directive" data-tv-form="${zl(t)}"></div>`;i=i.replace(n,r)}),i}},Ul=e=>{let t=[],n=Vl(e,t),r=Ll(n);return t.forEach(({token:e,type:t})=>{let n=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`g`),i=`<div class="persona-form-directive" data-tv-form="${zl(t)}"></div>`;r=r.replace(n,i)}),r},Wl={ALLOWED_TAGS:/* @__PURE__ */ `h1.h2.h3.h4.h5.h6.p.br.hr.div.span.ul.ol.li.dl.dt.dd.strong.em.b.i.u.s.del.ins.mark.small.sub.sup.abbr.kbd.var.samp.code.a.img.blockquote.pre.details.summary.table.thead.tbody.tfoot.tr.th.td.caption.colgroup.col.input.label.select.option.textarea.button`.split(`.`),ALLOWED_ATTR:/* @__PURE__ */ `href.src.alt.title.target.rel.loading.width.height.colspan.rowspan.scope.class.id.type.name.value.placeholder.disabled.checked.for.aria-label.aria-hidden.aria-expanded.role.tabindex.data-tv-form.data-message-id.data-persona-component-directive.data-preserve-animation.data-persona-instance`.split(`.`)},Gl=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Kl=()=>{let e=null;return t=>{let n=Kt();if(!n)return Rl(t);if(!e){let{DOMPurify:t}=n;e=t(typeof window<`u`?window:void 0),e.addHook(`uponSanitizeAttribute`,(e,t)=>{if(t.attrName===`src`||t.attrName===`href`){let e=t.attrValue;e.toLowerCase().startsWith(`data:`)&&!Gl.test(e)&&(t.attrValue=``,t.keepAttr=!1)}})}return e.sanitize(t,Wl)}},ql=e=>e===!1?null:typeof e==`function`?e:Kl(),Jl=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Yl=e=>e.includes(`|`),Xl=e=>{let t=e.trim();return t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&(t=t.slice(0,-1)),t.split(`|`).map(e=>e.trim())},Zl=e=>`| ${e.join(` | `)} |`,Ql=e=>`| ${Array.from({length:e},()=>`---`).join(` | `)} |`,$l=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>``)),eu=e=>{if(!e||!e.includes(`|`))return e;let t=e.split(`
|
|
12
|
+
`),n=!1;for(let e=0;e<t.length-1;e++){let r=t[e],i=t[e+1];if(!Yl(r)||Jl.test(r)||!Jl.test(i))continue;let a=Xl(r).length;if(a<1)continue;let o=Ql(a);t[e+1]!==o&&(t[e+1]=o,n=!0);let s=e+2;for(;s<t.length;s++){let e=t[s];if(e.trim()===``||!Yl(e))break;let r=Zl($l(Xl(e),a));t[s]!==r&&(t[s]=r,n=!0)}e=s-1}return n?t.join(`
|
|
13
|
+
`):e},tu=`var(--persona-md-table-scroll-fade, 24px)`,nu=/* @__PURE__ */ new WeakSet;function ru(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(`persona-table-scroll`))return;let t=document.createElement(`div`);t.className=`persona-table-scroll`,e.replaceWith(t),t.appendChild(e)})}function iu(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute(`data-persona-scroll-x`);return}e.setAttribute(`data-persona-scroll-x`,``);let n=getComputedStyle(e).direction===`rtl`?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty(`--persona-fade-l`,n<=1?`0px`:tu),e.style.setProperty(`--persona-fade-r`,r<=1?`0px`:tu)}function au(e){nu.has(e)||(nu.add(e),e.addEventListener(`scroll`,e=>{let t=e.target;t?.classList?.contains(`persona-table-scroll`)&&iu(t)},!0)),e.querySelectorAll(`.persona-table-scroll`).forEach(iu)}Pt();const{setLoader:ou,load:su}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/webmcp-runtime`)}),cu=su;Pt();const{setLoader:lu,load:uu}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/voice-client-tools`)}),du=uu;function fu(e){return e.startsWith(`agent_`)?{kind:`agentId`,agentId:e}:e.startsWith(`flow_`)?{kind:`flowId`,flowId:e}:null}function pu(e,t){let n=e.trim();if(!n)throw Error("[Persona] `target` is empty.");let r=n.indexOf(`:`);if(r>0){let e=n.slice(0,r),i=n.slice(r+1);if(e===`runtype`){let e=fu(i);if(e)return e;throw Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let a=t?.[e];if(!a)throw Error(`[Persona] No target provider registered for "${e}". Add a \`targetProviders.${e}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:`payload`,payload:a(i).payload}}let i=fu(n);if(i)return i;let a=t?.default;if(a)return{kind:`payload`,payload:a(n).payload};throw Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}const mu=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),hu=e=>typeof e==`object`&&!!e&&!Array.isArray(e),gu=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=mu(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:hu(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},_u=(e,t)=>{let n=[],r=[],i=[],a=``,o,s=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let c of e){let e=gu(c);if(e){let t=c.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==o)&&s(),r.length===0&&(a=c.createdAt,o=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let l=t(c);l&&(s(),n.push(l))}return s(),n},vu=e=>e.localOnly===!0||e.role===`assistant`&&typeof e.id==`string`&&e.id.startsWith(`reconnect-failed-`);En(),Xs(),Z(),er(),Ri(),Yc(),yi();var yu=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryClientError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};const bu=e=>`reason`in e?e.reason:void 0,xu=(e,t)=>e instanceof yu&&e.code===t,Su=e=>e.voiceCaption||vu(e)?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),Cu=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),wu=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function Tu(e){switch(e){case`json`:return Zn;case`regex-json`:return Xn;case`xml`:return $n;default:return Yn}}var Eu=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;constructor(e={},t={}){if(this.config=e,this.historyInternals=t,this.#l=null,this.clientSession=null,this.#u=null,this.#d=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null,this.#p=!1,this.#m=!1,this.#h=!1,this.#g=null,this.#_=/* @__PURE__ */ new Set,this.#v=/* @__PURE__ */ new Set,this.webMcpBridge=null,this.#y=null,this.#H=null,this.#W=null,e.target&&(e.agentId||e.flowId||e.agent))throw Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??`https://api.runtype.com/v1/dispatch`,this.#t={"Content-Type":`application/json`,"X-Persona-Version":Li,...e.headers},this.debug=!!e.debug,this.#n=e.streamParser??Tu(e.parserType),this.#r=e.contextProviders??[],this.#i=e.requestMiddleware,this.#a=e.customFetch,this.#o=e.parseSSEEvent,this.#s=e.getHeaders,e.webmcp?.enabled===!0&&(this.#y=this.#x(e.webmcp))}#x(e){return cu().then(t=>{let n=new t.WebMcpBridge(e,{recordToolDisplayTitles:bn,getToolDisplayTitle:xn,loadPolyfill:Tn});return this.#b!==void 0&&n.setConfirmHandler(this.#b),this.webMcpBridge=n,n}).catch(e=>(this.#y=null,console.warn(`[Persona] Failed to load the WebMCP runtime chunk`,e),null))}#S(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled===!0?(this.#y||=this.#x(this.config.webmcp),this.#y):Promise.resolve(null)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#c=e}setWebMcpConfirmHandler(e){this.#b=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}getVoiceClientTools(){if(this.config.webmcp?.enabled!==!0)return null;let e=()=>this.#S(),t={open:async e=>(await du()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await(await e())?.snapshotForDispatch()??[];return{tools:t,fingerprint:hn(t)}},onChange:t=>{let n=null,r=!1;return e().then(e=>{e&&!r&&(n=e.watchToolChanges(t))}),()=>{r=!0,n?.()}},execute:async(t,n,r)=>{let i=await e();return i?i.executeVoiceToolCall(t,n,r):{status:`failed`,error:{message:`WebMCP runtime failed to load.`}}}};return t}executeWebMcpToolCall(e,t,n){return this.config.webmcp?.enabled===!0?this.#S().then(r=>r?r.executeToolCall(e,t,n):{isError:!0,content:[{type:`text`,text:`WebMCP runtime failed to load.`}]}):null}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#C(){let{agentId:e,flowId:t,target:n,targetProviders:r}=this.config;if(!n)return{agentId:e,flowId:t};let i=pu(n,r);return i.kind===`agentId`?{agentId:i.agentId}:i.kind===`flowId`?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.#C().agentId)}#w(){return this.config.apiUrl?.replace(/\/+$/,``).replace(/\/v1\/dispatch$/,``)||`https://api.runtype.com`}#T(e){return`${this.#w()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),n=!1;for(;;){let r=t.conversationId,i=await this.readVisitorToken();if(t.durableRecovery?.enabled!==!0||!r||!i)throw new yu(`visitor_token_missing`,`Durable recovery is not enabled for this client session`);let a=`${this.#w()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,o=new URLSearchParams({sessionId:t.sessionId,after:e.after}),s=await fetch(`${a}?${o}`,{method:`GET`,headers:{"X-Persona-Version":Li,"X-Visitor-Token":i},signal:e.signal});if(s.status===401&&!n){n=!0;let e=await pa();t=await e.recoverFromUnauthorized(this.#G(),await e.readErrorCode(this.#G(),s),null,!0)}else{if(!s.ok)throw await(await pa()).historyErrorFor(this.#G(),s,!0);return s}}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#u||e&&/* @__PURE__ */ new Date<e.expiresAt||this.#d===e?null:(this.#d=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw Error(`initSession() only available in client token mode`);if(this.clientSession&&/* @__PURE__ */ new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#u)return this.#u;let e=this.#u=this.#N().then(t=>this.#u===e?(this.clientSession=t,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#u===e&&(this.#u=null)});return e}#E(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#p}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#D(){if(!this.#p){this.#j({state:`unavailable`,reason:`history_disabled`}),this.#p=!0,!this.#m&&typeof console<`u`&&(this.#m=!0,console.warn(`[Persona] Visitor history is disabled for this surface; continuing without it.`)),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#v])e(!1)}}getHistoryIdentityStatus(){return this.#g??this.#O()}subscribeHistoryIdentityStatus(e){return this.#_.add(e),()=>{this.#_.delete(e)}}subscribeHistoryAvailability(e){return this.#v.add(e),this.#p&&e(!1),()=>{this.#v.delete(e)}}#O(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#p?{state:`unavailable`,reason:`history_disabled`}:this.#k():{state:`unavailable`,reason:`ineligible_mode`}}#k(){let e=this.#g;return e?.state===`browser_only`?e:this.#A()}#A(){return this.config.features?.history?.scope===`browser`?{state:`browser_only`,reason:`configured_browser_scope`}:this.config.getIdentityProof?{state:`browser_only`,reason:`proof_unavailable_before_binding`}:{state:`browser_only`,reason:`no_identity_provider`}}#j(e){let t=this.getHistoryIdentityStatus(),n=t.state===e.state&&bu(t)===bu(e);if(this.#g=e,!n){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#_])t(e)}}async#M(e){let t=this.#E()&&!e.omitVisitorFields,n=!e.omitVisitorFields,r=null;(t||n)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let i=this.#C(),a=i.agentId??i.flowId,o=t||e.durableResume?e.conversationId:void 0,s={token:this.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(t||n)&&r?{visitorToken:r}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...o?{conversationId:o}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let c=await fetch(this.#T(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":Li},body:JSON.stringify(s),signal:e.signal});if(!c.ok){let n=await c.json().catch(()=>({error:`Session initialization failed`}));if(t&&c.status===403&&n.error===`visitor_history_disabled`){if(this.#D(),o)throw new yu(`history_disabled`,`Visitor history is disabled for this surface`);return this.#M({...e,omitVisitorFields:!0})}throw c.status===403&&n.error===`durable_recovery_disabled`?new yu(`history_disabled`,`Durable recovery is disabled for this surface`):(t||e.durableResume)&&c.status===401&&n.error===`visitor_required`?new yu(`visitor_required`,`Visitor credential no longer resolves`):o&&c.status===404?new yu(`not_found`,`Conversation not found`):c.status===401?Error(`Invalid client token: ${n.hint||n.error}`):c.status===403?Error(`Origin not allowed: ${n.hint||n.error}`):Error(n.error||`Failed to initialize session`)}let l=await c.json();return l.visitor?.token&&await this.historyInternals.visitorStore?.set(l.visitor.token),{sessionId:l.sessionId,expiresAt:new Date(l.expiresAt),flow:l.flow,...l.conversationId?{conversationId:l.conversationId}:{},...l.targetId?{targetId:l.targetId}:{},...l.conversationRevision?{conversationRevision:l.conversationRevision}:{},...l.durableRecovery?{durableRecovery:l.durableRecovery}:{},...l.visitor?{visitor:l.visitor}:{},config:{welcomeMessage:l.config.welcomeMessage,placeholder:l.config.placeholder,theme:l.config.theme}}}async#N(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,t=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#E()&&!t)return this.#P(e,!1);let n=await this.readVisitorToken();if(e&&n)try{let n=await this.#M({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#R(n,e,!1)}catch(n){if(!xu(n,`not_found`)&&!xu(n,`visitor_required`)&&!xu(n,`history_disabled`))throw n;return t&&this.historyInternals.setStoredResumableHandle?.(null),this.#P(e,!0)}return this.#P(e,!1)}async#P(e,t){let n=this.historyInternals.visitorStore;return n&&!await this.readVisitorToken()?n.withFirstInitLock(()=>this.#F(e,t)):this.#F(e,t)}async#F(e,t){let n=this.config.getStoredSessionId?.()||null,r=await this.#M({storedSessionId:n}),i=await this.#L(r);return this.#R(i,e,t)}async#I(e){let t=this.config.getStoredSessionId?.()||null,n=this.config.getStoredConversationId?.()||null,r=await this.#M({storedSessionId:t,identityProof:e}),i=this.#R(r,n,!1);return this.clientSession=i,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint(),i}async#L(e){if(!e.visitor?.token||this.#h||!this.#E()&&e.durableRecovery?.enabled!==!0)return e;this.#h=!0;try{return await this.#M({storedSessionId:e.sessionId})}catch{return e}finally{this.#h=!1}}#R(e,t,n){let r=e.conversationId;return r&&t&&(n||r!==t)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#z(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#d=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw Error(`prepareConversationSession() only available in client token mode`);if(!this.#E())throw new yu(`history_disabled`,`Visitor history is disabled for this surface`);await this.historyInternals.historyBootstrapReady;let n=t?.proof??null;if(!await this.readVisitorToken()&&!n)throw new yu(`conversation_credential_missing`,`Reopening a conversation requires a stored visitor token or an identity proof`);let r=await this.#M({conversationId:e,identityProof:n});return this.#z(r)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error(`prepareNewConversationSession() only available in client token mode`);await this.historyInternals.historyBootstrapReady;let e=await this.#M({});return this.#z(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#E()&&this.#j(this.#A())}clearClientSession(){this.clientSession=null,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null}#B(){return`${this.#w()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw Error(`sendFeedback() only available in client token mode`);if(!this.getClientSession())throw Error(`No active session. Please initialize session first.`);if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let t={...e,...this.config.clientToken&&{token:this.config.clientToken}},n=await fetch(this.#B(),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":Li},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:`Feedback submission failed`}));throw n.status===401?(this.clientSession=null,this.#d=!1,this.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async submitMessageFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`csat`,rating:e,comment:t})}async submitNPSFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`nps`,rating:e,comment:t})}async#V(e){e?.throwIfAborted();let t=this.config.identityProvider;if(t===void 0)return;let n=this.config.getIdentityProof;if(!t.trim()||!n)throw Error(`Chat identity requires identityProvider and getIdentityProof.`);let r,i;try{let t=Promise.resolve().then(()=>n());r=e?await Promise.race([t,new Promise((t,n)=>{i=()=>n(e.reason),e.addEventListener(`abort`,i,{once:!0}),e.aborted&&i()})]):await t}catch{throw e?.throwIfAborted(),Error(`The identity proof provider failed.`)}finally{i&&e?.removeEventListener(`abort`,i)}if(typeof r!=`string`||!r.trim())throw Error(`A fresh identity proof is required to send this message.`);return{provider:t,token:r}}#H;#U(){let e=this;return this.#H??={get config(){return e.config},headers:this.#t,getHeaders:this.#s,debug:this.debug,clientApiBase:()=>e.#w(),getClientApiUrl:t=>e.#T(t),getWebMcpBridge:()=>e.#S(),sendWithClientToolsDiff:(t,n,r,i)=>e.#Y(t,n,r,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#W;#G(){let e=this;return this.#W??={HistoryClientError:yu,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#w(),setHistoryIdentityStatus:t=>e.#j(t),browserOnlyStatus:()=>e.#k(),derivedBrowserOnly:()=>e.#A(),reinitWithProof:t=>e.#I(t),isHistoryCapable:()=>e.#E(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await pa()).listConversations(this.#G(),e)}async getConversation(e,t){return(await pa()).getConversation(this.#G(),e,t)}async finalizeDisplayProjections(e,t){return(await pa()).finalizeDisplayProjections(this.#G(),e,t)}async deleteConversation(e,t){return(await pa()).deleteConversation(this.#G(),e,t)}async deleteAllConversations(e){return(await pa()).deleteAllConversations(this.#G(),e)}async resetVisitor(){return(await pa()).resetVisitor(this.#G())}async dispatch(e,t){return e.signal?.throwIfAborted(),Ni().catch(()=>{}),this.isClientTokenMode()?this.#K(e,t):this.isAgentMode()?this.#J(e,t):this.#q(e,t)}async#K(e,t){let n=Ys();this.#l=n;let r=()=>this.#l===n,i=e=>{r()&&t(e)};t({type:`status`,status:`connecting`});try{let t=()=>{if(e.signal?.throwIfAborted(),!r())throw new DOMException(`Turn superseded`,`AbortError`)},a=this.clientSession??await this.initSession();t();let o=async()=>{t();let n=a,r=n.durableRecovery?.enabled===!0;if(r&&(!n.conversationId||!await this.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);t();let i=await this.#M({...r||this.#E()?{conversationId:n.conversationId,durableResume:r}:{storedSessionId:n.sessionId},signal:e.signal});if(t(),n.conversationId&&i.conversationId!==n.conversationId||r&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);a=this.#R(i,n.conversationId??null,!1),this.clientSession=a,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(a)};Date.now()>=a.expiresAt.getTime()-6e4&&await o();let s=await this.#te(e.messages),c=s.metadata?Object.fromEntries(Object.entries(s.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,l=this.#E(),u={sessionId:a.sessionId,messages:e.messages.filter(Su).map(e=>{let t=l?Gc(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...c&&Object.keys(c).length>0&&{metadata:c},...s.inputs&&Object.keys(s.inputs).length>0&&{inputs:s.inputs},...s.context&&{context:s.context},turnId:n,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},d=async()=>{t();let n=a.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return t(),this.#Y(a.sessionId,s.clientTools,async r=>{t();let i=await this.#V(e.signal);t();let o={...u,sessionId:a.sessionId,...r,...i&&{identityProof:i}};return this.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...o,...i&&{identityProof:{provider:i.provider,token:`[REDACTED]`}}}),fetch(this.#T(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":Li,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(o),signal:e.signal})})},f=await d();if(t(),f.response.status===401){let e=await f.response.clone().json().catch(()=>null);t(),e?.error===`Session not found or expired`&&(await o(),f=await d(),t())}let{response:p,commit:m}=f;if(!p.ok){let e=await p.json().catch(()=>({error:`Chat request failed`}));if(p.status===401&&e.error===`invalid_identity_proof`){let e=new yu(`invalid_identity_proof`,`The identity proof was rejected`);throw i({type:`error`,error:e}),e}if(p.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw i({type:`error`,error:e}),e}if(p.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw i({type:`error`,error:t}),t}if(p.status===410&&e.error===`conversation_deleted`){let e=new yu(`conversation_deleted`,`This conversation was deleted`);throw i({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw i({type:`error`,error:t}),t}if(!p.body){let e=/* @__PURE__ */ Error(`No response body received`);throw i({type:`error`,error:e}),e}m(),i({type:`status`,status:`connected`});try{await this.#ne(p.body,i,e.assistantMessageId)}finally{i({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof yu)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&i({type:`error`,error:t}),t}}async#q(e,t){t({type:`status`,status:`connecting`});let n=await this.#te(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t)}finally{t({type:`status`,status:`idle`})}}async#J(e,t){t({type:`status`,status:`connecting`});let n=await this.#ee(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t,e.assistantMessageId)}finally{t({type:`status`,status:`idle`})}}async processStream(e,t,n,r){t({type:`status`,status:`connected`});try{await this.#ne(e,t,n,r)}finally{t({type:`status`,status:`idle`})}}async resolveApproval(e,t,n){return(await Ni()).resolveApproval(this.#U(),e,t,n)}async#Y(e,t,n,r){let i=!!(t&&t.length>0),a=i?hn(t):void 0,o=this.clientToolsFingerprintSessionId===e,s=i&&o&&this.lastSentClientToolsFingerprint===a,c=!i&&r?.emptyMeansReplace===!0&&this.#f===e,l=!1,u;for(let e=0;u=await n({...i&&(l||!s)&&t?{clientTools:t}:{},...c?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&e===0&&i&&(await u.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)l=!0,this.lastSentClientToolsFingerprint=null;return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,i?this.#f=e:c&&(this.#f=null)}}}async resumeFlow(e,t,n){return(await Ni()).resumeFlow(this.#U(),e,t,n)}#X(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#Z(e){let t={};this.#r.length&&await Promise.all(this.#r.map(async n=>{try{let r=await n({messages:e,config:this.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#X(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#Q(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#$(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}async#ee(e,t){let n=this.#C().agentId;if(!this.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=_u(Cu(e),e=>Su(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?wu(e):null),i=this.#Q(t),a={agent:this.#$(this.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.config.agentOptions}};i&&(a.composerOptions=i);let o=[...hi(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let s=await this.#Z(e);return s&&(a.context=s),a}async#te(e,t){let n=_u(Cu(e),e=>Su(e)?wu(e):null),r=this.#C(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...hi(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#Z(e);o&&(i.context=o);let s=this.#Q(t);if(s&&(i.composerOptions=s),this.#i)try{let e=await this.#i({payload:{...i},config:this.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}async#ne(e,t,n,r){let{streamResponse:i}=Fi()??await Ni();return i({config:()=>this.config,createStreamParser:this.#n,parseSSEEvent:this.#o,onSSEEvent:(e,t)=>this.#c?.(e,t)},e,t,n,r)}},Du=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryProviderError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};function Ou(e){return e instanceof Du}const ku=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Au=(e,t)=>{let n=/* @__PURE__ */ new Set;return(Array.isArray(e)?e:[]).flatMap(e=>{if(!ku(e))return[];let{toolCallId:r,name:i}=e;if(typeof r!=`string`||!r||typeof i!=`string`||!i||n.has(r))return[];n.add(r);let a=ku(e.arguments)?e.arguments:{},o=e.result??null;return[{id:`voice-tool-${r}`,role:`assistant`,variant:`tool`,content:``,createdAt:t,streaming:!1,toolCall:{id:r,name:i,status:`complete`,args:a,result:o},agentMetadata:{clientToolAnswer:{toolCallId:r,toolName:i,args:a,result:o}}}]})};function ju(e){let t=0;for(let n of e.split(`
|
|
14
|
+
`)){let e=/^ {0,3}(`+)/.exec(n);e&&e[1].length>t&&(t=e[1].length)}return t}function Mu(e,t){let n="`".repeat(Math.max(3,ju(t)+1));return`${n}${e}\n${t}\n${n}`}$o();const Nu=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:`quoted-text`;function Pu(e){let t=e?.text?.trim()??``;return t?Mu(Nu(e),t):``}function Fu(e){let t=Pu(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[Ro(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
|
|
15
15
|
|
|
16
|
-
`)}:{}}function
|
|
16
|
+
`)}:{}}function Iu(e,t=140){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Lu(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1||e[n].role!==`user`)return null;let r=n+1;for(;r<e.length&&e[r].role!==`user`;)r+=1;return{start:n,end:r}}function Ru(e,t){let n=e.findIndex(e=>e.id===t);if(n<=0)return null;for(let t=n-1;t>=0;--t)if(e[t].role===`user`)return e[t].id;return null}function zu(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role===`user`||n.streaming)return null;if(!(n.role!==`assistant`||n.variant))return Ru(e,n.id)?n.id:null}return null}function Bu(e){return e.role!==`user`||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||e.rawContent!==void 0||e.llmContent!==void 0&&e.llmContent!==e.content||e.quote?!1:typeof e.content==`string`&&e.content.length>0}function Vu(e){for(let t of[`Microsoft Jenny Online (Natural) - English (United States)`,`Microsoft Aria Online (Natural) - English (United States)`,`Microsoft Guy Online (Natural) - English (United States)`,`Google US English`,`Google UK English Female`,`Ava (Premium)`,`Evan (Enhanced)`,`Samantha (Enhanced)`,`Samantha`,`Daniel`,`Karen`,`Microsoft David Desktop - English (United States)`,`Microsoft Zira Desktop - English (United States)`]){let n=e.find(e=>e.name===t);if(n)return n}return e.find(e=>e.lang.startsWith(`en`))??e[0]}var Hu=class e{constructor(e={}){this.options=e,this.id=`browser`,this.supportsPause=!0}static isSupported(){return typeof window<`u`&&`speechSynthesis`in window}speak(t,n){if(!e.isSupported()){n.onError?.(/* @__PURE__ */ Error(`Web Speech API is unavailable`));return}let r=window.speechSynthesis;r.cancel();let i=new SpeechSynthesisUtterance(t.text),a=r.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(i.voice=e)}else a.length>0&&(i.voice=this.options.pickVoice?this.options.pickVoice(a):Vu(a));t.rate!==void 0&&(i.rate=t.rate),t.pitch!==void 0&&(i.pitch=t.pitch),i.onend=()=>n.onEnd?.(),i.onerror=e=>{let t=e.error;t===`canceled`||t===`interrupted`?n.onEnd?.():n.onError?.(Error(t||`Speech synthesis failed`))},setTimeout(()=>{r.speak(i),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},Uu=class{#e=null;#t=null;#n=`idle`;#r=/* @__PURE__ */ new Set;#i=0;#a;constructor(e){this.#a=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#t===e?this.#n:`idle`}activeMessageId(){return this.#t}onChange(e){return this.#r.add(e),()=>this.#r.delete(e)}toggle(e,t){if(this.#t===e){if(this.#n===`playing`){this.#e?.supportsPause?(this.#e.pause(),this.#o(e,`paused`)):this.stop();return}if(this.#n===`paused`){this.#e?.resume(),this.#o(e,`playing`);return}if(this.#n===`loading`){this.stop();return}}this.play(e,t)}async play(e,t){let n=++this.#i;this.#e?.stop(),this.#o(e,`loading`);try{if(!this.#e){let e=await this.#a();if(n!==this.#i)return;if(!e){this.#o(null,`idle`);return}this.#e=e}this.#e.speak(t,{onStart:()=>{n===this.#i&&this.#o(e,`playing`)},onEnd:()=>{n===this.#i&&this.#o(null,`idle`)},onError:()=>{n===this.#i&&this.#o(null,`idle`)}})}catch{n===this.#i&&this.#o(null,`idle`)}}stop(){this.#i++,this.#e?.stop(),this.#o(null,`idle`)}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#r.clear()}#o(e,t){this.#t=t===`idle`?null:e,this.#n=t;for(let e of this.#r)e(this.#t,this.#n)}},Wu=class{#e;#t=!1;start(e){this.#e=e,this.#t=!1}cancel(){this.#t=!0}accepts(e){return!this.#t&&(!e||!this.#e||e===this.#e)}};Pt();const{setLoader:Gu,load:Ku,getSync:qu}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/voice-runtime`)}),Ju=Ku,Yu=qu;function Xu(e){if(!e)return``;let t=Zu(e);return Qu(t===null?e:t)}function Zu(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith(`{`))return null;try{let e=JSON.parse(t);if(e&&typeof e==`object`&&typeof e.text==`string`)return e.text}catch{}return null}function Qu(e){if(!e)return``;let t=e;return t=t.replace(/```[\s\S]*?```/g,` `),t=t.replace(/~~~[\s\S]*?~~~/g,` `),t=t.replace(/`([^`]+)`/g,`$1`),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,`$1`),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,`$1`),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,`$1`),t=t.replace(/<\/?[a-zA-Z][^>]*>/g,` `),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,``),t=t.replace(/^[ \t]*>[ \t]?/gm,``),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,``),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,``),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm,` `),t=t.replace(/(\*\*|__)(.*?)\1/g,`$2`),t=t.replace(/(\*|_)(.*?)\1/g,`$2`),t=t.replace(/~~(.*?)~~/g,`$1`),t=t.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/ /g,` `),t=t.replace(/[ \t]+/g,` `),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
17
17
|
`),t=t.replace(/\n{2,}/g,`
|
|
18
|
-
`),t.trim()}var qu,Ju=W((()=>{qu=class{#e=null;#t=0;#n=[];#r=[];#i=[];#a=!1;#o=!1;#s=0;#c=!1;#l=!1;#u;#d=[];#f=0;#p=!1;#m;#h;#g;#_=null;constructor(e=24e3,t={}){this.#h=e;let n=Math.max(0,t.prebufferMs??0);this.#g=Math.round(e*n/1e3),this.#u=this.#g>0}#v(){if(!this.#e){let e=typeof window<`u`?window:void 0;if(!e)throw Error(`AudioPlaybackManager requires a browser environment`);let t=e.AudioContext||e.webkitAudioContext;this.#e=new t({sampleRate:this.#h})}let e=this.#e;return e.state===`suspended`&&!this.#l&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.#_){let n=new Uint8Array(this.#_.length+e.length);n.set(this.#_),n.set(e,this.#_.length),t=n,this.#_=null}if(t.length%2!=0&&(this.#_=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.#S(t);n.length!==0&&(this.#u?(this.#d.push(n),this.#f+=n.length,clearTimeout(this.#m),this.#f>=this.#g?this.#y():this.#p&&(this.#m=setTimeout(()=>this.#y(),this.#g/this.#h*1e3))):this.#b(n))}markStreamEnd(){this.#d.length>0&&this.#y(),this.#o=!0,this.#x()}flush(){for(let e of this.#n){e.onended=null;try{e.stop(),e.disconnect()}catch{}}this.#n=[],this.#s=0,this.#t=0,this.#a=!1,this.#o=!1,this.#r=[],this.#i=[],this.#_=null,this.#d=[],this.#f=0,this.#u=this.#g>0,this.#c=!1,clearTimeout(this.#m)}setContinuousMode(e){this.#p=e}isPlaying(){return this.#a}onFinished(e){this.#r.push(e)}onStarted(e){this.#i.push(e)}pause(){this.#l=!0,this.#e&&this.#e.state===`running`&&this.#e.suspend()}resume(){this.#l=!1,this.#e&&this.#e.state===`suspended`&&this.#e.resume()}async destroy(){this.flush(),this.#e&&=(await this.#e.close(),null)}#y(){this.#u=!1;let e=this.#d;this.#d=[],this.#f=0;for(let t of e)this.#b(t)}#b(e){if(e.length===0)return;let t=this.#v(),n=t.createBuffer(1,e.length,this.#h);n.getChannelData(0).set(e);let r=t.createBufferSource();r.buffer=n,r.connect(t.destination);let i=t.currentTime;if(this.#t===0?this.#t=i:this.#t<i&&(this.#t=i,this.#g>0&&(this.#u=!0)),r.start(this.#t),this.#t+=n.duration,this.#n.push(r),this.#s++,this.#a=!0,!this.#c){this.#c=!0;let e=this.#i.slice();this.#i=[];for(let t of e)t()}r.onended=()=>{let e=this.#n.indexOf(r);e!==-1&&(this.#n.splice(e,1),this.#s--,this.#x())}}#x(){if(this.#o&&this.#s<=0&&this.#d.length===0){this.#a=!1,this.#o=!1;let e=this.#r.slice();this.#r=[];for(let t of e)t()}}#S(e){let t=Math.floor(e.length/2),n=new Float32Array(t),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let e=0;e<t;e++){let t=r.getInt16(e*2,!0);n[e]=t/32768}return n}}}));function Yu(e){return e.replace(/\/+$/,``)}async function Xu(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Zu,Qu=W((()=>{Ju(),Zu=class{#e;#t;#n;#r;constructor(e){this.id=`runtype-tts`,this.supportsPause=!0,this.#e=null,this.#t=null,this.#n=0,this.#r=e}#i(){return this.#t??=Promise.resolve(this.#r.createPlaybackEngine?this.#r.createPlaybackEngine():new qu(24e3,{prebufferMs:this.#r.prebufferMs??200})).then(e=>this.#e=e)}speak(e,t){let n=++this.#n;this.#a(n,e,t)}async#a(e,t,n){try{let r=await this.#i();if(e!==this.#n)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.#n&&n.onStart?.()}),r.onFinished(()=>{e===this.#n&&n.onEnd?.()});let i=`${Yu(this.#r.host)}/v1/agents/${encodeURIComponent(this.#r.agentId)}/speak`,a=await fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.#r.clientToken}`},body:JSON.stringify({text:t.text,voice:t.voice??this.#r.voice,format:`pcm`})});if(e!==this.#n)return;if(!a.ok||!a.body)throw Error(await Xu(a));let o=a.body.getReader();for(;;){let{done:t,value:n}=await o.read();if(e!==this.#n){await o.cancel().catch(()=>{});return}if(t)break;n&&n.byteLength>0&&r.enqueue(n)}r.markStreamEnd()}catch(t){if(e!==this.#n)return;let r=t instanceof Error?t:Error(String(t));this.#r.onError?.(r),n.onError?.(r)}}pause(){this.#e?.pause()}resume(){this.#e?.resume()}stop(){this.#n++,this.#e?.flush()}destroy(){this.#n++,this.#e?.destroy(),this.#e=null,this.#t=null}}})),$u,ed=W((()=>{$u=class{#e;#t;#n;#r;constructor(e,t,n={}){this.id=`fallback`,this.#t=e,this.#n=t,this.#r=n,this.#e=e}get supportsPause(){return this.#e.supportsPause}speak(e,t){this.#e=this.#t;let n=!1;this.#t.speak(e,{onStart:()=>{n=!0,t.onStart?.()},onEnd:()=>t.onEnd?.(),onError:r=>{n?t.onError?.(r):(this.#r.onFallback?.(r),this.#e=this.#n,this.#n.speak(e,t))}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#t.destroy?.(),this.#n.destroy?.()}}})),td=/* @__PURE__ */ Mt({FallbackSpeechEngine:()=>$u,RuntypeSpeechEngine:()=>Zu}),nd=W((()=>{Qu(),ed()}));const rd=()=>Promise.resolve().then(()=>(nd(),td));Pt();const{setLoader:id,load:ad}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/session-reconnect`)}),od=ad;En(),fi(),$o(),Nn(),Wc();const sd=/* @__PURE__ */ `apiUrl.clientToken.flowId.agentId.target.targetProviders.agent.agentOptions.headers.getHeaders.webmcp.streamParser.parserType.contextProviders.requestMiddleware.customFetch.parseSSEEvent.onSessionInit.onSessionExpired.getStoredSessionId.setStoredSessionId.getIdentityProof.identityProvider.getStoredConversationId.setStoredConversationId.clearStoredConversationId.clearStoredSessionId`.split(`.`);function cd(e,t){return sd.some(n=>e[n]!==t[n])}var ld=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function ud(e,t){let n=e instanceof Error?e:Error(String(e));if(typeof t==`string`)return t;if(typeof t==`function`)return t(n);let r=`Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.`;return n.message?`${r}\n\n_Details: ${n.message}_`:r}const dd=e=>wn(e)||e===`suggest_replies`;var fd=class e{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;constructor(e={},t,n={}){this.config=e,this.callbacks=t,this.historyInternals=n,this.status=`idle`,this.streaming=!1,this.#e=/* @__PURE__ */ new Map,this.abortController=null,this.#n=Date.now(),this.clientSession=null,this.agentExecution=null,this.#r=null,this.#i=null,this.#a=!1,this.#o=null,this.#s=null,this.#c=null,this.artifacts=/* @__PURE__ */ new Map,this.#l=null,this.webMcpInflightKeys=/* @__PURE__ */ new Set,this.webMcpResolvedKeys=/* @__PURE__ */ new Set,this.webMcpResolveControllers=/* @__PURE__ */ new Set,this.#u=0,this.webMcpApprovalResolvers=/* @__PURE__ */ new Map,this.#d=0,this.approvalTokens=/* @__PURE__ */ new Map,this.webMcpAwaitBatches=/* @__PURE__ */ new Map,this.#f=null,this.#p=null,this.#m=0,this.#h=0,this.#g=!1,this.#_=`disconnected`,this.#v=null,this.#y=null,this.#b=null,this.#x=0,this.#S=!1,this.#C=null,this.#w=!1,this.#T=null,this.#E=/* @__PURE__ */ new Map,this.#D=null,this.#O=/* @__PURE__ */ new Map,this.#k=null,this.#A=null,this.#j=!1,this.#M=null,this.#N=null,this.#P=!1,this.#F=null,this.#R=null,this.#z=null,this.#B=new Ru,this.#V=Promise.resolve(),this.#H=null,this.#U=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new Lu(()=>this.#W()),this.#Fe=null,this.#Ie=0,this.handleEvent=e=>{let t=this.#U,n=!1;if(t&&(e.type===`error`||e.type===`status`&&e.status===`error`?t.failed=!0:e.type===`message`&&e.message.role===`assistant`&&(t.dropped||this.ttsSpokenMessageIds.add(e.message.id),t.ids.includes(e.message.id)||t.ids.push(e.message.id),n=!0)),e.type===`message`){this.upsertMessage(e.message),n&&t.onUpdate?.(),e.message.variant===`approval`&&e.message.approval&&e.message.approval.status!==`pending`&&this.#e.set(e.message.id,this.#t),e.message.role===`assistant`&&!e.message.variant&&e.message.streaming&&(this.#i=e.message.id),(e.message.variant===`approval`||e.message.agentMetadata?.awaitingLocalTool===!0)&&lc().catch(()=>{});let r=e.message.toolCall,i=!!r?.name&&(wn(r.name)||r.name===`suggest_replies`&&di(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&i&&this.#Re(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:``,agentName:e.message.agentMetadata.agentName??``,status:`running`,currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type===`cursor`)this.#qe(e.id);else if(e.type===`status`){if(e.status===`idle`&&!e.terminal&&this.#Je()){this.#Xe();return}if(this.#rt(e.status),e.status===`connecting`)this.#it(!0);else if(e.status===`idle`||e.status===`error`){this.#Ye()||this.#tt(),this.webMcpResolveControllers.size===0&&(this.#it(!1),this.abortController=null,this.#De(),this.#Se());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status===`running`&&(e.status===`error`?this.agentExecution.status=`error`:t||(this.agentExecution.status=`complete`)),this.#ze()}}else e.type===`error`?(this.#rt(`error`),this.#tt(),this.webMcpResolveControllers.size===0&&(this.#it(!1),this.abortController=null),this.agentExecution?.status===`running`&&(this.agentExecution.status=`error`),this.callbacks.onError?.(e.error)):(e.type===`artifact_start`||e.type===`artifact_delta`||e.type===`artifact_update`||e.type===`artifact_complete`)&&this.#Ke(e)},this.historyInternals=this.#X(n),this.messages=[...e.initialMessages??[]].map(e=>({...e,sequence:e.sequence??this.#ut()})),this.messages=this.#dt(this.messages),this.client=new Su(e,this.historyInternals),this.#pe(),this.#Pe();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:`complete`});e.initialSelectedArtifactId!=null&&(this.#l=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#Ge(),this.callbacks.onStatusChanged(this.status),this.#L(),this.#I()}#I(){this.config.voiceRecognition?.provider&&Hu().catch(()=>{})}#L(){let e=this.config.textToSpeech;if(e?.provider!==`runtype`||e.createEngine)return;let t=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&n&&this.config.clientToken&&rd().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status===`running`}isVoiceSupported(){return Tl(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#g}getVoiceStatus(){return this.#_}getVoiceNotice(){return this.#f?.takeNotice?.()??null}getVoiceDisclosure(){return this.#f?.getDisclosure?.()??null}getVoiceLevel(){return this.#f?.onLevel?this.#h:null}getVoiceInterruptionMode(){return this.#f?.getInterruptionMode?this.#f.getInterruptionMode():`none`}stopVoicePlayback(){this.#f?.stopPlayback&&(this.#B.cancel(),this.#H?.cancel(),this.#f.stopPlayback())}isBargeInActive(){return this.#f?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#f?.deactivateBargeIn&&await this.#f.deactivateBargeIn()}#R;#z;#B;#V;#H;#U;#W(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=Iu.isSupported()?new Iu({pickVoice:e?.pickVoice}):null;if(e?.provider===`runtype`){let n=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,a=e.browserFallback!==!1;if(n&&r&&i)return rd().then(({RuntypeSpeechEngine:o,FallbackSpeechEngine:s})=>{let c=new o({host:n,agentId:r,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new s(c,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):c});if(a&&t)return i&&console.warn(`[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId).`),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error(`Voice configuration not provided`);this.cleanupVoice();let n=this.#V,r=++this.#m;this.#p=Hu().then(async e=>{await n,r===this.#m&&this.#G(e,e.createVoiceProvider(t))}).catch(e=>{console.error(`Failed to setup voice:`,e)}).finally(()=>{r===this.#m&&(this.#p=null)})}catch(e){console.error(`Failed to setup voice:`,e)}}#G(e,t){this.#f=t;let n=this;e.wireSessionVoice({session:this,provider:()=>n.#f,generation:()=>n.#m,get keyed(){return n.#H},set keyed(e){n.#H=e},get pendingUser(){return n.#R},set pendingUser(e){n.#R=e},get pendingAssistant(){return n.#z},set pendingAssistant(e){n.#z=e},turns:()=>n.#B,busy:()=>n.#K(),setStreaming:e=>n.#it(e),setDelegation:e=>{n.#U=e},setLevel:e=>{n.#h=e},setStatus:e=>{n.#_=e,n.#g=e===`listening`},settlePending:e=>n.#J(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#f&&this.#p&&await this.#p,!this.#f)console.error(`Voice not configured`);else if(this.#g)await this.#f.stopListening();else{this.stopSpeaking();try{await this.#f.startListening()}catch(e){console.error(`Failed to start voice:`,e)}}}prewarmVoice(){if(!Cl(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#m,t=()=>{let t=this.#f;t?.prewarm&&e===this.#m&&(this.#g||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#f&&this.#p?this.#p.then(t,()=>{}):t()}#K(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#a||this.status===`resuming`}cleanupVoice(){let e=this.#f!==null;if(this.#m++,this.#p=null,this.#f){let e=this.#f;this.#f=null,this.#V=this.#q(e)}this.#g=!1,this.#_=`disconnected`,this.#J(!0),this.#H?.settle(),this.#H=null,this.#B=new Ru,e&&this.callbacks.onVoiceStatusChanged?.(`disconnected`)}async#q(e){try{await e.disconnect()}catch(e){console.error(`Failed to disconnect voice:`,e)}}#J(e){let t=e?this.#R:null,n=this.#z;(t||n)&&(n&&this.#B.cancel(),e&&(this.#R=null),this.#z=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==n?[e]:e.id===n&&!e.content.trim()?[]:[{...e,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.#it(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case`runtype`:return{type:`runtype`,runtype:{agentId:e.runtype?.agentId??this.config.agentId??``,clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};case`browser`:return{type:`browser`,browser:{language:e.browser?.language||`en-US`,continuous:e.browser?.continuous}};case`custom`:return{type:`custom`,custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#A=this.historyInternals.getStoredConversationRevision?.()??null,this.#j=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#Y(e,t)}#Y(e,t=!this.messages.length){if(this.#S||!e.config.welcomeMessage||!t)return;let n=this.messages[0],r={id:`welcome-${Date.now()}`,role:`assistant`,content:e.config.welcomeMessage,createdAt:n?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),sequence:n?(n.sequence??0)-1:this.#ut()};this.#ct(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?/* @__PURE__ */ new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){this.historyInternals=this.#X(e),this.client.setHistoryInternals(this.historyInternals),this.#pe()}destroy(){this.cleanupVoice(),this.#M?.(),this.#M=null,this.#N=null}#X(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#fe(e),t?.(e)}}}get#Z(){return this.historyInternals.historyProvider??null}#Q(){let e=this.#Z;if(!e)throw new ld(`history_unavailable`,`No conversation history provider is installed`);return e}#$(e){let t=this.#Q(),n=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?`verified-user`:`browser`,i=n??(t.capabilities.scopes.includes(r)?r:t.capabilities.scopes[0]??r);if(!t.capabilities.scopes.includes(i))throw new Cu(`unsupported_scope`,`This history scope is not supported.`);return{scope:i}}getHistoryState(){return{activeConversationId:this.#v,conversationRevision:this.#y,nextMessageCursor:this.#b,recovery:this.#C,sendBlocked:this.#w}}getActiveConversationId(){return this.#v}#ee(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#te(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#T;e&&await e.catch(()=>{});let t=this.#D;t&&await t.catch(()=>{})}#ne(){if(this.streaming||this.status===`paused`||this.status===`resuming`)throw new ld(`conversation_busy`,`Finish or stop the current turn before switching conversations`)}listConversations(e){return this.#Q().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit===void 0?{}:{limit:e.limit},...e?.targetId===void 0?{}:{targetId:e.targetId},context:this.#$(e?.scope)})}async openConversation(e,t){let n=this.#Q();this.#ne();let r=this.#$(t?.scope);await this.awaitHistorySettled();let i=++this.#x,a=await n.getPage(e,{context:r});if(i!==this.#x)throw new ld(`superseded`,`A later selection won`);let o=await n.prepareOpen(e,{context:r});if(i!==this.#x)throw o.discard(),new ld(`superseded`,`A later selection won`);this.#S=!0;try{await this.#ce(o)}finally{this.#S=!1}this.#v=o.conversationId||e,this.#y=o.conversationRevision||a.conversationRevision||null,this.#b=a.nextCursor,this.#C=null,this.#w=!1,this.#ue();for(let e of a.messages)this.#O.set(e.id,e.content);return this.#le(),this.hydrateMessages(a.messages),this.#ee(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,t,n){let r=this.#Q(),i=this.#$(n?.scope),a=t??this.#b;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let o=`${e} ${a}`,s=this.#E.get(o);if(s)return s;let c=this.#re(r,e,a,i).finally(()=>{this.#E.delete(o)});return this.#E.set(o,c),c}async#re(e,t,n,r){let i=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:n,...i?{beforeCreatedAt:i}:{},context:r});if(this.#v&&this.#v!==t)return{messages:[],nextMessageCursor:a.nextCursor};let o=Vc(this.messages,a.messages);this.messages=this.#dt(o.map(e=>this.#lt(e))),this.#b=a.nextCursor;for(let e of a.messages)this.#O.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#ee(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=++this.#x,i=await t.prepareStartNew({context:n});if(r!==this.#x)throw i.discard(),new ld(`superseded`,`A later action won`);await this.#ie(i)}async#ie(e){this.#de(),await this.#ce(e),this.#v=e.conversationId||null,this.#y=e.conversationRevision||null,this.#b=null,this.#C=null,this.#w=!1,this.#le(),this.#ee()}async deleteConversation(e,t){let n=this.#Q(),r=this.#$(t?.scope);await this.awaitHistorySettled(),await n.delete(e,{context:r}),e===this.#v&&await this.#ae(r)}async updateConversation(e,t,n){let r=this.#Q();if(!r.update)throw new ld(`history_unavailable`,`This history provider cannot update conversations`);let i=this.#$(n?.scope);return await this.awaitHistorySettled(),r.update(e,t,{context:i})}canUpdateConversations(){return typeof this.#Z?.update==`function`}async clearConversationHistory(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=await t.deleteAll({...e?.targetId===void 0?{}:{targetId:e.targetId},context:n});return await this.#ae(n),r}async resetHistoryDevice(){let e=this.#Q();if(!e.resetDevice)throw new ld(`history_unavailable`,`This history provider cannot reset the device`);this.#x+=1,this.#D=null;try{return await e.resetDevice()}finally{this.#de(),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#w=!1,this.#ee()}}async#ae(e){this.#x+=1,this.#D=null,this.#de(),this.#v=null,this.#y=null,this.#b=null,this.#w=!0,this.#C=null,this.#ee(),await this.#oe(e)}async#oe(e){let t=this.#Z;if(!t)this.#w=!1,this.#ee();else try{let n=await t.prepareStartNew({context:e});await this.#ie(n)}catch{this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`)}}async#se(){if(this.#C===`new_conversation_required`&&this.#Z&&(this.#C=null,await this.#oe(this.#$()),this.#C===`new_conversation_required`))throw new ld(`new_conversation_required`,`A new conversation is required before sending`)}async#ce(e){await e.commit();let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#v=e.conversationId,this.#y=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#S||this.#Y(e)}#le(){this.#v?this.config.setStoredConversationId?.(this.#v):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#y),this.historyInternals.setStoredMessageCursor?.(this.#b)}#ue(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#We(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#O.clear(),this.#ye(null)}#de(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#et(),this.#Ve(),this.#Ie++,this.messages=[],this.#ue(),this.#E.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#it(!1),this.#rt(`idle`),this.callbacks.onMessagesChanged([...this.messages])}#fe(e){this.#x+=1,this.#D=null,this.#w=!0,this.#de(),this.#v=e.conversationId,this.#y=null,this.#b=null,this.#C=null,this.#ee(),this.#te(`history_continuity_reset`,`This browser was reconnected to a different conversation, so the previous messages were cleared.`),this.#T=Promise.resolve().then(()=>{this.#w=!1,this.#T=null,this.#ee()})}#pe(){let e=this.historyInternals.visitorStore??null;e!==this.#N&&(this.#M?.(),this.#M=null,this.#N=e,e&&(this.#M=e.subscribe(e=>this.#me(e))))}#me(e){if(e.source!==`external`||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#x+=1,this.#D=null,this.#P=!0,this.#F=null;let t=this.messages.length>0;t||this.#v!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#de():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#E.clear(),this.#ye(null)),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#ee(),t&&this.#te(`history_continuity_reset`,`This browser's conversation history was reset in another tab, so the previous messages were cleared.`)}#he(){return this.#P?(this.#F||=this.#ge().finally(()=>{this.#F=null}),this.#F):Promise.resolve()}async#ge(){if(!this.isClientTokenMode())this.#P=!1;else try{this.bindActivatedSession(await this.client.initSession()),this.#P=!1}catch{}}reconcileBootConversation(e){let t=this.#Z,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#v;if(!t||!n)return Promise.resolve();let r=this.#$(e?.scope);this.#w=!0,this.#ee();let i=this.#_e(t,n,r).finally(()=>{this.#w=this.#C!==null,this.#T===i&&(this.#T=null),this.#ee()});return this.#T=i,i}async#_e(e,t,n){this.#v=t;let r=this.clientSession?.conversationRevision??this.#y??null,i=this.#j?this.#A:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#j=!1,this.#b=this.historyInternals.getStoredMessageCursor?.()??this.#b,await this.replayPendingProjections(),r&&i&&r===i){this.#y=r;return}let a=await e.getPage(t,{context:n}),o=new Set(a.messages.map(e=>e.id)),s=this.messages.some(e=>o.has(e.id)),c=a.messages[0]?.createdAt,l;if(!s)l=a.messages.map(e=>this.#lt(e));else{let e=this.#r?this.#i:null;l=Vc(this.messages.filter(t=>o.has(t.id)||t.id===e?!0:c!==void 0&&t.createdAt<c),a.messages).map(e=>this.#lt(e))}this.#b=a.nextCursor,this.#y=a.conversationRevision||r||null,this.#O.clear();for(let e of a.messages)this.#O.set(e.id,e.content);this.#le(),this.messages=this.#dt(l),this.callbacks.onMessagesChanged([...this.messages])}#ve(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#ye(e){this.#k=e,this.historyInternals.setPendingDisplayProjections?.(e)}#be(){return this.historyInternals.getPendingDisplayProjections?.()??this.#k}#xe(e){if(this.#ve())for(let t of e){let e=Bc(t);e!==void 0&&this.#O.set(t.id,e)}}#Se(){if(!this.#ve())return;let e=this.#v;if(!e)return;let t=[];for(let e of this.messages){if(e.role!==`assistant`||e.streaming)continue;let n=Bc(e);n!==void 0&&this.#O.get(e.id)!==n&&t.push({id:e.id,displayContent:n})}t.length!==0&&(this.#ye({conversationId:e,messageIds:t.map(e=>e.id)}),this.#Ce(e,t))}#Ce(e,t){let n=(this.#D??Promise.resolve()).catch(()=>{}).then(()=>this.#we(e,t,!1)).finally(()=>{this.#D===n&&(this.#D=null)});this.#D=n}async#we(e,t,n){if(this.#v!==e)return;let r=t.filter(e=>this.#O.get(e.id)!==e.displayContent);if(r.length===0)this.#Ee(e,t);else try{let{conversationRevision:n}=await this.client.finalizeDisplayProjections(e,r);for(let e of r)this.#O.set(e.id,e.displayContent);this.#v===e&&n&&(this.#y=n),this.#Ee(e,t)}catch(i){if(!n&&this.#Te(i)){await this.#we(e,r,!0);return}if(i instanceof hu&&(i.code===`not_found`||i.code===`conversation_deleted`)){this.#Ee(e,t);return}this.#te(`projection_finalization_failed`,`Some message formatting could not be saved for history; it will be retried.`)}}#Te(e){return e instanceof hu?e.code===`request_failed`:e instanceof Error}#Ee(e,t){let n=this.#be();if(!n||n.conversationId!==e)return;let r=new Set(t.map(e=>e.id)),i=n.messageIds.filter(e=>!r.has(e));this.#ye(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#ve())return;let e=this.#be();if(!e)return;if(this.#v&&e.conversationId!==this.#v){this.#ye(null);return}let t=[];for(let n of e.messageIds){let e=this.messages.find(e=>e.id===n);e&&typeof e.content==`string`&&t.push({id:n,displayContent:e.content})}t.length===0?this.#ye(null):(this.#Ce(e.conversationId,t),await this.#D?.catch(()=>{}))}#De(){this.#v&&(this.#y=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Oe(){await this.awaitHistorySettled(),await this.#he(),this.#C===`new_conversation_required`&&await this.#se()}static#ke(e){return e instanceof hu&&e.code===`conversation_deleted`}async#Ae(t,n,r,i,a){this.#xe(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken},this.handleEvent);return}catch(t){if(!e.#ke(t))throw t;let o=await this.#je(i);if(!o)throw t;this.#xe([o]),await this.client.dispatch({messages:[o],signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken},this.handleEvent)}}async#je(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let n={...t};this.#x+=1,this.#D=null,this.#de(),this.#v=null,this.#y=null,this.#b=null,this.#S=!0;try{let e=this.#Z;if(e){let t=await e.prepareStartNew({context:this.#$()});await this.#ie(t)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`),null}finally{this.#S=!1}return this.#ct(n),this.#it(!0),this.#te(`conversation_deleted_recovered`,`That conversation was deleted. Started a new conversation.`),this.messages.find(e=>e.id===n.id)??n}updateConfig(e){let t=this.config.features?.artifacts?.display,n={...this.config,...e},r=Sl(this.config,n),i=cd(this.config,n);this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&Cl(n.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(n.features?.artifacts?.display);if(!i){this.client.updateConfig(n),a&&this.#Ue();return}this.#Ve(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.client=new Su(this.config,this.historyInternals),a&&this.#Ue(),this.#Pe(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:n,llmContent:r,contentParts:i,id:a,createdAt:o,sequence:s,streaming:c=!1,voiceProcessing:l,voiceCaption:u,rawContent:d}=e,f={id:a??(t===`user`?cu():t===`assistant`?lu():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:n,createdAt:o??(/* @__PURE__ */ new Date()).toISOString(),sequence:s??this.#ut(),streaming:c,...r!==void 0&&{llmContent:r},...i!==void 0&&{contentParts:i},...l!==void 0&&{voiceProcessing:l},...u&&{voiceCaption:u},...d!==void 0&&{rawContent:d}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:`assistant`})}injectUserMessage(e){return this.injectMessage({...e,role:`user`})}injectSystemMessage(e){return this.injectMessage({...e,role:`system`})}injectMessageBatch(e){let t=[];for(let n of e){let{role:e,content:r,llmContent:i,contentParts:a,id:o,createdAt:s,sequence:c,streaming:l=!1,voiceProcessing:u,rawContent:d}=n,f={id:o??(e===`user`?cu():e===`assistant`?lu():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:e,content:r,createdAt:s??(/* @__PURE__ */ new Date()).toISOString(),sequence:c??this.#ut(),streaming:l,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a},...u!==void 0&&{voiceProcessing:u},...d!==void 0&&{rawContent:d}};t.push(f)}return this.messages=this.#dt([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:r=``,llmContent:i,id:a,createdAt:o,sequence:s}=e,c={text:r,component:t,props:n};return this.injectMessage({role:`assistant`,content:r,rawContent:JSON.stringify(c),...i!==void 0&&{llmContent:i},...a!==void 0&&{id:a},...o!==void 0&&{createdAt:o},...s!==void 0&&{sequence:s}})}async#Me(e,t,n){let r;try{r=await n()}catch{return}let i=r.blocks.join(`
|
|
18
|
+
`),t.trim()}var $u,ed=W((()=>{$u=class{#e=null;#t=0;#n=[];#r=[];#i=[];#a=!1;#o=!1;#s=0;#c=!1;#l=!1;#u;#d=[];#f=0;#p=!1;#m;#h;#g;#_=null;constructor(e=24e3,t={}){this.#h=e;let n=Math.max(0,t.prebufferMs??0);this.#g=Math.round(e*n/1e3),this.#u=this.#g>0}#v(){if(!this.#e){let e=typeof window<`u`?window:void 0;if(!e)throw Error(`AudioPlaybackManager requires a browser environment`);let t=e.AudioContext||e.webkitAudioContext;this.#e=new t({sampleRate:this.#h})}let e=this.#e;return e.state===`suspended`&&!this.#l&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.#_){let n=new Uint8Array(this.#_.length+e.length);n.set(this.#_),n.set(e,this.#_.length),t=n,this.#_=null}if(t.length%2!=0&&(this.#_=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.#S(t);n.length!==0&&(this.#u?(this.#d.push(n),this.#f+=n.length,clearTimeout(this.#m),this.#f>=this.#g?this.#y():this.#p&&(this.#m=setTimeout(()=>this.#y(),this.#g/this.#h*1e3))):this.#b(n))}markStreamEnd(){this.#d.length>0&&this.#y(),this.#o=!0,this.#x()}flush(){for(let e of this.#n){e.onended=null;try{e.stop(),e.disconnect()}catch{}}this.#n=[],this.#s=0,this.#t=0,this.#a=!1,this.#o=!1,this.#r=[],this.#i=[],this.#_=null,this.#d=[],this.#f=0,this.#u=this.#g>0,this.#c=!1,clearTimeout(this.#m)}setContinuousMode(e){this.#p=e}isPlaying(){return this.#a}onFinished(e){this.#r.push(e)}onStarted(e){this.#i.push(e)}pause(){this.#l=!0,this.#e&&this.#e.state===`running`&&this.#e.suspend()}resume(){this.#l=!1,this.#e&&this.#e.state===`suspended`&&this.#e.resume()}async destroy(){this.flush(),this.#e&&=(await this.#e.close(),null)}#y(){this.#u=!1;let e=this.#d;this.#d=[],this.#f=0;for(let t of e)this.#b(t)}#b(e){if(e.length===0)return;let t=this.#v(),n=t.createBuffer(1,e.length,this.#h);n.getChannelData(0).set(e);let r=t.createBufferSource();r.buffer=n,r.connect(t.destination);let i=t.currentTime;if(this.#t===0?this.#t=i:this.#t<i&&(this.#t=i,this.#g>0&&(this.#u=!0)),r.start(this.#t),this.#t+=n.duration,this.#n.push(r),this.#s++,this.#a=!0,!this.#c){this.#c=!0;let e=this.#i.slice();this.#i=[];for(let t of e)t()}r.onended=()=>{let e=this.#n.indexOf(r);e!==-1&&(this.#n.splice(e,1),this.#s--,this.#x())}}#x(){if(this.#o&&this.#s<=0&&this.#d.length===0){this.#a=!1,this.#o=!1;let e=this.#r.slice();this.#r=[];for(let t of e)t()}}#S(e){let t=Math.floor(e.length/2),n=new Float32Array(t),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let e=0;e<t;e++){let t=r.getInt16(e*2,!0);n[e]=t/32768}return n}}}));function td(e){return e.replace(/\/+$/,``)}async function nd(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var rd,id=W((()=>{ed(),rd=class{#e;#t;#n;#r;constructor(e){this.id=`runtype-tts`,this.supportsPause=!0,this.#e=null,this.#t=null,this.#n=0,this.#r=e}#i(){return this.#t??=Promise.resolve(this.#r.createPlaybackEngine?this.#r.createPlaybackEngine():new $u(24e3,{prebufferMs:this.#r.prebufferMs??200})).then(e=>this.#e=e)}speak(e,t){let n=++this.#n;this.#a(n,e,t)}async#a(e,t,n){try{let r=await this.#i();if(e!==this.#n)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.#n&&n.onStart?.()}),r.onFinished(()=>{e===this.#n&&n.onEnd?.()});let i=`${td(this.#r.host)}/v1/agents/${encodeURIComponent(this.#r.agentId)}/speak`,a=await fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.#r.clientToken}`},body:JSON.stringify({text:t.text,voice:t.voice??this.#r.voice,format:`pcm`})});if(e!==this.#n)return;if(!a.ok||!a.body)throw Error(await nd(a));let o=a.body.getReader();for(;;){let{done:t,value:n}=await o.read();if(e!==this.#n){await o.cancel().catch(()=>{});return}if(t)break;n&&n.byteLength>0&&r.enqueue(n)}r.markStreamEnd()}catch(t){if(e!==this.#n)return;let r=t instanceof Error?t:Error(String(t));this.#r.onError?.(r),n.onError?.(r)}}pause(){this.#e?.pause()}resume(){this.#e?.resume()}stop(){this.#n++,this.#e?.flush()}destroy(){this.#n++,this.#e?.destroy(),this.#e=null,this.#t=null}}})),ad,od=W((()=>{ad=class{#e;#t;#n;#r;constructor(e,t,n={}){this.id=`fallback`,this.#t=e,this.#n=t,this.#r=n,this.#e=e}get supportsPause(){return this.#e.supportsPause}speak(e,t){this.#e=this.#t;let n=!1;this.#t.speak(e,{onStart:()=>{n=!0,t.onStart?.()},onEnd:()=>t.onEnd?.(),onError:r=>{n?t.onError?.(r):(this.#r.onFallback?.(r),this.#e=this.#n,this.#n.speak(e,t))}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#t.destroy?.(),this.#n.destroy?.()}}})),sd=/* @__PURE__ */ Mt({FallbackSpeechEngine:()=>ad,RuntypeSpeechEngine:()=>rd}),cd=W((()=>{id(),od()}));const ld=()=>Promise.resolve().then(()=>(cd(),sd));Pt();const{setLoader:ud,load:dd}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/session-reconnect`)}),fd=dd;En(),fi(),Xs(),$o(),Nn(),Yc();const pd=/* @__PURE__ */ `apiUrl.clientToken.flowId.agentId.target.targetProviders.agent.agentOptions.headers.getHeaders.webmcp.streamParser.parserType.contextProviders.requestMiddleware.customFetch.parseSSEEvent.onSessionInit.onSessionExpired.getStoredSessionId.setStoredSessionId.getIdentityProof.identityProvider.getStoredConversationId.setStoredConversationId.clearStoredConversationId.clearStoredSessionId`.split(`.`);function md(e,t){return pd.some(n=>e[n]!==t[n])}var hd=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function gd(e,t){let n=e instanceof Error?e:Error(String(e));if(typeof t==`string`)return t;if(typeof t==`function`)return t(n);let r=`Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.`;return n.message?`${r}\n\n_Details: ${n.message}_`:r}const _d=e=>wn(e)||e===`suggest_replies`;var vd=class e{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;constructor(e={},t,n={}){this.config=e,this.callbacks=t,this.historyInternals=n,this.status=`idle`,this.streaming=!1,this.#e=/* @__PURE__ */ new Map,this.abortController=null,this.#n=Date.now(),this.clientSession=null,this.agentExecution=null,this.#r=null,this.#i=null,this.#a=!1,this.#o=null,this.#s=null,this.#c=null,this.artifacts=/* @__PURE__ */ new Map,this.#l=null,this.webMcpInflightKeys=/* @__PURE__ */ new Set,this.webMcpResolvedKeys=/* @__PURE__ */ new Set,this.webMcpResolveControllers=/* @__PURE__ */ new Set,this.#u=0,this.webMcpApprovalResolvers=/* @__PURE__ */ new Map,this.#d=0,this.approvalTokens=/* @__PURE__ */ new Map,this.webMcpAwaitBatches=/* @__PURE__ */ new Map,this.#f=null,this.#p=null,this.#m=0,this.#h=0,this.#g=!1,this.#_=`disconnected`,this.#v=null,this.#y=null,this.#b=null,this.#x=0,this.#S=!1,this.#C=null,this.#w=!1,this.#T=null,this.#E=/* @__PURE__ */ new Map,this.#D=null,this.#O=/* @__PURE__ */ new Map,this.#k=null,this.#A=null,this.#j=!1,this.#M=null,this.#N=null,this.#P=!1,this.#F=null,this.#R=null,this.#z=null,this.#B=new Wu,this.#V=Promise.resolve(),this.#H=null,this.#U=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new Uu(()=>this.#W()),this.#Ie=null,this.#Le=0,this.handleEvent=e=>{let t=this.#U,n=!1;if(t&&(e.type===`error`||e.type===`status`&&e.status===`error`?t.failed=!0:e.type===`message`&&e.message.role===`assistant`&&(t.dropped||this.ttsSpokenMessageIds.add(e.message.id),t.ids.includes(e.message.id)||t.ids.push(e.message.id),n=!0)),e.type===`message`){this.upsertMessage(e.message),n&&t.onUpdate?.(),e.message.variant===`approval`&&e.message.approval&&e.message.approval.status!==`pending`&&this.#e.set(e.message.id,this.#t),e.message.role===`assistant`&&!e.message.variant&&e.message.streaming&&(this.#i=e.message.id),(e.message.variant===`approval`||e.message.agentMetadata?.awaitingLocalTool===!0)&&mc().catch(()=>{});let r=e.message.toolCall,i=!!r?.name&&(wn(r.name)||r.name===`suggest_replies`&&di(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&i&&this.messages.find(t=>t.id===e.message.id)?.agentMetadata?.awaitingLocalTool===!0&&this.#ze(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:``,agentName:e.message.agentMetadata.agentName??``,status:`running`,currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type===`cursor`)this.#Je(e.id);else if(e.type===`status`){if(e.status===`idle`&&!e.terminal&&this.#Ye()){this.#Ze();return}if(this.#st(e.status),e.status===`connecting`)this.#ct(!0);else if(e.status===`idle`||e.status===`error`){this.#Xe()||this.#at(),this.webMcpResolveControllers.size===0&&(this.#ct(!1),this.abortController=null,this.#Oe(),this.#Ce());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status===`running`&&(e.status===`error`?this.agentExecution.status=`error`:t||(this.agentExecution.status=`complete`)),this.#Be()}}else e.type===`error`?(this.#st(`error`),this.#at(),this.webMcpResolveControllers.size===0&&(this.#ct(!1),this.abortController=null),this.agentExecution?.status===`running`&&(this.agentExecution.status=`error`),this.callbacks.onError?.(e.error)):(e.type===`artifact_start`||e.type===`artifact_delta`||e.type===`artifact_update`||e.type===`artifact_complete`)&&this.#qe(e)},this.historyInternals=this.#X(n),this.messages=[...e.initialMessages??[]].map(e=>({...pl(e),sequence:e.sequence??this.#mt()})),this.messages=this.#gt(this.messages),this.client=new Eu(e,this.historyInternals),this.#me(),this.#Fe();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:`complete`});e.initialSelectedArtifactId!=null&&(this.#l=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#Ke(),this.callbacks.onStatusChanged(this.status),this.#L(),this.#I()}#I(){this.config.voiceRecognition?.provider&&Ju().catch(()=>{})}#L(){let e=this.config.textToSpeech;if(e?.provider!==`runtype`||e.createEngine)return;let t=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&n&&this.config.clientToken&&ld().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status===`running`}isVoiceSupported(){return Ml(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#g}getVoiceStatus(){return this.#_}getVoiceNotice(){return this.#f?.takeNotice?.()??null}getVoiceDisclosure(){return this.#f?.getDisclosure?.()??null}getVoiceLevel(){return this.#f?.onLevel?this.#h:null}getVoiceInterruptionMode(){return this.#f?.getInterruptionMode?this.#f.getInterruptionMode():`none`}stopVoicePlayback(){this.#f?.stopPlayback&&(this.#B.cancel(),this.#H?.cancel(),this.#f.stopPlayback())}isBargeInActive(){return this.#f?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#f?.deactivateBargeIn&&await this.#f.deactivateBargeIn()}#R;#z;#B;#V;#H;#U;#W(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=Hu.isSupported()?new Hu({pickVoice:e?.pickVoice}):null;if(e?.provider===`runtype`){let n=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,a=e.browserFallback!==!1;if(n&&r&&i)return ld().then(({RuntypeSpeechEngine:o,FallbackSpeechEngine:s})=>{let c=new o({host:n,agentId:r,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new s(c,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):c});if(a&&t)return i&&console.warn(`[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId).`),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error(`Voice configuration not provided`);this.cleanupVoice();let n=this.#V,r=++this.#m;this.#p=Ju().then(async e=>{await n,r===this.#m&&this.#G(e,e.createVoiceProvider(t))}).catch(e=>{console.error(`Failed to setup voice:`,e)}).finally(()=>{r===this.#m&&(this.#p=null)})}catch(e){console.error(`Failed to setup voice:`,e)}}#G(e,t){this.#f=t;let n=this;e.wireSessionVoice({session:this,provider:()=>n.#f,generation:()=>n.#m,get keyed(){return n.#H},set keyed(e){n.#H=e},get pendingUser(){return n.#R},set pendingUser(e){n.#R=e},get pendingAssistant(){return n.#z},set pendingAssistant(e){n.#z=e},turns:()=>n.#B,busy:()=>n.#K(),setStreaming:e=>n.#ct(e),setDelegation:e=>{n.#U=e},setLevel:e=>{n.#h=e},setStatus:e=>{n.#_=e,n.#g=e===`listening`},settlePending:e=>n.#J(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#f&&this.#p&&await this.#p,!this.#f)console.error(`Voice not configured`);else if(this.#g)await this.#f.stopListening();else{this.stopSpeaking();try{await this.#f.startListening()}catch(e){console.error(`Failed to start voice:`,e)}}}prewarmVoice(){if(!Al(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#m,t=()=>{let t=this.#f;t?.prewarm&&e===this.#m&&(this.#g||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#f&&this.#p?this.#p.then(t,()=>{}):t()}#K(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#a||this.status===`resuming`}cleanupVoice(){let e=this.#f!==null;if(this.#m++,this.#p=null,this.#f){let e=this.#f;this.#f=null,this.#V=this.#q(e)}this.#g=!1,this.#_=`disconnected`,this.#J(!0),this.#H?.settle(),this.#H=null,this.#B=new Wu,e&&this.callbacks.onVoiceStatusChanged?.(`disconnected`)}async#q(e){try{await e.disconnect()}catch(e){console.error(`Failed to disconnect voice:`,e)}}#J(e){let t=e?this.#R:null,n=this.#z;(t||n)&&(n&&this.#B.cancel(),e&&(this.#R=null),this.#z=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==n?[e]:e.id===n&&!e.content.trim()?[]:[{...e,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.#ct(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case`runtype`:return{type:`runtype`,runtype:{agentId:e.runtype?.agentId??this.config.agentId??``,clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};case`browser`:return{type:`browser`,browser:{language:e.browser?.language||`en-US`,continuous:e.browser?.continuous}};case`custom`:return{type:`custom`,custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#A=this.historyInternals.getStoredConversationRevision?.()??null,this.#j=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#Y(e,t)}#Y(e,t=!this.messages.length){if(this.#S||!e.config.welcomeMessage||!t)return;let n=this.messages[0],r={id:`welcome-${Date.now()}`,role:`assistant`,content:e.config.welcomeMessage,createdAt:n?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),sequence:n?(n.sequence??0)-1:this.#mt()};this.#ft(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?/* @__PURE__ */ new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){this.historyInternals=this.#X(e),this.client.setHistoryInternals(this.historyInternals),this.#me()}destroy(){this.cleanupVoice(),this.#M?.(),this.#M=null,this.#N=null}#X(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#pe(e),t?.(e)}}}get#Z(){return this.historyInternals.historyProvider??null}#Q(){let e=this.#Z;if(!e)throw new hd(`history_unavailable`,`No conversation history provider is installed`);return e}#$(e){let t=this.#Q(),n=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?`verified-user`:`browser`,i=n??(t.capabilities.scopes.includes(r)?r:t.capabilities.scopes[0]??r);if(!t.capabilities.scopes.includes(i))throw new Du(`unsupported_scope`,`This history scope is not supported.`);return{scope:i}}getHistoryState(){return{activeConversationId:this.#v,conversationRevision:this.#y,nextMessageCursor:this.#b,recovery:this.#C,sendBlocked:this.#w}}getActiveConversationId(){return this.#v}#ee(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#te(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#T;e&&await e.catch(()=>{});let t=this.#D;t&&await t.catch(()=>{})}#ne(){if(this.streaming||this.status===`paused`||this.status===`resuming`)throw new hd(`conversation_busy`,`Finish or stop the current turn before switching conversations`)}listConversations(e){return this.#Q().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit===void 0?{}:{limit:e.limit},...e?.targetId===void 0?{}:{targetId:e.targetId},context:this.#$(e?.scope)})}async openConversation(e,t){let n=this.#Q();this.#ne();let r=this.#$(t?.scope);await this.awaitHistorySettled();let i=++this.#x,a=await n.getPage(e,{context:r});if(i!==this.#x)throw new hd(`superseded`,`A later selection won`);let o=await n.prepareOpen(e,{context:r});if(i!==this.#x)throw o.discard(),new hd(`superseded`,`A later selection won`);this.#S=!0;try{await this.#le(o)}finally{this.#S=!1}this.#v=o.conversationId||e,this.#y=o.conversationRevision||a.conversationRevision||null,this.#b=a.nextCursor,this.#C=null,this.#w=!1,this.#de();for(let e of a.messages)this.#O.set(e.id,e.content);return this.#ue(),this.hydrateMessages(a.messages),this.#ee(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,t,n){let r=this.#Q(),i=this.#$(n?.scope),a=t??this.#b;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let o=`${e} ${a}`,s=this.#E.get(o);if(s)return s;let c=this.#re(r,e,a,i).finally(()=>{this.#E.delete(o)});return this.#E.set(o,c),c}async#re(e,t,n,r){let i=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:n,...i?{beforeCreatedAt:i}:{},context:r});if(this.#v&&this.#v!==t)return{messages:[],nextMessageCursor:a.nextCursor};let o=this.#ie(a.messages),s=Kc(this.messages,o);this.messages=this.#gt(s.map(e=>this.#pt(e))),this.#b=a.nextCursor;for(let e of a.messages)this.#O.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#ee(),{messages:o,nextMessageCursor:a.nextCursor}}#ie(e){let t=new Map(this.messages.map(e=>[e.id,e]));return e.map(e=>{let n=t.get(e.id);if(n){if(this.webMcpApprovalResolvers.has(n.id)||n.approval&&fl(n.approval)&&n.approval.id===e.approval?.id&&n.approval.status!==`pending`&&e.approval?.status===`pending`)return n;let t=n.agentMetadata?.executionId,r=[...n.toolCall?[n.toolCall]:[],...n.tools??[]];if(t&&r.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return n}return pl(e)})}async startNewConversation(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=++this.#x,i=await t.prepareStartNew({context:n});if(r!==this.#x)throw i.discard(),new hd(`superseded`,`A later action won`);await this.#ae(i)}async#ae(e){this.#fe(),await this.#le(e),this.#v=e.conversationId||null,this.#y=e.conversationRevision||null,this.#b=null,this.#C=null,this.#w=!1,this.#ue(),this.#ee()}async deleteConversation(e,t){let n=this.#Q(),r=this.#$(t?.scope);await this.awaitHistorySettled(),await n.delete(e,{context:r}),e===this.#v&&await this.#oe(r)}async updateConversation(e,t,n){let r=this.#Q();if(!r.update)throw new hd(`history_unavailable`,`This history provider cannot update conversations`);let i=this.#$(n?.scope);return await this.awaitHistorySettled(),r.update(e,t,{context:i})}canUpdateConversations(){return typeof this.#Z?.update==`function`}async clearConversationHistory(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=await t.deleteAll({...e?.targetId===void 0?{}:{targetId:e.targetId},context:n});return await this.#oe(n),r}async resetHistoryDevice(){let e=this.#Q();if(!e.resetDevice)throw new hd(`history_unavailable`,`This history provider cannot reset the device`);this.#x+=1,this.#D=null;try{return await e.resetDevice()}finally{this.#fe(),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#w=!1,this.#ee()}}async#oe(e){this.#x+=1,this.#D=null,this.#fe(),this.#v=null,this.#y=null,this.#b=null,this.#w=!0,this.#C=null,this.#ee(),await this.#se(e)}async#se(e){let t=this.#Z;if(!t)this.#w=!1,this.#ee();else try{let n=await t.prepareStartNew({context:e});await this.#ae(n)}catch{this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`)}}async#ce(){if(this.#C===`new_conversation_required`&&this.#Z&&(this.#C=null,await this.#se(this.#$()),this.#C===`new_conversation_required`))throw new hd(`new_conversation_required`,`A new conversation is required before sending`)}async#le(e){await e.commit();let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#v=e.conversationId,this.#y=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#S||this.#Y(e)}#ue(){this.#v?this.config.setStoredConversationId?.(this.#v):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#y),this.historyInternals.setStoredMessageCursor?.(this.#b)}#de(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Ge(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#O.clear(),this.#be(null)}#fe(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.messages=[],this.#de(),this.#E.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#ct(!1),this.#st(`idle`),this.callbacks.onMessagesChanged([...this.messages])}#pe(e){this.#x+=1,this.#D=null,this.#w=!0,this.#fe(),this.#v=e.conversationId,this.#y=null,this.#b=null,this.#C=null,this.#ee(),this.#te(`history_continuity_reset`,`This browser was reconnected to a different conversation, so the previous messages were cleared.`),this.#T=Promise.resolve().then(()=>{this.#w=!1,this.#T=null,this.#ee()})}#me(){let e=this.historyInternals.visitorStore??null;e!==this.#N&&(this.#M?.(),this.#M=null,this.#N=e,e&&(this.#M=e.subscribe(e=>this.#he(e))))}#he(e){if(e.source!==`external`||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#x+=1,this.#D=null,this.#P=!0,this.#F=null;let t=this.messages.length>0;t||this.#v!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#fe():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#E.clear(),this.#be(null)),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#ee(),t&&this.#te(`history_continuity_reset`,`This browser's conversation history was reset in another tab, so the previous messages were cleared.`)}#ge(){return this.#P?(this.#F||=this.#_e().finally(()=>{this.#F=null}),this.#F):Promise.resolve()}async#_e(){if(!this.isClientTokenMode())this.#P=!1;else try{this.bindActivatedSession(await this.client.initSession()),this.#P=!1}catch{}}reconcileBootConversation(e){let t=this.#Z,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#v;if(!t||!n)return Promise.resolve();let r=this.#$(e?.scope);this.#w=!0,this.#ee();let i=this.#ve(t,n,r).finally(()=>{this.#w=this.#C!==null,this.#T===i&&(this.#T=null),this.#ee()});return this.#T=i,i}async#ve(e,t,n){this.#v=t;let r=this.clientSession?.conversationRevision??this.#y??null,i=this.#j?this.#A:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#j=!1,this.#b=this.historyInternals.getStoredMessageCursor?.()??this.#b,await this.replayPendingProjections(),r&&i&&r===i){this.#y=r;return}let a=await e.getPage(t,{context:n}),o=this.#ie(a.messages),s=new Set(a.messages.map(e=>e.id)),c=this.messages.some(e=>s.has(e.id)),l=a.messages[0]?.createdAt,u;if(!c)u=o.map(e=>this.#pt(e));else{let e=this.#r?this.#i:null;u=Kc(this.messages.filter(t=>s.has(t.id)||t.id===e?!0:l!==void 0&&t.createdAt<l),o).map(e=>this.#pt(e))}this.#b=a.nextCursor,this.#y=a.conversationRevision||r||null,this.#O.clear();for(let e of a.messages)this.#O.set(e.id,e.content);this.#ue(),this.messages=this.#gt(u),this.callbacks.onMessagesChanged([...this.messages])}#ye(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#be(e){this.#k=e,this.historyInternals.setPendingDisplayProjections?.(e)}#xe(){return this.historyInternals.getPendingDisplayProjections?.()??this.#k}#Se(e){if(this.#ye())for(let t of e){let e=Gc(t);e!==void 0&&this.#O.set(t.id,e)}}#Ce(){if(!this.#ye())return;let e=this.#v;if(!e)return;let t=[];for(let e of this.messages){if(e.role!==`assistant`||e.streaming)continue;let n=Gc(e);n!==void 0&&this.#O.get(e.id)!==n&&t.push({id:e.id,displayContent:n})}t.length!==0&&(this.#be({conversationId:e,messageIds:t.map(e=>e.id)}),this.#we(e,t))}#we(e,t){let n=(this.#D??Promise.resolve()).catch(()=>{}).then(()=>this.#Te(e,t,!1)).finally(()=>{this.#D===n&&(this.#D=null)});this.#D=n}async#Te(e,t,n){if(this.#v!==e)return;let r=t.filter(e=>this.#O.get(e.id)!==e.displayContent);if(r.length===0)this.#De(e,t);else try{let{conversationRevision:n}=await this.client.finalizeDisplayProjections(e,r);for(let e of r)this.#O.set(e.id,e.displayContent);this.#v===e&&n&&(this.#y=n),this.#De(e,t)}catch(i){if(!n&&this.#Ee(i)){await this.#Te(e,r,!0);return}if(i instanceof yu&&(i.code===`not_found`||i.code===`conversation_deleted`)){this.#De(e,t);return}this.#te(`projection_finalization_failed`,`Some message formatting could not be saved for history; it will be retried.`)}}#Ee(e){return e instanceof yu?e.code===`request_failed`:e instanceof Error}#De(e,t){let n=this.#xe();if(!n||n.conversationId!==e)return;let r=new Set(t.map(e=>e.id)),i=n.messageIds.filter(e=>!r.has(e));this.#be(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#ye())return;let e=this.#xe();if(!e)return;if(this.#v&&e.conversationId!==this.#v){this.#be(null);return}let t=[];for(let n of e.messageIds){let e=this.messages.find(e=>e.id===n);e&&typeof e.content==`string`&&t.push({id:n,displayContent:e.content})}t.length===0?this.#be(null):(this.#we(e.conversationId,t),await this.#D?.catch(()=>{}))}#Oe(){this.#v&&(this.#y=null,this.historyInternals.setStoredConversationRevision?.(null))}async#ke(){await this.awaitHistorySettled(),await this.#ge(),this.#C===`new_conversation_required`&&await this.#ce()}static#Ae(e){return e instanceof yu&&e.code===`conversation_deleted`}async#je(t,n,r,i,a){this.#Se(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},this.handleEvent);return}catch(t){if(!e.#Ae(t))throw t;let o=await this.#Me(i);if(!o)throw t;this.#Se([o]),await this.client.dispatch({messages:[o],signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},this.handleEvent)}}async#Me(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let n={...t};this.#x+=1,this.#D=null,this.#fe(),this.#v=null,this.#y=null,this.#b=null,this.#S=!0;try{let e=this.#Z;if(e){let t=await e.prepareStartNew({context:this.#$()});await this.#ae(t)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`),null}finally{this.#S=!1}return this.#ft(n),this.#ct(!0),this.#te(`conversation_deleted_recovered`,`That conversation was deleted. Started a new conversation.`),this.messages.find(e=>e.id===n.id)??n}updateConfig(e){let t=this.config.features?.artifacts?.display,n={...this.config,...e},r=kl(this.config,n),i=md(this.config,n);this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&Al(n.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(n.features?.artifacts?.display);if(!i){this.client.updateConfig(n),a&&this.#We();return}this.#He(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.client=new Eu(this.config,this.historyInternals),a&&this.#We(),this.#Fe(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:n,llmContent:r,contentParts:i,id:a,createdAt:o,sequence:s,streaming:c=!1,voiceProcessing:l,voiceCaption:u,rawContent:d}=e,f={id:a??(t===`user`?qs():t===`assistant`?Js():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:n,createdAt:o??(/* @__PURE__ */ new Date()).toISOString(),sequence:s??this.#mt(),streaming:c,...r!==void 0&&{llmContent:r},...i!==void 0&&{contentParts:i},...l!==void 0&&{voiceProcessing:l},...u&&{voiceCaption:u},...d!==void 0&&{rawContent:d}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:`assistant`})}injectUserMessage(e){return this.injectMessage({...e,role:`user`})}injectSystemMessage(e){return this.injectMessage({...e,role:`system`})}injectMessageBatch(e){let t=[];for(let n of e){let{role:e,content:r,llmContent:i,contentParts:a,id:o,createdAt:s,sequence:c,streaming:l=!1,voiceProcessing:u,rawContent:d}=n,f={id:o??(e===`user`?qs():e===`assistant`?Js():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:e,content:r,createdAt:s??(/* @__PURE__ */ new Date()).toISOString(),sequence:c??this.#mt(),streaming:l,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a},...u!==void 0&&{voiceProcessing:u},...d!==void 0&&{rawContent:d}};t.push(f)}return this.messages=this.#gt([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:r=``,llmContent:i,id:a,createdAt:o,sequence:s}=e,c={text:r,component:t,props:n};return this.injectMessage({role:`assistant`,content:r,rawContent:JSON.stringify(c),...i!==void 0&&{llmContent:i},...a!==void 0&&{id:a},...o!==void 0&&{createdAt:o},...s!==void 0&&{sequence:s}})}async#Ne(e,t,n){let r;try{r=await n()}catch{return}let i=r.blocks.join(`
|
|
19
19
|
|
|
20
20
|
`),a=[i,t].filter(Boolean).join(`
|
|
21
21
|
|
|
22
|
-
`),o=Array.isArray(e.contentParts)&&e.contentParts.length>0,s=r.contentParts.length>0;if(o){let t=[];i&&t.push(Ro(i)),t.push(...r.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(s){let t=[];a&&t.push(Ro(a)),t.push(...r.contentParts),e.contentParts=t}else i&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,t){let n=e.trim(),r=!!t?.replayFields&&(t.replayFields.llmContent!==void 0||t.replayFields.rawContent!==void 0||(t.replayFields.contextMentions?.length??0)>0);if(!n&&(!t?.contentParts||t.contentParts.length===0)&&(!t?.mentions||t.mentions.refs.length===0)&&!r)return;this.#U&&!t?.voiceTurn&&(this.#U.failed=!0,this.#U=null),(this.#T||this.#D||this.#w||this.#P)&&await this.#Oe(),this.stopSpeaking(),this.abortController?.abort(),this.#Ve(),this.#Ie++,this.#et();let i=t?.voiceTurn?.userMessageId,a=i?this.messages.find(e=>e.id===i&&e.role===`user`):void 0,o=a?.id??cu(),s=lu();this.#i=null;let c=t?.contentParts&&Io(t.contentParts)?Yo:``,l={id:o,role:`user`,content:n||c,createdAt:(/* @__PURE__ */ new Date()).toISOString(),sequence:this.#ut(),viaVoice:t?.viaVoice||!1,...t?.contentParts&&t.contentParts.length>0&&{contentParts:t.contentParts},...t?.mentions&&t.mentions.refs.length>0&&{contextMentions:t.mentions.refs},...t?.contentSegments&&t.contentSegments.length>0&&{contentSegments:t.contentSegments},...t?.composerOptions&&{composerOptions:t.composerOptions},...t?.replayFields??{}};a?(a.viaVoice=!0,delete a.voiceCaption,a.content.trim()!==n&&(a.llmContent=n),this.callbacks.onMessagesChanged([...this.messages])):this.#ct(l),this.#it(!0);let u=new AbortController;if(this.abortController=u,t?.mentions){let e=this.messages.find(e=>e.id===o)??l;if(await this.#Me(e,n,t.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(t?.quote&&!t.replayFields){let e=this.messages.find(e=>e.id===o)??l,n=ku({quote:t.quote,text:e.llmContent??e.content,contentParts:e.contentParts});n.contentParts&&(e.contentParts=n.contentParts),n.llmContent!==void 0&&(e.llmContent=n.llmContent),(n.contentParts||n.llmContent!==void 0)&&(e.quote={...t.quote},this.callbacks.onMessagesChanged([...this.messages]))}let d=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:(/* @__PURE__ */ new Date()).toISOString()}]:[...this.messages];try{await this.#Ae(d,u,s,o,{composerOptions:t?.composerOptions,interrupt:t?.interrupt,voiceSpoken:!!t?.voiceTurn})}catch(e){if(this.status===`resuming`||this.#a)return;this.#U&&(this.#U.failed=!0);let t=e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`abort`));if(!t){let t=ud(e,this.config.errorMessage);if(t){let e={id:s,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:t,sequence:this.#ut()};this.#ct(e)}}this.#rt(`idle`),this.#it(!1),this.abortController=null,t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(Error(String(e))))}}resubmitFrom(e,t){let n=ju(this.messages,e);if(!n)return!1;let r=this.messages[n.start],i=t.replacement,a=i?i.text:r.content,o=i?i.contentParts:r.contentParts;if(!(a?.trim()||(o?.length??0)>0||!i&&(r.llmContent?.trim()?.length??0)>0))return!1;let s=i?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},c=i?this.#Ne(i.options):r.composerOptions,l=i?i.contentSegments:r.contentSegments,u=i?i.options?.quote:void 0,d=i?i.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(a??``,{...o?.length?{contentParts:[...o]}:{},...l?.length?{contentSegments:[...l]}:{},...c?{composerOptions:c}:{},...u?{quote:u}:{},...s&&Object.keys(s).length>0?{replayFields:s}:{},viaVoice:d===!0}),!0}#Ne(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}async continueConversation(){if(this.streaming)return;(this.#T||this.#D||this.#w||this.#P)&&await this.#Oe(),this.abortController?.abort(),this.#et();let e=lu();this.#i=null,this.#it(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(t){if(this.status===`resuming`||this.#a)return;let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));if(!n){let n=ud(t,this.config.errorMessage);if(n){let t={id:e,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:n,sequence:this.#ut()};this.#ct(t)}}this.#rt(`idle`),this.#it(!1),this.abortController=null,n||(t instanceof Error?this.callbacks.onError?.(t):this.callbacks.onError?.(Error(String(t))))}}async connectStream(e,t){if(this.streaming&&!t?.allowReentry)return;t?.allowReentry||this.abortController?.abort(),t?.preserveAssistantId&&t.assistantMessageId&&(this.#i=t.assistantMessageId);let n=t?.preserveAssistantId?t.assistantMessageId:void 0,r=!1;for(let e of this.messages)e.streaming&&e.id!==n&&(e.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#it(!0);let i={};try{await this.client.processStream(e,e=>{let t=this.#t;this.#t=i;try{this.handleEvent(e)}finally{this.#t=t}},t?.assistantMessageId,t?.seedContent),this.#at(i)}catch(e){if(this.status===`resuming`||this.#a){this.#ot(i);return}this.#at(i),this.#rt(`error`),this.webMcpResolveControllers.size===0&&(this.#it(!1),this.abortController=null),this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))}}#Pe(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}if(e.signal?.aborted)return Promise.resolve(!1);let t={id:`webmcp-${++this.#d}`,status:`pending`,agentId:``,executionId:``,toolName:e.toolName,toolType:`webmcp`,description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},n=`approval-${t.id}`;return this.upsertMessage({id:n,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,approval:t}),new Promise(t=>{this.webMcpApprovalResolvers.set(n,t),e.signal?.addEventListener(`abort`,()=>this.resolveWebMcpApproval(n,`timeout`),{once:!0})})}resolveWebMcpApproval(e,t){let n=this.webMcpApprovalResolvers.get(e);if(!n)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(t=>t.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:t,resolvedAt:Date.now()}}),n(t===`approved`)}#Fe;#Ie;#Le(e){let t=this.#Fe??={s:this,setStreaming:e=>this.#it(e),appendMessage:e=>this.#ct(e),nextSequence:()=>this.#ut(),settleApprovalPausedToolCall:e=>this.#st(e),resumeAfter:e=>this.#r?.executionId===e?this.#r.lastEventId:void 0},n=dc();if(n)return e(n,t);let r=this.#Ie;return lc().then(n=>r===this.#Ie?e(n,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))})}resolveApproval(e,t,n){return this.#Le((r,i)=>r.resolveApproval(i,e,t,n))}resolveAskUserQuestion(e,t){return this.#Le((n,r)=>n.resolveAskUserQuestion(r,e,t))}resolveWebMcpToolCall(e){return this.#Le((t,n)=>t.resolveWebMcpToolCall(n,e))}persistAskUserQuestionProgress(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}#Re(e){let t=e.agentMetadata?.executionId,n=e.toolCall?.id;if(!t||!n){let t=this.#u;queueMicrotask(()=>{t===this.#u&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(t);r||(r={snapshots:[],seen:/* @__PURE__ */ new Set},this.webMcpAwaitBatches.set(t,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(e))}#ze(){if(this.webMcpAwaitBatches.size===0)return;let e=this.#u;queueMicrotask(()=>{if(e===this.#u)for(let e of[...this.webMcpAwaitBatches.keys()])this.#Be(e)})}#Be(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:n}=t;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.#Le((t,r)=>t.resolveWebMcpToolCallBatch(r,e,n))}#Ve(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,`denied`);this.webMcpAwaitBatches.clear(),this.#u++}cancel(){this.abortController?.abort(),this.abortController=null,this.#et(),this.#Ve(),this.#Ie++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#it(!1),this.#rt(`idle`)}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#et(),this.#Ve(),this.#Ie++,this.messages=[],this.agentExecution=null,this.#We(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#it(!1),this.#rt(`idle`),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#l}selectArtifact(e){this.#l=e,this.#Ge()}clearArtifacts(){this.#We()}upsertArtifact(e){let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=e.artifactType===`markdown`?{id:t,artifactType:`markdown`,title:e.title,status:`complete`,markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:t,artifactType:`component`,title:e.title,status:`complete`,component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(t,n),this.#l=t,this.#Ge(),e.transcript!==!1&&this.#He(n),n}#He(e){let t=`artifact-ref-${e.id}`,n=Mn(jn(this.config.features?.artifacts,e),{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:`complete`,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown===void 0?{}:{markdown:e.markdown}}),r=this.messages.find(e=>e.id===t);r?(r.rawContent=n,r.streaming=!1,this.callbacks.onMessagesChanged([...this.messages])):this.injectAssistantMessage({id:t,content:``,rawContent:n})}#Ue(){let e=!1;for(let t of this.artifacts.values()){let n=this.messages.find(e=>e.id===`artifact-ref-${t.id}`);if(!n)continue;let r=Mn(jn(this.config.features?.artifacts,t),{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown===void 0?{}:{markdown:t.markdown}});n.rawContent!==r&&(n.rawContent=r,n.streaming=t.status===`streaming`,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#We(){(this.artifacts.size!==0||this.#l!==null)&&(this.artifacts.clear(),this.#l=null,this.#Ge())}#Ge(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#l})}#Ke(e){switch(e.type){case`artifact_start`:e.artifactType===`markdown`?this.artifacts.set(e.id,{id:e.id,artifactType:`markdown`,title:e.title,status:`streaming`,markdown:``,...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:`component`,title:e.title,status:`streaming`,component:e.component??``,props:{}}),this.#l=e.id;break;case`artifact_delta`:{let t=this.artifacts.get(e.id);t?.artifactType===`markdown`&&(t.markdown=(t.markdown??``)+e.artDelta);break}case`artifact_update`:{let t=this.artifacts.get(e.id);t?.artifactType===`component`&&(t.props={...t.props,...e.props},e.component&&(t.component=e.component));break}case`artifact_complete`:{let t=this.artifacts.get(e.id);t&&(t.status=`complete`);break}default:return}this.#Ge()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#et(),this.#Ve(),this.#Ie++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#dt(e.map(e=>({...e,streaming:!1,sequence:e.sequence??this.#ut()}))),this.#it(!1),this.#rt(`idle`),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let t of e)this.artifacts.set(t.id,{...t,status:`complete`});this.#l=t,this.#Ge()}#qe(e){let t=this.agentExecution?.executionId;if(!t||!this.#i||this.agentExecution?.status!==`running`)return;let n=this.#r===null;this.#r={executionId:t,lastEventId:e,assistantMessageId:this.#i,status:`running`},this.#nt(n)}#Je(){return this.#r!==null&&typeof this.config.reconnectStream==`function`&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#Ye()}#Ye(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant===`approval`&&e.approval?.status===`pending`)}#Xe(){this.#a||this.#r&&typeof this.config.reconnectStream==`function`&&(this.#a=!0,this.callbacks.onReconnect?.({phase:`paused`,handle:this.#r}),this.#it(!0),this.#rt(`resuming`),this.#Ze().then(e=>{this.#a&&this.#r&&e.begin()}))}#Ze(){return this.#o?Promise.resolve(this.#o):(this.#s||(this.#s=od().then(({createReconnectController:e})=>{let t=e(this.#Qe());return this.#o=t,t}),this.#s.catch(()=>{this.#s=null})),this.#s)}#Qe(){let e=this;return{get config(){return e.config},getResumable:()=>e.#r,clearResumable:()=>e.#tt(),getStatus:()=>e.status,setStatus:t=>e.#rt(t),setStreaming:t=>e.#it(t),setReconnecting:t=>{e.#a=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,n,r)=>e.connectStream(t,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:t=>e.#ct(t),nextSequence:()=>e.#ut(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>ud(Error(t),e.config.errorMessage),onError:t=>e.callbacks.onError?.(t)}}reconnectNow(){this.#a?this.#o?.wake():this.#Xe()}resumeFromHandle(e){if(typeof this.config.reconnectStream!=`function`||this.#a)return;let t=this.#$e();t||(t=lu(),this.#ct({id:t,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:this.#ut()})),this.#i=t,this.agentExecution||={executionId:e.executionId,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0},this.#r={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:`running`},this.#Xe()}#$e(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role===`assistant`&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role===`user`)break}return null}#et(){this.#a=!1,this.#o?.teardown(),this.#tt()}#tt(){this.#c&&=(clearTimeout(this.#c),null);let e=this.#r!==null;this.#r=null,e&&this.config.onExecutionState?.(null)}#nt(e){let t=this.config.onExecutionState;t&&(e?(this.#c&&=(clearTimeout(this.#c),null),t(this.#r)):this.#c||=setTimeout(()=>{this.#c=null,this.config.onExecutionState?.(this.#r)},500))}getResumableHandle(){return this.#r}#rt(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#it(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&(this.#at(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(e){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider===`browser`||t.provider===`runtype`&&t.browserFallback))return;let n=[...this.messages].reverse().find(e=>e.role===`assistant`&&e.content&&!e.voiceProcessing);if(!n||e&&!e.includes(n.id))return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=Wu(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return Fu(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||t.role!==`assistant`)return;let n=Wu(t.content||``);if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<`u`&&`speechSynthesis`in window&&window.speechSynthesis.cancel()}#at(e){for(let[t,n]of[...this.#e])n===e&&(this.#e.delete(t),this.#st(t))}#ot(e){for(let[t,n]of this.#e)n===e&&this.#e.set(t,void 0)}#st(e){let t=this.messages.find(t=>t.id===e)?.approval,n=t?.toolCallId,r=n&&this.messages.find(e=>e.toolCall?.id===n),i=r&&r.toolCall;if(!i||i.status===`complete`||t.status===`pending`)return;let a={...i,status:`complete`,approvalStatus:t.status,completedAt:Date.now(),...t.status===`approved`?{superseded:!0}:{success:!1,error:t.status===`denied`?`Denied`:`Approval timed out`}};this.upsertMessage({...r,streaming:!1,toolCall:a})}#ct(e){let t=this.#lt(e);this.messages=this.#dt([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#lt(e),n=this.messages.findIndex(e=>e.id===t.id);n===-1?this.#ct(t):(this.messages=this.messages.map((e,r)=>{if(r!==n)return e;let i={...e,...t};e.agentMetadata?.askUserQuestionAnswered===!0&&t.agentMetadata&&(i.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),e.agentMetadata?.suggestRepliesResolved===!0&&t.agentMetadata&&(i.agentMetadata={...i.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let n=e.approval,r=t.approval;i.approval={...n,...r,executionId:r.executionId||n.executionId,toolName:r.toolName||n.toolName,description:r.description||n.description,toolType:r.toolType??n.toolType,reason:r.reason??n.reason,parameters:r.parameters??n.parameters,toolCallId:r.toolCallId??n.toolCallId}}let o=t.toolCall?.name,s=t.agentMetadata?.executionId,c=t.toolCall?.id;if(o&&dd(o)&&s&&c&&t.agentMetadata?.awaitingLocalTool===!0){let t=`${s}:${c}`,n=this.webMcpInflightKeys.has(t),r=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,o=e.agentMetadata?.executionId===s&&e.toolCall?.id===c&&a!==void 0&&dd(a)&&e.toolCall?.status===`complete`;(n||r||o)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=e.toolCall,i.streaming=e.streaming)}return i}),this.messages=this.#dt(this.messages),this.callbacks.onMessagesChanged([...this.messages]))}#lt(e){return e.sequence===void 0?{...e,sequence:this.#ut()}:{...e}}#ut(){return this.#n++}#dt(e){return[...e].sort((e,t)=>{let n=new Date(e.createdAt).getTime(),r=new Date(t.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(r)&&n!==r)return n-r;let i=e.sequence??0,a=t.sequence??0;return i===a?e.id.localeCompare(t.id):i-a})}};Y(),Yt(),mn(),$o();const pd={add:e=>Go(e)},md=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,hd={allowedTypes:Qo,maxFileSize:10485760,maxFiles:4};function gd(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function _d(e){return e===`application/pdf`||e.startsWith(`text/`)||e.includes(`word`)?fe:e.includes(`excel`)||e.includes(`spreadsheet`)?de:e===`application/json`?ue:le}var vd=class e{#e;#t;#n;constructor(e={}){this.attachments=[],this.#e=null,this.#t=/* @__PURE__ */ new Map,this.#n=!1,this.config={allowedTypes:e.allowedTypes??hd.allowedTypes,maxFileSize:e.maxFileSize??hd.maxFileSize,maxFiles:e.maxFiles??hd.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#r(){return typeof this.config.adapter?.add==`function`}#i(){return this.#r()?this.config.adapter:pd}setPreviewsContainer(e){this.#e=e}remountPreviews(e){if(this.#e=e,e){e.innerHTML=``;for(let e of this.attachments)this.#l(e)}this.#f()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:hd.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status===`ready`)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){e&&e.length!==0&&await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#n)return;let t=[];for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,`count`);continue}let e=Ko(n,this.config.allowedTypes,this.config.maxFileSize);if(!e.valid){let t=e.error?.includes(`type`)?`type`:`size`;this.config.onFileRejected?.(n,t);continue}let r={id:gd(),file:n,previewUrl:Uo(n)?URL.createObjectURL(n):null,contentPart:null,status:this.#r()?`uploading`:`processing`,progress:this.#r()?0:void 0};this.attachments.push(r),this.#l(r),t.push(r)}this.#f(),this.#c(),await Promise.all(t.map(e=>this.#a(e)))}async#a(e){let t=new AbortController;this.#t.set(e.id,t);let n=()=>this.#n||t.signal.aborted||this.#t.get(e.id)!==t||!this.attachments.includes(e);try{let r=await this.#i().add(e.file,{signal:t.signal,onProgress:t=>{n()||e.status!==`uploading`||(e.progress=md(t),this.#u(e),this.#c())}});if(n())return;e.contentPart=r,e.status=`ready`,e.progress=void 0,e.error=void 0}catch(t){if(n())return;e.status=`error`,e.progress=void 0,e.error=t instanceof Error?t.message:String(t??`Upload failed`)}finally{this.#t.get(e.id)===t&&this.#t.delete(e.id)}this.#u(e),this.#c()}retryAttachment(e){let t=this.attachments.find(t=>t.id===e);!t||t.status!==`error`||this.#n||(t.status=this.#r()?`uploading`:`processing`,t.progress=this.#r()?0:void 0,t.error=void 0,this.#u(t),this.#c(),this.#a(t))}#o(e){let t=this.#t.get(e);t&&(this.#t.delete(e),t.abort())}removeAttachment(e){let t=this.attachments.findIndex(t=>t.id===e);if(t===-1)return;let n=this.attachments[t];this.#o(e),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let r=this.#e?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),n.status===`ready`&&n.contentPart&&this.#s(n.contentPart),this.#f(),this.#c()}#s(e){let t=this.config.adapter?.remove;if(t)try{let n=t(e,{signal:new AbortController().signal});n&&typeof n.catch==`function`&&n.catch(e=>{console.error(`[AttachmentManager] adapter.remove failed:`,e)})}catch(e){console.error(`[AttachmentManager] adapter.remove failed:`,e)}}clearAttachments(){for(let e of this.attachments)this.#o(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=``),this.#f(),this.#c()}destroy(){if(!this.#n){this.#n=!0;for(let e of this.#t.values())e.abort();this.#t.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#e=null}}#c(){this.#n||this.config.onAttachmentsChange?.(this.getAttachments())}#l(e){if(!this.#e)return;let t=Uo(e.file),n=q(`div`,`persona-attachment-preview persona-relative persona-inline-block`);if(n.setAttribute(`data-attachment-id`,e.id),n.style.width=`48px`,n.style.height=`48px`,t&&e.previewUrl){let t=q(`img`);t.src=e.previewUrl,t.alt=e.file.name,t.className=`persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200`,t.style.width=`48px`,t.style.height=`48px`,t.style.objectFit=`cover`,t.style.borderRadius=`8px`,n.appendChild(t)}else{let t=q(`div`);t.style.width=`48px`,t.style.height=`48px`,t.style.borderRadius=`8px`,t.style.backgroundColor=`var(--persona-container, #f3f4f6)`,t.style.border=`1px solid var(--persona-border, #e5e7eb)`,t.style.display=`flex`,t.style.flexDirection=`column`,t.style.alignItems=`center`,t.style.justifyContent=`center`,t.style.gap=`2px`,t.style.overflow=`hidden`;let r=_d(e.file.type),i=Jt(r,20,`var(--persona-muted, #6b7280)`,1.5);i&&t.appendChild(i);let a=q(`span`);a.textContent=Jo(e.file.type,e.file.name),a.style.fontSize=`8px`,a.style.fontWeight=`600`,a.style.color=`var(--persona-muted, #6b7280)`,a.style.textTransform=`uppercase`,a.style.lineHeight=`1`,t.appendChild(a),n.appendChild(t)}let r=J(`div`,{className:`persona-attachment-status`,attrs:{"data-persona-attachment-status":``}}),i=q(`div`,`persona-attachment-progress`);i.appendChild(q(`div`,`persona-attachment-progress__bar`));let a=J(`button`,{className:`persona-attachment-retry`,attrs:{type:`button`,"aria-label":`Retry upload`}}),o=K(`rotate-cw`,12,`var(--persona-text-inverse, #ffffff)`,2);o?a.appendChild(o):a.textContent=`↻`,a.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.retryAttachment(e.id)}),r.append(i,a),n.appendChild(r);let s=q(`button`,`persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center`);s.type=`button`,s.setAttribute(`aria-label`,`Remove attachment`),s.style.position=`absolute`,s.style.top=`-4px`,s.style.insetInlineEnd=`-4px`,s.style.width=`18px`,s.style.height=`18px`,s.style.borderRadius=`50%`,s.style.backgroundColor=`var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))`,s.style.border=`none`,s.style.cursor=`pointer`,s.style.display=`flex`,s.style.alignItems=`center`,s.style.justifyContent=`center`,s.style.padding=`0`;let c=Jt(Tt,10,`var(--persona-text-inverse, #ffffff)`,2);c?s.appendChild(c):(s.textContent=`×`,s.style.color=`var(--persona-text-inverse, #ffffff)`,s.style.fontSize=`14px`,s.style.lineHeight=`1`),s.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.removeAttachment(e.id)}),n.appendChild(s),this.#e.appendChild(n),this.#d(n,e)}#u(e){let t=this.#e?.querySelector(`[data-attachment-id="${e.id}"]`);t&&this.#d(t,e)}#d(e,t){e.dataset.status=t.status;let n=t.status!==`ready`&&t.status!==`error`;e.setAttribute(`aria-busy`,n?`true`:`false`),e.title=t.status===`error`?`${t.file.name}: ${t.error??`Upload failed`}`:t.file.name;let r=e.querySelector(`.persona-attachment-progress__bar`);if(r){let e=t.progress;r.style.width=typeof e==`number`?`${Math.round(e*100)}%`:``}}#f(){this.#e&&(this.#e.style.display=this.attachments.length>0?`flex`:`none`)}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n,adapter:t?.adapter})}};const yd=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),bd=(e,t)=>e.length===t.length&&e.every((e,n)=>{let r=t[n];return e.id===r.id&&e.name===r.name&&e.mimeType===r.mimeType&&e.size===r.size&&e.status===r.status&&e.progress===r.progress&&e.error===r.error});function xd(){let e={text:``,attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=/* @__PURE__ */ new Set,n=null,r=!1,i=!1,a=()=>e.preparing?`preparing`:e.streaming?`streaming`:`idle`,o=()=>{let t=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(e=>Object.freeze({...e}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:t,inputDisabled:e.inputDisabled,sendDisabled:t!==`idle`||e.sendDisabled||e.inputDisabled})},s=()=>(n||=o(),n),c=()=>{if(r=!1,i||t.size===0)return;let e=s();for(let n of[...t])try{n(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] composer state listener failed:`,e)}},l=()=>{n=null,!(i||r)&&(r=!0,queueMicrotask(c))};return{getState:s,subscribe:e=>(t.add(e),()=>t.delete(e)),setText:t=>{e.text!==t&&(e.text=t,l())},setAttachments:t=>{bd(e.attachments,t)||(e.attachments=[...t],l())},setMentionRefs:t=>{yd(e.mentionRefs,t)||(e.mentionRefs=[...t],l())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,l())},setActiveModeIds:t=>{yd(e.activeModeIds,t)||(e.activeModeIds=[...t],l())},setQuote:t=>{let n=e.quote;(n?.text!==t?.text||n?.messageId!==t?.messageId||n?.sourceLabel!==t?.sourceLabel)&&(e.quote=t?{...t}:void 0,l())},setPendingSubmission:t=>{e.pendingSubmission!==t&&(e.pendingSubmission=t,l())},setPreparing:t=>{e.preparing!==t&&(e.preparing=t,l())},setStreaming:t=>{e.streaming!==t&&(e.streaming=t,l())},setInputDisabled:t=>{e.inputDisabled!==t&&(e.inputDisabled=t,l())},setSendDisabled:t=>{e.sendDisabled!==t&&(e.sendDisabled=t,l())},flush:()=>{r&&c()},destroy:()=>{i=!0,r=!1,t.clear()}}}Y();const Sd=(e,...t)=>{for(let n of t){let t=e.querySelector(n);if(t)return t}return null},Cd=(e,t)=>{let n=q(`div`,e);return n.setAttribute(t,``),n.setAttribute(`data-persona-composer-synthesized`,``),n.style.display=`contents`,n};function wd(e,t={}){let n=Sd(e,`[data-persona-composer-form]`),r=Sd(e,`[data-persona-composer-input]`);if(!n||!r){let e=`[Persona] composer surface is missing required element(s): ${[!n&&`form`,!r&&`input`].filter(Boolean).join(`, `)}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||r))throw Error(e);return typeof console<`u`&&console.warn(e),null}let i={header:Sd(e,`[data-persona-composer-header]`),body:Sd(e,`[data-persona-composer-body]`),actionsStart:Sd(e,`[data-persona-composer-actions-start]`,`.persona-widget-composer__left-actions`),actionsEnd:Sd(e,`[data-persona-composer-actions-end]`,`.persona-widget-composer__right-actions`),actionsRow:Sd(e,`[data-persona-composer-actions]`,`.persona-widget-composer .persona-flex.persona-items-center.persona-justify-between`),suggestions:Sd(e,`[data-persona-composer-suggestions]`,`.persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2`),status:Sd(e,`[data-persona-composer-status]`)},a=/* @__PURE__ */ new Set,o=i.header;o||(a.add(`header`),o=Cd(`persona-widget-composer__header`,`data-persona-composer-header`),n.parentNode?n.parentNode.insertBefore(o,n):e.appendChild(o));let s=i.body??r.parentElement??n,c=(e,t,n,r,i)=>{if(t)return t;a.add(e);let o=Cd(n,r);return i.appendChild(o),o},l=c(`actionsStart`,i.actionsStart,`persona-widget-composer__left-actions`,`data-persona-composer-actions-start`,n),u=c(`actionsEnd`,i.actionsEnd,`persona-widget-composer__right-actions`,`data-persona-composer-actions-end`,n),d=c(`suggestions`,i.suggestions,`persona-widget-composer__suggestions`,`data-persona-composer-suggestions`,e),f=c(`status`,i.status,`persona-widget-composer__status`,`data-persona-composer-status`,e),p=[],m=(e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler,h=Sd(e,`[data-persona-composer-attachment-input]`,`input[type="file"]`)??void 0;return{footer:e,form:n,input:r,header:o,body:s,actionsStart:l,actionsEnd:u,suggestions:d,status:f,attachmentInput:h,attachmentPreviews:Sd(e,`[data-persona-composer-attachment-previews]`,`.persona-attachment-previews`)??void 0,attachmentButton:Sd(e,`[data-persona-composer-attachment-button]`,`.persona-attachment-button`)??void 0,sendButton:Sd(e,`[data-persona-composer-submit]`)??void 0,micButton:Sd(e,`[data-persona-composer-mic]`)??void 0,synthesized:a,found:i,addListener:(e,t,n,r)=>{e.addEventListener(t,n,r),p.push({target:e,type:t,handler:n,options:r})},removeListener:(e,t,n,r)=>{e.removeEventListener(t,n,r),p=p.filter(r=>!m(r,{target:e,type:t,handler:n}))},destroy:()=>{for(let e of p)e.target.removeEventListener(e.type,e.handler,e.options);p=[]}}}function Td(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Ed(e){let{anchor:t,content:n,placement:r=`bottom-start`,offset:i=6,matchAnchorWidth:a=!1,horizontalOffset:o,verticalOffset:s,zIndex:c=2147483e3,onOpen:l,onDismiss:u}=e,d=e.container??Td(t),f=!1,p=null,m=()=>{if(!f)return;let e=t.getBoundingClientRect();n.style.position=`fixed`,a&&(n.style.minWidth=`${e.width}px`),o&&(n.style.maxWidth=`${e.width}px`);let c=n.getBoundingClientRect(),l=s?.()??null,u=l==null?e.top:e.top+l,d=r===`top-start`||r===`top-end`?u-i-c.height:e.bottom+i,p=r===`bottom-end`||r===`top-end`?e.right-c.width:e.left,m=o?.()??null;if(m!=null){let t=Math.max(e.left,e.right-c.width);p=Math.min(Math.max(e.left+m,e.left),t)}n.style.top=`${d}px`,n.style.left=`${p}px`},h=()=>{f&&(f=!1,p&&=(p(),null),n.remove())},g=()=>{if(f)return;f=!0,c!=null&&(n.style.zIndex=String(c)),d.appendChild(n),m();let e=(t.ownerDocument??document).defaultView??window,r=t.ownerDocument??document,i=()=>{t.isConnected?m():(h(),u?.(`anchor-removed`))},a=e=>{let r=typeof e.composedPath==`function`?e.composedPath():[];r.includes(n)||r.includes(t)||(h(),u?.(`outside`))},o=e.setTimeout(()=>{r.addEventListener(`pointerdown`,a,!0)},0);e.addEventListener(`scroll`,i,!0),e.addEventListener(`resize`,i),p=()=>{e.clearTimeout(o),r.removeEventListener(`pointerdown`,a,!0),e.removeEventListener(`scroll`,i,!0),e.removeEventListener(`resize`,i)},l?.()};return{get isOpen(){return f},open:g,close:h,toggle:()=>f?h():g(),reposition:m,destroy:h}}Y(),mn(),xs();const Dd=[`--persona-components-composer-overflowMenu-background`,`--persona-components-composer-overflowMenu-borderColor`,`--persona-components-composer-overflowMenu-borderRadius`,`--persona-components-composer-overflowMenu-foreground`,`--persona-components-composer-overflowMenu-shadow`],Od=`data-persona-menu-focus`,kd=/* @__PURE__ */ new Set([`ArrowDown`,`ArrowUp`,`Home`,`End`]);function Ad(e){return e.getAttribute(`role`)===`menuitem`?e:e.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`)??e}const jd=e=>e.disabled===!0||e.getAttribute(`aria-disabled`)===`true`;function Md(e){let t=e.label,n=!1,r=q(`div`,`persona-send-button-wrapper`),i=J(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${ds} ${fs}`,attrs:{type:`button`,"aria-haspopup":`menu`,"aria-expanded":`false`,"data-persona-composer-overflow-trigger":``}});r.appendChild(i);let a=J(`div`,{className:`persona-composer-overflow-menu`,attrs:{role:`menu`,tabindex:`-1`,"data-persona-composer-overflow-menu":``}}),o=()=>{let t=e.getButtonSize?.()??``;i.style.width=t,i.style.height=t,i.style.minWidth=t,i.style.minHeight=t,i.style.lineHeight=`1`,i.replaceChildren();let n=K(`plus`,24,`currentColor`,1.5);n?i.appendChild(n):i.textContent=`+`},s=()=>{i.setAttribute(`aria-label`,t),i.setAttribute(`title`,t),a.setAttribute(`aria-label`,t)};s(),o();let c=[],l=-1,u=!1,d=()=>{let e=a.getRootNode().activeElement;return e instanceof HTMLElement?e:null},f=()=>{let e=d();for(let t of c){let n=!!e&&Ad(t)===e;t.toggleAttribute(Od,n&&u)}},p=()=>c.filter(e=>e.isConnected||a.contains(e)).map(Ad).filter(e=>!jd(e)),m=(e,t)=>{e.forEach((e,n)=>{e.setAttribute(`tabindex`,n===t?`0`:`-1`)})},h=e=>{let t=p();if(t.length===0)return;let n=(e%t.length+t.length)%t.length;l=n,m(t,n),t[n].focus(),f()},g=()=>r.ownerDocument??document,_=null,v=null,y=null,b=()=>{_&&=(g().removeEventListener(`focusin`,_,!0),null)},x=()=>{v&&=(a.removeEventListener(`focusin`,v),null),y&&=(a.removeEventListener(`pointerdown`,y,!0),null)},S=null,C=()=>(S||=Ed({anchor:i,content:a,placement:`top-start`,offset:6,onDismiss:()=>{i.setAttribute(`aria-expanded`,`false`),b()}}),S),w=()=>S?.isOpen===!0,T=(e=!1)=>{if(w()){S?.close(),i.setAttribute(`aria-expanded`,`false`),b(),x(),l=-1,u=!1;for(let e of c)e.removeAttribute(Od);e&&i.focus()}},E=(e=0,t=!1)=>{if(n||w())return;u=t,ps(i,a,Dd),C().open(),i.setAttribute(`aria-expanded`,`true`);let o=p();m(o,-1),h(e<0?o.length-1:e),_=e=>{let t=typeof e.composedPath==`function`?e.composedPath():[];t.includes(a)||t.includes(r)||T()},g().addEventListener(`focusin`,_,!0),v=()=>f(),a.addEventListener(`focusin`,v),y=()=>{u=!1},a.addEventListener(`pointerdown`,y,!0)},D=e=>{e.preventDefault(),e.stopPropagation(),w()?T(!0):E(0)},O=e=>{e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),u=!0,w()?h(0):E(0,!0)):e.key===`ArrowUp`&&(e.preventDefault(),u=!0,w()?h(-1):E(-1,!0))},k=e=>{switch(kd.has(e.key)&&(u=!0),e.key){case`ArrowDown`:e.preventDefault(),h(l+1);return;case`ArrowUp`:e.preventDefault(),h(l-1);return;case`Home`:e.preventDefault(),h(0);return;case`End`:e.preventDefault(),h(p().length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),T(!0);return;case`Tab`:T(!0);return}};return i.addEventListener(`click`,D),i.addEventListener(`keydown`,O),a.addEventListener(`keydown`,k),{trigger:r,triggerButton:i,panel:a,setItems:e=>{for(let t of c)e.includes(t)||t.removeAttribute(Od);if(c=[...e],!w())return;let t=p();m(t,Math.min(l,t.length-1)),f()},isOpen:w,open:()=>E(0),close:T,setLabel:e=>{e!==t&&(t=e,s())},applyButtonSize:o,destroy:()=>{n=!0,b(),x(),i.removeEventListener(`click`,D),i.removeEventListener(`keydown`,O),a.removeEventListener(`keydown`,k),S?.destroy(),S=null,r.remove(),a.remove(),c=[]}}}Y(),mn(),Ua(),xs();const Nd={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Pd=`data-persona-composer-action`,Fd=`data-persona-composer-disable-when-streaming`,Id=e=>e===`core:attachment`?`attachments`:e.startsWith(`core:mention`)?`mentions`:null;function Ld(e,t){if(e===void 0)return null;if(typeof e==`number`)return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let r=q(`div`);r.style.position=`absolute`,r.style.visibility=`hidden`,r.style.pointerEvents=`none`,r.style.height=`0`,r.style.width=e,t.appendChild(r);let i=r.getBoundingClientRect().width;return r.remove(),Number.isFinite(i)&&i>0?i:Number.isFinite(n)?n:null}function Rd(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let r=n.getComputedStyle(e),i=(Number.parseFloat(r.paddingLeft)||0)+(Number.parseFloat(r.paddingRight)||0);return Math.max(0,t-i)}const zd=(e,t)=>{e&&typeof console<`u`&&console.warn(t)},Bd=(e,t)=>t.includes(`:`)?t:`${e}:${t}`;function Vd(e){let{debug:t}=e,n=[],r=/* @__PURE__ */ new Map,i=0,a=e=>{let i=r.get(e.id);i?zd(t,`[Persona] composer action "${e.id}" is already contributed by ${Hd(i)}; the ${Hd(e)} copy is ignored.`):(r.set(e.id,e),n.push(e))};for(let t of e.builtIns)a({id:t.id,placement:t.placement,presentation:`bar`,order:t.order,sequence:i++,source:`core`,builtIn:t});let o=(e,n,r)=>{let o=r?Bd(r,e.id):e.id,s=e.order??Nd.custom;e.placement===`end`&&s>=Nd.send&&(zd(t,`[Persona] composer action "${o}" ordered at ${s} would render after send; clamped to ${Nd.send-1}.`),s=Nd.send-1),a({id:o,placement:e.placement,presentation:e.presentation??`bar`,order:s,sequence:i++,source:n,pluginId:r,action:e})};for(let t of e.configActions??[])o(t,`config`);for(let t of e.plugins){if(!t.contributeComposerActions)continue;let n;try{n=t.contributeComposerActions(e.contributionContext)}catch(e){typeof console<`u`&&console.error(`[Persona] plugin "${t.id}" contributeComposerActions failed:`,e);continue}for(let e of n??[])o(e,`plugin`,t.id)}return n.sort((e,t)=>e.order===t.order?e.sequence-t.sequence:e.order-t.order)}const Hd=e=>e.source===`plugin`?`plugin "${e.pluginId}"`:e.source===`config`?`composer.actions`:`a core built-in`,Ud=(e,t,n)=>e===void 0?n:typeof e==`function`?e(t)===!0:e===!0,Wd=e=>e.phase===`streaming`||e.text.trim().length>0||e.attachments.length>0;function Gd(e,t){if(!e||e===`always`)return!0;let n=Wd(t);return e===`when-text`?n:!n}const Kd=e=>e.kind===`custom`,qd=e=>e instanceof HTMLButtonElement?e:e.querySelector(`button`)??e,Jd=e=>{let t=qd(e);return t.getAttribute(`aria-label`)?.trim()||t.getAttribute(`title`)?.trim()||``};function Yd(e){let t=``,n=e=>{if(e.nodeType===Node.TEXT_NODE){t+=e.nodeValue??``;return}if(e.nodeType!==Node.ELEMENT_NODE)return;let r=e;typeof r.matches==`function`&&r.matches(`.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]`)||e.childNodes.forEach(n)};return n(e),t.trim()}const Xd=e=>Yd(e).length===0;function Zd(e){let t=/* @__PURE__ */ new Map,n=[],r=!1,i=()=>e.getButtonSize?.(),a=(e,t)=>{let n=e.button;if(!n)return;n.setAttribute(`role`,`menuitem`),n.setAttribute(`tabindex`,`-1`),n.className=`persona-composer-overflow-menu__item`;for(let e of[`width`,`height`,`minWidth`,`minHeight`,`fontSize`,`color`,`backgroundColor`])n.style[e]=``;n.style.lineHeight=`1`,t.tooltipText?n.setAttribute(`title`,t.tooltipText):n.removeAttribute(`title`),n.replaceChildren();let r=q(`span`,`persona-composer-overflow-menu__icon`);if(t.iconName){let e=K(t.iconName,16,`currentColor`,1.5);e&&r.appendChild(e)}let i=q(`span`,`persona-composer-overflow-menu__label`);i.textContent=t.shortLabel??t.label,n.append(r,i)},o=(e,t)=>{let n=e.button;if(!n)return;if(n.setAttribute(`aria-label`,t.label),t.pressed===void 0?n.removeAttribute(`aria-pressed`):n.setAttribute(`aria-pressed`,t.pressed?`true`:`false`),n.toggleAttribute(Fd,t.disableWhenStreaming===!0),e.mode===`menu`){e.tooltip?.destroy(),e.tooltip=void 0,a(e,t);return}n.removeAttribute(`role`),n.removeAttribute(`tabindex`),n.removeAttribute(`title`);let r=i(),o=!!t.shortLabel;if(n.className=tr(`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button`,ds,fs,o&&`persona-composer-action-button--text persona-gap-1 persona-text-sm`),n.style.width=r&&!o?r:``,n.style.height=r??``,n.style.minWidth=r&&!o?r:``,n.style.minHeight=r??``,n.style.fontSize=o?``:`18px`,n.style.lineHeight=`1`,n.style.color=t.iconColor??``,n.style.backgroundColor=t.backgroundColor??``,n.replaceChildren(),t.iconName){let e=K(t.iconName,24,`currentColor`,1.5);e&&n.appendChild(e)}if(o){let e=q(`span`,`persona-composer-action-button__label`);e.textContent=t.shortLabel,n.appendChild(e)}else n.firstChild||(n.textContent=t.label);e.tooltip?.destroy(),e.tooltip=Ea({anchor:n,trigger:e.element,text:()=>t.tooltipText??t.label,enabled:!!t.tooltipText})},s=(t,n)=>{let r=t.action,i=J(`button`,{attrs:{type:`button`}}),a=i;if(n===`bar`){let e=q(`div`,`persona-send-button-wrapper`);e.appendChild(i),a=e}a.setAttribute(Pd,t.id);let s={resolved:t,element:a,button:i,owned:!0,managed:!0,busy:!1,visible:!0,mode:n},c=t=>{if(t.preventDefault(),t.stopPropagation(),s.busy||i.disabled)return;let n=s.resolved.action;s.mode===`menu`&&p?.close(!0);let r;try{r=n.onSelect(e.actionContext,t)}catch(t){e.reportError(t,{actionId:s.resolved.id});return}r&&typeof r.then==`function`&&(s.busy=!0,i.setAttribute(`aria-busy`,`true`),r.catch(t=>{e.reportError(t,{actionId:s.resolved.id})}).finally(()=>{s.busy=!1,i.removeAttribute(`aria-busy`)}))};return i.addEventListener(`click`,c),s.detach=()=>i.removeEventListener(`click`,c),o(s,r),s},c=t=>{let n=t.action,r;try{r=n.render({...e.actionContext,id:t.id,action:n})}catch(n){return e.reportError(n,{actionId:t.id}),null}return r?.element?(r.element.setAttribute(Pd,t.id),r.element.toggleAttribute(Fd,n.disableWhenStreaming===!0),{resolved:t,element:r.element,owned:!0,managed:!0,destroy:r.destroy,busy:!1,visible:!0,mode:`bar`}):null},l=(e,t)=>{if(e.builtIn){let t=e.builtIn.element;return t?{resolved:e,element:t,owned:!1,managed:e.builtIn.managed===!0,busy:!1,visible:!0,mode:`bar`}:null}let n=e.action;return n?Kd(n)?c(e):s(e,t):null},u=t=>{if(t.detach?.(),t.tooltip?.destroy(),t.detachMenuSlot?.(),t.detachMenuSlot=void 0,t.menuLabel?.remove(),t.menuLabel=void 0,t.menuSlot?.remove(),t.menuSlot=void 0,t.owned){try{t.destroy?.()}catch(n){e.reportError(n,{actionId:t.resolved.id})}t.element.remove()}},d=(e,t)=>{for(let n=0;n<t.length;n++){let r=t[n];if(!r.managed)continue;let i=null;for(let r=n+1;r<t.length;r++){let n=t[r];if(!n.managed&&n.element.parentElement===e){i=n.element;break}}i?(r.element.parentElement!==e||r.element.nextSibling!==i)&&e.insertBefore(r.element,i):e.lastChild!==r.element&&e.appendChild(r.element)}},f=(e,t)=>{if(e.button){e.button.disabled=t;return}if(!e.owned)return;let n=e.element;n.toggleAttribute(`data-disabled`,t),n.setAttribute(`aria-disabled`,t?`true`:`false`);let r=n instanceof HTMLButtonElement||n instanceof HTMLSelectElement||n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?n:n.querySelector(`button, select, input, textarea`);r&&(r.disabled=t)},p=null,m=null,h=null,g=0,_=()=>{let t=e.getOverflow?.();return t?.enabled===!0?t:void 0},v=()=>(p?p.setLabel(e.getOverflowLabel?.()??`More actions`):p=Md({label:e.getOverflowLabel?.()??`More actions`,getButtonSize:i}),p),y=e=>{m!==e&&(h?.disconnect(),m=e,g=Rd(e),typeof ResizeObserver<`u`&&(h=new ResizeObserver(t=>{let n=t[t.length-1]?.contentRect?.width??Rd(e);n!==g&&(g=n,T())}),h.observe(e)))},b=(e,t)=>{let n=Ld(e.collapseAutoActionsBelow,t);if(n===null)return!1;let r=g||Rd(t);return r>0&&r<n},x=(e,t,n)=>{if(!t)return`bar`;if(e.resolved.builtIn){let n=Id(e.resolved.id);return n&&t.includeBuiltIns?.includes(n)?`menu`:`bar`}let r=e.resolved.presentation;return r===`overflow`||r===`auto`&&n?`menu`:`bar`},S=e=>{let t=e.menuSlot;if(!t)return;if(!Xd(e.element)){e.menuLabel?.remove(),e.menuLabel=void 0;return}let n=Jd(e.element);n?(e.menuLabel||=q(`span`,`persona-composer-overflow-menu__label`),e.menuLabel.textContent!==n&&(e.menuLabel.textContent=n),e.menuLabel.parentElement!==t&&t.appendChild(e.menuLabel)):(e.menuLabel?.remove(),e.menuLabel=void 0)},C=(e,n)=>{if(e.mode===n)return e;let r=e.resolved.action;if(r&&!Kd(r)){u(e),t.delete(e.resolved.id);let r=s(e.resolved,n);return t.set(e.resolved.id,r),r}if(n===`menu`){let t=J(`div`,{className:`persona-composer-overflow-menu__slot`,attrs:{role:`none`,[La]:``}});t.appendChild(e.element),Ta(qd(e.element)),e.menuSlot=t;let n=t=>{let n=qd(e.element);if(n.disabled)return;let r=t.target===n||n.contains(t.target);p?.close(!0),r||n.click()};t.addEventListener(`click`,n,!0),e.detachMenuSlot=()=>t.removeEventListener(`click`,n,!0),e.managed=!0,S(e)}else e.detachMenuSlot?.(),e.detachMenuSlot=void 0,e.menuLabel?.remove(),e.menuLabel=void 0,e.menuSlot?.remove(),e.menuSlot=void 0;return e.mode=n,e},w=(e,t)=>{let n=t.map(e=>e.menuSlot??e.element);for(n.forEach((t,n)=>{let r=e.children[n];r!==t&&(r?e.insertBefore(t,r):e.appendChild(t))});e.children.length>n.length;)e.lastElementChild?.remove()},T=()=>{if(r)return;let i=e.getBindings();if(!i)return;let a=e.getState(),o=a.phase===`streaming`,s=_();s&&y(i.footer);let c=s?b(s,i.footer):!1,l={start:[],end:[]},u=[];for(let e of n){let n=t.get(e.id);if(!n)continue;let r=e.action,i=!r||Ud(r.visible,a,!0)&&Gd(r.visibility,a);if(n.visible!==i&&(n.visible=i,!i&&n.managed&&(n.menuSlot??n.element).remove()),i){if(n=C(n,x(n,s,c)),r){let e=Ud(r.disabled,a,!1)||r.disableWhenStreaming===!0&&o;f(n,e),!Kd(r)&&r.pressed!==void 0&&n.button?.setAttribute(`aria-pressed`,r.pressed?`true`:`false`)}n.mode===`menu`?(S(n),u.push(n)):l[e.placement].push(n)}}if(u.length>0){let e=v();w(e.panel,u),e.setItems(u.map(e=>e.menuSlot??e.element)),e.applyButtonSize();let t=Number.isFinite(s?.order)?s?.order:Nd.overflow,n=l.start.findIndex(e=>e.resolved.order>t),r={resolved:{id:`core:overflow`,placement:`start`,presentation:`bar`,order:t,sequence:-1,source:`core`},element:e.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:`bar`};l.start.splice(n<0?l.start.length:n,0,r)}else p&&(p.close(),p.trigger.remove(),p.setItems([]));d(i.actionsStart,l.start),d(i.actionsEnd,l.end)};return{resolve:()=>{if(r)return;let i=Vd(e.collect()),a=new Set(i.map(e=>e.id));for(let[e,n]of t)a.has(e)||(u(n),t.delete(e));for(let e of i){let n=t.get(e.id);if(!n){let n=l(e,`bar`);n&&t.set(e.id,n);continue}let r=n.resolved.action,i=e.action;if(!!r!=!!i||r&&i&&Kd(r)!==Kd(i)||r&&i&&Kd(r)&&Kd(i)&&r.render!==i.render){u(n),t.delete(e.id);let r=l(e,n.mode);r&&t.set(e.id,r)}else n.resolved=e,e.builtIn?(n.managed=e.builtIn.managed===!0||n.mode===`menu`,e.builtIn.element&&n.mode===`bar`&&(n.element=e.builtIn.element)):i&&!Kd(i)?o(n,i):i&&n.element.toggleAttribute(Fd,i.disableWhenStreaming===!0)}n=i,T()},sync:T,getResolved:()=>n,getOverflowMenu:()=>p,destroy:()=>{if(!r){r=!0,h?.disconnect(),h=null,m=null;for(let e of t.values())u(e);t.clear(),p?.destroy(),p=null,n=[]}}}}Y(),mn(),xs();const Qd=[`--persona-components-composer-modelPicker-menuBackground`,`--persona-components-composer-modelPicker-menuBorderRadius`,`--persona-components-composer-modelPicker-rowHoverBackground`,`--persona-components-composer-modelPicker-labelColor`,`--persona-components-composer-modelPicker-descriptionColor`],$d=()=>({wrapper:J(`span`,{className:`persona-composer-model-picker-wrapper`,attrs:{"data-persona-composer-model-picker-wrapper":``}}),chevron:J(`span`,{className:`persona-composer-model-picker-chevron`,attrs:{"aria-hidden":`true`}})});function ef(e){let t=e.label??`Model`,n=e.presentation??`native`,r=null,i=t=>{let n=e.getSelectedModelId();return t.find(e=>e.id===n)??t[0]},a=()=>{let n=J(`select`,{className:`persona-composer-model-picker`,attrs:{"aria-label":t,"data-persona-composer-model-picker":``}}),a=``,o=()=>{let t=e.getModels(),r=t.map(e=>`${e.id}:${e.label}`).join(`|`);r!==a&&(a=r,n.replaceChildren(...t.map(e=>{let t=J(`option`,{attrs:{value:e.id}});return t.textContent=e.label,t}))),n.value=i(t)?.id??``};o(),r=o;let s=()=>{n.value&&e.onSelect(n.value)};n.addEventListener(`change`,s);let c=e=>e.stopPropagation();n.addEventListener(`click`,c);let{wrapper:l,chevron:u}=$d();return l.append(n,u),{element:l,destroy:()=>{r===o&&(r=null),n.removeEventListener(`change`,s),n.removeEventListener(`click`,c)}}},o=()=>{let n=J(`button`,{className:`persona-composer-model-picker persona-composer-model-picker-trigger`,attrs:{type:`button`,"aria-haspopup":`listbox`,"aria-expanded":`false`,"data-persona-composer-model-picker":`popover`}}),a=q(`span`,`persona-composer-model-picker-label`),o=q(`span`,`persona-composer-model-picker-suffix`);n.append(a,o);let s=J(`div`,{className:`persona-composer-model-menu`,attrs:{role:`listbox`,tabindex:`-1`,"aria-label":t,"data-persona-composer-model-menu":``}}),c=/* @__PURE__ */ new Map,l=``,u=null,d=()=>u?.isOpen===!0,f=(e=!1)=>{d()&&(u?.close(),n.setAttribute(`aria-expanded`,`false`),e&&n.focus())},p=e=>{let t=[...c.values()];t.length!==0&&t[(e%t.length+t.length)%t.length].focus()},m=t=>{if(d())return;u||=Ed({anchor:n,content:s,placement:`top-start`,offset:6,onDismiss:()=>n.setAttribute(`aria-expanded`,`false`)}),ps(n,s,Qd),u.open(),n.setAttribute(`aria-expanded`,`true`);let r=[...c.keys()].indexOf(i(e.getModels())?.id??``);p(t??(r>=0?r:0))},h=t=>{f(!0),e.onSelect(t)},g=e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getAttribute(`data-persona-model-option`);t&&h(t)},_=e=>{let t=J(`button`,{className:`persona-composer-model-option`,attrs:{type:`button`,role:`option`,tabindex:`-1`,"aria-selected":`false`,"data-persona-model-option":e.id}});if(e.icon){let n=K(e.icon,16,`currentColor`,1.5);if(n){let e=q(`span`,`persona-composer-model-option-icon`);e.appendChild(n),t.appendChild(e)}}let n=q(`span`,`persona-composer-model-option-body`),r=q(`span`,`persona-composer-model-option-label`);if(r.textContent=e.label,n.appendChild(r),e.description){let t=q(`span`,`persona-composer-model-option-description`);t.textContent=e.description,n.appendChild(t)}t.appendChild(n);let i=q(`span`,`persona-composer-model-option-check`);i.setAttribute(`aria-hidden`,`true`);let a=K(`check`,16,`currentColor`,2);return a&&i.appendChild(a),t.appendChild(i),t.addEventListener(`click`,g),t},v=()=>{let r=e.getModels(),u=r.map(e=>`${e.id}:${e.label}:${e.icon??``}:${e.description??``}`).join(`|`);if(u!==l){l=u;for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),s.replaceChildren(...r.map(e=>{let t=_(e);return c.set(e.id,t),t}))}let d=i(r);for(let[e,t]of c)t.setAttribute(`aria-selected`,String(e===d?.id));a.textContent=d?.label??``;let f=e.getSuffix?.()??``;o.textContent=f,n.setAttribute(`aria-label`,[t,[d?.label,f].filter(Boolean).join(` `)].filter(Boolean).join(`: `))};v(),r=v;let y=e=>{e.preventDefault(),e.stopPropagation(),d()?f(!0):m()},b=e=>{e.key===`ArrowDown`?(e.preventDefault(),d()?p(0):m(0)):e.key===`ArrowUp`&&(e.preventDefault(),d()?p(-1):m(-1))},x=e=>{let t=[...c.values()],n=t.indexOf(e.target?.closest?.(`.persona-composer-model-option`));switch(e.key){case`ArrowDown`:e.preventDefault(),p(n+1);return;case`ArrowUp`:e.preventDefault(),p(n-1);return;case`Home`:e.preventDefault(),p(0);return;case`End`:e.preventDefault(),p(t.length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),f(!0);return;case`Tab`:f(!0);return}};n.addEventListener(`click`,y),n.addEventListener(`keydown`,b),s.addEventListener(`keydown`,x);let{wrapper:S,chevron:C}=$d();return S.append(n,C),{element:S,destroy:()=>{r===v&&(r=null),n.removeEventListener(`click`,y),n.removeEventListener(`keydown`,b),s.removeEventListener(`keydown`,x);for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),u?.destroy(),u=null,s.remove()}}};return{action:{id:`core:model`,kind:`custom`,placement:`end`,order:700,presentation:n===`popover`?`bar`:`auto`,label:t,render:()=>n===`popover`?o():a()},repaint:()=>r?.()}}Y();const tf=`[data-persona-composer-chip-row]`;function nf(e){e.style.display=e.childElementCount>0?`flex`:`none`}function rf(e){let t=e.querySelector(tf);if(t)return t;let n=J(`div`,{className:`persona-composer-chip-row`,attrs:{"data-persona-composer-chip-row":``}});n.style.display=`none`;let r=e.querySelector(`[data-persona-composer-quote], [data-persona-composer-pending]`);return r?.parentElement===e?e.insertBefore(n,r):e.appendChild(n),n}Y(),mn();function af(e){let t=e.row,n=``,r=!1,i=new Set(e.initialIds??[]),a=t=>{let n=J(`span`,{className:`persona-mention-chip persona-composer-mode-chip`,attrs:{"data-persona-composer-mode":t.id}});if(t.iconName){let e=q(`span`,`persona-mention-chip-icon`),r=K(t.iconName,12,`currentColor`,1.5);r&&e.appendChild(r),n.appendChild(e)}let r=q(`span`,`persona-mention-chip-label`);r.textContent=t.shortLabel??t.label,n.appendChild(r);let i=J(`button`,{className:`persona-mention-chip-remove`,attrs:{type:`button`,"aria-label":`Remove ${t.label}`}}),a=K(`x`,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=`×`,i.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation(),e.onRemove(t.id)}),n.appendChild(i),n},o=()=>Array.from(t.querySelectorAll(`:scope > [data-persona-composer-mode]`)),s=e=>{e.setAttribute(`data-persona-chip-exit`,``),e.setAttribute(`aria-hidden`,`true`),e.style.pointerEvents=`none`;let n=()=>{e.remove(),nf(t)},r=t.ownerDocument.defaultView,i=typeof r?.getComputedStyle==`function`?r.getComputedStyle(e).animationName:``;!i||i===`none`?n():(e.addEventListener(`animationend`,n,{once:!0}),e.addEventListener(`animationcancel`,n,{once:!0}))},c=()=>{for(let e of o())e.remove()};return{element:t,render:(e,c)=>{if(r)return;let l=c.filter(t=>e.includes(t.id)),u=l.map(e=>`${e.id}:${e.shortLabel??e.label}`).join(`|`);if(u===n)return;n=u;let d=/* @__PURE__ */ new Map;for(let e of o()){let t=e.getAttribute(`data-persona-composer-mode`);t&&l.some(e=>e.id===t)&&!e.hasAttribute(`data-persona-chip-exit`)?d.set(t,e):e.hasAttribute(`data-persona-chip-exit`)||s(e)}let f=t.firstChild;for(let e of l){let n=d.get(e.id);n||(n=a(e),i.has(e.id)||(n.setAttribute(`data-persona-chip-enter`,``),n.addEventListener(`animationend`,()=>n?.removeAttribute(`data-persona-chip-enter`),{once:!0}))),i.delete(e.id),n!==f&&t.insertBefore(n,f),f=n.nextSibling}nf(t)},destroy:()=>{r=!0,c(),nf(t)}}}const of=e=>`core:mode:${e}`,sf=e=>Math.min(300+e,499),cf=e=>`core:mode-group:${e}`;function lf(e,t){return e?t?.find(t=>t.id===e)?.presentation===`segmented`:!1}function uf(e,t){return e?t?.find(t=>t.id===e)?.chipVisibility===`hidden`:!1}function df(e,t){return e?.length?e.filter(e=>!lf(e.groupId,t)&&!uf(e.groupId,t)):[]}const ff=(e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null;function pf(e,t,n,r){let i=n.find(e=>e.id===t);if(!i)return[...e];let a=e.includes(t),o=new Set(e);if(a)o.delete(t);else{if(ff(i,r)===`single`){let e=n.filter(e=>e.groupId===i.groupId).map(e=>e.id);o=new Set([...o].filter(t=>!e.includes(t)))}o.add(t)}return n.filter(e=>o.has(e.id)).map(e=>e.id)}function mf(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function hf(e,t){return t?.length?t.filter(t=>e.includes(t.id)&&(t.persistence??`sticky`)!==`once`).map(e=>e.id):[]}function gf(e,t){if(t?.length&&e.length!==0)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}Y(),mn();function _f(e){let t=null;return{action:{id:cf(e.groupId),kind:`custom`,placement:`start`,presentation:`bar`,label:e.getGroup()?.label??e.groupId,render:()=>{let n=J(`div`,{className:`persona-composer-segmented`,attrs:{"data-persona-composer-mode-group":e.groupId}}),r=/* @__PURE__ */ new Map,i=``,a=t=>{t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getAttribute(`data-persona-composer-mode`);n&&(e.getActiveIds().includes(n)&&e.getGroup()?.selection===`single`||e.onSelect(n))},o=e=>{let t=J(`button`,{className:`persona-composer-segmented-item`,attrs:{type:`button`,"data-persona-composer-mode":e.id,"aria-label":e.label}});if(e.iconName){let n=K(e.iconName,16,`currentColor`,1.5);n&&t.appendChild(n)}let n=q(`span`,`persona-composer-segmented-label`);return n.textContent=e.shortLabel??e.label,t.appendChild(n),t.addEventListener(`click`,a),t},s=()=>{let t=e.getGroup();t?.label?(n.setAttribute(`role`,`group`),n.setAttribute(`aria-label`,t.label)):(n.removeAttribute(`role`),n.removeAttribute(`aria-label`));let s=e.getModes(),c=s.map(e=>`${e.id}:${e.shortLabel??e.label}:${e.iconName??``}`).join(`|`);if(c!==i){i=c;for(let e of r.values())e.removeEventListener(`click`,a);r.clear();let e=s.map(e=>{let t=o(e);return r.set(e.id,t),t});n.replaceChildren(...e)}let l=e.getActiveIds();for(let[e,t]of r)t.setAttribute(`aria-pressed`,String(l.includes(e)))};return s(),t=s,{element:n,destroy:()=>{t===s&&(t=null);for(let e of r.values())e.removeEventListener(`click`,a);r.clear()}}}},repaint:()=>t?.()}}Y(),mn();function vf(e){let t=J(`div`,{className:`persona-composer-quote`,attrs:{"data-persona-composer-quote":``}});t.style.display=`none`;let n=``,r=!1,i=n=>{let r=q(`span`,`persona-composer-quote-bar`),i=q(`div`,`persona-composer-quote-content`);if(n.sourceLabel){let e=q(`div`,`persona-composer-quote-source`);e.textContent=n.sourceLabel,i.appendChild(e)}let a=J(`div`,{className:`persona-composer-quote-text`,attrs:{"data-persona-composer-quote-text":``}});a.textContent=Au(n.text),i.appendChild(a);let o=J(`button`,{className:`persona-composer-quote-dismiss`,attrs:{type:`button`,"aria-label":e.dismissLabel??`Remove quote`,"data-persona-composer-quote-dismiss":``}}),s=K(`x`,12,`currentColor`,2);s?o.appendChild(s):o.textContent=`×`,o.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(r,i,o)};return{element:t,render:e=>{if(r)return;let a=e?`${e.sourceLabel??``}${e.text}`:``;a!==n&&(n=a,e?(i(e),t.style.display=`flex`):(t.replaceChildren(),t.style.display=`none`))},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}Y(),mn();function yf(e){let t=J(`div`,{className:`persona-composer-pending`,attrs:{"data-persona-composer-pending":``}});t.style.display=`none`;let n,r=!1,i=(e,t,n,r)=>{let i=J(`button`,{className:`persona-composer-pending-action`,attrs:{type:`button`,"aria-label":t,[n]:``}}),a=K(e,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=t,i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},a=e=>{let t=Au(e.text??``,90);if(t)return t;let n=e.contentParts?.length??0;return n>0?n===1?`1 attachment`:`${n} attachments`:(e.mentionRefs?.length??0)>0?e.mentionRefs.map(e=>e.label).join(`, `):`Queued message`};return{element:t,render:o=>{if(r||o===n)return;if(n=o,!o){t.replaceChildren(),t.style.display=`none`;return}let s=q(`span`,`persona-composer-pending-badge`);s.textContent=e.label??`Sends next`;let c=J(`div`,{className:`persona-composer-pending-text`,attrs:{"data-persona-composer-pending-text":``}});c.textContent=a(o),t.replaceChildren(s,c,i(`pencil`,e.editLabel??`Edit queued message`,`data-persona-composer-pending-edit`,e.onEdit),i(`x`,e.removeLabel??`Remove queued message`,`data-persona-composer-pending-remove`,e.onRemove)),t.style.display=`flex`},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}Y();function bf(e){let t=J(`div`,{className:`persona-message-edit`,attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":``}}),n=J(`textarea`,{className:`persona-message-edit-input`,attrs:{rows:`1`,dir:`auto`,"aria-label":`Edit message`,"data-persona-message-edit-input":``}});n.value=e.initialText;let r=()=>{n.style.height=`auto`,n.style.height=`${n.scrollHeight}px`};n.addEventListener(`input`,r);let i=q(`div`,`persona-message-edit-actions`),a=(e,t,n,r)=>{let i=J(`button`,{className:`persona-message-edit-button ${t}`,attrs:{type:`button`,[n]:``},text:e});return i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},o=()=>{let t=n.value.trim();t&&e.onSave(t)};return i.append(a(e.cancelLabel??`Cancel`,`persona-message-edit-cancel`,`data-persona-message-edit-cancel`,e.onCancel),a(e.saveLabel??`Send`,`persona-message-edit-save`,`data-persona-message-edit-save`,o)),n.addEventListener(`keydown`,t=>{t.key===`Escape`?(t.preventDefault(),t.stopPropagation(),e.onCancel()):t.key===`Enter`&&!t.shiftKey&&(t.preventDefault(),o())}),t.append(n,i),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let e=n.value.length;n.setSelectionRange(e,e),r()},destroy:()=>{t.replaceChildren(),t.remove()}}}function xf(e){let t=e.text??``;if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}function Sf(e,t){if(!e||typeof e.text!=`string`)return;let n=new Set(t.mentionSourceIds),r=(e.mentionRefs??[]).filter(e=>n.has(e.sourceId)),i=r.length===(e.mentionRefs?.length??0)&&r.length>0,a=new Set(t.modes.map(e=>e.id)),o=(e.activeModeIds??[]).filter(e=>a.has(e)),s=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...i?{mentionRefs:r}:{},...i&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...s?{selectedModelId:s}:{},...o.length?{activeModeIds:o}:{},...e.quote?.text?{quote:e.quote}:{}}}function Cf(e){let t=e.delay??500,n=null,r=!1,i=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{r||(i(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{r||n===null||(i(),e.write())},cancel:i,destroy:()=>{r=!0,i()}}}function wf(e){return e.wrapped||e.text.includes(`
|
|
23
|
-
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function Tf(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function Ef(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),r=Number.parseFloat(n.lineHeight),i=Number.parseFloat(n.fontSize),a=Number.isFinite(r)&&r>0?r:Number.isFinite(i)&&i>0?i*1.4:0;if(!a)return!1;let o=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-o>a*1.5}function Df(e){e&&(typeof e.requestSubmit==`function`?e.requestSubmit():e.dispatchEvent(new Event(`submit`,{bubbles:!0,cancelable:!0})))}function Of(e){return Object.freeze({text:e.text,contentParts:e.contentParts?Object.freeze([...e.contentParts]):void 0,mentionRefs:Object.freeze([...e.mentionRefs]),contentSegments:e.contentSegments?Object.freeze([...e.contentSegments]):void 0,options:Object.freeze({...e.options}),viaVoice:e.viaVoice})}function kf(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}const Af=e=>typeof e?.then==`function`;function jf(e,t){return t===!1?{status:`canceled`}:(!t||typeof t!=`object`||(typeof t.text==`string`&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options})),{status:`proceed`})}function Mf(e,t,n){let r;try{r=e(Of(t),{signal:n})}catch(e){return{status:`error`,error:e}}return Af(r)?Promise.resolve(r).then(e=>n.aborted?{status:`aborted`}:jf(t,e),e=>n.aborted?{status:`aborted`}:{status:`error`,error:e}):jf(t,r)}const Nf=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?`circle`:`pill`),Pf={background:`semantic.colors.primary`,foreground:`semantic.colors.textInverse`,border:`transparent`,size:`48px`,iconSize:`24px`,borderRadius:`palette.radius.full`,shadow:`0 8px 24px rgba(0,0,0,.16)`,offset:`20px`};No();const Ff=`16px`,If=`transparent`,Lf={colors:{primary:{50:`#ffffff`,100:`#f5f5f5`,200:`#d4d4d4`,300:`#a3a3a3`,400:`#737373`,500:`#171717`,600:`#0f0f0f`,700:`#0a0a0a`,800:`#050505`,900:`#030303`,950:`#000000`},secondary:{50:`#f5f3ff`,100:`#ede9fe`,200:`#ddd6fe`,300:`#c4b5fd`,400:`#a78bfa`,500:`#8b5cf6`,600:`#7c3aed`,700:`#6d28d9`,800:`#5b21b6`,900:`#4c1d95`,950:`#2e1065`},accent:{50:`#ecfeff`,100:`#cffafe`,200:`#a5f3fc`,300:`#67e8f9`,400:`#22d3ee`,500:`#06b6d4`,600:`#0891b2`,700:`#0e7490`,800:`#155e75`,900:`#164e63`,950:`#083344`},gray:{50:`#f9fafb`,100:`#f3f4f6`,200:`#e5e7eb`,300:`#d1d5db`,400:`#9ca3af`,500:`#6b7280`,600:`#4b5563`,700:`#374151`,800:`#1f2937`,900:`#111827`,950:`#030712`},success:{50:`#f0fdf4`,100:`#dcfce7`,200:`#bbf7d0`,300:`#86efac`,400:`#4ade80`,500:`#22c55e`,600:`#16a34a`,700:`#15803d`,800:`#166534`,900:`#14532d`},warning:{50:`#fefce8`,100:`#fef9c3`,200:`#fef08a`,300:`#fde047`,400:`#facc15`,500:`#eab308`,600:`#ca8a04`,700:`#a16207`,800:`#854d0e`,900:`#713f12`},error:{50:`#fef2f2`,100:`#fee2e2`,200:`#fecaca`,300:`#fca5a5`,400:`#f87171`,500:`#ef4444`,600:`#dc2626`,700:`#b91c1c`,800:`#991b1b`,900:`#7f1d1d`},info:{50:`#eff6ff`,100:`#dbeafe`,200:`#bfdbfe`,300:`#93c5fd`,400:`#60a5fa`,500:`#3b82f6`,600:`#2563eb`,700:`#1d4ed8`,800:`#1e40af`,900:`#1e3a8a`,950:`#172554`},purple:{50:`#faf5ff`,100:`#f3e8ff`,200:`#e9d5ff`,300:`#d8b4fe`,400:`#c084fc`,500:`#a855f7`,600:`#9333ea`,700:`#7e22ce`,800:`#6b21a8`,900:`#581c87`,950:`#3b0764`},teal:{50:`#f0fdfa`,100:`#ccfbf1`,200:`#99f6e4`,300:`#5eead4`,400:`#2dd4bf`,500:`#14b8a6`,600:`#0d9488`,700:`#0f766e`,800:`#115e59`,900:`#134e4a`,950:`#042f2e`}},spacing:(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?`0px`:`${t/4}rem`;return e})(),typography:{fontFamily:{sans:`system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`,serif:`Georgia, Cambria, "Times New Roman", Times, serif`,mono:`ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace`},fontSize:{xs:`0.75rem`,sm:`0.875rem`,base:`1rem`,lg:`1.125rem`,xl:`1.25rem`,"2xl":`1.5rem`,"3xl":`1.875rem`,"4xl":`2.25rem`},fontWeight:{normal:`400`,medium:`500`,semibold:`600`,bold:`700`},lineHeight:{tight:`1.25`,normal:`1.5`,relaxed:`1.625`}},shadows:{none:`none`,sm:`0 1px 2px 0 rgb(0 0 0 / 0.05)`,md:`0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)`,lg:`0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)`,xl:`0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)`,"2xl":`0 25px 50px -12px rgb(0 0 0 / 0.25)`},borders:{none:`none`,sm:`1px solid`,md:`2px solid`,lg:`4px solid`},radius:{none:`0px`,sm:`0.125rem`,md:`0.375rem`,lg:`0.5rem`,xl:`0.75rem`,"2xl":`1rem`,full:`9999px`}},Rf={colors:{primary:`palette.colors.primary.500`,secondary:`palette.colors.secondary.500`,accent:`palette.colors.primary.600`,surface:`palette.colors.gray.50`,background:`palette.colors.gray.50`,container:`palette.colors.gray.50`,text:`palette.colors.gray.900`,textMuted:`palette.colors.gray.500`,textInverse:`palette.colors.gray.50`,border:`palette.colors.gray.200`,divider:`palette.colors.gray.200`,interactive:{default:`palette.colors.primary.600`,hover:`palette.colors.primary.700`,focus:`palette.colors.primary.600`,active:`palette.colors.primary.600`,disabled:`palette.colors.gray.300`},feedback:{success:`palette.colors.success.500`,warning:`palette.colors.warning.500`,error:`palette.colors.error.500`,info:`palette.colors.info.500`}},spacing:{xs:`palette.spacing.1`,sm:`palette.spacing.2`,md:`palette.spacing.4`,lg:`palette.spacing.6`,xl:`palette.spacing.8`,"2xl":`palette.spacing.10`},typography:{fontFamily:`palette.typography.fontFamily.sans`,fontSize:`palette.typography.fontSize.base`,fontWeight:`palette.typography.fontWeight.normal`,lineHeight:`palette.typography.lineHeight.normal`}},zf={button:{primary:{background:`palette.colors.primary.500`,foreground:`palette.colors.primary.50`,borderRadius:`palette.radius.lg`,padding:`semantic.spacing.md`},secondary:{background:`semantic.colors.surface`,foreground:`semantic.colors.secondary`,borderRadius:`palette.radius.lg`,padding:`semantic.spacing.md`},ghost:{background:`transparent`,foreground:`semantic.colors.text`,borderRadius:`palette.radius.md`,padding:`semantic.spacing.sm`,hoverBackground:`rgba(0, 0, 0, 0.05)`}},input:{background:`semantic.colors.surface`,placeholder:`semantic.colors.textMuted`,borderRadius:`palette.radius.lg`,padding:`semantic.spacing.md`,focus:{border:`palette.colors.gray.400`,ring:`palette.colors.gray.400`}},launcher:{background:`semantic.colors.surface`,foreground:`semantic.colors.primary`,border:`semantic.colors.border`,size:`60px`,iconSize:`28px`,borderRadius:`palette.radius.full`,shadow:`palette.shadows.lg`},panel:{width:xo,maxWidth:`none`,height:`min(640px, max(200px, calc(100vh - 64px)))`,maxHeight:`none`,borderRadius:`palette.radius.xl`,shadow:`palette.shadows.xl`,inset:Ff,canvasBackground:If,modes:{floating:{border:`1px solid var(--persona-border)`,shadow:`palette.shadows.xl`,borderRadius:`palette.radius.xl`},inline:{border:`1px solid var(--persona-border)`,shadow:`none`,borderRadius:`palette.radius.xl`},docked:{border:`none`,shadow:`none`,borderRadius:`palette.radius.xl`},sidebar:{border:`none`,borderRadius:`0`},mobile:{border:`none`,shadow:`none`,borderRadius:`0`}}},header:{background:`palette.colors.primary.500`,foreground:`palette.colors.primary.50`,borderRadius:`palette.radius.xl palette.radius.xl 0 0`,padding:`20px 24px`,minimalPadding:`16px 24px`,iconBackground:`palette.colors.primary.600`,iconForeground:`palette.colors.primary.50`},message:{gap:`12px`,user:{background:`palette.colors.primary.500`,text:`palette.colors.primary.50`,borderRadius:`palette.radius.lg`,shadow:`palette.shadows.sm`},assistant:{background:`semantic.colors.container`,text:`semantic.colors.text`,borderRadius:`palette.radius.lg`,border:`semantic.colors.border`,shadow:`palette.shadows.sm`},border:`semantic.colors.border`},introCard:{background:`transparent`,borderRadius:`palette.radius.2xl`,padding:`semantic.spacing.lg`,shadow:`palette.shadows.none`},suggestion:{chip:{background:`semantic.colors.surface`,foreground:`semantic.colors.text`,border:`semantic.colors.border`,borderRadius:`palette.radius.full`,padding:`0.5rem 0.875rem`,gap:`0.5rem`,itemGap:`8px`,minHeight:`36px`,fontSize:`0.8125rem`,lineHeight:`1.25`,iconSize:`16px`,hoverBackground:`palette.colors.gray.100`,hoverBorder:`palette.colors.gray.300`,pressedBackground:`palette.colors.gray.200`,focusRing:`semantic.colors.interactive.focus`,disabledOpacity:`0.5`},card:{background:`semantic.colors.surface`,foreground:`semantic.colors.text`,border:`semantic.colors.border`,borderRadius:`palette.radius.xl`,padding:`1rem`,shadow:`palette.shadows.sm`,gap:`0.625rem`,itemGap:`8px`,minHeight:`72px`,fontSize:`0.875rem`,lineHeight:`1.35`,iconSize:`18px`,hoverBackground:`palette.colors.gray.100`,hoverBorder:`palette.colors.gray.300`,pressedBackground:`palette.colors.gray.200`,focusRing:`semantic.colors.interactive.focus`,disabledOpacity:`0.5`},list:{background:`transparent`,foreground:`semantic.colors.text`,border:`semantic.colors.border`,borderRadius:`palette.radius.md`,padding:`0.75rem`,gap:`0.625rem`,itemGap:`8px`,minHeight:`44px`,fontSize:`0.875rem`,lineHeight:`1.35`,iconSize:`17px`,hoverBackground:`palette.colors.gray.100`,hoverBorder:`palette.colors.gray.300`,pressedBackground:`palette.colors.gray.200`,focusRing:`semantic.colors.interactive.focus`,disabledOpacity:`0.5`}},toolBubble:{shadow:`palette.shadows.sm`},reasoningBubble:{shadow:`palette.shadows.sm`},composer:{shadow:`palette.shadows.none`},scrollbar:{thumb:`semantic.colors.border`,track:`transparent`},markdown:{inlineCode:{background:`palette.colors.gray.50`,foreground:`palette.colors.gray.900`},link:{foreground:`palette.colors.primary.600`},prose:{fontFamily:`inherit`},codeBlock:{background:`semantic.colors.container`,borderColor:`semantic.colors.border`,textColor:`inherit`,borderRadius:`palette.radius.md`},table:{headerBackground:`semantic.colors.container`,borderColor:`semantic.colors.border`},hr:{color:`semantic.colors.divider`},blockquote:{borderColor:`palette.colors.gray.900`,background:`transparent`,textColor:`palette.colors.gray.500`}},collapsibleWidget:{container:`palette.colors.gray.50`,surface:`semantic.colors.surface`,border:`semantic.colors.border`},voice:{recording:{indicator:`palette.colors.error.500`,background:`palette.colors.error.50`,border:`palette.colors.error.200`},processing:{icon:`palette.colors.primary.500`,background:`palette.colors.primary.50`},speaking:{icon:`palette.colors.success.500`}},approval:{requested:{background:`semantic.colors.surface`,border:`semantic.colors.border`,text:`palette.colors.gray.900`,shadow:`0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)`},approve:{background:`semantic.colors.primary`,foreground:`semantic.colors.textInverse`,borderRadius:`palette.radius.md`,padding:`semantic.spacing.sm`},deny:{background:`semantic.colors.container`,foreground:`semantic.colors.text`,borderRadius:`palette.radius.md`,padding:`semantic.spacing.sm`}},attachment:{image:{background:`palette.colors.gray.100`,border:`palette.colors.gray.200`}},eventStream:{badge:{flow:{background:`palette.colors.success.100`,foreground:`palette.colors.success.700`},step:{background:`palette.colors.primary.100`,foreground:`palette.colors.primary.700`},reasoning:{background:`palette.colors.warning.100`,foreground:`palette.colors.warning.700`},tool:{background:`palette.colors.purple.100`,foreground:`palette.colors.purple.800`},agent:{background:`palette.colors.teal.100`,foreground:`palette.colors.teal.800`},error:{background:`palette.colors.error.100`,foreground:`palette.colors.error.700`},default:{background:`palette.colors.gray.100`,foreground:`palette.colors.gray.600`}}},scrollToBottom:{background:`components.button.primary.background`,foreground:`components.button.primary.foreground`,border:`semantic.colors.primary`,size:`40px`,borderRadius:`palette.radius.full`,shadow:`palette.shadows.sm`,padding:`0.5rem 0.875rem`,gap:`0.5rem`,fontSize:`0.875rem`,iconSize:`14px`},artifact:{pane:{background:`semantic.colors.container`,toolbarBackground:`semantic.colors.container`}}},Bf=Lf.colors.gray,Vf={50:`#fafafa`,100:`#f5f5f5`,200:`#e5e5e5`,300:`#d4d4d4`,400:`#a3a3a3`,500:`#737373`,600:`#525252`,700:`#404040`,800:`#262626`,900:`#171717`,950:`#0a0a0a`},Hf={...Lf,colors:{...Lf.colors,gray:Bf}},Uf={...Lf,colors:{...Lf.colors,gray:Vf},radius:{none:`0px`,sm:`4px`,md:`8px`,lg:`12px`,xl:`16px`,"2xl":`24px`,full:`9999px`}},Wf=Hf,Gf=Rf,Kf={...Rf,colors:{...Rf.colors,surface:`#ffffff`,background:`#ffffff`,container:`semantic.colors.surface`,textInverse:`#ffffff`},typography:{...Rf.typography,fontSize:`14px`,lineHeight:`1.5`}},qf=Gf,Jf=zf,Yf={...zf,launcher:Pf,activity:{rowHeight:`32px`,labelSize:`13px`,iconSize:`16px`,indent:`0px`,groupIndent:`0px`,groupGap:`0px`,groupPadding:`0px`,transcriptGap:`0px`,responseGap:`12px`,bodyPadding:`4px 0`,bodySize:`13px`,bodyLineHeight:`1.5`,bodyFontWeight:`400`,sectionGap:`8px`,bodySurface:`transparent`},toolBubble:{shadow:`none`},reasoningBubble:{shadow:`none`},input:{...zf.input,borderRadius:`palette.radius.full`},introCard:{...zf.introCard,title:{fontSize:`22px`,fontWeight:`500`}},suggestion:{chip:{...zf.suggestion.chip,fontWeight:`400`},card:{...zf.suggestion.card,fontWeight:`400`},list:{...zf.suggestion.list,fontWeight:`400`}},panel:{...zf.panel,width:`min(400px, calc(100vw - 24px))`,height:`min(704px, calc(100dvh - 104px))`,borderRadius:`palette.radius.xl`},header:{...zf.header,background:`semantic.colors.container`,foreground:`semantic.colors.text`,padding:`8px 8px 8px 16px`,minimalPadding:`8px 8px 8px 16px`,minHeight:`48px`,borderBottom:`none`,iconBackground:`transparent`,iconForeground:`semantic.colors.text`,iconScale:`1`,controlSize:`28px`,controlIconSize:`18px`,controlStrokeWidth:`1.5`,actionIconForeground:`semantic.colors.textMuted`,controlBorderRadius:`8px`,controlHoverBackground:`color-mix(in srgb, var(--persona-text) 8%, transparent)`,controlHoverForeground:`semantic.colors.text`,controlFocusOutline:`2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)`,title:{fontSize:`14px`,fontWeight:`500`,lineHeight:`1.5`}},message:{...zf.message,gap:`20px`,fullscreenGap:`28px`,topFadeHeight:`18px`,user:{...zf.message.user,background:`palette.colors.gray.100`,text:`semantic.colors.text`,borderRadius:`palette.radius.xl`,shadow:`none`,padding:`8px 14px`,fontSize:`14px`,lineHeight:`1.5`},assistant:{...zf.message.assistant,background:`transparent`,border:`transparent`,borderWidth:`0px`,borderRadius:`0px`,shadow:`none`,padding:`0px`,fontSize:`14px`,lineHeight:`1.55`}},composer:{...zf.composer,padding:`8px`,fontSize:`15px`,lineHeight:`1.5`,controlSize:`32px`,controlIconSize:`20px`,sendIconSize:`18px`,sendButtonRadius:`9999px`,footerBorder:`none`,overlayBand:`linear-gradient(to bottom, transparent, var(--persona-container) 24px)`,focusBorderColor:`color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))`,focusRing:`1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)`}},Xf=Jf,Zf=e=>_o({future:e}),Qf=e=>Zf(e)===`v5`?{palette:Uf,semantic:Kf,components:Yf}:{palette:Hf,semantic:Gf,components:Jf};function $f(e,t){if(!t.startsWith(`palette.`)&&!t.startsWith(`semantic.`)&&!t.startsWith(`components.`))return t;let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return typeof r==`string`&&(r.startsWith(`palette.`)||r.startsWith(`semantic.`)||r.startsWith(`components.`))?$f(e,r):r}function ep(e){let t={};function n(r,i){for(let[a,o]of Object.entries(r)){let r=`${i}.${a}`;if(typeof o==`string`){let n=$f(e,o);n!==void 0&&(t[r]={path:r,value:n,type:i.includes(`color`)?`color`:i.includes(`spacing`)?`spacing`:i.includes(`typography`)?`typography`:i.includes(`shadow`)?`shadow`:i.includes(`border`)?`border`:`color`})}else typeof o==`object`&&o&&n(o,r)}}return n(e.palette,`palette`),n(e.semantic,`semantic`),n(e.components,`components`),t}function tp(e){let t=[],n=[];return e.palette||t.push({path:`palette`,message:`Theme must include a palette`,severity:`error`}),e.semantic||n.push({path:`semantic`,message:`No semantic tokens defined - defaults will be used`,severity:`warning`}),e.components||n.push({path:`components`,message:`No component tokens defined - defaults will be used`,severity:`warning`}),{valid:t.length===0,errors:t,warnings:n}}function np(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t&&typeof t==`object`&&!Array.isArray(t)&&r&&typeof r==`object`&&!Array.isArray(r)?np(t,r):r}return n}function rp(e,t){return t?np(e,t):e}function ip(e,t={}){let n=Qf(t.future),r={palette:n.palette,semantic:n.semantic,components:n.components},i={palette:{...r.palette,...e?.palette,colors:{...r.palette.colors,...e?.palette?.colors},spacing:{...r.palette.spacing,...e?.palette?.spacing},typography:{...r.palette.typography,...e?.palette?.typography},shadows:{...r.palette.shadows,...e?.palette?.shadows},borders:{...r.palette.borders,...e?.palette?.borders},radius:{...r.palette.radius,...e?.palette?.radius}},semantic:{...r.semantic,...e?.semantic,colors:{...r.semantic.colors,...e?.semantic?.colors,interactive:{...r.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...r.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...r.semantic.spacing,...e?.semantic?.spacing},typography:{...r.semantic.typography,...e?.semantic?.typography}},components:rp(r.components,e?.components)},a=e?.components?.activity;for(let e of[`toolBubble`,`reasoningBubble`])for(let t of[`rowHeight`,`labelSize`,`iconSize`,`indent`,`bodySurface`])a?.[t]!==void 0&&(i.components[e][t]=a[t]);let o=e?.components?.collapsibleWidget?.surface;o!==void 0&&a?.bodySurface===void 0&&(i.components.activity={...i.components.activity,bodySurface:o});let s=e?.components?.header;s?.padding!==void 0&&s.minimalPadding===void 0&&(i.components.header.minimalPadding=i.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(i.components.message.fullscreenGap=i.components.message.gap),t.validate!==!1){let e=tp(i);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(`, `)}`)}if(t.plugins)for(let e of t.plugins)i=e.transform(i);return i}const ap=e=>e.trim()===`0`?`0px`:e,op=`--persona-`,sp=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let e=t.slice(1);if(!/^[0-9a-f]+$/.test(e))return;e.length===3||e.length===4?n=[0,1,2].map(t=>parseInt(e[t]+e[t],16)):(e.length===6||e.length===8)&&(n=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16)))}else{let e=t.match(/^rgba?\(([^)]+)\)$/);if(e){let t=e[1].split(/[,/\s]+/).filter(Boolean);t.length>=3&&(n=t.slice(0,3).map(e=>{let t=e.endsWith(`%`),n=parseFloat(t?e.slice(0,-1):e);return t?n/100*255:n}))}}if(!n||n.some(e=>!Number.isFinite(e)))return;let[r,i,a]=n.map(e=>{let t=Math.max(0,Math.min(255,e))/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a},cp=(e,t)=>{for(let[n,...r]of t){let t;for(let n of r)if(t=n.charCodeAt(0)===61?n.slice(1):e[op+n],t!==void 0)break;t!==void 0&&(e[op+n]=t)}};function lp(e){let t=ep(e),n={};for(let[e,r]of Object.entries(t)){let t=e.replace(/\./g,`-`);n[`--persona-${t}`]=r.value}cp(n,[[`primary`,`semantic-colors-primary`,`palette-colors-primary-500`],[`secondary`,`semantic-colors-secondary`,`palette-colors-secondary-500`],[`accent`,`semantic-colors-accent`,`palette-colors-accent-500`],[`surface`,`semantic-colors-surface`,`palette-colors-gray-50`],[`background`,`semantic-colors-background`,`palette-colors-gray-50`],[`container`,`semantic-colors-container`,`palette-colors-gray-100`],[`text`,`semantic-colors-text`,`palette-colors-gray-900`],[`text-muted`,`semantic-colors-text-muted`,`palette-colors-gray-500`],[`text-inverse`,`semantic-colors-text-inverse`,`palette-colors-gray-50`],[`border`,`semantic-colors-border`,`palette-colors-gray-200`],[`divider`,`semantic-colors-divider`,`palette-colors-gray-200`],[`muted`,`text-muted`],[`voice-recording-indicator`,`components-voice-recording-indicator`,`palette-colors-error-500`],[`voice-recording-bg`,`components-voice-recording-background`,`palette-colors-error-50`],[`voice-processing-icon`,`components-voice-processing-icon`,`palette-colors-primary-500`],[`voice-speaking-icon`,`components-voice-speaking-icon`,`palette-colors-success-500`],[`approval-bg`,`components-approval-requested-background`,`surface`],[`approval-border`,`components-approval-requested-border`,`border`],[`approval-text`,`components-approval-requested-text`,`palette-colors-gray-900`],[`approval-shadow`,`components-approval-requested-shadow`,`=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)`],[`approval-approve-bg`,`components-approval-approve-background`,`button-primary-bg`],[`approval-deny-bg`,`components-approval-deny-background`,`container`],[`attachment-image-bg`,`components-attachment-image-background`,`palette-colors-gray-100`],[`attachment-image-border`,`components-attachment-image-border`,`palette-colors-gray-200`],[`font-family`,`semantic-typography-fontFamily`,`palette-typography-fontFamily-sans`],[`font-size`,`semantic-typography-fontSize`,`palette-typography-fontSize-base`],[`font-weight`,`semantic-typography-fontWeight`,`palette-typography-fontWeight-normal`],[`line-height`,`semantic-typography-lineHeight`,`palette-typography-lineHeight-normal`],[`input-font-family`,`font-family`],[`input-font-weight`,`font-weight`],[`radius-sm`,`palette-radius-sm`,`=0.125rem`],[`radius-md`,`palette-radius-md`,`=0.375rem`],[`radius-lg`,`palette-radius-lg`,`=0.5rem`],[`radius-xl`,`palette-radius-xl`,`=0.75rem`],[`radius-full`,`palette-radius-full`,`=9999px`],[`launcher-radius`,`components-launcher-borderRadius`,`palette-radius-full`,`=9999px`],[`launcher-bg`,`components-launcher-background`,`surface`],[`launcher-fg`,`components-launcher-foreground`,`primary`]]);let r=n[`--persona-components-launcher-foreground`];n[`--persona-launcher-fg-muted`]=r&&r!==n[`--persona-primary`]?`color-mix(in srgb, ${r} 70%, transparent)`:n[`--persona-muted`],cp(n,[[`launcher-border`,`components-launcher-border`,`border`],[`button-primary-bg`,`components-button-primary-background`,`primary`],[`button-primary-fg`,`components-button-primary-foreground`,`text-inverse`],[`button-radius`,`components-button-primary-borderRadius`,`palette-radius-full`,`=9999px`],[`button-stop-bg`,`components-button-stop-background`],[`button-stop-fg`,`components-button-stop-foreground`]]),cp(n,[[`button-ghost-bg`,`components-button-ghost-background`,`=transparent`],[`button-ghost-fg`,`components-button-ghost-foreground`,`text`],[`button-ghost-radius`,`components-button-ghost-borderRadius`,`radius-md`,`=0.375rem`],[`button-ghost-hover-bg`,`components-button-ghost-hoverBackground`,`=rgba(0, 0, 0, 0.05)`],[`panel-radius`,`components-panel-borderRadius`,`radius-xl`,`=0.75rem`]]),n[`--persona-panel-border`]=n[`--persona-components-panel-border`]??`1px solid ${n[`--persona-border`]}`,cp(n,[[`panel-shadow`,`components-panel-shadow`,`palette-shadows-xl`,`=0 25px 50px -12px rgba(0, 0, 0, 0.25)`]]),n[`--persona-panel-inset`]=n[`--persona-components-panel-inset`]??`16px`,n[`--persona-panel-canvas-bg`]=n[`--persona-components-panel-canvasBackground`]??`transparent`,cp(n,[[`launcher-shadow`,`components-launcher-shadow`,`=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)`],[`input-radius`,`components-input-borderRadius`,`radius-lg`,`=0.5rem`],[`message-user-radius`,`components-message-user-borderRadius`,`radius-lg`,`=0.5rem`],[`message-assistant-radius`,`components-message-assistant-borderRadius`,`radius-lg`,`=0.5rem`]]),cp(n,[[`header-bg`,`components-header-background`,`surface`]]);let i=n[`--persona-header-bg`],a=n[`--persona-components-header-foreground`],o=a?`color-mix(in srgb, ${a} 72%, ${i})`:void 0;n[`--persona-header-border`]=n[`--persona-components-header-border`]??(a?`color-mix(in srgb, ${a} 14%, ${i})`:void 0)??n[`--persona-divider`],cp(n,[[`header-icon-bg`,`components-header-iconBackground`,`primary`],[`header-icon-fg`,`components-header-iconForeground`,`text-inverse`]]),n[`--persona-header-title-fg`]=n[`--persona-components-header-title-color`]??n[`--persona-components-header-titleForeground`]??a??n[`--persona-primary`],n[`--persona-header-subtitle-fg`]=n[`--persona-components-header-subtitle-color`]??n[`--persona-components-header-subtitleForeground`]??o??n[`--persona-text-muted`],n[`--persona-header-action-icon-fg`]=n[`--persona-components-header-actionIconForeground`]??o??n[`--persona-muted`],cp(n,[[`header-control-size`,`components-header-controlSize`,`=32px`],[`header-control-icon-size`,`components-header-controlIconSize`,`=20px`]]);let s=e.components?.header;s?.shadow&&(n[`--persona-header-shadow`]=s.shadow),s?.borderBottom&&(n[`--persona-header-border-bottom`]=s.borderBottom),s?.minHeight&&(n[`--persona-header-min-height`]=s.minHeight);let c=n[`--persona-components-history-railHeader-background`];c&&(n[`--persona-history-rail-header-bg`]=c);let l=n[`--persona-components-history-railHeader-border`];l&&(n[`--persona-history-rail-header-border`]=l);let u=n[`--persona-components-history-railHeader-minHeight`];u&&(n[`--persona-history-rail-header-min-height`]=u);for(let[e,t]of[[`margin`,`margin`],[`borderRadius`,`radius`],[`shadow`,`shadow`],[`background`,`bg`]]){let r=n[`--persona-components-history-overlay-${e}`];r&&(n[`--persona-history-overlay-${t}`]=r)}for(let[e,t]of[[`background`,`bg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-history-menu-${e}`];r&&(n[`--persona-history-menu-${t}`]=r)}let d=e.components?.history?.motion;if(d){let e=e=>{if(e===void 0)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},t=e(d.enterDurationMs);t!==void 0&&(n[`--persona-history-enter-ms`]=t);let r=e(d.exitDurationMs);r!==void 0&&(n[`--persona-history-exit-ms`]=r),d.enterEasing&&(n[`--persona-history-enter-easing`]=d.enterEasing),d.exitEasing&&(n[`--persona-history-exit-easing`]=d.exitEasing)}let f=n[`--persona-components-history-dangerForeground`];f&&(n[`--persona-history-danger-fg`]=f),n[`--persona-danger`]=n[`--persona-components-history-confirm-dangerBackground`]??n[`--persona-palette-colors-error-700`]??`#b42318`,n[`--persona-danger-fg`]=n[`--persona-components-history-confirm-dangerForeground`]??`#ffffff`;for(let e of[`scrim`,`shadow`]){let t=n[`--persona-components-history-confirm-${e}`];t&&(n[`--persona-history-confirm-${e}`]=t)}for(let[e,t]of[[`background`,`background`],[`foreground`,`foreground`],[`hintForeground`,`hint-fg`],[`borderRadius`,`radius`],[`fontSize`,`font-size`],[`padding`,`padding`],[`maxWidth`,`max-width`],[`shadow`,`shadow`]]){let r=n[`--persona-components-tooltip-${e}`];r&&(n[`--persona-tooltip-${t}`]=r)}e.components?.tooltip?.arrow===!1&&(n[`--persona-tooltip-arrow-display`]=`none`);for(let[e,t]of[[`background`,`bg`],[`border`,`border`],[`hoverBackground`,`hover-bg`],[`hoverForeground`,`hover-fg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-messageActions-${e}`];r&&(n[`--persona-message-action-${t}`]=r)}cp(n,[[`intro-card-bg`,`components-introCard-background`,`=transparent`],[`intro-card-radius`,`components-introCard-borderRadius`,`=1rem`]]);let p=n[`--persona-components-introCard-background`],m=n[`--persona-components-introCard-shadow`],h=(!p||p===`transparent`||p===`none`)&&(!m||m===`none`),g=n[`--persona-components-introCard-padding`]??`1.5rem`;n[`--persona-intro-card-padding`]=h&&g===`1.5rem`?`1.5rem 0`:g,cp(n,[[`intro-card-shadow`,`components-introCard-shadow`,`=none`],[`intro-card-border`,`components-introCard-border`,`=none`],[`input-background`,`components-input-background`,`surface`],[`input-placeholder`,`components-input-placeholder`,`text-muted`],[`input-backdrop-filter`,`components-input-backdropFilter`,`=none`],[`message-user-bg`,`components-message-user-background`,`accent`],[`message-user-text`,`components-message-user-text`,`text-inverse`],[`message-user-shadow`,`components-message-user-shadow`,`=0 5px 15px rgba(15, 23, 42, 0.08)`],[`message-assistant-bg`,`components-message-assistant-background`,`surface`],[`message-assistant-text`,`components-message-assistant-text`,`text`],[`message-assistant-border`,`components-message-assistant-border`,`border`],[`message-assistant-shadow`,`components-message-assistant-shadow`,`=0 1px 2px 0 rgb(0 0 0 / 0.05)`],[`scroll-to-bottom-bg`,`components-scrollToBottom-background`,`button-primary-bg`,`accent`],[`scroll-to-bottom-fg`,`components-scrollToBottom-foreground`,`button-primary-fg`,`text-inverse`],[`scroll-to-bottom-border`,`components-scrollToBottom-border`,`primary`],[`scroll-to-bottom-size`,`components-scrollToBottom-size`,`=40px`],[`scroll-to-bottom-radius`,`components-scrollToBottom-borderRadius`,`button-radius`,`radius-full`,`=9999px`],[`scroll-to-bottom-shadow`,`components-scrollToBottom-shadow`,`palette-shadows-sm`,`=0 1px 2px 0 rgb(0 0 0 / 0.05)`],[`scroll-to-bottom-padding`,`components-scrollToBottom-padding`,`=0.5rem 0.875rem`],[`scroll-to-bottom-gap`,`components-scrollToBottom-gap`,`=0.5rem`],[`scroll-to-bottom-font-size`,`components-scrollToBottom-fontSize`,`palette-typography-fontSize-sm`,`=0.875rem`],[`scroll-to-bottom-icon-size`,`components-scrollToBottom-iconSize`,`=14px`],[`event-badge-flow-bg`,`components-eventStream-badge-flow-background`,`=#dcfce7`],[`event-badge-flow-fg`,`components-eventStream-badge-flow-foreground`,`=#15803d`],[`event-badge-step-bg`,`components-eventStream-badge-step-background`,`=#f5f5f5`],[`event-badge-step-fg`,`components-eventStream-badge-step-foreground`,`=#0a0a0a`],[`event-badge-reasoning-bg`,`components-eventStream-badge-reasoning-background`,`=#fef9c3`],[`event-badge-reasoning-fg`,`components-eventStream-badge-reasoning-foreground`,`=#a16207`],[`event-badge-tool-bg`,`components-eventStream-badge-tool-background`,`=#f3e8ff`],[`event-badge-tool-fg`,`components-eventStream-badge-tool-foreground`,`=#6b21a8`],[`event-badge-agent-bg`,`components-eventStream-badge-agent-background`,`=#ccfbf1`],[`event-badge-agent-fg`,`components-eventStream-badge-agent-foreground`,`=#115e59`],[`event-badge-error-bg`,`components-eventStream-badge-error-background`,`=#fee2e2`],[`event-badge-error-fg`,`components-eventStream-badge-error-foreground`,`=#b91c1c`],[`event-badge-default-bg`,`components-eventStream-badge-default-background`,`=#f3f4f6`],[`event-badge-default-fg`,`components-eventStream-badge-default-foreground`,`=#4b5563`],[`tool-bubble-shadow`,`components-toolBubble-shadow`,`=0 5px 15px rgba(15, 23, 42, 0.08)`],[`reasoning-bubble-shadow`,`components-reasoningBubble-shadow`,`=0 5px 15px rgba(15, 23, 42, 0.08)`],[`composer-shadow`,`components-composer-shadow`,`=none`]]),cp(n,[[`composer-padding`,`components-composer-padding`,`=0.75rem 1rem`],[`composer-gap`,`components-composer-gap`,`=0.5rem`],[`composer-font-size`,`components-composer-fontSize`,`=0.875rem`],[`composer-line-height`,`components-composer-lineHeight`,`=1.25rem`],[`composer-control-size`,`components-composer-controlSize`,`=40px`],[`composer-control-icon-size`,`components-composer-controlIconSize`,`=24px`],[`motion-duration-fast`,`components-motion-durationFast`,`=120ms`],[`motion-duration-base`,`components-motion-durationBase`,`=200ms`],[`motion-easing`,`components-motion-easing`,`=cubic-bezier(0.2, 0, 0, 1)`],[`composer-border-color`,`components-composer-borderColor`,`border`,`=#e5e7eb`],[`composer-overlay-band`,`components-composer-overlayBand`,`=transparent`],[`scrollbar-thumb`,`components-scrollbar-thumb`,`border`,`=#e5e7eb`],[`scrollbar-track`,`components-scrollbar-track`,`=transparent`],[`md-inline-code-bg`,`components-markdown-inlineCode-background`,`container`],[`md-inline-code-color`,`components-markdown-inlineCode-foreground`,`text`],[`md-link-color`,`components-markdown-link-foreground`,`accent`,`=#0f0f0f`]]);let _=n[`--persona-components-markdown-heading-h1-fontSize`];_&&(n[`--persona-md-h1-size`]=_);let v=n[`--persona-components-markdown-heading-h1-fontWeight`];v&&(n[`--persona-md-h1-weight`]=v);let y=n[`--persona-components-markdown-heading-h2-fontSize`];y&&(n[`--persona-md-h2-size`]=y);let b=n[`--persona-components-markdown-heading-h2-fontWeight`];b&&(n[`--persona-md-h2-weight`]=b);let x=n[`--persona-components-markdown-prose-fontFamily`];x&&x!==`inherit`&&(n[`--persona-md-prose-font-family`]=x),cp(n,[[`md-code-block-bg`,`components-markdown-codeBlock-background`,`container`],[`md-code-block-border-color`,`components-markdown-codeBlock-borderColor`,`border`],[`md-code-block-text-color`,`components-markdown-codeBlock-textColor`,`=inherit`]]),cp(n,[[`md-code-block-border-radius`,`components-markdown-codeBlock-borderRadius`,`radius-md`,`=0.375rem`]]),cp(n,[[`md-table-header-bg`,`components-markdown-table-headerBackground`,`container`],[`md-table-border-color`,`components-markdown-table-borderColor`,`border`]]),cp(n,[[`md-hr-color`,`components-markdown-hr-color`,`divider`]]),cp(n,[[`md-blockquote-border-color`,`components-markdown-blockquote-borderColor`,`palette-colors-gray-900`],[`md-blockquote-bg`,`components-markdown-blockquote-background`,`=transparent`],[`md-blockquote-text-color`,`components-markdown-blockquote-textColor`,`palette-colors-gray-500`]]);for(let[e,t]of[[`container`,`surface`],[`surface`,`surface`],[`border`,`border`]]){let r=n[`--persona-components-collapsibleWidget-${e}`]??n[`--persona-${t}`];r!==void 0&&(n[`--persona-cw-${e}`]=r,n[`--cw-${e}`]=r)}cp(n,[[`message-border`,`components-message-border`,`border`]]),cp(n,[[`message-user-padding`,`components-message-user-padding`],[`message-user-max-width`,`components-message-user-maxWidth`],[`message-user-font-size`,`components-message-user-fontSize`],[`message-user-font-family`,`components-message-user-fontFamily`],[`message-user-line-height`,`components-message-user-lineHeight`],[`message-assistant-padding`,`components-message-assistant-padding`],[`message-assistant-border-width`,`components-message-assistant-borderWidth`],[`message-assistant-max-width`,`components-message-assistant-maxWidth`],[`message-assistant-font-size`,`components-message-assistant-fontSize`],[`message-assistant-font-family`,`components-message-assistant-fontFamily`],[`message-assistant-line-height`,`components-message-assistant-lineHeight`]]);let S=e.components,C=S?.iconButton;C&&(C.background&&(n[`--persona-icon-btn-bg`]=C.background),C.border&&(n[`--persona-icon-btn-border`]=C.border),C.color&&(n[`--persona-icon-btn-color`]=C.color),C.padding&&(n[`--persona-icon-btn-padding`]=C.padding),C.borderRadius&&(n[`--persona-icon-btn-radius`]=C.borderRadius),C.hoverBackground&&(n[`--persona-icon-btn-hover-bg`]=C.hoverBackground),C.hoverColor&&(n[`--persona-icon-btn-hover-color`]=C.hoverColor),C.activeBackground&&(n[`--persona-icon-btn-active-bg`]=C.activeBackground),C.activeBorder&&(n[`--persona-icon-btn-active-border`]=C.activeBorder));let w=S?.labelButton;w&&(w.background&&(n[`--persona-label-btn-bg`]=w.background),w.border&&(n[`--persona-label-btn-border`]=w.border),w.color&&(n[`--persona-label-btn-color`]=w.color),w.padding&&(n[`--persona-label-btn-padding`]=w.padding),w.borderRadius&&(n[`--persona-label-btn-radius`]=w.borderRadius),w.hoverBackground&&(n[`--persona-label-btn-hover-bg`]=w.hoverBackground),w.fontSize&&(n[`--persona-label-btn-font-size`]=w.fontSize),w.gap&&(n[`--persona-label-btn-gap`]=w.gap));let T=S?.toggleGroup;T&&(T.gap&&(n[`--persona-toggle-group-gap`]=T.gap),T.borderRadius&&(n[`--persona-toggle-group-radius`]=T.borderRadius));let E=S?.artifact;if(E?.toolbar){let t=E.toolbar;t.iconHoverColor&&(n[`--persona-artifact-toolbar-icon-hover-color`]=t.iconHoverColor),t.iconHoverBackground&&(n[`--persona-artifact-toolbar-icon-hover-bg`]=t.iconHoverBackground),t.iconPadding&&(n[`--persona-artifact-toolbar-icon-padding`]=t.iconPadding),t.iconBorderRadius&&(n[`--persona-artifact-toolbar-icon-radius`]=t.iconBorderRadius),t.iconBorder&&(n[`--persona-artifact-toolbar-icon-border`]=t.iconBorder),t.toggleGroupGap&&(n[`--persona-artifact-toolbar-toggle-group-gap`]=ap(t.toggleGroupGap)),t.toggleBorderRadius&&(n[`--persona-artifact-toolbar-toggle-radius`]=t.toggleBorderRadius),t.toggleGroupPadding&&(n[`--persona-artifact-toolbar-toggle-group-padding`]=ap(t.toggleGroupPadding)),t.toggleGroupBorder&&(n[`--persona-artifact-toolbar-toggle-group-border`]=t.toggleGroupBorder),t.toggleGroupBorderRadius&&(n[`--persona-artifact-toolbar-toggle-group-radius`]=t.toggleGroupBorderRadius),t.toggleGroupBackground&&(n[`--persona-artifact-toolbar-toggle-group-bg`]=$f(e,t.toggleGroupBackground)??t.toggleGroupBackground),t.copyBackground&&(n[`--persona-artifact-toolbar-copy-bg`]=t.copyBackground),t.copyBorder&&(n[`--persona-artifact-toolbar-copy-border`]=t.copyBorder),t.copyColor&&(n[`--persona-artifact-toolbar-copy-color`]=t.copyColor),t.copyBorderRadius&&(n[`--persona-artifact-toolbar-copy-radius`]=ap(t.copyBorderRadius)),t.copyPadding&&(n[`--persona-artifact-toolbar-copy-padding`]=t.copyPadding),t.copyMenuBackground&&(n[`--persona-artifact-toolbar-copy-menu-bg`]=t.copyMenuBackground,n[`--persona-dropdown-bg`]=n[`--persona-dropdown-bg`]??t.copyMenuBackground),t.copyMenuBorder&&(n[`--persona-artifact-toolbar-copy-menu-border`]=t.copyMenuBorder,n[`--persona-dropdown-border`]=n[`--persona-dropdown-border`]??t.copyMenuBorder),t.copyMenuShadow&&(n[`--persona-artifact-toolbar-copy-menu-shadow`]=t.copyMenuShadow,n[`--persona-dropdown-shadow`]=n[`--persona-dropdown-shadow`]??t.copyMenuShadow),t.copyMenuBorderRadius&&(n[`--persona-artifact-toolbar-copy-menu-radius`]=t.copyMenuBorderRadius,n[`--persona-dropdown-radius`]=n[`--persona-dropdown-radius`]??t.copyMenuBorderRadius),t.copyMenuItemHoverBackground&&(n[`--persona-artifact-toolbar-copy-menu-item-hover-bg`]=t.copyMenuItemHoverBackground,n[`--persona-dropdown-item-hover-bg`]=n[`--persona-dropdown-item-hover-bg`]??t.copyMenuItemHoverBackground),t.iconBackground&&(n[`--persona-artifact-toolbar-icon-bg`]=t.iconBackground),t.toolbarBorder&&(n[`--persona-artifact-toolbar-border`]=t.toolbarBorder)}if(E?.tab){let e=E.tab;e.background&&(n[`--persona-artifact-tab-bg`]=e.background),e.activeBackground&&(n[`--persona-artifact-tab-active-bg`]=e.activeBackground),e.activeBorder&&(n[`--persona-artifact-tab-active-border`]=e.activeBorder),e.borderRadius&&(n[`--persona-artifact-tab-radius`]=e.borderRadius),e.textColor&&(n[`--persona-artifact-tab-color`]=e.textColor),e.hoverBackground&&(n[`--persona-artifact-tab-hover-bg`]=e.hoverBackground),e.listBackground&&(n[`--persona-artifact-tab-list-bg`]=e.listBackground),e.listBorderColor&&(n[`--persona-artifact-tab-list-border-color`]=e.listBorderColor),e.listPadding&&(n[`--persona-artifact-tab-list-padding`]=e.listPadding)}if(E?.pane){let t=E.pane;t.toolbarBackground&&(n[`--persona-artifact-toolbar-bg`]=$f(e,t.toolbarBackground)??t.toolbarBackground)}if(E?.card){let e=E.card;e.background&&(n[`--persona-artifact-card-bg`]=e.background),e.border&&(n[`--persona-artifact-card-border`]=e.border),e.borderRadius&&(n[`--persona-artifact-card-radius`]=e.borderRadius),e.hoverBackground&&(n[`--persona-artifact-card-hover-bg`]=e.hoverBackground),e.hoverBorderColor&&(n[`--persona-artifact-card-hover-border`]=e.hoverBorderColor)}if(E?.inline){let t=E.inline;t.background&&(n[`--persona-artifact-inline-bg`]=$f(e,t.background)??t.background),t.border&&(n[`--persona-artifact-inline-border`]=t.border),t.borderRadius&&(n[`--persona-artifact-inline-radius`]=t.borderRadius),t.chromeBackground&&(n[`--persona-artifact-inline-chrome-bg`]=$f(e,t.chromeBackground)??t.chromeBackground),t.chromeBorder&&(n[`--persona-artifact-inline-chrome-border`]=$f(e,t.chromeBorder)??t.chromeBorder),t.titleColor&&(n[`--persona-artifact-inline-title-color`]=$f(e,t.titleColor)??t.titleColor),t.mutedColor&&(n[`--persona-artifact-inline-muted-color`]=$f(e,t.mutedColor)??t.mutedColor),t.frameHeight&&(n[`--persona-artifact-inline-frame-height`]=t.frameHeight)}let D=S?.code;D&&(D.keywordColor&&(n[`--persona-code-keyword-color`]=D.keywordColor),D.stringColor&&(n[`--persona-code-string-color`]=D.stringColor),D.commentColor&&(n[`--persona-code-comment-color`]=D.commentColor),D.numberColor&&(n[`--persona-code-number-color`]=D.numberColor),D.tagColor&&(n[`--persona-code-tag-color`]=D.tagColor),D.attrColor&&(n[`--persona-code-attr-color`]=D.attrColor),D.propertyColor&&(n[`--persona-code-property-color`]=D.propertyColor),D.lineNumberColor&&(n[`--persona-code-line-number-color`]=D.lineNumberColor),D.gutterBorderColor&&(n[`--persona-code-gutter-border-color`]=D.gutterBorderColor),D.background&&(n[`--persona-code-bg`]=$f(e,D.background)??D.background));let O=n[`--persona-surface`],k=n[`--persona-container`],ee=n[`--persona-palette-colors-gray-100`]??`#f3f4f6`,A=n[`--persona-palette-colors-gray-200`]??`#e5e7eb`,te=n[`--persona-palette-colors-gray-300`]??`#d1d5db`,ne=!k||k===O,re=sp(O??n[`--persona-background`]),ie=ne&&re!==void 0&&re<.179,ae=ie?`rgba(255, 255, 255, 0.08)`:ee,oe=ie?`rgba(255, 255, 255, 0.12)`:A,j=ie?`rgba(255, 255, 255, 0.16)`:te,se=ne?ae:k,ce=ne?oe:k;return n[`--persona-icon-btn-hover-bg`]=n[`--persona-icon-btn-hover-bg`]??se,n[`--persona-icon-btn-active-bg`]=n[`--persona-icon-btn-active-bg`]??ce,ne&&(n[`--persona-icon-btn-active-border`]=n[`--persona-icon-btn-active-border`]??j),n[`--persona-label-btn-hover-bg`]=n[`--persona-label-btn-hover-bg`]??se,n[`--persona-artifact-tab-hover-bg`]=n[`--persona-artifact-tab-hover-bg`]??se,n[`--persona-artifact-card-hover-bg`]=n[`--persona-artifact-card-hover-bg`]??se,n}const up={header:`Widget header bar`,messages:`Message list area`,"user-message":`User message bubble`,"assistant-message":`Assistant message bubble`,composer:`Footer / composer area`,container:`Main widget container`,"artifact-pane":`Artifact sidebar`,"artifact-toolbar":`Artifact toolbar`,"artifact-inline":`Inline artifact block`,"artifact-inline-chrome":`Inline artifact title bar`};No(),Xa();const dp=e=>!!e&&`launcher`in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode===`docked`),fp=(e,t)=>{if(!t||!dp(t))return e;let n=t.theme?.components?.panel?.width,r=t.darkTheme?.components?.panel?.width;return(Cp(t)===`dark`?r??n:n)==null?{...e,components:{...e.components,panel:{...e.components.panel,width:_o(t)===`v5`?`400px`:`420px`}}}:e},pp={colors:{primary:{50:`#ffffff`,100:`#f5f5f5`,200:`#d4d4d4`,300:`#a3a3a3`,400:`#737373`,500:`#171717`,600:`#0f0f0f`,700:`#0a0a0a`,800:`#050505`,900:`#030303`,950:`#000000`},secondary:{50:`#f5f3ff`,100:`#ede9fe`,200:`#ddd6fe`,300:`#c4b5fd`,400:`#a78bfa`,500:`#8b5cf6`,600:`#7c3aed`,700:`#6d28d9`,800:`#5b21b6`,900:`#4c1d95`,950:`#2e1065`},accent:{50:`#ecfeff`,100:`#cffafe`,200:`#a5f3fc`,300:`#67e8f9`,400:`#22d3ee`,500:`#06b6d4`,600:`#0891b2`,700:`#0e7490`,800:`#155e75`,900:`#164e63`,950:`#083344`},gray:{50:`#f9fafb`,100:`#f3f4f6`,200:`#e5e7eb`,300:`#d1d5db`,400:`#9ca3af`,500:`#6b7280`,600:`#4b5563`,700:`#374151`,800:`#1f2937`,900:`#111827`,950:`#030712`},success:{50:`#f0fdf4`,100:`#dcfce7`,200:`#bbf7d0`,300:`#86efac`,400:`#4ade80`,500:`#22c55e`,600:`#16a34a`,700:`#15803d`,800:`#166534`,900:`#14532d`},warning:{50:`#fefce8`,100:`#fef9c3`,200:`#fef08a`,300:`#fde047`,400:`#facc15`,500:`#eab308`,600:`#ca8a04`,700:`#a16207`,800:`#854d0e`,900:`#713f12`},error:{50:`#fef2f2`,100:`#fee2e2`,200:`#fecaca`,300:`#fca5a5`,400:`#f87171`,500:`#ef4444`,600:`#dc2626`,700:`#b91c1c`,800:`#991b1b`,900:`#7f1d1d`}}},mp={components:{button:{ghost:{hoverBackground:`rgba(255, 255, 255, 0.08)`}},markdown:{link:{foreground:`palette.colors.primary.300`}},eventStream:{badge:{flow:{background:`palette.colors.success.900`,foreground:`palette.colors.success.300`},step:{background:`palette.colors.primary.800`,foreground:`palette.colors.primary.200`},reasoning:{background:`palette.colors.warning.900`,foreground:`palette.colors.warning.300`},tool:{background:`palette.colors.purple.900`,foreground:`palette.colors.purple.300`},agent:{background:`palette.colors.teal.900`,foreground:`palette.colors.teal.300`},error:{background:`palette.colors.error.900`,foreground:`palette.colors.error.300`},default:{background:`palette.colors.gray.800`,foreground:`palette.colors.gray.300`}}},history:{dangerForeground:`#f87171`,confirm:{dangerBackground:`palette.colors.error.600`,scrim:`rgba(0, 0, 0, 0.6)`}}}},hp=pp,gp={...hp,colors:{...hp.colors,primary:{50:`#0f0f10`,100:`#27272a`,200:`#3f3f46`,300:`#52525b`,400:`#71717a`,500:`#f4f4f5`,600:`#e4e4e7`,700:`#d4d4d8`,800:`#a1a1aa`,900:`#fafafa`,950:`#ffffff`},gray:{50:`#1a1a1b`,100:`#27272a`,200:`#2a2a2d`,300:`#52525b`,400:`#71717a`,500:`#a1a1aa`,600:`#b4b4bd`,700:`#d4d4d8`,800:`#e4e4e7`,900:`#f4f4f5`,950:`#fafafa`}}},_p=mp,vp={semantic:{colors:{primary:`palette.colors.primary.500`,accent:`palette.colors.primary.600`,background:`#0f0f10`,surface:`palette.colors.gray.50`,container:`#1c1c20`,text:`palette.colors.gray.900`,textMuted:`palette.colors.gray.500`,textInverse:`#0f0f10`,border:`palette.colors.gray.200`,divider:`palette.colors.gray.200`,interactive:{default:`palette.colors.primary.600`,hover:`palette.colors.primary.700`,focus:`palette.colors.primary.600`,active:`palette.colors.primary.600`}}},components:{...mp.components,button:{...mp.components?.button,primary:{background:`semantic.colors.primary`,foreground:`palette.colors.primary.50`}},markdown:{inlineCode:{background:`palette.colors.gray.100`,foreground:`semantic.colors.text`},link:{foreground:`semantic.colors.accent`},codeBlock:{background:`semantic.colors.container`,borderColor:`semantic.colors.border`,textColor:`semantic.colors.text`},table:{headerBackground:`palette.colors.gray.100`,borderColor:`semantic.colors.border`},blockquote:{background:`semantic.colors.container`,borderColor:`palette.colors.gray.300`,textColor:`semantic.colors.textMuted`}},eventStream:{...mp.components?.eventStream,badge:{...mp.components?.eventStream?.badge,step:{background:`palette.colors.gray.100`,foreground:`palette.colors.gray.700`},default:{background:`palette.colors.gray.100`,foreground:`palette.colors.gray.700`}}}}},yp=e=>_o({future:e})===`v5`?{palette:gp,components:vp}:{palette:hp,components:_p},bp=e=>{if(e&&typeof e==`object`&&!Array.isArray(e))return e},xp=()=>typeof document<`u`&&document.documentElement.classList.contains(`dark`)||typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`,Sp=e=>{let t=e?.colorScheme??`light`;return t===`light`?`light`:t===`dark`?`dark`:xp()},Cp=e=>Sp(e),wp=(e,t={})=>ip(e,t),Tp=(e,t={})=>{let n=yp(t.future),r=Ja(n.components,e??{})??{};return ip({...r,palette:{...r.palette,colors:_o(t)===`v5`?Ja(n.palette.colors,r.palette?.colors):{...n.palette.colors,...r.palette?.colors}}},{validate:!1,future:t.future})},Ep=e=>{let t=Cp(e),n=bp(e?.theme),r=Ja({components:{launcher:Nf(e)===`circle`?Pf:{...Jf.launcher,...e?.future?.v5Defaults?{offset:`1.5rem`}:{}}}},n),i=bp(e?.darkTheme);return fp(t===`dark`?Tp(Ja(r??{},i??{}),{future:e?.future}):wp(r,{future:e?.future}),e)},Dp=e=>lp(e),Op=(e,t)=>{let n=Ep(t),r=Dp(n);for(let[t,n]of Object.entries(r))e.style.setProperty(t,n);e.setAttribute(`data-persona-color-scheme`,Cp(t)),e.setAttribute(`data-persona-defaults`,_o(t))},kp=e=>{let t=[];if(typeof document<`u`&&typeof MutationObserver<`u`){let n=new MutationObserver(()=>{e(xp())});n.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),t.push(()=>n.disconnect())}if(typeof window<`u`&&window.matchMedia){let n=window.matchMedia(`(prefers-color-scheme: dark)`),r=()=>e(xp());n.addEventListener?(n.addEventListener(`change`,r),t.push(()=>n.removeEventListener(`change`,r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(e=>e())}},Ap=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??`720px`:`768px`),jp=(e,t)=>t||e?.composer?.placement!==`overlay`?`block`:`overlay`,Mp=e=>{if(typeof e!=`string`)return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let n=Number(t[1])/100;return n>0&&n<1?n:null},Np=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight),Pp=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;At.morph(e,t.innerHTML,{morphStyle:`innerHTML`,callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement&&r){if(e.classList.contains(`persona-animate-typing`)||e.hasAttribute(`data-preserve-runtime`))return!1;if(e.hasAttribute(`data-tool-elapsed`))return t instanceof HTMLElement&&t.getAttribute(`data-tool-elapsed`)===e.getAttribute(`data-tool-elapsed`)?!1:void 0;if(e.hasAttribute(`data-preserve-animation`))return t instanceof HTMLElement&&!t.hasAttribute(`data-preserve-animation`)||t instanceof HTMLElement&&t.hasAttribute(`data-preserve-animation`)&&(e.textContent??``)!==(t.textContent??``)?void 0:!1}}}})},Fp=e=>e.replace(/^\n+/,``).replace(/\s+$/,``),Ip={index:-1,draft:``};function Lp(e){let{direction:t,history:n,currentValue:r,atStart:i,state:a}=e,o=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t===`up`){if(!o&&!i)return{handled:!1,state:a};if(!o){let e=n.length-1;return{handled:!0,value:n[e],state:{index:e,draft:r}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!o)return{handled:!1,state:a};if(a.index<n.length-1){let e=a.index+1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function Rp(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??``,e.streaming?`1`:`0`,e.voiceProcessing?`1`:`0`,e.variant??``,e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??``,e.toolCall?.status??``,e.toolCall?.name??``,e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??``,typeof e.toolCall?.args==`string`?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??``,e.contentParts?.length??0,e.stopReason??``,t].join(`\0`)}function zp(){return/* @__PURE__ */ new Map}function Bp(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Vp(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Hp(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Up(e){return e.role!==`assistant`||e.variant===`tool`||e.variant===`reasoning`?!1:e.variant===`approval`||!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function Wp(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>!t&&(t=!0,!0)}}function Gp(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Kp(e,t){return Gp(e)-e.scrollTop<=t}function qp(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:i,userScrollThreshold:a,isAutoScrolling:o=!1,pauseOnUpwardScroll:s=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:l=!1}=e,u=n-r;return o||Math.abs(u)<a?{action:`none`,delta:u,nextLastScrollTop:n}:!t&&i&&(!l||u>0)?{action:`resume`,delta:u,nextLastScrollTop:n}:t&&s&&u<0||t&&c&&!i?{action:`pause`,delta:u,nextLastScrollTop:n}:{action:`none`,delta:u,nextLastScrollTop:n}}function Jp(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:i=!1}=e;return t&&n<0?`pause`:!t&&i&&n>0&&r?`resume`:`none`}function Yp(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Xp(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset);return{targetScrollTop:t,spacerHeight:Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0))}}function Zp(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}const Qp={type:`none`,placeholder:`none`,speed:120,duration:1800,buffer:`none`},$p=[`pre`,`code`,`a`,`script`,`style`],em=e=>({type:e?.type??Qp.type,placeholder:e?.placeholder??Qp.placeholder,speed:e?.speed??Qp.speed,duration:e?.duration??Qp.duration,buffer:e?.buffer??Qp.buffer}),tm=[{name:`typewriter`,containerClass:`persona-stream-typewriter`,wrap:`char`,useCaret:!0},{name:`pop-bubble`,bubbleClass:`persona-stream-pop`,wrap:`none`},{name:`letter-rise`,containerClass:`persona-stream-letter-rise`,wrap:`char`},{name:`word-fade`,containerClass:`persona-stream-word-fade`,wrap:`word`}],nm=/* @__PURE__ */ new Map;for(let e of tm)nm.set(e.name,e);const rm=[`wipe`,`glyph-cycle`],im=e=>{nm.set(e.name,e)},am=e=>{tm.some(t=>t.name===e)||nm.delete(e)},om=()=>Array.from(nm.keys()),sm=(e,t)=>e===`none`?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:nm.get(e)??null,cm=(e,t,n,r,i)=>{if(!i)return e;if(n?.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t===`word`){let t=e.search(/\s(?=\S*$)/);return t<0?``:e.slice(0,t)}if(t===`line`){let t=e.lastIndexOf(`
|
|
24
|
-
`);return t<0?``:e.slice(0,t)}return e},lm=(e,t,n,r)=>{let i=e.createElement(`span`);return i.className=`persona-stream-char`,i.id=`stream-c-${n}-${r}`,i.style.setProperty(`--char-index`,String(r)),i.textContent=t,i},um=(e,t,n,r)=>{let i=e.createElement(`span`);return i.className=`persona-stream-word`,i.id=`stream-w-${n}-${r}`,i.style.setProperty(`--word-index`,String(r)),i.textContent=t,i},dm=/\s/,fm=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let e=n;if(t.has(e.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},pm=(e,t,n)=>{let r=e.ownerDocument,i=e.parentNode;if(!r||!i)return;let a=e.nodeValue??``;if(!a)return;let o=r.createDocumentFragment(),s=0;for(;s<a.length;)if(dm.test(a[s])){let e=s;for(;e<a.length&&dm.test(a[e]);)e+=1;o.appendChild(r.createTextNode(a.slice(s,e))),s=e}else{let e=r.createElement(`span`);e.className=`persona-stream-word-group`;let i=s;for(;i<a.length&&!dm.test(a[i]);)e.appendChild(lm(r,a[i],t,n.value)),n.value+=1,i+=1;o.appendChild(e),s=i}i.replaceChild(o,e)},mm=(e,t,n)=>{let r=e.ownerDocument,i=e.parentNode;if(!r||!i)return;let a=e.nodeValue??``;if(!a)return;let o=r.createDocumentFragment(),s=a.split(/(\s+)/);for(let e of s)e&&(/^\s+$/.test(e)?o.appendChild(r.createTextNode(e)):(o.appendChild(um(r,e,t,n.value)),n.value+=1));i.replaceChild(o,e)},hm=(e,t,n,r)=>{if(!e||typeof document>`u`)return e;let i=document.createElement(`div`);i.innerHTML=e;let a=new Set((r?.skipTags??$p).map(e=>e.toLowerCase())),o=document.createTreeWalker(i,NodeFilter.SHOW_TEXT,null),s=[],c=o.nextNode();for(;c;)fm(c,a)||s.push(c),c=o.nextNode();let l={value:r?.startIndex??0},u=t===`char`?pm:mm;for(let e of s)u(e,n,l);return i.innerHTML},gm=(e=document)=>{let t=e.createElement(`span`);return t.className=`persona-stream-caret`,t.setAttribute(`aria-hidden`,`true`),t.setAttribute(`data-preserve-animation`,`stream-caret`),t},_m=(e=document)=>{let t=e.createElement(`div`);t.className=`persona-stream-skeleton`,t.setAttribute(`data-preserve-animation`,`stream-skeleton`),t.setAttribute(`aria-hidden`,`true`);let n=e.createElement(`div`);return n.className=`persona-stream-skeleton-line`,t.appendChild(n),t},vm=/* @__PURE__ */ new WeakMap,ym=(e,t)=>{if(!e.styles)return;let n=vm.get(t);if(n||(n=/* @__PURE__ */ new Set,vm.set(t,n)),n.has(e.name)){let r=e.name.replace(/["\\]/g,`\\$&`);if(t.querySelector(`style[data-persona-animation="${r}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement(`style`);r.setAttribute(`data-persona-animation`,e.name),r.textContent=e.styles,t.appendChild(r)},bm=/* @__PURE__ */ new WeakMap,xm=(e,t)=>{if(!e.onAttach)return;let n=bm.get(t);if(n||(n=/* @__PURE__ */ new Map,bm.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},Sm=e=>{let t=bm.get(e);if(t){for(let e of t.values())typeof e==`function`&&e();t.clear()}},Cm=(e,t)=>{ym(e,t),xm(e,t)};Pt();const{setLoader:wm,load:Tm}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/animations-extra`)}),Em=Tm;yi();function Dm(e,t=_i){let n=e.style.position,r=e.style.zIndex,i=e.style.isolation,a=getComputedStyle(e),o=a.position===`static`||a.position===``;return o&&(e.style.position=`relative`),e.style.zIndex=String(t),e.style.isolation=`isolate`,()=>{o&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=i}}let Om=0,km=null;function Am(e=document){if(Om++,Om===1){let t=e.body,n=(e.defaultView??window).scrollY||e.documentElement.scrollTop;km={originalOverflow:t.style.overflow,originalPosition:t.style.position,originalTop:t.style.top,originalWidth:t.style.width,scrollY:n},t.style.overflow=`hidden`,t.style.position=`fixed`,t.style.top=`-${n}px`,t.style.width=`100%`}let t=!1;return()=>{if(!t&&(t=!0,Om=Math.max(0,Om-1),Om===0&&km)){let t=e.body,n=e.defaultView??window;t.style.overflow=km.originalOverflow,t.style.position=km.originalPosition,t.style.top=km.originalTop,t.style.width=km.originalWidth,n.scrollTo(0,km.scrollY),km=null}}}go();const jm={side:`right`,width:`420px`,animate:!0,reveal:`resize`,maxHeight:`100dvh`},Mm=e=>(e?.launcher?.mountMode??`floating`)===`docked`,Nm=e=>(e?.launcher?.mountMode??`floating`)===`composer-bar`,Pm=e=>{let t=e?.launcher?.dock,n=fo(e).dockWidth?t?.width:$f(Ep(e),`components.panel.width`);return{side:t?.side??jm.side,width:n??jm.width,animate:t?.animate??jm.animate,reveal:t?.reveal??jm.reveal,maxHeight:t?.maxHeight??jm.maxHeight}};Y(),mn(),Yt();const Fm=e=>e===`followUp`?`follow-up`:e,Im=(e,t=0)=>{if(typeof e==`string`){let t=e.trim();return t?{id:t,label:t,prompt:t,emphasis:`default`}:null}let n=e.label.trim();if(!n)return null;let r=e.prompt?.trim()||n;return{id:e.id?.trim()||r||`suggestion-${t}`,label:n,prompt:r,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??`default`}},Lm=/* @__PURE__ */ new WeakSet,Rm=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,zm=e=>{Rm()||e.forEach((e,t)=>{typeof e.animate==`function`&&e.animate([{opacity:`0`,transform:`translateY(4px)`},{opacity:`1`,transform:`none`}],{duration:250,delay:t*60,easing:`ease-out`,fill:`backwards`})})},Bm=e=>{let{item:t,index:n,surface:r,source:i,variant:a,streaming:o,config:c,plugins:l,chipsConfig:u,session:d,getTextarea:f,eventTarget:p,submitPrompt:m}=e,h=r===`followUp`,g=t.behavior,_=()=>{if(d.isStreaming())return;let e={suggestion:{...t},surface:r,source:i,behavior:g},n=p.dispatchEvent(new CustomEvent(`persona:suggestion:selected`,{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(h&&p.dispatchEvent(new CustomEvent(`persona:suggestReplies:selected`,{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!n)return;for(let e of l)if(e.onSuggestionSelect?.({suggestion:{...t},surface:r,source:i,variant:a,config:c})===!1)return;let o=f();g===`fill`?(o.value=t.prompt,o.dispatchEvent(new Event(`input`,{bubbles:!0,composed:!0})),o.focus()):m?m(t.prompt):(o.value=``,d.sendMessage(t.prompt))},v=()=>{let e=q(`button`,`persona-suggestion persona-suggestion--${a}`);if(e.type=`button`,e.disabled=o,e.dataset.suggestionId=t.id,e.dataset.emphasis=t.emphasis,e.dataset.behavior=g,a===`chip`&&(u?.fontWeight&&(e.style.fontWeight=u.fontWeight),u?.paddingX&&(e.style.paddingLeft=u.paddingX,e.style.paddingRight=u.paddingX),u?.paddingY&&(e.style.paddingTop=u.paddingY,e.style.paddingBottom=u.paddingY)),t.icon){let n=K(t.icon,`var(--persona-suggestion-icon-size)`,`currentColor`,1.8);n&&(n.classList.add(`persona-suggestion__icon`),t.iconColor&&(n.style.color=t.iconColor),e.appendChild(n))}let n=q(`span`,`persona-suggestion__copy`);if(n.appendChild(J(`span`,{className:`persona-suggestion__label`,text:t.label})),t.description&&a!==`chip`&&n.appendChild(J(`span`,{className:`persona-suggestion__description`,text:t.description})),e.appendChild(n),a!==`chip`){let t=Jt(s,16,`currentColor`,1.8);t&&(t.classList.add(`persona-suggestion__arrow`),e.appendChild(t))}return e.addEventListener(`click`,_),e},y=null;for(let e of l)if(e.renderSuggestion&&(y=e.renderSuggestion({suggestion:{...t},index:n,surface:r,source:i,variant:a,streaming:o,config:c,defaultRenderer:v,select:_}),y))break;return y??=v(),y.dataset.suggestionId||=t.id,y.dataset.behavior||=g,y.dataset.emphasis||=t.emphasis,y instanceof HTMLButtonElement||y.setAttribute(`aria-disabled`,o?`true`:`false`),y},Vm=e=>{let t=[],n=[],r=null,i=null,a=()=>{e.removeAttribute(`data-scroll-left`),e.removeAttribute(`data-scroll-right`)},o=()=>{if(i=null,e.hidden||e.dataset.variant!==`chip`||e.dataset.overflow!==`scroll`){a();return}let t=Math.max(0,e.scrollWidth-e.clientWidth);if(t<=1){a();return}let n=getComputedStyle(e).direction===`rtl`,r=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),o=r<=4,s=r>=t-4,c=n?!s:!o,l=n?!o:!s;e.toggleAttribute(`data-scroll-left`,c),e.toggleAttribute(`data-scroll-right`,l)},s=()=>{i!==null||typeof requestAnimationFrame!=`function`?typeof requestAnimationFrame!=`function`&&o():i=requestAnimationFrame(o)};e.addEventListener(`scroll`,s,{passive:!0});let c=typeof ResizeObserver==`function`?new ResizeObserver(s):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener(`scroll`,s),c?.disconnect(),i!==null&&typeof cancelAnimationFrame==`function`&&cancelAnimationFrame(i),i=null},render:(i,c,l,u,d,f)=>{e.replaceChildren(),t.length=0,n.length=0;let p=f?.source??`config`,m=f?.surface??(p===`config`?`starter`:`followUp`),h=m===`followUp`,g=f?.variant??`chip`,_=f?.behavior??`send`,v=f?.overflow??`wrap`,y=f?.config??{},b=f?.plugins??[],x=typeof f?.maxItems==`number`?Math.max(0,Math.floor(f.maxItems)):void 0,S=h?`followUps`:`starters`;!Lm.has(y)&&y.debug===!0&&g!==`chip`&&y.suggestions?.[S]?.overflow!==void 0&&(Lm.add(y),console.info(`[persona] suggestions.${S}.overflow applies to the "chip" variant only; the "${g}" variant manages its own stacking.`));let C=e=>e.map(Im).filter(e=>e!==null).map(e=>({...e,behavior:e.behavior??_})),w=C(i??[]);b.forEach(e=>{e.transformSuggestions&&(w=C(e.transformSuggestions({suggestions:w.map(e=>({...e})),surface:m,source:p,config:y})))});let T=x===void 0?w:w.slice(0,x);if(!T.length){e.hidden=!0,r=null,a();return}if(!h&&(u??c.getMessages()).some(e=>e.role===`user`)){e.hidden=!0,r=null;return}e.hidden=!1,e.classList.add(`persona-suggestions`),e.dataset.personaSuggestionSurface=Fm(m),e.dataset.variant=g,e.dataset.overflow=v;let E=document.createDocumentFragment(),D=c.isStreaming();T.forEach((r,i)=>{let a=Bm({item:r,index:i,surface:m,source:p,variant:g,streaming:D,config:y,plugins:b,chipsConfig:d,session:c,getTextarea:()=>l,eventTarget:e,submitPrompt:f?.submitPrompt});E.appendChild(a),n.push(a),[...a instanceof HTMLButtonElement?[a]:[],...Array.from(a.querySelectorAll(`button`))].forEach(e=>{t.includes(e)||(e.disabled=D,t.push(e))})}),e.appendChild(E),o(),s();let O=JSON.stringify({normalized:T,surface:m,variant:g,source:p});O!==r&&(r=O,zm(n),e.dispatchEvent(new CustomEvent(`persona:suggestion:shown`,{detail:{suggestions:T.map(e=>({...e})),surface:m,source:p,variant:g},bubbles:!0,composed:!0})),h&&e.dispatchEvent(new CustomEvent(`persona:suggestReplies:shown`,{detail:{suggestions:T.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},Hm={"bottom-right":`persona-bottom-6 persona-right-6`,"bottom-left":`persona-bottom-6 persona-left-6`,"top-right":`persona-top-6 persona-right-6`,"top-left":`persona-top-6 persona-left-6`};Y(),mn(),Ua();const Um={x:[1.4,1.05]},Wm=`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`,Gm=(e,t,n={})=>{let{iconSize:r,iconText:i}=n,[a,o]=Um[t]??[1,1.5],s=!r;e.classList.toggle(`persona-header-control--glyph`,s),e.classList.toggle(`persona-header-control--sparse`,s&&a!==1);let c=K(t,`${Math.round((parseFloat(r??``)||20)*a)}px`,`currentColor`,o);c?(c.style.display=`block`,s||(c.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((o/1.5).toFixed(4))})`),e.replaceChildren(c)):i&&(e.textContent=i)},Km=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:r,iconName:i,iconText:a,wrapperClassName:o=Wm,size:s,iconSize:c,color:l,backgroundColor:u,borderWidth:d,borderColor:f,borderRadius:p,paddingX:m,paddingY:h,hidden:g,extraClassName:_,attrs:v}=e,y=q(`div`,o),b=!!(d||f),x=J(`button`,{className:tr(`persona-header-control`,`persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer`,!u&&`persona-bg-transparent hover:persona-bg-gray-100`,!b&&`persona-border-none`,!p&&`persona-rounded-full`,_),attrs:{type:`button`,"aria-label":t,...v},style:{width:s,height:s,minWidth:s,minHeight:s,display:g?`none`:void 0,color:l||Ym.actionIconColor,backgroundColor:u,border:b?`${d||`0px`} solid ${f||`transparent`}`:void 0,borderRadius:p,paddingLeft:m,paddingRight:m,paddingTop:h,paddingBottom:h}});return i?Gm(x,i,{iconSize:c,iconText:a}):a&&(x.textContent=a),y.appendChild(x),Ea({anchor:x,trigger:y,text:()=>x.getAttribute(`aria-label`)??t,hint:r,enabled:n}),{button:x,wrapper:y}},qm=(e,t={})=>{let{showClose:n=!0,wrapperClassName:r=Wm,buttonSize:i,iconSize:a}=t,o=e?.launcher??{},s=o.closeButtonTooltipText??`Close chat`,c=o.closeButtonShowTooltip??!0,{button:l,wrapper:u}=Km({ariaLabel:s,tooltip:c,iconName:o.closeButtonIconName??`x`,iconText:o.closeButtonIconText??`×`,wrapperClassName:r,size:i??o.closeButtonSize,iconSize:a,color:o.closeButtonColor,backgroundColor:o.closeButtonBackgroundColor,borderWidth:o.closeButtonBorderWidth,borderColor:o.closeButtonBorderColor,borderRadius:o.closeButtonBorderRadius,paddingX:o.closeButtonPaddingX,paddingY:o.closeButtonPaddingY,hidden:!n});return{button:l,wrapper:u}},Jm=(e,t={})=>{let{wrapperClassName:n=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,buttonSize:r,iconSize:i}=t,a=(e?.launcher??{}).clearChat??{},o=a.tooltipText??`Clear chat`,s=a.showTooltip??!0,{button:c,wrapper:l}=Km({ariaLabel:o,tooltip:s,iconName:a.iconName??`refresh-cw`,wrapperClassName:n,size:r??a.size,iconSize:i,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:c,wrapper:l}};Y(),mn(),No();const Ym={titleColor:`var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))`,subtitleColor:`var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))`,actionIconColor:`var(--persona-header-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))`,minHeight:`var(--persona-header-min-height, auto)`},Xm={fontFamily:`var(--persona-components-header-title-fontFamily, inherit)`,fontSize:`var(--persona-components-header-title-fontSize, 1rem)`,fontWeight:`var(--persona-components-header-title-fontWeight, 600)`,lineHeight:`var(--persona-components-header-title-lineHeight, 1.5rem)`,letterSpacing:`var(--persona-components-header-title-letterSpacing, normal)`},Zm={fontFamily:`var(--persona-components-header-subtitle-fontFamily, inherit)`,fontSize:`var(--persona-components-header-subtitle-fontSize, 0.75rem)`,fontWeight:`var(--persona-components-header-subtitle-fontWeight, inherit)`,lineHeight:`var(--persona-components-header-subtitle-lineHeight, 1rem)`,letterSpacing:`var(--persona-components-header-subtitle-letterSpacing, normal)`},Qm=e=>{let{config:t,showClose:n=!0}=e,r=J(`div`,{className:`persona-widget-header persona-flex persona-items-center persona-gap-3`,attrs:{"data-persona-theme-zone":`header`},style:{padding:`var(--persona-components-header-padding, 20px 24px)`,minHeight:Ym.minHeight,backgroundColor:`var(--persona-header-bg, var(--persona-surface, #ffffff))`,borderBottomColor:`var(--persona-header-border, var(--persona-divider, #f1f5f9))`,boxShadow:`var(--persona-header-shadow, none)`,borderBottom:`var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))`}}),i=t?.launcher??{},a=i.headerIconSize??`40px`,o=i.closeButtonPlacement??`inline`,s=i.headerIconHidden??!1,c=i.headerIconName,l=J(`div`,{className:`persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl`,style:{height:a,width:a,backgroundColor:`var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))`,color:`var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))`}});if(!s){if(c){let e=parseFloat(a)||24,n=K(c,e*.6,`currentColor`,1);n?(n.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,n.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,l.replaceChildren(n)):l.textContent=t?.launcher?.agentIconText??`💬`}else if(t?.launcher?.iconUrl){let e=q(`img`);e.src=t.launcher.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=a,e.style.width=a,l.replaceChildren(e)}else l.textContent=t?.launcher?.agentIconText??`💬`}let u=q(`div`,`persona-flex persona-flex-col persona-flex-1 persona-min-w-0`),d=J(`span`,{className:`persona-text-base persona-font-semibold`,text:t?.launcher?.title??`Chat Assistant`,style:{color:Ym.titleColor,...Xm}}),f=J(`span`,{className:`persona-text-xs`,text:t?.launcher?.subtitle??`Here to help you get answers fast`,style:{color:Ym.subtitleColor,...Zm}});u.append(d,f),s?r.append(u):r.append(l,u);let p=i.clearChat??{},m=p.enabled??!0,h=p.placement??`inline`,g=null,_=null;if(m){let e=Jm(t,{wrapperClassName:h===`top-right`?`persona-absolute persona-top-4 persona-z-50`:`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`});g=e.button,_=e.wrapper,h===`top-right`&&(_.style.right=`48px`),h===`inline`&&r.appendChild(_)}let{button:v,wrapper:y}=qm(t,{showClose:n,wrapperClassName:o===`top-right`?`persona-absolute persona-top-4 persona-right-4 persona-z-50`:m&&h===`inline`?`persona-relative persona-inline-flex persona-items-center persona-justify-center`:`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`});return o!==`top-right`&&r.appendChild(y),{header:r,iconHolder:l,headerTitle:d,headerSubtitle:f,closeButton:v,closeButtonWrapper:y,clearChatButton:g,clearChatButtonWrapper:_}},$m=(e,t,n)=>{let r=n?.launcher??{},i=r.closeButtonPlacement??`inline`,a=r.clearChat?.placement??`inline`;e.appendChild(t.header),i===`top-right`&&(e.style.position=`relative`,e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a===`top-right`&&(e.style.position=`relative`,e.appendChild(t.clearChatButtonWrapper))};Y(),mn(),yi();function eh(e){let{items:t,onSelect:n,anchor:r,position:i=`bottom-left`,portal:a,onOpenChange:o}=e,s=q(`div`,`persona-dropdown-menu persona-hidden`);s.setAttribute(`role`,`menu`),s.setAttribute(`data-persona-theme-zone`,`dropdown`),a?(s.style.position=`fixed`,s.style.zIndex=String(vi)):(s.style.position=`absolute`,s.style.top=`100%`,s.style.marginTop=`4px`,i===`bottom-right`?s.style.right=`0`:s.style.left=`0`);for(let e of t){if(e.dividerBefore){let e=document.createElement(`hr`);s.appendChild(e)}let t=document.createElement(`button`);if(t.type=`button`,t.setAttribute(`role`,`menuitem`),t.setAttribute(`data-dropdown-item-id`,e.id),e.destructive&&t.setAttribute(`data-destructive`,``),e.icon){let n=K(e.icon,16,`currentColor`,1.5);n&&t.appendChild(n)}let r=document.createElement(`span`);r.textContent=e.label,t.appendChild(r),t.addEventListener(`click`,t=>{t.stopPropagation(),d(),n(e.id)}),s.appendChild(t)}let c=null;function l(){if(!a)return;let e=r.getBoundingClientRect();s.style.top=`${e.bottom+4}px`,i===`bottom-right`?(s.style.right=`${window.innerWidth-e.right}px`,s.style.left=`auto`):(s.style.left=`${e.left}px`,s.style.right=`auto`)}function u(){let e=s.classList.contains(`persona-hidden`);l(),s.classList.remove(`persona-hidden`),e&&o?.(!0),requestAnimationFrame(()=>{let e=e=>{!s.contains(e.target)&&!r.contains(e.target)&&d()};document.addEventListener(`click`,e,!0),c=()=>document.removeEventListener(`click`,e,!0)})}function d(){let e=!s.classList.contains(`persona-hidden`);s.classList.add(`persona-hidden`),c?.(),c=null,e&&o?.(!1)}function f(){s.classList.contains(`persona-hidden`)?u():d()}function p(){d(),s.remove()}return a&&a.appendChild(s),{element:s,show:u,hide:d,toggle:f,destroy:p}}Y(),mn();function th(e){let{icon:t,label:n,size:r,strokeWidth:i,className:a,chromeless:o,onClick:s,aria:c}=e,l=q(`button`,tr(!o&&`persona-icon-btn`,a));l.type=`button`,l.setAttribute(`aria-label`,n),l.title=n;let u=K(t,r??16,`currentColor`,i??2);if(u&&l.appendChild(u),s&&l.addEventListener(`click`,s),c)for(let[e,t]of Object.entries(c))l.setAttribute(e,t);return l}function nh(e){let{icon:t,label:n,variant:r=`default`,size:i=`sm`,iconSize:a,className:o,onClick:s,aria:c}=e,l=`persona-label-btn`;r!=="default"&&(l+=` persona-label-btn--`+r),l+=` persona-label-btn--`+i,o&&(l+=` `+o);let u=q(`button`,l);if(u.type=`button`,u.setAttribute(`aria-label`,n),t){let e=K(t,a??14,`currentColor`,2);e&&u.appendChild(e)}let d=q(`span`);if(d.textContent=n,u.appendChild(d),s&&u.addEventListener(`click`,s),c)for(let[e,t]of Object.entries(c))u.setAttribute(e,t);return u}function rh(e){let{items:t,selectedId:n,onSelect:r,className:i}=e,a=q(`div`,`persona-toggle-group`+(i?` `+i:``));a.setAttribute(`role`,`group`);let o=n,s=[];function c(){for(let e of s)e.btn.setAttribute(`aria-pressed`,e.id===o?`true`:`false`)}for(let e of t){let t;e.icon?t=th({icon:e.icon,label:e.label,className:e.className,onClick:()=>{o=e.id,c(),r(e.id)}}):(t=q(`button`,`persona-icon-btn`+(e.className?` `+e.className:``)),t.type=`button`,t.setAttribute(`aria-label`,e.label),t.title=e.label,t.textContent=e.label,t.addEventListener(`click`,()=>{o=e.id,c(),r(e.id)})),t.setAttribute(`aria-pressed`,e.id===o?`true`:`false`),s.push({id:e.id,btn:t}),a.appendChild(t)}function l(e){o=e,c()}return{element:a,setSelected:l}}function ih(e){let{label:t,icon:n,iconSize:r,iconOnly:i,menuItems:a,onSelect:o,onPrimary:s,position:c=`bottom-left`,portal:l,chevronLabel:u=`More options`,chevronIconSize:d,className:f,primaryClassName:p,chevronClassName:m}=e,h=q(`div`,`persona-split-btn`+(f?` `+f:``)),g={label:t,className:`persona-split-btn-primary`+(p?` `+p:``),onClick:s},_=i&&n?th({...g,icon:n,size:r??14}):nh({...g,icon:n,iconSize:r??14}),v=th({icon:`chevron-down`,label:u,size:d??14,className:`persona-split-btn-chevron`+(m?` `+m:``),aria:{"aria-haspopup":`true`,"aria-expanded":`false`}});h.append(_,v);let y=null,b=()=>{if(y)return y;let e=(typeof l==`function`?l():l)??void 0;return y=eh({items:a,onSelect:o,anchor:h,position:c,portal:e,onOpenChange:e=>{v.setAttribute(`aria-expanded`,e?`true`:`false`)}}),e||h.appendChild(y.element),y};return h.isConnected?b():requestAnimationFrame(()=>{y||b()}),v.addEventListener(`click`,e=>{e.stopPropagation(),b().toggle()}),{element:h,primaryButton:_,chevronButton:v,openMenu:()=>b().show(),closeMenu:()=>y?.hide(),toggleMenu:()=>b().toggle(),destroy:()=>{y?.destroy(),h.remove()}}}function ah(e){let{label:t,icon:n=`chevron-down`,menuItems:r,onSelect:i,position:a=`bottom-left`,portal:o,className:s,hover:c}=e,l=q(`div`,`persona-combo-btn`+(s?` `+s:``));l.style.position=`relative`,l.style.display=`inline-flex`,l.style.alignItems=`center`,l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`),l.setAttribute(`aria-haspopup`,`true`),l.setAttribute(`aria-expanded`,`false`),l.setAttribute(`aria-label`,t);let u=q(`span`,`persona-combo-btn-label`);u.textContent=t,l.appendChild(u);let d=K(n,14,`currentColor`,2);d&&(d.style.marginLeft=`4px`,d.style.opacity=`0.6`,l.appendChild(d)),c&&(l.style.borderRadius=c.borderRadius??`10px`,l.style.padding=c.padding??`6px 4px 6px 12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=c.background??``,l.style.borderColor=c.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}));let f=eh({items:r,onSelect:e=>{l.setAttribute(`aria-expanded`,`false`),i(e)},anchor:l,position:a,portal:o});o||l.appendChild(f.element);let p=()=>l.getAttribute(`data-persona-menu-locked`)===`true`;return l.addEventListener(`click`,e=>{if(e.stopPropagation(),p())return;let t=!f.element.classList.contains(`persona-hidden`);l.setAttribute(`aria-expanded`,t?`false`:`true`),f.toggle()}),l.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),l.click())}),{element:l,setLabel:e=>{u.textContent=e,l.setAttribute(`aria-label`,e)},open:()=>{l.setAttribute(`aria-expanded`,`true`),f.show()},close:()=>{l.setAttribute(`aria-expanded`,`false`),f.hide()},toggle:()=>{let e=!f.element.classList.contains(`persona-hidden`);l.setAttribute(`aria-expanded`,e?`false`:`true`),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}Y(),Pc();const oh=e=>{let t=Qm({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let e=t.headerTitle.parentElement;e&&(e.style.cursor=`pointer`,e.setAttribute(`role`,`button`),e.setAttribute(`tabindex`,`0`),e.addEventListener(`click`,()=>n()),e.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n())}))}return t};function sh(e,t,n){if(t?.length)for(let r of t){let{button:t,wrapper:i}=Km({ariaLabel:r.ariaLabel??r.label??r.id,iconName:r.icon,iconText:r.icon?void 0:r.label,tooltipHint:r.shortcut?kc(r.shortcut):void 0,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`});if(t.setAttribute(`data-persona-header-action`,r.id),r.shortcut){let e=Ac(r.shortcut);e&&t.setAttribute(`aria-keyshortcuts`,e)}if(r.menuItems?.length){let e=eh({items:r.menuItems,onSelect:e=>n?.(e),anchor:i,position:`bottom-right`});i.appendChild(e.element),t.addEventListener(`click`,t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener(`click`,()=>n?.(r.id));e.appendChild(i)}}const ch=e=>{let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:i,onHeaderAction:a}=e,o=t?.launcher??{},s=q(`div`,`persona-flex persona-items-center persona-justify-between`);s.setAttribute(`data-persona-theme-zone`,`header`),s.style.minHeight=Ym.minHeight,s.style.padding=`var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))`,s.style.backgroundColor=`var(--persona-header-bg, var(--persona-surface, #ffffff))`,s.style.borderBottomColor=`var(--persona-header-border, var(--persona-divider, #f1f5f9))`,s.style.boxShadow=`var(--persona-header-shadow, none)`,s.style.borderBottom=`var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))`;let c=i?.titleMenu,l,u;if(c){let e=ah({label:o.title??`Chat Assistant`,menuItems:c.menuItems,onSelect:t=>{let n=n=>{n===!1&&e.element.dispatchEvent(new CustomEvent(`persona:title-menu-builtin`,{bubbles:!0,composed:!0,detail:{actionId:t}}))},r=c.onSelect(t);r instanceof Promise?r.then(n,()=>{}):n(r)},hover:c.hover,className:``});l=e.element,l.style.color=Ym.titleColor,u=l.querySelector(`.persona-combo-btn-label`)??l}else{if(l=q(`div`,`persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1`),u=q(`span`,`persona-text-base persona-font-semibold persona-truncate`),u.style.color=Ym.titleColor,Object.assign(u.style,Xm),u.textContent=o.title??`Chat Assistant`,l.appendChild(u),i?.onTitleClick){l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`);let e=i.onTitleClick;l.addEventListener(`click`,t=>{t.target.closest(`button`)||e()}),l.addEventListener(`keydown`,t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e())})}let e=i?.titleRowHover;e&&(l.style.borderRadius=e.borderRadius??`10px`,l.style.padding=e.padding??`6px 4px 6px 12px`,l.style.margin=`-6px 0 -6px -12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.style.width=`fit-content`,l.style.flex=`none`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=e.background??``,l.style.borderColor=e.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}))}s.appendChild(l);let d=`persona-relative persona-inline-flex persona-items-center persona-justify-center`,{button:f,wrapper:p}=qm(t,{showClose:n,wrapperClassName:d});r&&f.addEventListener(`click`,r);let m=q(`div`,`persona-flex persona-items-center persona-gap-1`);c||sh(m,i?.trailingActions,i?.onAction??a);let h=o.clearChat??{},g=null,_=null;if(h.enabled??!0){let e=h.placement??`inline`,n=Jm(t,{wrapperClassName:e===`top-right`?`persona-absolute persona-top-4 persona-z-50`:d});g=n.button,_=n.wrapper,e===`top-right`?_.style.right=`48px`:m.appendChild(_)}m.appendChild(p),s.appendChild(m);let v=q(`div`);v.style.display=`none`;let y=q(`span`);return y.style.display=`none`,{header:s,iconHolder:v,headerTitle:u,headerSubtitle:y,closeButton:f,closeButtonWrapper:p,clearChatButton:g,clearChatButtonWrapper:_}},lh={default:oh,minimal:ch},uh=e=>lh[e]??lh.default,dh=(e,t,n)=>{if(t?.render){let r=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=q(`div`);i.style.display=`none`;let a=q(`span`),o=q(`span`),s=q(`button`);s.style.display=`none`;let c=q(`div`);return c.style.display=`none`,{header:r,iconHolder:i,headerTitle:a,headerSubtitle:o,closeButton:s,closeButtonWrapper:c,clearChatButton:null,clearChatButtonWrapper:null}}let r=t?.layout??`default`,i=uh(r)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(i.iconHolder.style.display=`none`),t.showTitle===!1&&(i.headerTitle.style.display=`none`),t.showSubtitle===!1&&(i.headerSubtitle.style.display=`none`),t.showCloseButton===!1&&(i.closeButton.style.display=`none`),t.showClearChat===!1&&i.clearChatButtonWrapper&&(i.clearChatButtonWrapper.style.display=`none`)),i};Y(),xs();const fh=e=>{let{config:t}=e,n=J(`div`,{className:`persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4`,attrs:{"data-persona-theme-zone":`composer`}}),r=bs(),i=J(`form`,{className:`persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3`,attrs:{"data-persona-composer-form":``}}),{textarea:a,attachAutoResize:o}=ms(t);o();let s=gs(t),c=_s(t),l=vs(t),u=ys(t),d=J(`div`,{className:`persona-widget-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});i.append(d),l&&(l.previewsContainer.style.gap=`8px`,d.append(l.previewsContainer),i.append(l.input)),i.append(a);let f=J(`div`,{className:`persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full`,attrs:{"data-persona-composer-actions":``}}),p=J(`div`,{className:`persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-start":``}}),m=J(`div`,{className:`persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-end":``}});return l&&p.append(l.wrapper),c&&m.append(c.wrapper),m.append(s.wrapper),f.append(p,m),i.append(f),i.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),t?.statusIndicator?.mode===`transient`?n.append(r,u,i):n.append(r,i,u),{footer:n,suggestions:r,composerForm:i,header:d,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:u,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:f,leftActions:p,rightActions:m,setSendButtonMode:s.setMode}};Y(),Yt(),xs(),us();const ph=()=>{let e=J(`button`,{className:`persona-pill-peek`,attrs:{type:`button`,"data-persona-pill-peek":``,"aria-label":`Show conversation`,tabindex:`-1`}}),t=q(`span`,`persona-pill-peek__icon`),n=Jt(Le,16,`currentColor`,1.5);n&&t.appendChild(n);let r=q(`span`,`persona-pill-peek__text`),i=q(`span`,`persona-pill-peek__caret`),a=Jt(w,16,`currentColor`,1.5);return a&&i.appendChild(a),e.append(t,r,i),{root:e,textNode:r}},mh=e=>{let{config:t}=e,n=J(`div`,{className:`persona-widget-footer persona-widget-footer--pill`,attrs:{"data-persona-theme-zone":`composer`}}),r=bs(),i=ys(t);i.style.display=`none`;let{textarea:a,attachAutoResize:o}=ms(t,{defaultMaxLines:5});o();let s=gs(t),c=_s(t),l=vs(t);l&&l.previewsContainer.classList.add(`persona-pill-composer__previews`);let u=J(`form`,{className:`persona-widget-composer persona-pill-composer`,attrs:{"data-persona-composer-form":``}}),d=J(`div`,{className:`persona-widget-composer__left-actions persona-pill-composer__left`,attrs:{"data-persona-composer-actions-start":``}});l&&d.append(l.wrapper);let f=J(`div`,{className:`persona-widget-composer__right-actions persona-pill-composer__right`,attrs:{"data-persona-composer-actions-end":``}});c&&f.append(c.wrapper),f.append(s.wrapper),u.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),l&&u.append(l.input),u.append(d,a,f);let p=J(`div`,{className:`persona-pill-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});n.append(p),l&&p.append(l.previewsContainer),n.append(r,u,i);let m=u;return{footer:n,suggestions:r,composerForm:u,header:p,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:i,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:m,leftActions:d,rightActions:f,setSendButtonMode:s.setMode}};Y(),Ns(),mn(),$o();const hh=e=>{switch(e){case`max_tool_calls`:return`Stopped after calling a tool. Send a follow-up to continue.`;case`length`:return`Response cut off as max tokens reached. Ask for more to continue.`;case`content_filter`:return`The provider filtered this response.`;case`error`:return`Something went wrong generating this response.`;default:return null}},gh=(e,t)=>{if(!e)return null;let n=hh(e);if(n===null)return null;let r=t?.[e];return(r===void 0?n:r)||null},_h=(e,t)=>{let n=q(`div`,`persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic`);return n.setAttribute(`data-stop-reason`,e),n.setAttribute(`role`,`note`),n.style.opacity=`0.75`,n.textContent=t,n},vh=e=>{let t=e.toLowerCase();return!t.startsWith(`data:image/svg+xml`)&&!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:image/`)||!e.includes(`:`))},yh=e=>{let t=e.toLowerCase();return t.startsWith(`javascript:`)||t.startsWith(`data:text/html`)||t.startsWith(`data:text/javascript`)||t.startsWith(`data:text/xml`)||t.startsWith(`data:application/xhtml`)||t.startsWith(`data:image/svg+xml`)?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:`)||!e.includes(`:`))},bh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`image`&&typeof e.image==`string`&&e.image.trim().length>0),xh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`audio`&&typeof e.audio==`string`&&e.audio.trim().length>0),Sh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`video`&&typeof e.video==`string`&&e.video.trim().length>0),Ch=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`file`&&typeof e.data==`string`&&e.data.trim().length>0),wh=e=>{if(!e||e.length===0)return null;let t=J(`div`,{className:`persona-mention-context-row persona-message-mentions`,attrs:{"data-message-mentions":``}});t.style.display=`flex`;for(let n of e){let e=J(`div`,{className:`persona-mention-chip persona-mention-chip-readonly`,attrs:{"data-status":`ready`,title:n.label}}),r=q(`span`,`persona-mention-chip-icon`),i=K(n.iconName??`at-sign`,13,`currentColor`,2);i&&r.appendChild(i),e.appendChild(r),e.appendChild(J(`span`,{className:`persona-mention-chip-label`,text:n.label})),t.appendChild(e)}return t},Th=(e,t)=>{let n=document.createDocumentFragment();for(let r of e)r.kind===`text`?n.appendChild(document.createTextNode(r.text)):n.appendChild(Ms(r.ref,{readonly:!0,render:t}));return n},Eh=(e,t,n,r)=>{let i=Math.random().toString(36).slice(2,8),a=e=>`${i}:${e}`,o=n(t.map((e,t)=>e.kind===`text`?e.text:a(t)).join(``));if(!t.every((e,t)=>e.kind===`text`||o.includes(a(t)))){e.replaceChildren(Th(t,r));return}e.innerHTML=o;let s=RegExp(`${i}:(\\d+)`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),l=[];for(let e=c.nextNode();e;e=c.nextNode())l.push(e);for(let e of l){let n=e;for(let e=s.exec(n.data);e;e=s.exec(n.data)){let i=t[Number(e[1])],a=n.splitText(e.index);a.data=a.data.slice(e[0].length),i?.kind===`mention`&&a.parentNode?.insertBefore(Ms(i.ref,{readonly:!0,render:r}),a),n=a}}},Dh=(e,t,n)=>{if(e.length===0)return null;try{let r=q(`div`,`persona-flex persona-flex-col persona-gap-2`);r.setAttribute(`data-message-attachments`,`images`),t&&(r.style.marginBottom=`8px`);let i=0,a=!1,o=()=>{a||(a=!0,r.remove(),n?.())};return e.forEach((e,t)=>{let n=q(`img`);n.alt=e.alt?.trim()||`Attached image ${t+1}`,n.loading=`lazy`,n.decoding=`async`,n.referrerPolicy=`no-referrer`,n.style.display=`block`,n.style.width=`100%`,n.style.maxWidth=`320px`,n.style.maxHeight=`320px`,n.style.height=`auto`,n.style.objectFit=`contain`,n.style.borderRadius=`10px`,n.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,n.style.border=`1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))`;let a=!1;i+=1,n.addEventListener(`error`,()=>{a||(a=!0,i=Math.max(0,i-1),n.remove(),i===0&&o())}),n.addEventListener(`load`,()=>{a=!0}),vh(e.image)?(n.src=e.image,r.appendChild(n)):(a=!0,i=Math.max(0,i-1),n.remove())}),i===0?(o(),null):r}catch{return n?.(),null}},Oh=e=>{if(e.length===0)return null;try{let t=q(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`audio`);let n=0;return e.forEach(e=>{if(!yh(e.audio))return;let r=q(`audio`);r.controls=!0,r.preload=`metadata`,r.src=e.audio,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},kh=e=>{if(e.length===0)return null;try{let t=q(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`video`);let n=0;return e.forEach(e=>{if(!yh(e.video))return;let r=q(`video`);r.controls=!0,r.preload=`metadata`,r.src=e.video,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,r.style.maxHeight=`320px`,r.style.borderRadius=`10px`,r.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ah=e=>{if(e.length===0)return null;try{let t=q(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`files`);let n=0;return e.forEach(e=>{if(!yh(e.data))return;let r=q(`a`);r.href=e.data,r.download=e.filename,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=e.filename,r.className=`persona-message-file-attachment`,r.style.display=`inline-flex`,r.style.alignItems=`center`,r.style.gap=`6px`,r.style.padding=`6px 10px`,r.style.borderRadius=`8px`,r.style.fontSize=`0.875rem`,r.style.textDecoration=`underline`,r.style.backgroundColor=`var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))`,r.style.border=`1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))`,r.style.color=`inherit`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},jh=()=>{let e=document.createElement(`div`);e.className=`persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2`;let t=document.createElement(`div`);t.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,t.style.backgroundColor=`currentColor`,t.style.opacity=`0.4`,t.style.animationDelay=`0ms`;let n=document.createElement(`div`);n.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,n.style.backgroundColor=`currentColor`,n.style.opacity=`0.4`,n.style.animationDelay=`250ms`;let r=document.createElement(`div`);r.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,r.style.backgroundColor=`currentColor`,r.style.opacity=`0.4`,r.style.animationDelay=`500ms`;let i=document.createElement(`span`);return i.className=`persona-sr-only`,i.textContent=`Loading`,e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(i),e},Mh=(e,t,n)=>{let r={config:n??{},streaming:!0,location:e,defaultRenderer:jh};if(t){let e=t(r);if(e!==null)return e}return jh()},Nh=(e,t)=>{let n=q(`div`,`persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm`),r=t===`user`?e.userAvatar:e.assistantAvatar;if(r){if(r.startsWith(`http`)||r.startsWith(`/`)||r.startsWith(`data:`)){let e=q(`img`);e.src=r,e.alt=t===`user`?`User`:`Assistant`,e.className=`persona-w-full persona-h-full persona-rounded-full persona-object-cover`,n.appendChild(e)}else n.textContent=r,n.classList.add(t===`user`?`persona-bg-persona-accent`:`persona-bg-persona-primary`,`persona-text-white`)}else n.textContent=t===`user`?`U`:`A`,n.classList.add(t===`user`?`persona-bg-persona-accent`:`persona-bg-persona-primary`,`persona-text-white`);return n},Ph=(e,t,n=`div`)=>{let r=q(n,`persona-text-xs persona-text-persona-muted`),i=new Date(e.createdAt);return r.textContent=t.format?t.format(i):i.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`}),r},Fh=(e,t=`bubble`)=>{let n=[`persona-message-bubble`];switch(t){case`flat`:e===`user`?n.push(`persona-message-user-bubble`,`persona-ml-auto`,`persona-text-persona-primary`,`persona-py-2`):n.push(`persona-message-assistant-bubble`,`persona-text-persona-text`,`persona-py-2`);break;case`minimal`:n.push(`persona-text-sm`,`persona-leading-relaxed`),e===`user`?n.push(`persona-message-user-bubble`,`persona-ml-auto`,`persona-bg-persona-accent`,`persona-text-white`,`persona-px-3`,`persona-py-2`,`persona-rounded-lg`):n.push(`persona-message-assistant-bubble`,`persona-bg-persona-container`,`persona-text-persona-text`,`persona-px-3`,`persona-py-2`,`persona-rounded-lg`);break;default:n.push(`persona-rounded-2xl`,`persona-text-sm`,`persona-leading-relaxed`,`persona-shadow-sm`),e===`user`?n.push(`persona-message-user-bubble`,`persona-ml-auto`,`persona-bg-persona-accent`,`persona-text-white`,`persona-px-5`,`persona-py-3`):n.push(`persona-message-assistant-bubble`,`persona-bg-persona-container`,`persona-border`,`persona-border-persona-message-border`,`persona-text-persona-text`,`persona-px-5`,`persona-py-3`)}return n},Ih={bubble:{padding:`0.75rem 1.25rem`,fontSize:`0.875rem`,lineHeight:`1.75`},minimal:{padding:`0.5rem 0.75rem`,fontSize:`0.875rem`,lineHeight:`1.75`},flat:{padding:`0.5rem 0`,fontSize:`inherit`,lineHeight:`inherit`}},Lh=(e,t,n=`bubble`,r)=>{if(!r)return;let i=t===`user`?`user`:`assistant`,a=Ih[n??`bubble`]??Ih.bubble;r.padding&&(e.style.padding=`var(--persona-message-${i}-padding, ${a.padding})`),r.fontSize&&(e.style.fontSize=`var(--persona-message-${i}-font-size, ${a.fontSize})`),r.lineHeight&&(e.style.lineHeight=`var(--persona-message-${i}-line-height, ${a.lineHeight})`),r.fontFamily&&(e.style.fontFamily=`var(--persona-message-${i}-font-family, inherit)`)},Rh=e=>`custom:${e}`,zh=(e,t)=>t!==`user`&&t!==`assistant`?[]:(e?.custom??[]).filter(e=>(e.roles??[`assistant`]).includes(t)),Bh=(e,t,n,r)=>{let i=t.showCopy??!0,a=t.showUpvote??!1,o=t.showDownvote??!1,s=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&r?.canRegenerate===!0,l=(t.showEdit??!1)&&r?.canEdit===!0,u=(t.showQuote??!1)&&r?.canQuote!==!1,d=zh(t,e.role);if(!i&&!a&&!o&&!s&&!c&&!l&&!u&&d.length===0){let t=q(`div`);return t.style.display=`none`,t.id=`actions-${e.id}`,t.setAttribute(`data-actions-for`,e.id),t}let f=t.visibility??`hover`,p=t.align??`right`,m=t.layout??`pill-inside`,h={left:`persona-message-actions-left`,center:`persona-message-actions-center`,right:`persona-message-actions-right`}[p],g={"pill-inside":`persona-message-actions-pill`,"row-inside":`persona-message-actions-row`}[m],_=q(`div`,`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${h} ${g} ${f===`hover`?`persona-message-actions-hover`:``}`);_.id=`actions-${e.id}`,_.setAttribute(`data-actions-for`,e.id);let v=(e,t,n)=>{let r=th({icon:e,label:t,size:14,className:`persona-message-action-btn`,chromeless:!0});return r.setAttribute(`data-action`,n),r};i&&_.appendChild(v(`copy`,`Copy message`,`copy`)),s&&_.appendChild(v(`volume-2`,`Read aloud`,`read-aloud`)),a&&_.appendChild(v(`thumbs-up`,`Upvote`,`upvote`)),o&&_.appendChild(v(`thumbs-down`,`Downvote`,`downvote`)),c&&_.appendChild(v(`refresh-cw`,`Regenerate response`,`regenerate`)),l&&_.appendChild(v(`pencil`,`Edit message`,`edit`)),u&&_.appendChild(v(`quote`,`Quote message`,`quote`));for(let e of d)_.appendChild(v(e.iconName??`ellipsis`,e.label,Rh(e.id)));return _},Vh=(e,t,n,r,i,a)=>{let o=n??{},s=o.layout??`bubble`,c=o.avatar,l=o.timestamp,u=c?.show??!1,d=l?.show??!1,f=c?.position??`left`,p=l?.position??`below`,m=Fh(e.role,s),h=q(`div`,m.join(` `));h.id=`bubble-${e.id}`,h.setAttribute(`data-message-id`,e.id),h.setAttribute(`data-persona-theme-zone`,e.role===`user`?`user-message`:`assistant-message`);let g=Qf(a?.widgetConfig?.future).components.message,_=a?.widgetConfig?.theme?.components?.message;Lh(h,e.role,s,e.role===`user`?{...g.user,..._?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...g.assistant,..._?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),s===`flat`?(h.style.backgroundColor=`transparent`,h.style.color=e.role===`user`?`var(--persona-primary, var(--persona-text))`:`var(--persona-message-assistant-text, var(--persona-text))`):e.role===`user`?(h.style.backgroundColor=`var(--persona-message-user-bg, var(--persona-accent))`,h.style.color=`var(--persona-message-user-text, white)`):e.role===`assistant`&&(h.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,h.style.color=`var(--persona-message-assistant-text, var(--persona-text))`);let v=bh(e),y=e.content?.trim()??``,b=v.length>0&&y===`[Image]`,x=em(a?.widgetConfig?.features?.streamAnimation),S=a?.widgetConfig?.features?.streamAnimation?.plugins,C=e.role===`assistant`&&x.type!==`none`?sm(x.type,S):null,w=e.role===`assistant`&&C?.isAnimating?.(e)===!0,T=e.role===`assistant`&&C!==null&&(!!e.streaming||w);T&&C?.bubbleClass&&h.classList.add(C.bubbleClass);let E=document.createElement(`div`);E.classList.add(`persona-message-content`),e.streaming&&E.classList.add(`persona-content-streaming`),T&&C&&(C.containerClass&&E.classList.add(C.containerClass),E.style.setProperty(`--persona-stream-step`,`${x.speed}ms`),E.style.setProperty(`--persona-stream-duration`,`${x.duration}ms`));let D=T?cm(e.content??``,x.buffer,C,e,!!e.streaming):e.content??``,O=()=>{let n=t({text:D,message:e,streaming:!!e.streaming,raw:e.rawContent});return T&&C?.wrap===`char`?hm(n,`char`,e.id,{skipTags:C.skipTags}):T&&C?.wrap===`word`?hm(n,`word`,e.id,{skipTags:C.skipTags}):n},k=null;if(b?(k=document.createElement(`div`),k.innerHTML=O(),k.style.display=`none`,E.appendChild(k)):e.contentSegments?.length?Eh(E,e.contentSegments,n=>t({text:n,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):E.innerHTML=O(),T&&C?.useCaret&&!b&&y){let e=gm(),t=E.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];if(n?.parentNode)n.parentNode.insertBefore(e,n.nextSibling);else{let t=E.lastElementChild;t?t.appendChild(e):E.appendChild(e)}}if(d&&p===`inline`&&e.createdAt){let t=Ph(e,l,`span`);t.classList.add(`persona-timestamp-inline`);let n=E.lastElementChild;n?n.appendChild(t):E.appendChild(t)}if(v.length>0){let e=Dh(v,!b&&!!y,()=>{b&&k&&(k.style.display=``)});e?h.appendChild(e):b&&k&&(k.style.display=``)}let ee=xh(e);if(ee.length>0){let e=Oh(ee);e&&h.appendChild(e)}let A=Sh(e);if(A.length>0){let e=kh(A);e&&h.appendChild(e)}let te=Ch(e);if(te.length>0){let e=Ah(te);e&&h.appendChild(e)}let ne=e.contentSegments?.length?null:wh(e.contextMentions);if(ne&&h.appendChild(ne),h.appendChild(E),d&&p===`below`&&e.createdAt){let t=Ph(e,l);t.classList.add(`persona-mt-1`),h.appendChild(t)}let re=e.role===`assistant`?gh(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role===`assistant`){let e=!!(D&&D.trim()),t=x.placeholder===`skeleton`,n=t&&x.buffer===`line`&&e;if(e)n&&h.appendChild(_m());else if(t)h.appendChild(_m());else{let e=Mh(`inline`,a?.loadingIndicatorRenderer,a?.widgetConfig);e&&h.appendChild(e)}}re&&e.stopReason&&!e.streaming&&(y||(E.style.display=`none`),h.appendChild(_h(e.stopReason,re)));let ie=e.role===`assistant`&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&r?.enabled!==!1,ae=a?.actionEligibility,oe=e.role===`user`&&!e.streaming&&r?.enabled!==!1&&(r?.showEdit===!0&&ae?.canEdit===!0||r?.showQuote===!0&&ae?.canQuote===!0||zh(r,`user`).length>0);if((ie||oe)&&r){let t=Bh(e,oe?{...r,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:r,i,ae);h.appendChild(t)}if(!u||e.role===`system`)return h;let j=q(`div`,`persona-message-with-avatar persona-flex persona-gap-2 ${e.role===`user`?`persona-flex-row-reverse`:``}`),se=Nh(c,e.role);return f===`right`||f===`left`&&e.role===`user`?j.append(h,se):j.append(se,h),j},Hh=(e,t,n,r,i,a)=>{let o=n??{};return e.role===`user`&&o.renderUserMessage?o.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role===`assistant`&&o.renderAssistantMessage?o.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Vh(e,t,n,r,i,a)};Y(),mn();const Uh=(e,t)=>{if(e.replaceChildren(),!t)e.hidden=!0;else if(typeof t==`function`){let n=null;try{n=t()}catch(e){console.warn(`[persona] welcome.icon renderer threw`,e)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1}else{if(t.type===`lucide`){let n=K(t.name,40);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type===`image`?e.appendChild(J(`img`,{className:`persona-welcome-icon-image`,attrs:{src:t.url,alt:t.alt}})):e.appendChild(J(`span`,{className:`persona-welcome-icon-text`,text:t.text}));e.hidden=!1}},Wh=(e,t,n={})=>{let r=J(`div`,{className:`persona-welcome-icon`,attrs:{"data-persona-welcome-icon":``}});r.hidden=!0;let i=q(`p`,`persona-welcome-kicker`);i.hidden=!0;let a=q(`h2`,`persona-welcome-title`),o=q(`p`,`persona-welcome-subtitle`),s=J(`div`,{className:`persona-welcome-head-text`},i,a),c=J(`div`,{className:`persona-welcome-title-row`},r,s);return{host:J(`div`,{className:`persona-welcome persona-rounded-2xl`,attrs:{"data-persona-welcome":``,"data-persona-intro-card":``,"data-persona-welcome-variant":`card`},style:{background:`var(--persona-intro-card-bg, transparent)`,boxShadow:n.flatShadow?`none`:`var(--persona-intro-card-shadow, none)`,border:`var(--persona-intro-card-border, none)`}},c,o,t),iconHolder:r,kicker:i,title:a,subtitle:o,starterSuggestions:t}},Gh=(e,t,n)=>{t.hidden=!n,t.style.display=n?``:`none`,e.classList.toggle(`persona-gap-6`,n),e.classList.toggle(`persona-gap-3`,!n)},Kh=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??``,e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle===``,Uh(e.iconHolder,t.icon),e.host.setAttribute(`data-persona-welcome-variant`,t.variant),e.host.setAttribute(`data-persona-welcome-dismiss`,t.dismiss),e.host.setAttribute(`data-persona-welcome-layout`,t.layout??`top`),e.host.setAttribute(`data-persona-welcome-anchor`,t.anchor??`bottom`),t.iconPlacement===`inline`?e.host.setAttribute(`data-persona-welcome-icon-placement`,`inline`):e.host.removeAttribute(`data-persona-welcome-icon-placement`),t.align?e.host.setAttribute(`data-persona-welcome-align`,t.align):e.host.removeAttribute(`data-persona-welcome-align`)},qh=`data-persona-welcome-overlay`,Jh=`persona-welcome-overlay-active`,Yh=/* @__PURE__ */ new WeakMap,Xh=(e,t,n)=>{n.setAttribute(`data-persona-welcome-plugin`,``),t.appendChild(n),t.setAttribute(`data-persona-welcome-content`,`plugin`),t.setAttribute(qh,``),e.classList.contains(Jh)||(Yh.set(e,e.scrollTop),e.classList.add(Jh),e.scrollTop=0)},Zh=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute(`data-persona-welcome-content`),t.removeAttribute(qh),e.classList.contains(Jh)&&(e.classList.remove(Jh),e.scrollTop=Yh.get(e)??e.scrollTop,Yh.delete(e))},Qh=()=>{let e=J(`div`,{className:`persona-welcome-greeting persona-flex persona-flex-col`,attrs:{"data-persona-welcome-greeting":``}});return e.hidden=!0,e},$h=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let r=n?.layout?.messages?.layout??`bubble`,i=J(`div`,{className:Fh(`assistant`,r).join(` `),attrs:{"data-persona-theme-zone":`assistant-message`},text:t,style:r===`flat`?{backgroundColor:`transparent`,color:`var(--persona-message-assistant-text, var(--persona-text))`}:{backgroundColor:`var(--persona-message-assistant-bg, var(--persona-container))`,color:`var(--persona-message-assistant-text, var(--persona-text))`}});e.appendChild(J(`div`,{className:`persona-flex`},i)),e.hidden=!1},eg=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,tg=(e,t)=>{if(eg()||typeof e.animate!=`function`||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),r=e.parentElement,i=0,a=0,o=0;if(r){let t=getComputedStyle(r);i=parseFloat(t.rowGap)||0;let s=e.previousElementSibling,c=e.nextElementSibling,l=r.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-r.scrollTop;a=Math.max(0,s?n.top-s.getBoundingClientRect().bottom-i:n.top-l),o=Math.max(0,c?c.getBoundingClientRect().top-n.bottom-i:0)}let s=e.style.overflow;e.style.overflow=`hidden`;let c=getComputedStyle(e),l=parseFloat(c.paddingTop)||0,u=parseFloat(c.paddingBottom)||0,d=e.animate([{opacity:`1`,transform:`none`,height:`${n.height}px`,minHeight:`0px`,paddingTop:`${l}px`,paddingBottom:`${u}px`,marginTop:`${a}px`,marginBottom:`${o}px`},{opacity:`0`,transform:`translateY(-4px)`,height:`0px`,minHeight:`0px`,paddingTop:`0px`,paddingBottom:`0px`,marginTop:`0px`,marginBottom:`${-i}px`}],{duration:180,easing:`ease-out`,fill:`forwards`}),f=!1,p=()=>{f||(f=!0,e.style.overflow=s,t(d))};return d.finished.then(p).catch(p),d},ng=(e,t,n,r=260)=>{if(t<=1||eg()||typeof e.animate!=`function`||!e.isConnected)return null;let i=n===`drop`?-t:t;return e.animate([{transform:`translateY(${i}px)`},{transform:`none`}],{duration:r,easing:`cubic-bezier(0.2, 0, 0, 1)`,fill:`none`})},rg=/* @__PURE__ */ new WeakSet,ig=(e,t)=>!!e&&e[t]!==void 0,ag=(e,t)=>{e&&e.debug===!0&&t.length&&(rg.has(e)||(rg.add(e),t.forEach(e=>console.warn(`[persona] ${e}`))))},og=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!==`docked`)=>{let n=e?.welcome,r=e?.copy,i=e?.future?.v5Defaults===!0,a=n?.layout??(i?`centered`:`top`),o=ig(n,`variant`)?n.variant:r?.showWelcomeCard===!1?`none`:`card`,s=o===`hero`&&!i&&n?.layout===void 0?`on-first-message`:ig(n,`dismiss`)?n.dismiss:i||o===`hero`?`on-first-message`:`never`,c=[];ig(n,`title`)&&ig(r,`welcomeTitle`)&&c.push(`welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated.`),ig(n,`subtitle`)&&ig(r,`welcomeSubtitle`)&&c.push(`welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated.`),ig(n,`variant`)&&ig(r,`showWelcomeCard`)&&c.push(`welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated.`),o===`hero`&&ig(n,`message`)&&c.push(`welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.`),!i&&n?.layout===void 0&&o===`hero`&&ig(n,`dismiss`)&&n.dismiss!==`on-first-message`&&c.push(`welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".`);let l=n?.anchor??(a===`centered`&&t?`center`:`bottom`),u=Mp(n?.anchorComposerTop)!==null;return ig(n,`anchorComposerTop`)&&!u&&c.push(`welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".`),l!==`center`&&(ig(n,`anchorComposerTop`)||ig(n,`composerGap`))&&c.push(`welcome.anchorComposerTop is ignored unless welcome.anchor is "center".`),ag(e,c),{title:ig(n,`title`)?n.title:r?.welcomeTitle??(i?`What can I help with?`:`Hello 👋`),kicker:n?.kicker??``,subtitle:ig(n,`subtitle`)?n.subtitle:r?.welcomeSubtitle??(i?``:`I can answer questions and help you get things done here.`),icon:n?.icon,align:n?.align===`start`||n?.align===`center`?n.align:a===`centered`?`center`:void 0,iconPlacement:n?.icon&&typeof n.icon!=`function`&&n.icon.placement===`inline`?`inline`:`above`,variant:o,dismiss:s,message:o===`hero`?void 0:n?.message,layout:a,anchor:l,anchorComposerTop:u?n.anchorComposerTop:`44%`,composerGap:n?.composerGap?.trim()||`24px`}},sg=e=>(e??[]).some(e=>e.role===`user`)?`active`:`empty`,cg=(e,t)=>e.variant===`none`?!1:e.dismiss===`never`||!(t??[]).some(e=>e.role===`user`);Y(),yi(),go();const lg=`var(--persona-components-panel-height)`,ug=e=>{let t=fo(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,r=e?.launcher?.heightOffset??0,i=r===0?`max(200px, ${lg})`:`max(200px, calc(${lg} - ${r}px))`;return{width:n??`var(--persona-components-panel-width)`,maxWidth:n??`var(--persona-components-panel-maxWidth)`,height:i,maxHeight:`var(--persona-components-panel-maxHeight)`}},dg=`16px`,fg=`10px`,pg=`14px`,mg=e=>{let t=e?.launcher?.enabled??!0,n=Mm(e);if(Nm(e)){let t=e?.launcher?.composerBar??{},n=q(`div`,`persona-widget-wrapper persona-fixed persona-transition`);n.setAttribute(`data-persona-composer-bar`,``),n.dataset.state=`collapsed`,n.dataset.expandedSize=t.expandedSize??`anchored`,n.style.zIndex=String(e?.launcher?.zIndex??1e5);let r=q(`div`,`persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);r.style.width=`100%`,n.appendChild(r);let i=q(`div`,`persona-widget-pill-root`);return i.setAttribute(`data-persona-composer-bar`,``),i.dataset.state=`collapsed`,i.dataset.expandedSize=t.expandedSize??`anchored`,i.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:n,panel:r,pillRoot:i}}if(n){let e=q(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`),t=q(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);return e.appendChild(t),{wrapper:e,panel:t}}if(!t){let t=q(`div`,`persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0`),n=q(`div`,`persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0`),r=fo(e),i=r.launcherWidth||r.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?ug(e).width:`100%`;return t.style.width=i,n.style.width=`100%`,t.appendChild(n),{wrapper:t,panel:n}}let r=e?.launcher??{},i=r.position&&Hm[r.position]?Hm[r.position]:Hm[`bottom-right`],a=q(`div`,`persona-widget-wrapper persona-fixed ${i} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let o=q(`div`,`persona-widget-panel persona-relative persona-min-h-[320px]`),s=ug(e);return o.style.width=s.width,o.style.maxWidth=s.maxWidth,a.appendChild(o),{wrapper:a,panel:o}},hg=e=>{let t=J(`div`,{className:`persona-suggestions`,attrs:{"data-persona-suggestions":Fm(e)}});return t.hidden=!0,t},gg=(e,t)=>{let n=hg(`starter`),r=Wh(e,n,{flatShadow:Mm(e)}),i=og(e);Kh(r,i),Gh(t,r.host,cg(i,e?.initialMessages));let a=Qh();return $h(a,i.message,e),{welcome:r,greetingHost:a}},_g=(e,t)=>{let n=q(`div`,`persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary`);n.setAttribute(`data-persona-theme-zone`,`container`);let{button:r,wrapper:i}=qm(e,{showClose:t,wrapperClassName:`persona-composer-bar-close`,buttonSize:dg,iconSize:fg});i.style.position=`absolute`,i.style.top=`8px`,i.style.right=`8px`,i.style.zIndex=`10`;let a=e?.launcher?.clearChat?.enabled??!0,o=null,s=null;if(a){let t=Jm(e,{wrapperClassName:`persona-composer-bar-clear-chat`,buttonSize:dg,iconSize:pg});o=t.button,s=t.wrapper,s.style.position=`absolute`,s.style.top=`8px`,s.style.right=`32px`,s.style.zIndex=`10`}let c=J(`span`,{className:`persona-widget-header`,attrs:{"data-persona-theme-zone":`header`},style:{display:`none`}}),l=J(`div`,{className:`persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6`,attrs:{id:`persona-scroll-container`,"data-persona-theme-zone":`messages`},style:{paddingTop:`48px`}});l.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:u,greetingHost:d}=gg(e,l),{host:f,title:p,subtitle:m}=u,h=u.starterSuggestions,g=q(`div`,`persona-widget-messages persona-flex persona-flex-col`);g.style.gap=`var(--persona-components-message-gap, 12px)`;let _=hg(`followUp`),v=Ap(e,!0);v&&(g.style.maxWidth=v,g.style.marginLeft=`auto`,g.style.marginRight=`auto`,g.style.width=`100%`),l.append(f,d,g,_);let y=J(`div`,{className:`persona-composer-overlay persona-pointer-events-none`,attrs:{"data-persona-composer-overlay":``},style:{position:`absolute`,left:`0`,right:`0`,bottom:`calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))`,zIndex:`20`}}),b=mh({config:e}),{root:x,textNode:S}=ph();return n.append(c,i,l,y),s&&n.appendChild(s),{container:n,body:l,messagesWrapper:g,starterSuggestions:h,transcriptSuggestions:_,composerOverlay:y,suggestions:b.suggestions,textarea:b.textarea,sendButton:b.sendButton,sendButtonWrapper:b.sendButtonWrapper,micButton:b.micButton,micButtonWrapper:b.micButtonWrapper,composerForm:b.composerForm,statusText:b.statusText,welcomeHost:f,welcomeIconHolder:u.iconHolder,greetingHost:d,introKicker:u.kicker,introTitle:p,introSubtitle:m,closeButton:r,closeButtonWrapper:i,clearChatButton:o,clearChatButtonWrapper:s,iconHolder:q(`span`),headerTitle:q(`span`),headerSubtitle:q(`span`),header:c,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:x,peekTextNode:S}},vg=(e,t=!0)=>{if(Nm(e))return _g(e,t);let n=J(`div`,{className:`persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border`,attrs:{"data-persona-theme-zone":`container`}}),r=e?.layout?.header,i=e?.layout?.showHeader!==!1,a=r?dh(e,r,{showClose:t}):Qm({config:e,showClose:t}),o=J(`div`,{className:`persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6`,attrs:{id:`persona-scroll-container`,"data-persona-theme-zone":`messages`}});o.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:s,greetingHost:c}=gg(e,o),{host:l,title:u,subtitle:d}=s,f=s.starterSuggestions,p=q(`div`,`persona-widget-messages persona-flex persona-flex-col`);p.style.gap=`var(--persona-components-message-gap, 12px)`;let m=hg(`followUp`),h=Ap(e,!1);h&&(p.style.maxWidth=h,p.style.marginLeft=`auto`,p.style.marginRight=`auto`,p.style.width=`100%`),o.append(l,c,p,m);let g=fh({config:e}),_=e?.layout?.showFooter!==!1;i||(a.header.style.display=`none`),$m(n,a,e),n.append(o);let v=J(`div`,{className:`persona-composer-overlay persona-pointer-events-none`,attrs:{"data-persona-composer-overlay":``},style:{position:`absolute`,left:`0`,right:`0`,bottom:`calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))`,zIndex:`20`}});return _||(g.footer.style.display=`none`),n.append(g.footer),n.append(v),{container:n,body:o,messagesWrapper:p,starterSuggestions:f,transcriptSuggestions:m,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,welcomeHost:l,welcomeIconHolder:s.iconHolder,greetingHost:c,introKicker:s.kicker,introTitle:u,introSubtitle:d,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};Y(),mn(),yi();const yg=(e,t)=>{let n=q(`button`);n.type=`button`,n.innerHTML=`
|
|
22
|
+
`),o=Array.isArray(e.contentParts)&&e.contentParts.length>0,s=r.contentParts.length>0;if(o){let t=[];i&&t.push(Ro(i)),t.push(...r.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(s){let t=[];a&&t.push(Ro(a)),t.push(...r.contentParts),e.contentParts=t}else i&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,t){let n=e.trim(),r=!!t?.replayFields&&(t.replayFields.llmContent!==void 0||t.replayFields.rawContent!==void 0||(t.replayFields.contextMentions?.length??0)>0);if(!n&&(!t?.contentParts||t.contentParts.length===0)&&(!t?.mentions||t.mentions.refs.length===0)&&!r)return;this.#U&&!t?.voiceTurn&&(this.#U.failed=!0,this.#U=null),(this.#T||this.#D||this.#w||this.#P)&&await this.#ke(),this.stopSpeaking(),this.abortController?.abort(),this.#He(),this.#Le++,this.#it();let i=t?.voiceTurn?.userMessageId,a=i?this.messages.find(e=>e.id===i&&e.role===`user`):void 0,o=a?.id??qs(),s=Js();this.#i=null;let c=t?.contentParts&&Io(t.contentParts)?Yo:``,l={id:o,role:`user`,content:n||c,createdAt:(/* @__PURE__ */ new Date()).toISOString(),sequence:this.#mt(),viaVoice:t?.viaVoice||!1,...t?.contentParts&&t.contentParts.length>0&&{contentParts:t.contentParts},...t?.mentions&&t.mentions.refs.length>0&&{contextMentions:t.mentions.refs},...t?.contentSegments&&t.contentSegments.length>0&&{contentSegments:t.contentSegments},...t?.composerOptions&&{composerOptions:t.composerOptions},...t?.replayFields??{}};a?(a.viaVoice=!0,delete a.voiceCaption,a.content.trim()!==n&&(a.llmContent=n),this.callbacks.onMessagesChanged([...this.messages])):this.#ft(l),this.#ct(!0);let u=new AbortController;if(this.abortController=u,t?.mentions){let e=this.messages.find(e=>e.id===o)??l;if(await this.#Ne(e,n,t.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(t?.quote&&!t.replayFields){let e=this.messages.find(e=>e.id===o)??l,n=Fu({quote:t.quote,text:e.llmContent??e.content,contentParts:e.contentParts});n.contentParts&&(e.contentParts=n.contentParts),n.llmContent!==void 0&&(e.llmContent=n.llmContent),(n.contentParts||n.llmContent!==void 0)&&(e.quote={...t.quote},this.callbacks.onMessagesChanged([...this.messages]))}let d=(/* @__PURE__ */ new Date()).toISOString(),f=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:d}]:[...this.messages],p=(a??this.messages.find(e=>e.id===o))?.createdAt??d,m=Au(t?.voiceTurn?.priorToolResults,p);for(let e of m)this.messages.some(t=>t.id===e.id)||(this.#ft(e),f.push({...e,createdAt:d}));let h=m.map(({agentMetadata:e})=>{let{toolCallId:t,toolName:n,args:r,result:i}=e.clientToolAnswer;return{toolCallId:t,name:n,arguments:r,result:i}});try{await this.#je(f,u,s,o,{composerOptions:t?.composerOptions,interrupt:t?.interrupt,voiceSpoken:!!t?.voiceTurn,...h.length>0&&{voicePriorToolResults:h}})}catch(e){if(this.status===`resuming`||this.#a)return;this.#U&&(this.#U.failed=!0);let t=e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`abort`));if(!t){let t=gd(e,this.config.errorMessage);if(t){let e={id:s,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:t,localOnly:!0,sequence:this.#mt()};this.#ft(e)}}this.#st(`idle`),this.#ct(!1),this.abortController=null,t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(Error(String(e))))}}resubmitFrom(e,t){let n=Lu(this.messages,e);if(!n)return!1;let r=this.messages[n.start],i=t.replacement,a=i?i.text:r.content,o=i?i.contentParts:r.contentParts;if(!(a?.trim()||(o?.length??0)>0||!i&&(r.llmContent?.trim()?.length??0)>0))return!1;let s=i?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},c=i?this.#Pe(i.options):r.composerOptions,l=i?i.contentSegments:r.contentSegments,u=i?i.options?.quote:void 0,d=i?i.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(a??``,{...o?.length?{contentParts:[...o]}:{},...l?.length?{contentSegments:[...l]}:{},...c?{composerOptions:c}:{},...u?{quote:u}:{},...s&&Object.keys(s).length>0?{replayFields:s}:{},viaVoice:d===!0}),!0}#Pe(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}async continueConversation(){if(this.streaming)return;(this.#T||this.#D||this.#w||this.#P)&&await this.#ke(),this.abortController?.abort(),this.#it();let e=Js();this.#i=null,this.#ct(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(t){if(this.status===`resuming`||this.#a)return;let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));if(!n){let n=gd(t,this.config.errorMessage);if(n){let t={id:e,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:n,localOnly:!0,sequence:this.#mt()};this.#ft(t)}}this.#st(`idle`),this.#ct(!1),this.abortController=null,n||(t instanceof Error?this.callbacks.onError?.(t):this.callbacks.onError?.(Error(String(t))))}}async connectStream(e,t){if(this.streaming&&!t?.allowReentry)return;t?.allowReentry||this.abortController?.abort(),t?.preserveAssistantId&&t.assistantMessageId&&(this.#i=t.assistantMessageId);let n=t?.preserveAssistantId?t.assistantMessageId:void 0,r=!1;for(let e of this.messages)e.streaming&&e.id!==n&&(e.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#ct(!0);let i={};try{await this.client.processStream(e,e=>{let t=this.#t;this.#t=i;try{this.handleEvent(e)}finally{this.#t=t}},t?.assistantMessageId,t?.seedContent),this.#lt(i)}catch(e){if(this.status===`resuming`||this.#a){this.#ut(i);return}this.#lt(i),this.#st(`error`),this.webMcpResolveControllers.size===0&&(this.#ct(!1),this.abortController=null),this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))}}#Fe(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}if(e.signal?.aborted)return Promise.resolve(!1);let t;do t=`webmcp-${++this.#d}`;while(this.messages.some(e=>e.id===`approval-${t}`||e.approval?.id===t));let n={id:t,status:`pending`,agentId:``,executionId:``,toolName:e.toolName,toolType:`webmcp`,description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,approval:n}),new Promise(t=>{this.webMcpApprovalResolvers.set(r,t),e.signal?.addEventListener(`abort`,()=>this.resolveWebMcpApproval(r,`timeout`),{once:!0})})}resolveWebMcpApproval(e,t){let n=this.webMcpApprovalResolvers.get(e);if(!n)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(t=>t.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:t,resolvedAt:Date.now()}}),n(t===`approved`)}#Ie;#Le;#Re(e){let t=this.#Ie??={s:this,setStreaming:e=>this.#ct(e),appendMessage:e=>this.#ft(e),nextSequence:()=>this.#mt(),settleApprovalPausedToolCall:e=>this.#dt(e),resumeAfter:e=>this.#r?.executionId===e?this.#r.lastEventId:void 0},n=gc();if(n)return e(n,t);let r=this.#Le;return mc().then(n=>r===this.#Le?e(n,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))})}resolveApproval(e,t,n){return this.#Re((r,i)=>r.resolveApproval(i,e,t,n))}resolveAskUserQuestion(e,t){return this.#Re((n,r)=>n.resolveAskUserQuestion(r,e,t))}resolveWebMcpToolCall(e){return this.#Re((t,n)=>t.resolveWebMcpToolCall(n,e))}persistAskUserQuestionProgress(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}#ze(e){let t=e.agentMetadata?.executionId,n=e.toolCall?.id;if(!t||!n){let t=this.#u;queueMicrotask(()=>{t===this.#u&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(t);r||(r={snapshots:[],seen:/* @__PURE__ */ new Set},this.webMcpAwaitBatches.set(t,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(e))}#Be(){if(this.webMcpAwaitBatches.size===0)return;let e=this.#u;queueMicrotask(()=>{if(e===this.#u)for(let e of[...this.webMcpAwaitBatches.keys()])this.#Ve(e)})}#Ve(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:n}=t;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.#Re((t,r)=>t.resolveWebMcpToolCallBatch(r,e,n))}#He(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,`denied`);this.webMcpAwaitBatches.clear(),this.#u++}cancel(){this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#ct(!1),this.#st(`idle`)}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.messages=[],this.agentExecution=null,this.#Ge(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#ct(!1),this.#st(`idle`),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#l}selectArtifact(e){this.#l=e,this.#Ke()}clearArtifacts(){this.#Ge()}upsertArtifact(e){let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=e.artifactType===`markdown`?{id:t,artifactType:`markdown`,title:e.title,status:`complete`,markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:t,artifactType:`component`,title:e.title,status:`complete`,component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(t,n),this.#l=t,this.#Ke(),e.transcript!==!1&&this.#Ue(n),n}#Ue(e){let t=`artifact-ref-${e.id}`,n=Mn(jn(this.config.features?.artifacts,e),{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:`complete`,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown===void 0?{}:{markdown:e.markdown}}),r=this.messages.find(e=>e.id===t);r?(r.rawContent=n,r.streaming=!1,this.callbacks.onMessagesChanged([...this.messages])):this.injectAssistantMessage({id:t,content:``,rawContent:n})}#We(){let e=!1;for(let t of this.artifacts.values()){let n=this.messages.find(e=>e.id===`artifact-ref-${t.id}`);if(!n)continue;let r=Mn(jn(this.config.features?.artifacts,t),{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown===void 0?{}:{markdown:t.markdown}});n.rawContent!==r&&(n.rawContent=r,n.streaming=t.status===`streaming`,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#Ge(){(this.artifacts.size!==0||this.#l!==null)&&(this.artifacts.clear(),this.#l=null,this.#Ke())}#Ke(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#l})}#qe(e){switch(e.type){case`artifact_start`:e.artifactType===`markdown`?this.artifacts.set(e.id,{id:e.id,artifactType:`markdown`,title:e.title,status:`streaming`,markdown:``,...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:`component`,title:e.title,status:`streaming`,component:e.component??``,props:{}}),this.#l=e.id;break;case`artifact_delta`:{let t=this.artifacts.get(e.id);t?.artifactType===`markdown`&&(t.markdown=(t.markdown??``)+e.artDelta);break}case`artifact_update`:{let t=this.artifacts.get(e.id);t?.artifactType===`component`&&(t.props={...t.props,...e.props},e.component&&(t.component=e.component));break}case`artifact_complete`:{let t=this.artifacts.get(e.id);t&&(t.status=`complete`);break}default:return}this.#Ke()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#gt(e.map(e=>({...pl(e),streaming:!1,sequence:e.sequence??this.#mt()}))),this.#ct(!1),this.#st(`idle`),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let t of e)this.artifacts.set(t.id,{...t,status:`complete`});this.#l=t,this.#Ke()}#Je(e){let t=this.agentExecution?.executionId;if(!t||!this.#i||this.agentExecution?.status!==`running`)return;let n=this.#r===null;this.#r={executionId:t,lastEventId:e,assistantMessageId:this.#i,status:`running`},this.#ot(n)}#Ye(){return this.#r!==null&&typeof this.config.reconnectStream==`function`&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#Xe()}#Xe(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant===`approval`&&e.approval?.status===`pending`)}#Ze(){this.#a||this.#r&&typeof this.config.reconnectStream==`function`&&(this.#a=!0,this.callbacks.onReconnect?.({phase:`paused`,handle:this.#r}),this.#ct(!0),this.#st(`resuming`),this.#Qe().then(e=>{this.#a&&this.#r&&e.begin()}))}#Qe(){return this.#o?Promise.resolve(this.#o):(this.#s||(this.#s=fd().then(({createReconnectController:e})=>{let t=e(this.#$e());return this.#o=t,t}),this.#s.catch(()=>{this.#s=null})),this.#s)}#$e(){let e=this;return{get config(){return e.config},getResumable:()=>e.#r,clearResumable:()=>e.#at(),getStatus:()=>e.status,setStatus:t=>e.#st(t),setStreaming:t=>e.#ct(t),setReconnecting:t=>{e.#a=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,n,r)=>e.connectStream(t,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:t=>e.#ft(t),settleParked:t=>e.#et(t),nextSequence:()=>e.#mt(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>gd(Error(t),e.config.errorMessage),onError:t=>e.callbacks.onError?.(t)}}reconnectNow(){this.#a?this.#o?.wake():this.#Ze()}resumeFromHandle(e){if(typeof this.config.reconnectStream!=`function`||this.#a)return;if(this.#Xe()){this.#tt(e.executionId),this.#r={executionId:e.executionId,lastEventId:e.after,assistantMessageId:this.#i??``,status:`running`};return}let t=this.#nt(e.executionId)?Js():this.#rt();t||(t=Js(),this.#ft({id:t,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:this.#mt()})),this.#i=t,this.#tt(e.executionId),this.#r={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:`running`},this.#Ze()}#et(e){let t=this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0;if(!t&&!this.#Xe()){if(!this.#nt(e))return!1;this.#at()}if(this.#a=!1,!t){let e=!1;for(let t of this.messages)t.streaming&&(t.streaming=!1,e=!0);e&&this.callbacks.onMessagesChanged([...this.messages]),this.#ct(!1),this.abortController=null}return this.#st(`idle`),!0}#tt(e){this.agentExecution||={executionId:e,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0}}#nt(e){return this.messages.some(t=>t.agentMetadata?.executionId===e&&[t.toolCall,...t.tools??[]].some(e=>e?.interrupted===!0))}#rt(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role===`assistant`&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role===`user`)break}return null}#it(){this.#a=!1,this.#o?.teardown(),this.#at()}#at(){this.#c&&=(clearTimeout(this.#c),null);let e=this.#r!==null;this.#r=null,e&&this.config.onExecutionState?.(null)}#ot(e){let t=this.config.onExecutionState;t&&(e?(this.#c&&=(clearTimeout(this.#c),null),t(this.#r)):this.#c||=setTimeout(()=>{this.#c=null,this.config.onExecutionState?.(this.#r)},500))}getResumableHandle(){return this.#r}#st(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#ct(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&(this.#lt(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(e){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider===`browser`||t.provider===`runtype`&&t.browserFallback))return;let n=[...this.messages].reverse().find(e=>e.role===`assistant`&&e.content&&!e.voiceProcessing);if(!n||e&&!e.includes(n.id))return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=Xu(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return Vu(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||t.role!==`assistant`)return;let n=Xu(t.content||``);if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<`u`&&`speechSynthesis`in window&&window.speechSynthesis.cancel()}#lt(e){for(let[t,n]of[...this.#e])n===e&&(this.#e.delete(t),this.#dt(t))}#ut(e){for(let[t,n]of this.#e)n===e&&this.#e.set(t,void 0)}#dt(e){let t=this.messages.find(t=>t.id===e)?.approval,n=t?.toolCallId,r=n&&this.messages.find(e=>e.toolCall?.id===n),i=r&&r.toolCall;if(!i||i.status===`complete`||t.status===`pending`)return;let a={...i,status:`complete`,approvalStatus:t.status,completedAt:Date.now(),...t.status===`approved`?{superseded:!0}:{success:!1,error:t.status===`denied`?`Denied`:`Approval timed out`}};this.upsertMessage({...r,streaming:!1,toolCall:a})}#ft(e){let t=this.#pt(e),n=this.messages[this.messages.length-1];this.messages=!n||this.#ht(n,t)<=0?[...this.messages,t]:this.#gt([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#pt(e),n=this.messages.findIndex(e=>e.id===t.id);if(n===-1){this.#ft(t);return}this.messages=this.messages.map((e,r)=>{if(r!==n||e.toolCall?.name&&wn(e.toolCall.name)&&e.toolCall.status===`complete`&&t.toolCall?.id===e.toolCall.id&&t.toolCall.status!==`complete`&&(t.toolCall.status===`pending`&&!t.toolCall.name||!e.toolCall.interrupted&&(e.toolCall.result!==void 0||e.toolCall.success!==void 0)&&(!t.agentMetadata?.executionId||t.agentMetadata.executionId===e.agentMetadata?.executionId)))return e;let i={...e,...t};e.agentMetadata?.askUserQuestionAnswered===!0&&t.agentMetadata&&(i.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),e.agentMetadata?.suggestRepliesResolved===!0&&t.agentMetadata&&(i.agentMetadata={...i.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let n=e.approval,r=t.approval;i.approval={...n,...r,executionId:r.executionId||n.executionId,toolName:r.toolName||n.toolName,description:r.description||n.description,toolType:r.toolType??n.toolType,reason:r.reason??n.reason,parameters:r.parameters??n.parameters,toolCallId:r.toolCallId??n.toolCallId}}let o=t.toolCall?.name,s=t.agentMetadata?.executionId,c=t.toolCall?.id;if(o&&_d(o)&&s&&c&&t.agentMetadata?.awaitingLocalTool===!0){let t=`${s}:${c}`,n=this.webMcpInflightKeys.has(t),r=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,o=e.agentMetadata?.executionId===s&&e.toolCall?.id===c&&a!==void 0&&_d(a)&&e.toolCall?.status===`complete`&&!e.toolCall.interrupted;(n||r||o)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=e.toolCall,i.streaming=e.streaming)}return i});let r=this.messages[n],i=this.messages[n-1],a=this.messages[n+1];(i&&this.#ht(i,r)>0||a&&this.#ht(r,a)>0)&&(this.messages=this.#gt(this.messages)),this.callbacks.onMessagesChanged([...this.messages])}#pt(e){return e.sequence===void 0?{...e,sequence:this.#mt()}:{...e}}#mt(){return this.#n++}#ht(e,t){let n=new Date(e.createdAt).getTime(),r=new Date(t.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(r)&&n!==r)return n-r;let i=e.sequence??0,a=t.sequence??0;return i===a?e.id.localeCompare(t.id):i-a}#gt(e){return[...e].sort((e,t)=>this.#ht(e,t))}};Y(),Yt(),mn(),$o();const yd={add:e=>Go(e)},bd=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,xd={allowedTypes:Qo,maxFileSize:10485760,maxFiles:4};function Sd(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Cd(e){return e===`application/pdf`||e.startsWith(`text/`)||e.includes(`word`)?fe:e.includes(`excel`)||e.includes(`spreadsheet`)?de:e===`application/json`?ue:le}var wd=class e{#e;#t;#n;constructor(e={}){this.attachments=[],this.#e=null,this.#t=/* @__PURE__ */ new Map,this.#n=!1,this.config={allowedTypes:e.allowedTypes??xd.allowedTypes,maxFileSize:e.maxFileSize??xd.maxFileSize,maxFiles:e.maxFiles??xd.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#r(){return typeof this.config.adapter?.add==`function`}#i(){return this.#r()?this.config.adapter:yd}setPreviewsContainer(e){this.#e=e}remountPreviews(e){if(this.#e=e,e){e.innerHTML=``;for(let e of this.attachments)this.#l(e)}this.#f()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:xd.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status===`ready`)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){e&&e.length!==0&&await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#n)return;let t=[];for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,`count`);continue}let e=Ko(n,this.config.allowedTypes,this.config.maxFileSize);if(!e.valid){let t=e.error?.includes(`type`)?`type`:`size`;this.config.onFileRejected?.(n,t);continue}let r={id:Sd(),file:n,previewUrl:Uo(n)?URL.createObjectURL(n):null,contentPart:null,status:this.#r()?`uploading`:`processing`,progress:this.#r()?0:void 0};this.attachments.push(r),this.#l(r),t.push(r)}this.#f(),this.#c(),await Promise.all(t.map(e=>this.#a(e)))}async#a(e){let t=new AbortController;this.#t.set(e.id,t);let n=()=>this.#n||t.signal.aborted||this.#t.get(e.id)!==t||!this.attachments.includes(e);try{let r=await this.#i().add(e.file,{signal:t.signal,onProgress:t=>{n()||e.status!==`uploading`||(e.progress=bd(t),this.#u(e),this.#c())}});if(n())return;e.contentPart=r,e.status=`ready`,e.progress=void 0,e.error=void 0}catch(t){if(n())return;e.status=`error`,e.progress=void 0,e.error=t instanceof Error?t.message:String(t??`Upload failed`)}finally{this.#t.get(e.id)===t&&this.#t.delete(e.id)}this.#u(e),this.#c()}retryAttachment(e){let t=this.attachments.find(t=>t.id===e);!t||t.status!==`error`||this.#n||(t.status=this.#r()?`uploading`:`processing`,t.progress=this.#r()?0:void 0,t.error=void 0,this.#u(t),this.#c(),this.#a(t))}#o(e){let t=this.#t.get(e);t&&(this.#t.delete(e),t.abort())}removeAttachment(e){let t=this.attachments.findIndex(t=>t.id===e);if(t===-1)return;let n=this.attachments[t];this.#o(e),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let r=this.#e?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),n.status===`ready`&&n.contentPart&&this.#s(n.contentPart),this.#f(),this.#c()}#s(e){let t=this.config.adapter?.remove;if(t)try{let n=t(e,{signal:new AbortController().signal});n&&typeof n.catch==`function`&&n.catch(e=>{console.error(`[AttachmentManager] adapter.remove failed:`,e)})}catch(e){console.error(`[AttachmentManager] adapter.remove failed:`,e)}}clearAttachments(){for(let e of this.attachments)this.#o(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=``),this.#f(),this.#c()}destroy(){if(!this.#n){this.#n=!0;for(let e of this.#t.values())e.abort();this.#t.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#e=null}}#c(){this.#n||this.config.onAttachmentsChange?.(this.getAttachments())}#l(e){if(!this.#e)return;let t=Uo(e.file),n=q(`div`,`persona-attachment-preview persona-relative persona-inline-block`);if(n.setAttribute(`data-attachment-id`,e.id),n.style.width=`48px`,n.style.height=`48px`,t&&e.previewUrl){let t=q(`img`);t.src=e.previewUrl,t.alt=e.file.name,t.className=`persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200`,t.style.width=`48px`,t.style.height=`48px`,t.style.objectFit=`cover`,t.style.borderRadius=`8px`,n.appendChild(t)}else{let t=q(`div`);t.style.width=`48px`,t.style.height=`48px`,t.style.borderRadius=`8px`,t.style.backgroundColor=`var(--persona-container, #f3f4f6)`,t.style.border=`1px solid var(--persona-border, #e5e7eb)`,t.style.display=`flex`,t.style.flexDirection=`column`,t.style.alignItems=`center`,t.style.justifyContent=`center`,t.style.gap=`2px`,t.style.overflow=`hidden`;let r=Cd(e.file.type),i=Jt(r,20,`var(--persona-muted, #6b7280)`,1.5);i&&t.appendChild(i);let a=q(`span`);a.textContent=Jo(e.file.type,e.file.name),a.style.fontSize=`8px`,a.style.fontWeight=`600`,a.style.color=`var(--persona-muted, #6b7280)`,a.style.textTransform=`uppercase`,a.style.lineHeight=`1`,t.appendChild(a),n.appendChild(t)}let r=J(`div`,{className:`persona-attachment-status`,attrs:{"data-persona-attachment-status":``}}),i=q(`div`,`persona-attachment-progress`);i.appendChild(q(`div`,`persona-attachment-progress__bar`));let a=J(`button`,{className:`persona-attachment-retry`,attrs:{type:`button`,"aria-label":`Retry upload`}}),o=K(`rotate-cw`,12,`var(--persona-text-inverse, #ffffff)`,2);o?a.appendChild(o):a.textContent=`↻`,a.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.retryAttachment(e.id)}),r.append(i,a),n.appendChild(r);let s=q(`button`,`persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center`);s.type=`button`,s.setAttribute(`aria-label`,`Remove attachment`),s.style.position=`absolute`,s.style.top=`-4px`,s.style.insetInlineEnd=`-4px`,s.style.width=`18px`,s.style.height=`18px`,s.style.borderRadius=`50%`,s.style.backgroundColor=`var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))`,s.style.border=`none`,s.style.cursor=`pointer`,s.style.display=`flex`,s.style.alignItems=`center`,s.style.justifyContent=`center`,s.style.padding=`0`;let c=Jt(Tt,10,`var(--persona-text-inverse, #ffffff)`,2);c?s.appendChild(c):(s.textContent=`×`,s.style.color=`var(--persona-text-inverse, #ffffff)`,s.style.fontSize=`14px`,s.style.lineHeight=`1`),s.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.removeAttachment(e.id)}),n.appendChild(s),this.#e.appendChild(n),this.#d(n,e)}#u(e){let t=this.#e?.querySelector(`[data-attachment-id="${e.id}"]`);t&&this.#d(t,e)}#d(e,t){e.dataset.status=t.status;let n=t.status!==`ready`&&t.status!==`error`;e.setAttribute(`aria-busy`,n?`true`:`false`),e.title=t.status===`error`?`${t.file.name}: ${t.error??`Upload failed`}`:t.file.name;let r=e.querySelector(`.persona-attachment-progress__bar`);if(r){let e=t.progress;r.style.width=typeof e==`number`?`${Math.round(e*100)}%`:``}}#f(){this.#e&&(this.#e.style.display=this.attachments.length>0?`flex`:`none`)}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n,adapter:t?.adapter})}};const Td=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),Ed=(e,t)=>e.length===t.length&&e.every((e,n)=>{let r=t[n];return e.id===r.id&&e.name===r.name&&e.mimeType===r.mimeType&&e.size===r.size&&e.status===r.status&&e.progress===r.progress&&e.error===r.error});function Dd(){let e={text:``,attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=/* @__PURE__ */ new Set,n=null,r=!1,i=!1,a=()=>e.preparing?`preparing`:e.streaming?`streaming`:`idle`,o=()=>{let t=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(e=>Object.freeze({...e}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:t,inputDisabled:e.inputDisabled,sendDisabled:t!==`idle`||e.sendDisabled||e.inputDisabled})},s=()=>(n||=o(),n),c=()=>{if(r=!1,i||t.size===0)return;let e=s();for(let n of[...t])try{n(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] composer state listener failed:`,e)}},l=()=>{n=null,!(i||r)&&(r=!0,queueMicrotask(c))};return{getState:s,subscribe:e=>(t.add(e),()=>t.delete(e)),setText:t=>{e.text!==t&&(e.text=t,l())},setAttachments:t=>{Ed(e.attachments,t)||(e.attachments=[...t],l())},setMentionRefs:t=>{Td(e.mentionRefs,t)||(e.mentionRefs=[...t],l())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,l())},setActiveModeIds:t=>{Td(e.activeModeIds,t)||(e.activeModeIds=[...t],l())},setQuote:t=>{let n=e.quote;(n?.text!==t?.text||n?.messageId!==t?.messageId||n?.sourceLabel!==t?.sourceLabel)&&(e.quote=t?{...t}:void 0,l())},setPendingSubmission:t=>{e.pendingSubmission!==t&&(e.pendingSubmission=t,l())},setPreparing:t=>{e.preparing!==t&&(e.preparing=t,l())},setStreaming:t=>{e.streaming!==t&&(e.streaming=t,l())},setInputDisabled:t=>{e.inputDisabled!==t&&(e.inputDisabled=t,l())},setSendDisabled:t=>{e.sendDisabled!==t&&(e.sendDisabled=t,l())},flush:()=>{r&&c()},destroy:()=>{i=!0,r=!1,t.clear()}}}Y();const Od=(e,...t)=>{for(let n of t){let t=e.querySelector(n);if(t)return t}return null},kd=(e,t)=>{let n=q(`div`,e);return n.setAttribute(t,``),n.setAttribute(`data-persona-composer-synthesized`,``),n.style.display=`contents`,n};function Ad(e,t={}){let n=Od(e,`[data-persona-composer-form]`),r=Od(e,`[data-persona-composer-input]`);if(!n||!r){let e=`[Persona] composer surface is missing required element(s): ${[!n&&`form`,!r&&`input`].filter(Boolean).join(`, `)}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||r))throw Error(e);return typeof console<`u`&&console.warn(e),null}let i={header:Od(e,`[data-persona-composer-header]`),body:Od(e,`[data-persona-composer-body]`),actionsStart:Od(e,`[data-persona-composer-actions-start]`,`.persona-widget-composer__left-actions`),actionsEnd:Od(e,`[data-persona-composer-actions-end]`,`.persona-widget-composer__right-actions`),actionsRow:Od(e,`[data-persona-composer-actions]`,`.persona-widget-composer .persona-flex.persona-items-center.persona-justify-between`),suggestions:Od(e,`[data-persona-composer-suggestions]`,`.persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2`),status:Od(e,`[data-persona-composer-status]`)},a=/* @__PURE__ */ new Set,o=i.header;o||(a.add(`header`),o=kd(`persona-widget-composer__header`,`data-persona-composer-header`),n.parentNode?n.parentNode.insertBefore(o,n):e.appendChild(o));let s=i.body??r.parentElement??n,c=(e,t,n,r,i)=>{if(t)return t;a.add(e);let o=kd(n,r);return i.appendChild(o),o},l=c(`actionsStart`,i.actionsStart,`persona-widget-composer__left-actions`,`data-persona-composer-actions-start`,n),u=c(`actionsEnd`,i.actionsEnd,`persona-widget-composer__right-actions`,`data-persona-composer-actions-end`,n),d=c(`suggestions`,i.suggestions,`persona-widget-composer__suggestions`,`data-persona-composer-suggestions`,e),f=c(`status`,i.status,`persona-widget-composer__status`,`data-persona-composer-status`,e),p=[],m=(e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler,h=Od(e,`[data-persona-composer-attachment-input]`,`input[type="file"]`)??void 0;return{footer:e,form:n,input:r,header:o,body:s,actionsStart:l,actionsEnd:u,suggestions:d,status:f,attachmentInput:h,attachmentPreviews:Od(e,`[data-persona-composer-attachment-previews]`,`.persona-attachment-previews`)??void 0,attachmentButton:Od(e,`[data-persona-composer-attachment-button]`,`.persona-attachment-button`)??void 0,sendButton:Od(e,`[data-persona-composer-submit]`)??void 0,micButton:Od(e,`[data-persona-composer-mic]`)??void 0,synthesized:a,found:i,addListener:(e,t,n,r)=>{e.addEventListener(t,n,r),p.push({target:e,type:t,handler:n,options:r})},removeListener:(e,t,n,r)=>{e.removeEventListener(t,n,r),p=p.filter(r=>!m(r,{target:e,type:t,handler:n}))},destroy:()=>{for(let e of p)e.target.removeEventListener(e.type,e.handler,e.options);p=[]}}}function jd(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Md(e){let{anchor:t,content:n,placement:r=`bottom-start`,offset:i=6,matchAnchorWidth:a=!1,horizontalOffset:o,verticalOffset:s,zIndex:c=2147483e3,onOpen:l,onDismiss:u}=e,d=e.container??jd(t),f=!1,p=null,m=()=>{if(!f)return;let e=t.getBoundingClientRect();n.style.position=`fixed`,a&&(n.style.minWidth=`${e.width}px`),o&&(n.style.maxWidth=`${e.width}px`);let c=n.getBoundingClientRect(),l=s?.()??null,u=l==null?e.top:e.top+l,d=r===`top-start`||r===`top-end`?u-i-c.height:e.bottom+i,p=r===`bottom-end`||r===`top-end`?e.right-c.width:e.left,m=o?.()??null;if(m!=null){let t=Math.max(e.left,e.right-c.width);p=Math.min(Math.max(e.left+m,e.left),t)}n.style.top=`${d}px`,n.style.left=`${p}px`},h=()=>{f&&(f=!1,p&&=(p(),null),n.remove())},g=()=>{if(f)return;f=!0,c!=null&&(n.style.zIndex=String(c)),d.appendChild(n),m();let e=(t.ownerDocument??document).defaultView??window,r=t.ownerDocument??document,i=()=>{t.isConnected?m():(h(),u?.(`anchor-removed`))},a=e=>{let r=typeof e.composedPath==`function`?e.composedPath():[];r.includes(n)||r.includes(t)||(h(),u?.(`outside`))},o=e.setTimeout(()=>{r.addEventListener(`pointerdown`,a,!0)},0);e.addEventListener(`scroll`,i,!0),e.addEventListener(`resize`,i),p=()=>{e.clearTimeout(o),r.removeEventListener(`pointerdown`,a,!0),e.removeEventListener(`scroll`,i,!0),e.removeEventListener(`resize`,i)},l?.()};return{get isOpen(){return f},open:g,close:h,toggle:()=>f?h():g(),reposition:m,destroy:h}}Y(),mn(),xs();const Nd=[`--persona-components-composer-overflowMenu-background`,`--persona-components-composer-overflowMenu-borderColor`,`--persona-components-composer-overflowMenu-borderRadius`,`--persona-components-composer-overflowMenu-foreground`,`--persona-components-composer-overflowMenu-shadow`],Pd=`data-persona-menu-focus`,Fd=/* @__PURE__ */ new Set([`ArrowDown`,`ArrowUp`,`Home`,`End`]);function Id(e){return e.getAttribute(`role`)===`menuitem`?e:e.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`)??e}const Ld=e=>e.disabled===!0||e.getAttribute(`aria-disabled`)===`true`;function Rd(e){let t=e.label,n=!1,r=q(`div`,`persona-send-button-wrapper`),i=J(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${ds} ${fs}`,attrs:{type:`button`,"aria-haspopup":`menu`,"aria-expanded":`false`,"data-persona-composer-overflow-trigger":``}});r.appendChild(i);let a=J(`div`,{className:`persona-composer-overflow-menu`,attrs:{role:`menu`,tabindex:`-1`,"data-persona-composer-overflow-menu":``}}),o=()=>{let t=e.getButtonSize?.()??``;i.style.width=t,i.style.height=t,i.style.minWidth=t,i.style.minHeight=t,i.style.lineHeight=`1`,i.replaceChildren();let n=K(`plus`,24,`currentColor`,1.5);n?i.appendChild(n):i.textContent=`+`},s=()=>{i.setAttribute(`aria-label`,t),i.setAttribute(`title`,t),a.setAttribute(`aria-label`,t)};s(),o();let c=[],l=-1,u=!1,d=()=>{let e=a.getRootNode().activeElement;return e instanceof HTMLElement?e:null},f=()=>{let e=d();for(let t of c){let n=!!e&&Id(t)===e;t.toggleAttribute(Pd,n&&u)}},p=()=>c.filter(e=>e.isConnected||a.contains(e)).map(Id).filter(e=>!Ld(e)),m=(e,t)=>{e.forEach((e,n)=>{e.setAttribute(`tabindex`,n===t?`0`:`-1`)})},h=e=>{let t=p();if(t.length===0)return;let n=(e%t.length+t.length)%t.length;l=n,m(t,n),t[n].focus(),f()},g=()=>r.ownerDocument??document,_=null,v=null,y=null,b=()=>{_&&=(g().removeEventListener(`focusin`,_,!0),null)},x=()=>{v&&=(a.removeEventListener(`focusin`,v),null),y&&=(a.removeEventListener(`pointerdown`,y,!0),null)},S=null,C=()=>(S||=Md({anchor:i,content:a,placement:`top-start`,offset:6,onDismiss:()=>{i.setAttribute(`aria-expanded`,`false`),b()}}),S),w=()=>S?.isOpen===!0,T=(e=!1)=>{if(w()){S?.close(),i.setAttribute(`aria-expanded`,`false`),b(),x(),l=-1,u=!1;for(let e of c)e.removeAttribute(Pd);e&&i.focus()}},E=(e=0,t=!1)=>{if(n||w())return;u=t,ps(i,a,Nd),C().open(),i.setAttribute(`aria-expanded`,`true`);let o=p();m(o,-1),h(e<0?o.length-1:e),_=e=>{let t=typeof e.composedPath==`function`?e.composedPath():[];t.includes(a)||t.includes(r)||T()},g().addEventListener(`focusin`,_,!0),v=()=>f(),a.addEventListener(`focusin`,v),y=()=>{u=!1},a.addEventListener(`pointerdown`,y,!0)},D=e=>{e.preventDefault(),e.stopPropagation(),w()?T(!0):E(0)},O=e=>{e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),u=!0,w()?h(0):E(0,!0)):e.key===`ArrowUp`&&(e.preventDefault(),u=!0,w()?h(-1):E(-1,!0))},k=e=>{switch(Fd.has(e.key)&&(u=!0),e.key){case`ArrowDown`:e.preventDefault(),h(l+1);return;case`ArrowUp`:e.preventDefault(),h(l-1);return;case`Home`:e.preventDefault(),h(0);return;case`End`:e.preventDefault(),h(p().length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),T(!0);return;case`Tab`:T(!0);return}};return i.addEventListener(`click`,D),i.addEventListener(`keydown`,O),a.addEventListener(`keydown`,k),{trigger:r,triggerButton:i,panel:a,setItems:e=>{for(let t of c)e.includes(t)||t.removeAttribute(Pd);if(c=[...e],!w())return;let t=p();m(t,Math.min(l,t.length-1)),f()},isOpen:w,open:()=>E(0),close:T,setLabel:e=>{e!==t&&(t=e,s())},applyButtonSize:o,destroy:()=>{n=!0,b(),x(),i.removeEventListener(`click`,D),i.removeEventListener(`keydown`,O),a.removeEventListener(`keydown`,k),S?.destroy(),S=null,r.remove(),a.remove(),c=[]}}}Y(),mn(),Ua(),xs();const zd={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Bd=`data-persona-composer-action`,Vd=`data-persona-composer-disable-when-streaming`,Hd=e=>e===`core:attachment`?`attachments`:e.startsWith(`core:mention`)?`mentions`:null;function Ud(e,t){if(e===void 0)return null;if(typeof e==`number`)return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let r=q(`div`);r.style.position=`absolute`,r.style.visibility=`hidden`,r.style.pointerEvents=`none`,r.style.height=`0`,r.style.width=e,t.appendChild(r);let i=r.getBoundingClientRect().width;return r.remove(),Number.isFinite(i)&&i>0?i:Number.isFinite(n)?n:null}function Wd(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let r=n.getComputedStyle(e),i=(Number.parseFloat(r.paddingLeft)||0)+(Number.parseFloat(r.paddingRight)||0);return Math.max(0,t-i)}const Gd=(e,t)=>{e&&typeof console<`u`&&console.warn(t)},Kd=(e,t)=>t.includes(`:`)?t:`${e}:${t}`;function qd(e){let{debug:t}=e,n=[],r=/* @__PURE__ */ new Map,i=0,a=e=>{let i=r.get(e.id);i?Gd(t,`[Persona] composer action "${e.id}" is already contributed by ${Jd(i)}; the ${Jd(e)} copy is ignored.`):(r.set(e.id,e),n.push(e))};for(let t of e.builtIns)a({id:t.id,placement:t.placement,presentation:`bar`,order:t.order,sequence:i++,source:`core`,builtIn:t});let o=(e,n,r)=>{let o=r?Kd(r,e.id):e.id,s=e.order??zd.custom;e.placement===`end`&&s>=zd.send&&(Gd(t,`[Persona] composer action "${o}" ordered at ${s} would render after send; clamped to ${zd.send-1}.`),s=zd.send-1),a({id:o,placement:e.placement,presentation:e.presentation??`bar`,order:s,sequence:i++,source:n,pluginId:r,action:e})};for(let t of e.configActions??[])o(t,`config`);for(let t of e.plugins){if(!t.contributeComposerActions)continue;let n;try{n=t.contributeComposerActions(e.contributionContext)}catch(e){typeof console<`u`&&console.error(`[Persona] plugin "${t.id}" contributeComposerActions failed:`,e);continue}for(let e of n??[])o(e,`plugin`,t.id)}return n.sort((e,t)=>e.order===t.order?e.sequence-t.sequence:e.order-t.order)}const Jd=e=>e.source===`plugin`?`plugin "${e.pluginId}"`:e.source===`config`?`composer.actions`:`a core built-in`,Yd=(e,t,n)=>e===void 0?n:typeof e==`function`?e(t)===!0:e===!0,Xd=e=>e.phase===`streaming`||e.text.trim().length>0||e.attachments.length>0;function Zd(e,t){if(!e||e===`always`)return!0;let n=Xd(t);return e===`when-text`?n:!n}const Qd=e=>e.kind===`custom`,$d=e=>e instanceof HTMLButtonElement?e:e.querySelector(`button`)??e,ef=e=>{let t=$d(e);return t.getAttribute(`aria-label`)?.trim()||t.getAttribute(`title`)?.trim()||``};function tf(e){let t=``,n=e=>{if(e.nodeType===Node.TEXT_NODE){t+=e.nodeValue??``;return}if(e.nodeType!==Node.ELEMENT_NODE)return;let r=e;typeof r.matches==`function`&&r.matches(`.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]`)||e.childNodes.forEach(n)};return n(e),t.trim()}const nf=e=>tf(e).length===0;function rf(e){let t=/* @__PURE__ */ new Map,n=[],r=!1,i=()=>e.getButtonSize?.(),a=(e,t)=>{let n=e.button;if(!n)return;n.setAttribute(`role`,`menuitem`),n.setAttribute(`tabindex`,`-1`),n.className=`persona-composer-overflow-menu__item`;for(let e of[`width`,`height`,`minWidth`,`minHeight`,`fontSize`,`color`,`backgroundColor`])n.style[e]=``;n.style.lineHeight=`1`,t.tooltipText?n.setAttribute(`title`,t.tooltipText):n.removeAttribute(`title`),n.replaceChildren();let r=q(`span`,`persona-composer-overflow-menu__icon`);if(t.iconName){let e=K(t.iconName,16,`currentColor`,1.5);e&&r.appendChild(e)}let i=q(`span`,`persona-composer-overflow-menu__label`);i.textContent=t.shortLabel??t.label,n.append(r,i)},o=(e,t)=>{let n=e.button;if(!n)return;if(n.setAttribute(`aria-label`,t.label),t.pressed===void 0?n.removeAttribute(`aria-pressed`):n.setAttribute(`aria-pressed`,t.pressed?`true`:`false`),n.toggleAttribute(Vd,t.disableWhenStreaming===!0),e.mode===`menu`){e.tooltip?.destroy(),e.tooltip=void 0,a(e,t);return}n.removeAttribute(`role`),n.removeAttribute(`tabindex`),n.removeAttribute(`title`);let r=i(),o=!!t.shortLabel;if(n.className=tr(`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button`,ds,fs,o&&`persona-composer-action-button--text persona-gap-1 persona-text-sm`),n.style.width=r&&!o?r:``,n.style.height=r??``,n.style.minWidth=r&&!o?r:``,n.style.minHeight=r??``,n.style.fontSize=o?``:`18px`,n.style.lineHeight=`1`,n.style.color=t.iconColor??``,n.style.backgroundColor=t.backgroundColor??``,n.replaceChildren(),t.iconName){let e=K(t.iconName,24,`currentColor`,1.5);e&&n.appendChild(e)}if(o){let e=q(`span`,`persona-composer-action-button__label`);e.textContent=t.shortLabel,n.appendChild(e)}else n.firstChild||(n.textContent=t.label);e.tooltip?.destroy(),e.tooltip=Ea({anchor:n,trigger:e.element,text:()=>t.tooltipText??t.label,enabled:!!t.tooltipText})},s=(t,n)=>{let r=t.action,i=J(`button`,{attrs:{type:`button`}}),a=i;if(n===`bar`){let e=q(`div`,`persona-send-button-wrapper`);e.appendChild(i),a=e}a.setAttribute(Bd,t.id);let s={resolved:t,element:a,button:i,owned:!0,managed:!0,busy:!1,visible:!0,mode:n},c=t=>{if(t.preventDefault(),t.stopPropagation(),s.busy||i.disabled)return;let n=s.resolved.action;s.mode===`menu`&&p?.close(!0);let r;try{r=n.onSelect(e.actionContext,t)}catch(t){e.reportError(t,{actionId:s.resolved.id});return}r&&typeof r.then==`function`&&(s.busy=!0,i.setAttribute(`aria-busy`,`true`),r.catch(t=>{e.reportError(t,{actionId:s.resolved.id})}).finally(()=>{s.busy=!1,i.removeAttribute(`aria-busy`)}))};return i.addEventListener(`click`,c),s.detach=()=>i.removeEventListener(`click`,c),o(s,r),s},c=t=>{let n=t.action,r;try{r=n.render({...e.actionContext,id:t.id,action:n})}catch(n){return e.reportError(n,{actionId:t.id}),null}return r?.element?(r.element.setAttribute(Bd,t.id),r.element.toggleAttribute(Vd,n.disableWhenStreaming===!0),{resolved:t,element:r.element,owned:!0,managed:!0,destroy:r.destroy,busy:!1,visible:!0,mode:`bar`}):null},l=(e,t)=>{if(e.builtIn){let t=e.builtIn.element;return t?{resolved:e,element:t,owned:!1,managed:e.builtIn.managed===!0,busy:!1,visible:!0,mode:`bar`}:null}let n=e.action;return n?Qd(n)?c(e):s(e,t):null},u=t=>{if(t.detach?.(),t.tooltip?.destroy(),t.detachMenuSlot?.(),t.detachMenuSlot=void 0,t.menuLabel?.remove(),t.menuLabel=void 0,t.menuSlot?.remove(),t.menuSlot=void 0,t.owned){try{t.destroy?.()}catch(n){e.reportError(n,{actionId:t.resolved.id})}t.element.remove()}},d=(e,t)=>{for(let n=0;n<t.length;n++){let r=t[n];if(!r.managed)continue;let i=null;for(let r=n+1;r<t.length;r++){let n=t[r];if(!n.managed&&n.element.parentElement===e){i=n.element;break}}i?(r.element.parentElement!==e||r.element.nextSibling!==i)&&e.insertBefore(r.element,i):e.lastChild!==r.element&&e.appendChild(r.element)}},f=(e,t)=>{if(e.button){e.button.disabled=t;return}if(!e.owned)return;let n=e.element;n.toggleAttribute(`data-disabled`,t),n.setAttribute(`aria-disabled`,t?`true`:`false`);let r=n instanceof HTMLButtonElement||n instanceof HTMLSelectElement||n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?n:n.querySelector(`button, select, input, textarea`);r&&(r.disabled=t)},p=null,m=null,h=null,g=0,_=()=>{let t=e.getOverflow?.();return t?.enabled===!0?t:void 0},v=()=>(p?p.setLabel(e.getOverflowLabel?.()??`More actions`):p=Rd({label:e.getOverflowLabel?.()??`More actions`,getButtonSize:i}),p),y=e=>{m!==e&&(h?.disconnect(),m=e,g=Wd(e),typeof ResizeObserver<`u`&&(h=new ResizeObserver(t=>{let n=t[t.length-1]?.contentRect?.width??Wd(e);n!==g&&(g=n,T())}),h.observe(e)))},b=(e,t)=>{let n=Ud(e.collapseAutoActionsBelow,t);if(n===null)return!1;let r=g||Wd(t);return r>0&&r<n},x=(e,t,n)=>{if(!t)return`bar`;if(e.resolved.builtIn){let n=Hd(e.resolved.id);return n&&t.includeBuiltIns?.includes(n)?`menu`:`bar`}let r=e.resolved.presentation;return r===`overflow`||r===`auto`&&n?`menu`:`bar`},S=e=>{let t=e.menuSlot;if(!t)return;if(!nf(e.element)){e.menuLabel?.remove(),e.menuLabel=void 0;return}let n=ef(e.element);n?(e.menuLabel||=q(`span`,`persona-composer-overflow-menu__label`),e.menuLabel.textContent!==n&&(e.menuLabel.textContent=n),e.menuLabel.parentElement!==t&&t.appendChild(e.menuLabel)):(e.menuLabel?.remove(),e.menuLabel=void 0)},C=(e,n)=>{if(e.mode===n)return e;let r=e.resolved.action;if(r&&!Qd(r)){u(e),t.delete(e.resolved.id);let r=s(e.resolved,n);return t.set(e.resolved.id,r),r}if(n===`menu`){let t=J(`div`,{className:`persona-composer-overflow-menu__slot`,attrs:{role:`none`,[La]:``}});t.appendChild(e.element),$($d(e.element)),e.menuSlot=t;let n=t=>{let n=$d(e.element);if(n.disabled)return;let r=t.target===n||n.contains(t.target);p?.close(!0),r||n.click()};t.addEventListener(`click`,n,!0),e.detachMenuSlot=()=>t.removeEventListener(`click`,n,!0),e.managed=!0,S(e)}else e.detachMenuSlot?.(),e.detachMenuSlot=void 0,e.menuLabel?.remove(),e.menuLabel=void 0,e.menuSlot?.remove(),e.menuSlot=void 0;return e.mode=n,e},w=(e,t)=>{let n=t.map(e=>e.menuSlot??e.element);for(n.forEach((t,n)=>{let r=e.children[n];r!==t&&(r?e.insertBefore(t,r):e.appendChild(t))});e.children.length>n.length;)e.lastElementChild?.remove()},T=()=>{if(r)return;let i=e.getBindings();if(!i)return;let a=e.getState(),o=a.phase===`streaming`,s=_();s&&y(i.footer);let c=s?b(s,i.footer):!1,l={start:[],end:[]},u=[];for(let e of n){let n=t.get(e.id);if(!n)continue;let r=e.action,i=!r||Yd(r.visible,a,!0)&&Zd(r.visibility,a);if(n.visible!==i&&(n.visible=i,!i&&n.managed&&(n.menuSlot??n.element).remove()),i){if(n=C(n,x(n,s,c)),r){let e=Yd(r.disabled,a,!1)||r.disableWhenStreaming===!0&&o;f(n,e),!Qd(r)&&r.pressed!==void 0&&n.button?.setAttribute(`aria-pressed`,r.pressed?`true`:`false`)}n.mode===`menu`?(S(n),u.push(n)):l[e.placement].push(n)}}if(u.length>0){let e=v();w(e.panel,u),e.setItems(u.map(e=>e.menuSlot??e.element)),e.applyButtonSize();let t=Number.isFinite(s?.order)?s?.order:zd.overflow,n=l.start.findIndex(e=>e.resolved.order>t),r={resolved:{id:`core:overflow`,placement:`start`,presentation:`bar`,order:t,sequence:-1,source:`core`},element:e.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:`bar`};l.start.splice(n<0?l.start.length:n,0,r)}else p&&(p.close(),p.trigger.remove(),p.setItems([]));d(i.actionsStart,l.start),d(i.actionsEnd,l.end)};return{resolve:()=>{if(r)return;let i=qd(e.collect()),a=new Set(i.map(e=>e.id));for(let[e,n]of t)a.has(e)||(u(n),t.delete(e));for(let e of i){let n=t.get(e.id);if(!n){let n=l(e,`bar`);n&&t.set(e.id,n);continue}let r=n.resolved.action,i=e.action;if(!!r!=!!i||r&&i&&Qd(r)!==Qd(i)||r&&i&&Qd(r)&&Qd(i)&&r.render!==i.render){u(n),t.delete(e.id);let r=l(e,n.mode);r&&t.set(e.id,r)}else n.resolved=e,e.builtIn?(n.managed=e.builtIn.managed===!0||n.mode===`menu`,e.builtIn.element&&n.mode===`bar`&&(n.element=e.builtIn.element)):i&&!Qd(i)?o(n,i):i&&n.element.toggleAttribute(Vd,i.disableWhenStreaming===!0)}n=i,T()},sync:T,getResolved:()=>n,getOverflowMenu:()=>p,destroy:()=>{if(!r){r=!0,h?.disconnect(),h=null,m=null;for(let e of t.values())u(e);t.clear(),p?.destroy(),p=null,n=[]}}}}Y(),mn(),xs();const af=[`--persona-components-composer-modelPicker-menuBackground`,`--persona-components-composer-modelPicker-menuBorderRadius`,`--persona-components-composer-modelPicker-rowHoverBackground`,`--persona-components-composer-modelPicker-labelColor`,`--persona-components-composer-modelPicker-descriptionColor`],of=()=>({wrapper:J(`span`,{className:`persona-composer-model-picker-wrapper`,attrs:{"data-persona-composer-model-picker-wrapper":``}}),chevron:J(`span`,{className:`persona-composer-model-picker-chevron`,attrs:{"aria-hidden":`true`}})});function sf(e){let t=e.label??`Model`,n=e.presentation??`native`,r=null,i=t=>{let n=e.getSelectedModelId();return t.find(e=>e.id===n)??t[0]},a=()=>{let n=J(`select`,{className:`persona-composer-model-picker`,attrs:{"aria-label":t,"data-persona-composer-model-picker":``}}),a=``,o=()=>{let t=e.getModels(),r=t.map(e=>`${e.id}:${e.label}`).join(`|`);r!==a&&(a=r,n.replaceChildren(...t.map(e=>{let t=J(`option`,{attrs:{value:e.id}});return t.textContent=e.label,t}))),n.value=i(t)?.id??``};o(),r=o;let s=()=>{n.value&&e.onSelect(n.value)};n.addEventListener(`change`,s);let c=e=>e.stopPropagation();n.addEventListener(`click`,c);let{wrapper:l,chevron:u}=of();return l.append(n,u),{element:l,destroy:()=>{r===o&&(r=null),n.removeEventListener(`change`,s),n.removeEventListener(`click`,c)}}},o=()=>{let n=J(`button`,{className:`persona-composer-model-picker persona-composer-model-picker-trigger`,attrs:{type:`button`,"aria-haspopup":`listbox`,"aria-expanded":`false`,"data-persona-composer-model-picker":`popover`}}),a=q(`span`,`persona-composer-model-picker-label`),o=q(`span`,`persona-composer-model-picker-suffix`);n.append(a,o);let s=J(`div`,{className:`persona-composer-model-menu`,attrs:{role:`listbox`,tabindex:`-1`,"aria-label":t,"data-persona-composer-model-menu":``}}),c=/* @__PURE__ */ new Map,l=``,u=null,d=()=>u?.isOpen===!0,f=(e=!1)=>{d()&&(u?.close(),n.setAttribute(`aria-expanded`,`false`),e&&n.focus())},p=e=>{let t=[...c.values()];t.length!==0&&t[(e%t.length+t.length)%t.length].focus()},m=t=>{if(d())return;u||=Md({anchor:n,content:s,placement:`top-start`,offset:6,onDismiss:()=>n.setAttribute(`aria-expanded`,`false`)}),ps(n,s,af),u.open(),n.setAttribute(`aria-expanded`,`true`);let r=[...c.keys()].indexOf(i(e.getModels())?.id??``);p(t??(r>=0?r:0))},h=t=>{f(!0),e.onSelect(t)},g=e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getAttribute(`data-persona-model-option`);t&&h(t)},_=e=>{let t=J(`button`,{className:`persona-composer-model-option`,attrs:{type:`button`,role:`option`,tabindex:`-1`,"aria-selected":`false`,"data-persona-model-option":e.id}});if(e.icon){let n=K(e.icon,16,`currentColor`,1.5);if(n){let e=q(`span`,`persona-composer-model-option-icon`);e.appendChild(n),t.appendChild(e)}}let n=q(`span`,`persona-composer-model-option-body`),r=q(`span`,`persona-composer-model-option-label`);if(r.textContent=e.label,n.appendChild(r),e.description){let t=q(`span`,`persona-composer-model-option-description`);t.textContent=e.description,n.appendChild(t)}t.appendChild(n);let i=q(`span`,`persona-composer-model-option-check`);i.setAttribute(`aria-hidden`,`true`);let a=K(`check`,16,`currentColor`,2);return a&&i.appendChild(a),t.appendChild(i),t.addEventListener(`click`,g),t},v=()=>{let r=e.getModels(),u=r.map(e=>`${e.id}:${e.label}:${e.icon??``}:${e.description??``}`).join(`|`);if(u!==l){l=u;for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),s.replaceChildren(...r.map(e=>{let t=_(e);return c.set(e.id,t),t}))}let d=i(r);for(let[e,t]of c)t.setAttribute(`aria-selected`,String(e===d?.id));a.textContent=d?.label??``;let f=e.getSuffix?.()??``;o.textContent=f,n.setAttribute(`aria-label`,[t,[d?.label,f].filter(Boolean).join(` `)].filter(Boolean).join(`: `))};v(),r=v;let y=e=>{e.preventDefault(),e.stopPropagation(),d()?f(!0):m()},b=e=>{e.key===`ArrowDown`?(e.preventDefault(),d()?p(0):m(0)):e.key===`ArrowUp`&&(e.preventDefault(),d()?p(-1):m(-1))},x=e=>{let t=[...c.values()],n=t.indexOf(e.target?.closest?.(`.persona-composer-model-option`));switch(e.key){case`ArrowDown`:e.preventDefault(),p(n+1);return;case`ArrowUp`:e.preventDefault(),p(n-1);return;case`Home`:e.preventDefault(),p(0);return;case`End`:e.preventDefault(),p(t.length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),f(!0);return;case`Tab`:f(!0);return}};n.addEventListener(`click`,y),n.addEventListener(`keydown`,b),s.addEventListener(`keydown`,x);let{wrapper:S,chevron:C}=of();return S.append(n,C),{element:S,destroy:()=>{r===v&&(r=null),n.removeEventListener(`click`,y),n.removeEventListener(`keydown`,b),s.removeEventListener(`keydown`,x);for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),u?.destroy(),u=null,s.remove()}}};return{action:{id:`core:model`,kind:`custom`,placement:`end`,order:700,presentation:n===`popover`?`bar`:`auto`,label:t,render:()=>n===`popover`?o():a()},repaint:()=>r?.()}}Y();const cf=`[data-persona-composer-chip-row]`;function lf(e){e.style.display=e.childElementCount>0?`flex`:`none`}function uf(e){let t=e.querySelector(cf);if(t)return t;let n=J(`div`,{className:`persona-composer-chip-row`,attrs:{"data-persona-composer-chip-row":``}});n.style.display=`none`;let r=e.querySelector(`[data-persona-composer-quote], [data-persona-composer-pending]`);return r?.parentElement===e?e.insertBefore(n,r):e.appendChild(n),n}Y(),mn();function df(e){let t=e.row,n=``,r=!1,i=new Set(e.initialIds??[]),a=t=>{let n=J(`span`,{className:`persona-mention-chip persona-composer-mode-chip`,attrs:{"data-persona-composer-mode":t.id}});if(t.iconName){let e=q(`span`,`persona-mention-chip-icon`),r=K(t.iconName,12,`currentColor`,1.5);r&&e.appendChild(r),n.appendChild(e)}let r=q(`span`,`persona-mention-chip-label`);r.textContent=t.shortLabel??t.label,n.appendChild(r);let i=J(`button`,{className:`persona-mention-chip-remove`,attrs:{type:`button`,"aria-label":`Remove ${t.label}`}}),a=K(`x`,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=`×`,i.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation(),e.onRemove(t.id)}),n.appendChild(i),n},o=()=>Array.from(t.querySelectorAll(`:scope > [data-persona-composer-mode]`)),s=e=>{e.setAttribute(`data-persona-chip-exit`,``),e.setAttribute(`aria-hidden`,`true`),e.style.pointerEvents=`none`;let n=()=>{e.remove(),lf(t)},r=t.ownerDocument.defaultView,i=typeof r?.getComputedStyle==`function`?r.getComputedStyle(e).animationName:``;!i||i===`none`?n():(e.addEventListener(`animationend`,n,{once:!0}),e.addEventListener(`animationcancel`,n,{once:!0}))},c=()=>{for(let e of o())e.remove()};return{element:t,render:(e,c)=>{if(r)return;let l=c.filter(t=>e.includes(t.id)),u=l.map(e=>`${e.id}:${e.shortLabel??e.label}`).join(`|`);if(u===n)return;n=u;let d=/* @__PURE__ */ new Map;for(let e of o()){let t=e.getAttribute(`data-persona-composer-mode`);t&&l.some(e=>e.id===t)&&!e.hasAttribute(`data-persona-chip-exit`)?d.set(t,e):e.hasAttribute(`data-persona-chip-exit`)||s(e)}let f=t.firstChild;for(let e of l){let n=d.get(e.id);n||(n=a(e),i.has(e.id)||(n.setAttribute(`data-persona-chip-enter`,``),n.addEventListener(`animationend`,()=>n?.removeAttribute(`data-persona-chip-enter`),{once:!0}))),i.delete(e.id),n!==f&&t.insertBefore(n,f),f=n.nextSibling}lf(t)},destroy:()=>{r=!0,c(),lf(t)}}}const ff=e=>`core:mode:${e}`,pf=e=>Math.min(300+e,499),mf=e=>`core:mode-group:${e}`;function hf(e,t){return e?t?.find(t=>t.id===e)?.presentation===`segmented`:!1}function gf(e,t){return e?t?.find(t=>t.id===e)?.chipVisibility===`hidden`:!1}function _f(e,t){return e?.length?e.filter(e=>!hf(e.groupId,t)&&!gf(e.groupId,t)):[]}const vf=(e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null;function yf(e,t,n,r){let i=n.find(e=>e.id===t);if(!i)return[...e];let a=e.includes(t),o=new Set(e);if(a)o.delete(t);else{if(vf(i,r)===`single`){let e=n.filter(e=>e.groupId===i.groupId).map(e=>e.id);o=new Set([...o].filter(t=>!e.includes(t)))}o.add(t)}return n.filter(e=>o.has(e.id)).map(e=>e.id)}function bf(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function xf(e,t){return t?.length?t.filter(t=>e.includes(t.id)&&(t.persistence??`sticky`)!==`once`).map(e=>e.id):[]}function Sf(e,t){if(t?.length&&e.length!==0)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}Y(),mn();function Cf(e){let t=null;return{action:{id:mf(e.groupId),kind:`custom`,placement:`start`,presentation:`bar`,label:e.getGroup()?.label??e.groupId,render:()=>{let n=J(`div`,{className:`persona-composer-segmented`,attrs:{"data-persona-composer-mode-group":e.groupId}}),r=/* @__PURE__ */ new Map,i=``,a=t=>{t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getAttribute(`data-persona-composer-mode`);n&&(e.getActiveIds().includes(n)&&e.getGroup()?.selection===`single`||e.onSelect(n))},o=e=>{let t=J(`button`,{className:`persona-composer-segmented-item`,attrs:{type:`button`,"data-persona-composer-mode":e.id,"aria-label":e.label}});if(e.iconName){let n=K(e.iconName,16,`currentColor`,1.5);n&&t.appendChild(n)}let n=q(`span`,`persona-composer-segmented-label`);return n.textContent=e.shortLabel??e.label,t.appendChild(n),t.addEventListener(`click`,a),t},s=()=>{let t=e.getGroup();t?.label?(n.setAttribute(`role`,`group`),n.setAttribute(`aria-label`,t.label)):(n.removeAttribute(`role`),n.removeAttribute(`aria-label`));let s=e.getModes(),c=s.map(e=>`${e.id}:${e.shortLabel??e.label}:${e.iconName??``}`).join(`|`);if(c!==i){i=c;for(let e of r.values())e.removeEventListener(`click`,a);r.clear();let e=s.map(e=>{let t=o(e);return r.set(e.id,t),t});n.replaceChildren(...e)}let l=e.getActiveIds();for(let[e,t]of r)t.setAttribute(`aria-pressed`,String(l.includes(e)))};return s(),t=s,{element:n,destroy:()=>{t===s&&(t=null);for(let e of r.values())e.removeEventListener(`click`,a);r.clear()}}}},repaint:()=>t?.()}}Y(),mn();function wf(e){let t=J(`div`,{className:`persona-composer-quote`,attrs:{"data-persona-composer-quote":``}});t.style.display=`none`;let n=``,r=!1,i=n=>{let r=q(`span`,`persona-composer-quote-bar`),i=q(`div`,`persona-composer-quote-content`);if(n.sourceLabel){let e=q(`div`,`persona-composer-quote-source`);e.textContent=n.sourceLabel,i.appendChild(e)}let a=J(`div`,{className:`persona-composer-quote-text`,attrs:{"data-persona-composer-quote-text":``}});a.textContent=Iu(n.text),i.appendChild(a);let o=J(`button`,{className:`persona-composer-quote-dismiss`,attrs:{type:`button`,"aria-label":e.dismissLabel??`Remove quote`,"data-persona-composer-quote-dismiss":``}}),s=K(`x`,12,`currentColor`,2);s?o.appendChild(s):o.textContent=`×`,o.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(r,i,o)};return{element:t,render:e=>{if(r)return;let a=e?`${e.sourceLabel??``}${e.text}`:``;a!==n&&(n=a,e?(i(e),t.style.display=`flex`):(t.replaceChildren(),t.style.display=`none`))},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}Y(),mn();function Tf(e){let t=J(`div`,{className:`persona-composer-pending`,attrs:{"data-persona-composer-pending":``}});t.style.display=`none`;let n,r=!1,i=(e,t,n,r)=>{let i=J(`button`,{className:`persona-composer-pending-action`,attrs:{type:`button`,"aria-label":t,[n]:``}}),a=K(e,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=t,i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},a=e=>{let t=Iu(e.text??``,90);if(t)return t;let n=e.contentParts?.length??0;return n>0?n===1?`1 attachment`:`${n} attachments`:(e.mentionRefs?.length??0)>0?e.mentionRefs.map(e=>e.label).join(`, `):`Queued message`};return{element:t,render:o=>{if(r||o===n)return;if(n=o,!o){t.replaceChildren(),t.style.display=`none`;return}let s=q(`span`,`persona-composer-pending-badge`);s.textContent=e.label??`Sends next`;let c=J(`div`,{className:`persona-composer-pending-text`,attrs:{"data-persona-composer-pending-text":``}});c.textContent=a(o),t.replaceChildren(s,c,i(`pencil`,e.editLabel??`Edit queued message`,`data-persona-composer-pending-edit`,e.onEdit),i(`x`,e.removeLabel??`Remove queued message`,`data-persona-composer-pending-remove`,e.onRemove)),t.style.display=`flex`},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}Y();function Ef(e){let t=J(`div`,{className:`persona-message-edit`,attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":``}}),n=J(`textarea`,{className:`persona-message-edit-input`,attrs:{rows:`1`,dir:`auto`,"aria-label":`Edit message`,"data-persona-message-edit-input":``}});n.value=e.initialText;let r=()=>{n.style.height=`auto`,n.style.height=`${n.scrollHeight}px`};n.addEventListener(`input`,r);let i=q(`div`,`persona-message-edit-actions`),a=(e,t,n,r)=>{let i=J(`button`,{className:`persona-message-edit-button ${t}`,attrs:{type:`button`,[n]:``},text:e});return i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},o=()=>{let t=n.value.trim();t&&e.onSave(t)};return i.append(a(e.cancelLabel??`Cancel`,`persona-message-edit-cancel`,`data-persona-message-edit-cancel`,e.onCancel),a(e.saveLabel??`Send`,`persona-message-edit-save`,`data-persona-message-edit-save`,o)),n.addEventListener(`keydown`,t=>{t.key===`Escape`?(t.preventDefault(),t.stopPropagation(),e.onCancel()):t.key===`Enter`&&!t.shiftKey&&(t.preventDefault(),o())}),t.append(n,i),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let e=n.value.length;n.setSelectionRange(e,e),r()},destroy:()=>{t.replaceChildren(),t.remove()}}}function Df(e){let t=e.text??``;if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}function Of(e,t){if(!e||typeof e.text!=`string`)return;let n=new Set(t.mentionSourceIds),r=(e.mentionRefs??[]).filter(e=>n.has(e.sourceId)),i=r.length===(e.mentionRefs?.length??0)&&r.length>0,a=new Set(t.modes.map(e=>e.id)),o=(e.activeModeIds??[]).filter(e=>a.has(e)),s=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...i?{mentionRefs:r}:{},...i&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...s?{selectedModelId:s}:{},...o.length?{activeModeIds:o}:{},...e.quote?.text?{quote:e.quote}:{}}}function kf(e){let t=e.delay??500,n=null,r=!1,i=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{r||(i(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{r||n===null||(i(),e.write())},cancel:i,destroy:()=>{r=!0,i()}}}function Af(e){return e.wrapped||e.text.includes(`
|
|
23
|
+
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function jf(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function Mf(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),r=Number.parseFloat(n.lineHeight),i=Number.parseFloat(n.fontSize),a=Number.isFinite(r)&&r>0?r:Number.isFinite(i)&&i>0?i*1.4:0;if(!a)return!1;let o=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-o>a*1.5}function Nf(e){e&&(typeof e.requestSubmit==`function`?e.requestSubmit():e.dispatchEvent(new Event(`submit`,{bubbles:!0,cancelable:!0})))}function Pf(e){return Object.freeze({text:e.text,contentParts:e.contentParts?Object.freeze([...e.contentParts]):void 0,mentionRefs:Object.freeze([...e.mentionRefs]),contentSegments:e.contentSegments?Object.freeze([...e.contentSegments]):void 0,options:Object.freeze({...e.options}),viaVoice:e.viaVoice})}function Ff(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}const If=e=>typeof e?.then==`function`;function Lf(e,t){return t===!1?{status:`canceled`}:(!t||typeof t!=`object`||(typeof t.text==`string`&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options})),{status:`proceed`})}function Rf(e,t,n){let r;try{r=e(Pf(t),{signal:n})}catch(e){return{status:`error`,error:e}}return If(r)?Promise.resolve(r).then(e=>n.aborted?{status:`aborted`}:Lf(t,e),e=>n.aborted?{status:`aborted`}:{status:`error`,error:e}):Lf(t,r)}const zf=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?`circle`:`pill`),Bf={background:`semantic.colors.primary`,foreground:`semantic.colors.textInverse`,border:`transparent`,size:`48px`,iconSize:`24px`,borderRadius:`palette.radius.full`,shadow:`0 8px 24px rgba(0,0,0,.16)`,offset:`20px`};No();const Vf=`16px`,Hf=`transparent`,Uf={colors:{primary:{50:`#ffffff`,100:`#f5f5f5`,200:`#d4d4d4`,300:`#a3a3a3`,400:`#737373`,500:`#171717`,600:`#0f0f0f`,700:`#0a0a0a`,800:`#050505`,900:`#030303`,950:`#000000`},secondary:{50:`#f5f3ff`,100:`#ede9fe`,200:`#ddd6fe`,300:`#c4b5fd`,400:`#a78bfa`,500:`#8b5cf6`,600:`#7c3aed`,700:`#6d28d9`,800:`#5b21b6`,900:`#4c1d95`,950:`#2e1065`},accent:{50:`#ecfeff`,100:`#cffafe`,200:`#a5f3fc`,300:`#67e8f9`,400:`#22d3ee`,500:`#06b6d4`,600:`#0891b2`,700:`#0e7490`,800:`#155e75`,900:`#164e63`,950:`#083344`},gray:{50:`#f9fafb`,100:`#f3f4f6`,200:`#e5e7eb`,300:`#d1d5db`,400:`#9ca3af`,500:`#6b7280`,600:`#4b5563`,700:`#374151`,800:`#1f2937`,900:`#111827`,950:`#030712`},success:{50:`#f0fdf4`,100:`#dcfce7`,200:`#bbf7d0`,300:`#86efac`,400:`#4ade80`,500:`#22c55e`,600:`#16a34a`,700:`#15803d`,800:`#166534`,900:`#14532d`},warning:{50:`#fefce8`,100:`#fef9c3`,200:`#fef08a`,300:`#fde047`,400:`#facc15`,500:`#eab308`,600:`#ca8a04`,700:`#a16207`,800:`#854d0e`,900:`#713f12`},error:{50:`#fef2f2`,100:`#fee2e2`,200:`#fecaca`,300:`#fca5a5`,400:`#f87171`,500:`#ef4444`,600:`#dc2626`,700:`#b91c1c`,800:`#991b1b`,900:`#7f1d1d`},info:{50:`#eff6ff`,100:`#dbeafe`,200:`#bfdbfe`,300:`#93c5fd`,400:`#60a5fa`,500:`#3b82f6`,600:`#2563eb`,700:`#1d4ed8`,800:`#1e40af`,900:`#1e3a8a`,950:`#172554`},purple:{50:`#faf5ff`,100:`#f3e8ff`,200:`#e9d5ff`,300:`#d8b4fe`,400:`#c084fc`,500:`#a855f7`,600:`#9333ea`,700:`#7e22ce`,800:`#6b21a8`,900:`#581c87`,950:`#3b0764`},teal:{50:`#f0fdfa`,100:`#ccfbf1`,200:`#99f6e4`,300:`#5eead4`,400:`#2dd4bf`,500:`#14b8a6`,600:`#0d9488`,700:`#0f766e`,800:`#115e59`,900:`#134e4a`,950:`#042f2e`}},spacing:(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?`0px`:`${t/4}rem`;return e})(),typography:{fontFamily:{sans:`system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`,serif:`Georgia, Cambria, "Times New Roman", Times, serif`,mono:`ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace`},fontSize:{xs:`0.75rem`,sm:`0.875rem`,base:`1rem`,lg:`1.125rem`,xl:`1.25rem`,"2xl":`1.5rem`,"3xl":`1.875rem`,"4xl":`2.25rem`},fontWeight:{normal:`400`,medium:`500`,semibold:`600`,bold:`700`},lineHeight:{tight:`1.25`,normal:`1.5`,relaxed:`1.625`}},shadows:{none:`none`,sm:`0 1px 2px 0 rgb(0 0 0 / 0.05)`,md:`0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)`,lg:`0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)`,xl:`0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)`,"2xl":`0 25px 50px -12px rgb(0 0 0 / 0.25)`},borders:{none:`none`,sm:`1px solid`,md:`2px solid`,lg:`4px solid`},radius:{none:`0px`,sm:`0.125rem`,md:`0.375rem`,lg:`0.5rem`,xl:`0.75rem`,"2xl":`1rem`,full:`9999px`}},Wf={colors:{primary:`palette.colors.primary.500`,secondary:`palette.colors.secondary.500`,accent:`palette.colors.primary.600`,surface:`palette.colors.gray.50`,background:`palette.colors.gray.50`,container:`palette.colors.gray.50`,text:`palette.colors.gray.900`,textMuted:`palette.colors.gray.500`,textInverse:`palette.colors.gray.50`,border:`palette.colors.gray.200`,divider:`palette.colors.gray.200`,interactive:{default:`palette.colors.primary.600`,hover:`palette.colors.primary.700`,focus:`palette.colors.primary.600`,active:`palette.colors.primary.600`,disabled:`palette.colors.gray.300`},feedback:{success:`palette.colors.success.500`,warning:`palette.colors.warning.500`,error:`palette.colors.error.500`,info:`palette.colors.info.500`}},spacing:{xs:`palette.spacing.1`,sm:`palette.spacing.2`,md:`palette.spacing.4`,lg:`palette.spacing.6`,xl:`palette.spacing.8`,"2xl":`palette.spacing.10`},typography:{fontFamily:`palette.typography.fontFamily.sans`,fontSize:`palette.typography.fontSize.base`,fontWeight:`palette.typography.fontWeight.normal`,lineHeight:`palette.typography.lineHeight.normal`}},Gf={button:{primary:{background:`palette.colors.primary.500`,foreground:`palette.colors.primary.50`,borderRadius:`palette.radius.lg`,padding:`semantic.spacing.md`},secondary:{background:`semantic.colors.surface`,foreground:`semantic.colors.secondary`,borderRadius:`palette.radius.lg`,padding:`semantic.spacing.md`},ghost:{background:`transparent`,foreground:`semantic.colors.text`,borderRadius:`palette.radius.md`,padding:`semantic.spacing.sm`,hoverBackground:`rgba(0, 0, 0, 0.05)`}},input:{background:`semantic.colors.surface`,placeholder:`semantic.colors.textMuted`,borderRadius:`palette.radius.lg`,padding:`semantic.spacing.md`,focus:{border:`palette.colors.gray.400`,ring:`palette.colors.gray.400`}},launcher:{background:`semantic.colors.surface`,foreground:`semantic.colors.primary`,border:`semantic.colors.border`,size:`60px`,iconSize:`28px`,borderRadius:`palette.radius.full`,shadow:`palette.shadows.lg`},panel:{width:xo,maxWidth:`none`,height:`min(640px, max(200px, calc(100vh - 64px)))`,maxHeight:`none`,borderRadius:`palette.radius.xl`,shadow:`palette.shadows.xl`,inset:Vf,canvasBackground:Hf,modes:{floating:{border:`1px solid var(--persona-border)`,shadow:`palette.shadows.xl`,borderRadius:`palette.radius.xl`},inline:{border:`1px solid var(--persona-border)`,shadow:`none`,borderRadius:`palette.radius.xl`},docked:{border:`none`,shadow:`none`,borderRadius:`palette.radius.xl`},sidebar:{border:`none`,borderRadius:`0`},mobile:{border:`none`,shadow:`none`,borderRadius:`0`}}},header:{background:`palette.colors.primary.500`,foreground:`palette.colors.primary.50`,borderRadius:`palette.radius.xl palette.radius.xl 0 0`,padding:`20px 24px`,minimalPadding:`16px 24px`,iconBackground:`palette.colors.primary.600`,iconForeground:`palette.colors.primary.50`},message:{gap:`12px`,user:{background:`palette.colors.primary.500`,text:`palette.colors.primary.50`,borderRadius:`palette.radius.lg`,shadow:`palette.shadows.sm`},assistant:{background:`semantic.colors.container`,text:`semantic.colors.text`,borderRadius:`palette.radius.lg`,border:`semantic.colors.border`,shadow:`palette.shadows.sm`},border:`semantic.colors.border`},introCard:{background:`transparent`,borderRadius:`palette.radius.2xl`,padding:`semantic.spacing.lg`,shadow:`palette.shadows.none`},suggestion:{chip:{background:`semantic.colors.surface`,foreground:`semantic.colors.text`,border:`semantic.colors.border`,borderRadius:`palette.radius.full`,padding:`0.5rem 0.875rem`,gap:`0.5rem`,itemGap:`8px`,minHeight:`36px`,fontSize:`0.8125rem`,lineHeight:`1.25`,iconSize:`16px`,hoverBackground:`palette.colors.gray.100`,hoverBorder:`palette.colors.gray.300`,pressedBackground:`palette.colors.gray.200`,focusRing:`semantic.colors.interactive.focus`,disabledOpacity:`0.5`},card:{background:`semantic.colors.surface`,foreground:`semantic.colors.text`,border:`semantic.colors.border`,borderRadius:`palette.radius.xl`,padding:`1rem`,shadow:`palette.shadows.sm`,gap:`0.625rem`,itemGap:`8px`,minHeight:`72px`,fontSize:`0.875rem`,lineHeight:`1.35`,iconSize:`18px`,hoverBackground:`palette.colors.gray.100`,hoverBorder:`palette.colors.gray.300`,pressedBackground:`palette.colors.gray.200`,focusRing:`semantic.colors.interactive.focus`,disabledOpacity:`0.5`},list:{background:`transparent`,foreground:`semantic.colors.text`,border:`semantic.colors.border`,borderRadius:`palette.radius.md`,padding:`0.75rem`,gap:`0.625rem`,itemGap:`8px`,minHeight:`44px`,fontSize:`0.875rem`,lineHeight:`1.35`,iconSize:`17px`,hoverBackground:`palette.colors.gray.100`,hoverBorder:`palette.colors.gray.300`,pressedBackground:`palette.colors.gray.200`,focusRing:`semantic.colors.interactive.focus`,disabledOpacity:`0.5`}},toolBubble:{shadow:`palette.shadows.sm`},reasoningBubble:{shadow:`palette.shadows.sm`},composer:{shadow:`palette.shadows.none`},scrollbar:{thumb:`semantic.colors.border`,track:`transparent`},markdown:{inlineCode:{background:`palette.colors.gray.50`,foreground:`palette.colors.gray.900`},link:{foreground:`palette.colors.primary.600`},prose:{fontFamily:`inherit`},codeBlock:{background:`semantic.colors.container`,borderColor:`semantic.colors.border`,textColor:`inherit`,borderRadius:`palette.radius.md`},table:{headerBackground:`semantic.colors.container`,borderColor:`semantic.colors.border`},hr:{color:`semantic.colors.divider`},blockquote:{borderColor:`palette.colors.gray.900`,background:`transparent`,textColor:`palette.colors.gray.500`}},collapsibleWidget:{container:`palette.colors.gray.50`,surface:`semantic.colors.surface`,border:`semantic.colors.border`},voice:{recording:{indicator:`palette.colors.error.500`,background:`palette.colors.error.50`,border:`palette.colors.error.200`},processing:{icon:`palette.colors.primary.500`,background:`palette.colors.primary.50`},speaking:{icon:`palette.colors.success.500`}},approval:{requested:{background:`semantic.colors.surface`,border:`semantic.colors.border`,text:`palette.colors.gray.900`,shadow:`0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)`},approve:{background:`semantic.colors.primary`,foreground:`semantic.colors.textInverse`,borderRadius:`palette.radius.md`,padding:`semantic.spacing.sm`},deny:{background:`semantic.colors.container`,foreground:`semantic.colors.text`,borderRadius:`palette.radius.md`,padding:`semantic.spacing.sm`}},attachment:{image:{background:`palette.colors.gray.100`,border:`palette.colors.gray.200`}},eventStream:{badge:{flow:{background:`palette.colors.success.100`,foreground:`palette.colors.success.700`},step:{background:`palette.colors.primary.100`,foreground:`palette.colors.primary.700`},reasoning:{background:`palette.colors.warning.100`,foreground:`palette.colors.warning.700`},tool:{background:`palette.colors.purple.100`,foreground:`palette.colors.purple.800`},agent:{background:`palette.colors.teal.100`,foreground:`palette.colors.teal.800`},error:{background:`palette.colors.error.100`,foreground:`palette.colors.error.700`},default:{background:`palette.colors.gray.100`,foreground:`palette.colors.gray.600`}}},scrollToBottom:{background:`components.button.primary.background`,foreground:`components.button.primary.foreground`,border:`semantic.colors.primary`,size:`40px`,borderRadius:`palette.radius.full`,shadow:`palette.shadows.sm`,padding:`0.5rem 0.875rem`,gap:`0.5rem`,fontSize:`0.875rem`,iconSize:`14px`},artifact:{pane:{background:`semantic.colors.container`,toolbarBackground:`semantic.colors.container`}}},Kf=Uf.colors.gray,qf={50:`#fafafa`,100:`#f5f5f5`,200:`#e5e5e5`,300:`#d4d4d4`,400:`#a3a3a3`,500:`#737373`,600:`#525252`,700:`#404040`,800:`#262626`,900:`#171717`,950:`#0a0a0a`},Jf={...Uf,colors:{...Uf.colors,gray:Kf}},Yf={...Uf,colors:{...Uf.colors,gray:qf},radius:{none:`0px`,sm:`4px`,md:`8px`,lg:`12px`,xl:`16px`,"2xl":`24px`,full:`9999px`}},Xf=Jf,Zf=Wf,Qf={...Wf,colors:{...Wf.colors,surface:`#ffffff`,background:`#ffffff`,container:`semantic.colors.surface`,textInverse:`#ffffff`},typography:{...Wf.typography,fontSize:`14px`,lineHeight:`1.5`}},$f=Zf,ep=Gf,tp={...Gf,launcher:Bf,activity:{rowHeight:`32px`,labelSize:`13px`,iconSize:`16px`,indent:`0px`,groupIndent:`0px`,groupGap:`0px`,groupPadding:`0px`,transcriptGap:`0px`,responseGap:`12px`,bodyPadding:`4px 0`,bodySize:`13px`,bodyLineHeight:`1.5`,bodyFontWeight:`400`,sectionGap:`8px`,bodySurface:`transparent`},toolBubble:{shadow:`none`},reasoningBubble:{shadow:`none`},input:{...Gf.input,borderRadius:`palette.radius.full`},introCard:{...Gf.introCard,title:{fontSize:`22px`,fontWeight:`500`}},suggestion:{chip:{...Gf.suggestion.chip,fontWeight:`400`},card:{...Gf.suggestion.card,fontWeight:`400`},list:{...Gf.suggestion.list,fontWeight:`400`}},panel:{...Gf.panel,width:`min(400px, calc(100vw - 24px))`,height:`min(704px, calc(100dvh - 104px))`,borderRadius:`palette.radius.xl`},header:{...Gf.header,background:`semantic.colors.container`,foreground:`semantic.colors.text`,padding:`8px 8px 8px 16px`,minimalPadding:`8px 8px 8px 16px`,minHeight:`48px`,borderBottom:`none`,iconBackground:`transparent`,iconForeground:`semantic.colors.text`,iconScale:`1`,controlSize:`28px`,controlIconSize:`18px`,controlStrokeWidth:`1.5`,actionIconForeground:`semantic.colors.textMuted`,controlBorderRadius:`8px`,controlHoverBackground:`color-mix(in srgb, var(--persona-text) 8%, transparent)`,controlHoverForeground:`semantic.colors.text`,controlFocusOutline:`2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)`,title:{fontSize:`14px`,fontWeight:`500`,lineHeight:`1.5`}},message:{...Gf.message,gap:`20px`,fullscreenGap:`28px`,topFadeHeight:`18px`,user:{...Gf.message.user,background:`palette.colors.gray.100`,text:`semantic.colors.text`,borderRadius:`palette.radius.xl`,shadow:`none`,padding:`8px 14px`,fontSize:`14px`,lineHeight:`1.5`},assistant:{...Gf.message.assistant,background:`transparent`,border:`transparent`,borderWidth:`0px`,borderRadius:`0px`,shadow:`none`,padding:`0px`,fontSize:`14px`,lineHeight:`1.55`}},composer:{...Gf.composer,padding:`8px`,fontSize:`15px`,lineHeight:`1.5`,controlSize:`32px`,controlIconSize:`20px`,sendIconSize:`18px`,sendButtonRadius:`9999px`,footerBorder:`none`,overlayBand:`linear-gradient(to bottom, transparent, var(--persona-container) 24px)`,focusBorderColor:`color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))`,focusRing:`1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)`}},np=ep,rp=e=>_o({future:e}),ip=e=>rp(e)===`v5`?{palette:Yf,semantic:Qf,components:tp}:{palette:Jf,semantic:Zf,components:ep};function ap(e,t){if(!t.startsWith(`palette.`)&&!t.startsWith(`semantic.`)&&!t.startsWith(`components.`))return t;let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return typeof r==`string`&&(r.startsWith(`palette.`)||r.startsWith(`semantic.`)||r.startsWith(`components.`))?ap(e,r):r}function op(e){let t={};function n(r,i){for(let[a,o]of Object.entries(r)){let r=`${i}.${a}`;if(typeof o==`string`){let n=ap(e,o);n!==void 0&&(t[r]={path:r,value:n,type:i.includes(`color`)?`color`:i.includes(`spacing`)?`spacing`:i.includes(`typography`)?`typography`:i.includes(`shadow`)?`shadow`:i.includes(`border`)?`border`:`color`})}else typeof o==`object`&&o&&n(o,r)}}return n(e.palette,`palette`),n(e.semantic,`semantic`),n(e.components,`components`),t}function sp(e){let t=[],n=[];return e.palette||t.push({path:`palette`,message:`Theme must include a palette`,severity:`error`}),e.semantic||n.push({path:`semantic`,message:`No semantic tokens defined - defaults will be used`,severity:`warning`}),e.components||n.push({path:`components`,message:`No component tokens defined - defaults will be used`,severity:`warning`}),{valid:t.length===0,errors:t,warnings:n}}function cp(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t&&typeof t==`object`&&!Array.isArray(t)&&r&&typeof r==`object`&&!Array.isArray(r)?cp(t,r):r}return n}function lp(e,t){return t?cp(e,t):e}function up(e,t={}){let n=ip(t.future),r={palette:n.palette,semantic:n.semantic,components:n.components},i={palette:{...r.palette,...e?.palette,colors:{...r.palette.colors,...e?.palette?.colors},spacing:{...r.palette.spacing,...e?.palette?.spacing},typography:{...r.palette.typography,...e?.palette?.typography},shadows:{...r.palette.shadows,...e?.palette?.shadows},borders:{...r.palette.borders,...e?.palette?.borders},radius:{...r.palette.radius,...e?.palette?.radius}},semantic:{...r.semantic,...e?.semantic,colors:{...r.semantic.colors,...e?.semantic?.colors,interactive:{...r.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...r.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...r.semantic.spacing,...e?.semantic?.spacing},typography:{...r.semantic.typography,...e?.semantic?.typography}},components:lp(r.components,e?.components)},a=e?.components?.activity;for(let e of[`toolBubble`,`reasoningBubble`])for(let t of[`rowHeight`,`labelSize`,`iconSize`,`indent`,`bodySurface`])a?.[t]!==void 0&&(i.components[e][t]=a[t]);let o=e?.components?.collapsibleWidget?.surface;o!==void 0&&a?.bodySurface===void 0&&(i.components.activity={...i.components.activity,bodySurface:o});let s=e?.components?.header;s?.padding!==void 0&&s.minimalPadding===void 0&&(i.components.header.minimalPadding=i.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(i.components.message.fullscreenGap=i.components.message.gap),t.validate!==!1){let e=sp(i);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(`, `)}`)}if(t.plugins)for(let e of t.plugins)i=e.transform(i);return i}const dp=e=>e.trim()===`0`?`0px`:e,fp=`--persona-`,pp=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let e=t.slice(1);if(!/^[0-9a-f]+$/.test(e))return;e.length===3||e.length===4?n=[0,1,2].map(t=>parseInt(e[t]+e[t],16)):(e.length===6||e.length===8)&&(n=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16)))}else{let e=t.match(/^rgba?\(([^)]+)\)$/);if(e){let t=e[1].split(/[,/\s]+/).filter(Boolean);t.length>=3&&(n=t.slice(0,3).map(e=>{let t=e.endsWith(`%`),n=parseFloat(t?e.slice(0,-1):e);return t?n/100*255:n}))}}if(!n||n.some(e=>!Number.isFinite(e)))return;let[r,i,a]=n.map(e=>{let t=Math.max(0,Math.min(255,e))/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a},mp=(e,t)=>{for(let[n,...r]of t){let t;for(let n of r)if(t=n.charCodeAt(0)===61?n.slice(1):e[fp+n],t!==void 0)break;t!==void 0&&(e[fp+n]=t)}};function hp(e){let t=op(e),n={};for(let[e,r]of Object.entries(t)){let t=e.replace(/\./g,`-`);n[`--persona-${t}`]=r.value}mp(n,[[`primary`,`semantic-colors-primary`,`palette-colors-primary-500`],[`secondary`,`semantic-colors-secondary`,`palette-colors-secondary-500`],[`accent`,`semantic-colors-accent`,`palette-colors-accent-500`],[`surface`,`semantic-colors-surface`,`palette-colors-gray-50`],[`background`,`semantic-colors-background`,`palette-colors-gray-50`],[`container`,`semantic-colors-container`,`palette-colors-gray-100`],[`text`,`semantic-colors-text`,`palette-colors-gray-900`],[`text-muted`,`semantic-colors-text-muted`,`palette-colors-gray-500`],[`text-inverse`,`semantic-colors-text-inverse`,`palette-colors-gray-50`],[`border`,`semantic-colors-border`,`palette-colors-gray-200`],[`divider`,`semantic-colors-divider`,`palette-colors-gray-200`],[`muted`,`text-muted`],[`voice-recording-indicator`,`components-voice-recording-indicator`,`palette-colors-error-500`],[`voice-recording-bg`,`components-voice-recording-background`,`palette-colors-error-50`],[`voice-processing-icon`,`components-voice-processing-icon`,`palette-colors-primary-500`],[`voice-speaking-icon`,`components-voice-speaking-icon`,`palette-colors-success-500`],[`approval-bg`,`components-approval-requested-background`,`surface`],[`approval-border`,`components-approval-requested-border`,`border`],[`approval-text`,`components-approval-requested-text`,`palette-colors-gray-900`],[`approval-shadow`,`components-approval-requested-shadow`,`=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)`],[`approval-approve-bg`,`components-approval-approve-background`,`button-primary-bg`],[`approval-deny-bg`,`components-approval-deny-background`,`container`],[`attachment-image-bg`,`components-attachment-image-background`,`palette-colors-gray-100`],[`attachment-image-border`,`components-attachment-image-border`,`palette-colors-gray-200`],[`font-family`,`semantic-typography-fontFamily`,`palette-typography-fontFamily-sans`],[`font-size`,`semantic-typography-fontSize`,`palette-typography-fontSize-base`],[`font-weight`,`semantic-typography-fontWeight`,`palette-typography-fontWeight-normal`],[`line-height`,`semantic-typography-lineHeight`,`palette-typography-lineHeight-normal`],[`input-font-family`,`font-family`],[`input-font-weight`,`font-weight`],[`radius-sm`,`palette-radius-sm`,`=0.125rem`],[`radius-md`,`palette-radius-md`,`=0.375rem`],[`radius-lg`,`palette-radius-lg`,`=0.5rem`],[`radius-xl`,`palette-radius-xl`,`=0.75rem`],[`radius-full`,`palette-radius-full`,`=9999px`],[`launcher-radius`,`components-launcher-borderRadius`,`palette-radius-full`,`=9999px`],[`launcher-bg`,`components-launcher-background`,`surface`],[`launcher-fg`,`components-launcher-foreground`,`primary`]]);let r=n[`--persona-components-launcher-foreground`];n[`--persona-launcher-fg-muted`]=r&&r!==n[`--persona-primary`]?`color-mix(in srgb, ${r} 70%, transparent)`:n[`--persona-muted`],mp(n,[[`launcher-border`,`components-launcher-border`,`border`],[`button-primary-bg`,`components-button-primary-background`,`primary`],[`button-primary-fg`,`components-button-primary-foreground`,`text-inverse`],[`button-radius`,`components-button-primary-borderRadius`,`palette-radius-full`,`=9999px`],[`button-stop-bg`,`components-button-stop-background`],[`button-stop-fg`,`components-button-stop-foreground`]]),mp(n,[[`button-ghost-bg`,`components-button-ghost-background`,`=transparent`],[`button-ghost-fg`,`components-button-ghost-foreground`,`text`],[`button-ghost-radius`,`components-button-ghost-borderRadius`,`radius-md`,`=0.375rem`],[`button-ghost-hover-bg`,`components-button-ghost-hoverBackground`,`=rgba(0, 0, 0, 0.05)`],[`panel-radius`,`components-panel-borderRadius`,`radius-xl`,`=0.75rem`]]),n[`--persona-panel-border`]=n[`--persona-components-panel-border`]??`1px solid ${n[`--persona-border`]}`,mp(n,[[`panel-shadow`,`components-panel-shadow`,`palette-shadows-xl`,`=0 25px 50px -12px rgba(0, 0, 0, 0.25)`]]),n[`--persona-panel-inset`]=n[`--persona-components-panel-inset`]??`16px`,n[`--persona-panel-canvas-bg`]=n[`--persona-components-panel-canvasBackground`]??`transparent`,mp(n,[[`launcher-shadow`,`components-launcher-shadow`,`=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)`],[`input-radius`,`components-input-borderRadius`,`radius-lg`,`=0.5rem`],[`message-user-radius`,`components-message-user-borderRadius`,`radius-lg`,`=0.5rem`],[`message-assistant-radius`,`components-message-assistant-borderRadius`,`radius-lg`,`=0.5rem`]]),mp(n,[[`header-bg`,`components-header-background`,`surface`]]);let i=n[`--persona-header-bg`],a=n[`--persona-components-header-foreground`],o=a?`color-mix(in srgb, ${a} 72%, ${i})`:void 0;n[`--persona-header-border`]=n[`--persona-components-header-border`]??(a?`color-mix(in srgb, ${a} 14%, ${i})`:void 0)??n[`--persona-divider`],mp(n,[[`header-icon-bg`,`components-header-iconBackground`,`primary`],[`header-icon-fg`,`components-header-iconForeground`,`text-inverse`]]),n[`--persona-header-title-fg`]=n[`--persona-components-header-title-color`]??n[`--persona-components-header-titleForeground`]??a??n[`--persona-primary`],n[`--persona-header-subtitle-fg`]=n[`--persona-components-header-subtitle-color`]??n[`--persona-components-header-subtitleForeground`]??o??n[`--persona-text-muted`],n[`--persona-header-action-icon-fg`]=n[`--persona-components-header-actionIconForeground`]??o??n[`--persona-muted`],mp(n,[[`header-control-size`,`components-header-controlSize`,`=32px`],[`header-control-icon-size`,`components-header-controlIconSize`,`=20px`]]);let s=e.components?.header;s?.shadow&&(n[`--persona-header-shadow`]=s.shadow),s?.borderBottom&&(n[`--persona-header-border-bottom`]=s.borderBottom),s?.minHeight&&(n[`--persona-header-min-height`]=s.minHeight);let c=n[`--persona-components-history-railHeader-background`];c&&(n[`--persona-history-rail-header-bg`]=c);let l=n[`--persona-components-history-railHeader-border`];l&&(n[`--persona-history-rail-header-border`]=l);let u=n[`--persona-components-history-railHeader-minHeight`];u&&(n[`--persona-history-rail-header-min-height`]=u);for(let[e,t]of[[`margin`,`margin`],[`borderRadius`,`radius`],[`shadow`,`shadow`],[`background`,`bg`]]){let r=n[`--persona-components-history-overlay-${e}`];r&&(n[`--persona-history-overlay-${t}`]=r)}for(let[e,t]of[[`background`,`bg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-history-menu-${e}`];r&&(n[`--persona-history-menu-${t}`]=r)}let d=e.components?.history?.motion;if(d){let e=e=>{if(e===void 0)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},t=e(d.enterDurationMs);t!==void 0&&(n[`--persona-history-enter-ms`]=t);let r=e(d.exitDurationMs);r!==void 0&&(n[`--persona-history-exit-ms`]=r),d.enterEasing&&(n[`--persona-history-enter-easing`]=d.enterEasing),d.exitEasing&&(n[`--persona-history-exit-easing`]=d.exitEasing)}let f=n[`--persona-components-history-dangerForeground`];f&&(n[`--persona-history-danger-fg`]=f),n[`--persona-danger`]=n[`--persona-components-history-confirm-dangerBackground`]??n[`--persona-palette-colors-error-700`]??`#b42318`,n[`--persona-danger-fg`]=n[`--persona-components-history-confirm-dangerForeground`]??`#ffffff`;for(let e of[`scrim`,`shadow`]){let t=n[`--persona-components-history-confirm-${e}`];t&&(n[`--persona-history-confirm-${e}`]=t)}for(let[e,t]of[[`background`,`background`],[`foreground`,`foreground`],[`hintForeground`,`hint-fg`],[`borderRadius`,`radius`],[`fontSize`,`font-size`],[`padding`,`padding`],[`maxWidth`,`max-width`],[`shadow`,`shadow`]]){let r=n[`--persona-components-tooltip-${e}`];r&&(n[`--persona-tooltip-${t}`]=r)}e.components?.tooltip?.arrow===!1&&(n[`--persona-tooltip-arrow-display`]=`none`);for(let[e,t]of[[`background`,`bg`],[`border`,`border`],[`hoverBackground`,`hover-bg`],[`hoverForeground`,`hover-fg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-messageActions-${e}`];r&&(n[`--persona-message-action-${t}`]=r)}mp(n,[[`intro-card-bg`,`components-introCard-background`,`=transparent`],[`intro-card-radius`,`components-introCard-borderRadius`,`=1rem`]]);let p=n[`--persona-components-introCard-background`],m=n[`--persona-components-introCard-shadow`],h=(!p||p===`transparent`||p===`none`)&&(!m||m===`none`),g=n[`--persona-components-introCard-padding`]??`1.5rem`;n[`--persona-intro-card-padding`]=h&&g===`1.5rem`?`1.5rem 0`:g,mp(n,[[`intro-card-shadow`,`components-introCard-shadow`,`=none`],[`intro-card-border`,`components-introCard-border`,`=none`],[`input-background`,`components-input-background`,`surface`],[`input-placeholder`,`components-input-placeholder`,`text-muted`],[`input-backdrop-filter`,`components-input-backdropFilter`,`=none`],[`message-user-bg`,`components-message-user-background`,`accent`],[`message-user-text`,`components-message-user-text`,`text-inverse`],[`message-user-shadow`,`components-message-user-shadow`,`=0 5px 15px rgba(15, 23, 42, 0.08)`],[`message-assistant-bg`,`components-message-assistant-background`,`surface`],[`message-assistant-text`,`components-message-assistant-text`,`text`],[`message-assistant-border`,`components-message-assistant-border`,`border`],[`message-assistant-shadow`,`components-message-assistant-shadow`,`=0 1px 2px 0 rgb(0 0 0 / 0.05)`],[`scroll-to-bottom-bg`,`components-scrollToBottom-background`,`button-primary-bg`,`accent`],[`scroll-to-bottom-fg`,`components-scrollToBottom-foreground`,`button-primary-fg`,`text-inverse`],[`scroll-to-bottom-border`,`components-scrollToBottom-border`,`primary`],[`scroll-to-bottom-size`,`components-scrollToBottom-size`,`=40px`],[`scroll-to-bottom-radius`,`components-scrollToBottom-borderRadius`,`button-radius`,`radius-full`,`=9999px`],[`scroll-to-bottom-shadow`,`components-scrollToBottom-shadow`,`palette-shadows-sm`,`=0 1px 2px 0 rgb(0 0 0 / 0.05)`],[`scroll-to-bottom-padding`,`components-scrollToBottom-padding`,`=0.5rem 0.875rem`],[`scroll-to-bottom-gap`,`components-scrollToBottom-gap`,`=0.5rem`],[`scroll-to-bottom-font-size`,`components-scrollToBottom-fontSize`,`palette-typography-fontSize-sm`,`=0.875rem`],[`scroll-to-bottom-icon-size`,`components-scrollToBottom-iconSize`,`=14px`],[`event-badge-flow-bg`,`components-eventStream-badge-flow-background`,`=#dcfce7`],[`event-badge-flow-fg`,`components-eventStream-badge-flow-foreground`,`=#15803d`],[`event-badge-step-bg`,`components-eventStream-badge-step-background`,`=#f5f5f5`],[`event-badge-step-fg`,`components-eventStream-badge-step-foreground`,`=#0a0a0a`],[`event-badge-reasoning-bg`,`components-eventStream-badge-reasoning-background`,`=#fef9c3`],[`event-badge-reasoning-fg`,`components-eventStream-badge-reasoning-foreground`,`=#a16207`],[`event-badge-tool-bg`,`components-eventStream-badge-tool-background`,`=#f3e8ff`],[`event-badge-tool-fg`,`components-eventStream-badge-tool-foreground`,`=#6b21a8`],[`event-badge-agent-bg`,`components-eventStream-badge-agent-background`,`=#ccfbf1`],[`event-badge-agent-fg`,`components-eventStream-badge-agent-foreground`,`=#115e59`],[`event-badge-error-bg`,`components-eventStream-badge-error-background`,`=#fee2e2`],[`event-badge-error-fg`,`components-eventStream-badge-error-foreground`,`=#b91c1c`],[`event-badge-default-bg`,`components-eventStream-badge-default-background`,`=#f3f4f6`],[`event-badge-default-fg`,`components-eventStream-badge-default-foreground`,`=#4b5563`],[`tool-bubble-shadow`,`components-toolBubble-shadow`,`=0 5px 15px rgba(15, 23, 42, 0.08)`],[`reasoning-bubble-shadow`,`components-reasoningBubble-shadow`,`=0 5px 15px rgba(15, 23, 42, 0.08)`],[`composer-shadow`,`components-composer-shadow`,`=none`]]),mp(n,[[`composer-padding`,`components-composer-padding`,`=0.75rem 1rem`],[`composer-gap`,`components-composer-gap`,`=0.5rem`],[`composer-font-size`,`components-composer-fontSize`,`=0.875rem`],[`composer-line-height`,`components-composer-lineHeight`,`=1.25rem`],[`composer-control-size`,`components-composer-controlSize`,`=40px`],[`composer-control-icon-size`,`components-composer-controlIconSize`,`=24px`],[`motion-duration-fast`,`components-motion-durationFast`,`=120ms`],[`motion-duration-base`,`components-motion-durationBase`,`=200ms`],[`motion-easing`,`components-motion-easing`,`=cubic-bezier(0.2, 0, 0, 1)`],[`composer-border-color`,`components-composer-borderColor`,`border`,`=#e5e7eb`],[`composer-overlay-band`,`components-composer-overlayBand`,`=transparent`],[`scrollbar-thumb`,`components-scrollbar-thumb`,`border`,`=#e5e7eb`],[`scrollbar-track`,`components-scrollbar-track`,`=transparent`],[`md-inline-code-bg`,`components-markdown-inlineCode-background`,`container`],[`md-inline-code-color`,`components-markdown-inlineCode-foreground`,`text`],[`md-link-color`,`components-markdown-link-foreground`,`accent`,`=#0f0f0f`]]);let _=n[`--persona-components-markdown-heading-h1-fontSize`];_&&(n[`--persona-md-h1-size`]=_);let v=n[`--persona-components-markdown-heading-h1-fontWeight`];v&&(n[`--persona-md-h1-weight`]=v);let y=n[`--persona-components-markdown-heading-h2-fontSize`];y&&(n[`--persona-md-h2-size`]=y);let b=n[`--persona-components-markdown-heading-h2-fontWeight`];b&&(n[`--persona-md-h2-weight`]=b);let x=n[`--persona-components-markdown-prose-fontFamily`];x&&x!==`inherit`&&(n[`--persona-md-prose-font-family`]=x),mp(n,[[`md-code-block-bg`,`components-markdown-codeBlock-background`,`container`],[`md-code-block-border-color`,`components-markdown-codeBlock-borderColor`,`border`],[`md-code-block-text-color`,`components-markdown-codeBlock-textColor`,`=inherit`]]),mp(n,[[`md-code-block-border-radius`,`components-markdown-codeBlock-borderRadius`,`radius-md`,`=0.375rem`]]),mp(n,[[`md-table-header-bg`,`components-markdown-table-headerBackground`,`container`],[`md-table-border-color`,`components-markdown-table-borderColor`,`border`]]),mp(n,[[`md-hr-color`,`components-markdown-hr-color`,`divider`]]),mp(n,[[`md-blockquote-border-color`,`components-markdown-blockquote-borderColor`,`palette-colors-gray-900`],[`md-blockquote-bg`,`components-markdown-blockquote-background`,`=transparent`],[`md-blockquote-text-color`,`components-markdown-blockquote-textColor`,`palette-colors-gray-500`]]);for(let[e,t]of[[`container`,`surface`],[`surface`,`surface`],[`border`,`border`]]){let r=n[`--persona-components-collapsibleWidget-${e}`]??n[`--persona-${t}`];r!==void 0&&(n[`--persona-cw-${e}`]=r,n[`--cw-${e}`]=r)}mp(n,[[`message-border`,`components-message-border`,`border`]]),mp(n,[[`message-user-padding`,`components-message-user-padding`],[`message-user-max-width`,`components-message-user-maxWidth`],[`message-user-font-size`,`components-message-user-fontSize`],[`message-user-font-family`,`components-message-user-fontFamily`],[`message-user-line-height`,`components-message-user-lineHeight`],[`message-assistant-padding`,`components-message-assistant-padding`],[`message-assistant-border-width`,`components-message-assistant-borderWidth`],[`message-assistant-max-width`,`components-message-assistant-maxWidth`],[`message-assistant-font-size`,`components-message-assistant-fontSize`],[`message-assistant-font-family`,`components-message-assistant-fontFamily`],[`message-assistant-line-height`,`components-message-assistant-lineHeight`]]);let S=e.components,C=S?.iconButton;C&&(C.background&&(n[`--persona-icon-btn-bg`]=C.background),C.border&&(n[`--persona-icon-btn-border`]=C.border),C.color&&(n[`--persona-icon-btn-color`]=C.color),C.padding&&(n[`--persona-icon-btn-padding`]=C.padding),C.borderRadius&&(n[`--persona-icon-btn-radius`]=C.borderRadius),C.hoverBackground&&(n[`--persona-icon-btn-hover-bg`]=C.hoverBackground),C.hoverColor&&(n[`--persona-icon-btn-hover-color`]=C.hoverColor),C.activeBackground&&(n[`--persona-icon-btn-active-bg`]=C.activeBackground),C.activeBorder&&(n[`--persona-icon-btn-active-border`]=C.activeBorder));let w=S?.labelButton;w&&(w.background&&(n[`--persona-label-btn-bg`]=w.background),w.border&&(n[`--persona-label-btn-border`]=w.border),w.color&&(n[`--persona-label-btn-color`]=w.color),w.padding&&(n[`--persona-label-btn-padding`]=w.padding),w.borderRadius&&(n[`--persona-label-btn-radius`]=w.borderRadius),w.hoverBackground&&(n[`--persona-label-btn-hover-bg`]=w.hoverBackground),w.fontSize&&(n[`--persona-label-btn-font-size`]=w.fontSize),w.gap&&(n[`--persona-label-btn-gap`]=w.gap));let T=S?.toggleGroup;T&&(T.gap&&(n[`--persona-toggle-group-gap`]=T.gap),T.borderRadius&&(n[`--persona-toggle-group-radius`]=T.borderRadius));let E=S?.artifact;if(E?.toolbar){let t=E.toolbar;t.iconHoverColor&&(n[`--persona-artifact-toolbar-icon-hover-color`]=t.iconHoverColor),t.iconHoverBackground&&(n[`--persona-artifact-toolbar-icon-hover-bg`]=t.iconHoverBackground),t.iconPadding&&(n[`--persona-artifact-toolbar-icon-padding`]=t.iconPadding),t.iconBorderRadius&&(n[`--persona-artifact-toolbar-icon-radius`]=t.iconBorderRadius),t.iconBorder&&(n[`--persona-artifact-toolbar-icon-border`]=t.iconBorder),t.toggleGroupGap&&(n[`--persona-artifact-toolbar-toggle-group-gap`]=dp(t.toggleGroupGap)),t.toggleBorderRadius&&(n[`--persona-artifact-toolbar-toggle-radius`]=t.toggleBorderRadius),t.toggleGroupPadding&&(n[`--persona-artifact-toolbar-toggle-group-padding`]=dp(t.toggleGroupPadding)),t.toggleGroupBorder&&(n[`--persona-artifact-toolbar-toggle-group-border`]=t.toggleGroupBorder),t.toggleGroupBorderRadius&&(n[`--persona-artifact-toolbar-toggle-group-radius`]=t.toggleGroupBorderRadius),t.toggleGroupBackground&&(n[`--persona-artifact-toolbar-toggle-group-bg`]=ap(e,t.toggleGroupBackground)??t.toggleGroupBackground),t.copyBackground&&(n[`--persona-artifact-toolbar-copy-bg`]=t.copyBackground),t.copyBorder&&(n[`--persona-artifact-toolbar-copy-border`]=t.copyBorder),t.copyColor&&(n[`--persona-artifact-toolbar-copy-color`]=t.copyColor),t.copyBorderRadius&&(n[`--persona-artifact-toolbar-copy-radius`]=dp(t.copyBorderRadius)),t.copyPadding&&(n[`--persona-artifact-toolbar-copy-padding`]=t.copyPadding),t.copyMenuBackground&&(n[`--persona-artifact-toolbar-copy-menu-bg`]=t.copyMenuBackground,n[`--persona-dropdown-bg`]=n[`--persona-dropdown-bg`]??t.copyMenuBackground),t.copyMenuBorder&&(n[`--persona-artifact-toolbar-copy-menu-border`]=t.copyMenuBorder,n[`--persona-dropdown-border`]=n[`--persona-dropdown-border`]??t.copyMenuBorder),t.copyMenuShadow&&(n[`--persona-artifact-toolbar-copy-menu-shadow`]=t.copyMenuShadow,n[`--persona-dropdown-shadow`]=n[`--persona-dropdown-shadow`]??t.copyMenuShadow),t.copyMenuBorderRadius&&(n[`--persona-artifact-toolbar-copy-menu-radius`]=t.copyMenuBorderRadius,n[`--persona-dropdown-radius`]=n[`--persona-dropdown-radius`]??t.copyMenuBorderRadius),t.copyMenuItemHoverBackground&&(n[`--persona-artifact-toolbar-copy-menu-item-hover-bg`]=t.copyMenuItemHoverBackground,n[`--persona-dropdown-item-hover-bg`]=n[`--persona-dropdown-item-hover-bg`]??t.copyMenuItemHoverBackground),t.iconBackground&&(n[`--persona-artifact-toolbar-icon-bg`]=t.iconBackground),t.toolbarBorder&&(n[`--persona-artifact-toolbar-border`]=t.toolbarBorder)}if(E?.tab){let e=E.tab;e.background&&(n[`--persona-artifact-tab-bg`]=e.background),e.activeBackground&&(n[`--persona-artifact-tab-active-bg`]=e.activeBackground),e.activeBorder&&(n[`--persona-artifact-tab-active-border`]=e.activeBorder),e.borderRadius&&(n[`--persona-artifact-tab-radius`]=e.borderRadius),e.textColor&&(n[`--persona-artifact-tab-color`]=e.textColor),e.hoverBackground&&(n[`--persona-artifact-tab-hover-bg`]=e.hoverBackground),e.listBackground&&(n[`--persona-artifact-tab-list-bg`]=e.listBackground),e.listBorderColor&&(n[`--persona-artifact-tab-list-border-color`]=e.listBorderColor),e.listPadding&&(n[`--persona-artifact-tab-list-padding`]=e.listPadding)}if(E?.pane){let t=E.pane;t.toolbarBackground&&(n[`--persona-artifact-toolbar-bg`]=ap(e,t.toolbarBackground)??t.toolbarBackground)}if(E?.card){let e=E.card;e.background&&(n[`--persona-artifact-card-bg`]=e.background),e.border&&(n[`--persona-artifact-card-border`]=e.border),e.borderRadius&&(n[`--persona-artifact-card-radius`]=e.borderRadius),e.hoverBackground&&(n[`--persona-artifact-card-hover-bg`]=e.hoverBackground),e.hoverBorderColor&&(n[`--persona-artifact-card-hover-border`]=e.hoverBorderColor)}if(E?.inline){let t=E.inline;t.background&&(n[`--persona-artifact-inline-bg`]=ap(e,t.background)??t.background),t.border&&(n[`--persona-artifact-inline-border`]=t.border),t.borderRadius&&(n[`--persona-artifact-inline-radius`]=t.borderRadius),t.chromeBackground&&(n[`--persona-artifact-inline-chrome-bg`]=ap(e,t.chromeBackground)??t.chromeBackground),t.chromeBorder&&(n[`--persona-artifact-inline-chrome-border`]=ap(e,t.chromeBorder)??t.chromeBorder),t.titleColor&&(n[`--persona-artifact-inline-title-color`]=ap(e,t.titleColor)??t.titleColor),t.mutedColor&&(n[`--persona-artifact-inline-muted-color`]=ap(e,t.mutedColor)??t.mutedColor),t.frameHeight&&(n[`--persona-artifact-inline-frame-height`]=t.frameHeight)}let D=S?.code;D&&(D.keywordColor&&(n[`--persona-code-keyword-color`]=D.keywordColor),D.stringColor&&(n[`--persona-code-string-color`]=D.stringColor),D.commentColor&&(n[`--persona-code-comment-color`]=D.commentColor),D.numberColor&&(n[`--persona-code-number-color`]=D.numberColor),D.tagColor&&(n[`--persona-code-tag-color`]=D.tagColor),D.attrColor&&(n[`--persona-code-attr-color`]=D.attrColor),D.propertyColor&&(n[`--persona-code-property-color`]=D.propertyColor),D.lineNumberColor&&(n[`--persona-code-line-number-color`]=D.lineNumberColor),D.gutterBorderColor&&(n[`--persona-code-gutter-border-color`]=D.gutterBorderColor),D.background&&(n[`--persona-code-bg`]=ap(e,D.background)??D.background));let O=n[`--persona-surface`],k=n[`--persona-container`],ee=n[`--persona-palette-colors-gray-100`]??`#f3f4f6`,te=n[`--persona-palette-colors-gray-200`]??`#e5e7eb`,ne=n[`--persona-palette-colors-gray-300`]??`#d1d5db`,re=!k||k===O,ie=pp(O??n[`--persona-background`]),ae=re&&ie!==void 0&&ie<.179,oe=ae?`rgba(255, 255, 255, 0.08)`:ee,A=ae?`rgba(255, 255, 255, 0.12)`:te,j=ae?`rgba(255, 255, 255, 0.16)`:ne,se=re?oe:k,ce=re?A:k;return n[`--persona-icon-btn-hover-bg`]=n[`--persona-icon-btn-hover-bg`]??se,n[`--persona-icon-btn-active-bg`]=n[`--persona-icon-btn-active-bg`]??ce,re&&(n[`--persona-icon-btn-active-border`]=n[`--persona-icon-btn-active-border`]??j),n[`--persona-label-btn-hover-bg`]=n[`--persona-label-btn-hover-bg`]??se,n[`--persona-artifact-tab-hover-bg`]=n[`--persona-artifact-tab-hover-bg`]??se,n[`--persona-artifact-card-hover-bg`]=n[`--persona-artifact-card-hover-bg`]??se,n}const gp={header:`Widget header bar`,messages:`Message list area`,"user-message":`User message bubble`,"assistant-message":`Assistant message bubble`,composer:`Footer / composer area`,container:`Main widget container`,"artifact-pane":`Artifact sidebar`,"artifact-toolbar":`Artifact toolbar`,"artifact-inline":`Inline artifact block`,"artifact-inline-chrome":`Inline artifact title bar`};No(),Xa();const _p=e=>!!e&&`launcher`in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode===`docked`),vp=(e,t)=>{if(!t||!_p(t))return e;let n=t.theme?.components?.panel?.width,r=t.darkTheme?.components?.panel?.width;return(kp(t)===`dark`?r??n:n)==null?{...e,components:{...e.components,panel:{...e.components.panel,width:_o(t)===`v5`?`400px`:`420px`}}}:e},yp={colors:{primary:{50:`#ffffff`,100:`#f5f5f5`,200:`#d4d4d4`,300:`#a3a3a3`,400:`#737373`,500:`#171717`,600:`#0f0f0f`,700:`#0a0a0a`,800:`#050505`,900:`#030303`,950:`#000000`},secondary:{50:`#f5f3ff`,100:`#ede9fe`,200:`#ddd6fe`,300:`#c4b5fd`,400:`#a78bfa`,500:`#8b5cf6`,600:`#7c3aed`,700:`#6d28d9`,800:`#5b21b6`,900:`#4c1d95`,950:`#2e1065`},accent:{50:`#ecfeff`,100:`#cffafe`,200:`#a5f3fc`,300:`#67e8f9`,400:`#22d3ee`,500:`#06b6d4`,600:`#0891b2`,700:`#0e7490`,800:`#155e75`,900:`#164e63`,950:`#083344`},gray:{50:`#f9fafb`,100:`#f3f4f6`,200:`#e5e7eb`,300:`#d1d5db`,400:`#9ca3af`,500:`#6b7280`,600:`#4b5563`,700:`#374151`,800:`#1f2937`,900:`#111827`,950:`#030712`},success:{50:`#f0fdf4`,100:`#dcfce7`,200:`#bbf7d0`,300:`#86efac`,400:`#4ade80`,500:`#22c55e`,600:`#16a34a`,700:`#15803d`,800:`#166534`,900:`#14532d`},warning:{50:`#fefce8`,100:`#fef9c3`,200:`#fef08a`,300:`#fde047`,400:`#facc15`,500:`#eab308`,600:`#ca8a04`,700:`#a16207`,800:`#854d0e`,900:`#713f12`},error:{50:`#fef2f2`,100:`#fee2e2`,200:`#fecaca`,300:`#fca5a5`,400:`#f87171`,500:`#ef4444`,600:`#dc2626`,700:`#b91c1c`,800:`#991b1b`,900:`#7f1d1d`}}},bp={components:{button:{ghost:{hoverBackground:`rgba(255, 255, 255, 0.08)`}},markdown:{link:{foreground:`palette.colors.primary.300`}},eventStream:{badge:{flow:{background:`palette.colors.success.900`,foreground:`palette.colors.success.300`},step:{background:`palette.colors.primary.800`,foreground:`palette.colors.primary.200`},reasoning:{background:`palette.colors.warning.900`,foreground:`palette.colors.warning.300`},tool:{background:`palette.colors.purple.900`,foreground:`palette.colors.purple.300`},agent:{background:`palette.colors.teal.900`,foreground:`palette.colors.teal.300`},error:{background:`palette.colors.error.900`,foreground:`palette.colors.error.300`},default:{background:`palette.colors.gray.800`,foreground:`palette.colors.gray.300`}}},history:{dangerForeground:`#f87171`,confirm:{dangerBackground:`palette.colors.error.600`,scrim:`rgba(0, 0, 0, 0.6)`}}}},xp=yp,Sp={...xp,colors:{...xp.colors,primary:{50:`#0f0f10`,100:`#27272a`,200:`#3f3f46`,300:`#52525b`,400:`#71717a`,500:`#f4f4f5`,600:`#e4e4e7`,700:`#d4d4d8`,800:`#a1a1aa`,900:`#fafafa`,950:`#ffffff`},gray:{50:`#1a1a1b`,100:`#27272a`,200:`#2a2a2d`,300:`#52525b`,400:`#71717a`,500:`#a1a1aa`,600:`#b4b4bd`,700:`#d4d4d8`,800:`#e4e4e7`,900:`#f4f4f5`,950:`#fafafa`}}},Cp=bp,wp={semantic:{colors:{primary:`palette.colors.primary.500`,accent:`palette.colors.primary.600`,background:`#0f0f10`,surface:`palette.colors.gray.50`,container:`#1c1c20`,text:`palette.colors.gray.900`,textMuted:`palette.colors.gray.500`,textInverse:`#0f0f10`,border:`palette.colors.gray.200`,divider:`palette.colors.gray.200`,interactive:{default:`palette.colors.primary.600`,hover:`palette.colors.primary.700`,focus:`palette.colors.primary.600`,active:`palette.colors.primary.600`}}},components:{...bp.components,button:{...bp.components?.button,primary:{background:`semantic.colors.primary`,foreground:`palette.colors.primary.50`}},markdown:{inlineCode:{background:`palette.colors.gray.100`,foreground:`semantic.colors.text`},link:{foreground:`semantic.colors.accent`},codeBlock:{background:`semantic.colors.container`,borderColor:`semantic.colors.border`,textColor:`semantic.colors.text`},table:{headerBackground:`palette.colors.gray.100`,borderColor:`semantic.colors.border`},blockquote:{background:`semantic.colors.container`,borderColor:`palette.colors.gray.300`,textColor:`semantic.colors.textMuted`}},eventStream:{...bp.components?.eventStream,badge:{...bp.components?.eventStream?.badge,step:{background:`palette.colors.gray.100`,foreground:`palette.colors.gray.700`},default:{background:`palette.colors.gray.100`,foreground:`palette.colors.gray.700`}}}}},Tp=e=>_o({future:e})===`v5`?{palette:Sp,components:wp}:{palette:xp,components:Cp},Ep=e=>{if(e&&typeof e==`object`&&!Array.isArray(e))return e},Dp=()=>typeof document<`u`&&document.documentElement.classList.contains(`dark`)||typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`,Op=e=>{let t=e?.colorScheme??`light`;return t===`light`?`light`:t===`dark`?`dark`:Dp()},kp=e=>Op(e),Ap=(e,t={})=>up(e,t),jp=(e,t={})=>{let n=Tp(t.future),r=Ja(n.components,e??{})??{};return up({...r,palette:{...r.palette,colors:_o(t)===`v5`?Ja(n.palette.colors,r.palette?.colors):{...n.palette.colors,...r.palette?.colors}}},{validate:!1,future:t.future})},Mp=e=>{let t=kp(e),n=Ep(e?.theme),r=Ja({components:{launcher:zf(e)===`circle`?Bf:{...ep.launcher,...e?.future?.v5Defaults?{offset:`1.5rem`}:{}}}},n),i=Ep(e?.darkTheme);return vp(t===`dark`?jp(Ja(r??{},i??{}),{future:e?.future}):Ap(r,{future:e?.future}),e)},Np=e=>hp(e),Pp=(e,t)=>{let n=Mp(t),r=Np(n);for(let[t,n]of Object.entries(r))e.style.setProperty(t,n);e.setAttribute(`data-persona-color-scheme`,kp(t)),e.setAttribute(`data-persona-defaults`,_o(t))},Fp=e=>{let t=[];if(typeof document<`u`&&typeof MutationObserver<`u`){let n=new MutationObserver(()=>{e(Dp())});n.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),t.push(()=>n.disconnect())}if(typeof window<`u`&&window.matchMedia){let n=window.matchMedia(`(prefers-color-scheme: dark)`),r=()=>e(Dp());n.addEventListener?(n.addEventListener(`change`,r),t.push(()=>n.removeEventListener(`change`,r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(e=>e())}},Ip=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??`720px`:`768px`),Lp=(e,t)=>t||e?.composer?.placement!==`overlay`?`block`:`overlay`,Rp=e=>{if(typeof e!=`string`)return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let n=Number(t[1])/100;return n>0&&n<1?n:null},zp=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight),Bp=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;At.morph(e,t.innerHTML,{morphStyle:`innerHTML`,callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement){if(t instanceof HTMLElement&&t.hasAttribute(`data-persona-reuse`)&&e.id===t.id)return!1;if(r){if(e.classList.contains(`persona-animate-typing`)||e.hasAttribute(`data-preserve-runtime`))return!1;if(e.hasAttribute(`data-tool-elapsed`))return t instanceof HTMLElement&&t.getAttribute(`data-tool-elapsed`)===e.getAttribute(`data-tool-elapsed`)?!1:void 0;if(e.hasAttribute(`data-preserve-animation`))return t instanceof HTMLElement&&!t.hasAttribute(`data-preserve-animation`)||t instanceof HTMLElement&&t.hasAttribute(`data-preserve-animation`)&&(e.textContent??``)!==(t.textContent??``)?void 0:!1}}}}})},Vp=e=>e.replace(/^\n+/,``).replace(/\s+$/,``),Hp={index:-1,draft:``};function Up(e){let{direction:t,history:n,currentValue:r,atStart:i,state:a}=e,o=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t===`up`){if(!o&&!i)return{handled:!1,state:a};if(!o){let e=n.length-1;return{handled:!0,value:n[e],state:{index:e,draft:r}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!o)return{handled:!1,state:a};if(a.index<n.length-1){let e=a.index+1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}const Wp=/* @__PURE__ */ new WeakMap;function Gp(e){if(typeof e==`string`)return e.length;if(!e)return 0;if(typeof e!=`object`)return JSON.stringify(e)?.length??0;let t=Wp.get(e);return t===void 0&&(t=JSON.stringify(e)?.length??0,Wp.set(e,t)),t}function Kp(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??``,e.streaming?`1`:`0`,e.voiceProcessing?`1`:`0`,e.variant??``,e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??``,e.toolCall?.status??``,e.toolCall?.name??``,e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??``,Gp(e.toolCall?.args),e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??``,e.contentParts?.length??0,e.stopReason??``,t].join(`\0`)}function qp(){return/* @__PURE__ */ new Map}function Jp(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Yp(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Xp(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Zp(e){return e.role!==`assistant`||e.variant===`tool`||e.variant===`reasoning`?!1:e.variant===`approval`||!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function Qp(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>!t&&(t=!0,!0)}}function $p(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function em(e,t){return $p(e)-e.scrollTop<=t}function tm(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:i,userScrollThreshold:a,isAutoScrolling:o=!1,pauseOnUpwardScroll:s=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:l=!1}=e,u=n-r;return o||Math.abs(u)<a?{action:`none`,delta:u,nextLastScrollTop:n}:!t&&i&&(!l||u>0)?{action:`resume`,delta:u,nextLastScrollTop:n}:t&&s&&u<0||t&&c&&!i?{action:`pause`,delta:u,nextLastScrollTop:n}:{action:`none`,delta:u,nextLastScrollTop:n}}function nm(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:i=!1}=e;return t&&n<0?`pause`:!t&&i&&n>0&&r?`resume`:`none`}function rm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function im(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset);return{targetScrollTop:t,spacerHeight:Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0))}}function am(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}const om={type:`none`,placeholder:`none`,speed:120,duration:1800,buffer:`none`},sm=[`pre`,`code`,`a`,`script`,`style`],cm=e=>({type:e?.type??om.type,placeholder:e?.placeholder??om.placeholder,speed:e?.speed??om.speed,duration:e?.duration??om.duration,buffer:e?.buffer??om.buffer}),lm=[{name:`typewriter`,containerClass:`persona-stream-typewriter`,wrap:`char`,useCaret:!0},{name:`pop-bubble`,bubbleClass:`persona-stream-pop`,wrap:`none`},{name:`letter-rise`,containerClass:`persona-stream-letter-rise`,wrap:`char`},{name:`word-fade`,containerClass:`persona-stream-word-fade`,wrap:`word`}],um=/* @__PURE__ */ new Map;for(let e of lm)um.set(e.name,e);const dm=[`wipe`,`glyph-cycle`],fm=e=>{um.set(e.name,e)},pm=e=>{lm.some(t=>t.name===e)||um.delete(e)},mm=()=>Array.from(um.keys()),hm=(e,t)=>e===`none`?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:um.get(e)??null,gm=(e,t,n,r,i)=>{if(!i)return e;if(n?.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t===`word`){let t=e.search(/\s(?=\S*$)/);return t<0?``:e.slice(0,t)}if(t===`line`){let t=e.lastIndexOf(`
|
|
24
|
+
`);return t<0?``:e.slice(0,t)}return e},_m=(e,t,n,r)=>{let i=e.createElement(`span`);return i.className=`persona-stream-char`,i.id=`stream-c-${n}-${r}`,i.style.setProperty(`--char-index`,String(r)),i.textContent=t,i},vm=(e,t,n,r)=>{let i=e.createElement(`span`);return i.className=`persona-stream-word`,i.id=`stream-w-${n}-${r}`,i.style.setProperty(`--word-index`,String(r)),i.textContent=t,i},ym=/\s/,bm=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let e=n;if(t.has(e.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},xm=(e,t,n)=>{let r=e.ownerDocument,i=e.parentNode;if(!r||!i)return;let a=e.nodeValue??``;if(!a)return;let o=r.createDocumentFragment(),s=0;for(;s<a.length;)if(ym.test(a[s])){let e=s;for(;e<a.length&&ym.test(a[e]);)e+=1;o.appendChild(r.createTextNode(a.slice(s,e))),s=e}else{let e=r.createElement(`span`);e.className=`persona-stream-word-group`;let i=s;for(;i<a.length&&!ym.test(a[i]);)e.appendChild(_m(r,a[i],t,n.value)),n.value+=1,i+=1;o.appendChild(e),s=i}i.replaceChild(o,e)},Sm=(e,t,n)=>{let r=e.ownerDocument,i=e.parentNode;if(!r||!i)return;let a=e.nodeValue??``;if(!a)return;let o=r.createDocumentFragment(),s=a.split(/(\s+)/);for(let e of s)e&&(/^\s+$/.test(e)?o.appendChild(r.createTextNode(e)):(o.appendChild(vm(r,e,t,n.value)),n.value+=1));i.replaceChild(o,e)},Cm=(e,t,n,r)=>{if(!e||typeof document>`u`)return e;let i=document.createElement(`div`);i.innerHTML=e;let a=new Set((r?.skipTags??sm).map(e=>e.toLowerCase())),o=document.createTreeWalker(i,NodeFilter.SHOW_TEXT,null),s=[],c=o.nextNode();for(;c;)bm(c,a)||s.push(c),c=o.nextNode();let l={value:r?.startIndex??0},u=t===`char`?xm:Sm;for(let e of s)u(e,n,l);return i.innerHTML},wm=(e=document)=>{let t=e.createElement(`span`);return t.className=`persona-stream-caret`,t.setAttribute(`aria-hidden`,`true`),t.setAttribute(`data-preserve-animation`,`stream-caret`),t},Tm=(e=document)=>{let t=e.createElement(`div`);t.className=`persona-stream-skeleton`,t.setAttribute(`data-preserve-animation`,`stream-skeleton`),t.setAttribute(`aria-hidden`,`true`);let n=e.createElement(`div`);return n.className=`persona-stream-skeleton-line`,t.appendChild(n),t},Em=/* @__PURE__ */ new WeakMap,Dm=(e,t)=>{if(!e.styles)return;let n=Em.get(t);if(n||(n=/* @__PURE__ */ new Set,Em.set(t,n)),n.has(e.name)){let r=e.name.replace(/["\\]/g,`\\$&`);if(t.querySelector(`style[data-persona-animation="${r}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement(`style`);r.setAttribute(`data-persona-animation`,e.name),r.textContent=e.styles,t.appendChild(r)},Om=/* @__PURE__ */ new WeakMap,km=(e,t)=>{if(!e.onAttach)return;let n=Om.get(t);if(n||(n=/* @__PURE__ */ new Map,Om.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},Am=e=>{let t=Om.get(e);if(t){for(let e of t.values())typeof e==`function`&&e();t.clear()}},jm=(e,t)=>{Dm(e,t),km(e,t)};Pt();const{setLoader:Mm,load:Nm}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/animations-extra`)}),Pm=Nm;yi();function Fm(e,t=_i){let n=e.style.position,r=e.style.zIndex,i=e.style.isolation,a=getComputedStyle(e),o=a.position===`static`||a.position===``;return o&&(e.style.position=`relative`),e.style.zIndex=String(t),e.style.isolation=`isolate`,()=>{o&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=i}}let Im=0,Lm=null;function Rm(e=document){if(Im++,Im===1){let t=e.body,n=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Lm={originalOverflow:t.style.overflow,originalPosition:t.style.position,originalTop:t.style.top,originalWidth:t.style.width,scrollY:n},t.style.overflow=`hidden`,t.style.position=`fixed`,t.style.top=`-${n}px`,t.style.width=`100%`}let t=!1;return()=>{if(!t&&(t=!0,Im=Math.max(0,Im-1),Im===0&&Lm)){let t=e.body,n=e.defaultView??window;t.style.overflow=Lm.originalOverflow,t.style.position=Lm.originalPosition,t.style.top=Lm.originalTop,t.style.width=Lm.originalWidth,n.scrollTo(0,Lm.scrollY),Lm=null}}}go();const zm={side:`right`,width:`420px`,animate:!0,reveal:`resize`,maxHeight:`100dvh`},Bm=e=>(e?.launcher?.mountMode??`floating`)===`docked`,Vm=e=>(e?.launcher?.mountMode??`floating`)===`composer-bar`,Hm=e=>{let t=e?.launcher?.dock,n=fo(e).dockWidth?t?.width:ap(Mp(e),`components.panel.width`);return{side:t?.side??zm.side,width:n??zm.width,animate:t?.animate??zm.animate,reveal:t?.reveal??zm.reveal,maxHeight:t?.maxHeight??zm.maxHeight}};Y(),mn(),Yt();const Um=e=>e===`followUp`?`follow-up`:e,Wm=(e,t=0)=>{if(typeof e==`string`){let t=e.trim();return t?{id:t,label:t,prompt:t,emphasis:`default`}:null}let n=e.label.trim();if(!n)return null;let r=e.prompt?.trim()||n;return{id:e.id?.trim()||r||`suggestion-${t}`,label:n,prompt:r,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??`default`}},Gm=/* @__PURE__ */ new WeakSet,Km=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,qm=e=>{Km()||e.forEach((e,t)=>{typeof e.animate==`function`&&e.animate([{opacity:`0`,transform:`translateY(4px)`},{opacity:`1`,transform:`none`}],{duration:250,delay:t*60,easing:`ease-out`,fill:`backwards`})})},Jm=e=>{let{item:t,index:n,surface:r,source:i,variant:a,streaming:o,config:c,plugins:l,chipsConfig:u,session:d,getTextarea:f,eventTarget:p,submitPrompt:m}=e,h=r===`followUp`,g=t.behavior,_=()=>{if(d.isStreaming())return;let e={suggestion:{...t},surface:r,source:i,behavior:g},n=p.dispatchEvent(new CustomEvent(`persona:suggestion:selected`,{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(h&&p.dispatchEvent(new CustomEvent(`persona:suggestReplies:selected`,{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!n)return;for(let e of l)if(e.onSuggestionSelect?.({suggestion:{...t},surface:r,source:i,variant:a,config:c})===!1)return;let o=f();g===`fill`?(o.value=t.prompt,o.dispatchEvent(new Event(`input`,{bubbles:!0,composed:!0})),o.focus()):m?m(t.prompt):(o.value=``,d.sendMessage(t.prompt))},v=()=>{let e=q(`button`,`persona-suggestion persona-suggestion--${a}`);if(e.type=`button`,e.disabled=o,e.dataset.suggestionId=t.id,e.dataset.emphasis=t.emphasis,e.dataset.behavior=g,a===`chip`&&(u?.fontWeight&&(e.style.fontWeight=u.fontWeight),u?.paddingX&&(e.style.paddingLeft=u.paddingX,e.style.paddingRight=u.paddingX),u?.paddingY&&(e.style.paddingTop=u.paddingY,e.style.paddingBottom=u.paddingY)),t.icon){let n=K(t.icon,`var(--persona-suggestion-icon-size)`,`currentColor`,1.8);n&&(n.classList.add(`persona-suggestion__icon`),t.iconColor&&(n.style.color=t.iconColor),e.appendChild(n))}let n=q(`span`,`persona-suggestion__copy`);if(n.appendChild(J(`span`,{className:`persona-suggestion__label`,text:t.label})),t.description&&a!==`chip`&&n.appendChild(J(`span`,{className:`persona-suggestion__description`,text:t.description})),e.appendChild(n),a!==`chip`){let t=Jt(s,16,`currentColor`,1.8);t&&(t.classList.add(`persona-suggestion__arrow`),e.appendChild(t))}return e.addEventListener(`click`,_),e},y=null;for(let e of l)if(e.renderSuggestion&&(y=e.renderSuggestion({suggestion:{...t},index:n,surface:r,source:i,variant:a,streaming:o,config:c,defaultRenderer:v,select:_}),y))break;return y??=v(),y.dataset.suggestionId||=t.id,y.dataset.behavior||=g,y.dataset.emphasis||=t.emphasis,y instanceof HTMLButtonElement||y.setAttribute(`aria-disabled`,o?`true`:`false`),y},Ym=e=>{let t=[],n=[],r=null,i=null,a=()=>{e.removeAttribute(`data-scroll-left`),e.removeAttribute(`data-scroll-right`)},o=()=>{if(i=null,e.hidden||e.dataset.variant!==`chip`||e.dataset.overflow!==`scroll`){a();return}let t=Math.max(0,e.scrollWidth-e.clientWidth);if(t<=1){a();return}let n=getComputedStyle(e).direction===`rtl`,r=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),o=r<=4,s=r>=t-4,c=n?!s:!o,l=n?!o:!s;e.toggleAttribute(`data-scroll-left`,c),e.toggleAttribute(`data-scroll-right`,l)},s=()=>{i!==null||typeof requestAnimationFrame!=`function`?typeof requestAnimationFrame!=`function`&&o():i=requestAnimationFrame(o)};e.addEventListener(`scroll`,s,{passive:!0});let c=typeof ResizeObserver==`function`?new ResizeObserver(s):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener(`scroll`,s),c?.disconnect(),i!==null&&typeof cancelAnimationFrame==`function`&&cancelAnimationFrame(i),i=null},render:(i,c,l,u,d,f)=>{e.replaceChildren(),t.length=0,n.length=0;let p=f?.source??`config`,m=f?.surface??(p===`config`?`starter`:`followUp`),h=m===`followUp`,g=f?.variant??`chip`,_=f?.behavior??`send`,v=f?.overflow??`wrap`,y=f?.config??{},b=f?.plugins??[],x=typeof f?.maxItems==`number`?Math.max(0,Math.floor(f.maxItems)):void 0,S=h?`followUps`:`starters`;!Gm.has(y)&&y.debug===!0&&g!==`chip`&&y.suggestions?.[S]?.overflow!==void 0&&(Gm.add(y),console.info(`[persona] suggestions.${S}.overflow applies to the "chip" variant only; the "${g}" variant manages its own stacking.`));let C=e=>e.map(Wm).filter(e=>e!==null).map(e=>({...e,behavior:e.behavior??_})),w=C(i??[]);b.forEach(e=>{e.transformSuggestions&&(w=C(e.transformSuggestions({suggestions:w.map(e=>({...e})),surface:m,source:p,config:y})))});let T=x===void 0?w:w.slice(0,x);if(!T.length){e.hidden=!0,r=null,a();return}if(!h&&(u??c.getMessages()).some(e=>e.role===`user`)){e.hidden=!0,r=null;return}e.hidden=!1,e.classList.add(`persona-suggestions`),e.dataset.personaSuggestionSurface=Um(m),e.dataset.variant=g,e.dataset.overflow=v;let E=document.createDocumentFragment(),D=c.isStreaming();T.forEach((r,i)=>{let a=Jm({item:r,index:i,surface:m,source:p,variant:g,streaming:D,config:y,plugins:b,chipsConfig:d,session:c,getTextarea:()=>l,eventTarget:e,submitPrompt:f?.submitPrompt});E.appendChild(a),n.push(a),[...a instanceof HTMLButtonElement?[a]:[],...Array.from(a.querySelectorAll(`button`))].forEach(e=>{t.includes(e)||(e.disabled=D,t.push(e))})}),e.appendChild(E),o(),s();let O=JSON.stringify({normalized:T,surface:m,variant:g,source:p});O!==r&&(r=O,qm(n),e.dispatchEvent(new CustomEvent(`persona:suggestion:shown`,{detail:{suggestions:T.map(e=>({...e})),surface:m,source:p,variant:g},bubbles:!0,composed:!0})),h&&e.dispatchEvent(new CustomEvent(`persona:suggestReplies:shown`,{detail:{suggestions:T.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},Xm={"bottom-right":`persona-bottom-6 persona-right-6`,"bottom-left":`persona-bottom-6 persona-left-6`,"top-right":`persona-top-6 persona-right-6`,"top-left":`persona-top-6 persona-left-6`};Y(),mn(),Ua();const Zm={x:[1.4,1.05]},Qm=`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`,$m=(e,t,n={})=>{let{iconSize:r,iconText:i}=n,[a,o]=Zm[t]??[1,1.5],s=!r;e.classList.toggle(`persona-header-control--glyph`,s),e.classList.toggle(`persona-header-control--sparse`,s&&a!==1);let c=K(t,`${Math.round((parseFloat(r??``)||20)*a)}px`,`currentColor`,o);c?(c.style.display=`block`,s||(c.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((o/1.5).toFixed(4))})`),e.replaceChildren(c)):i&&(e.textContent=i)},eh=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:r,iconName:i,iconText:a,wrapperClassName:o=Qm,size:s,iconSize:c,color:l,backgroundColor:u,borderWidth:d,borderColor:f,borderRadius:p,paddingX:m,paddingY:h,hidden:g,extraClassName:_,attrs:v}=e,y=q(`div`,o),b=!!(d||f),x=J(`button`,{className:tr(`persona-header-control`,`persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer`,!u&&`persona-bg-transparent hover:persona-bg-gray-100`,!b&&`persona-border-none`,!p&&`persona-rounded-full`,_),attrs:{type:`button`,"aria-label":t,...v},style:{width:s,height:s,minWidth:s,minHeight:s,display:g?`none`:void 0,color:l||rh.actionIconColor,backgroundColor:u,border:b?`${d||`0px`} solid ${f||`transparent`}`:void 0,borderRadius:p,paddingLeft:m,paddingRight:m,paddingTop:h,paddingBottom:h}});return i?$m(x,i,{iconSize:c,iconText:a}):a&&(x.textContent=a),y.appendChild(x),Ea({anchor:x,trigger:y,text:()=>x.getAttribute(`aria-label`)??t,hint:r,enabled:n}),{button:x,wrapper:y}},th=(e,t={})=>{let{showClose:n=!0,wrapperClassName:r=Qm,buttonSize:i,iconSize:a}=t,o=e?.launcher??{},s=o.closeButtonTooltipText??`Close chat`,c=o.closeButtonShowTooltip??!0,{button:l,wrapper:u}=eh({ariaLabel:s,tooltip:c,iconName:o.closeButtonIconName??`x`,iconText:o.closeButtonIconText??`×`,wrapperClassName:r,size:i??o.closeButtonSize,iconSize:a,color:o.closeButtonColor,backgroundColor:o.closeButtonBackgroundColor,borderWidth:o.closeButtonBorderWidth,borderColor:o.closeButtonBorderColor,borderRadius:o.closeButtonBorderRadius,paddingX:o.closeButtonPaddingX,paddingY:o.closeButtonPaddingY,hidden:!n});return{button:l,wrapper:u}},nh=(e,t={})=>{let{wrapperClassName:n=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,buttonSize:r,iconSize:i}=t,a=(e?.launcher??{}).clearChat??{},o=a.tooltipText??`Clear chat`,s=a.showTooltip??!0,{button:c,wrapper:l}=eh({ariaLabel:o,tooltip:s,iconName:a.iconName??`refresh-cw`,wrapperClassName:n,size:r??a.size,iconSize:i,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:c,wrapper:l}};Y(),mn(),No();const rh={titleColor:`var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))`,subtitleColor:`var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))`,actionIconColor:`var(--persona-header-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))`,minHeight:`var(--persona-header-min-height, auto)`},ih={fontFamily:`var(--persona-components-header-title-fontFamily, inherit)`,fontSize:`var(--persona-components-header-title-fontSize, 1rem)`,fontWeight:`var(--persona-components-header-title-fontWeight, 600)`,lineHeight:`var(--persona-components-header-title-lineHeight, 1.5rem)`,letterSpacing:`var(--persona-components-header-title-letterSpacing, normal)`},ah={fontFamily:`var(--persona-components-header-subtitle-fontFamily, inherit)`,fontSize:`var(--persona-components-header-subtitle-fontSize, 0.75rem)`,fontWeight:`var(--persona-components-header-subtitle-fontWeight, inherit)`,lineHeight:`var(--persona-components-header-subtitle-lineHeight, 1rem)`,letterSpacing:`var(--persona-components-header-subtitle-letterSpacing, normal)`},oh=e=>{let{config:t,showClose:n=!0}=e,r=J(`div`,{className:`persona-widget-header persona-flex persona-items-center persona-gap-3`,attrs:{"data-persona-theme-zone":`header`},style:{padding:`var(--persona-components-header-padding, 20px 24px)`,minHeight:rh.minHeight,backgroundColor:`var(--persona-header-bg, var(--persona-surface, #ffffff))`,borderBottomColor:`var(--persona-header-border, var(--persona-divider, #f1f5f9))`,boxShadow:`var(--persona-header-shadow, none)`,borderBottom:`var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))`}}),i=t?.launcher??{},a=i.headerIconSize??`40px`,o=i.closeButtonPlacement??`inline`,s=i.headerIconHidden??!1,c=i.headerIconName,l=J(`div`,{className:`persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl`,style:{height:a,width:a,backgroundColor:`var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))`,color:`var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))`}});if(!s){if(c){let e=parseFloat(a)||24,n=K(c,e*.6,`currentColor`,1);n?(n.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,n.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,l.replaceChildren(n)):l.textContent=t?.launcher?.agentIconText??`💬`}else if(t?.launcher?.iconUrl){let e=q(`img`);e.src=t.launcher.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=a,e.style.width=a,l.replaceChildren(e)}else l.textContent=t?.launcher?.agentIconText??`💬`}let u=q(`div`,`persona-flex persona-flex-col persona-flex-1 persona-min-w-0`),d=J(`span`,{className:`persona-text-base persona-font-semibold`,text:t?.launcher?.title??`Chat Assistant`,style:{color:rh.titleColor,...ih}}),f=J(`span`,{className:`persona-text-xs`,text:t?.launcher?.subtitle??`Here to help you get answers fast`,style:{color:rh.subtitleColor,...ah}});u.append(d,f),s?r.append(u):r.append(l,u);let p=i.clearChat??{},m=p.enabled??!0,h=p.placement??`inline`,g=null,_=null;if(m){let e=nh(t,{wrapperClassName:h===`top-right`?`persona-absolute persona-top-4 persona-z-50`:`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`});g=e.button,_=e.wrapper,h===`top-right`&&(_.style.right=`48px`),h===`inline`&&r.appendChild(_)}let{button:v,wrapper:y}=th(t,{showClose:n,wrapperClassName:o===`top-right`?`persona-absolute persona-top-4 persona-right-4 persona-z-50`:m&&h===`inline`?`persona-relative persona-inline-flex persona-items-center persona-justify-center`:`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`});return o!==`top-right`&&r.appendChild(y),{header:r,iconHolder:l,headerTitle:d,headerSubtitle:f,closeButton:v,closeButtonWrapper:y,clearChatButton:g,clearChatButtonWrapper:_}},sh=(e,t,n)=>{let r=n?.launcher??{},i=r.closeButtonPlacement??`inline`,a=r.clearChat?.placement??`inline`;e.appendChild(t.header),i===`top-right`&&(e.style.position=`relative`,e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a===`top-right`&&(e.style.position=`relative`,e.appendChild(t.clearChatButtonWrapper))};Y(),mn(),yi();function ch(e){let{items:t,onSelect:n,anchor:r,position:i=`bottom-left`,portal:a,onOpenChange:o}=e,s=q(`div`,`persona-dropdown-menu persona-hidden`);s.setAttribute(`role`,`menu`),s.setAttribute(`data-persona-theme-zone`,`dropdown`),a?(s.style.position=`fixed`,s.style.zIndex=String(vi)):(s.style.position=`absolute`,s.style.top=`100%`,s.style.marginTop=`4px`,i===`bottom-right`?s.style.right=`0`:s.style.left=`0`);for(let e of t){if(e.dividerBefore){let e=document.createElement(`hr`);s.appendChild(e)}let t=document.createElement(`button`);if(t.type=`button`,t.setAttribute(`role`,`menuitem`),t.setAttribute(`data-dropdown-item-id`,e.id),e.destructive&&t.setAttribute(`data-destructive`,``),e.icon){let n=K(e.icon,16,`currentColor`,1.5);n&&t.appendChild(n)}let r=document.createElement(`span`);r.textContent=e.label,t.appendChild(r),t.addEventListener(`click`,t=>{t.stopPropagation(),d(),n(e.id)}),s.appendChild(t)}let c=null;function l(){if(!a)return;let e=r.getBoundingClientRect();s.style.top=`${e.bottom+4}px`,i===`bottom-right`?(s.style.right=`${window.innerWidth-e.right}px`,s.style.left=`auto`):(s.style.left=`${e.left}px`,s.style.right=`auto`)}function u(){let e=s.classList.contains(`persona-hidden`);l(),s.classList.remove(`persona-hidden`),e&&o?.(!0),requestAnimationFrame(()=>{let e=e=>{!s.contains(e.target)&&!r.contains(e.target)&&d()};document.addEventListener(`click`,e,!0),c=()=>document.removeEventListener(`click`,e,!0)})}function d(){let e=!s.classList.contains(`persona-hidden`);s.classList.add(`persona-hidden`),c?.(),c=null,e&&o?.(!1)}function f(){s.classList.contains(`persona-hidden`)?u():d()}function p(){d(),s.remove()}return a&&a.appendChild(s),{element:s,show:u,hide:d,toggle:f,destroy:p}}Y(),mn();function lh(e){let{icon:t,label:n,size:r,strokeWidth:i,className:a,chromeless:o,onClick:s,aria:c}=e,l=q(`button`,tr(!o&&`persona-icon-btn`,a));l.type=`button`,l.setAttribute(`aria-label`,n),l.title=n;let u=K(t,r??16,`currentColor`,i??2);if(u&&l.appendChild(u),s&&l.addEventListener(`click`,s),c)for(let[e,t]of Object.entries(c))l.setAttribute(e,t);return l}function uh(e){let{icon:t,label:n,variant:r=`default`,size:i=`sm`,iconSize:a,className:o,onClick:s,aria:c}=e,l=`persona-label-btn`;r!=="default"&&(l+=` persona-label-btn--`+r),l+=` persona-label-btn--`+i,o&&(l+=` `+o);let u=q(`button`,l);if(u.type=`button`,u.setAttribute(`aria-label`,n),t){let e=K(t,a??14,`currentColor`,2);e&&u.appendChild(e)}let d=q(`span`);if(d.textContent=n,u.appendChild(d),s&&u.addEventListener(`click`,s),c)for(let[e,t]of Object.entries(c))u.setAttribute(e,t);return u}function dh(e){let{items:t,selectedId:n,onSelect:r,className:i}=e,a=q(`div`,`persona-toggle-group`+(i?` `+i:``));a.setAttribute(`role`,`group`);let o=n,s=[];function c(){for(let e of s)e.btn.setAttribute(`aria-pressed`,e.id===o?`true`:`false`)}for(let e of t){let t;e.icon?t=lh({icon:e.icon,label:e.label,className:e.className,onClick:()=>{o=e.id,c(),r(e.id)}}):(t=q(`button`,`persona-icon-btn`+(e.className?` `+e.className:``)),t.type=`button`,t.setAttribute(`aria-label`,e.label),t.title=e.label,t.textContent=e.label,t.addEventListener(`click`,()=>{o=e.id,c(),r(e.id)})),t.setAttribute(`aria-pressed`,e.id===o?`true`:`false`),s.push({id:e.id,btn:t}),a.appendChild(t)}function l(e){o=e,c()}return{element:a,setSelected:l}}function fh(e){let{label:t,icon:n,iconSize:r,iconOnly:i,menuItems:a,onSelect:o,onPrimary:s,position:c=`bottom-left`,portal:l,chevronLabel:u=`More options`,chevronIconSize:d,className:f,primaryClassName:p,chevronClassName:m}=e,h=q(`div`,`persona-split-btn`+(f?` `+f:``)),g={label:t,className:`persona-split-btn-primary`+(p?` `+p:``),onClick:s},_=i&&n?lh({...g,icon:n,size:r??14}):uh({...g,icon:n,iconSize:r??14}),v=lh({icon:`chevron-down`,label:u,size:d??14,className:`persona-split-btn-chevron`+(m?` `+m:``),aria:{"aria-haspopup":`true`,"aria-expanded":`false`}});h.append(_,v);let y=null,b=()=>{if(y)return y;let e=(typeof l==`function`?l():l)??void 0;return y=ch({items:a,onSelect:o,anchor:h,position:c,portal:e,onOpenChange:e=>{v.setAttribute(`aria-expanded`,e?`true`:`false`)}}),e||h.appendChild(y.element),y};return h.isConnected?b():requestAnimationFrame(()=>{y||b()}),v.addEventListener(`click`,e=>{e.stopPropagation(),b().toggle()}),{element:h,primaryButton:_,chevronButton:v,openMenu:()=>b().show(),closeMenu:()=>y?.hide(),toggleMenu:()=>b().toggle(),destroy:()=>{y?.destroy(),h.remove()}}}function ph(e){let{label:t,icon:n=`chevron-down`,menuItems:r,onSelect:i,position:a=`bottom-left`,portal:o,className:s,hover:c}=e,l=q(`div`,`persona-combo-btn`+(s?` `+s:``));l.style.position=`relative`,l.style.display=`inline-flex`,l.style.alignItems=`center`,l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`),l.setAttribute(`aria-haspopup`,`true`),l.setAttribute(`aria-expanded`,`false`),l.setAttribute(`aria-label`,t);let u=q(`span`,`persona-combo-btn-label`);u.textContent=t,l.appendChild(u);let d=K(n,14,`currentColor`,2);d&&(d.style.marginLeft=`4px`,d.style.opacity=`0.6`,l.appendChild(d)),c&&(l.style.borderRadius=c.borderRadius??`10px`,l.style.padding=c.padding??`6px 4px 6px 12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=c.background??``,l.style.borderColor=c.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}));let f=ch({items:r,onSelect:e=>{l.setAttribute(`aria-expanded`,`false`),i(e)},anchor:l,position:a,portal:o});o||l.appendChild(f.element);let p=()=>l.getAttribute(`data-persona-menu-locked`)===`true`;return l.addEventListener(`click`,e=>{if(e.stopPropagation(),p())return;let t=!f.element.classList.contains(`persona-hidden`);l.setAttribute(`aria-expanded`,t?`false`:`true`),f.toggle()}),l.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),l.click())}),{element:l,setLabel:e=>{u.textContent=e,l.setAttribute(`aria-label`,e)},open:()=>{l.setAttribute(`aria-expanded`,`true`),f.show()},close:()=>{l.setAttribute(`aria-expanded`,`false`),f.hide()},toggle:()=>{let e=!f.element.classList.contains(`persona-hidden`);l.setAttribute(`aria-expanded`,e?`false`:`true`),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}Y(),zc();const mh=e=>{let t=oh({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let e=t.headerTitle.parentElement;e&&(e.style.cursor=`pointer`,e.setAttribute(`role`,`button`),e.setAttribute(`tabindex`,`0`),e.addEventListener(`click`,()=>n()),e.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n())}))}return t};function hh(e,t,n){if(t?.length)for(let r of t){let{button:t,wrapper:i}=eh({ariaLabel:r.ariaLabel??r.label??r.id,iconName:r.icon,iconText:r.icon?void 0:r.label,tooltipHint:r.shortcut?Pc(r.shortcut):void 0,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`});if(t.setAttribute(`data-persona-header-action`,r.id),r.shortcut){let e=Fc(r.shortcut);e&&t.setAttribute(`aria-keyshortcuts`,e)}if(r.menuItems?.length){let e=ch({items:r.menuItems,onSelect:e=>n?.(e),anchor:i,position:`bottom-right`});i.appendChild(e.element),t.addEventListener(`click`,t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener(`click`,()=>n?.(r.id));e.appendChild(i)}}const gh=e=>{let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:i,onHeaderAction:a}=e,o=t?.launcher??{},s=q(`div`,`persona-flex persona-items-center persona-justify-between`);s.setAttribute(`data-persona-theme-zone`,`header`),s.style.minHeight=rh.minHeight,s.style.padding=`var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))`,s.style.backgroundColor=`var(--persona-header-bg, var(--persona-surface, #ffffff))`,s.style.borderBottomColor=`var(--persona-header-border, var(--persona-divider, #f1f5f9))`,s.style.boxShadow=`var(--persona-header-shadow, none)`,s.style.borderBottom=`var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))`;let c=i?.titleMenu,l,u;if(c){let e=ph({label:o.title??`Chat Assistant`,menuItems:c.menuItems,onSelect:t=>{let n=n=>{n===!1&&e.element.dispatchEvent(new CustomEvent(`persona:title-menu-builtin`,{bubbles:!0,composed:!0,detail:{actionId:t}}))},r=c.onSelect(t);r instanceof Promise?r.then(n,()=>{}):n(r)},hover:c.hover,className:``});l=e.element,l.style.color=rh.titleColor,u=l.querySelector(`.persona-combo-btn-label`)??l}else{if(l=q(`div`,`persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1`),u=q(`span`,`persona-text-base persona-font-semibold persona-truncate`),u.style.color=rh.titleColor,Object.assign(u.style,ih),u.textContent=o.title??`Chat Assistant`,l.appendChild(u),i?.onTitleClick){l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`);let e=i.onTitleClick;l.addEventListener(`click`,t=>{t.target.closest(`button`)||e()}),l.addEventListener(`keydown`,t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e())})}let e=i?.titleRowHover;e&&(l.style.borderRadius=e.borderRadius??`10px`,l.style.padding=e.padding??`6px 4px 6px 12px`,l.style.margin=`-6px 0 -6px -12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.style.width=`fit-content`,l.style.flex=`none`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=e.background??``,l.style.borderColor=e.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}))}s.appendChild(l);let d=`persona-relative persona-inline-flex persona-items-center persona-justify-center`,{button:f,wrapper:p}=th(t,{showClose:n,wrapperClassName:d});r&&f.addEventListener(`click`,r);let m=q(`div`,`persona-flex persona-items-center persona-gap-1`);c||hh(m,i?.trailingActions,i?.onAction??a);let h=o.clearChat??{},g=null,_=null;if(h.enabled??!0){let e=h.placement??`inline`,n=nh(t,{wrapperClassName:e===`top-right`?`persona-absolute persona-top-4 persona-z-50`:d});g=n.button,_=n.wrapper,e===`top-right`?_.style.right=`48px`:m.appendChild(_)}m.appendChild(p),s.appendChild(m);let v=q(`div`);v.style.display=`none`;let y=q(`span`);return y.style.display=`none`,{header:s,iconHolder:v,headerTitle:u,headerSubtitle:y,closeButton:f,closeButtonWrapper:p,clearChatButton:g,clearChatButtonWrapper:_}},_h={default:mh,minimal:gh},vh=e=>_h[e]??_h.default,yh=(e,t,n)=>{if(t?.render){let r=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=q(`div`);i.style.display=`none`;let a=q(`span`),o=q(`span`),s=q(`button`);s.style.display=`none`;let c=q(`div`);return c.style.display=`none`,{header:r,iconHolder:i,headerTitle:a,headerSubtitle:o,closeButton:s,closeButtonWrapper:c,clearChatButton:null,clearChatButtonWrapper:null}}let r=t?.layout??`default`,i=vh(r)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(i.iconHolder.style.display=`none`),t.showTitle===!1&&(i.headerTitle.style.display=`none`),t.showSubtitle===!1&&(i.headerSubtitle.style.display=`none`),t.showCloseButton===!1&&(i.closeButton.style.display=`none`),t.showClearChat===!1&&i.clearChatButtonWrapper&&(i.clearChatButtonWrapper.style.display=`none`)),i};Y(),xs();const bh=e=>{let{config:t}=e,n=J(`div`,{className:`persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4`,attrs:{"data-persona-theme-zone":`composer`}}),r=bs(),i=J(`form`,{className:`persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3`,attrs:{"data-persona-composer-form":``}}),{textarea:a,attachAutoResize:o}=ms(t);o();let s=gs(t),c=_s(t),l=vs(t),u=ys(t),d=J(`div`,{className:`persona-widget-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});i.append(d),l&&(l.previewsContainer.style.gap=`8px`,d.append(l.previewsContainer),i.append(l.input)),i.append(a);let f=J(`div`,{className:`persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full`,attrs:{"data-persona-composer-actions":``}}),p=J(`div`,{className:`persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-start":``}}),m=J(`div`,{className:`persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-end":``}});return l&&p.append(l.wrapper),c&&m.append(c.wrapper),m.append(s.wrapper),f.append(p,m),i.append(f),i.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),t?.statusIndicator?.mode===`transient`?n.append(r,u,i):n.append(r,i,u),{footer:n,suggestions:r,composerForm:i,header:d,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:u,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:f,leftActions:p,rightActions:m,setSendButtonMode:s.setMode}};Y(),Yt(),xs(),us();const xh=()=>{let e=J(`button`,{className:`persona-pill-peek`,attrs:{type:`button`,"data-persona-pill-peek":``,"aria-label":`Show conversation`,tabindex:`-1`}}),t=q(`span`,`persona-pill-peek__icon`),n=Jt(Le,16,`currentColor`,1.5);n&&t.appendChild(n);let r=q(`span`,`persona-pill-peek__text`),i=q(`span`,`persona-pill-peek__caret`),a=Jt(w,16,`currentColor`,1.5);return a&&i.appendChild(a),e.append(t,r,i),{root:e,textNode:r}},Sh=e=>{let{config:t}=e,n=J(`div`,{className:`persona-widget-footer persona-widget-footer--pill`,attrs:{"data-persona-theme-zone":`composer`}}),r=bs(),i=ys(t);i.style.display=`none`;let{textarea:a,attachAutoResize:o}=ms(t,{defaultMaxLines:5});o();let s=gs(t),c=_s(t),l=vs(t);l&&l.previewsContainer.classList.add(`persona-pill-composer__previews`);let u=J(`form`,{className:`persona-widget-composer persona-pill-composer`,attrs:{"data-persona-composer-form":``}}),d=J(`div`,{className:`persona-widget-composer__left-actions persona-pill-composer__left`,attrs:{"data-persona-composer-actions-start":``}});l&&d.append(l.wrapper);let f=J(`div`,{className:`persona-widget-composer__right-actions persona-pill-composer__right`,attrs:{"data-persona-composer-actions-end":``}});c&&f.append(c.wrapper),f.append(s.wrapper),u.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),l&&u.append(l.input),u.append(d,a,f);let p=J(`div`,{className:`persona-pill-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});n.append(p),l&&p.append(l.previewsContainer),n.append(r,u,i);let m=u;return{footer:n,suggestions:r,composerForm:u,header:p,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:i,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:m,leftActions:d,rightActions:f,setSendButtonMode:s.setMode}};Y(),Ns(),mn(),$o();const Ch=e=>{switch(e){case`max_tool_calls`:return`Stopped after calling a tool. Send a follow-up to continue.`;case`length`:return`Response cut off as max tokens reached. Ask for more to continue.`;case`content_filter`:return`The provider filtered this response.`;case`error`:return`Something went wrong generating this response.`;default:return null}},wh=(e,t)=>{if(!e)return null;let n=Ch(e);if(n===null)return null;let r=t?.[e];return(r===void 0?n:r)||null},Th=(e,t)=>{let n=q(`div`,`persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic`);return n.setAttribute(`data-stop-reason`,e),n.setAttribute(`role`,`note`),n.style.opacity=`0.75`,n.textContent=t,n},Eh=e=>{let t=e.toLowerCase();return!t.startsWith(`data:image/svg+xml`)&&!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:image/`)||!e.includes(`:`))},Dh=e=>{let t=e.toLowerCase();return t.startsWith(`javascript:`)||t.startsWith(`data:text/html`)||t.startsWith(`data:text/javascript`)||t.startsWith(`data:text/xml`)||t.startsWith(`data:application/xhtml`)||t.startsWith(`data:image/svg+xml`)?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:`)||!e.includes(`:`))},Oh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`image`&&typeof e.image==`string`&&e.image.trim().length>0),kh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`audio`&&typeof e.audio==`string`&&e.audio.trim().length>0),Ah=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`video`&&typeof e.video==`string`&&e.video.trim().length>0),jh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`file`&&typeof e.data==`string`&&e.data.trim().length>0),Mh=e=>{if(!e||e.length===0)return null;let t=J(`div`,{className:`persona-mention-context-row persona-message-mentions`,attrs:{"data-message-mentions":``}});t.style.display=`flex`;for(let n of e){let e=J(`div`,{className:`persona-mention-chip persona-mention-chip-readonly`,attrs:{"data-status":`ready`,title:n.label}}),r=q(`span`,`persona-mention-chip-icon`),i=K(n.iconName??`at-sign`,13,`currentColor`,2);i&&r.appendChild(i),e.appendChild(r),e.appendChild(J(`span`,{className:`persona-mention-chip-label`,text:n.label})),t.appendChild(e)}return t},Nh=(e,t)=>{let n=document.createDocumentFragment();for(let r of e)r.kind===`text`?n.appendChild(document.createTextNode(r.text)):n.appendChild(Ms(r.ref,{readonly:!0,render:t}));return n},Ph=(e,t,n,r)=>{let i=Math.random().toString(36).slice(2,8),a=e=>`${i}:${e}`,o=n(t.map((e,t)=>e.kind===`text`?e.text:a(t)).join(``));if(!t.every((e,t)=>e.kind===`text`||o.includes(a(t)))){e.replaceChildren(Nh(t,r));return}e.innerHTML=o;let s=RegExp(`${i}:(\\d+)`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),l=[];for(let e=c.nextNode();e;e=c.nextNode())l.push(e);for(let e of l){let n=e;for(let e=s.exec(n.data);e;e=s.exec(n.data)){let i=t[Number(e[1])],a=n.splitText(e.index);a.data=a.data.slice(e[0].length),i?.kind===`mention`&&a.parentNode?.insertBefore(Ms(i.ref,{readonly:!0,render:r}),a),n=a}}},Fh=(e,t,n)=>{if(e.length===0)return null;try{let r=q(`div`,`persona-flex persona-flex-col persona-gap-2`);r.setAttribute(`data-message-attachments`,`images`),t&&(r.style.marginBottom=`8px`);let i=0,a=!1,o=()=>{a||(a=!0,r.remove(),n?.())};return e.forEach((e,t)=>{let n=q(`img`);n.alt=e.alt?.trim()||`Attached image ${t+1}`,n.loading=`lazy`,n.decoding=`async`,n.referrerPolicy=`no-referrer`,n.style.display=`block`,n.style.width=`100%`,n.style.maxWidth=`320px`,n.style.maxHeight=`320px`,n.style.height=`auto`,n.style.objectFit=`contain`,n.style.borderRadius=`10px`,n.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,n.style.border=`1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))`;let a=!1;i+=1,n.addEventListener(`error`,()=>{a||(a=!0,i=Math.max(0,i-1),n.remove(),i===0&&o())}),n.addEventListener(`load`,()=>{a=!0}),Eh(e.image)?(n.src=e.image,r.appendChild(n)):(a=!0,i=Math.max(0,i-1),n.remove())}),i===0?(o(),null):r}catch{return n?.(),null}},Ih=e=>{if(e.length===0)return null;try{let t=q(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`audio`);let n=0;return e.forEach(e=>{if(!Dh(e.audio))return;let r=q(`audio`);r.controls=!0,r.preload=`metadata`,r.src=e.audio,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Lh=e=>{if(e.length===0)return null;try{let t=q(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`video`);let n=0;return e.forEach(e=>{if(!Dh(e.video))return;let r=q(`video`);r.controls=!0,r.preload=`metadata`,r.src=e.video,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,r.style.maxHeight=`320px`,r.style.borderRadius=`10px`,r.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Rh=e=>{if(e.length===0)return null;try{let t=q(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`files`);let n=0;return e.forEach(e=>{if(!Dh(e.data))return;let r=q(`a`);r.href=e.data,r.download=e.filename,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=e.filename,r.className=`persona-message-file-attachment`,r.style.display=`inline-flex`,r.style.alignItems=`center`,r.style.gap=`6px`,r.style.padding=`6px 10px`,r.style.borderRadius=`8px`,r.style.fontSize=`0.875rem`,r.style.textDecoration=`underline`,r.style.backgroundColor=`var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))`,r.style.border=`1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))`,r.style.color=`inherit`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},zh=()=>{let e=document.createElement(`div`);e.className=`persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2`;let t=document.createElement(`div`);t.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,t.style.backgroundColor=`currentColor`,t.style.opacity=`0.4`,t.style.animationDelay=`0ms`;let n=document.createElement(`div`);n.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,n.style.backgroundColor=`currentColor`,n.style.opacity=`0.4`,n.style.animationDelay=`250ms`;let r=document.createElement(`div`);r.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,r.style.backgroundColor=`currentColor`,r.style.opacity=`0.4`,r.style.animationDelay=`500ms`;let i=document.createElement(`span`);return i.className=`persona-sr-only`,i.textContent=`Loading`,e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(i),e},Bh=(e,t,n)=>{let r={config:n??{},streaming:!0,location:e,defaultRenderer:zh};if(t){let e=t(r);if(e!==null)return e}return zh()},Vh=(e,t)=>{let n=q(`div`,`persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm`),r=t===`user`?e.userAvatar:e.assistantAvatar;if(r){if(r.startsWith(`http`)||r.startsWith(`/`)||r.startsWith(`data:`)){let e=q(`img`);e.src=r,e.alt=t===`user`?`User`:`Assistant`,e.className=`persona-w-full persona-h-full persona-rounded-full persona-object-cover`,n.appendChild(e)}else n.textContent=r,n.classList.add(t===`user`?`persona-bg-persona-accent`:`persona-bg-persona-primary`,`persona-text-white`)}else n.textContent=t===`user`?`U`:`A`,n.classList.add(t===`user`?`persona-bg-persona-accent`:`persona-bg-persona-primary`,`persona-text-white`);return n},Hh=(e,t,n=`div`)=>{let r=q(n,`persona-text-xs persona-text-persona-muted`),i=new Date(e.createdAt);return r.textContent=t.format?t.format(i):i.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`}),r},Uh=(e,t=`bubble`)=>{let n=[`persona-message-bubble`];switch(t){case`flat`:e===`user`?n.push(`persona-message-user-bubble`,`persona-ml-auto`,`persona-text-persona-primary`,`persona-py-2`):n.push(`persona-message-assistant-bubble`,`persona-text-persona-text`,`persona-py-2`);break;case`minimal`:n.push(`persona-text-sm`,`persona-leading-relaxed`),e===`user`?n.push(`persona-message-user-bubble`,`persona-ml-auto`,`persona-bg-persona-accent`,`persona-text-white`,`persona-px-3`,`persona-py-2`,`persona-rounded-lg`):n.push(`persona-message-assistant-bubble`,`persona-bg-persona-container`,`persona-text-persona-text`,`persona-px-3`,`persona-py-2`,`persona-rounded-lg`);break;default:n.push(`persona-rounded-2xl`,`persona-text-sm`,`persona-leading-relaxed`,`persona-shadow-sm`),e===`user`?n.push(`persona-message-user-bubble`,`persona-ml-auto`,`persona-bg-persona-accent`,`persona-text-white`,`persona-px-5`,`persona-py-3`):n.push(`persona-message-assistant-bubble`,`persona-bg-persona-container`,`persona-border`,`persona-border-persona-message-border`,`persona-text-persona-text`,`persona-px-5`,`persona-py-3`)}return n},Wh={bubble:{padding:`0.75rem 1.25rem`,fontSize:`0.875rem`,lineHeight:`1.75`},minimal:{padding:`0.5rem 0.75rem`,fontSize:`0.875rem`,lineHeight:`1.75`},flat:{padding:`0.5rem 0`,fontSize:`inherit`,lineHeight:`inherit`}},Gh=(e,t,n=`bubble`,r)=>{if(!r)return;let i=t===`user`?`user`:`assistant`,a=Wh[n??`bubble`]??Wh.bubble;r.padding&&(e.style.padding=`var(--persona-message-${i}-padding, ${a.padding})`),r.fontSize&&(e.style.fontSize=`var(--persona-message-${i}-font-size, ${a.fontSize})`),r.lineHeight&&(e.style.lineHeight=`var(--persona-message-${i}-line-height, ${a.lineHeight})`),r.fontFamily&&(e.style.fontFamily=`var(--persona-message-${i}-font-family, inherit)`)},Kh=e=>`custom:${e}`,qh=(e,t)=>t!==`user`&&t!==`assistant`?[]:(e?.custom??[]).filter(e=>(e.roles??[`assistant`]).includes(t)),Jh=(e,t,n,r)=>{let i=t.showCopy??!0,a=t.showUpvote??!1,o=t.showDownvote??!1,s=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&r?.canRegenerate===!0,l=(t.showEdit??!1)&&r?.canEdit===!0,u=(t.showQuote??!1)&&r?.canQuote!==!1,d=qh(t,e.role);if(!i&&!a&&!o&&!s&&!c&&!l&&!u&&d.length===0){let t=q(`div`);return t.style.display=`none`,t.id=`actions-${e.id}`,t.setAttribute(`data-actions-for`,e.id),t}let f=t.visibility??`hover`,p=t.align??`right`,m=t.layout??`pill-inside`,h={left:`persona-message-actions-left`,center:`persona-message-actions-center`,right:`persona-message-actions-right`}[p],g={"pill-inside":`persona-message-actions-pill`,"row-inside":`persona-message-actions-row`}[m],_=q(`div`,`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${h} ${g} ${f===`hover`?`persona-message-actions-hover`:``}`);_.id=`actions-${e.id}`,_.setAttribute(`data-actions-for`,e.id);let v=(e,t,n)=>{let r=lh({icon:e,label:t,size:14,className:`persona-message-action-btn`,chromeless:!0});return r.setAttribute(`data-action`,n),r};i&&_.appendChild(v(`copy`,`Copy message`,`copy`)),s&&_.appendChild(v(`volume-2`,`Read aloud`,`read-aloud`)),a&&_.appendChild(v(`thumbs-up`,`Upvote`,`upvote`)),o&&_.appendChild(v(`thumbs-down`,`Downvote`,`downvote`)),c&&_.appendChild(v(`refresh-cw`,`Regenerate response`,`regenerate`)),l&&_.appendChild(v(`pencil`,`Edit message`,`edit`)),u&&_.appendChild(v(`quote`,`Quote message`,`quote`));for(let e of d)_.appendChild(v(e.iconName??`ellipsis`,e.label,Kh(e.id)));return _},Yh=(e,t,n,r,i,a)=>{let o=n??{},s=o.layout??`bubble`,c=o.avatar,l=o.timestamp,u=c?.show??!1,d=l?.show??!1,f=c?.position??`left`,p=l?.position??`below`,m=Uh(e.role,s),h=q(`div`,m.join(` `));h.id=`bubble-${e.id}`,h.setAttribute(`data-message-id`,e.id),h.setAttribute(`data-persona-theme-zone`,e.role===`user`?`user-message`:`assistant-message`);let g=ip(a?.widgetConfig?.future).components.message,_=a?.widgetConfig?.theme?.components?.message;Gh(h,e.role,s,e.role===`user`?{...g.user,..._?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...g.assistant,..._?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),s===`flat`?(h.style.backgroundColor=`transparent`,h.style.color=e.role===`user`?`var(--persona-primary, var(--persona-text))`:`var(--persona-message-assistant-text, var(--persona-text))`):e.role===`user`?(h.style.backgroundColor=`var(--persona-message-user-bg, var(--persona-accent))`,h.style.color=`var(--persona-message-user-text, white)`):e.role===`assistant`&&(h.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,h.style.color=`var(--persona-message-assistant-text, var(--persona-text))`);let v=Oh(e),y=e.content?.trim()??``,b=v.length>0&&y===`[Image]`,x=cm(a?.widgetConfig?.features?.streamAnimation),S=a?.widgetConfig?.features?.streamAnimation?.plugins,C=e.role===`assistant`&&x.type!==`none`?hm(x.type,S):null,w=e.role===`assistant`&&C?.isAnimating?.(e)===!0,T=e.role===`assistant`&&C!==null&&(!!e.streaming||w);T&&C?.bubbleClass&&h.classList.add(C.bubbleClass);let E=document.createElement(`div`);E.classList.add(`persona-message-content`),e.streaming&&E.classList.add(`persona-content-streaming`),T&&C&&(C.containerClass&&E.classList.add(C.containerClass),E.style.setProperty(`--persona-stream-step`,`${x.speed}ms`),E.style.setProperty(`--persona-stream-duration`,`${x.duration}ms`));let D=T?gm(e.content??``,x.buffer,C,e,!!e.streaming):e.content??``,O=()=>{let n=t({text:D,message:e,streaming:!!e.streaming,raw:e.rawContent});return T&&C?.wrap===`char`?Cm(n,`char`,e.id,{skipTags:C.skipTags}):T&&C?.wrap===`word`?Cm(n,`word`,e.id,{skipTags:C.skipTags}):n},k=null;if(b?(k=document.createElement(`div`),k.innerHTML=O(),k.style.display=`none`,E.appendChild(k)):e.contentSegments?.length?Ph(E,e.contentSegments,n=>t({text:n,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):E.innerHTML=O(),T&&C?.useCaret&&!b&&y){let e=wm(),t=E.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];if(n?.parentNode)n.parentNode.insertBefore(e,n.nextSibling);else{let t=E.lastElementChild;t?t.appendChild(e):E.appendChild(e)}}if(d&&p===`inline`&&e.createdAt){let t=Hh(e,l,`span`);t.classList.add(`persona-timestamp-inline`);let n=E.lastElementChild;n?n.appendChild(t):E.appendChild(t)}if(v.length>0){let e=Fh(v,!b&&!!y,()=>{b&&k&&(k.style.display=``)});e?h.appendChild(e):b&&k&&(k.style.display=``)}let ee=kh(e);if(ee.length>0){let e=Ih(ee);e&&h.appendChild(e)}let te=Ah(e);if(te.length>0){let e=Lh(te);e&&h.appendChild(e)}let ne=jh(e);if(ne.length>0){let e=Rh(ne);e&&h.appendChild(e)}let re=e.contentSegments?.length?null:Mh(e.contextMentions);if(re&&h.appendChild(re),h.appendChild(E),d&&p===`below`&&e.createdAt){let t=Hh(e,l);t.classList.add(`persona-mt-1`),h.appendChild(t)}let ie=e.role===`assistant`?wh(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role===`assistant`){let e=!!(D&&D.trim()),t=x.placeholder===`skeleton`,n=t&&x.buffer===`line`&&e;if(e)n&&h.appendChild(Tm());else if(t)h.appendChild(Tm());else{let e=Bh(`inline`,a?.loadingIndicatorRenderer,a?.widgetConfig);e&&h.appendChild(e)}}ie&&e.stopReason&&!e.streaming&&(y||(E.style.display=`none`),h.appendChild(Th(e.stopReason,ie)));let ae=e.role===`assistant`&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&r?.enabled!==!1,oe=a?.actionEligibility,A=e.role===`user`&&!e.streaming&&r?.enabled!==!1&&(r?.showEdit===!0&&oe?.canEdit===!0||r?.showQuote===!0&&oe?.canQuote===!0||qh(r,`user`).length>0);if((ae||A)&&r){let t=Jh(e,A?{...r,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:r,i,oe);h.appendChild(t)}if(!u||e.role===`system`)return h;let j=q(`div`,`persona-message-with-avatar persona-flex persona-gap-2 ${e.role===`user`?`persona-flex-row-reverse`:``}`),se=Vh(c,e.role);return f===`right`||f===`left`&&e.role===`user`?j.append(h,se):j.append(se,h),j},Xh=(e,t,n,r,i,a)=>{let o=n??{};return e.role===`user`&&o.renderUserMessage?o.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role===`assistant`&&o.renderAssistantMessage?o.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Yh(e,t,n,r,i,a)};Y(),mn();const Zh=(e,t)=>{if(e.replaceChildren(),!t)e.hidden=!0;else if(typeof t==`function`){let n=null;try{n=t()}catch(e){console.warn(`[persona] welcome.icon renderer threw`,e)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1}else{if(t.type===`lucide`){let n=K(t.name,40);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type===`image`?e.appendChild(J(`img`,{className:`persona-welcome-icon-image`,attrs:{src:t.url,alt:t.alt}})):e.appendChild(J(`span`,{className:`persona-welcome-icon-text`,text:t.text}));e.hidden=!1}},Qh=(e,t,n={})=>{let r=J(`div`,{className:`persona-welcome-icon`,attrs:{"data-persona-welcome-icon":``}});r.hidden=!0;let i=q(`p`,`persona-welcome-kicker`);i.hidden=!0;let a=q(`h2`,`persona-welcome-title`),o=q(`p`,`persona-welcome-subtitle`),s=J(`div`,{className:`persona-welcome-head-text`},i,a),c=J(`div`,{className:`persona-welcome-title-row`},r,s);return{host:J(`div`,{className:`persona-welcome persona-rounded-2xl`,attrs:{"data-persona-welcome":``,"data-persona-intro-card":``,"data-persona-welcome-variant":`card`},style:{background:`var(--persona-intro-card-bg, transparent)`,boxShadow:n.flatShadow?`none`:`var(--persona-intro-card-shadow, none)`,border:`var(--persona-intro-card-border, none)`}},c,o,t),iconHolder:r,kicker:i,title:a,subtitle:o,starterSuggestions:t}},$h=(e,t,n)=>{t.hidden=!n,t.style.display=n?``:`none`,e.classList.toggle(`persona-gap-6`,n),e.classList.toggle(`persona-gap-3`,!n)},eg=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??``,e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle===``,Zh(e.iconHolder,t.icon),e.host.setAttribute(`data-persona-welcome-variant`,t.variant),e.host.setAttribute(`data-persona-welcome-dismiss`,t.dismiss),e.host.setAttribute(`data-persona-welcome-layout`,t.layout??`top`),e.host.setAttribute(`data-persona-welcome-anchor`,t.anchor??`bottom`),t.iconPlacement===`inline`?e.host.setAttribute(`data-persona-welcome-icon-placement`,`inline`):e.host.removeAttribute(`data-persona-welcome-icon-placement`),t.align?e.host.setAttribute(`data-persona-welcome-align`,t.align):e.host.removeAttribute(`data-persona-welcome-align`)},tg=`data-persona-welcome-overlay`,ng=`persona-welcome-overlay-active`,rg=/* @__PURE__ */ new WeakMap,ig=(e,t,n)=>{n.setAttribute(`data-persona-welcome-plugin`,``),t.appendChild(n),t.setAttribute(`data-persona-welcome-content`,`plugin`),t.setAttribute(tg,``),e.classList.contains(ng)||(rg.set(e,e.scrollTop),e.classList.add(ng),e.scrollTop=0)},ag=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute(`data-persona-welcome-content`),t.removeAttribute(tg),e.classList.contains(ng)&&(e.classList.remove(ng),e.scrollTop=rg.get(e)??e.scrollTop,rg.delete(e))},og=()=>{let e=J(`div`,{className:`persona-welcome-greeting persona-flex persona-flex-col`,attrs:{"data-persona-welcome-greeting":``}});return e.hidden=!0,e},sg=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let r=n?.layout?.messages?.layout??`bubble`,i=J(`div`,{className:Uh(`assistant`,r).join(` `),attrs:{"data-persona-theme-zone":`assistant-message`},text:t,style:r===`flat`?{backgroundColor:`transparent`,color:`var(--persona-message-assistant-text, var(--persona-text))`}:{backgroundColor:`var(--persona-message-assistant-bg, var(--persona-container))`,color:`var(--persona-message-assistant-text, var(--persona-text))`}});e.appendChild(J(`div`,{className:`persona-flex`},i)),e.hidden=!1},cg=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,lg=(e,t)=>{if(cg()||typeof e.animate!=`function`||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),r=e.parentElement,i=0,a=0,o=0;if(r){let t=getComputedStyle(r);i=parseFloat(t.rowGap)||0;let s=e.previousElementSibling,c=e.nextElementSibling,l=r.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-r.scrollTop;a=Math.max(0,s?n.top-s.getBoundingClientRect().bottom-i:n.top-l),o=Math.max(0,c?c.getBoundingClientRect().top-n.bottom-i:0)}let s=e.style.overflow;e.style.overflow=`hidden`;let c=getComputedStyle(e),l=parseFloat(c.paddingTop)||0,u=parseFloat(c.paddingBottom)||0,d=e.animate([{opacity:`1`,transform:`none`,height:`${n.height}px`,minHeight:`0px`,paddingTop:`${l}px`,paddingBottom:`${u}px`,marginTop:`${a}px`,marginBottom:`${o}px`},{opacity:`0`,transform:`translateY(-4px)`,height:`0px`,minHeight:`0px`,paddingTop:`0px`,paddingBottom:`0px`,marginTop:`0px`,marginBottom:`${-i}px`}],{duration:180,easing:`ease-out`,fill:`forwards`}),f=!1,p=()=>{f||(f=!0,e.style.overflow=s,t(d))};return d.finished.then(p).catch(p),d},ug=(e,t,n,r=260)=>{if(t<=1||cg()||typeof e.animate!=`function`||!e.isConnected)return null;let i=n===`drop`?-t:t;return e.animate([{transform:`translateY(${i}px)`},{transform:`none`}],{duration:r,easing:`cubic-bezier(0.2, 0, 0, 1)`,fill:`none`})},dg=/* @__PURE__ */ new WeakSet,fg=(e,t)=>!!e&&e[t]!==void 0,pg=(e,t)=>{e&&e.debug===!0&&t.length&&(dg.has(e)||(dg.add(e),t.forEach(e=>console.warn(`[persona] ${e}`))))},mg=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!==`docked`)=>{let n=e?.welcome,r=e?.copy,i=e?.future?.v5Defaults===!0,a=n?.layout??(i?`centered`:`top`),o=fg(n,`variant`)?n.variant:r?.showWelcomeCard===!1?`none`:`card`,s=o===`hero`&&!i&&n?.layout===void 0?`on-first-message`:fg(n,`dismiss`)?n.dismiss:i||o===`hero`?`on-first-message`:`never`,c=[];fg(n,`title`)&&fg(r,`welcomeTitle`)&&c.push(`welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated.`),fg(n,`subtitle`)&&fg(r,`welcomeSubtitle`)&&c.push(`welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated.`),fg(n,`variant`)&&fg(r,`showWelcomeCard`)&&c.push(`welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated.`),o===`hero`&&fg(n,`message`)&&c.push(`welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.`),!i&&n?.layout===void 0&&o===`hero`&&fg(n,`dismiss`)&&n.dismiss!==`on-first-message`&&c.push(`welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".`);let l=n?.anchor??(a===`centered`&&t?`center`:`bottom`),u=Rp(n?.anchorComposerTop)!==null;return fg(n,`anchorComposerTop`)&&!u&&c.push(`welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".`),l!==`center`&&(fg(n,`anchorComposerTop`)||fg(n,`composerGap`))&&c.push(`welcome.anchorComposerTop is ignored unless welcome.anchor is "center".`),pg(e,c),{title:fg(n,`title`)?n.title:r?.welcomeTitle??(i?`What can I help with?`:`Hello 👋`),kicker:n?.kicker??``,subtitle:fg(n,`subtitle`)?n.subtitle:r?.welcomeSubtitle??(i?``:`I can answer questions and help you get things done here.`),icon:n?.icon,align:n?.align===`start`||n?.align===`center`?n.align:a===`centered`?`center`:void 0,iconPlacement:n?.icon&&typeof n.icon!=`function`&&n.icon.placement===`inline`?`inline`:`above`,variant:o,dismiss:s,message:o===`hero`?void 0:n?.message,layout:a,anchor:l,anchorComposerTop:u?n.anchorComposerTop:`44%`,composerGap:n?.composerGap?.trim()||`24px`}},hg=e=>(e??[]).some(e=>e.role===`user`)?`active`:`empty`,gg=(e,t)=>e.variant===`none`?!1:e.dismiss===`never`||!(t??[]).some(e=>e.role===`user`);Y(),yi(),go();const _g=`var(--persona-components-panel-height)`,vg=e=>{let t=fo(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,r=e?.launcher?.heightOffset??0,i=r===0?`max(200px, ${_g})`:`max(200px, calc(${_g} - ${r}px))`;return{width:n??`var(--persona-components-panel-width)`,maxWidth:n??`var(--persona-components-panel-maxWidth)`,height:i,maxHeight:`var(--persona-components-panel-maxHeight)`}},yg=`16px`,bg=`10px`,xg=`14px`,Sg=e=>{let t=e?.launcher?.enabled??!0,n=Bm(e);if(Vm(e)){let t=e?.launcher?.composerBar??{},n=q(`div`,`persona-widget-wrapper persona-fixed persona-transition`);n.setAttribute(`data-persona-composer-bar`,``),n.dataset.state=`collapsed`,n.dataset.expandedSize=t.expandedSize??`anchored`,n.style.zIndex=String(e?.launcher?.zIndex??1e5);let r=q(`div`,`persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);r.style.width=`100%`,n.appendChild(r);let i=q(`div`,`persona-widget-pill-root`);return i.setAttribute(`data-persona-composer-bar`,``),i.dataset.state=`collapsed`,i.dataset.expandedSize=t.expandedSize??`anchored`,i.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:n,panel:r,pillRoot:i}}if(n){let e=q(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`),t=q(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);return e.appendChild(t),{wrapper:e,panel:t}}if(!t){let t=q(`div`,`persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0`),n=q(`div`,`persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0`),r=fo(e),i=r.launcherWidth||r.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?vg(e).width:`100%`;return t.style.width=i,n.style.width=`100%`,t.appendChild(n),{wrapper:t,panel:n}}let r=e?.launcher??{},i=r.position&&Xm[r.position]?Xm[r.position]:Xm[`bottom-right`],a=q(`div`,`persona-widget-wrapper persona-fixed ${i} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let o=q(`div`,`persona-widget-panel persona-relative persona-min-h-[320px]`),s=vg(e);return o.style.width=s.width,o.style.maxWidth=s.maxWidth,a.appendChild(o),{wrapper:a,panel:o}},Cg=e=>{let t=J(`div`,{className:`persona-suggestions`,attrs:{"data-persona-suggestions":Um(e)}});return t.hidden=!0,t},wg=(e,t)=>{let n=Cg(`starter`),r=Qh(e,n,{flatShadow:Bm(e)}),i=mg(e);eg(r,i),$h(t,r.host,gg(i,e?.initialMessages));let a=og();return sg(a,i.message,e),{welcome:r,greetingHost:a}},Tg=(e,t)=>{let n=q(`div`,`persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary`);n.setAttribute(`data-persona-theme-zone`,`container`);let{button:r,wrapper:i}=th(e,{showClose:t,wrapperClassName:`persona-composer-bar-close`,buttonSize:yg,iconSize:bg});i.style.position=`absolute`,i.style.top=`8px`,i.style.right=`8px`,i.style.zIndex=`10`;let a=e?.launcher?.clearChat?.enabled??!0,o=null,s=null;if(a){let t=nh(e,{wrapperClassName:`persona-composer-bar-clear-chat`,buttonSize:yg,iconSize:xg});o=t.button,s=t.wrapper,s.style.position=`absolute`,s.style.top=`8px`,s.style.right=`32px`,s.style.zIndex=`10`}let c=J(`span`,{className:`persona-widget-header`,attrs:{"data-persona-theme-zone":`header`},style:{display:`none`}}),l=J(`div`,{className:`persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6`,attrs:{id:`persona-scroll-container`,"data-persona-theme-zone":`messages`},style:{paddingTop:`48px`}});l.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:u,greetingHost:d}=wg(e,l),{host:f,title:p,subtitle:m}=u,h=u.starterSuggestions,g=q(`div`,`persona-widget-messages persona-flex persona-flex-col`);g.style.gap=`var(--persona-components-message-gap, 12px)`;let _=Cg(`followUp`),v=Ip(e,!0);v&&(g.style.maxWidth=v,g.style.marginLeft=`auto`,g.style.marginRight=`auto`,g.style.width=`100%`),l.append(f,d,g,_);let y=J(`div`,{className:`persona-composer-overlay persona-pointer-events-none`,attrs:{"data-persona-composer-overlay":``},style:{position:`absolute`,left:`0`,right:`0`,bottom:`calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))`,zIndex:`20`}}),b=Sh({config:e}),{root:x,textNode:S}=xh();return n.append(c,i,l,y),s&&n.appendChild(s),{container:n,body:l,messagesWrapper:g,starterSuggestions:h,transcriptSuggestions:_,composerOverlay:y,suggestions:b.suggestions,textarea:b.textarea,sendButton:b.sendButton,sendButtonWrapper:b.sendButtonWrapper,micButton:b.micButton,micButtonWrapper:b.micButtonWrapper,composerForm:b.composerForm,statusText:b.statusText,welcomeHost:f,welcomeIconHolder:u.iconHolder,greetingHost:d,introKicker:u.kicker,introTitle:p,introSubtitle:m,closeButton:r,closeButtonWrapper:i,clearChatButton:o,clearChatButtonWrapper:s,iconHolder:q(`span`),headerTitle:q(`span`),headerSubtitle:q(`span`),header:c,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:x,peekTextNode:S}},Eg=(e,t=!0)=>{if(Vm(e))return Tg(e,t);let n=J(`div`,{className:`persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border`,attrs:{"data-persona-theme-zone":`container`}}),r=e?.layout?.header,i=e?.layout?.showHeader!==!1,a=r?yh(e,r,{showClose:t}):oh({config:e,showClose:t}),o=J(`div`,{className:`persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6`,attrs:{id:`persona-scroll-container`,"data-persona-theme-zone":`messages`}});o.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:s,greetingHost:c}=wg(e,o),{host:l,title:u,subtitle:d}=s,f=s.starterSuggestions,p=q(`div`,`persona-widget-messages persona-flex persona-flex-col`);p.style.gap=`var(--persona-components-message-gap, 12px)`;let m=Cg(`followUp`),h=Ip(e,!1);h&&(p.style.maxWidth=h,p.style.marginLeft=`auto`,p.style.marginRight=`auto`,p.style.width=`100%`),o.append(l,c,p,m);let g=bh({config:e}),_=e?.layout?.showFooter!==!1;i||(a.header.style.display=`none`),sh(n,a,e),n.append(o);let v=J(`div`,{className:`persona-composer-overlay persona-pointer-events-none`,attrs:{"data-persona-composer-overlay":``},style:{position:`absolute`,left:`0`,right:`0`,bottom:`calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))`,zIndex:`20`}});return _||(g.footer.style.display=`none`),n.append(g.footer),n.append(v),{container:n,body:o,messagesWrapper:p,starterSuggestions:f,transcriptSuggestions:m,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,welcomeHost:l,welcomeIconHolder:s.iconHolder,greetingHost:c,introKicker:s.kicker,introTitle:u,introSubtitle:d,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};Y(),mn(),yi();const Dg=(e,t)=>{let n=q(`button`);n.type=`button`,n.innerHTML=`
|
|
25
25
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">💬</span>
|
|
26
26
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
27
27
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -29,15 +29,15 @@ import{Marked as e,Marked as t}from"marked";import n,{default as r}from"dompurif
|
|
|
29
29
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
|
|
30
30
|
</span>
|
|
31
31
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">↗</span>
|
|
32
|
-
`,n.addEventListener(`click`,t);let r=e=>{let t=e.launcher??{},r=
|
|
33
|
-
`):``},
|
|
34
|
-
`).length>7?{tabindex:`0`,"aria-label":`${t} content`}:{},style:{color:i.codeBlockTextColor??i.contentTextColor}}),c=J(`button`,{className:`persona-tool-detail-copy`,attrs:{type:`button`,"data-persona-copy-tool-detail":``,"aria-label":`Copy ${t.toLowerCase()}`,title:`Copy ${t.toLowerCase()}`}}),l=K(`copy`,14,`currentColor`,1.7);l&&c.appendChild(l),r.append(a,s,c),e.appendChild(r)};
|
|
32
|
+
`,n.addEventListener(`click`,t);let r=e=>{let t=e.launcher??{},r=Bm(e),i=zf(e)===`circle`;i?(n.dataset.personaLauncherVariant=`circle`,n.setAttribute(`aria-label`,t.title??`Open chat`)):(n.removeAttribute(`data-persona-launcher-variant`),n.removeAttribute(`aria-label`));let a=n.querySelector(`[data-role='launcher-title']`);if(a){let e=t.title??`Chat Assistant`;a.textContent=e,a.setAttribute(`title`,e)}let o=n.querySelector(`[data-role='launcher-subtitle']`);if(o){let e=t.subtitle??`Here to help you get answers fast`;o.textContent=e,o.setAttribute(`title`,e)}let s=n.querySelector(`.persona-flex-col`);s&&(t.textHidden||r||i?s.style.display=`none`:s.style.display=``);let c=n.querySelector(`[data-role='launcher-icon']`);if(c){if(t.agentIconHidden)c.style.display=`none`;else{let e=t.agentIconSize??`40px`;if(c.style.height=e,c.style.width=e,t.agentIconBackgroundColor?(c.style.backgroundColor=t.agentIconBackgroundColor,c.classList.remove(`persona-bg-persona-primary`)):(c.style.backgroundColor=``,c.classList.add(`persona-bg-persona-primary`)),c.innerHTML=``,t.agentIconName){let n=parseFloat(e)||24,r=K(t.agentIconName,n*.6,`var(--persona-text-inverse, #ffffff)`,1.5);r?(c.appendChild(r),c.style.display=``):(c.textContent=t.agentIconText??`💬`,c.style.display=``)}else t.iconUrl?c.style.display=`none`:(c.textContent=t.agentIconText??`💬`,c.style.display=``)}}let l=n.querySelector(`[data-role='launcher-image']`);if(l){let e=t.agentIconSize??`40px`;l.style.height=e,l.style.width=e,t.iconUrl&&!t.agentIconName&&!t.agentIconHidden?(l.src=t.iconUrl,l.style.display=`block`):l.style.display=`none`}let u=n.querySelector(`[data-role='launcher-call-to-action-icon']`);if(u){let e=t.callToActionIconSize??`32px`;u.style.height=e,u.style.width=e,t.callToActionIconBackgroundColor?(u.style.backgroundColor=t.callToActionIconBackgroundColor,u.classList.remove(`persona-bg-persona-primary`)):(u.style.backgroundColor=``,u.classList.add(`persona-bg-persona-primary`)),t.callToActionIconColor?(u.style.color=t.callToActionIconColor,u.classList.remove(`persona-text-persona-call-to-action`)):(u.style.color=``,u.classList.add(`persona-text-persona-call-to-action`));let n=0;if(t.callToActionIconPadding?(u.style.boxSizing=`border-box`,u.style.padding=t.callToActionIconPadding,n=(parseFloat(t.callToActionIconPadding)||0)*2):(u.style.boxSizing=``,u.style.padding=``),t.callToActionIconHidden||i)u.style.display=`none`;else if(u.style.display=r?`none`:``,u.innerHTML=``,t.callToActionIconName){let r=Math.max((parseFloat(e)||24)-n,8),i=K(t.callToActionIconName,r,`currentColor`,1.5);i?u.appendChild(i):u.textContent=t.callToActionIconText??`↗`}else u.textContent=t.callToActionIconText??`↗`}let d=t.position&&Xm[t.position]?Xm[t.position]:Xm[`bottom-right`];n.className=r?`persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer`:`persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer ${d}`,r||(n.style.zIndex=String(t.zIndex??1e5)),n.style.border=t.border??`1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))`,n.style.boxShadow=t.shadow===void 0?`var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))`:t.shadow.trim()===``?`none`:t.shadow,r?(n.style.width=`0`,n.style.minWidth=`0`,n.style.maxWidth=`0`,n.style.padding=`0`,n.style.overflow=`hidden`,n.style.border=`none`,n.style.boxShadow=`none`):(n.style.width=``,n.style.minWidth=``,n.style.maxWidth=t.collapsedMaxWidth??``,n.style.justifyContent=``,n.style.padding=``,n.style.overflow=``)};return e&&r(e),{element:n,update:r,destroy:()=>{n.removeEventListener(`click`,t),n.remove()}}},Og=/* @__PURE__ */ new Set,kg=e=>{let t=e?.persistState;return`${(typeof t==`object`?t?.keyPrefix:void 0)??`persona-`}teaser-dismissed`},Ag=(e,t)=>{if(Og.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)===`1`}catch{return!1}},jg=(e,t)=>{if(Og.add(e),t)try{window.localStorage.setItem(e,`1`)}catch{}},Mg=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,Ng=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Bm(e??{})?null:t},Pg=(e,t)=>{let n=q(`div`,`persona-launcher-surface`);n.setAttribute(`data-persona-launcher-surface`,`true`);let r=e??{},i=null,a=null,o=null,s=null,c=null,l=!1,u=!1,d=!1,f=!1,p=()=>(i?.frequency??`once`)===`once`&&r.persistState!==!1,m=()=>{c!==null&&(clearTimeout(c),c=null)},h=()=>{a&&l&&(l=!1,a.hidden=!0)},g=e=>{m(),d=!0,h(),jg(kg(r),e&&p())},_=e=>{i&&!d&&g(e===`user`&&l)},v=()=>{c=null,!(!a||d||f)&&(u=!0,l=!0,a.hidden=!1,!(Mg()||typeof a.animate!=`function`)&&a.animate([{opacity:`0`,transform:`translateY(6px)`},{opacity:`1`,transform:`none`}],{duration:220,easing:`ease-out`,fill:`backwards`}))},y=()=>{i&&a&&(d||u||f||Ag(kg(r),p())||(m(),c=setTimeout(v,Math.max(0,i.delayMs??0))))},b=()=>{g(p()),t()},x=e=>{e.stopPropagation(),g(p())},S=Dg(e,()=>{_(`user`),t()}),C=()=>{m(),s?.removeEventListener(`click`,b),o?.removeEventListener(`click`,x),a?.remove(),a=null,s=null,o=null,l=!1},w=()=>{s=J(`button`,{className:`persona-launcher-teaser-text`,attrs:{type:`button`}}),s.addEventListener(`click`,b),o=J(`button`,{className:`persona-launcher-teaser-dismiss`,attrs:{type:`button`},text:`×`}),o.addEventListener(`click`,x),a=J(`div`,{className:`persona-launcher-teaser`,attrs:{"data-persona-launcher-teaser":`true`,role:`status`,"aria-live":`polite`,hidden:``}},s,o),n.insertBefore(a,S.element)},T=()=>{let e=r.launcher?.position??`bottom-right`,t=Xm[e]??Xm[`bottom-right`];a?(n.className=tr(`persona-launcher-surface`,t),n.setAttribute(`data-teaser`,e),n.style.zIndex=String(r.launcher?.zIndex??1e5),S.element.style.position=`static`):(n.className=`persona-launcher-surface`,n.removeAttribute(`data-teaser`),n.style.zIndex=``,S.element.style.position=``)},E=e=>{let t=Ng(e);i=t,t?(a||w(),s.textContent=t.text,o.hidden=t.dismissible===!1,o.setAttribute(`aria-label`,t.dismissLabel??`Dismiss message`),y()):C()};return n.appendChild(S.element),e&&(E(e),T()),{element:n,launcher:S,get teaser(){return a?{element:a,show:v,dismiss:g}:null},setPanelOpen:(e,t=`user`)=>{f=e,e&&_(t)},update:e=>{r=e,S.update(e),E(e),T()},destroy:()=>{C(),S.destroy(),n.remove()}}},Fg=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:i}=Sg(e),a=Eg(e,t),o={wrapper:n,panel:r,pillRoot:i},s={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},l={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:o,panelElements:a,transcript:s,header:c,composer:l,replaceHeader:e=>(c.element.replaceWith(e.header),c.element=e.header,c.iconHolder=e.iconHolder,c.headerTitle=e.headerTitle,c.headerSubtitle=e.headerSubtitle,c.closeButton=e.closeButton,c.closeButtonWrapper=e.closeButtonWrapper,c.clearChatButton=e.clearChatButton,c.clearChatButtonWrapper=e.clearChatButtonWrapper,e),replaceComposer:e=>{l.footer.replaceWith(e),l.footer=e}}},Ig=({config:e,plugins:t,onToggle:n})=>{let r=t.find(e=>e.renderLauncher);if(r?.renderLauncher){let t=r.renderLauncher({config:e,defaultRenderer:()=>Dg(e,n).element,onToggle:n});if(t)return{instance:null,element:t}}let i=Pg(e,n);return{instance:i,element:i.element}},Lg=e=>{let t=e?.persistState;return(typeof t==`object`?t?.keyPrefix:void 0)??`persona-`},Rg=(e,t,n)=>`${Lg(e)}plugin:${t}:${n}`,zg=e=>{let t=/* @__PURE__ */ new Map,n=!1,r=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>`u`||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return i=>{let a=t=>Rg(e(),i,t);return{get:e=>{let i=a(e),o=r();if(o)try{return o.getItem(i)}catch{n=!0}return t.get(i)??null},set:(e,i)=>{let o=a(e),s=r();if(s)try{s.setItem(o,i);return}catch{n=!0}t.set(o,i)},remove:e=>{let i=a(e);t.delete(i);let o=r();if(o)try{o.removeItem(i)}catch{n=!0}}}}};Y();const Bg=(e,t,n)=>{let r=n;for(let n of t){let t=q(`span`,`persona-tool-char`);t.style.setProperty(`--char-index`,String(r)),t.textContent=n===` `?`\xA0`:n,e.appendChild(t),r++}return r};Y(),mn(),No(),er();const Vg=(e,t)=>{let n=e.reasoning?.chunks.join(``).trim()??``;return n?n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join(`
|
|
33
|
+
`):``},Hg=(e,t,n)=>{Sl(e,t,{stateSet:n,previewKind:`reasoning`,iconColor:`currentColor`})},Ug=(e,t,n=/* @__PURE__ */ new Set)=>{t=Cl(t,`reasoning`);let r=e.reasoning,i=gl(`persona-reasoning-bubble`,e.id);if(!r)return El(i,e,t,`reasoning`);let a=t?.features?.reasoningDisplay??{},o=a.expandable??Eo.expandable,s=o&&n.has(e.id),c=r.status!==`complete`,l=Vg(e,a.previewMaxLines??Eo.previewMaxLines),u=_l({expandable:o,expanded:s,bubbleType:`reasoning`}),d=q(`div`,`persona-flex persona-flex-col persona-text-left`),f=q(`span`,`persona-text-xs persona-text-persona-primary`),p=wl(t,`reasoning`)===`row`,m=p&&!c?`Thought for ${Tl(r.durationMs??(r.completedAt!==void 0&&r.startedAt!==void 0?r.completedAt-r.startedAt:void 0))}`:`Thinking...`,h=t?.reasoning??{},g=String(r.startedAt??Date.now()),_=()=>{let e=q(`span`,``);return e.setAttribute(`data-tool-elapsed`,g),e.textContent=Un(r),e},v=h.renderCollapsedSummary?.({message:e,reasoning:r,defaultSummary:m,previewText:l,isActive:c,config:t??{},elapsed:Un(r),createElapsedElement:_});typeof v==`string`&&v.trim()?(f.textContent=v,d.appendChild(f)):v instanceof HTMLElement?d.appendChild(v):(f.textContent=m,d.appendChild(f));let y=q(`span`,`persona-text-xs persona-text-persona-primary`);y.textContent=Ln(r),p||d.appendChild(y);let b=a.loadingAnimation??Eo.loadingAnimation,x=h.activeTextTemplate,S=h.completeTextTemplate,C=c?x:S,w=v instanceof HTMLElement,T=(e,t)=>{f.textContent=``;let n=Gn(e,``),i=0;for(let e of n){let n=e.styles.length>0?(()=>{let t=q(`span`,e.styles.map(e=>`persona-tool-text-${e}`).join(` `));return f.appendChild(t),t})():f;if(e.isDuration&&c)n.appendChild(_());else{let a=e.isDuration?Un(r):e.text;t?i=Bg(n,a,i):n.appendChild(document.createTextNode(a))}}};if(!w&&C){if(y.style.display=`none`,f.style.display=``,c&&b!==`none`){let e=h.loadingAnimationDuration??2e3;f.setAttribute(`data-preserve-animation`,`true`),b===`pulse`?(f.classList.add(`persona-tool-loading-pulse`),f.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),T(C,!1)):(f.classList.add(`persona-tool-loading-${b}`),f.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),b===`shimmer-color`&&(h.loadingAnimationColor&&f.style.setProperty(`--persona-tool-anim-color`,h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&f.style.setProperty(`--persona-tool-anim-secondary-color`,h.loadingAnimationSecondaryColor)),T(C,!0))}else T(C,!1)}else if(!w&&c&&b!==`none`){f.style.display=``;let e=h.loadingAnimationDuration??2e3;if(f.setAttribute(`data-preserve-animation`,`true`),b===`pulse`)f.classList.add(`persona-tool-loading-pulse`),f.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`);else{f.classList.add(`persona-tool-loading-${b}`),f.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),b===`shimmer-color`&&(h.loadingAnimationColor&&f.style.setProperty(`--persona-tool-anim-color`,h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&f.style.setProperty(`--persona-tool-anim-secondary-color`,h.loadingAnimationSecondaryColor));let t=f.textContent||m;f.textContent=``,Bg(f,t,0)}r.status===`complete`&&!p&&(f.style.display=`none`)}else w||(r.status===`complete`&&!p?f.style.display=`none`:f.style.display=``);if(a.iconName&&!w){let e=q(`span`,`persona-reasoning-header-icon`),t=K(a.iconName,16,`currentColor`,2);t&&(e.appendChild(t),u.appendChild(e))}let E=`currentColor`,D=yl(u,d,{expandable:o,expanded:s,iconColor:E,metaGap:!1}),O=bl({bubble:i,previewKind:`reasoning`,expanded:s,isActive:c,previewText:l,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:r,defaultPreview:l,isActive:c,config:t??{}})});if(!o)return i.append(u,O),El(i,e,t,`reasoning`);let k=q(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3`);k.style.display=s?``:`none`;let ee=r.chunks.join(``),te=q(`div`,`persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted`);return te.textContent=ee||(r.status===`complete`?`No additional context was shared.`:`Waiting for details…`),k.appendChild(te),xl({expanded:s,header:u,toggleIcon:D,content:k,collapsedPreview:O,iconColor:E}),i.append(u,O,k),El(i,e,t,`reasoning`)};Y(),er(),mn();const Wg=e=>{if(e==null)return!0;if(typeof e==`string`){if(!e.trim())return!0;try{return Wg(JSON.parse(e))}catch{return!1}}return typeof e==`object`&&Object.keys(e).length===0},Gg=e=>{if(typeof e==`object`&&e)return!0;if(typeof e!=`string`)return!1;try{let t=JSON.parse(e);return typeof t==`object`&&!!t}catch{return!1}};function Kg(e,t,n){let r=t.toolCall;if(!r)return;let i=n.toolCall??{},a=(t,n)=>{let r=J(`section`,{className:`persona-tool-detail`,attrs:{"data-persona-tool-detail":t.toLowerCase()},style:{backgroundColor:i.codeBlockBackgroundColor,borderColor:i.codeBlockBorderColor,borderWidth:i.codeBlockBorderColor?`1px`:void 0}}),a=J(`div`,{className:`persona-tool-detail-label`,text:t,style:{color:i.labelTextColor}}),o=Fn(n),s=J(`pre`,{className:`persona-tool-detail-value${Gg(n)?` persona-tool-detail-code`:``}`,text:o,attrs:o.length>420||o.split(`
|
|
34
|
+
`).length>7?{tabindex:`0`,"aria-label":`${t} content`}:{},style:{color:i.codeBlockTextColor??i.contentTextColor}}),c=J(`button`,{className:`persona-tool-detail-copy`,attrs:{type:`button`,"data-persona-copy-tool-detail":``,"aria-label":`Copy ${t.toLowerCase()}`,title:`Copy ${t.toLowerCase()}`}}),l=K(`copy`,14,`currentColor`,1.7);l&&c.appendChild(l),r.append(a,s,c),e.appendChild(r)};Wg(r.args)||a(`Request`,r.args);let o=r.status===`complete`&&r.result!==void 0?r.result:r.chunks?.join(``);o!==void 0&&(typeof o!=`string`||o.trim())&&a(`Response`,o),r.success===!1&&e.appendChild(J(`div`,{className:`persona-text-sm persona-whitespace-pre-wrap`,text:r.error||`Tool failed`,attrs:{"data-persona-tool-error":``,role:`status`}}))}const qg=/* @__PURE__ */ new WeakMap;async function Jg(e){let t=e.closest(`[data-persona-tool-detail]`),n=t?.querySelector(`pre`);if(!n)return;let r=`Copy ${t?.getAttribute(`data-persona-tool-detail`)}`;clearTimeout(qg.get(e));try{await navigator.clipboard.writeText(n.textContent??``),e.dataset.copied=`true`,e.setAttribute(`aria-label`,`Copied`),e.title=`Copied`;let t=K(`check`,14,`currentColor`,2);t&&e.replaceChildren(t)}catch{e.setAttribute(`aria-label`,`Copy failed — try again`),e.title=`Copy failed — try again`}qg.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute(`aria-label`,r),e.title=r;let t=K(`copy`,14,`currentColor`,1.7);t&&e.replaceChildren(t),qg.delete(e)},1800))}Y(),No(),er();const Yg=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?`currentColor`:`var(--persona-primary, #171717)`),Xg=(e,t)=>{let n=e.toolCall;if(!n)return``;let r=(n.chunks??[]).join(``).trim();if(r)return r.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(-t).join(`
|
|
35
35
|
`);let i=Fn(n.args).trim();return i?i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join(`
|
|
36
|
-
`):``},Ug=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??`var(--persona-container, #f3f4f6)`,e.style.borderColor=t.codeBlockBorderColor??`var(--persona-border, #e5e7eb)`,e.style.color=t.codeBlockTextColor??`var(--persona-text, #171717)`},Wg=(e,t)=>{let n=e.toolCall,r=t?.features?.toolCallDisplay,i=r?.collapsedMode??To.collapsedMode,a=n?.success===!1?n.error||`Tool failed`:Hg(e,r?.previewMaxLines??To.previewMaxLines),o=n?_l(t,`tool`)===`row`?`${n.status===`complete`?`Used`:`Using`} ${n.name?.trim()||`tool`}`:Bn(n):``;if(!n)return{summary:o,previewText:a,isActive:!1};let s=n.status!==`complete`,c=t?.toolCall??{},l=o;return i===`tool-name`?l=n.name?.trim()||o:i===`tool-preview`&&a&&(l=a),s&&c.activeTextTemplate?l=Wn(n,c.activeTextTemplate,l):!s&&c.completeTextTemplate&&(l=Wn(n,c.completeTextTemplate,l)),n.success===!1?l+=` · Failed`:n.superseded&&(l+=` · Approved, ran again below`),{summary:l,previewText:a,isActive:s}},Gg=(e,t,n,r)=>{hl(e,t,{stateSet:n,previewKind:`tool`,iconColor:Vg(r?.toolCall??{},t.classList.contains(`persona-activity-row`))})},Kg=(e,t,n=/* @__PURE__ */ new Set)=>{t=gl(t,`tool`);let r=e.toolCall,i=t?.toolCall??{},a=ll(`persona-tool-bubble`,e.id);if(i.backgroundColor&&(a.style.backgroundColor=i.backgroundColor),i.borderColor&&(a.style.borderColor=i.borderColor),i.borderWidth&&(a.style.borderWidth=i.borderWidth),i.borderRadius&&(a.style.borderRadius=i.borderRadius),a.style.boxShadow=i.shadow===void 0?`var(--persona-tool-bubble-shadow)`:i.shadow.trim()===``?`none`:i.shadow,!r)return yl(a,e,t,`tool`);let o=t?.features?.toolCallDisplay??{},s=o.expandable??To.expandable,c=s&&n.has(e.id),{summary:l,previewText:u,isActive:d}=Wg(e,t),f=ul({expandable:s,expanded:c,bubbleType:`tool`});i.headerBackgroundColor&&(f.style.backgroundColor=i.headerBackgroundColor),i.headerPaddingX&&(f.style.paddingLeft=i.headerPaddingX,f.style.paddingRight=i.headerPaddingX),i.headerPaddingY&&(f.style.paddingTop=i.headerPaddingY,f.style.paddingBottom=i.headerPaddingY);let p=q(`div`,`persona-flex persona-flex-col persona-text-left`),m=q(`span`,`persona-text-xs persona-text-persona-primary`);i.headerTextColor&&(m.style.color=i.headerTextColor);let h=String(r.startedAt??Date.now()),g=()=>{let e=q(`span`,``);return e.setAttribute(`data-tool-elapsed`,h),e.textContent=Hn(r),e},_=i.renderCollapsedSummary?.({message:e,toolCall:r,defaultSummary:l,previewText:u,collapsedMode:o.collapsedMode??To.collapsedMode,isActive:d,config:t??{},elapsed:Hn(r),createElapsedElement:g});typeof _==`string`&&_.trim()?(m.textContent=_,p.appendChild(m)):_ instanceof HTMLElement?p.appendChild(_):(m.textContent=l,p.appendChild(m));let v=o.loadingAnimation??To.loadingAnimation,y=i.activeTextTemplate,b=i.completeTextTemplate,x=d?y:b,S=_ instanceof HTMLElement,C=(e,t)=>{m.textContent=``;let n=r.name?.trim()||`tool`,i=Gn(e,n),a=0;for(let e of i){let n=e.styles.length>0?(()=>{let t=q(`span`,e.styles.map(e=>`persona-tool-text-${e}`).join(` `));return m.appendChild(t),t})():m;if(e.isDuration&&d)n.appendChild(g());else{let i=e.isDuration?Hn(r):e.text;t?a=Mg(n,i,a):n.appendChild(document.createTextNode(i))}}};if(!S){if(d&&v!==`none`){let e=i.loadingAnimationDuration??2e3;if(m.setAttribute(`data-preserve-animation`,`true`),v===`pulse`)m.classList.add(`persona-tool-loading-pulse`),m.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),x&&C(x,!1);else if(m.classList.add(`persona-tool-loading-${v}`),m.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),v===`shimmer-color`&&(i.loadingAnimationColor&&m.style.setProperty(`--persona-tool-anim-color`,i.loadingAnimationColor),i.loadingAnimationSecondaryColor&&m.style.setProperty(`--persona-tool-anim-secondary-color`,i.loadingAnimationSecondaryColor)),x)C(x,!0);else{let e=m.textContent||l;m.textContent=``,Mg(m,e,0)}}else x&&C(x,!1)}let w=Vg(i,_l(t,`tool`)===`row`),T=fl(f,p,{expandable:s,expanded:c,iconColor:w,metaGap:!0}),E=pl({bubble:a,previewKind:`tool`,expanded:c,isActive:d,previewText:u,activePreview:o.activePreview,activeMinHeight:o.activeMinHeight,renderPreview:()=>i.renderCollapsedPreview?.({message:e,toolCall:r,defaultPreview:u,isActive:d,config:t??{}})});if(!s)return a.append(f,E),yl(a,e,t,`tool`);let D=q(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3`);if(D.style.display=c?``:`none`,i.contentBackgroundColor&&(D.style.backgroundColor=i.contentBackgroundColor),i.contentTextColor&&(D.style.color=i.contentTextColor),i.contentPaddingX&&(D.style.paddingLeft=i.contentPaddingX,D.style.paddingRight=i.contentPaddingX),i.contentPaddingY&&(D.style.paddingTop=i.contentPaddingY,D.style.paddingBottom=i.contentPaddingY),t.future?.v5Defaults===!0)Rg(D,e,t);else{if(r.name){let e=q(`div`,`persona-text-xs persona-text-persona-muted persona-italic`);i.contentTextColor?e.style.color=i.contentTextColor:i.headerTextColor&&(e.style.color=i.headerTextColor),e.textContent=r.name,D.appendChild(e)}if(r.args!==void 0){let e=q(`div`,`persona-space-y-1`),t=q(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Arguments`;let n=q(`pre`,`persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,Ug(n,i),n.textContent=Fn(r.args),e.append(t,n),D.appendChild(e)}if(r.chunks&&r.chunks.length){let e=q(`div`,`persona-space-y-1`),t=q(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Activity`;let n=q(`pre`,`persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,Ug(n,i),n.textContent=r.chunks.join(``),e.append(t,n),D.appendChild(e)}if(r.success===!1&&D.appendChild(J(`div`,{className:`persona-text-sm persona-whitespace-pre-wrap`,text:r.error||`Tool failed`,attrs:{"data-persona-tool-error":``}})),r.status===`complete`&&r.result!==void 0){let e=q(`div`,`persona-space-y-1`),t=q(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Result`;let n=q(`pre`,`persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,Ug(n,i),n.textContent=Fn(r.result),e.append(t,n),D.appendChild(e)}if(r.status===`complete`&&typeof r.duration==`number`){let e=q(`div`,`persona-text-xs persona-text-persona-muted`);i.contentTextColor&&(e.style.color=i.contentTextColor),e.textContent=`Duration: ${r.duration}ms`,D.appendChild(e)}}return ml({expanded:c,header:f,toggleIcon:T,content:D,collapsedPreview:E,iconColor:w}),a.append(f,E,D),yl(a,e,t,`tool`)};Pt();const{setLoader:qg,load:Jg,provide:Yg,getSync:Xg}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/approval-ui`)}),Zg=Jg,Qg=Xg;Pt();const{setLoader:$g,load:e_}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/event-stream-view`)}),t_=e_,n_=new class{constructor(){this.components=/* @__PURE__ */ new Map,this.#e=/* @__PURE__ */ new Map}#e;register(e,t,n){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t),n?this.#e.set(e,n):this.#e.delete(e)}unregister(e){this.components.delete(e),this.#e.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.#e.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.#e.clear()}registerAll(e){Object.entries(e).forEach(([e,t])=>{this.register(e,t)})}};Pt(),$t();const r_=[`PersonaArtifactCard`,`PersonaArtifactInline`],{setLoader:i_,load:a_,provide:o_,getSync:s_}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/artifacts-ui`)});let c_=null;const l_=/* @__PURE__ */ new Set,u_=e=>{if(c_)return c_;c_=e,e.initArtifactsUi({componentRegistry:n_});for(let t of r_)n_.has(t)||n_.register(t,t===`PersonaArtifactCard`?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Kt();t?e.__provideMarkdownParsers(t):Wt(()=>{let t=Kt();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader(()=>Qt());let n=[...l_];l_.clear();for(let e of n)try{e()}catch{}return e},d_=()=>a_().then(u_),f_=()=>{if(c_)return c_;let e=s_();return e?u_(e):null},p_=e=>c_?()=>{}:(l_.add(e),()=>{l_.delete(e)});function m_(e){return e?.features?.artifacts?.enabled===!0}function h_(e,t){if(e.classList.remove(`persona-artifact-border-full`,`persona-artifact-border-left`),e.style.removeProperty(`--persona-artifact-pane-border`),e.style.removeProperty(`--persona-artifact-pane-border-left`),!m_(t))return;let n=t.features?.artifacts?.layout,r=n?.paneBorder?.trim(),i=n?.paneBorderLeft?.trim();r?(e.classList.add(`persona-artifact-border-full`),e.style.setProperty(`--persona-artifact-pane-border`,r)):i&&(e.classList.add(`persona-artifact-border-left`),e.style.setProperty(`--persona-artifact-pane-border-left`,i))}function g_(e){e.style.removeProperty(`--persona-artifact-doc-toolbar-icon-color`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-bg`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-border`)}const __=[`panel`,`seamless`,`detached`];function v_(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&__.includes(t)?t:t?`panel`:e.launcher?.detachedPanel?`detached`:`panel`}function y_(e){return!e||!m_(e)?!1:v_(e)===`detached`}function b_(e,t){if(!m_(t)){e.style.removeProperty(`--persona-artifact-split-gap`),e.style.removeProperty(`--persona-artifact-pane-width`),e.style.removeProperty(`--persona-artifact-pane-max-width`),e.style.removeProperty(`--persona-artifact-pane-min-width`),e.style.removeProperty(`--persona-artifact-drawer-width`),e.style.removeProperty(`--persona-artifact-pane-bg`),e.style.removeProperty(`--persona-artifact-pane-padding`),g_(e),h_(e,t);return}let n=t.features?.artifacts?.layout,r=v_(t)===`detached`?`var(--persona-panel-inset)`:`0`;e.style.setProperty(`--persona-artifact-split-gap`,n?.splitGap??r),e.style.setProperty(`--persona-artifact-pane-width`,n?.paneWidth??`40%`),e.style.setProperty(`--persona-artifact-pane-max-width`,n?.paneMaxWidth??`28rem`),n?.drawerWidth?e.style.setProperty(`--persona-artifact-drawer-width`,n.drawerWidth):e.style.removeProperty(`--persona-artifact-drawer-width`),n?.paneMinWidth?e.style.setProperty(`--persona-artifact-pane-min-width`,n.paneMinWidth):e.style.removeProperty(`--persona-artifact-pane-min-width`);let i=n?.paneBackground?.trim();i?e.style.setProperty(`--persona-artifact-pane-bg`,i):e.style.removeProperty(`--persona-artifact-pane-bg`);let a=n?.panePadding?.trim();a?e.style.setProperty(`--persona-artifact-pane-padding`,a):e.style.removeProperty(`--persona-artifact-pane-padding`);let o=[[n?.documentToolbarIconColor,`--persona-artifact-doc-toolbar-icon-color`],[n?.documentToolbarToggleActiveBackground,`--persona-artifact-doc-toggle-active-bg`],[n?.documentToolbarToggleActiveBorderColor,`--persona-artifact-doc-toggle-active-border`],[n?.documentToolbarToggleActiveColor,`--persona-artifact-doc-toggle-active-color`]];for(let[t,n]of o){let r=t?.trim();r?e.style.setProperty(n,r):e.style.removeProperty(n)}h_(e,t)}function x_(e,t){for(let t of __)e.classList.remove(`persona-artifact-appearance-${t}`);if(e.style.removeProperty(`--persona-artifact-pane-radius`),e.style.removeProperty(`--persona-artifact-pane-shadow`),e.style.removeProperty(`--persona-artifact-chat-shadow`),!m_(t))return;let n=t.features?.artifacts?.layout,r=v_(t);e.classList.add(`persona-artifact-appearance-${r}`);let i=n?.paneBorderRadius?.trim();i&&e.style.setProperty(`--persona-artifact-pane-radius`,i);let a=n?.paneShadow?.trim();a&&e.style.setProperty(`--persona-artifact-pane-shadow`,a);let o=n?.chatShadow?.trim();o&&e.style.setProperty(`--persona-artifact-chat-shadow`,o)}function S_(e,t){return!t||!m_(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}Nn();const C_=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`]),w_=/* @__PURE__ */ new Set([`collapsed`,`card`,`panel`,`inline`]),T_=/* @__PURE__ */ new Set([`markdown`,`component`]),E_=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,D_=e=>typeof e==`object`&&!!e&&!Array.isArray(e),O_=e=>!C_.has(e),k_=e=>typeof e==`string`&&w_.has(e),A_=e=>Object.keys(e).length>0;function j_(e,t,n,r){e.push({path:t,code:n,message:r})}const M_=`Ignored an unsupported value.`,N_={kind:`mode`,message:M_},P_={kind:`string`,message:`Expected a CSS length string.`},F_={kind:`boolean`},I_={kind:`object`,message:`Expected a preference object.`,children:{showToolCalls:F_,showReasoning:F_,toolCallDisplay:{kind:`object`,children:{collapsedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`tool-call`,`tool-name`,`tool-preview`]),message:M_},groupedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`stack`,`summary`]),message:M_},loadingAnimation:{kind:`enum`,values:/* @__PURE__ */ new Set([`none`,`pulse`,`shimmer`,`shimmer-color`,`rainbow`]),message:M_},expandable:F_,grouped:F_}},reasoningDisplay:{kind:`object`,children:{expandable:F_,activePreview:F_}},artifacts:{kind:`object`,children:{display:{kind:`object`,bareMode:!0,message:`Expected an artifact display rules object.`,children:{default:N_,files:{kind:`object`,bareMode:!0,message:`Expected collapsed, panel, inline, or a file display rules object.`,children:{default:N_,byMediaType:{kind:`modeMap`,keys:`mediaType`}}},byType:{kind:`modeMap`,keys:T_,alias:`byKind`,deprecated:`Use byKind. The legacy selector was normalized automatically.`},byKind:{kind:`modeMap`,keys:T_}}},filePreview:{kind:`object`,children:{enabled:F_}},layout:{kind:`object`,children:{paneWidth:P_,paneMaxWidth:P_,paneMinWidth:P_,expandedPanelWidth:P_,resizableMinWidth:P_,resizableMaxWidth:P_,expandLauncherPanelWhenOpen:F_,resizable:F_}}}}}};function L_(e,t,n,r){if(e!==void 0)switch(t.kind){case`boolean`:return typeof e==`boolean`?e:j_(r,n,`invalid_type`,`Expected a boolean.`);case`string`:return typeof e==`string`?e:j_(r,n,`invalid_type`,t.message);case`enum`:return typeof e==`string`&&t.values.has(e)?e:j_(r,n,`invalid_value`,t.message);case`mode`:return k_(e)?Dn(e):j_(r,n,`invalid_value`,t.message);case`modeMap`:{if(!D_(e))return j_(r,n,`invalid_type`,`Expected an object.`);let i=t.keys===`mediaType`?void 0:t.keys,a={};for(let[t,o]of Object.entries(e)){let e=i?t:On(t);O_(t)&&(i?i.has(t):E_.test(e))?k_(o)?a[e]=Dn(o):j_(r,`${n}.${t}`,`invalid_value`,`Expected collapsed, panel, or inline.`):j_(r,`${n}.${t}`,i?`unknown_key`:`invalid_value`,i?`Ignored an unsupported selector.`:`Expected a MIME type such as "text/html" or a wildcard such as "image/*".`)}return A_(a)?a:void 0}case`object`:{if(t.bareMode&&k_(e))return Dn(e);if(!D_(e))return j_(r,n,`invalid_type`,t.message??`Expected an object.`);let i=Object.keys(t.children),a=e=>n?`${n}.${e}`:e;for(let t of Object.keys(e))(!O_(t)||!i.includes(t))&&j_(r,a(t),`unknown_key`,`Ignored because this key is not part of the persisted preference schema.`);let o={};for(let n of i){let i=t.children[n],s=L_(e[n],i,a(n),r);if(i.deprecated&&e[n]!==void 0&&j_(r,a(n),`deprecated_key`,i.deprecated),s===void 0)continue;let c=i.alias??n,l=o[c];o[c]=D_(l)&&D_(s)?{...l,...s}:s}return A_(o)?o:void 0}}}function R_(e){let t=[];return{preferences:(e===null?void 0:L_(e,I_,``,t))??{},issues:t}}function z_(e){if(Array.isArray(e))return e.map(z_);if(!D_(e))return e;let t={};for(let[n,r]of Object.entries(e))O_(n)&&r!==void 0&&(t[n]=z_(r));return t}function B_(e,t){let n=z_(e);for(let[e,r]of Object.entries(t)){if(!O_(e)||r===void 0)continue;let t=n[e];n[e]=D_(t)&&D_(r)?B_(t,r):z_(r)}return n}function V_(e){let t={},n;for(let r of e){let e=R_(r).preferences;n=U_(n,e.artifacts?.display),t=B_(t,e)}let r=t;return r.artifacts&&(n===void 0?delete r.artifacts.display:r.artifacts.display=n),r}function H_(e,t){if(t===void 0)return e===void 0?void 0:z_(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byMediaType,...t.byMediaType},a={...r?{default:r}:{},...A_(i)?{byMediaType:i}:{}};return A_(a)?a:void 0}function U_(e,t){if(t===void 0)return e===void 0?void 0:z_(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byType,...n.byKind,...t.byType,...t.byKind},a=H_(n.files,t.files),o={...r?{default:r}:{},...A_(i)?{byKind:i}:{},...a===void 0?{}:{files:a}};return A_(o)?o:void 0}function W_(e={},t){let n=V_(t),r={...e};if(n.showToolCalls!==void 0&&(r.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(r.showReasoning=n.showReasoning),n.toolCallDisplay&&(r.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(r.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let t=e.artifacts??{},i={...t};if(n.artifacts.display!==void 0){let e=U_(t.display,n.artifacts.display);e!==void 0&&(i.display=e)}n.artifacts.filePreview&&(i.filePreview={...t.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...t.layout,...n.artifacts.layout}),r.artifacts=i}return r}function G_(e){let t=e.preferences;return!t||!A_(t)?e:{...e,features:W_(e.features??{},[t])}}function K_(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function q_(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function J_(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Y_(e,t,n,r){let i=e-r-2*t-n;return Math.max(0,i)}function X_(e,t){let n=(t.getComputedStyle(e).gap||`0px`).trim().split(/\s+/)[0]??`0px`,r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let i=/^([\d.]+)/.exec(n);return i?Number(i[1]):8}function Z_(e,t,n,r,i,a,o=200){let s=K_(i,200),c=Y_(t,n,r,o);c=Math.max(s,c);let l=q_(a);return l!==null&&(c=Math.min(c,l)),J_(e,s,c)}Pt();const{setLoader:Q_,load:$_,provide:ev,getSync:tv}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/forms-ui`)}),nv=$_,rv=tv,iv=new class{#e=/* @__PURE__ */ new Map;register(e){this.#e.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.#e.set(e.id,e),e.onRegister?.()}unregister(e){let t=this.#e.get(e);t&&(t.onUnregister?.(),this.#e.delete(e))}getAll(){return Array.from(this.#e.values()).sort((e,t)=>(t.priority??0)-(e.priority??0))}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let n=new Set(e.map(e=>e.id));return[...t.filter(e=>!n.has(e.id)),...e].sort((e,t)=>(t.priority??0)-(e.priority??0))}clear(){this.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}};No(),go(),oo();const av=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ov=/* @__PURE__ */ new Set([`headers`,`agent`,`storageAdapter`,`components`,`targetProviders`,`voiceRecognition.provider.custom`,`features.artifacts.display`,`features.streamAnimation.plugins`,`preferences`,`welcome.icon`]),sv=(e,t,n)=>{if(!av(e)||!av(t)||ov.has(n))return t;let r={...e};for(let i of Object.keys(t)){if(t[i]===void 0){delete r[i];continue}let a=n?`${n}.${i}`:i;r[i]=sv(e[i],t[i],a)}return r};function cv(e,t){let n=Za(jo),r=no(e,t,n),i=eo(ro(sv(e,t,``),n,r),r);return po(bo(i),ho(e,t))}const lv=()=>{let e=/* @__PURE__ */ new Map,t=(t,r)=>(e.has(t)||e.set(t,/* @__PURE__ */ new Set),e.get(t).add(r),()=>n(t,r)),n=(t,n)=>{e.get(t)?.delete(n)};return{on:t,off:n,emit:(t,n)=>{e.get(t)?.forEach(e=>{try{e(n)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Event handler error:`,e)}})}}},uv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},dv=e=>{let t=e.trim(),n=t.indexOf(`{`);if(n===-1)return null;let r=0;for(let e=n;e<t.length;e+=1){let i=t[e];if(i===`{`&&(r+=1),i===`}`&&(--r,r===0))return t.slice(n,e+1)}return null},fv=({text:e})=>{if(!e||!e.includes(`{`))return null;try{let t=uv(e),n=dv(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!=`object`||!r.action)return null;let{action:i,...a}=r;return{type:String(i),payload:a,raw:r}}catch{return null}},pv=e=>typeof e==`string`?e:e==null?``:String(e),mv={message:e=>{if(e.type===`message`)return{handled:!0,displayText:pv(e.payload.text)}},messageAndClick:(e,t)=>{if(e.type!==`message_and_click`)return;let n=e.payload,r=pv(n.element);if(r&&t.document?.querySelector){let e=t.document.querySelector(r);e?setTimeout(()=>{e.click()},400):typeof console<`u`&&console.warn(`[AgentWidget] Element not found for selector:`,r)}return{handled:!0,displayText:pv(n.text)}}},hv=e=>Array.isArray(e)?e.map(e=>String(e)):[],gv=e=>{let t=new Set(hv(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(hv(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let n=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:n}))};return{process:n=>{if(n.streaming||n.message.role!==`assistant`||!n.text||t.has(n.message.id))return null;let i=typeof n.raw==`string`&&n.raw||typeof n.message.rawContent==`string`&&n.message.rawContent||typeof n.text==`string`&&n.text||null;!i&&typeof n.text==`string`&&n.text.trim().startsWith(`{`)&&typeof console<`u`&&console.warn(`[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.`);let a=i?e.parsers.reduce((e,t)=>e||t?.({text:i,message:n.message})||null,null):null;if(!a)return null;t.add(n.message.id),r();let o={action:a,message:n.message};e.emit(`action:detected`,o);for(let t of e.handlers)if(t)try{let r=t(a,{message:n.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{e.emit(`action:resubmit`,o)}});if(!r)continue;if(r.handled){let e=r.persistMessage!==!1;return{text:r.displayText===void 0?``:r.displayText,persist:e,resubmit:r.resubmit}}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Action handler error:`,e)}return{text:``,persist:!0}},syncFromMetadata:n}},_v=e=>{if(!e)return null;try{return JSON.parse(e)}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] Failed to parse stored state:`,e),null}},vv=e=>e.map(e=>({...e,streaming:!1})),yv=e=>e.map(e=>({...e,status:`complete`})),bv=(e=`persona-state`)=>{let t=()=>typeof window>`u`||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?_v(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let t={...n,messages:n.messages?vv(n.messages):void 0,artifacts:n.artifacts?yv(n.artifacts):void 0};r.setItem(e,JSON.stringify(t))}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to persist state:`,e)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to clear stored state:`,e)}}}},xv=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,`0`)},Sv=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let n=await t.digest(`SHA-256`,new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}catch{}return xv(e)},Cv=async(e,t)=>{let n=await Sv(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await Sv(`${e}\0${t}`)}`}},wv=(e,t,n)=>{let r=``,i=``,a=``,o=!1,s=!1,c=0,l=null,u=null,d=/* @__PURE__ */ new Set,f=()=>{if(n||o)return null;try{return typeof window>`u`||!window.localStorage?null:window.localStorage}catch{return o=!0,null}},p=()=>{let e=f();if(!e)return l;try{return e.getItem(r)}catch{return o=!0,l}},m=(e,t)=>{if(s||e===l)return;let n=l;l=e,c+=1;let r={previousToken:n,token:e,source:t,revision:c};for(let e of d)e(r)},h=e=>{s||(e.key===null||e.key===r)&&m(e.key===null?null:e.newValue??null,`external`)},g=(async()=>{let o=await Cv(e,t);r=o.storageKey,i=o.leaseKey,a=o.lockName,l=p(),!n&&typeof window<`u`&&window.addEventListener(`storage`,h)})(),_=e=>new Promise(t=>setTimeout(t,e)),v=()=>{let e=f();if(!e)return null;try{let t=e.getItem(i);if(!t)return null;let n=JSON.parse(t);return typeof n?.expiresAt==`number`&&typeof n?.ownerNonce==`string`?n:null}catch{return null}},y=e=>{let t=f();if(t)try{v()?.ownerNonce===e&&t.removeItem(i)}catch{}},b=/* @__PURE__ */ new Set,x=e=>s?Promise.reject(/* @__PURE__ */ Error(`Visitor store destroyed before its first init could start`)):e(),S=e=>new Promise(t=>{let n=setTimeout(r,e);function r(){clearTimeout(n),b.delete(r),window.removeEventListener(`storage`,a),t()}function a(e){(e.key===null||e.key===i)&&r()}b.add(r),window.addEventListener(`storage`,a)}),C=async e=>{let t=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,n=Date.now()+15e3;for(;!s&&Date.now()<n;){let n=f();if(!n)break;let r=Date.now(),a=v();if(a&&a.expiresAt>r&&a.ownerNonce!==t)await S(Math.min(a.expiresAt-r,500));else{try{n.setItem(i,JSON.stringify({ownerNonce:t,expiresAt:r+1e4}))}catch{o=!0;break}if(await _(20+Math.random()*40),v()?.ownerNonce!==t)await S(500);else{u=t;try{return await x(e)}finally{u=null,y(t)}}}}return x(e)};return{ready:g,async get(){return await g,m(p(),`external`),l},async set(e){await g;let t=f();if(t)try{t.setItem(r,e)}catch{o=!0}m(e,`local`)},async clear(){await g;let e=f();if(e)try{e.removeItem(r)}catch{o=!0}m(null,`local`)},revision(){return c},subscribe(e){return d.add(e),()=>{d.delete(e)}},async withFirstInitLock(e){await g;let t=globalThis.navigator?.locks;return t?.request?t.request(a,()=>x(e)):f()?C(e):x(e)},matches(r,i,a){return r===e&&i===t&&a===n},destroy(){s=!0,d.clear(),typeof window<`u`&&window.removeEventListener(`storage`,h),u&&y(u);for(let e of[...b])e()}}};Pt();const{setLoader:Tv,load:Ev}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/history-view`)}),Dv=Ev;function Ov(){return null}function kv(e){if(!e||typeof e!=`object`||!(`component`in e))return!1;let t=e.component;return typeof t==`string`&&t.length>0}function Av(e,t){if(!kv(e))return null;let n=e.props&&typeof e.props==`object`&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function jv(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith(`{`)&&!r.startsWith(`[`))return null;if(n.length<=t)return e;try{let t=Av(kt(n,Ot|Dt),n);t&&(e=t)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Mv(e){return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`&&`props`in e&&typeof e.props==`object`}Y();function Nv(e,t){let{config:n,message:r,onPropsUpdate:i}=t,a=n_.get(e.component);if(!a){if(r_.includes(e.component)){d_().catch(()=>{});let e=q(`div`,`persona-w-full`);return e.setAttribute(`data-persona-artifact-pending`,`true`),e}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let o={message:r,config:n,updateProps:e=>{i&&i(e)}};try{return a(e.props,o)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function Pv(){let e=jv();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Fv(e){if(typeof e.rawContent==`string`&&e.rawContent.length>0)return e.rawContent;if(typeof e.content==`string`){let t=e.content.trim();if(t.startsWith(`{`)||t.startsWith(`[`))return e.content}return null}function Iv(e){let t=Fv(e);if(!t)return!1;try{let e=JSON.parse(t);return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`}catch{return!1}}function Lv(e){let t=Fv(e);if(!t)return null;try{let e=JSON.parse(t);if(typeof e==`object`&&e&&`component`in e&&typeof e.component==`string`){let n=e;return{component:n.component,props:n.props&&typeof n.props==`object`&&n.props!==null?n.props:{},raw:t}}}catch{}return null}const Rv=[`Very dissatisfied`,`Dissatisfied`,`Neutral`,`Satisfied`,`Very satisfied`];function zv(e){let{onSubmit:t,onDismiss:n,title:r=`How satisfied are you?`,subtitle:i=`Please rate your experience`,commentPlaceholder:a=`Share your thoughts (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,ratingLabels:l=Rv}=e,u=document.createElement(`div`);u.className=`persona-feedback-container persona-feedback-csat`,u.setAttribute(`role`,`dialog`),u.setAttribute(`aria-label`,`Customer satisfaction feedback`);let d=null,f=document.createElement(`div`);f.className=`persona-feedback-content`;let p=document.createElement(`div`);p.className=`persona-feedback-header`;let m=document.createElement(`h3`);m.className=`persona-feedback-title`,m.textContent=r,p.appendChild(m);let h=document.createElement(`p`);h.className=`persona-feedback-subtitle`,h.textContent=i,p.appendChild(h),f.appendChild(p);let g=document.createElement(`div`);g.className=`persona-feedback-rating persona-feedback-rating-csat`,g.setAttribute(`role`,`radiogroup`),g.setAttribute(`aria-label`,`Satisfaction rating from 1 to 5`);let _=[];for(let e=1;e<=5;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-star-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`${e} star${e>1?`s`:``}: ${l[e-1]}`),t.title=l[e-1],t.dataset.rating=String(e),t.innerHTML=`
|
|
36
|
+
`):``},Zg=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??`var(--persona-container, #f3f4f6)`,e.style.borderColor=t.codeBlockBorderColor??`var(--persona-border, #e5e7eb)`,e.style.color=t.codeBlockTextColor??`var(--persona-text, #171717)`},Qg=(e,t)=>{let n=e.toolCall,r=t?.features?.toolCallDisplay,i=r?.collapsedMode??To.collapsedMode,a=n?.success===!1?n.error||`Tool failed`:Xg(e,r?.previewMaxLines??To.previewMaxLines),o=n?.interrupted?`${n.name?.trim()||`Tool`} · Interrupted`:n?wl(t,`tool`)===`row`?`${n.status===`complete`?`Used`:`Using`} ${n.name?.trim()||`tool`}`:Bn(n):``;if(!n)return{summary:o,previewText:a,isActive:!1};let s=n.status!==`complete`,c=t?.toolCall??{},l=o;return i===`tool-name`?l=n.name?.trim()||o:i===`tool-preview`&&a&&(l=a),s&&c.activeTextTemplate?l=Wn(n,c.activeTextTemplate,l):!s&&!n.interrupted&&c.completeTextTemplate&&(l=Wn(n,c.completeTextTemplate,l)),n.interrupted?l.includes(` · Interrupted`)||(l+=` · Interrupted`):n.success===!1?l+=` · Failed`:n.superseded&&(l+=` · Approved, ran again below`),{summary:l,previewText:a,isActive:s}},$g=(e,t,n,r)=>{Sl(e,t,{stateSet:n,previewKind:`tool`,iconColor:Yg(r?.toolCall??{},t.classList.contains(`persona-activity-row`))})},e_=(e,t,n=/* @__PURE__ */ new Set)=>{t=Cl(t,`tool`);let r=e.toolCall,i=t?.toolCall??{},a=gl(`persona-tool-bubble`,e.id);if(i.backgroundColor&&(a.style.backgroundColor=i.backgroundColor),i.borderColor&&(a.style.borderColor=i.borderColor),i.borderWidth&&(a.style.borderWidth=i.borderWidth),i.borderRadius&&(a.style.borderRadius=i.borderRadius),a.style.boxShadow=i.shadow===void 0?`var(--persona-tool-bubble-shadow)`:i.shadow.trim()===``?`none`:i.shadow,!r)return El(a,e,t,`tool`);let o=t?.features?.toolCallDisplay??{},s=o.expandable??To.expandable,c=s&&n.has(e.id),{summary:l,previewText:u,isActive:d}=Qg(e,t),f=_l({expandable:s,expanded:c,bubbleType:`tool`});i.headerBackgroundColor&&(f.style.backgroundColor=i.headerBackgroundColor),i.headerPaddingX&&(f.style.paddingLeft=i.headerPaddingX,f.style.paddingRight=i.headerPaddingX),i.headerPaddingY&&(f.style.paddingTop=i.headerPaddingY,f.style.paddingBottom=i.headerPaddingY);let p=q(`div`,`persona-flex persona-flex-col persona-text-left`),m=q(`span`,`persona-text-xs persona-text-persona-primary`);i.headerTextColor&&(m.style.color=i.headerTextColor);let h=String(r.startedAt??Date.now()),g=()=>{let e=q(`span`,``);return d&&e.setAttribute(`data-tool-elapsed`,h),e.textContent=Hn(r),e},_=i.renderCollapsedSummary?.({message:e,toolCall:r,defaultSummary:l,previewText:u,collapsedMode:o.collapsedMode??To.collapsedMode,isActive:d,config:t??{},elapsed:Hn(r),createElapsedElement:g});typeof _==`string`&&_.trim()?(m.textContent=_,p.appendChild(m)):_ instanceof HTMLElement?p.appendChild(_):(m.textContent=l,p.appendChild(m));let v=o.loadingAnimation??To.loadingAnimation,y=i.activeTextTemplate,b=r.interrupted?void 0:i.completeTextTemplate,x=d?y:b,S=_ instanceof HTMLElement,C=(e,t)=>{m.textContent=``;let n=r.name?.trim()||`tool`,i=Gn(e,n),a=0;for(let e of i){let n=e.styles.length>0?(()=>{let t=q(`span`,e.styles.map(e=>`persona-tool-text-${e}`).join(` `));return m.appendChild(t),t})():m;if(e.isDuration&&d)n.appendChild(g());else{let i=e.isDuration?Hn(r):e.text;t?a=Bg(n,i,a):n.appendChild(document.createTextNode(i))}}};if(!S){if(d&&v!==`none`){let e=i.loadingAnimationDuration??2e3;if(m.setAttribute(`data-preserve-animation`,`true`),v===`pulse`)m.classList.add(`persona-tool-loading-pulse`),m.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),x&&C(x,!1);else if(m.classList.add(`persona-tool-loading-${v}`),m.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),v===`shimmer-color`&&(i.loadingAnimationColor&&m.style.setProperty(`--persona-tool-anim-color`,i.loadingAnimationColor),i.loadingAnimationSecondaryColor&&m.style.setProperty(`--persona-tool-anim-secondary-color`,i.loadingAnimationSecondaryColor)),x)C(x,!0);else{let e=m.textContent||l;m.textContent=``,Bg(m,e,0)}}else x&&C(x,!1)}let w=Yg(i,wl(t,`tool`)===`row`),T=yl(f,p,{expandable:s,expanded:c,iconColor:w,metaGap:!0}),E=bl({bubble:a,previewKind:`tool`,expanded:c,isActive:d,previewText:u,activePreview:o.activePreview,activeMinHeight:o.activeMinHeight,renderPreview:()=>i.renderCollapsedPreview?.({message:e,toolCall:r,defaultPreview:u,isActive:d,config:t??{}})});if(!s)return a.append(f,E),El(a,e,t,`tool`);let D=q(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3`);if(D.style.display=c?``:`none`,i.contentBackgroundColor&&(D.style.backgroundColor=i.contentBackgroundColor),i.contentTextColor&&(D.style.color=i.contentTextColor),i.contentPaddingX&&(D.style.paddingLeft=i.contentPaddingX,D.style.paddingRight=i.contentPaddingX),i.contentPaddingY&&(D.style.paddingTop=i.contentPaddingY,D.style.paddingBottom=i.contentPaddingY),t.future?.v5Defaults===!0)Kg(D,e,t);else{if(r.name){let e=q(`div`,`persona-text-xs persona-text-persona-muted persona-italic`);i.contentTextColor?e.style.color=i.contentTextColor:i.headerTextColor&&(e.style.color=i.headerTextColor),e.textContent=r.name,D.appendChild(e)}if(r.args!==void 0){let e=q(`div`,`persona-space-y-1`),t=q(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Arguments`;let n=q(`pre`,`persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,Zg(n,i),n.textContent=Fn(r.args),e.append(t,n),D.appendChild(e)}if(r.chunks&&r.chunks.length){let e=q(`div`,`persona-space-y-1`),t=q(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Activity`;let n=q(`pre`,`persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,Zg(n,i),n.textContent=r.chunks.join(``),e.append(t,n),D.appendChild(e)}if(r.success===!1&&D.appendChild(J(`div`,{className:`persona-text-sm persona-whitespace-pre-wrap`,text:r.error||`Tool failed`,attrs:{"data-persona-tool-error":``}})),r.status===`complete`&&r.result!==void 0){let e=q(`div`,`persona-space-y-1`),t=q(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Result`;let n=q(`pre`,`persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,Zg(n,i),n.textContent=Fn(r.result),e.append(t,n),D.appendChild(e)}if(r.status===`complete`&&typeof r.duration==`number`){let e=q(`div`,`persona-text-xs persona-text-persona-muted`);i.contentTextColor&&(e.style.color=i.contentTextColor),e.textContent=`Duration: ${r.duration}ms`,D.appendChild(e)}}return xl({expanded:c,header:f,toggleIcon:T,content:D,collapsedPreview:E,iconColor:w}),a.append(f,E,D),El(a,e,t,`tool`)};Pt();const{setLoader:t_,load:n_,provide:r_,getSync:i_}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/approval-ui`)}),a_=n_,o_=i_;Pt();const{setLoader:s_,load:c_}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/event-stream-view`)}),l_=c_,u_=new class{constructor(){this.components=/* @__PURE__ */ new Map,this.#e=/* @__PURE__ */ new Map}#e;register(e,t,n){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t),n?this.#e.set(e,n):this.#e.delete(e)}unregister(e){this.components.delete(e),this.#e.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.#e.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.#e.clear()}registerAll(e){Object.entries(e).forEach(([e,t])=>{this.register(e,t)})}};Pt(),$t();const d_=[`PersonaArtifactCard`,`PersonaArtifactInline`],{setLoader:f_,load:p_,provide:m_,getSync:h_}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/artifacts-ui`)});let g_=null;const __=/* @__PURE__ */ new Set,v_=e=>{if(g_)return g_;g_=e,e.initArtifactsUi({componentRegistry:u_});for(let t of d_)u_.has(t)||u_.register(t,t===`PersonaArtifactCard`?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Kt();t?e.__provideMarkdownParsers(t):Wt(()=>{let t=Kt();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader(()=>Qt());let n=[...__];__.clear();for(let e of n)try{e()}catch{}return e},y_=()=>p_().then(v_),b_=()=>{if(g_)return g_;let e=h_();return e?v_(e):null},x_=e=>g_?()=>{}:(__.add(e),()=>{__.delete(e)});function S_(e){return e?.features?.artifacts?.enabled===!0}function C_(e,t){if(e.classList.remove(`persona-artifact-border-full`,`persona-artifact-border-left`),e.style.removeProperty(`--persona-artifact-pane-border`),e.style.removeProperty(`--persona-artifact-pane-border-left`),!S_(t))return;let n=t.features?.artifacts?.layout,r=n?.paneBorder?.trim(),i=n?.paneBorderLeft?.trim();r?(e.classList.add(`persona-artifact-border-full`),e.style.setProperty(`--persona-artifact-pane-border`,r)):i&&(e.classList.add(`persona-artifact-border-left`),e.style.setProperty(`--persona-artifact-pane-border-left`,i))}function w_(e){e.style.removeProperty(`--persona-artifact-doc-toolbar-icon-color`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-bg`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-border`)}const T_=[`panel`,`seamless`,`detached`];function E_(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&T_.includes(t)?t:t?`panel`:e.launcher?.detachedPanel?`detached`:`panel`}function D_(e){return!e||!S_(e)?!1:E_(e)===`detached`}function O_(e,t){if(!S_(t)){e.style.removeProperty(`--persona-artifact-split-gap`),e.style.removeProperty(`--persona-artifact-pane-width`),e.style.removeProperty(`--persona-artifact-pane-max-width`),e.style.removeProperty(`--persona-artifact-pane-min-width`),e.style.removeProperty(`--persona-artifact-drawer-width`),e.style.removeProperty(`--persona-artifact-pane-bg`),e.style.removeProperty(`--persona-artifact-pane-padding`),w_(e),C_(e,t);return}let n=t.features?.artifacts?.layout,r=E_(t)===`detached`?`var(--persona-panel-inset)`:`0`;e.style.setProperty(`--persona-artifact-split-gap`,n?.splitGap??r),e.style.setProperty(`--persona-artifact-pane-width`,n?.paneWidth??`40%`),e.style.setProperty(`--persona-artifact-pane-max-width`,n?.paneMaxWidth??`28rem`),n?.drawerWidth?e.style.setProperty(`--persona-artifact-drawer-width`,n.drawerWidth):e.style.removeProperty(`--persona-artifact-drawer-width`),n?.paneMinWidth?e.style.setProperty(`--persona-artifact-pane-min-width`,n.paneMinWidth):e.style.removeProperty(`--persona-artifact-pane-min-width`);let i=n?.paneBackground?.trim();i?e.style.setProperty(`--persona-artifact-pane-bg`,i):e.style.removeProperty(`--persona-artifact-pane-bg`);let a=n?.panePadding?.trim();a?e.style.setProperty(`--persona-artifact-pane-padding`,a):e.style.removeProperty(`--persona-artifact-pane-padding`);let o=[[n?.documentToolbarIconColor,`--persona-artifact-doc-toolbar-icon-color`],[n?.documentToolbarToggleActiveBackground,`--persona-artifact-doc-toggle-active-bg`],[n?.documentToolbarToggleActiveBorderColor,`--persona-artifact-doc-toggle-active-border`],[n?.documentToolbarToggleActiveColor,`--persona-artifact-doc-toggle-active-color`]];for(let[t,n]of o){let r=t?.trim();r?e.style.setProperty(n,r):e.style.removeProperty(n)}C_(e,t)}function k_(e,t){for(let t of T_)e.classList.remove(`persona-artifact-appearance-${t}`);if(e.style.removeProperty(`--persona-artifact-pane-radius`),e.style.removeProperty(`--persona-artifact-pane-shadow`),e.style.removeProperty(`--persona-artifact-chat-shadow`),!S_(t))return;let n=t.features?.artifacts?.layout,r=E_(t);e.classList.add(`persona-artifact-appearance-${r}`);let i=n?.paneBorderRadius?.trim();i&&e.style.setProperty(`--persona-artifact-pane-radius`,i);let a=n?.paneShadow?.trim();a&&e.style.setProperty(`--persona-artifact-pane-shadow`,a);let o=n?.chatShadow?.trim();o&&e.style.setProperty(`--persona-artifact-chat-shadow`,o)}function A_(e,t){return!t||!S_(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}Nn();const j_=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`]),M_=/* @__PURE__ */ new Set([`collapsed`,`card`,`panel`,`inline`]),N_=/* @__PURE__ */ new Set([`markdown`,`component`]),P_=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,F_=e=>typeof e==`object`&&!!e&&!Array.isArray(e),I_=e=>!j_.has(e),L_=e=>typeof e==`string`&&M_.has(e),R_=e=>Object.keys(e).length>0;function z_(e,t,n,r){e.push({path:t,code:n,message:r})}const B_=`Ignored an unsupported value.`,V_={kind:`mode`,message:B_},H_={kind:`string`,message:`Expected a CSS length string.`},U_={kind:`boolean`},W_={kind:`object`,message:`Expected a preference object.`,children:{showToolCalls:U_,showReasoning:U_,toolCallDisplay:{kind:`object`,children:{collapsedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`tool-call`,`tool-name`,`tool-preview`]),message:B_},groupedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`stack`,`summary`]),message:B_},loadingAnimation:{kind:`enum`,values:/* @__PURE__ */ new Set([`none`,`pulse`,`shimmer`,`shimmer-color`,`rainbow`]),message:B_},expandable:U_,grouped:U_}},reasoningDisplay:{kind:`object`,children:{expandable:U_,activePreview:U_}},artifacts:{kind:`object`,children:{display:{kind:`object`,bareMode:!0,message:`Expected an artifact display rules object.`,children:{default:V_,files:{kind:`object`,bareMode:!0,message:`Expected collapsed, panel, inline, or a file display rules object.`,children:{default:V_,byMediaType:{kind:`modeMap`,keys:`mediaType`}}},byType:{kind:`modeMap`,keys:N_,alias:`byKind`,deprecated:`Use byKind. The legacy selector was normalized automatically.`},byKind:{kind:`modeMap`,keys:N_}}},filePreview:{kind:`object`,children:{enabled:U_}},layout:{kind:`object`,children:{paneWidth:H_,paneMaxWidth:H_,paneMinWidth:H_,expandedPanelWidth:H_,resizableMinWidth:H_,resizableMaxWidth:H_,expandLauncherPanelWhenOpen:U_,resizable:U_}}}}}};function G_(e,t,n,r){if(e!==void 0)switch(t.kind){case`boolean`:return typeof e==`boolean`?e:z_(r,n,`invalid_type`,`Expected a boolean.`);case`string`:return typeof e==`string`?e:z_(r,n,`invalid_type`,t.message);case`enum`:return typeof e==`string`&&t.values.has(e)?e:z_(r,n,`invalid_value`,t.message);case`mode`:return L_(e)?Dn(e):z_(r,n,`invalid_value`,t.message);case`modeMap`:{if(!F_(e))return z_(r,n,`invalid_type`,`Expected an object.`);let i=t.keys===`mediaType`?void 0:t.keys,a={};for(let[t,o]of Object.entries(e)){let e=i?t:On(t);I_(t)&&(i?i.has(t):P_.test(e))?L_(o)?a[e]=Dn(o):z_(r,`${n}.${t}`,`invalid_value`,`Expected collapsed, panel, or inline.`):z_(r,`${n}.${t}`,i?`unknown_key`:`invalid_value`,i?`Ignored an unsupported selector.`:`Expected a MIME type such as "text/html" or a wildcard such as "image/*".`)}return R_(a)?a:void 0}case`object`:{if(t.bareMode&&L_(e))return Dn(e);if(!F_(e))return z_(r,n,`invalid_type`,t.message??`Expected an object.`);let i=Object.keys(t.children),a=e=>n?`${n}.${e}`:e;for(let t of Object.keys(e))(!I_(t)||!i.includes(t))&&z_(r,a(t),`unknown_key`,`Ignored because this key is not part of the persisted preference schema.`);let o={};for(let n of i){let i=t.children[n],s=G_(e[n],i,a(n),r);if(i.deprecated&&e[n]!==void 0&&z_(r,a(n),`deprecated_key`,i.deprecated),s===void 0)continue;let c=i.alias??n,l=o[c];o[c]=F_(l)&&F_(s)?{...l,...s}:s}return R_(o)?o:void 0}}}function K_(e){let t=[];return{preferences:(e===null?void 0:G_(e,W_,``,t))??{},issues:t}}function q_(e){if(Array.isArray(e))return e.map(q_);if(!F_(e))return e;let t={};for(let[n,r]of Object.entries(e))I_(n)&&r!==void 0&&(t[n]=q_(r));return t}function J_(e,t){let n=q_(e);for(let[e,r]of Object.entries(t)){if(!I_(e)||r===void 0)continue;let t=n[e];n[e]=F_(t)&&F_(r)?J_(t,r):q_(r)}return n}function Y_(e){let t={},n;for(let r of e){let e=K_(r).preferences;n=Z_(n,e.artifacts?.display),t=J_(t,e)}let r=t;return r.artifacts&&(n===void 0?delete r.artifacts.display:r.artifacts.display=n),r}function X_(e,t){if(t===void 0)return e===void 0?void 0:q_(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byMediaType,...t.byMediaType},a={...r?{default:r}:{},...R_(i)?{byMediaType:i}:{}};return R_(a)?a:void 0}function Z_(e,t){if(t===void 0)return e===void 0?void 0:q_(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byType,...n.byKind,...t.byType,...t.byKind},a=X_(n.files,t.files),o={...r?{default:r}:{},...R_(i)?{byKind:i}:{},...a===void 0?{}:{files:a}};return R_(o)?o:void 0}function Q_(e={},t){let n=Y_(t),r={...e};if(n.showToolCalls!==void 0&&(r.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(r.showReasoning=n.showReasoning),n.toolCallDisplay&&(r.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(r.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let t=e.artifacts??{},i={...t};if(n.artifacts.display!==void 0){let e=Z_(t.display,n.artifacts.display);e!==void 0&&(i.display=e)}n.artifacts.filePreview&&(i.filePreview={...t.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...t.layout,...n.artifacts.layout}),r.artifacts=i}return r}function $_(e){let t=e.preferences;return!t||!R_(t)?e:{...e,features:Q_(e.features??{},[t])}}function ev(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function tv(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function nv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function rv(e,t,n,r){let i=e-r-2*t-n;return Math.max(0,i)}function iv(e,t){let n=(t.getComputedStyle(e).gap||`0px`).trim().split(/\s+/)[0]??`0px`,r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let i=/^([\d.]+)/.exec(n);return i?Number(i[1]):8}function av(e,t,n,r,i,a,o=200){let s=ev(i,200),c=rv(t,n,r,o);c=Math.max(s,c);let l=tv(a);return l!==null&&(c=Math.min(c,l)),nv(e,s,c)}Pt();const{setLoader:ov,load:sv,provide:cv,getSync:lv}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/forms-ui`)}),uv=sv,dv=lv,fv=new class{#e=/* @__PURE__ */ new Map;register(e){this.#e.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.#e.set(e.id,e),e.onRegister?.()}unregister(e){let t=this.#e.get(e);t&&(t.onUnregister?.(),this.#e.delete(e))}getAll(){return Array.from(this.#e.values()).sort((e,t)=>(t.priority??0)-(e.priority??0))}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let n=new Set(e.map(e=>e.id));return[...t.filter(e=>!n.has(e.id)),...e].sort((e,t)=>(t.priority??0)-(e.priority??0))}clear(){this.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}};No(),go(),oo();const pv=e=>typeof e==`object`&&!!e&&!Array.isArray(e),mv=/* @__PURE__ */ new Set([`headers`,`agent`,`storageAdapter`,`components`,`targetProviders`,`voiceRecognition.provider.custom`,`features.artifacts.display`,`features.streamAnimation.plugins`,`preferences`,`welcome.icon`]),hv=(e,t,n)=>{if(!pv(e)||!pv(t)||mv.has(n))return t;let r={...e};for(let i of Object.keys(t)){if(t[i]===void 0){delete r[i];continue}let a=n?`${n}.${i}`:i;r[i]=hv(e[i],t[i],a)}return r};function gv(e,t){let n=Za(jo),r=no(e,t,n),i=eo(ro(hv(e,t,``),n,r),r);return po(bo(i),ho(e,t))}const _v=()=>{let e=/* @__PURE__ */ new Map,t=(t,r)=>(e.has(t)||e.set(t,/* @__PURE__ */ new Set),e.get(t).add(r),()=>n(t,r)),n=(t,n)=>{e.get(t)?.delete(n)};return{on:t,off:n,emit:(t,n)=>{e.get(t)?.forEach(e=>{try{e(n)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Event handler error:`,e)}})}}},vv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},yv=e=>{let t=e.trim(),n=t.indexOf(`{`);if(n===-1)return null;let r=0;for(let e=n;e<t.length;e+=1){let i=t[e];if(i===`{`&&(r+=1),i===`}`&&(--r,r===0))return t.slice(n,e+1)}return null},bv=({text:e})=>{if(!e||!e.includes(`{`))return null;try{let t=vv(e),n=yv(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!=`object`||!r.action)return null;let{action:i,...a}=r;return{type:String(i),payload:a,raw:r}}catch{return null}},xv=e=>typeof e==`string`?e:e==null?``:String(e),Sv={message:e=>{if(e.type===`message`)return{handled:!0,displayText:xv(e.payload.text)}},messageAndClick:(e,t)=>{if(e.type!==`message_and_click`)return;let n=e.payload,r=xv(n.element);if(r&&t.document?.querySelector){let e=t.document.querySelector(r);e?setTimeout(()=>{e.click()},400):typeof console<`u`&&console.warn(`[AgentWidget] Element not found for selector:`,r)}return{handled:!0,displayText:xv(n.text)}}},Cv=e=>Array.isArray(e)?e.map(e=>String(e)):[],wv=e=>{let t=new Set(Cv(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Cv(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let n=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:n}))};return{process:n=>{if(n.streaming||n.message.role!==`assistant`||!n.text||t.has(n.message.id))return null;let i=typeof n.raw==`string`&&n.raw||typeof n.message.rawContent==`string`&&n.message.rawContent||typeof n.text==`string`&&n.text||null;!i&&typeof n.text==`string`&&n.text.trim().startsWith(`{`)&&typeof console<`u`&&console.warn(`[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.`);let a=i?e.parsers.reduce((e,t)=>e||t?.({text:i,message:n.message})||null,null):null;if(!a)return null;t.add(n.message.id),r();let o={action:a,message:n.message};e.emit(`action:detected`,o);for(let t of e.handlers)if(t)try{let r=t(a,{message:n.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{e.emit(`action:resubmit`,o)}});if(!r)continue;if(r.handled){let e=r.persistMessage!==!1;return{text:r.displayText===void 0?``:r.displayText,persist:e,resubmit:r.resubmit}}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Action handler error:`,e)}return{text:``,persist:!0}},syncFromMetadata:n}},Tv=e=>{if(!e)return null;try{return JSON.parse(e)}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] Failed to parse stored state:`,e),null}},Ev=e=>e.map(e=>({...e,streaming:!1})),Dv=e=>e.map(e=>({...e,status:`complete`})),Ov=e=>`${e??`persona-`}state`,kv=(e=Ov())=>{let t=()=>typeof window>`u`||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Tv(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let t={...n,messages:n.messages?Ev(n.messages):void 0,artifacts:n.artifacts?Dv(n.artifacts):void 0};r.setItem(e,JSON.stringify(t))}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to persist state:`,e)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to clear stored state:`,e)}}}},Av=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,`0`)},jv=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let n=await t.digest(`SHA-256`,new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}catch{}return Av(e)},Mv=async(e,t)=>{let n=await jv(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await jv(`${e}\0${t}`)}`}},Nv=(e,t,n)=>{let r=``,i=``,a=``,o=!1,s=!1,c=0,l=null,u=null,d=/* @__PURE__ */ new Set,f=()=>{if(n||o)return null;try{return typeof window>`u`||!window.localStorage?null:window.localStorage}catch{return o=!0,null}},p=()=>{let e=f();if(!e)return l;try{return e.getItem(r)}catch{return o=!0,l}},m=(e,t)=>{if(s||e===l)return;let n=l;l=e,c+=1;let r={previousToken:n,token:e,source:t,revision:c};for(let e of d)e(r)},h=e=>{s||(e.key===null||e.key===r)&&m(e.key===null?null:e.newValue??null,`external`)},g=(async()=>{let o=await Mv(e,t);r=o.storageKey,i=o.leaseKey,a=o.lockName,l=p(),!n&&typeof window<`u`&&window.addEventListener(`storage`,h)})(),_=e=>new Promise(t=>setTimeout(t,e)),v=()=>{let e=f();if(!e)return null;try{let t=e.getItem(i);if(!t)return null;let n=JSON.parse(t);return typeof n?.expiresAt==`number`&&typeof n?.ownerNonce==`string`?n:null}catch{return null}},y=e=>{let t=f();if(t)try{v()?.ownerNonce===e&&t.removeItem(i)}catch{}},b=/* @__PURE__ */ new Set,x=e=>s?Promise.reject(/* @__PURE__ */ Error(`Visitor store destroyed before its first init could start`)):e(),S=e=>new Promise(t=>{let n=setTimeout(r,e);function r(){clearTimeout(n),b.delete(r),window.removeEventListener(`storage`,a),t()}function a(e){(e.key===null||e.key===i)&&r()}b.add(r),window.addEventListener(`storage`,a)}),C=async e=>{let t=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,n=Date.now()+15e3;for(;!s&&Date.now()<n;){let n=f();if(!n)break;let r=Date.now(),a=v();if(a&&a.expiresAt>r&&a.ownerNonce!==t)await S(Math.min(a.expiresAt-r,500));else{try{n.setItem(i,JSON.stringify({ownerNonce:t,expiresAt:r+1e4}))}catch{o=!0;break}if(await _(20+Math.random()*40),v()?.ownerNonce!==t)await S(500);else{u=t;try{return await x(e)}finally{u=null,y(t)}}}}return x(e)};return{ready:g,async get(){return await g,m(p(),`external`),l},async set(e){await g;let t=f();if(t)try{t.setItem(r,e)}catch{o=!0}m(e,`local`)},async clear(){await g;let e=f();if(e)try{e.removeItem(r)}catch{o=!0}m(null,`local`)},revision(){return c},subscribe(e){return d.add(e),()=>{d.delete(e)}},async withFirstInitLock(e){await g;let t=globalThis.navigator?.locks;return t?.request?t.request(a,()=>x(e)):f()?C(e):x(e)},matches(r,i,a){return r===e&&i===t&&a===n},destroy(){s=!0,d.clear(),typeof window<`u`&&window.removeEventListener(`storage`,h),u&&y(u);for(let e of[...b])e()}}};Pt();const{setLoader:Pv,load:Fv}=Nt({fallbackImport:()=>import(`@runtypelabs/persona/history-view`)}),Iv=Fv;function Lv(){return null}function Rv(e){if(!e||typeof e!=`object`||!(`component`in e))return!1;let t=e.component;return typeof t==`string`&&t.length>0}function zv(e,t){if(!Rv(e))return null;let n=e.props&&typeof e.props==`object`&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function Bv(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith(`{`)&&!r.startsWith(`[`))return null;if(n.length<=t)return e;try{let t=zv(kt(n,Ot|Dt),n);t&&(e=t)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Vv(e){return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`&&`props`in e&&typeof e.props==`object`}Y();function Hv(e,t){let{config:n,message:r,onPropsUpdate:i}=t,a=u_.get(e.component);if(!a){if(d_.includes(e.component)){y_().catch(()=>{});let e=q(`div`,`persona-w-full`);return e.setAttribute(`data-persona-artifact-pending`,`true`),e}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let o={message:r,config:n,updateProps:e=>{i&&i(e)}};try{return a(e.props,o)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function Uv(){let e=Bv();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Wv(e){if(typeof e.rawContent==`string`&&e.rawContent.length>0)return e.rawContent;if(typeof e.content==`string`){let t=e.content.trim();if(t.startsWith(`{`)||t.startsWith(`[`))return e.content}return null}function Gv(e){let t=Wv(e);if(!t)return!1;try{let e=JSON.parse(t);return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`}catch{return!1}}function Kv(e){let t=Wv(e);if(!t)return null;try{let e=JSON.parse(t);if(typeof e==`object`&&e&&`component`in e&&typeof e.component==`string`){let n=e;return{component:n.component,props:n.props&&typeof n.props==`object`&&n.props!==null?n.props:{},raw:t}}}catch{}return null}const qv=[`Very dissatisfied`,`Dissatisfied`,`Neutral`,`Satisfied`,`Very satisfied`];function Jv(e){let{onSubmit:t,onDismiss:n,title:r=`How satisfied are you?`,subtitle:i=`Please rate your experience`,commentPlaceholder:a=`Share your thoughts (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,ratingLabels:l=qv}=e,u=document.createElement(`div`);u.className=`persona-feedback-container persona-feedback-csat`,u.setAttribute(`role`,`dialog`),u.setAttribute(`aria-label`,`Customer satisfaction feedback`);let d=null,f=document.createElement(`div`);f.className=`persona-feedback-content`;let p=document.createElement(`div`);p.className=`persona-feedback-header`;let m=document.createElement(`h3`);m.className=`persona-feedback-title`,m.textContent=r,p.appendChild(m);let h=document.createElement(`p`);h.className=`persona-feedback-subtitle`,h.textContent=i,p.appendChild(h),f.appendChild(p);let g=document.createElement(`div`);g.className=`persona-feedback-rating persona-feedback-rating-csat`,g.setAttribute(`role`,`radiogroup`),g.setAttribute(`aria-label`,`Satisfaction rating from 1 to 5`);let _=[];for(let e=1;e<=5;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-star-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`${e} star${e>1?`s`:``}: ${l[e-1]}`),t.title=l[e-1],t.dataset.rating=String(e),t.innerHTML=`
|
|
37
37
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
38
38
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
39
39
|
</svg>
|
|
40
|
-
`,t.addEventListener(`click`,()=>{d=e,_.forEach((t,n)=>{let r=n<e;t.classList.toggle(`selected`,r),t.setAttribute(`aria-checked`,n===e-1?`true`:`false`)})}),_.push(t),g.appendChild(t)}f.appendChild(g);let v=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,v=document.createElement(`textarea`),v.className=`persona-feedback-comment`,v.placeholder=a,v.rows=3,v.setAttribute(`aria-label`,`Additional comments`),e.appendChild(v),f.appendChild(e)}let y=document.createElement(`div`);y.className=`persona-feedback-actions`;let b=document.createElement(`button`);b.type=`button`,b.className=`persona-feedback-btn persona-feedback-btn-skip`,b.textContent=s,b.addEventListener(`click`,()=>{n?.(),u.remove()});let x=document.createElement(`button`);return x.type=`button`,x.className=`persona-feedback-btn persona-feedback-btn-submit`,x.textContent=o,x.addEventListener(`click`,async()=>{if(d===null)g.classList.add(`persona-feedback-shake`),setTimeout(()=>g.classList.remove(`persona-feedback-shake`),500);else{x.disabled=!0,x.textContent=`Submitting...`;try{let e=v?.value.trim()||void 0;await t(d,e),u.remove()}catch(e){x.disabled=!1,x.textContent=o,console.error(`[CSAT Feedback] Failed to submit:`,e)}}}),y.appendChild(b),y.appendChild(x),f.appendChild(y),u.appendChild(f),u}function Bv(e){let{onSubmit:t,onDismiss:n,title:r=`How likely are you to recommend us?`,subtitle:i=`On a scale of 0 to 10`,commentPlaceholder:a=`What could we do better? (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,lowLabel:l=`Not likely`,highLabel:u=`Very likely`}=e,d=document.createElement(`div`);d.className=`persona-feedback-container persona-feedback-nps`,d.setAttribute(`role`,`dialog`),d.setAttribute(`aria-label`,`Net Promoter Score feedback`);let f=null,p=document.createElement(`div`);p.className=`persona-feedback-content`;let m=document.createElement(`div`);m.className=`persona-feedback-header`;let h=document.createElement(`h3`);h.className=`persona-feedback-title`,h.textContent=r,m.appendChild(h);let g=document.createElement(`p`);g.className=`persona-feedback-subtitle`,g.textContent=i,m.appendChild(g),p.appendChild(m);let _=document.createElement(`div`);_.className=`persona-feedback-rating persona-feedback-rating-nps`,_.setAttribute(`role`,`radiogroup`),_.setAttribute(`aria-label`,`Likelihood rating from 0 to 10`);let v=document.createElement(`div`);v.className=`persona-feedback-labels`;let y=document.createElement(`span`);y.className=`persona-feedback-label-low`,y.textContent=l;let b=document.createElement(`span`);b.className=`persona-feedback-label-high`,b.textContent=u,v.appendChild(y),v.appendChild(b);let x=document.createElement(`div`);x.className=`persona-feedback-numbers`;let S=[];for(let e=0;e<=10;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-number-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`Rating ${e} out of 10`),t.textContent=String(e),t.dataset.rating=String(e),e<=6?t.classList.add(`persona-feedback-detractor`):e<=8?t.classList.add(`persona-feedback-passive`):t.classList.add(`persona-feedback-promoter`),t.addEventListener(`click`,()=>{f=e,S.forEach((t,n)=>{t.classList.toggle(`selected`,n===e),t.setAttribute(`aria-checked`,n===e?`true`:`false`)})}),S.push(t),x.appendChild(t)}_.appendChild(v),_.appendChild(x),p.appendChild(_);let C=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,C=document.createElement(`textarea`),C.className=`persona-feedback-comment`,C.placeholder=a,C.rows=3,C.setAttribute(`aria-label`,`Additional comments`),e.appendChild(C),p.appendChild(e)}let w=document.createElement(`div`);w.className=`persona-feedback-actions`;let T=document.createElement(`button`);T.type=`button`,T.className=`persona-feedback-btn persona-feedback-btn-skip`,T.textContent=s,T.addEventListener(`click`,()=>{n?.(),d.remove()});let E=document.createElement(`button`);return E.type=`button`,E.className=`persona-feedback-btn persona-feedback-btn-submit`,E.textContent=o,E.addEventListener(`click`,async()=>{if(f===null)x.classList.add(`persona-feedback-shake`),setTimeout(()=>x.classList.remove(`persona-feedback-shake`),500);else{E.disabled=!0,E.textContent=`Submitting...`;try{let e=C?.value.trim()||void 0;await t(f,e),d.remove()}catch(e){E.disabled=!1,E.textContent=o,console.error(`[NPS Feedback] Failed to submit:`,e)}}}),w.appendChild(T),w.appendChild(E),p.appendChild(w),d.appendChild(p),d}qa(),us(),Ds(),js(),Cs(),$o(),Xa(),mn(),Yt(),Y(),Ua(),Ca(),Pc(),yi(),xs(),ti(),fi(),er(),En(),Nn(),No(),go();const Vv=`persona-chat-history`,Hv=`data-persona-composer-reason`,Uv=`data-persona-composer-notice`,Wv={"image/png":`png`,"image/jpeg":`jpg`,"image/jpg":`jpg`,"image/gif":`gif`,"image/webp":`webp`,"image/svg+xml":`svg`,"image/bmp":`bmp`,"image/tiff":`tiff`};function Gv(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let e of n){if(e.kind!==`file`||!e.type.startsWith(`image/`))continue;let n=e.getAsFile();if(!n)continue;if(n.name){t.push(n);continue}let r=Wv[n.type]??`png`;t.push(new File([n],`clipboard-image-${Date.now()}.${r}`,{type:n.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let n of Array.from(e.files??[]))n.type.startsWith(`image/`)&&t.push(n);return t}function Kv(e){if(!e)return!1;let t=e.types;return t?typeof t.contains==`function`?t.contains(`Files`):Array.from(t).includes(`Files`):!1}function qv(e){return e?e===!0?{storage:`session`,keyPrefix:`persona-`,persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??`session`,keyPrefix:e.keyPrefix??`persona-`,persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function Jv(e){try{let t=e===`local`?localStorage:sessionStorage,n=`__persist_test__`;return t.setItem(n,`1`),t.removeItem(n),t}catch{return null}}const Yv=e=>!e||typeof e!=`object`?{}:{...e},Xv=e=>e.map(e=>({...e,streaming:!1})),Zv=(e,t,n)=>{let r=e?.markdown?Ol(e.markdown):null,i=Bl(e?.sanitize);e?.postprocessMessage&&i&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let a=!1,o=a=>{let o=a.text??``,s=a.message.rawContent??null;if(t){let e=t.process({text:o,raw:s??o,message:a.message,streaming:a.streaming});e!==null&&(o=e.text,e.persist||(a.message.__skipPersist=!0),e.resubmit&&!a.streaming&&n&&n())}let c=Kt()!==null,l;if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:o,raw:s??a.text??``});l=i?i(t):t}else if(r){let e=a.streaming?ql(o):o,t=r(e);l=i&&c?i(t):t}else l=jl(o);return l};return e=>{try{return o(e)}catch(t){return a||(a=!0,console.error(`[Persona] markdown rendering failed; falling back to plain text:`,t)),jl(e.text??``)}}};function Qv(e){let t=q(`div`,`persona-attachment-drop-overlay`);e?.background&&t.style.setProperty(`--persona-drop-overlay-bg`,e.background),e?.backdropBlur!==void 0&&t.style.setProperty(`--persona-drop-overlay-blur`,e.backdropBlur),e?.border&&t.style.setProperty(`--persona-drop-overlay-border`,e.border),e?.borderRadius&&t.style.setProperty(`--persona-drop-overlay-radius`,e.borderRadius),e?.inset&&t.style.setProperty(`--persona-drop-overlay-inset`,e.inset),e?.labelSize&&t.style.setProperty(`--persona-drop-overlay-label-size`,e.labelSize),e?.labelColor&&t.style.setProperty(`--persona-drop-overlay-label-color`,e.labelColor);let n=e?.iconName??`upload`,r=e?.iconSize??`48px`,i=e?.iconColor??`rgba(59, 130, 246, 0.6)`,a=e?.iconStrokeWidth??.5,o=K(n,r,i,a);if(o&&t.appendChild(o),e?.label){let n=q(`span`,`persona-drop-overlay-label`);n.textContent=e.label,t.appendChild(n)}return t}const $v=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t?{...t,...r}:r}return n},ey=e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:$v(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}),ty=(e,t,n)=>{if(e==null)throw Error(`createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).`);e.id&&!e.getAttribute(`data-persona-instance`)&&e.setAttribute(`data-persona-instance`,e.id),e.hasAttribute(`data-persona-root`)||e.setAttribute(`data-persona-root`,`true`);let r=bo(t),a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Set,s=bl((e,t)=>{Gi.delete(e);let n=Array.from(z.querySelectorAll(`[data-message-id]`)).find(t=>t.dataset.messageId===e);n&&(t===`tool`?Gg(e,n,a,r):Pg(e,n,o))}),c=/* @__PURE__ */ new Map,l=()=>{wa({delayMs:r.tooltip?.delayMs??200,skipDelayMs:r.tooltip?.skipDelayMs??300})};l();let u=r.features;r=G_(r);let d=iv.getForInstance(r.plugins),f=Nc(e),p=[],m=!1,h=jg(()=>r),g=null,_=null,v=null,y=!1,x=null,S=e=>{g=e,e.initApprovalUi({webMcpToolTitle:xn});let t=e.createBuiltInApprovalPlugin(c);_=t.plugin,v=t.teardown},C=()=>{if(g)return g;let e=Qg();return e?(S(e),e):(Zg().then(e=>{y||g||(S(e),x?.())}).catch(()=>{}),null)},w=!1,T=!1,E=null,D=(e,t,n,r)=>{if(!e.querySelector(`[data-tv-form]`))return;let i=rv();i?i.enhanceWithForms(e,t,n,r):nv().then(()=>{w||T||!E||(T=!0,E())}).catch(()=>{})};r.components&&n_.registerAll(r.components);let O=lv(),k=r.persistState===!1?null:r.storageAdapter??bv(),ee=!!r.clientToken&&typeof r.reconnectStream!=`function`,A={},ne=null,re,ie=new Promise(e=>{re=e}),ae=()=>{},oe=new Promise(e=>{ae=e}),j,se=!1,ce=e=>{if(r.onStateLoaded)try{let t=r.onStateLoaded(e);if(t&&typeof t==`object`&&`state`in t){let{state:e,open:n}=t;return n&&(se=!0),e}return t}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}return e};if(k?.load)try{let e=k.load();if(e&&typeof e.then==`function`)ne=e.then(e=>ce(e??{messages:[],metadata:{}}));else{let t=ce(e??{messages:[],metadata:{}});t.metadata&&(A=Yv(t.metadata)),t.messages?.length&&(r={...r,initialMessages:t.messages}),t.artifacts?.length&&(r={...r,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),j=t.draft}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to load stored state:`,e)}else if(r.onStateLoaded)try{let e=ce({messages:[],metadata:{}});e.messages?.length&&(r={...r,initialMessages:e.messages})}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}ne||re();let le=()=>A,ue=e=>{A=e({...A})??{},Ia()},de=r.actionParsers&&r.actionParsers.length?r.actionParsers:[fv],fe=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[mv.message,mv.messageAndClick],pe=gv({parsers:de,handlers:fe,getSessionMetadata:le,updateSessionMetadata:ue,emit:O.emit,documentRef:typeof document<`u`?document:null});pe.syncFromMetadata();let M=r.launcher?.enabled??!0,me=r.launcher?.autoExpand??!1,he=r.autoFocusInput??!1,ge=me,_e=M,ve=r.layout?.header?.layout,ye=!1,N=()=>Nm(r),be=()=>M||N(),P=N()?!1:!M||me,xe=!1,Se=null,Ce=()=>{xe=!0,Se&&clearTimeout(Se),Se=setTimeout(()=>{xe&&=(typeof console<`u`&&console.warn(`[AgentWidget] Resubmit requested but no injection occurred within 10s`),!1)},1e4)},we=Zv(r,pe,Ce),Te=r.features?.showReasoning??!0,Ee=r.features?.showToolCalls??!0,De=r.features?.showEventStreamToggle??!1,Oe=r.features?.scrollToBottom??{},ke=r.features?.scrollBehavior??{},Ae=()=>(typeof r.persistState==`object`?r.persistState?.keyPrefix:void 0)??`persona-`,je=`${Ae()}event-stream`,Me=null,Ne=r.features?.eventStream?.maxEvents??2e3,Pe=null,Fe=null,Ie=null,Le=!1,Re=null,ze=!1,Be=null,Ve=0,He=(e,t)=>{Pe?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},Ue=(e,t)=>{Fe?.processEvent(e,t),Pe?He(e,t):Ie&&(Ie.length>=Ne&&Ie.shift(),Ie.push({type:e,payload:t}))},We=()=>{!Pe&&De&&(Ie??=[],t_().then(e=>{if(Le||Pe||!De)return;Me=new e.EventStreamStore(je),Pe=new e.EventStreamBuffer(Ne,Me),Fe??=new e.ThroughputTracker,Me.open().then(()=>Pe?.restore()).catch(e=>{r.debug&&console.warn(`[AgentWidget] IndexedDB not available for event stream:`,e)});let t=Ie??[];Ie=null;for(let e of t)Fe?.processEvent(e.type,e.payload),He(e.type,e.payload)}).catch(()=>{}))};De&&We();let Ge=!1,Ke=null,qe=()=>{},Je=()=>{},Ye=()=>{},Xe=()=>{},Ze=()=>{},Qe=()=>ze||Ge&&Ke===`panel`,$e={onCopy:e=>{O.emit(`message:copy`,e),Q?.isClientTokenMode()&&Q.submitMessageFeedback(e.id,`copy`).catch(e=>{r.debug&&console.error(`[AgentWidget] Failed to submit copy feedback:`,e)}),r.messageActions?.onCopy?.(e)},onFeedback:e=>{O.emit(`message:feedback`,e),Q?.isClientTokenMode()&&Q.submitMessageFeedback(e.messageId,e.type).catch(e=>{r.debug&&console.error(`[AgentWidget] Failed to submit feedback:`,e)}),r.messageActions?.onFeedback?.(e)}};r.statusIndicator;let et=(e,t=r.statusIndicator??{})=>e===`idle`?t.idleText??gi.idle:e===`connecting`?t.connectingText??gi.connecting:e===`connected`?t.connectedText??gi.connected:e===`error`?t.errorText??gi.error:e===`paused`?t.pausedText??gi.paused:e===`resuming`?t.resumingText??gi.resuming:gi[e];function tt(e,t,n,r){if(!N()&&(n.mode===`transient`||e.classList.contains(`persona-mb-2`))&&(Ka(e,ct,n),Ga(e,n,r)),!(e.hasAttribute(Hv)||e.hasAttribute(Uv))){if(r===`idle`&&n.idleLink){e.textContent=``;let r=document.createElement(`a`);r.href=n.idleLink,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=t,r.style.color=`inherit`,r.style.textDecoration=`none`,e.appendChild(r)}else e.textContent=t}}let nt=Dg({config:r,showClose:be()}),{wrapper:F,panel:I,pillRoot:rt}=nt.shell,it=nt.panelElements,{container:L,body:R,messagesWrapper:z,starterSuggestions:at,transcriptSuggestions:ot,suggestions:st,textarea:B,sendButton:V,composerForm:ct,statusText:lt,welcomeHost:ut,welcomeIconHolder:dt,greetingHost:ft,introKicker:pt,introTitle:mt,introSubtitle:ht,closeButton:H,iconHolder:gt,headerTitle:_t,headerSubtitle:vt,header:yt,footer:bt,actionsRow:xt}=it,St=it.leftActions,Ct=it.rightActions,wt=it.sendButtonWrapper,Tt=it.setSendButtonMode,U=it.micButton,Et=it.micButtonWrapper,Dt=it.attachmentButton,Ot=it.attachmentButtonWrapper,kt=it.attachmentInput,At=it.attachmentPreviewsContainer;L.classList.add(`persona-relative`),R.classList.add(`persona-relative`);let jt=()=>Oe.label??``,W=()=>Oe.iconName??`arrow-down`,Mt=()=>Oe.enabled!==!1,Nt=()=>ke.mode??`anchor-top`,Pt=()=>Nt()===`follow`||Nt()===`anchor-top`&&da,Ft=()=>ke.anchorTopOffset??16,It=()=>ke.restorePosition??`bottom`,Lt=()=>ke.pauseOnInteraction===!0,Rt=()=>ke.showActivityWhilePinned!==!1,zt=()=>ke.announce===!0,Bt=()=>ke.scrollbar??`on-scroll`,Vt=q(`button`,`persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer`);Vt.type=`button`,Vt.style.display=`none`,Vt.setAttribute(`data-persona-scroll-to-bottom`,`true`);let Ht=q(`span`,`persona-flex persona-items-center`),Gt=q(`span`,``),qt=q(`span`,``);qt.setAttribute(`data-persona-scroll-to-bottom-count`,``),qt.style.display=`none`,Vt.append(Ht,Gt,qt),L.appendChild(Vt);let Yt=q(`div`,`persona-stream-anchor-spacer`);Yt.setAttribute(`aria-hidden`,`true`),Yt.setAttribute(`data-persona-anchor-spacer`,``),Yt.style.flexShrink=`0`,Yt.style.pointerEvents=`none`,Yt.style.height=`0px`,Yt.style.display=`none`,R.appendChild(Yt);let Xt=q(`div`,`persona-sr-only`);Xt.setAttribute(`aria-live`,`polite`),Xt.setAttribute(`aria-atomic`,`true`),Xt.setAttribute(`role`,`status`),Xt.setAttribute(`data-persona-live-region`,``),Object.assign(Xt.style,{position:`absolute`,width:`1px`,height:`1px`,margin:`-1px`,padding:`0`,overflow:`hidden`,clip:`rect(0 0 0 0)`,clipPath:`inset(50%)`,whiteSpace:`nowrap`,border:`0`}),L.appendChild(Xt);let Zt=null,Qt=null,$t=e=>{zt()&&e&&(Qt=e,Zt===null&&(Zt=setTimeout(()=>{Zt=null,Qt&&zt()&&(Xt.textContent=Qt),Qt=null},400)))},en=()=>{let t=e.ownerDocument.defaultView??window;return(r.launcher?.mobileFullscreen??!0)&&t.innerWidth<=(r.launcher?.mobileBreakpoint??640)&&(M||Mm(r))||r.launcher?.fullHeight===!0&&!r.launcher.sidebarMode&&!Mm(r)},tn=()=>og(r,en()),nn=`empty`,rn=0,an=()=>rn||parseFloat(e.style.getPropertyValue(`--persona-composer-lift`))||0,on=()=>{let e=bt.style.display===`none`?0:bt.offsetHeight;Vt.style.bottom=`${e+an()+12}px`};on();let sn=()=>{Gn||(bt.style.marginBottom=rn>0?`${rn}px`:``)},ln=()=>{let t=jp(r,N()),n=tn();e.setAttribute(`data-persona-welcome-fullscreen`,String(en())),e.setAttribute(`data-persona-welcome-layout`,n.layout??`top`),e.setAttribute(`data-persona-welcome-layout-explicit`,r.welcome?.layout??``),e.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`);let i=bt.style.display===`none`?0:bt.offsetHeight,a=n.anchor===`center`&&nn===`empty`?Mp(n.anchorComposerTop)??Mp(`44%`):null,o=a!==null&&n.layout===`centered`&&r.welcome?.anchor===void 0&&r.welcome?.anchorComposerTop===void 0,s=o?getComputedStyle(R):null,c=parseFloat(e.style.getPropertyValue(`--persona-composer-overlay-height`))||0,l=parseFloat(e.style.getPropertyValue(`--persona-composer-lift`))||0,u=Math.max(0,(parseFloat(s?.paddingBottom??``)||0)-(t===`overlay`?c+l:0)),d=o?R.getBoundingClientRect().top-L.getBoundingClientRect().top:0,f=!o||ut.hidden?0:(ut.querySelector(`[data-persona-welcome-plugin]`)??ut).offsetHeight,p=a===null||N()?0:o?Math.max(0,Math.round((L.clientHeight-d-f-u-i)/2)):Np({columnHeight:L.clientHeight,footerHeight:i,fraction:a});e.style.setProperty(`--persona-composer-overlay-height`,`${i}px`),e.style.setProperty(`--persona-composer-lift`,`${t===`overlay`?p:0}px`),rn=t===`block`?p:0,sn(),on()},un=()=>{let e=!!jt();Vt.setAttribute(`aria-label`,jt()||`Jump to latest`),Vt.title=jt(),Vt.setAttribute(`data-persona-scroll-to-bottom-has-label`,e?`true`:`false`),Ht.innerHTML=``;let t=K(W(),`14px`,`currentColor`,2);t?(Ht.appendChild(t),Ht.style.display=``):Ht.style.display=`none`,Gt.textContent=jt(),Gt.style.display=e?``:`none`};un();let dn=null,fn=null,G=xd();G.subscribe(e=>{try{L.dispatchEvent(new CustomEvent(`persona:composer:state`,{detail:e,bubbles:!0,composed:!0}))}catch{}});let pn=()=>{G.setText(B?.value??``)},mn=()=>{G.setMentionRefs(fn?.getMentionRefs()??[])},hn=e=>({id:e.id,name:e.file.name,mimeType:e.file.type,size:e.file.size,status:e.status,progress:e.progress,error:e.error}),gn=e=>{let t=Object.freeze(e.map(hn));G.setAttachments(t);try{r.attachments?.onChange?.(t)}catch(e){console.error(`[AgentWidget] attachments.onChange failed:`,e)}us()};G.setSelectedModelId(r.composer?.selectedModelId);let _n=()=>r.composer?.modes??[],vn=()=>df(_n(),r.composer?.modeGroups);{let e=mf(r.composer?.defaultActiveModeIds??[],_n());e.length&&G.setActiveModeIds(e)}function yn(e){if(G.getState().selectedModelId!==e){G.setSelectedModelId(e),Cn?.repaint();try{r.composer?.onModelChange?.(e)}catch(e){console.error(`[AgentWidget] composer.onModelChange failed:`,e)}}}function bn(e){G.setActiveModeIds(e),Tn?.render(e,vn()),En.forEach(e=>e.repaint()),Y?.resolve(),qs(),lr()}function Sn(e){bn(pf(G.getState().activeModeIds,e,_n(),r.composer?.modeGroups))}let Cn=null,wn=null,Tn=null,En=/* @__PURE__ */ new Map,Dn=null;function On(e){G.setQuote(e),Dn?.render(G.getState().quote),lr(),Ba()}let kn=!1;function An(){let e=r.composer?.streamingSubmitBehavior??`block`;return e===`interrupt`?r.clientToken?`interrupt`:(!kn&&r.debug===!0&&(kn=!0,typeof console<`u`&&console.warn(`[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".`)),`block`):e}let Mn=null;function Nn(e){G.setPendingSubmission(e),Mn?.render(G.getState().pendingSubmission),lr()}let Pn=e=>{let t=En.get(e);if(t)return t;let n=_f({groupId:e,getGroup:()=>r.composer?.modeGroups?.find(t=>t.id===e),getModes:()=>_n().filter(t=>t.groupId===e),getActiveIds:()=>G.getState().activeModeIds,onSelect:e=>Sn(e)});return En.set(e,n),n},Fn=()=>{let e=[],t=G.getState().activeModeIds,n=/* @__PURE__ */ new Set;if(_n().forEach((i,a)=>{if(lf(i.groupId,r.composer?.modeGroups)){let t=i.groupId;if(n.has(t))return;n.add(t);let o=Pn(t);o.action.order=sf(a),o.action.label=r.composer?.modeGroups?.find(e=>e.id===t)?.label??t,e.push(o.action)}else e.push({id:of(i.id),kind:`button`,placement:`start`,order:sf(a),presentation:i.presentation??`auto`,label:i.label,shortLabel:i.shortLabel,iconName:i.iconName,pressed:t.includes(i.id),onSelect:()=>Sn(i.id)})}),r.composer?.models?.length&&!d.some(e=>e.renderComposer)){let t=r.composer?.modelPicker?.presentation??`native`;(!Cn||wn!==t)&&(wn=t,Cn=ef({getModels:()=>r.composer?.models??[],getSelectedModelId:()=>G.getState().selectedModelId,onSelect:e=>yn(e),presentation:t,getSuffix:()=>r.composer?.modelPicker?.suffix})),e.push(Cn.action)}return e},In=null,Ln=d.find(e=>e.renderHeader);if(Ln?.renderHeader){let e=Ln.renderHeader({config:r,defaultRenderer:()=>{let e=Qm({config:r,showClose:be()});return $m(L,e,r),e.header},onClose:()=>Xo(!1,`user`)});if(e){let t=yt;t&&(t.replaceWith(e),yt=e,nt.header.element=e)}}let zn=()=>{Re&&(R.style.display=`none`,bt.parentNode?.insertBefore(Re.element,bt),Re.update())},Bn=()=>{if(!Pe){We();return}if(ze=!0,Re?zn():t_().then(e=>{!Re&&ze&&Pe&&(Re=e.createEventStreamView({buffer:Pe,getFullHistory:()=>Pe.getAllFromStore(),onClose:()=>Hn(),config:r,plugins:d,getThroughput:()=>Fe?.getMetric()??{status:`idle`},renderIconByName:K}),zn())}).catch(()=>{Hn()}),Un){Un.style.boxShadow=`inset 0 0 0 1.5px ${Ym.actionIconColor}`;let e=r.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&Un.classList.add(e))}let e=()=>{if(!ze)return;let t=Date.now();t-Ve>=200&&(Re?.update(),Ve=t),Be=requestAnimationFrame(e)};Ve=0,Be=requestAnimationFrame(e),ro(),O.emit(`eventStream:opened`,{timestamp:Date.now()})},Hn=()=>{if(ze){if(ze=!1,Re&&Re.element.remove(),R.style.display=``,Un){Un.style.boxShadow=``;let e=r.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&Un.classList.remove(e))}Be!==null&&(cancelAnimationFrame(Be),Be=null),ro(),O.emit(`eventStream:closed`,{timestamp:Date.now()})}},Un=null;if(De){let e=r.features?.eventStream?.classNames,t=`persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1`+(e?.toggleButton?` `+e.toggleButton:``);Un=q(`button`,t),Un.style.width=`28px`,Un.style.height=`28px`,Un.style.color=Ym.actionIconColor,Un.type=`button`,Un.setAttribute(`aria-label`,`Event Stream`),Un.title=`Event Stream`;let n=Jt(i,`18px`,`currentColor`,1.5);n&&Un.appendChild(n);let a=it.clearChatButtonWrapper,o=it.closeButtonWrapper,s=a||o;s&&s.parentNode===yt?yt.insertBefore(Un,s):yt.appendChild(Un),Un.addEventListener(`click`,()=>{ze?Hn():Bn()})}let Wn=e=>{let t=r.attachments;if(!t?.enabled)return;let n=e.querySelector(`[data-persona-composer-attachment-previews]`)??e.querySelector(`.persona-attachment-previews`);if(!n){n=q(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),n.setAttribute(`data-persona-composer-attachment-previews`,``),n.style.display=`none`;let t=e.querySelector(`[data-persona-composer-form]`);t?.parentNode?t.parentNode.insertBefore(n,t):e.insertBefore(n,e.firstChild)}if(!(e.querySelector(`[data-persona-composer-attachment-input]`)??e.querySelector(`input[type="file"]`))){let n=q(`input`);n.type=`file`,n.setAttribute(`data-persona-composer-attachment-input`,``),n.accept=(t.allowedTypes??Qo).join(`,`),n.multiple=(t.maxFiles??4)>1,n.style.display=`none`,n.setAttribute(`aria-label`,t.buttonTooltipText??`Attach files`),e.appendChild(n)}},Gn=!1,Kn=e=>{let t=d.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let n=r.composer,i=m?Q.isStreaming():!1;return t.renderComposer({config:r,defaultRenderer:e,requestRender:()=>Xu(),storage:h(t.id),onSubmit:e=>{Q&&!Q.isStreaming()&&hl(e.trim(),{consumeDraft:!1})},streaming:i,disabled:i,openAttachmentPicker:()=>{$o()||kt?.click()},models:n?.models,selectedModelId:G.getState().selectedModelId??n?.selectedModelId,onModelChange:e=>yn(e),onVoiceToggle:r.voiceRecognition?.enabled===!0?()=>{In?.()}:void 0})},qn=Kn(()=>fh({config:r}).footer);qn&&(nt.replaceComposer(qn),bt=nt.composer.footer,Gn=!0);let Jn=null,Yn=e=>{ct=e.form,B=e.input,wt=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(V=e.sendButton),e.micButton&&(U=e.micButton,Et=e.micButton.parentElement),e.found.status&&(lt=e.found.status),e.found.suggestions&&(st=e.found.suggestions),e.attachmentButton&&(Dt=e.attachmentButton,Ot=e.attachmentButton.parentElement),kt=e.attachmentInput??null,At=e.attachmentPreviews??null,e.found.actionsRow&&(xt=e.found.actionsRow),St=e.found.actionsStart,Ct=e.found.actionsEnd};function Xn(){let e=B;if(!e)return;let t=r.composer?.inputAttributes,n=!t?.ariaLabel&&!(e instanceof HTMLTextAreaElement)?e.getAttribute(`aria-label`):null;cs(e,t),n&&e.setAttribute(`aria-label`,n),ss(e,{submitKey:r.composer?.submitKey,insertNewlineOnTouchEnter:r.composer?.insertNewlineOnTouchEnter,coarsePointer:rs(e)}),ns(e,ts(r.composer?.maxLines,N()?5:3))}let Zn=e=>{Jn=wd(e,{debug:r.debug===!0}),Jn&&Yn(Jn),Xn()};Wn(bt),Zn(bt),pn();let Qn=Ap(r,N());Qn&&(z.style.maxWidth=Qn,z.style.marginLeft=`auto`,z.style.marginRight=`auto`,z.style.width=`100%`,ft.style.maxWidth=Qn,ft.style.marginLeft=`auto`,ft.style.marginRight=`auto`,ft.style.width=`100%`,at.style.maxWidth=Qn,ot.style.maxWidth=Qn,ot.style.marginLeft=`auto`,ot.style.marginRight=`auto`,ot.style.width=`100%`);let $n=()=>{let e=Ap(r,N());if(e&&!N())for(let t of[ct,st,At,lt])t&&(t.style.maxWidth=e,t.style.marginLeft=`auto`,t.style.marginRight=`auto`,t.style.width=`100%`)};$n();let er=()=>{r.attachments?.enabled&&kt&&At&&(dn?dn.remountPreviews(At):(dn=vd.fromConfig(r.attachments,gn),dn.setPreviewsContainer(At)),Jn?.addListener(kt,`change`,e=>{let t=e.target;dn?.handleFileSelect(t.files),t.value=``}),L.querySelector(`.persona-attachment-drop-overlay`)||L.appendChild(Qv(r.attachments.dropOverlay)))};er();let J=()=>fn?.prefetch(),tr=()=>{if(!r.contextMentions?.enabled||!B)return;let e=Gs();if(!e){let e=B;Us().then(()=>{!fn&&B===e&&e.isConnected&&(tr(),Y?.resolve())},()=>{});return}let t=Jn?.header??null,n=t?rf(t):void 0;if(fn=e.createContextMentionOrchestrator({deps:{loadContextMentions:Es,loadContextMentionsInline:As,renderLucideIcon:K,createMentionButton:Ss},config:r,textarea:B,anchor:ct??B,getMessages:()=>Q.getMessages(),liveRegionHost:L,chipRow:n}),fn&&!n){let e=B;e.parentElement?.insertBefore(fn.contextRow,e)}};tr();let Y=null,nr={getState:()=>G.getState(),getValue:()=>B?.value??``,setValue:e=>{B&&(B.value=e,B.dispatchEvent(new Event(`input`,{bubbles:!0})),pn())},submit:()=>{Df(Jn?.form??null)},openAttachmentPicker:()=>{$o()||kt?.click()},toggleVoice:()=>{In?.()},requestRender:()=>Y?.resolve()},rr=()=>{let e=[];return(fn?.affordanceButtons??[]).forEach((t,n)=>{e.push({id:`core:mention-${n}`,placement:`start`,order:Nd.mention+n,element:t,managed:!0})}),Ot&&e.push({id:`core:attachment`,placement:`start`,order:Nd.attachment,element:Ot}),Et&&e.push({id:`core:mic`,placement:`end`,order:Nd.mic,element:Et}),wt&&e.push({id:`core:send`,placement:`end`,order:Nd.send,element:wt}),e},ir=()=>{Y?.destroy(),Y=Zd({getBindings:()=>Jn,collect:()=>({builtIns:rr(),configActions:[...Fn(),...r.composer?.actions??[]],plugins:d,contributionContext:{config:r,getState:()=>G.getState(),requestRender:()=>Y?.resolve()},debug:r.debug===!0}),actionContext:nr,getState:()=>G.getState(),getOverflow:()=>r.composer?.actionOverflow,reportError:(e,t)=>{typeof console<`u`&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),Y.resolve()};ir();let ar=()=>{if(Tn?.destroy(),Tn=null,!vn().length)return;let e=Jn?.header;e&&(Tn=af({row:rf(e),onRemove:e=>Sn(e),initialIds:G.getState().activeModeIds}),Tn.render(G.getState().activeModeIds,vn()))};ar();let or=()=>{Dn?.destroy(),Dn=null,Mn?.destroy(),Mn=null;let e=Jn?.header;e&&(Dn=vf({onDismiss:()=>On(void 0)}),e.appendChild(Dn.element),Dn.render(G.getState().quote),An()===`defer-one`&&(Mn=yf({onEdit:()=>nl(),onRemove:()=>Nn(void 0)}),e.appendChild(Mn.element),Mn.render(G.getState().pendingSubmission)))};or();let sr=Tf(),cr=()=>{let e=Jn?.header?.querySelector(tf);if(e)return e.childElementCount>0;let t=G.getState();return t.mentionRefs.length>0||mf(t.activeModeIds,vn()).length>0};function lr(){let e=G.getState(),t=sr.observe(Ef(B),e.text);bt.toggleAttribute(`data-persona-composer-compact`,wf({text:e.text,wrapped:t,hasAttachments:e.attachments.length>0,hasChips:cr(),hasQuote:e.quote!==void 0,hasPendingSubmission:e.pendingSubmission!==void 0}))}function ur(){r.composer?.layout===`single-row`&&!N()?bt.setAttribute(`data-persona-composer-layout`,`single-row`):bt.removeAttribute(`data-persona-composer-layout`)}ur(),G.subscribe(()=>{Y?.sync(),us(),ps(),lr(),Ba()}),ps();let dr=!1,fr=e=>{if(dr||r.debug!==!0)return;let t=[`messages`,`composer`].filter(t=>e[t]);t.length&&(dr=!0,console.warn(`[persona] layout.slots.${t.join(` and layout.slots.`)} ${t.length>1?`are`:`is`} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let e=r.layout?.slots??{};fr(e);let t=e=>{switch(e){case`body-top`:return R.querySelector(`[data-persona-intro-card]`);case`messages`:return z;case`footer-top`:return st;case`composer`:return ct;case`footer-bottom`:return lt;default:return null}},n=(e,t)=>{switch(e){case`header-left`:case`header-center`:case`header-right`:if(e===`header-left`)yt.insertBefore(t,yt.firstChild);else if(e===`header-right`)yt.appendChild(t);else{let e=yt.querySelector(`.persona-flex-col`);e?e.parentNode?.insertBefore(t,e.nextSibling):yt.appendChild(t)}break;case`body-top`:{let e=R.querySelector(`[data-persona-intro-card]`);e?e.replaceWith(t):R.insertBefore(t,R.firstChild);break}case`body-bottom`:R.appendChild(t);break;case`footer-top`:st.replaceWith(t);break;case`footer-bottom`:lt.replaceWith(t)}};for(let[i,a]of Object.entries(e))if(a)try{let e=a({config:r,defaultContent:()=>t(i)});e&&n(i,e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Error rendering slot "${i}":`,e)}})(),z.addEventListener(`click`,e=>{let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`button[data-persona-copy-tool-detail]`);n&&(e.preventDefault(),e.stopPropagation(),Bg(n))});let pr=e=>{let t=e.target.closest(`button[data-expand-header="true"]`);if(!t)return;let n=t.closest(`.persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble`);if(!n)return;let i=n.getAttribute(`data-message-id`);if(!i)return;ha(),io();let l=t.getAttribute(`data-bubble-type`);if(n.classList.contains(`persona-activity-row`)){s.manual(i);let e=n.parentElement?.closest(`[data-persona-tool-group]`);e?.dataset.messageId&&s.manual(e.dataset.messageId)}if(l===`reasoning`)o.has(i)?o.delete(i):o.add(i),Pg(i,n,o);else if(l===`tool`)a.has(i)?a.delete(i):a.add(i),Gg(i,n,a,r);else if(l===`approval`&&g){let e=((r.approval===!1?void 0:r.approval)?.detailsDisplay??`collapsed`)===`expanded`,t=c.get(i)??e;c.set(i,!t),g.updateApprovalDetailsUI(i,n,r,c)}Gi.delete(i)};z.addEventListener(`pointerdown`,e=>{e.target.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),pr(e))}),z.addEventListener(`click`,e=>{e.detail===0&&e.target.closest(`.persona-activity-row`)&&pr(e)}),z.addEventListener(`keydown`,e=>{let t=e.target;(e.key===`Enter`||e.key===` `)&&t.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),pr(e))}),z.addEventListener(`copy`,e=>{let{clipboardData:t}=e;if(!t)return;let n=z.getRootNode(),r=typeof n.getSelection==`function`?n.getSelection():window.getSelection();if(!r||r.isCollapsed)return;let i=r.toString(),a=Fp(i);a&&a!==i&&(t.setData(`text/plain`,a),e.preventDefault())});let mr=/* @__PURE__ */ new Map,hr=null,gr=`idle`,_r={idle:{icon:`volume-2`,label:`Read aloud`},loading:{icon:`loader-circle`,label:`Loading…`},playing:{icon:`pause`,label:`Pause`},paused:{icon:`play`,label:`Resume`}},vr=(e,t)=>{let{icon:n,label:r}=_r[t];e.setAttribute(`aria-label`,r),e.title=r,e.setAttribute(`aria-pressed`,t===`idle`?`false`:`true`),e.classList.toggle(`persona-message-action-active`,t!==`idle`),e.classList.toggle(`persona-message-action-loading`,t===`loading`);let i=K(n,14,`currentColor`,2);i&&(e.innerHTML=``,e.appendChild(i))},yr=()=>{z.querySelectorAll(`[data-action="read-aloud"]`).forEach(e=>{let t=e.closest(`[data-actions-for]`)?.getAttribute(`data-actions-for`)??null;vr(e,t&&t===hr?gr:`idle`)})};z.addEventListener(`click`,e=>{let t=e.target.closest(`.persona-message-action-btn[data-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`[data-actions-for]`);if(!n)return;let i=n.getAttribute(`data-actions-for`);if(!i)return;let a=t.getAttribute(`data-action`);if(a===`copy`){let e=Q.getMessages().find(e=>e.id===i);if(e&&$e.onCopy){let n=e.content||``;navigator.clipboard.writeText(n).then(()=>{t.classList.add(`persona-message-action-success`);let e=Jt(b,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e)),setTimeout(()=>{t.classList.remove(`persona-message-action-success`);let e=Jt(te,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))},2e3)}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to copy message:`,e)}),$e.onCopy(e)}}else if(a===`read-aloud`)Q.toggleReadAloud(i);else if(a===`upvote`||a===`downvote`){let e=(mr.get(i)??null)===a,r=a===`upvote`?`thumbs-up`:`thumbs-down`;if(e){mr.delete(i),t.classList.remove(`persona-message-action-active`);let e=K(r,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))}else{let e=a===`upvote`?`downvote`:`upvote`,o=n.querySelector(`[data-action="${e}"]`);if(o){o.classList.remove(`persona-message-action-active`);let t=K(e===`upvote`?`thumbs-up`:`thumbs-down`,14,`currentColor`,2);t&&(o.innerHTML=``,o.appendChild(t))}mr.set(i,a),t.classList.add(`persona-message-action-active`);let s=K(r,14,`currentColor`,2);s&&(s.setAttribute(`fill`,`currentColor`),t.innerHTML=``,t.appendChild(s)),t.classList.remove(`persona-message-action-pop`),t.offsetWidth,t.classList.add(`persona-message-action-pop`);let c=Q.getMessages().find(e=>e.id===i);c&&$e.onFeedback&&$e.onFeedback({type:a,messageId:c.id,message:c})}}else if(a===`regenerate`)br?.regenerate(i);else if(a===`edit`)br?.edit(i);else if(a===`quote`)br?.quote(i);else if(a?.startsWith(`custom:`)){let e=a.slice(7),t=r.messageActions?.custom?.find(t=>t.id===e),n=Q.getMessages().find(e=>e.id===i);if(!t||!n)return;try{t.onSelect(n)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let br=null;z.addEventListener(`click`,e=>{let t=e.target.closest(`button[data-approval-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`.persona-approval-bubble`);if(!n)return;let r=n.getAttribute(`data-message-id`);if(!r)return;let i=t.getAttribute(`data-approval-action`);if(!i)return;let a=i===`approve`?`approved`:`denied`,o=Q.getMessages().find(e=>e.id===r);if(!o?.approval)return;let s=n.querySelector(`[data-approval-buttons]`);s&&s.querySelectorAll(`button`).forEach(e=>{e.disabled=!0,e.style.opacity=`0.5`,e.style.cursor=`not-allowed`}),o.approval.toolType===`webmcp`?Q.resolveWebMcpApproval(r,a):Q.resolveApproval(o.approval,a)});let X=null,Sr=!1,wr=null,Tr=()=>{},Er=`none`,Dr=null,Or={artifacts:[],selectedId:null},kr=!1,Ar=!1,jr=!1,Mr=!1,Nr=()=>Mr||Or.artifacts.some(e=>jn(r.features?.artifacts,e)===`panel`),Pr=()=>Or.artifacts.length>0&&!kr&&Nr(),Fr={current:null},Ir=(e,t)=>{let n=Q.getArtifactById(t),r=n?.markdown,i=n?.title||`artifact`,a=n?.file,o=n?.artifactType??`markdown`;if(!r){let t=(e.closest(`[data-open-artifact], [data-artifact-inline]`)?.closest(`[data-message-id]`))?.getAttribute(`data-message-id`);if(t){let e=Q.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);r=t?.props?.markdown,i=t?.props?.title||i,t?.props?.file&&typeof t.props.file==`object`&&(a=t.props.file),!n&&typeof t?.props?.artifactType==`string`&&(o=t.props.artifactType)}catch{}}}return{markdown:r,title:i,file:a,artifactType:o}};z.addEventListener(`click`,e=>{let t=e.target.closest(`[data-download-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-download-artifact`);if(!n||r.features?.artifacts?.onArtifactAction?.({type:`download`,artifactId:n})===!0)return;let{markdown:i,title:a,file:o}=Ir(t,n);if(!i)return;let s=f_();s&&s.triggerArtifactDownload(s.downloadInfoFor({title:a,markdown:i,file:o}))}),z.addEventListener(`click`,e=>{let t=e.target.closest(`[data-artifact-custom-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-artifact-custom-action`);if(!n)return;let i=t.closest(`[data-artifact-inline]`),a=i?null:t.closest(`[data-open-artifact]`),o=i?i.getAttribute(`data-artifact-inline`):a?.getAttribute(`data-open-artifact`)??null,s=(i?r.features?.artifacts?.inlineActions:r.features?.artifacts?.cardActions)?.find(e=>e.id===n);if(!s)return;let{markdown:c,title:l,file:u,artifactType:d}=Ir(t,o??``),f={artifactId:o,title:l,artifactType:d,markdown:c,file:u};try{Promise.resolve(s.onClick(f)).catch(()=>{})}catch{}}),z.addEventListener(`click`,e=>{let t=e.target.closest(`[data-copy-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-copy-artifact`);if(!n)return;let r=Q.getArtifactById(n),i=f_();if(!i)return;let a=``;if(r)a=i.artifactCopyText(r);else{let{markdown:e,file:r,artifactType:o}=Ir(t,n);o===`markdown`&&(a=i.artifactCopyText({id:n,artifactType:`markdown`,status:`complete`,markdown:e??``,...r?{file:r}:{}}))}a&&navigator.clipboard.writeText(a).then(()=>{let e=Jt(b,16,`currentColor`,2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=Jt(te,16,`currentColor`,2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),z.addEventListener(`click`,e=>{let t=e.target.closest(`[data-expand-artifact-inline]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-expand-artifact-inline`);n&&r.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:n})!==!0&&(kr=!1,Mr=!0,Ar=!0,jr=!0,Q.selectArtifact(n),si())}),z.addEventListener(`click`,e=>{let t=e.target;if(t.closest(`[data-download-artifact]`)||t.closest(`[data-artifact-custom-action]`))return;let n=t.closest(`[data-open-artifact]`);if(!n)return;let i=n.getAttribute(`data-open-artifact`);i&&r.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:i})!==!0&&(e.preventDefault(),e.stopPropagation(),kr=!1,Mr=!0,Q.selectArtifact(i),si())}),z.addEventListener(`keydown`,e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target;(t.hasAttribute(`data-open-artifact`)||t.hasAttribute(`data-expand-artifact-inline`))&&(e.preventDefault(),t.click())});let Lr=it.composerOverlay,Rr=e=>{Us().catch(()=>{}),Xr(e,r,Lr)},zr=null,Br={mount:e,overlay:Lr,sessionRef:Fr,config:()=>r},Vr=!1,Hr=e=>t=>{let n=t.target,r=n?.closest?.(`[data-persona-ask-sheet-for]`);if(!r||!(e===`click`?n?.closest(`[data-ask-user-action]`):t.key===`Enter`&&n?.matches?.(`[data-ask-free-text-input="true"]`)))return;let i=n=>{zr??=n.createAskUserSheetHandlers(Br),zr[e](t)},a=Gs();a?i(a):Vr||(Vr=!0,Us().then(e=>{Vr=!1,r.isConnected&&i(e)},()=>{Vr=!1}))};Lr.addEventListener(`click`,Hr(`click`)),Lr.addEventListener(`keydown`,Hr(`keydown`));let Ur=e=>{if(!/^[1-9]$/.test(e.key)||e.metaKey||e.ctrlKey||e.altKey)return;let t=e.target;if(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable)return;let n=Lr.querySelector(`[data-persona-ask-sheet-for]`);if(!n||n.getAttribute(`data-ask-layout`)!==`rows`||n.getAttribute(`data-multi-select`)===`true`)return;let r=Number(e.key),i=n.querySelectorAll(`[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]`)[r-1];i&&(e.preventDefault(),i.click())};document.addEventListener(`keydown`,Ur);let Wr=null,Gr=null,Kr=null,qr=null,Jr=()=>{},Yr=!1,Qr=``,$r=``;function ei(){qr?.(),qr=null}let ti=()=>{let e=Sc?.railShell?Sc.railHost:null,t=e?.isConnected?e:null,n=t?t.getBoundingClientRect().width:0;return n<=0?200:n+360},ni=()=>{if(!Wr||!Gr)return;let t=e.classList.contains(`persona-artifact-welded-split`),n=e.ownerDocument.defaultView??window,r=n.innerWidth<=640;if(!t||e.classList.contains(`persona-artifact-narrow-host`)||r){Gr.style.removeProperty(`position`),Gr.style.removeProperty(`left`),Gr.style.removeProperty(`top`),Gr.style.removeProperty(`bottom`),Gr.style.removeProperty(`width`),Gr.style.removeProperty(`z-index`);return}let i=Wr.firstElementChild;if(!i||i===Gr)return;Gr.style.position=`absolute`,Gr.style.top=`0`,Gr.style.bottom=`0`,Gr.style.width=`10px`,Gr.style.zIndex=`5`;let a=X_(Wr,n),o=i.offsetWidth+a/2-5;Gr.style.left=`${Math.max(0,o)}px`},ri=()=>{},ii=()=>{let t=e.ownerDocument.defaultView??window,n=r.launcher?.mobileFullscreen??!0,i=r.launcher?.mobileBreakpoint??640;return!n||t.innerWidth>i?!1:M||Mm(r)},ai=()=>!m_(r)||!Pr()||e.classList.contains(`persona-artifact-narrow-host`)||ii()||(e.ownerDocument.defaultView??window).innerWidth<641?`none`:y_(r)?`detached`:`welded`,si=()=>{if(!X||!m_(r))return;b_(e,r),x_(e,r),ri();let t=r.features?.artifacts?.layout?.narrowHostMaxWidth??520,n=I.getBoundingClientRect().width||0;e.classList.toggle(`persona-artifact-narrow-host`,n>0&&n<=t);let i=Pr();X.setVisible(i),X.update(Or),kr?(X.setMobileOpen(!1),X.element.classList.add(`persona-hidden`),X.backdrop?.classList.add(`persona-hidden`),Ar=!1,jr=!1):Or.artifacts.length>0&&Nr()?(X.element.classList.remove(`persona-hidden`),X.setMobileOpen(!0)):(X.setMobileOpen(!1),X.element.classList.add(`persona-hidden`),X.backdrop?.classList.add(`persona-hidden`),Ar=!1,jr=!1);let a=r.features?.artifacts?.layout?.showExpandToggle===!0;if(X.setExpandToggleVisible(a),X.setCopyButtonVisible(r.features?.artifacts?.layout?.showCopyButton===!0),X.setRefreshButtonVisible(typeof r.features?.artifacts?.layout?.onDocumentToolbarRefresh==`function`),X.setCustomActions(r.features?.artifacts?.toolbarActions??[]),X.setTabFade(r.features?.artifacts?.layout?.tabFade),X.setRenderTabBar(r.features?.artifacts?.renderTabBar),!a&&!jr&&(Ar=!1),Ar!==Yr){let e=X.element;Ar?(Qr=e.style.width,$r=e.style.maxWidth,e.style.removeProperty(`width`),e.style.removeProperty(`max-width`)):(Qr&&(e.style.width=Qr),$r&&(e.style.maxWidth=$r),Qr=``,$r=``),Yr=Ar}e.classList.toggle(`persona-artifact-expanded`,Ar),X.setExpanded(Ar);let o=ai();o!==Er&&(Er=o,Tr()),Jr()};if(m_(r)){I.style.position=`relative`;let t=q(`div`,`persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0`),n=q(`div`,`persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root`);t.appendChild(L),Wr=n,n.appendChild(t),I.appendChild(n);let i=e=>{Sr||X||(X=e.createArtifactPane(r,{onSelect:e=>Fr.current?.selectArtifact(e),onDismiss:()=>{kr=!0,si()},onToggleExpand:()=>{let e=!Ar,t=Or.selectedId??Or.artifacts[Or.artifacts.length-1]?.id??null;r.features?.artifacts?.onArtifactAction?.({type:`expand`,artifactId:t,expanded:e})!==!0&&(Ar=e,e||(jr=!1),si())}}),X.element.classList.add(`persona-hidden`),n.appendChild(X.element),X.backdrop&&I.appendChild(X.backdrop),Jr(),si())},a=f_();a?i(a):(p_(()=>{let e=f_();e&&i(e)}),d_().catch(()=>{})),Jr=()=>{if(Wr&&X){if(r.features?.artifacts?.layout?.resizable!==!0)Kr?.(),Kr=null,ei(),Gr&&=(Gr.remove(),null),X.element.style.removeProperty(`width`),X.element.style.removeProperty(`maxWidth`);else{if(!Gr){let t=q(`div`,`persona-artifact-split-handle persona-shrink-0 persona-h-full`);t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-label`,`Resize artifacts panel`),t.tabIndex=0;let n=e.ownerDocument,i=n.defaultView??window,a=a=>{if(!X||a.button!==0||e.classList.contains(`persona-artifact-narrow-host`)||e.classList.contains(`persona-artifact-expanded`)||i.innerWidth<=640)return;a.preventDefault(),ei();let o=a.clientX,s=X.element.getBoundingClientRect().width,c=r.features?.artifacts?.layout,l=n=>{let r=Wr.getBoundingClientRect().width,a=e.classList.contains(`persona-artifact-welded-split`),l=X_(Wr,i),u=a?0:t.getBoundingClientRect().width||6,d=Z_(s-(n.clientX-o),r,l,u,c?.resizableMinWidth,c?.resizableMaxWidth,ti());X.element.style.width=`${d}px`,X.element.style.maxWidth=`none`,ni()},u=()=>{n.removeEventListener(`pointermove`,l),n.removeEventListener(`pointerup`,u),n.removeEventListener(`pointercancel`,u),qr=null;try{t.releasePointerCapture(a.pointerId)}catch{}};qr=u,n.addEventListener(`pointermove`,l),n.addEventListener(`pointerup`,u),n.addEventListener(`pointercancel`,u);try{t.setPointerCapture(a.pointerId)}catch{}};t.addEventListener(`pointerdown`,a),Gr=t,Wr.insertBefore(t,X.element),Kr=()=>{t.removeEventListener(`pointerdown`,a)}}if(Gr){let e=Pr();Gr.classList.toggle(`persona-hidden`,!e),ni()}}}},ri=()=>{if(!M||!X||(r.launcher?.sidebarMode??!1)||Mm(r)&&Pm(r).reveal===`emerge`)return;let t=e.ownerDocument.defaultView??window,n=r.launcher?.mobileFullscreen??!0,i=r.launcher?.mobileBreakpoint??640;if(n&&t.innerWidth<=i||!S_(r,M))return;let a=ug(r).width,o=r.features?.artifacts?.layout?.expandedPanelWidth??`min(720px, calc(100vw - 24px))`;Pr()?(I.style.width=o,I.style.maxWidth=o):(I.style.width=a,I.style.maxWidth=a)},typeof ResizeObserver<`u`&&(wr=new ResizeObserver(()=>{si()}),wr.observe(I))}else I.appendChild(L);N()&&rt&&(it.peekBanner&&rt.appendChild(it.peekBanner),rt.appendChild(bt)),e.appendChild(F),rt&&e.appendChild(rt);let li=()=>{let t=ii()||N()&&r.launcher?.composerBar?.expandedSize===`fullscreen`||r.launcher?.fullHeight===!0&&!r.launcher?.sidebarMode&&!Mm(r);if(z.style.gap=t?`var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))`:`var(--persona-components-message-gap, 12px)`,z.style.setProperty(`--persona-transcript-gap`,z.style.gap),N()){I.style.width=`100%`,I.style.maxWidth=`100%`;let e=r.launcher?.composerBar??{},t=F.dataset.state===`expanded`,n=e.expandedSize??`anchored`;if(!(t&&n!==`fullscreen`)){L.style.background=``,L.style.border=``,L.style.borderRadius=``,L.style.overflow=``,L.style.boxShadow=``;return}let i=r.theme?.components?.panel,a=Ep(r),o=(e,t)=>e==null||e===``?t:$f(a,e)??e;L.style.background=`var(--persona-surface, #ffffff)`,L.style.border=o(i?.border,`1px solid var(--persona-border)`),L.style.borderRadius=o(i?.borderRadius,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`),L.style.boxShadow=o(i?.shadow,`var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))`),L.style.overflow=`hidden`;return}let n=Mm(r),i=r.launcher?.sidebarMode??!1,a=n||i||(r.launcher?.fullHeight??!1),o=r.launcher?.enabled===!1,s=r.launcher?.detachedPanel===!0,c=r.theme?.components?.panel,l=r.darkTheme?.components?.panel,u=Cp(r)===`dark`?Ja(c??{},l??{}):c,d=Ep(r),f=(e,t)=>e==null||e===``?t:$f(d,e)??e,p=e.ownerDocument.defaultView??window,m=r.launcher?.mobileFullscreen??!0,h=r.launcher?.mobileBreakpoint??640,g=p.innerWidth<=h,_=m&&g&&M,v=n&&m&&g,y=r.launcher?.position??`bottom-left`,b=y===`bottom-left`||y===`top-left`,x=r.launcher?.zIndex??1e5,S=(e,t,n)=>`var(--persona-components-panel-modes-${e}-${t}, ${n})`,C=u?.modes?.floating,w=f(C?.border??u?.border,S(`floating`,`border`,`var(--persona-panel-border, 1px solid var(--persona-border))`)),T=f(C?.shadow??u?.shadow,S(`floating`,`shadow`,`var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))`)),E=f(C?.borderRadius??u?.borderRadius,S(`floating`,`borderRadius`,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`)),D=s&&!_&&!v,O=_||v?`mobile`:D?`floating`:n?`docked`:i?`sidebar`:o?`inline`:`floating`,k=u?.modes?.[O];D?e.setAttribute(`data-persona-panel-detached`,`true`):e.removeAttribute(`data-persona-panel-detached`);let ee=D?w:i||_?`none`:w,A=D?T:_?`none`:i?b?`2px 0 12px rgba(0, 0, 0, 0.08)`:`-2px 0 12px rgba(0, 0, 0, 0.08)`:o?`none`:T;n&&!_&&!D&&(A=`none`,ee=`none`);let te=D?E:i||_?`0`:E,ne=f(k?.border??u?.border,S(O,`border`,ee)),re=f(k?.shadow??u?.shadow,S(O,`shadow`,A)),ie=f(k?.borderRadius??u?.borderRadius,S(O,`borderRadius`,te)),ae=ai(),oe=ae===`detached`,j=ae===`welded`;e.classList.toggle(`persona-artifact-detached-split`,oe),e.classList.toggle(`persona-artifact-welded-split`,j);let se=`var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))`,ce=(r.features?.artifacts?.layout?.chatSurface===`flush`?`flush`:`card`)==`flush`&&m_(r)&&y_(r)&&o&&!n;e.classList.toggle(`persona-artifact-chat-flush`,ce);let le=oe||ce?`none`:re,ue=oe?w:j?`none`:ne,de=oe?E:ie;ce&&(ue=`none`,de=`0`);let fe=k?.borderRadius!=null&&k.borderRadius!==``||u?.borderRadius!=null&&u.borderRadius!==``,pe=ce&&!fe?`0`:ie,me=R.scrollTop;e.style.cssText=``,F.style.cssText=``,I.style.cssText=``,L.style.cssText=``,R.style.cssText=``,Gn||(bt.style.cssText=``),ze&&(R.style.display=`none`),(a||o)&&(e.style.minWidth=`0`);let he=()=>{me<=0||(R.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(R.scrollTop===me)return;let e=R.scrollHeight-R.clientHeight;e<=0||(R.scrollTop=Math.min(me,e))})};if(_){F.classList.remove(`persona-bottom-6`,`persona-right-6`,`persona-left-6`,`persona-top-6`,`persona-bottom-4`,`persona-right-4`,`persona-left-4`,`persona-top-4`),F.style.cssText=`
|
|
40
|
+
`,t.addEventListener(`click`,()=>{d=e,_.forEach((t,n)=>{let r=n<e;t.classList.toggle(`selected`,r),t.setAttribute(`aria-checked`,n===e-1?`true`:`false`)})}),_.push(t),g.appendChild(t)}f.appendChild(g);let v=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,v=document.createElement(`textarea`),v.className=`persona-feedback-comment`,v.placeholder=a,v.rows=3,v.setAttribute(`aria-label`,`Additional comments`),e.appendChild(v),f.appendChild(e)}let y=document.createElement(`div`);y.className=`persona-feedback-actions`;let b=document.createElement(`button`);b.type=`button`,b.className=`persona-feedback-btn persona-feedback-btn-skip`,b.textContent=s,b.addEventListener(`click`,()=>{n?.(),u.remove()});let x=document.createElement(`button`);return x.type=`button`,x.className=`persona-feedback-btn persona-feedback-btn-submit`,x.textContent=o,x.addEventListener(`click`,async()=>{if(d===null)g.classList.add(`persona-feedback-shake`),setTimeout(()=>g.classList.remove(`persona-feedback-shake`),500);else{x.disabled=!0,x.textContent=`Submitting...`;try{let e=v?.value.trim()||void 0;await t(d,e),u.remove()}catch(e){x.disabled=!1,x.textContent=o,console.error(`[CSAT Feedback] Failed to submit:`,e)}}}),y.appendChild(b),y.appendChild(x),f.appendChild(y),u.appendChild(f),u}function Yv(e){let{onSubmit:t,onDismiss:n,title:r=`How likely are you to recommend us?`,subtitle:i=`On a scale of 0 to 10`,commentPlaceholder:a=`What could we do better? (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,lowLabel:l=`Not likely`,highLabel:u=`Very likely`}=e,d=document.createElement(`div`);d.className=`persona-feedback-container persona-feedback-nps`,d.setAttribute(`role`,`dialog`),d.setAttribute(`aria-label`,`Net Promoter Score feedback`);let f=null,p=document.createElement(`div`);p.className=`persona-feedback-content`;let m=document.createElement(`div`);m.className=`persona-feedback-header`;let h=document.createElement(`h3`);h.className=`persona-feedback-title`,h.textContent=r,m.appendChild(h);let g=document.createElement(`p`);g.className=`persona-feedback-subtitle`,g.textContent=i,m.appendChild(g),p.appendChild(m);let _=document.createElement(`div`);_.className=`persona-feedback-rating persona-feedback-rating-nps`,_.setAttribute(`role`,`radiogroup`),_.setAttribute(`aria-label`,`Likelihood rating from 0 to 10`);let v=document.createElement(`div`);v.className=`persona-feedback-labels`;let y=document.createElement(`span`);y.className=`persona-feedback-label-low`,y.textContent=l;let b=document.createElement(`span`);b.className=`persona-feedback-label-high`,b.textContent=u,v.appendChild(y),v.appendChild(b);let x=document.createElement(`div`);x.className=`persona-feedback-numbers`;let S=[];for(let e=0;e<=10;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-number-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`Rating ${e} out of 10`),t.textContent=String(e),t.dataset.rating=String(e),e<=6?t.classList.add(`persona-feedback-detractor`):e<=8?t.classList.add(`persona-feedback-passive`):t.classList.add(`persona-feedback-promoter`),t.addEventListener(`click`,()=>{f=e,S.forEach((t,n)=>{t.classList.toggle(`selected`,n===e),t.setAttribute(`aria-checked`,n===e?`true`:`false`)})}),S.push(t),x.appendChild(t)}_.appendChild(v),_.appendChild(x),p.appendChild(_);let C=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,C=document.createElement(`textarea`),C.className=`persona-feedback-comment`,C.placeholder=a,C.rows=3,C.setAttribute(`aria-label`,`Additional comments`),e.appendChild(C),p.appendChild(e)}let w=document.createElement(`div`);w.className=`persona-feedback-actions`;let T=document.createElement(`button`);T.type=`button`,T.className=`persona-feedback-btn persona-feedback-btn-skip`,T.textContent=s,T.addEventListener(`click`,()=>{n?.(),d.remove()});let E=document.createElement(`button`);return E.type=`button`,E.className=`persona-feedback-btn persona-feedback-btn-submit`,E.textContent=o,E.addEventListener(`click`,async()=>{if(f===null)x.classList.add(`persona-feedback-shake`),setTimeout(()=>x.classList.remove(`persona-feedback-shake`),500);else{E.disabled=!0,E.textContent=`Submitting...`;try{let e=C?.value.trim()||void 0;await t(f,e),d.remove()}catch(e){E.disabled=!1,E.textContent=o,console.error(`[NPS Feedback] Failed to submit:`,e)}}}),w.appendChild(T),w.appendChild(E),p.appendChild(w),d.appendChild(p),d}qa(),us(),Ds(),js(),Cs(),$o(),Xa(),mn(),Yt(),Y(),Ua(),wa(),zc(),yi(),xs(),ti(),fi(),er(),En(),Nn(),No(),go();const Xv=`persona-chat-history`,Zv=`data-persona-composer-reason`,Qv=`data-persona-composer-notice`,$v={"image/png":`png`,"image/jpeg":`jpg`,"image/jpg":`jpg`,"image/gif":`gif`,"image/webp":`webp`,"image/svg+xml":`svg`,"image/bmp":`bmp`,"image/tiff":`tiff`};function ey(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let e of n){if(e.kind!==`file`||!e.type.startsWith(`image/`))continue;let n=e.getAsFile();if(!n)continue;if(n.name){t.push(n);continue}let r=$v[n.type]??`png`;t.push(new File([n],`clipboard-image-${Date.now()}.${r}`,{type:n.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let n of Array.from(e.files??[]))n.type.startsWith(`image/`)&&t.push(n);return t}function ty(e){if(!e)return!1;let t=e.types;return t?typeof t.contains==`function`?t.contains(`Files`):Array.from(t).includes(`Files`):!1}function ny(e){return e?e===!0?{storage:`session`,keyPrefix:`persona-`,persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??`session`,keyPrefix:e.keyPrefix??`persona-`,persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function ry(e){try{let t=e===`local`?localStorage:sessionStorage,n=`__persist_test__`;return t.setItem(n,`1`),t.removeItem(n),t}catch{return null}}const iy=e=>!e||typeof e!=`object`?{}:{...e},ay=e=>e.filter(e=>!vu(e)).map(e=>({...e,streaming:!1})),oy=(e,t,n)=>{let r=e?.markdown?Fl(e.markdown):null,i=ql(e?.sanitize);e?.postprocessMessage&&i&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let a=!1,o=a=>{let o=a.text??``,s=a.message.rawContent??null;if(t){let e=t.process({text:o,raw:s??o,message:a.message,streaming:a.streaming});e!==null&&(o=e.text,e.persist||(a.message.__skipPersist=!0),e.resubmit&&!a.streaming&&n&&n())}let c=Kt()!==null,l;if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:o,raw:s??a.text??``});l=i?i(t):t}else if(r){let e=a.streaming?eu(o):o,t=r(e);l=i&&c?i(t):t}else l=Rl(o);return l};return e=>{try{return o(e)}catch(t){return a||(a=!0,console.error(`[Persona] markdown rendering failed; falling back to plain text:`,t)),Rl(e.text??``)}}};function sy(e){let t=q(`div`,`persona-attachment-drop-overlay`);e?.background&&t.style.setProperty(`--persona-drop-overlay-bg`,e.background),e?.backdropBlur!==void 0&&t.style.setProperty(`--persona-drop-overlay-blur`,e.backdropBlur),e?.border&&t.style.setProperty(`--persona-drop-overlay-border`,e.border),e?.borderRadius&&t.style.setProperty(`--persona-drop-overlay-radius`,e.borderRadius),e?.inset&&t.style.setProperty(`--persona-drop-overlay-inset`,e.inset),e?.labelSize&&t.style.setProperty(`--persona-drop-overlay-label-size`,e.labelSize),e?.labelColor&&t.style.setProperty(`--persona-drop-overlay-label-color`,e.labelColor);let n=e?.iconName??`upload`,r=e?.iconSize??`48px`,i=e?.iconColor??`rgba(59, 130, 246, 0.6)`,a=e?.iconStrokeWidth??.5,o=K(n,r,i,a);if(o&&t.appendChild(o),e?.label){let n=q(`span`,`persona-drop-overlay-label`);n.textContent=e.label,t.appendChild(n)}return t}const cy=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t?{...t,...r}:r}return n},ly=e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:cy(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}),uy=(e,t,n)=>{if(e==null)throw Error(`createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).`);e.id&&!e.getAttribute(`data-persona-instance`)&&e.setAttribute(`data-persona-instance`,e.id),e.hasAttribute(`data-persona-root`)||e.setAttribute(`data-persona-root`,`true`);let r=bo(t),a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Set,s=Dl((e,t)=>{Gi.delete(e);let n=Array.from(z.querySelectorAll(`[data-message-id]`)).find(t=>t.dataset.messageId===e);n&&(t===`tool`?$g(e,n,a,r):Hg(e,n,o))}),c=/* @__PURE__ */ new Map,l=()=>{Ta({delayMs:r.tooltip?.delayMs??200,skipDelayMs:r.tooltip?.skipDelayMs??300})};l();let u=r.features;r=$_(r);let d=fv.getForInstance(r.plugins),f=Rc(e),p=[],m=!1,h=zg(()=>r),g=null,_=null,v=null,y=!1,x=null,S=e=>{g=e,e.initApprovalUi({webMcpToolTitle:xn});let t=e.createBuiltInApprovalPlugin(c);_=t.plugin,v=t.teardown},C=()=>{if(g)return g;let e=o_();return e?(S(e),e):(a_().then(e=>{y||g||(S(e),x?.())}).catch(()=>{}),null)},w=!1,T=!1,E=null,D=(e,t,n,r)=>{if(!e.querySelector(`[data-tv-form]`))return;let i=dv();i?i.enhanceWithForms(e,t,n,r):uv().then(()=>{w||T||!E||(T=!0,E())}).catch(()=>{})};r.components&&u_.registerAll(r.components);let O=_v(),k=r.persistState===!1?null:r.storageAdapter??kv(Ov(typeof r.persistState==`object`?r.persistState.keyPrefix:void 0)),ee=!!r.clientToken&&typeof r.reconnectStream!=`function`,te={},re=null,ie,ae=new Promise(e=>{ie=e}),oe=()=>{},A=new Promise(e=>{oe=e}),j,se=!1,ce=e=>{if(r.onStateLoaded)try{let t=r.onStateLoaded(e);if(t&&typeof t==`object`&&`state`in t){let{state:e,open:n}=t;return n&&(se=!0),e}return t}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}return e};if(k?.load)try{let e=k.load();if(e&&typeof e.then==`function`)re=e.then(e=>ce(e??{messages:[],metadata:{}}));else{let t=ce(e??{messages:[],metadata:{}});t.metadata&&(te=iy(t.metadata)),t.messages?.length&&(r={...r,initialMessages:t.messages}),t.artifacts?.length&&(r={...r,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),j=t.draft}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to load stored state:`,e)}else if(r.onStateLoaded)try{let e=ce({messages:[],metadata:{}});e.messages?.length&&(r={...r,initialMessages:e.messages})}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}re||ie();let le=()=>te,ue=e=>{te=e({...te})??{},Ra()},de=r.actionParsers&&r.actionParsers.length?r.actionParsers:[bv],fe=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Sv.message,Sv.messageAndClick],pe=wv({parsers:de,handlers:fe,getSessionMetadata:le,updateSessionMetadata:ue,emit:O.emit,documentRef:typeof document<`u`?document:null});pe.syncFromMetadata();let M=r.launcher?.enabled??!0,me=r.launcher?.autoExpand??!1,he=r.autoFocusInput??!1,ge=me,_e=M,ve=r.layout?.header?.layout,ye=!1,N=()=>Vm(r),be=()=>M||N(),P=N()?!1:!M||me,xe=!1,Se=null,Ce=()=>{xe=!0,Se&&clearTimeout(Se),Se=setTimeout(()=>{xe&&=(typeof console<`u`&&console.warn(`[AgentWidget] Resubmit requested but no injection occurred within 10s`),!1)},1e4)},we=oy(r,pe,Ce),Te=r.features?.showReasoning??!0,Ee=r.features?.showToolCalls??!0,De=r.features?.showEventStreamToggle??!1,Oe=r.features?.scrollToBottom??{},ke=r.features?.scrollBehavior??{},Ae=()=>(typeof r.persistState==`object`?r.persistState?.keyPrefix:void 0)??`persona-`,je=`${Ae()}event-stream`,Me=null,Ne=r.features?.eventStream?.maxEvents??2e3,Pe=null,Fe=null,Ie=null,Le=!1,Re=null,ze=!1,Be=null,Ve=0,He=(e,t)=>{Pe?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},Ue=(e,t)=>{Fe?.processEvent(e,t),Pe?He(e,t):Ie&&(Ie.length>=Ne&&Ie.shift(),Ie.push({type:e,payload:t}))},We=()=>{!Pe&&De&&(Ie??=[],l_().then(e=>{if(Le||Pe||!De)return;Me=new e.EventStreamStore(je),Pe=new e.EventStreamBuffer(Ne,Me),Fe??=new e.ThroughputTracker,Me.open().then(()=>Pe?.restore()).catch(e=>{r.debug&&console.warn(`[AgentWidget] IndexedDB not available for event stream:`,e)});let t=Ie??[];Ie=null;for(let e of t)Fe?.processEvent(e.type,e.payload),He(e.type,e.payload)}).catch(()=>{}))};De&&We();let Ge=!1,Ke=null,qe=()=>{},Je=()=>{},Ye=()=>{},Xe=()=>{},Ze=()=>{},Qe=()=>ze||Ge&&Ke===`panel`,$e={onCopy:e=>{O.emit(`message:copy`,e),Q?.isClientTokenMode()&&Q.submitMessageFeedback(e.id,`copy`).catch(e=>{r.debug&&console.error(`[AgentWidget] Failed to submit copy feedback:`,e)}),r.messageActions?.onCopy?.(e)},onFeedback:e=>{O.emit(`message:feedback`,e),Q?.isClientTokenMode()&&Q.submitMessageFeedback(e.messageId,e.type).catch(e=>{r.debug&&console.error(`[AgentWidget] Failed to submit feedback:`,e)}),r.messageActions?.onFeedback?.(e)}};r.statusIndicator;let et=(e,t=r.statusIndicator??{})=>e===`idle`?t.idleText??gi.idle:e===`connecting`?t.connectingText??gi.connecting:e===`connected`?t.connectedText??gi.connected:e===`error`?t.errorText??gi.error:e===`paused`?t.pausedText??gi.paused:e===`resuming`?t.resumingText??gi.resuming:gi[e];function tt(e,t,n,r){if(!N()&&(n.mode===`transient`||e.classList.contains(`persona-mb-2`))&&(Ka(e,ct,n),Ga(e,n,r)),!(e.hasAttribute(Zv)||e.hasAttribute(Qv))){if(r===`idle`&&n.idleLink){e.textContent=``;let r=document.createElement(`a`);r.href=n.idleLink,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=t,r.style.color=`inherit`,r.style.textDecoration=`none`,e.appendChild(r)}else e.textContent=t}}let nt=Fg({config:r,showClose:be()}),{wrapper:F,panel:I,pillRoot:rt}=nt.shell,it=nt.panelElements,{container:L,body:R,messagesWrapper:z,starterSuggestions:at,transcriptSuggestions:ot,suggestions:st,textarea:B,sendButton:V,composerForm:ct,statusText:lt,welcomeHost:ut,welcomeIconHolder:dt,greetingHost:ft,introKicker:pt,introTitle:mt,introSubtitle:ht,closeButton:H,iconHolder:gt,headerTitle:_t,headerSubtitle:vt,header:yt,footer:bt,actionsRow:xt}=it,St=it.leftActions,Ct=it.rightActions,wt=it.sendButtonWrapper,Tt=it.setSendButtonMode,U=it.micButton,Et=it.micButtonWrapper,Dt=it.attachmentButton,Ot=it.attachmentButtonWrapper,kt=it.attachmentInput,At=it.attachmentPreviewsContainer;L.classList.add(`persona-relative`),R.classList.add(`persona-relative`);let jt=()=>Oe.label??``,W=()=>Oe.iconName??`arrow-down`,Mt=()=>Oe.enabled!==!1,Nt=()=>ke.mode??`anchor-top`,Pt=()=>Nt()===`follow`||Nt()===`anchor-top`&&pa,Ft=()=>ke.anchorTopOffset??16,It=()=>ke.restorePosition??`bottom`,Lt=()=>ke.pauseOnInteraction===!0,Rt=()=>ke.showActivityWhilePinned!==!1,zt=()=>ke.announce===!0,Bt=()=>ke.scrollbar??`on-scroll`,Vt=q(`button`,`persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer`);Vt.type=`button`,Vt.style.display=`none`,Vt.setAttribute(`data-persona-scroll-to-bottom`,`true`);let Ht=q(`span`,`persona-flex persona-items-center`),Gt=q(`span`,``),qt=q(`span`,``);qt.setAttribute(`data-persona-scroll-to-bottom-count`,``),qt.style.display=`none`,Vt.append(Ht,Gt,qt),L.appendChild(Vt);let Yt=q(`div`,`persona-stream-anchor-spacer`);Yt.setAttribute(`aria-hidden`,`true`),Yt.setAttribute(`data-persona-anchor-spacer`,``),Yt.style.flexShrink=`0`,Yt.style.pointerEvents=`none`,Yt.style.height=`0px`,Yt.style.display=`none`,R.appendChild(Yt);let Xt=q(`div`,`persona-sr-only`);Xt.setAttribute(`aria-live`,`polite`),Xt.setAttribute(`aria-atomic`,`true`),Xt.setAttribute(`role`,`status`),Xt.setAttribute(`data-persona-live-region`,``),Object.assign(Xt.style,{position:`absolute`,width:`1px`,height:`1px`,margin:`-1px`,padding:`0`,overflow:`hidden`,clip:`rect(0 0 0 0)`,clipPath:`inset(50%)`,whiteSpace:`nowrap`,border:`0`}),L.appendChild(Xt);let Zt=null,Qt=null,$t=e=>{zt()&&e&&(Qt=e,Zt===null&&(Zt=setTimeout(()=>{Zt=null,Qt&&zt()&&(Xt.textContent=Qt),Qt=null},400)))},en=()=>{let t=e.ownerDocument.defaultView??window;return(r.launcher?.mobileFullscreen??!0)&&t.innerWidth<=(r.launcher?.mobileBreakpoint??640)&&(M||Bm(r))||r.launcher?.fullHeight===!0&&!r.launcher.sidebarMode&&!Bm(r)},tn=()=>mg(r,en()),nn=`empty`,rn=0,an=()=>rn||parseFloat(e.style.getPropertyValue(`--persona-composer-lift`))||0,on=()=>{let e=bt.style.display===`none`?0:bt.offsetHeight;Vt.style.bottom=`${e+an()+12}px`};on();let sn=()=>{Gn||(bt.style.marginBottom=rn>0?`${rn}px`:``)},ln=()=>{let t=Lp(r,N()),n=tn();e.setAttribute(`data-persona-welcome-fullscreen`,String(en())),e.setAttribute(`data-persona-welcome-layout`,n.layout??`top`),e.setAttribute(`data-persona-welcome-layout-explicit`,r.welcome?.layout??``),e.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`);let i=bt.style.display===`none`?0:bt.offsetHeight,a=n.anchor===`center`&&nn===`empty`?Rp(n.anchorComposerTop)??Rp(`44%`):null,o=a!==null&&n.layout===`centered`&&r.welcome?.anchor===void 0&&r.welcome?.anchorComposerTop===void 0,s=o?getComputedStyle(R):null,c=parseFloat(e.style.getPropertyValue(`--persona-composer-overlay-height`))||0,l=parseFloat(e.style.getPropertyValue(`--persona-composer-lift`))||0,u=Math.max(0,(parseFloat(s?.paddingBottom??``)||0)-(t===`overlay`?c+l:0)),d=o?R.getBoundingClientRect().top-L.getBoundingClientRect().top:0,f=!o||ut.hidden?0:(ut.querySelector(`[data-persona-welcome-plugin]`)??ut).offsetHeight,p=a===null||N()?0:o?Math.max(0,Math.round((L.clientHeight-d-f-u-i)/2)):zp({columnHeight:L.clientHeight,footerHeight:i,fraction:a});e.style.setProperty(`--persona-composer-overlay-height`,`${i}px`),e.style.setProperty(`--persona-composer-lift`,`${t===`overlay`?p:0}px`),rn=t===`block`?p:0,sn(),on()},un=()=>{let e=!!jt();Vt.setAttribute(`aria-label`,jt()||`Jump to latest`),Vt.title=jt(),Vt.setAttribute(`data-persona-scroll-to-bottom-has-label`,e?`true`:`false`),Ht.innerHTML=``;let t=K(W(),`14px`,`currentColor`,2);t?(Ht.appendChild(t),Ht.style.display=``):Ht.style.display=`none`,Gt.textContent=jt(),Gt.style.display=e?``:`none`};un();let dn=null,fn=null,G=Dd();G.subscribe(e=>{try{L.dispatchEvent(new CustomEvent(`persona:composer:state`,{detail:e,bubbles:!0,composed:!0}))}catch{}});let pn=()=>{G.setText(B?.value??``)},mn=()=>{G.setMentionRefs(fn?.getMentionRefs()??[])},hn=e=>({id:e.id,name:e.file.name,mimeType:e.file.type,size:e.file.size,status:e.status,progress:e.progress,error:e.error}),gn=e=>{let t=Object.freeze(e.map(hn));G.setAttachments(t);try{r.attachments?.onChange?.(t)}catch(e){console.error(`[AgentWidget] attachments.onChange failed:`,e)}ms()};G.setSelectedModelId(r.composer?.selectedModelId);let _n=()=>r.composer?.modes??[],vn=()=>_f(_n(),r.composer?.modeGroups);{let e=bf(r.composer?.defaultActiveModeIds??[],_n());e.length&&G.setActiveModeIds(e)}function yn(e){if(G.getState().selectedModelId!==e){G.setSelectedModelId(e),Cn?.repaint();try{r.composer?.onModelChange?.(e)}catch(e){console.error(`[AgentWidget] composer.onModelChange failed:`,e)}}}function bn(e){G.setActiveModeIds(e),Tn?.render(e,vn()),En.forEach(e=>e.repaint()),Y?.resolve(),Ys(),lr()}function Sn(e){bn(yf(G.getState().activeModeIds,e,_n(),r.composer?.modeGroups))}let Cn=null,wn=null,Tn=null,En=/* @__PURE__ */ new Map,Dn=null;function On(e){G.setQuote(e),Dn?.render(G.getState().quote),lr(),Ha()}let kn=!1;function An(){let e=r.composer?.streamingSubmitBehavior??`block`;return e===`interrupt`?r.clientToken?`interrupt`:(!kn&&r.debug===!0&&(kn=!0,typeof console<`u`&&console.warn(`[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".`)),`block`):e}let Mn=null;function Nn(e){G.setPendingSubmission(e),Mn?.render(G.getState().pendingSubmission),lr()}let Pn=e=>{let t=En.get(e);if(t)return t;let n=Cf({groupId:e,getGroup:()=>r.composer?.modeGroups?.find(t=>t.id===e),getModes:()=>_n().filter(t=>t.groupId===e),getActiveIds:()=>G.getState().activeModeIds,onSelect:e=>Sn(e)});return En.set(e,n),n},Fn=()=>{let e=[],t=G.getState().activeModeIds,n=/* @__PURE__ */ new Set;if(_n().forEach((i,a)=>{if(hf(i.groupId,r.composer?.modeGroups)){let t=i.groupId;if(n.has(t))return;n.add(t);let o=Pn(t);o.action.order=pf(a),o.action.label=r.composer?.modeGroups?.find(e=>e.id===t)?.label??t,e.push(o.action)}else e.push({id:ff(i.id),kind:`button`,placement:`start`,order:pf(a),presentation:i.presentation??`auto`,label:i.label,shortLabel:i.shortLabel,iconName:i.iconName,pressed:t.includes(i.id),onSelect:()=>Sn(i.id)})}),r.composer?.models?.length&&!d.some(e=>e.renderComposer)){let t=r.composer?.modelPicker?.presentation??`native`;(!Cn||wn!==t)&&(wn=t,Cn=sf({getModels:()=>r.composer?.models??[],getSelectedModelId:()=>G.getState().selectedModelId,onSelect:e=>yn(e),presentation:t,getSuffix:()=>r.composer?.modelPicker?.suffix})),e.push(Cn.action)}return e},In=null,Ln=d.find(e=>e.renderHeader);if(Ln?.renderHeader){let e=Ln.renderHeader({config:r,defaultRenderer:()=>{let e=oh({config:r,showClose:be()});return sh(L,e,r),e.header},onClose:()=>$o(!1,`user`)});if(e){let t=yt;t&&(t.replaceWith(e),yt=e,nt.header.element=e)}}let zn=()=>{Re&&(R.style.display=`none`,bt.parentNode?.insertBefore(Re.element,bt),Re.update())},Bn=()=>{if(!Pe){We();return}if(ze=!0,Re?zn():l_().then(e=>{!Re&&ze&&Pe&&(Re=e.createEventStreamView({buffer:Pe,getFullHistory:()=>Pe.getAllFromStore(),onClose:()=>Hn(),config:r,plugins:d,getThroughput:()=>Fe?.getMetric()??{status:`idle`},renderIconByName:K}),zn())}).catch(()=>{Hn()}),Un){Un.style.boxShadow=`inset 0 0 0 1.5px ${rh.actionIconColor}`;let e=r.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&Un.classList.add(e))}let e=()=>{if(!ze)return;let t=Date.now();t-Ve>=200&&(Re?.update(),Ve=t),Be=requestAnimationFrame(e)};Ve=0,Be=requestAnimationFrame(e),ao(),O.emit(`eventStream:opened`,{timestamp:Date.now()})},Hn=()=>{if(ze){if(ze=!1,Re&&Re.element.remove(),R.style.display=``,Un){Un.style.boxShadow=``;let e=r.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&Un.classList.remove(e))}Be!==null&&(cancelAnimationFrame(Be),Be=null),ao(),O.emit(`eventStream:closed`,{timestamp:Date.now()})}},Un=null;if(De){let e=r.features?.eventStream?.classNames,t=`persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1`+(e?.toggleButton?` `+e.toggleButton:``);Un=q(`button`,t),Un.style.width=`28px`,Un.style.height=`28px`,Un.style.color=rh.actionIconColor,Un.type=`button`,Un.setAttribute(`aria-label`,`Event Stream`),Un.title=`Event Stream`;let n=Jt(i,`18px`,`currentColor`,1.5);n&&Un.appendChild(n);let a=it.clearChatButtonWrapper,o=it.closeButtonWrapper,s=a||o;s&&s.parentNode===yt?yt.insertBefore(Un,s):yt.appendChild(Un),Un.addEventListener(`click`,()=>{ze?Hn():Bn()})}let Wn=e=>{let t=r.attachments;if(!t?.enabled)return;let n=e.querySelector(`[data-persona-composer-attachment-previews]`)??e.querySelector(`.persona-attachment-previews`);if(!n){n=q(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),n.setAttribute(`data-persona-composer-attachment-previews`,``),n.style.display=`none`;let t=e.querySelector(`[data-persona-composer-form]`);t?.parentNode?t.parentNode.insertBefore(n,t):e.insertBefore(n,e.firstChild)}if(!(e.querySelector(`[data-persona-composer-attachment-input]`)??e.querySelector(`input[type="file"]`))){let n=q(`input`);n.type=`file`,n.setAttribute(`data-persona-composer-attachment-input`,``),n.accept=(t.allowedTypes??Qo).join(`,`),n.multiple=(t.maxFiles??4)>1,n.style.display=`none`,n.setAttribute(`aria-label`,t.buttonTooltipText??`Attach files`),e.appendChild(n)}},Gn=!1,Kn=e=>{let t=d.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let n=r.composer,i=m?Q.isStreaming():!1;return t.renderComposer({config:r,defaultRenderer:e,requestRender:()=>Xu(),storage:h(t.id),onSubmit:e=>{Q&&!Q.isStreaming()&&hl(e.trim(),{consumeDraft:!1})},streaming:i,disabled:i,openAttachmentPicker:()=>{is()||kt?.click()},models:n?.models,selectedModelId:G.getState().selectedModelId??n?.selectedModelId,onModelChange:e=>yn(e),onVoiceToggle:r.voiceRecognition?.enabled===!0?()=>{In?.()}:void 0})},qn=Kn(()=>bh({config:r}).footer);qn&&(nt.replaceComposer(qn),bt=nt.composer.footer,Gn=!0);let Jn=null,Yn=e=>{ct=e.form,B=e.input,wt=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(V=e.sendButton),e.micButton&&(U=e.micButton,Et=e.micButton.parentElement),e.found.status&&(lt=e.found.status),e.found.suggestions&&(st=e.found.suggestions),e.attachmentButton&&(Dt=e.attachmentButton,Ot=e.attachmentButton.parentElement),kt=e.attachmentInput??null,At=e.attachmentPreviews??null,e.found.actionsRow&&(xt=e.found.actionsRow),St=e.found.actionsStart,Ct=e.found.actionsEnd};function Xn(){let e=B;if(!e)return;let t=r.composer?.inputAttributes,n=!t?.ariaLabel&&!(e instanceof HTMLTextAreaElement)?e.getAttribute(`aria-label`):null;cs(e,t),n&&e.setAttribute(`aria-label`,n),ss(e,{submitKey:r.composer?.submitKey,insertNewlineOnTouchEnter:r.composer?.insertNewlineOnTouchEnter,coarsePointer:rs(e)}),ns(e,ts(r.composer?.maxLines,N()?5:3))}let Zn=e=>{Jn=Ad(e,{debug:r.debug===!0}),Jn&&Yn(Jn),Xn()};Wn(bt),Zn(bt),pn();let Qn=Ip(r,N());Qn&&(z.style.maxWidth=Qn,z.style.marginLeft=`auto`,z.style.marginRight=`auto`,z.style.width=`100%`,ft.style.maxWidth=Qn,ft.style.marginLeft=`auto`,ft.style.marginRight=`auto`,ft.style.width=`100%`,at.style.maxWidth=Qn,ot.style.maxWidth=Qn,ot.style.marginLeft=`auto`,ot.style.marginRight=`auto`,ot.style.width=`100%`);let $n=()=>{let e=Ip(r,N());if(e&&!N())for(let t of[ct,st,At,lt])t&&(t.style.maxWidth=e,t.style.marginLeft=`auto`,t.style.marginRight=`auto`,t.style.width=`100%`)};$n();let er=()=>{r.attachments?.enabled&&kt&&At&&(dn?dn.remountPreviews(At):(dn=wd.fromConfig(r.attachments,gn),dn.setPreviewsContainer(At)),Jn?.addListener(kt,`change`,e=>{let t=e.target;dn?.handleFileSelect(t.files),t.value=``}),L.querySelector(`.persona-attachment-drop-overlay`)||L.appendChild(sy(r.attachments.dropOverlay)))};er();let J=()=>fn?.prefetch(),tr=()=>{if(!r.contextMentions?.enabled||!B)return;let e=Gs();if(!e){let e=B;Us().then(()=>{!fn&&B===e&&e.isConnected&&(tr(),Y?.resolve())},()=>{});return}let t=Jn?.header??null,n=t?uf(t):void 0;if(fn=e.createContextMentionOrchestrator({deps:{loadContextMentions:Es,loadContextMentionsInline:As,renderLucideIcon:K,createMentionButton:Ss},config:r,textarea:B,anchor:ct??B,getMessages:()=>Q.getMessages(),liveRegionHost:L,chipRow:n}),fn&&!n){let e=B;e.parentElement?.insertBefore(fn.contextRow,e)}};tr();let Y=null,nr={getState:()=>G.getState(),getValue:()=>B?.value??``,setValue:e=>{B&&(B.value=e,B.dispatchEvent(new Event(`input`,{bubbles:!0})),pn())},submit:()=>{Nf(Jn?.form??null)},openAttachmentPicker:()=>{is()||kt?.click()},toggleVoice:()=>{In?.()},requestRender:()=>Y?.resolve()},rr=()=>{let e=[];return(fn?.affordanceButtons??[]).forEach((t,n)=>{e.push({id:`core:mention-${n}`,placement:`start`,order:zd.mention+n,element:t,managed:!0})}),Ot&&e.push({id:`core:attachment`,placement:`start`,order:zd.attachment,element:Ot}),Et&&e.push({id:`core:mic`,placement:`end`,order:zd.mic,element:Et}),wt&&e.push({id:`core:send`,placement:`end`,order:zd.send,element:wt}),e},ir=()=>{Y?.destroy(),Y=rf({getBindings:()=>Jn,collect:()=>({builtIns:rr(),configActions:[...Fn(),...r.composer?.actions??[]],plugins:d,contributionContext:{config:r,getState:()=>G.getState(),requestRender:()=>Y?.resolve()},debug:r.debug===!0}),actionContext:nr,getState:()=>G.getState(),getOverflow:()=>r.composer?.actionOverflow,reportError:(e,t)=>{typeof console<`u`&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),Y.resolve()};ir();let ar=()=>{if(Tn?.destroy(),Tn=null,!vn().length)return;let e=Jn?.header;e&&(Tn=df({row:uf(e),onRemove:e=>Sn(e),initialIds:G.getState().activeModeIds}),Tn.render(G.getState().activeModeIds,vn()))};ar();let or=()=>{Dn?.destroy(),Dn=null,Mn?.destroy(),Mn=null;let e=Jn?.header;e&&(Dn=wf({onDismiss:()=>On(void 0)}),e.appendChild(Dn.element),Dn.render(G.getState().quote),An()===`defer-one`&&(Mn=Tf({onEdit:()=>tl(),onRemove:()=>Nn(void 0)}),e.appendChild(Mn.element),Mn.render(G.getState().pendingSubmission)))};or();let sr=jf(),cr=()=>{let e=Jn?.header?.querySelector(cf);if(e)return e.childElementCount>0;let t=G.getState();return t.mentionRefs.length>0||bf(t.activeModeIds,vn()).length>0};function lr(){let e=G.getState(),t=sr.observe(Mf(B),e.text);bt.toggleAttribute(`data-persona-composer-compact`,Af({text:e.text,wrapped:t,hasAttachments:e.attachments.length>0,hasChips:cr(),hasQuote:e.quote!==void 0,hasPendingSubmission:e.pendingSubmission!==void 0}))}function ur(){r.composer?.layout===`single-row`&&!N()?bt.setAttribute(`data-persona-composer-layout`,`single-row`):bt.removeAttribute(`data-persona-composer-layout`)}ur(),G.subscribe(()=>{Y?.sync(),ms(),gs(),lr(),Ha()}),gs();let dr=!1,fr=e=>{if(dr||r.debug!==!0)return;let t=[`messages`,`composer`].filter(t=>e[t]);t.length&&(dr=!0,console.warn(`[persona] layout.slots.${t.join(` and layout.slots.`)} ${t.length>1?`are`:`is`} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let e=r.layout?.slots??{};fr(e);let t=e=>{switch(e){case`body-top`:return R.querySelector(`[data-persona-intro-card]`);case`messages`:return z;case`footer-top`:return st;case`composer`:return ct;case`footer-bottom`:return lt;default:return null}},n=(e,t)=>{switch(e){case`header-left`:case`header-center`:case`header-right`:if(e===`header-left`)yt.insertBefore(t,yt.firstChild);else if(e===`header-right`)yt.appendChild(t);else{let e=yt.querySelector(`.persona-flex-col`);e?e.parentNode?.insertBefore(t,e.nextSibling):yt.appendChild(t)}break;case`body-top`:{let e=R.querySelector(`[data-persona-intro-card]`);e?e.replaceWith(t):R.insertBefore(t,R.firstChild);break}case`body-bottom`:R.appendChild(t);break;case`footer-top`:st.replaceWith(t);break;case`footer-bottom`:lt.replaceWith(t)}};for(let[i,a]of Object.entries(e))if(a)try{let e=a({config:r,defaultContent:()=>t(i)});e&&n(i,e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Error rendering slot "${i}":`,e)}})(),z.addEventListener(`click`,e=>{let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`button[data-persona-copy-tool-detail]`);n&&(e.preventDefault(),e.stopPropagation(),Jg(n))});let pr=e=>{let t=e.target.closest(`button[data-expand-header="true"]`);if(!t)return;let n=t.closest(`.persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble`);if(!n)return;let i=n.getAttribute(`data-message-id`);if(!i)return;_a(),oo();let l=t.getAttribute(`data-bubble-type`);if(n.classList.contains(`persona-activity-row`)){s.manual(i);let e=n.parentElement?.closest(`[data-persona-tool-group]`);e?.dataset.messageId&&s.manual(e.dataset.messageId)}if(l===`reasoning`)o.has(i)?o.delete(i):o.add(i),Hg(i,n,o);else if(l===`tool`)a.has(i)?a.delete(i):a.add(i),$g(i,n,a,r);else if(l===`approval`&&g){let e=((r.approval===!1?void 0:r.approval)?.detailsDisplay??`collapsed`)===`expanded`,t=c.get(i)??e;c.set(i,!t),g.updateApprovalDetailsUI(i,n,r,c)}Gi.delete(i)};z.addEventListener(`pointerdown`,e=>{e.target.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),pr(e))}),z.addEventListener(`click`,e=>{e.detail===0&&e.target.closest(`.persona-activity-row`)&&pr(e)}),z.addEventListener(`keydown`,e=>{let t=e.target;(e.key===`Enter`||e.key===` `)&&t.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),pr(e))}),z.addEventListener(`copy`,e=>{let{clipboardData:t}=e;if(!t)return;let n=z.getRootNode(),r=typeof n.getSelection==`function`?n.getSelection():window.getSelection();if(!r||r.isCollapsed)return;let i=r.toString(),a=Vp(i);a&&a!==i&&(t.setData(`text/plain`,a),e.preventDefault())});let mr=/* @__PURE__ */ new Map,hr=null,gr=`idle`,_r={idle:{icon:`volume-2`,label:`Read aloud`},loading:{icon:`loader-circle`,label:`Loading…`},playing:{icon:`pause`,label:`Pause`},paused:{icon:`play`,label:`Resume`}},vr=(e,t)=>{let{icon:n,label:r}=_r[t];e.setAttribute(`aria-label`,r),e.title=r,e.setAttribute(`aria-pressed`,t===`idle`?`false`:`true`),e.classList.toggle(`persona-message-action-active`,t!==`idle`),e.classList.toggle(`persona-message-action-loading`,t===`loading`);let i=K(n,14,`currentColor`,2);i&&(e.innerHTML=``,e.appendChild(i))},yr=()=>{z.querySelectorAll(`[data-action="read-aloud"]`).forEach(e=>{let t=e.closest(`[data-actions-for]`)?.getAttribute(`data-actions-for`)??null;vr(e,t&&t===hr?gr:`idle`)})};z.addEventListener(`click`,e=>{let t=e.target.closest(`.persona-message-action-btn[data-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`[data-actions-for]`);if(!n)return;let i=n.getAttribute(`data-actions-for`);if(!i)return;let a=t.getAttribute(`data-action`);if(a===`copy`){let e=Q.getMessages().find(e=>e.id===i);if(e&&$e.onCopy){let n=e.content||``;navigator.clipboard.writeText(n).then(()=>{t.classList.add(`persona-message-action-success`);let e=Jt(b,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e)),setTimeout(()=>{t.classList.remove(`persona-message-action-success`);let e=Jt(ne,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))},2e3)}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to copy message:`,e)}),$e.onCopy(e)}}else if(a===`read-aloud`)Q.toggleReadAloud(i);else if(a===`upvote`||a===`downvote`){let e=(mr.get(i)??null)===a,r=a===`upvote`?`thumbs-up`:`thumbs-down`;if(e){mr.delete(i),t.classList.remove(`persona-message-action-active`);let e=K(r,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))}else{let e=a===`upvote`?`downvote`:`upvote`,o=n.querySelector(`[data-action="${e}"]`);if(o){o.classList.remove(`persona-message-action-active`);let t=K(e===`upvote`?`thumbs-up`:`thumbs-down`,14,`currentColor`,2);t&&(o.innerHTML=``,o.appendChild(t))}mr.set(i,a),t.classList.add(`persona-message-action-active`);let s=K(r,14,`currentColor`,2);s&&(s.setAttribute(`fill`,`currentColor`),t.innerHTML=``,t.appendChild(s)),t.classList.remove(`persona-message-action-pop`),t.offsetWidth,t.classList.add(`persona-message-action-pop`);let c=Q.getMessages().find(e=>e.id===i);c&&$e.onFeedback&&$e.onFeedback({type:a,messageId:c.id,message:c})}}else if(a===`regenerate`)br?.regenerate(i);else if(a===`edit`)br?.edit(i);else if(a===`quote`)br?.quote(i);else if(a?.startsWith(`custom:`)){let e=a.slice(7),t=r.messageActions?.custom?.find(t=>t.id===e),n=Q.getMessages().find(e=>e.id===i);if(!t||!n)return;try{t.onSelect(n)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let br=null;z.addEventListener(`click`,e=>{let t=e.target.closest(`button[data-approval-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`.persona-approval-bubble`);if(!n)return;let r=n.getAttribute(`data-message-id`);if(!r)return;let i=t.getAttribute(`data-approval-action`);if(!i)return;let a=i===`approve`?`approved`:`denied`,o=Q.getMessages().find(e=>e.id===r);if(!o?.approval)return;let s=n.querySelector(`[data-approval-buttons]`);s&&s.querySelectorAll(`button`).forEach(e=>{e.disabled=!0,e.style.opacity=`0.5`,e.style.cursor=`not-allowed`}),fl(o.approval)?Q.resolveWebMcpApproval(r,a):Q.resolveApproval(o.approval,a)});let X=null,Sr=!1,wr=null,Tr=()=>{},Er=`none`,Dr=null,Or={artifacts:[],selectedId:null},kr=!1,Ar=!1,jr=!1,Mr=!1,Nr=()=>Mr||Or.artifacts.some(e=>jn(r.features?.artifacts,e)===`panel`),Pr=()=>Or.artifacts.length>0&&!kr&&Nr(),Fr={current:null},Ir=(e,t)=>{let n=Q.getArtifactById(t),r=n?.markdown,i=n?.title||`artifact`,a=n?.file,o=n?.artifactType??`markdown`;if(!r){let t=(e.closest(`[data-open-artifact], [data-artifact-inline]`)?.closest(`[data-message-id]`))?.getAttribute(`data-message-id`);if(t){let e=Q.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);r=t?.props?.markdown,i=t?.props?.title||i,t?.props?.file&&typeof t.props.file==`object`&&(a=t.props.file),!n&&typeof t?.props?.artifactType==`string`&&(o=t.props.artifactType)}catch{}}}return{markdown:r,title:i,file:a,artifactType:o}};z.addEventListener(`click`,e=>{let t=e.target.closest(`[data-download-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-download-artifact`);if(!n||r.features?.artifacts?.onArtifactAction?.({type:`download`,artifactId:n})===!0)return;let{markdown:i,title:a,file:o}=Ir(t,n);if(!i)return;let s=b_();s&&s.triggerArtifactDownload(s.downloadInfoFor({title:a,markdown:i,file:o}))}),z.addEventListener(`click`,e=>{let t=e.target.closest(`[data-artifact-custom-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-artifact-custom-action`);if(!n)return;let i=t.closest(`[data-artifact-inline]`),a=i?null:t.closest(`[data-open-artifact]`),o=i?i.getAttribute(`data-artifact-inline`):a?.getAttribute(`data-open-artifact`)??null,s=(i?r.features?.artifacts?.inlineActions:r.features?.artifacts?.cardActions)?.find(e=>e.id===n);if(!s)return;let{markdown:c,title:l,file:u,artifactType:d}=Ir(t,o??``),f={artifactId:o,title:l,artifactType:d,markdown:c,file:u};try{Promise.resolve(s.onClick(f)).catch(()=>{})}catch{}}),z.addEventListener(`click`,e=>{let t=e.target.closest(`[data-copy-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-copy-artifact`);if(!n)return;let r=Q.getArtifactById(n),i=b_();if(!i)return;let a=``;if(r)a=i.artifactCopyText(r);else{let{markdown:e,file:r,artifactType:o}=Ir(t,n);o===`markdown`&&(a=i.artifactCopyText({id:n,artifactType:`markdown`,status:`complete`,markdown:e??``,...r?{file:r}:{}}))}a&&navigator.clipboard.writeText(a).then(()=>{let e=Jt(b,16,`currentColor`,2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=Jt(ne,16,`currentColor`,2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),z.addEventListener(`click`,e=>{let t=e.target.closest(`[data-expand-artifact-inline]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-expand-artifact-inline`);n&&r.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:n})!==!0&&(kr=!1,Mr=!0,Ar=!0,jr=!0,Q.selectArtifact(n),si())}),z.addEventListener(`click`,e=>{let t=e.target;if(t.closest(`[data-download-artifact]`)||t.closest(`[data-artifact-custom-action]`))return;let n=t.closest(`[data-open-artifact]`);if(!n)return;let i=n.getAttribute(`data-open-artifact`);i&&r.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:i})!==!0&&(e.preventDefault(),e.stopPropagation(),kr=!1,Mr=!0,Q.selectArtifact(i),si())}),z.addEventListener(`keydown`,e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target;(t.hasAttribute(`data-open-artifact`)||t.hasAttribute(`data-expand-artifact-inline`))&&(e.preventDefault(),t.click())});let Lr=it.composerOverlay,Rr=e=>{Us().catch(()=>{}),Xr(e,r,Lr)},zr=null,Br={mount:e,overlay:Lr,sessionRef:Fr,config:()=>r},Vr=!1,Hr=e=>t=>{let n=t.target,r=n?.closest?.(`[data-persona-ask-sheet-for]`);if(!r||!(e===`click`?n?.closest(`[data-ask-user-action]`):t.key===`Enter`&&n?.matches?.(`[data-ask-free-text-input="true"]`)))return;let i=n=>{zr??=n.createAskUserSheetHandlers(Br),zr[e](t)},a=Gs();a?i(a):Vr||(Vr=!0,Us().then(e=>{Vr=!1,r.isConnected&&i(e)},()=>{Vr=!1}))};Lr.addEventListener(`click`,Hr(`click`)),Lr.addEventListener(`keydown`,Hr(`keydown`));let Ur=e=>{if(!/^[1-9]$/.test(e.key)||e.metaKey||e.ctrlKey||e.altKey)return;let t=e.target;if(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable)return;let n=Lr.querySelector(`[data-persona-ask-sheet-for]`);if(!n||n.getAttribute(`data-ask-layout`)!==`rows`||n.getAttribute(`data-multi-select`)===`true`)return;let r=Number(e.key),i=n.querySelectorAll(`[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]`)[r-1];i&&(e.preventDefault(),i.click())};document.addEventListener(`keydown`,Ur);let Wr=null,Gr=null,Kr=null,qr=null,Jr=()=>{},Yr=!1,Qr=``,$r=``;function ei(){qr?.(),qr=null}let ti=()=>{let e=xc?.railShell?xc.railHost:null,t=e?.isConnected?e:null,n=t?t.getBoundingClientRect().width:0;return n<=0?200:n+360},ni=()=>{if(!Wr||!Gr)return;let t=e.classList.contains(`persona-artifact-welded-split`),n=e.ownerDocument.defaultView??window,r=n.innerWidth<=640;if(!t||e.classList.contains(`persona-artifact-narrow-host`)||r){Gr.style.removeProperty(`position`),Gr.style.removeProperty(`left`),Gr.style.removeProperty(`top`),Gr.style.removeProperty(`bottom`),Gr.style.removeProperty(`width`),Gr.style.removeProperty(`z-index`);return}let i=Wr.firstElementChild;if(!i||i===Gr)return;Gr.style.position=`absolute`,Gr.style.top=`0`,Gr.style.bottom=`0`,Gr.style.width=`10px`,Gr.style.zIndex=`5`;let a=iv(Wr,n),o=i.offsetWidth+a/2-5;Gr.style.left=`${Math.max(0,o)}px`},ri=()=>{},ii=()=>{let t=e.ownerDocument.defaultView??window,n=r.launcher?.mobileFullscreen??!0,i=r.launcher?.mobileBreakpoint??640;return!n||t.innerWidth>i?!1:M||Bm(r)},ai=()=>!S_(r)||!Pr()||e.classList.contains(`persona-artifact-narrow-host`)||ii()||(e.ownerDocument.defaultView??window).innerWidth<641?`none`:D_(r)?`detached`:`welded`,si=()=>{if(!X||!S_(r))return;O_(e,r),k_(e,r),ri();let t=r.features?.artifacts?.layout?.narrowHostMaxWidth??520,n=I.getBoundingClientRect().width||0;e.classList.toggle(`persona-artifact-narrow-host`,n>0&&n<=t);let i=Pr();X.setVisible(i),X.update(Or),kr?(X.setMobileOpen(!1),X.element.classList.add(`persona-hidden`),X.backdrop?.classList.add(`persona-hidden`),Ar=!1,jr=!1):Or.artifacts.length>0&&Nr()?(X.element.classList.remove(`persona-hidden`),X.setMobileOpen(!0)):(X.setMobileOpen(!1),X.element.classList.add(`persona-hidden`),X.backdrop?.classList.add(`persona-hidden`),Ar=!1,jr=!1);let a=r.features?.artifacts?.layout?.showExpandToggle===!0;if(X.setExpandToggleVisible(a),X.setCopyButtonVisible(r.features?.artifacts?.layout?.showCopyButton===!0),X.setRefreshButtonVisible(typeof r.features?.artifacts?.layout?.onDocumentToolbarRefresh==`function`),X.setCustomActions(r.features?.artifacts?.toolbarActions??[]),X.setTabFade(r.features?.artifacts?.layout?.tabFade),X.setRenderTabBar(r.features?.artifacts?.renderTabBar),!a&&!jr&&(Ar=!1),Ar!==Yr){let e=X.element;Ar?(Qr=e.style.width,$r=e.style.maxWidth,e.style.removeProperty(`width`),e.style.removeProperty(`max-width`)):(Qr&&(e.style.width=Qr),$r&&(e.style.maxWidth=$r),Qr=``,$r=``),Yr=Ar}e.classList.toggle(`persona-artifact-expanded`,Ar),X.setExpanded(Ar);let o=ai();o!==Er&&(Er=o,Tr()),Jr()};if(S_(r)){I.style.position=`relative`;let t=q(`div`,`persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0`),n=q(`div`,`persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root`);t.appendChild(L),Wr=n,n.appendChild(t),I.appendChild(n);let i=e=>{Sr||X||(X=e.createArtifactPane(r,{onSelect:e=>Fr.current?.selectArtifact(e),onDismiss:()=>{kr=!0,si()},onToggleExpand:()=>{let e=!Ar,t=Or.selectedId??Or.artifacts[Or.artifacts.length-1]?.id??null;r.features?.artifacts?.onArtifactAction?.({type:`expand`,artifactId:t,expanded:e})!==!0&&(Ar=e,e||(jr=!1),si())}}),X.element.classList.add(`persona-hidden`),n.appendChild(X.element),X.backdrop&&I.appendChild(X.backdrop),Jr(),si())},a=b_();a?i(a):(x_(()=>{let e=b_();e&&i(e)}),y_().catch(()=>{})),Jr=()=>{if(Wr&&X){if(r.features?.artifacts?.layout?.resizable!==!0)Kr?.(),Kr=null,ei(),Gr&&=(Gr.remove(),null),X.element.style.removeProperty(`width`),X.element.style.removeProperty(`maxWidth`);else{if(!Gr){let t=q(`div`,`persona-artifact-split-handle persona-shrink-0 persona-h-full`);t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-label`,`Resize artifacts panel`),t.tabIndex=0;let n=e.ownerDocument,i=n.defaultView??window,a=a=>{if(!X||a.button!==0||e.classList.contains(`persona-artifact-narrow-host`)||e.classList.contains(`persona-artifact-expanded`)||i.innerWidth<=640)return;a.preventDefault(),ei();let o=a.clientX,s=X.element.getBoundingClientRect().width,c=r.features?.artifacts?.layout,l=n=>{let r=Wr.getBoundingClientRect().width,a=e.classList.contains(`persona-artifact-welded-split`),l=iv(Wr,i),u=a?0:t.getBoundingClientRect().width||6,d=av(s-(n.clientX-o),r,l,u,c?.resizableMinWidth,c?.resizableMaxWidth,ti());X.element.style.width=`${d}px`,X.element.style.maxWidth=`none`,ni()},u=()=>{n.removeEventListener(`pointermove`,l),n.removeEventListener(`pointerup`,u),n.removeEventListener(`pointercancel`,u),qr=null;try{t.releasePointerCapture(a.pointerId)}catch{}};qr=u,n.addEventListener(`pointermove`,l),n.addEventListener(`pointerup`,u),n.addEventListener(`pointercancel`,u);try{t.setPointerCapture(a.pointerId)}catch{}};t.addEventListener(`pointerdown`,a),Gr=t,Wr.insertBefore(t,X.element),Kr=()=>{t.removeEventListener(`pointerdown`,a)}}if(Gr){let e=Pr();Gr.classList.toggle(`persona-hidden`,!e),ni()}}}},ri=()=>{if(!M||!X||(r.launcher?.sidebarMode??!1)||Bm(r)&&Hm(r).reveal===`emerge`)return;let t=e.ownerDocument.defaultView??window,n=r.launcher?.mobileFullscreen??!0,i=r.launcher?.mobileBreakpoint??640;if(n&&t.innerWidth<=i||!A_(r,M))return;let a=vg(r).width,o=r.features?.artifacts?.layout?.expandedPanelWidth??`min(720px, calc(100vw - 24px))`;Pr()?(I.style.width=o,I.style.maxWidth=o):(I.style.width=a,I.style.maxWidth=a)},typeof ResizeObserver<`u`&&(wr=new ResizeObserver(()=>{si()}),wr.observe(I))}else I.appendChild(L);N()&&rt&&(it.peekBanner&&rt.appendChild(it.peekBanner),rt.appendChild(bt)),e.appendChild(F),rt&&e.appendChild(rt);let li=()=>{let t=ii()||N()&&r.launcher?.composerBar?.expandedSize===`fullscreen`||r.launcher?.fullHeight===!0&&!r.launcher?.sidebarMode&&!Bm(r);if(z.style.gap=t?`var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))`:`var(--persona-components-message-gap, 12px)`,z.style.setProperty(`--persona-transcript-gap`,z.style.gap),N()){I.style.width=`100%`,I.style.maxWidth=`100%`;let e=r.launcher?.composerBar??{},t=F.dataset.state===`expanded`,n=e.expandedSize??`anchored`;if(!(t&&n!==`fullscreen`)){L.style.background=``,L.style.border=``,L.style.borderRadius=``,L.style.overflow=``,L.style.boxShadow=``;return}let i=r.theme?.components?.panel,a=Mp(r),o=(e,t)=>e==null||e===``?t:ap(a,e)??e;L.style.background=`var(--persona-surface, #ffffff)`,L.style.border=o(i?.border,`1px solid var(--persona-border)`),L.style.borderRadius=o(i?.borderRadius,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`),L.style.boxShadow=o(i?.shadow,`var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))`),L.style.overflow=`hidden`;return}let n=Bm(r),i=r.launcher?.sidebarMode??!1,a=n||i||(r.launcher?.fullHeight??!1),o=r.launcher?.enabled===!1,s=r.launcher?.detachedPanel===!0,c=r.theme?.components?.panel,l=r.darkTheme?.components?.panel,u=kp(r)===`dark`?Ja(c??{},l??{}):c,d=Mp(r),f=(e,t)=>e==null||e===``?t:ap(d,e)??e,p=e.ownerDocument.defaultView??window,m=r.launcher?.mobileFullscreen??!0,h=r.launcher?.mobileBreakpoint??640,g=p.innerWidth<=h,_=m&&g&&M,v=n&&m&&g,y=r.launcher?.position??`bottom-left`,b=y===`bottom-left`||y===`top-left`,x=r.launcher?.zIndex??1e5,S=(e,t,n)=>`var(--persona-components-panel-modes-${e}-${t}, ${n})`,C=u?.modes?.floating,w=f(C?.border??u?.border,S(`floating`,`border`,`var(--persona-panel-border, 1px solid var(--persona-border))`)),T=f(C?.shadow??u?.shadow,S(`floating`,`shadow`,`var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))`)),E=f(C?.borderRadius??u?.borderRadius,S(`floating`,`borderRadius`,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`)),D=s&&!_&&!v,O=_||v?`mobile`:D?`floating`:n?`docked`:i?`sidebar`:o?`inline`:`floating`,k=u?.modes?.[O];D?e.setAttribute(`data-persona-panel-detached`,`true`):e.removeAttribute(`data-persona-panel-detached`);let ee=D?w:i||_?`none`:w,te=D?T:_?`none`:i?b?`2px 0 12px rgba(0, 0, 0, 0.08)`:`-2px 0 12px rgba(0, 0, 0, 0.08)`:o?`none`:T;n&&!_&&!D&&(te=`none`,ee=`none`);let ne=D?E:i||_?`0`:E,re=f(k?.border??u?.border,S(O,`border`,ee)),ie=f(k?.shadow??u?.shadow,S(O,`shadow`,te)),ae=f(k?.borderRadius??u?.borderRadius,S(O,`borderRadius`,ne)),oe=ai(),A=oe===`detached`,j=oe===`welded`;e.classList.toggle(`persona-artifact-detached-split`,A),e.classList.toggle(`persona-artifact-welded-split`,j);let se=`var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))`,ce=(r.features?.artifacts?.layout?.chatSurface===`flush`?`flush`:`card`)==`flush`&&S_(r)&&D_(r)&&o&&!n;e.classList.toggle(`persona-artifact-chat-flush`,ce);let le=A||ce?`none`:ie,ue=A?w:j?`none`:re,de=A?E:ae;ce&&(ue=`none`,de=`0`);let fe=k?.borderRadius!=null&&k.borderRadius!==``||u?.borderRadius!=null&&u.borderRadius!==``,pe=ce&&!fe?`0`:ae,me=R.scrollTop;e.style.cssText=``,F.style.cssText=``,I.style.cssText=``,L.style.cssText=``,R.style.cssText=``,Gn||(bt.style.cssText=``),ze&&(R.style.display=`none`),(a||o)&&(e.style.minWidth=`0`);let he=()=>{me<=0||(R.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(R.scrollTop===me)return;let e=R.scrollHeight-R.clientHeight;e<=0||(R.scrollTop=Math.min(me,e))})};if(_){F.classList.remove(`persona-bottom-6`,`persona-right-6`,`persona-left-6`,`persona-top-6`,`persona-bottom-4`,`persona-right-4`,`persona-left-4`,`persona-top-4`),F.style.cssText=`
|
|
41
41
|
position: fixed !important;
|
|
42
42
|
inset: 0 !important;
|
|
43
43
|
width: 100% !important;
|
|
@@ -73,7 +73,7 @@ import{Marked as e,Marked as t}from"marked";import n,{default as r}from"dompurif
|
|
|
73
73
|
overflow: hidden !important;
|
|
74
74
|
border-radius: 0 !important;
|
|
75
75
|
border: none !important;
|
|
76
|
-
`,R.style.flex=`1 1 0%`,R.style.minHeight=`0`,R.style.overflowY=`auto`,bt.style.flexShrink=`0`,sn(),ye=!0,he();return}let ge=
|
|
76
|
+
`,R.style.flex=`1 1 0%`,R.style.minHeight=`0`,R.style.overflowY=`auto`,bt.style.flexShrink=`0`,sn(),ye=!0,he();return}let ge=vg(r);if(!i&&!n)o&&a?(I.style.width=`100%`,I.style.maxWidth=`100%`):(I.style.width=ge.width,I.style.maxWidth=ge.maxWidth);else if(n){if(Hm(r).reveal===`emerge`&&!s){let e=Hm(r).width;I.style.width=e,I.style.maxWidth=e}else I.style.width=`100%`,I.style.maxWidth=`100%`}if(ri(),I.style.boxShadow=le,I.style.borderRadius=pe,A?I.style.border=`none`:j&&(I.style.border=re),L.style.border=ue,L.style.borderRadius=de,L.style.boxShadow=A&&!ce?se:``,ce&&(L.style.background=`transparent`,R.style.background=`transparent`,bt.style.background=`transparent`,bt.style.borderTop=`none`),j){let e=r.features?.artifacts?.layout;Dr=e?.unifiedSplitOuterRadius?.trim()||e?.paneBorderRadius?.trim()||ae}else Dr=null;let _e=k?.border!=null||u?.border!=null;if(n&&!_&&!D&&!A&&!j&&!_e&&(L.style.border=`none`,Hm(r).side===`right`?L.style.borderLeft=`1px solid var(--persona-border)`:L.style.borderRight=`1px solid var(--persona-border)`),n&&!_&&j&&!_e&&(Hm(r).side===`right`?I.style.borderLeft=`1px solid var(--persona-border)`:I.style.borderRight=`1px solid var(--persona-border)`),a&&(e.style.display=`flex`,e.style.flexDirection=`column`,e.style.height=`100%`,e.style.minHeight=`0`,o&&(e.style.width=`100%`),F.style.display=`flex`,F.style.flexDirection=`column`,F.style.flex=`1 1 0%`,F.style.minHeight=`0`,F.style.maxHeight=`100%`,F.style.height=`100%`,o&&(F.style.overflow=`hidden`),I.style.display=`flex`,I.style.flexDirection=`column`,I.style.flex=`1 1 0%`,I.style.minHeight=`0`,I.style.maxHeight=`100%`,I.style.height=`100%`,A||(I.style.overflow=`hidden`),L.style.display=`flex`,L.style.flexDirection=`column`,L.style.flex=`1 1 0%`,L.style.minHeight=`0`,L.style.maxHeight=`100%`,L.style.overflow=`hidden`,R.style.flex=`1 1 0%`,R.style.minHeight=`0`,R.style.overflowY=`auto`,bt.style.flexShrink=`0`),o&&(D||A||ce)&&!n&&(ce||(F.style.padding=`var(--persona-panel-inset)`),F.style.background=`var(--persona-panel-canvas-bg)`),F.classList.remove(`persona-bottom-6`,`persona-right-6`,`persona-left-6`,`persona-top-6`,`persona-bottom-4`,`persona-right-4`,`persona-left-4`,`persona-top-4`),!i&&!o&&!n&&(Xm[y]??Xm[`bottom-right`]).split(` `).forEach(e=>F.classList.add(e)),i){let e=fo(r).sidebarWidth?r.launcher?.sidebarWidth??`420px`:ap(Mp(r),`components.panel.width`)??`420px`;s?F.style.cssText=`
|
|
77
77
|
position: fixed !important;
|
|
78
78
|
top: var(--persona-panel-inset) !important;
|
|
79
79
|
bottom: var(--persona-panel-inset) !important;
|
|
@@ -112,7 +112,7 @@ import{Marked as e,Marked as t}from"marked";import n,{default as r}from"dompurif
|
|
|
112
112
|
padding: 0 !important;
|
|
113
113
|
box-shadow: ${le} !important;
|
|
114
114
|
border-radius: ${pe} !important;
|
|
115
|
-
${
|
|
115
|
+
${A?`border: none !important;`:j?`border: ${re} !important;`:``}
|
|
116
116
|
`,I.style.setProperty(`width`,`100%`,`important`),I.style.setProperty(`max-width`,`100%`,`important`),L.style.cssText=`
|
|
117
117
|
display: flex !important;
|
|
118
118
|
flex-direction: column !important;
|
|
@@ -124,16 +124,16 @@ import{Marked as e,Marked as t}from"marked";import n,{default as r}from"dompurif
|
|
|
124
124
|
overflow: hidden !important;
|
|
125
125
|
border-radius: ${de} !important;
|
|
126
126
|
border: ${ue} !important;
|
|
127
|
-
${
|
|
127
|
+
${A&&!ce?`box-shadow: ${se} !important;`:``}
|
|
128
128
|
${ce?`background: transparent !important;`:``}
|
|
129
129
|
`,Gn||(bt.style.cssText=`
|
|
130
130
|
flex-shrink: 0 !important;
|
|
131
131
|
border-top: none !important;
|
|
132
132
|
padding: 8px 16px 12px 16px !important;
|
|
133
133
|
${ce?`background: transparent !important;`:``}
|
|
134
|
-
`)}if(!o&&!n){let e=i?``:`padding-top: 1.25em !important;`,t=i?``:`z-index: ${r.launcher?.zIndex??1e5} !important;`;F.style.cssText+=`max-height: -moz-available !important; max-height: stretch !important;`+e+t}sn(),he()},ui=()=>{e.style.setProperty(`--persona-content-max-width`,Ap(r,N()))},fi=!1;function pi(){r.layout?.topFade&&R.scrollTop>1?R.setAttribute(`data-persona-top-fade`,`true`):R.removeAttribute(`data-persona-top-fade`)}let mi=()=>{pi();let t=jp(r,N());N()&&r.composer?.placement&&r.debug===!0&&!fi&&(fi=!0,console.warn(`[persona] composer.placement is ignored in composer-bar mount mode.`));let n=tn();e.setAttribute(`data-persona-composer-placement`,t),e.setAttribute(`data-persona-conversation-state`,nn),e.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`),e.style.setProperty(`--persona-composer-anchor-gap`,n.composerGap??`24px`),ln()},hi=()=>{if(N())return;let t=Mm(r),n=r.launcher?.sidebarMode??!1;if(t||n||(r.launcher?.fullHeight??!1)||!M)return;let i=e.ownerDocument.defaultView??window,a=r.launcher?.mobileFullscreen??!0,o=r.launcher?.mobileBreakpoint??640;if(a&&i.innerWidth<=o)return;let s=ug(r);I.style.height=s.height,I.style.maxHeight=s.maxHeight};li(),Op(e,r),b_(e,r),x_(e,r),ui(),mi(),Tr=()=>{li(),hi(),Op(e,r),b_(e,r),x_(e,r),ui(),mi(),Dr?e.style.setProperty(`--persona-artifact-welded-outer-radius`,Dr):e.style.removeProperty(`--persona-artifact-welded-outer-radius`),Je(),qe()};let Z=[];Z.push(()=>{Sr=!0}),Z.push(()=>{p.forEach(e=>e()),f.destroy()}),Z.push(()=>{document.removeEventListener(`keydown`,Ur)}),Z.push(()=>{Zt!==null&&clearTimeout(Zt)});let _i=null,vi=null;Z.push(()=>{_i?.(),_i=null,vi?.(),vi=null}),wr&&Z.push(()=>{wr?.disconnect(),wr=null}),Z.push(()=>{Kr?.(),Kr=null,ei(),Gr&&=(Gr.remove(),null),X?.element.style.removeProperty(`width`),X?.element.style.removeProperty(`maxWidth`),X?.destroy()}),De&&Z.push(()=>{Le=!0,Ie=null,Be!==null&&(cancelAnimationFrame(Be),Be=null),Re?.destroy(),Re=null,Pe?.destroy(),Pe=null,Me=null});let yi=null,bi=()=>{yi&&=(yi(),null),r.colorScheme===`auto`&&(yi=kp(()=>{Op(e,r)}))};bi(),Z.push(()=>{yi&&=(yi(),null)}),Z.push(()=>{y=!0,v?.()}),Z.push(()=>{w=!0});let xi=!1;Z.push(()=>{xi=!0});let Si=(t,n)=>{let r=sm(t,n);return r||!rm.includes(t)?r:(Em().then(r=>{if(xi)return;im(r.wipe),im(r.glyphCycle);let i=sm(t,n);i&&Cm(i,e)}).catch(()=>{}),null)},Ci=r.features?.streamAnimation;if(Ci?.type&&Ci.type!==`none`){let t=Si(Ci.type,Ci.plugins);t&&Cm(t,e),Z.push(()=>Sm(e))}let wi=Vm(st),Ti=Vm(at),Ei=Vm(ot),Di=[wi,Ti,Ei];Z.push(()=>{Di.forEach(e=>e.destroy())});let Oi=null,Q,ki=null,Ai=!1,ji=0,Mi=null,Pi=e=>e.reduce((e,t)=>t.role===`user`?e+1:e,0),Fi=e=>{for(let t=e.length-1;t>=0;t--)if(oi(e[t]))return e[t].id??null;return null},Ii=!1,Li=()=>{Ii||r.debug!==!0||(Ii=!0,console.warn(`[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".`))},Ri=!1,zi=!1,Bi=(e,t)=>{Ri||r.debug!==!0||t.enabled&&!t.expose&&(Ai||zi&&(Q.isStreaming()||e.some(oi)||(Ri=!0,console.info(`[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.`))))},Vi=e=>{if(!Q)return;let t=e??Q.getMessages(),n=e=>{e.render([],Q,B,t)},i=e=>{Di.forEach(t=>{t!==e&&n(t)})};ki&&(Pi(t)>ji||Fi(t)!==Mi)&&(ki=null);let a=di(r);Bi(t,a);let o=a.enabled?ci(t):null,s=ki??o,c=ki?`host`:`agent`;if(s){let e=r.suggestions?.followUps,n=e?.placement??(e?`auto`:`composer`),a=(n===`auto`?N()?`composer`:`after-message`:n)===`after-message`?Ei:wi;i(a),a.render(s,Q,B,t,r.suggestionChipsConfig,{source:c,surface:`followUp`,variant:e?.variant??`chip`,behavior:e?.behavior??`send`,overflow:e?.overflow??`wrap`,maxItems:e?.maxItems??4,config:r,plugins:d,submitPrompt:ml});return}if(t.some(e=>e.role===`user`)){Di.forEach(n);return}let l=r.future?.v5Defaults===!0,u=en(),f=r.suggestions?.starters??(l?{}:void 0);if(f){let e=cg(tn(),t),a=f.placement??`auto`,o=a===`auto`?e?`welcome`:`composer`:a;if(o===`welcome`&&!e){Li(),Di.forEach(n);return}let s=o===`welcome`?Ti:wi;i(s),s.render(f.items??r.suggestionChips,Q,B,t,r.suggestionChipsConfig,{surface:`starter`,variant:f.variant??(l&&!u?`chip`:`card`),behavior:f.behavior??`send`,overflow:f.overflow??`wrap`,maxItems:f.maxItems??(l&&!u?3:4),config:r,plugins:d,submitPrompt:ml})}else i(wi),wi.render(r.suggestionChips,Q,B,t,r.suggestionChipsConfig,{surface:`starter`,variant:`chip`,behavior:`send`,overflow:`wrap`,maxItems:4,config:r,plugins:d,submitPrompt:ml})},Hi=()=>{ki&&(ki=null,Vi())},Ui=e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length){Hi();return}let n=Q?Q.getMessages():[];ki=t,Ai=!0,ji=Pi(n),Mi=Fi(n),Vi(n)},Wi=!1,Gi=zp(),Ki=/* @__PURE__ */ new Map,qi=/* @__PURE__ */ new Map,Ji=/* @__PURE__ */ new Map,Yi=null,Xi=null;function Zi(){if(!Yi)return;let e=Yi;Yi=null,Xi?.destroy(),Xi=null,Gi.delete(e),L.querySelector(`#wrapper-${e}`)?.removeAttribute(`data-preserve-runtime`),Q&&Io(z,Q.getMessages(),we)}let Qi=0,$i=Kt()!==null,ea=Wp(),ta=0,na=null,ra=!1,ia=!1,aa=0,oa=null,sa=null,ca=!1,la=!1,ua=null,da=!0,fa=!1,pa=null,ma=!1,ha=()=>{ma=!0,ya()},ga=null,_a=null,va=()=>{e.setAttribute(`data-persona-scrollbar`,Bt()),Bt()!==`on-scroll`&&(_a!==null&&clearTimeout(_a),_a=null,R.removeAttribute(`data-persona-scrollbar-visible`))},ya=()=>{Bt()===`on-scroll`&&(R.setAttribute(`data-persona-scrollbar-visible`,``),_a!==null&&clearTimeout(_a),_a=setTimeout(()=>{_a=null,Kp(R,24)&&R.removeAttribute(`data-persona-scrollbar-visible`)},1e3))};va(),Z.push(()=>{_a!==null&&clearTimeout(_a)});let ba=/* @__PURE__ */ new Map,xa=!1,Sa=null,$={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};lr();let Ca=r.voiceRecognition?.autoResume??!1,Ta=()=>Q.isVoiceActive()||Q.isBargeInActive(),Da=!1,Oa=e=>{O.emit(`voice:state`,{active:$.active,source:e,timestamp:Date.now()})},ka=()=>{ue(e=>({...e,voiceState:{active:$.active,timestamp:Date.now(),manuallyDeactivated:$.manuallyDeactivated}}))},Aa=()=>{if(r.voiceRecognition?.enabled===!1)return;let e=Yv(A.voiceState),t=!!e.active,n=Number(e.timestamp??0);$.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-n<3e4&&setTimeout(()=>{$.active||($.manuallyDeactivated=!1,Cl(r.voiceRecognition?.provider)?Q.toggleVoice().then(()=>{$.active=Ta(),Oa(`restore`),$.active?ru():(ka(),tl(`Tap the mic to resume your voice call`,1e4))}):$l(`restore`))},Cl(r.voiceRecognition?.provider)?0:1e3)},ja=e=>{Da=!e.persisted,$.active&&ka()};typeof window<`u`&&(window.addEventListener(`pagehide`,ja),Z.push(()=>window.removeEventListener(`pagehide`,ja)));let Ma=()=>Q?Xv(Q.getMessages()).filter(e=>!e.__skipPersist):[],Na=null,Pa=(e,t)=>{typeof console<`u`&&console.error(e,t)},Fa=(e,t)=>{let n=()=>{try{let n=e();return!n||typeof n.then!=`function`?null:Promise.resolve(n).catch(e=>{Pa(t,e)})}catch(e){return Pa(t,e),null}},r=Na,i=r?r.then(()=>n()??void 0):n();if(!i)return;let a=i.finally(()=>{Na===a&&(Na=null)});Na=a};function Ia(e){if(!k?.save)return;let t=e?Xv(e):Q?Ma():[],n=ee&&Q?.getResumableHandle();n&&(A={...A,durableResume:{executionId:n.executionId,after:n.lastEventId}});let r={messages:t,metadata:A,artifacts:Or.artifacts,selectedArtifactId:Or.selectedId,...La?{draft:La}:{}};Fa(()=>k.save(r),`[AgentWidget] Failed to persist state:`)}let La,Ra=()=>!k?.save||r.persistState===!1?!1:typeof r.persistState!=`object`||r.persistState.persist?.draft!==!1,za=Cf({write:()=>{if(!Ra())return;let e=G.getState(),t=xf({text:e.text,mentionRefs:e.mentionRefs,contentSegments:Xc(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(La)&&(La=t,Ia())}});function Ba(){Ra()&&za.schedule()}function Va(){za.flush()}function Ha(e){if(!Ra())return;let t=Sf(e,{mentionSourceIds:(r.contextMentions?.sources??[]).map(e=>e.id),modelIds:(r.composer?.models??[]).map(e=>e.id),modes:r.composer?.modes??[]});t&&(La=e,B&&!B.value&&(B.value=t.text,B.dispatchEvent(new Event(`input`,{bubbles:!0})),pn()),t.selectedModelId&&(G.setSelectedModelId(t.selectedModelId),Cn?.repaint()),bn(t.activeModeIds??[]),t.quote&&On(t.quote),za.cancel())}function Ua(){za.cancel(),La&&(La=void 0,Ra()&&Ia())}let Wa=null,qa=()=>F.querySelector(`#persona-scroll-container`)||R,Ya=()=>{Wa!==null&&(cancelAnimationFrame(Wa),Wa=null),ra=!1},Xa=()=>{na!==null&&(cancelAnimationFrame(na),na=null),ia=!1,Ya()},Za=()=>Wi&&to()&&(Nt()!==`anchor-top`||Rt()),Qa=()=>{let e=jt()||`Jump to latest`,t=Za();Vt.toggleAttribute(`data-persona-scroll-to-bottom-streaming`,t),aa>0?(qt.textContent=String(aa),qt.style.display=``,Vt.setAttribute(`aria-label`,`${e} (${aa} new)`)):(qt.textContent=``,qt.style.display=`none`,Vt.setAttribute(`aria-label`,t?`${e} (response streaming below)`:e))},$a=()=>{aa!==0&&(aa=0,Qa())},eo=()=>{let e=oa?.spacerHeight??0;return e<=0?Kp(R,24):_o(e)-R.scrollTop-R.clientHeight<=24},to=()=>Pt()?!ea.isFollowing():!eo(),no=()=>!!Q&&Q.getMessages().length>0,ro=()=>{if(!Mt()||Qe()){Vt.parentNode&&Vt.remove(),Vt.style.display=`none`;return}Vt.parentNode!==L&&L.appendChild(Vt),on();let e=Gp(R)>0&&to()&&no();e?Qa():$a(),Vt.style.display=e?``:`none`},io=()=>{ea.pause()&&(Xa(),ro())},ao=()=>{ea.resume(),$a(),ro()},oo=(e=!1)=>{Pt()&&no()&&ea.isFollowing()&&(e||Wi)&&(na!==null&&(cancelAnimationFrame(na),na=null),ia=!0,na=requestAnimationFrame(()=>{na=null,ia=!1,ea.isFollowing()&&co(qa(),e?220:140)}))},so=(e,t,n,r=()=>!0)=>{let i=e.scrollTop,a=t(),o=a-i;if(Ya(),Math.abs(o)<1){ra=!0,e.scrollTop=a,ta=e.scrollTop,ra=!1;return}let s=performance.now();ra=!0;let c=e=>1-(1-e)**3,l=u=>{if(!r()){Ya();return}let d=t();d!==a&&(a=d,o=a-i);let f=u-s,p=Math.min(f/n,1),m=c(p);e.scrollTop=i+o*m,ta=e.scrollTop,p<1?Wa=requestAnimationFrame(l):(e.scrollTop=a,ta=e.scrollTop,Wa=null,ra=!1)};Wa=requestAnimationFrame(l)},co=(e,t=500)=>{let n=Gp(e)-e.scrollTop;Math.abs(n)<1?ta=e.scrollTop:Math.abs(n)>=80?(Ya(),ra=!0,e.scrollTop=Gp(e),ta=e.scrollTop,ra=!1):so(e,()=>Gp(e),t,()=>ea.isFollowing())},lo=()=>{if(!no()){ro();return}let e=qa();ra=!0,e.scrollTop=Gp(e),ta=e.scrollTop,ra=!1,ro()},uo=e=>{let t=0,n=e;for(;n&&n!==R;)t+=n.offsetTop,n=n.offsetParent;return t},po=()=>{let e=R.getRootNode();return(typeof e.getSelection==`function`?e.getSelection():null)??R.ownerDocument.getSelection()},mo=()=>Yp(po(),R),ho=()=>{if(It()!==`last-user-turn`)return!1;let e=Q?.getMessages()??[];if(e.length<2)return!1;let t=[...e].reverse().find(e=>e.role===`user`);if(!t)return!1;let n=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(t.id):t.id.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),r=R.querySelector(`[data-message-id="${n}"]`);if(!r)return!1;let i=Math.min(Math.max(0,uo(r)-Ft()),Gp(R));return ra=!0,R.scrollTop=i,ta=R.scrollTop,ra=!1,Nt()===`follow`&&!Kp(R,24)&&ea.pause(),ro(),!0},go=e=>{let t=Math.max(0,Math.round(e));Yt.style.height=`${t}px`,Yt.style.display=t>0?``:`none`,oa&&(oa.spacerHeight=Math.max(0,e))},_o=e=>{let t=parseFloat(getComputedStyle(R).paddingBottom)||0,n=0;for(let e of Array.from(R.children)){if(e===Yt||e.offsetHeight===0)continue;let t=uo(e)+e.offsetHeight;t>n&&(n=t)}let r=R.scrollHeight-e;return n>0?Math.min(n+t,r):r},vo=()=>{if(!oa||oa.spacerHeight<=0)return;let e=_o(oa.spacerHeight),t=Math.max(0,Math.round(R.scrollTop)+R.clientHeight-e+24);t<oa.spacerHeight&&(go(t),ro())},yo=()=>{sa!==null&&(cancelAnimationFrame(sa),sa=null),Ya(),oa=null,Yt.style.height=`0px`,Yt.style.display=`none`},xo=e=>typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),So=e=>R.querySelector(`[data-message-id="${xo(e)}"]`),Co=e=>{sa!==null&&cancelAnimationFrame(sa),sa=requestAnimationFrame(()=>{sa=null;let t=xo(e),n=R.querySelector(`[data-message-id="${t}"]`);if(!n)return;let r=uo(n),i=oa?.spacerHeight??0,a=_o(i),{targetScrollTop:o,spacerHeight:s}=Xp({anchorOffsetTop:r,topOffset:Ft(),viewportHeight:R.clientHeight,contentHeight:a,slack:24});oa={initialSpacerHeight:s,contentHeightAtAnchor:a,spacerHeight:s},go(s),so(R,()=>n.isConnected?Math.max(0,uo(n)-Ft()):o,220)})},wo=()=>{if(Nt()!==`anchor-top`||!oa||!pa)return;let e=So(pa);if(!e)return;Ya();let t=oa.spacerHeight,n=_o(t),{targetScrollTop:r,spacerHeight:i}=Xp({anchorOffsetTop:uo(e),topOffset:Ft(),viewportHeight:R.clientHeight,contentHeight:n,slack:24});oa={initialSpacerHeight:i,contentHeightAtAnchor:n,spacerHeight:i},go(i),ra=!0,R.scrollTop=r,ta=R.scrollTop,ra=!1,ro()},To=()=>{if(Pt()){if(!ea.isFollowing()||Kp(R,1))return;oo(!Wi)}else{if(oa&&oa.initialSpacerHeight>0){let e=R.scrollHeight-oa.spacerHeight,t=Zp({initialSpacerHeight:oa.initialSpacerHeight,contentHeightAtAnchor:oa.contentHeightAtAnchor,currentContentHeight:e});t!==oa.spacerHeight&&go(t)}ro()}},Eo=e=>{let t=Nt();t===`follow`?(ao(),oo(!0)):t===`anchor-top`&&(da=!1,fa=!0,ma=!1,pa=e,Co(e))},Do=()=>{Nt()===`anchor-top`&&(fa?da=!1:(da=!0,yo(),ao(),oo(!0)))},Oo=e=>{if(ua===null)return!0;let t=So(ua),n=So(e);if(!t||!n)return!0;let r=uo(n)-uo(t);return Ft()+r>R.clientHeight-96},ko=e=>{if(Nt()!==`anchor-top`||!fa||ma||mo())return;let t=ua===null;for(let n of e)if(!t)n.id===ua&&(t=!0);else if(Up(n)){if(n.id===pa||!Oo(n.id))return;pa=n.id,Co(n.id);return}},Ao=e=>{let t=/* @__PURE__ */ new Map;e.forEach(e=>{let n=ba.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!n&&e.role===`assistant`&&(O.emit(`assistant:message`,e),!la&&(Nt()!==`anchor-top`||Rt())&&to()&&(aa+=1,Qa(),ro(),$t(aa===1?`1 new message below.`:`${aa} new messages below.`))),e.role===`assistant`&&n?.streaming&&e.streaming===!1&&O.emit(`assistant:complete`,e),e.variant===`approval`&&e.approval&&(n?e.approval.status!==`pending`&&O.emit(`approval:resolved`,{approval:e.approval,decision:e.approval.status}):O.emit(`approval:requested`,{approval:e.approval,message:e}))}),ba.clear(),t.forEach((e,t)=>{ba.set(t,e)})},jo=(e,t)=>{let n=t===`user`?`user`:`assistant`,i=r.layout?.messages?.[n],a=i?.width??`content`,o=i?.maxWidth??(a===`full`?`var(--persona-message-${n}-max-width, 100%)`:void 0);e.classList.add(`persona-message-row`),e.classList.remove(`persona-message-row-user`,`persona-message-row-assistant`,`persona-message-row-system`,`persona-message-width-content`,`persona-message-width-full`),e.classList.add(`persona-message-row-${t}`,`persona-message-width-${a}`),e.classList.toggle(`persona-justify-end`,t===`user`),e.setAttribute(`data-message-role`,t),e.setAttribute(`data-message-width`,a),o?e.style.setProperty(`--persona-message-row-max-width`,o):e.style.removeProperty(`--persona-message-row-max-width`)},Mo=(e,t)=>{let n=document.createElement(`div`);return n.className=`persona-flex`,n.id=`wrapper-${e}`,n.setAttribute(`data-wrapper-id`,e),jo(n,t),n},No=(e,t,n)=>{let i=/* @__PURE__ */ new Set;for(let e of t){let t=e.variant===`tool`?`tool`:e.variant===`reasoning`?`reasoning`:null;if(!t||_l(r,t)!==`row`)continue;let n=t===`tool`?r.features?.toolCallDisplay:r.features?.reasoningDisplay;n?.expandable!==!1&&(i.add(e.id),s.observe(e,t,t===`tool`?a:o,n))}let l=document.createElement(`div`),u=(()=>{let e=d.find(e=>e.renderLoadingIndicator);if(e?.renderLoadingIndicator)return e.renderLoadingIndicator;if(r.loadingIndicator?.render)return r.loadingIndicator.render})(),f=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),p=/* @__PURE__ */ new Set,m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Set,g=d.some(e=>e.renderAskUserQuestion),v=[],y=[],b=r.enableComponentStreaming!==!1,x=r.approval!==!1,S=[],w=r.messageActions,T=w?.showRegenerate===!0&&w.enabled!==!1&&Fr.current?.isStreaming()!==!0?Nu(t):null,E=w?.showEdit===!0&&w.enabled!==!1,O=w?.showQuote===!0&&w.enabled!==!1,k=null,ee=r.features?.reasoningDisplay?.completedVisibility,A=e=>ee===`removed`||ee===`removed-when-short`&&Rn(e,r.features?.reasoningDisplay?.shortThinkThreshold),te=r.features?.toolCallDisplay?.completedVisibility===`removed`,ne=e=>e.variant===`reasoning`&&e.reasoning?.status===`complete`?A(e.reasoning):te&&e.variant===`tool`&&e.toolCall?.status===`complete`;if(t.forEach(t=>{if(ne(t))return;if(p.add(t.id),m.set(t.id,t.role),Yi===t.id&&Xi){let e=Mo(t.id,t.role);e.setAttribute(`data-persona-message-edit-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),k={messageId:t.id,element:Xi.element};return}let i=g&&xr(t),s=x&&t.variant===`approval`&&!!t.approval,f=!i&&t.role===`assistant`&&!t.variant&&b&&Iv(t);!s&&Ji.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),Ji.delete(t.id)),!f&&qi.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),qi.delete(t.id));let w=xr(t)?`:${t.agentMetadata?.askUserQuestionAnswered?`a`:`u`}:${t.agentMetadata?.askUserQuestionAnswers?Object.keys(t.agentMetadata.askUserQuestionAnswers).length:0}`:``,ee={canRegenerate:T===t.id,canEdit:E&&Pu(t),canQuote:O&&!t.variant&&(t.content?.trim().length??0)>0},A=`${ee.canRegenerate?`r`:``}${ee.canEdit?`e`:``}${ee.canQuote?`q`:``}`,te=Rp(t,Qi)+w+`:${A}`,re=i||s||f?null:Bp(Gi,t.id,te);if(re){l.appendChild(re.cloneNode(!0)),xr(t)&&t.toolCall?.id&&t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(h.add(t.toolCall.id),Rr(t));return}let ie=null,ae=d.find(e=>!!(t.variant===`reasoning`&&e.renderReasoning||t.variant===`tool`&&e.renderToolCall||!t.variant&&e.renderMessage)),oe=r.layout?.messages;if(xr(t)&&t.agentMetadata?.askUserQuestionAnswered===!0){Ki.delete(t.id),e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`);return}if(oi(t)&&di(r).enabled)return;if(xr(t)&&r.features?.askUserQuestion?.enabled!==!1){let e=d.find(e=>typeof e.renderAskUserQuestion==`function`);if(e&&Fr.current){let n=Ki.get(t.id),i=n!==te,a=null;if(i){let{payload:n,complete:i}=Cr(t),o=t.id,s=()=>Fr.current?.getMessages().find(e=>e.id===o);a=e.renderAskUserQuestion({message:t,payload:n,complete:i,resolve:e=>{let t=s();t&&Fr.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=s();e?.agentMetadata?.awaitingLocalTool&&(Fr.current?.markAskUserQuestionResolved(e),Fr.current?.resolveAskUserQuestion(e,`(dismissed)`))},config:r})}if(i&&a===null&&n==null){t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(h.add(t.toolCall.id),Rr(t));return}let o=Mo(t.id,t.role);o.setAttribute(`data-ask-plugin-stub`,`true`),o.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(o),v.push({messageId:t.id,fingerprint:te,bubble:a});return}t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(h.add(t.toolCall.id),Rr(t));return}if(s){let n=C();if(!n){l.appendChild(Mo(t.id,t.role));return}let i=d.find(e=>typeof e.renderApproval==`function`)??_,a=Ji.get(t.id)!==te,o=null;if(a&&i?.renderApproval){let e=t.id,a=(t,n)=>{let r=Fr.current?.getMessages().find(t=>t.id===e);r?.approval&&(r.approval.toolType===`webmcp`?Fr.current?.resolveWebMcpApproval(r.id,t):Fr.current?.resolveApproval(r.approval,t,n))};o=i.renderApproval({message:t,defaultRenderer:()=>n.createApprovalBubble(t,r,c),config:r,approve:e=>a(`approved`,e),deny:e=>a(`denied`,e)})}if(a&&o===null)e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),Ji.delete(t.id),ie=n.createApprovalBubble(t,r,c);else{let e=Mo(t.id,t.role);e.setAttribute(`data-approval-plugin-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),S.push({messageId:t.id,fingerprint:te,bubble:o});return}}else if(ae){if(t.variant===`reasoning`&&t.reasoning&&ae.renderReasoning){if(!Te)return;ie=ae.renderReasoning({message:t,defaultRenderer:()=>Fg(t,r,o),config:r})}else if(t.variant===`tool`&&t.toolCall&&ae.renderToolCall){if(!Ee)return;ie=ae.renderToolCall({message:t,defaultRenderer:()=>Kg(t,r,a),config:r})}else ae.renderMessage&&(ie=ae.renderMessage({message:t,defaultRenderer:()=>{let e=Vh(t,n,oe,r.messageActions,$e,{loadingIndicatorRenderer:u,widgetConfig:r,actionEligibility:ee});return t.role!==`user`&&D(e,t,r,Q),e},config:r}))}if(!ie&&f){let i=Lv(t);if(i){let a=qi.get(t.id),o=a!==te,s=r.wrapComponentDirectiveInBubble!==!1&&n_.getOptions(i.component)?.bubbleChrome!==!1,c=null;if(o){let a=Nv(i,{config:r,message:t,transform:n});if(a&&i.component===`PersonaArtifactInline`){let n=a.hasAttribute(`data-artifact-inline`)?a:a.querySelector(`[data-artifact-inline]`),r=n?.getAttribute(`data-artifact-inline`)??``,i=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(r):r,o=r?e.querySelector(`#wrapper-${t.id}`)?.querySelector(`[data-artifact-inline="${i}"]`)??null:null;n&&o&&o!==n&&f_()?.hasLiveInlineArtifactBlock(o)&&(n===a?a=o:n.replaceWith(o))}if(a){if(s){let e=document.createElement(`div`);if(e.className=[`persona-message-bubble`,`persona-rounded-2xl`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-p-4`].join(` `),e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-mb-3 persona-text-sm persona-leading-relaxed`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(a),c=e}else{let e=document.createElement(`div`);if(e.className=`persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch`,e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),e.setAttribute(`data-persona-component-directive`,`true`),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(a),c=e}}}if(c||a!=null){let e=Mo(t.id,t.role);e.setAttribute(`data-component-directive-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),y.push({messageId:t.id,fingerprint:te,bubble:c});return}}}if(!ie){if(t.variant===`reasoning`&&t.reasoning){if(!Te)return;ie=Fg(t,r,o)}else if(t.variant===`tool`&&t.toolCall){if(!Ee)return;ie=Kg(t,r,a)}else if(t.variant===`approval`&&t.approval){if(r.approval===!1)return;let e=C();if(!e)return;ie=e.createApprovalBubble(t,r,c)}else{let e=r.layout?.messages;ie=e?.renderUserMessage&&t.role===`user`?e.renderUserMessage({message:t,config:r,streaming:!!t.streaming}):e?.renderAssistantMessage&&t.role===`assistant`?e.renderAssistantMessage({message:t,config:r,streaming:!!t.streaming}):Vh(t,n,e,r.messageActions,$e,{loadingIndicatorRenderer:u,widgetConfig:r,actionEligibility:ee}),t.role!==`user`&&ie&&D(ie,t,r,Q)}}let j=Mo(t.id,t.role);j.appendChild(ie),Vp(Gi,t.id,te,j),l.appendChild(j)}),it.composerOverlay&&it.composerOverlay.querySelectorAll(`[data-persona-ask-sheet-for]`).forEach(e=>{let t=e.getAttribute(`data-persona-ask-sheet-for`);t&&!h.has(t)&&Zr(it.composerOverlay,t)}),r.features?.toolCallDisplay?.grouped){let e=[],n=[],o=r.features.toolCallDisplay.groupedMode===`summary`;t.forEach(t=>{if(t.variant===`tool`&&t.toolCall&&Ee){if(te&&t.toolCall.status===`complete`)return;n.push(t)}else(t.variant!==`reasoning`||Te&&(t.reasoning?.status!==`complete`||!A(t.reasoning)))&&((n.length>1||o&&n.length>0)&&e.push(n),n=[])}),(n.length>1||o&&n.length>0)&&e.push(n),e.forEach(e=>{let t=e.map(e=>Array.from(l.children).find(t=>t instanceof HTMLElement&&t.getAttribute(`data-wrapper-id`)===e.id)).filter(e=>!!e);if(t.length<(o?1:2))return;let n=Mo(`tool-group-${e[0].id}`,`assistant`);if(n.setAttribute(`data-persona-tool-group-row`,`true`),r.features?.toolCallDisplay?.groupedMode===`collapsible`){let o=`tool-group-${e[0].id}`,c=e.some(e=>e.toolCall?.status!==`complete`),l={...e[0],id:o,toolCall:{id:o,name:`${e.length} tools`,status:c?`running`:`complete`,chunks:e.flatMap(e=>e.toolCall?.chunks??[]),success:!e.some(e=>e.toolCall?.success===!1)}};i.add(o),s.observe(l,`tool`,a,r.features.toolCallDisplay);let u=`${c?`Using`:`Used`} ${e.length} tools`,d=r.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall),defaultSummary:u,config:r}),f=xl(l,r,a.has(o),d??u);f.bubble.classList.add(`persona-tool-group`),f.body.dataset.personaToolGroupStack=`true`,t[0].before(n),n.appendChild(f.bubble),t.forEach((e,t)=>{e.style.setProperty(`--persona-message-row-max-width`,`100%`),e.style.setProperty(`--persona-activity-stagger`,`${t*40}ms`),e.classList.add(`persona-activity-group-child`),f.body.appendChild(e)});return}let c=document.createElement(`div`);c.className=`persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2`,c.setAttribute(`data-persona-tool-group`,`true`);let u=document.createElement(`div`);u.className=`persona-tool-group-summary persona-text-xs persona-text-persona-muted`,u.id=`tool-group-summary-${e[0].id}`;let d=`Called ${e.length} ${e.length===1?`tool`:`tools`}`,p=r.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall).filter(e=>!!e),defaultSummary:d,config:r});f(u,p)||(u.textContent=d);let m=document.createElement(`div`);m.className=`persona-tool-group-stack persona-flex persona-flex-col`,m.id=`tool-group-stack-${e[0].id}`,m.setAttribute(`data-persona-tool-group-stack`,`true`),c.appendChild(u),o||c.appendChild(m),n.appendChild(c),t[0].before(n),t.forEach((e,n)=>{if(o){e.remove();return}e.style.setProperty(`--persona-message-row-max-width`,`100%`);let r=document.createElement(`div`);r.className=`persona-tool-group-item persona-relative`,r.setAttribute(`data-persona-tool-group-item`,`true`),n<t.length-1&&r.setAttribute(`data-persona-tool-group-connector`,`true`),r.appendChild(e),m.appendChild(r)})})}s.prune(i),Hp(Gi,p);let re=e=>e.variant===`tool`&&!Ee||e.variant===`reasoning`&&!Te||ne(e),ie=t.some(e=>e.role===`assistant`&&e.streaming&&!re(e)),ae=t.length-1;for(;ae>=0&&re(t[ae]);)ae--;let oe=ae>=0?t[ae]:void 0,j=ae<t.length-1,se=oe?.role===`assistant`&&!oe.streaming&&oe.variant!==`approval`&&!j;if(Wi&&t.some(e=>e.role===`user`)&&!ie&&!se){let e={config:r,streaming:!0,location:`standalone`,defaultRenderer:jh},t=d.find(e=>e.renderLoadingIndicator),n=null;if(t?.renderLoadingIndicator&&(n=t.renderLoadingIndicator(e)),n===null&&r.loadingIndicator?.render&&(n=r.loadingIndicator.render(e)),n===null&&(n=jh()),n){let e=document.createElement(`div`),t=r.loadingIndicator?.showBubble!==!1,i=r.layout?.messages?.layout??`bubble`;e.className=t?Fh(`assistant`,i).join(` `):[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-text`].join(` `),e.setAttribute(`data-typing-indicator`,`true`),t&&(e.style.color=`var(--persona-message-assistant-text, var(--persona-text))`,i!==`flat`&&(e.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,e.style.borderColor=`var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))`)),e.appendChild(n);let a=Mo(`typing-indicator`,`assistant`);a.appendChild(e),l.appendChild(a)}}if(!Wi&&t.length>0){let e=t[t.length-1],n={config:r,lastMessage:e,messageCount:t.length},i=d.find(e=>e.renderIdleIndicator),a=null;if(i?.renderIdleIndicator&&(a=i.renderIdleIndicator(n)),a===null&&r.loadingIndicator?.renderIdle&&(a=r.loadingIndicator.renderIdle(n)),a){let e=document.createElement(`div`);e.className=r.loadingIndicator?.showBubble===!1?[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-primary`].join(` `):[`persona-rounded-2xl`,`persona-text-sm`,`persona-leading-relaxed`,`persona-shadow-sm`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-text-persona-primary`,`persona-px-5`,`persona-py-3`].join(` `),e.setAttribute(`data-idle-indicator`,`true`),e.appendChild(a);let t=Mo(`idle-indicator`,`assistant`);t.appendChild(e),l.appendChild(t)}}if(Xl(l),Pp(e,l),Ql(e),k){let{messageId:t,element:n}=k,r=e.querySelector(`#wrapper-${t}`);r&&n.parentElement!==r&&(jo(r,m.get(t)??`user`),r.replaceChildren(n))}if(v.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of v){let i=e.querySelector(`#wrapper-${t}`);i&&(jo(i,m.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),Ki.set(t,n)))}if(Ki.size>0)for(let e of Ki.keys())p.has(e)||Ki.delete(e);if(y.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of y){let i=e.querySelector(`#wrapper-${t}`);i&&(jo(i,m.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),qi.set(t,n)))}if(qi.size>0)for(let e of qi.keys())p.has(e)||qi.delete(e);if(S.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of S){let i=e.querySelector(`#wrapper-${t}`);i&&(jo(i,m.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),Ji.set(t,n)))}if(Ji.size>0)for(let e of Ji.keys())p.has(e)||Ji.delete(e)},Po=!1,Fo=()=>{Po||(Po=!0,Ni().catch(()=>{}),Ut().catch(()=>{Po=!1}))},Io=(e,t,n)=>{t.length>0&&Fo(),No(e,t,n),yr()},Lo=null,zo=()=>{if(Lo)return;let t=e=>{let t=e.composedPath();t.includes(F)||rt&&t.includes(rt)||Xo(!1,`user`)};Lo=t,(e.ownerDocument??document).addEventListener(`pointerdown`,t,!0)},Bo=()=>{Lo&&=((e.ownerDocument??document).removeEventListener(`pointerdown`,Lo,!0),null)};Z.push(()=>Bo());let Vo=null,Ho=()=>{if(Vo)return;let t=e=>{e.key===`Escape`&&(e.isComposing||Xo(!1,`user`))};Vo=t,(e.ownerDocument??document).addEventListener(`keydown`,t,!0)},Uo=()=>{Vo&&=((e.ownerDocument??document).removeEventListener(`keydown`,Vo,!0),null)};Z.push(()=>Uo());let Wo=!1,Go=/* @__PURE__ */ new Set,Ko=()=>r.launcher?.composerBar?.peek?.streamAnimation||r.features?.streamAnimation,qo=()=>{if(!N())return;let t=it.peekBanner,n=it.peekTextNode;if(!t||!n)return;if(P){t.classList.remove(`persona-pill-peek--visible`);return}let r=Q?.getMessages()??[],i;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.role===`assistant`&&t.content){i=t;break}}if(!i){t.classList.remove(`persona-pill-peek--visible`);return}let a=i.content,o=!!i.streaming,s=Ko(),c=em(s),l=c.type===`none`?null:Si(c.type,s?.plugins),u=l?.isAnimating?.(i)===!0,d=l!==null&&(o||u);d&&l&&!Go.has(l.name)&&(Cm(l,e),Go.add(l.name));let f=d&&l?.containerClass?l.containerClass:null,p=n.dataset.personaPeekStreamClass??null;p&&p!==f&&(n.classList.remove(p),delete n.dataset.personaPeekStreamClass),f&&p!==f&&(n.classList.add(f),n.dataset.personaPeekStreamClass=f),d?(n.style.setProperty(`--persona-stream-step`,`${c.speed}ms`),n.style.setProperty(`--persona-stream-duration`,`${c.duration}ms`)):(n.style.removeProperty(`--persona-stream-step`),n.style.removeProperty(`--persona-stream-duration`));let m=d?cm(a,c.buffer,l,i,o):a;if(d&&c.placeholder===`skeleton`&&o&&(!m||!m.trim())){let e=document.createElement(`div`),t=_m();t.classList.add(`persona-pill-peek__skeleton`),e.appendChild(t),Pp(n,e)}else{let e=Math.max(0,m.length-100),r=m.length>100?m.slice(-100):m,a=jl(r);if(!d||!l){let e=m.length>100?`…${r}`:r;n.textContent!==e&&(n.textContent=e)}else{let o=a;(l.wrap===`char`||l.wrap===`word`)&&(o=hm(a,l.wrap,`peek-${i.id}`,{skipTags:l.skipTags,startIndex:e}));let s=document.createElement(`div`);if(s.innerHTML=o,l.useCaret&&r.length>0){let e=gm(),t=s.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];n?.parentNode?n.parentNode.insertBefore(e,n.nextSibling):s.appendChild(e)}Pp(n,s),l.onAfterRender?.({container:n,bubble:t,messageId:i.id,message:i,speed:c.speed,duration:c.duration})}}let h=Wi||Wo;t.classList.toggle(`persona-pill-peek--visible`,h)};if(N()){let e=it.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),Xo(!0,`user`)};e.addEventListener(`pointerdown`,t),Z.push(()=>{e.removeEventListener(`pointerdown`,t)})}let t=()=>{Wo||(Wo=!0,qo())},n=()=>{Wo&&(Wo=!1,qo())};I.addEventListener(`pointerenter`,t),I.addEventListener(`pointerleave`,n),Z.push(()=>{I.removeEventListener(`pointerenter`,t),I.removeEventListener(`pointerleave`,n)}),rt&&(rt.addEventListener(`pointerenter`,t),rt.addEventListener(`pointerleave`,n),Z.push(()=>{rt.removeEventListener(`pointerenter`,t),rt.removeEventListener(`pointerleave`,n)}))}let Jo=e=>{let t=r.launcher?.composerBar??{},n=t.expandedSize??`anchored`,i=t.bottomOffset??`16px`,a=t.collapsedMaxWidth,o=t.expandedMaxWidth??`880px`,s=t.expandedTopOffset??`5vh`,c=t.modalMaxWidth??`880px`,l=t.modalMaxHeight??`min(90vh, 800px)`,u=`calc(100vw - 32px)`,d=F.style;if(d.left=``,d.right=``,d.top=``,d.bottom=``,d.transform=``,d.width=``,d.maxWidth=``,d.height=``,d.maxHeight=``,rt){let e=rt.style;e.bottom=i,e.width=a??``}e&&n!==`fullscreen`&&(n===`modal`?(d.top=`50%`,d.left=`50%`,d.transform=`translate(-50%, -50%)`,d.bottom=`auto`,d.right=`auto`,d.width=c,d.maxWidth=u,d.maxHeight=l,d.height=l):(d.left=`50%`,d.transform=`translateX(-50%)`,d.bottom=`calc(${i} + var(--persona-pill-area-height, 80px))`,d.top=s,d.width=o,d.maxWidth=u))},Yo=()=>{if(P&&Fo(),!be())return;if(N()){let e=(r.launcher?.composerBar??{}).expandedSize??`anchored`,t=P?`expanded`:`collapsed`;F.dataset.state=t,F.dataset.expandedSize=e,rt&&(rt.dataset.state=t,rt.dataset.expandedSize=e),F.style.removeProperty(`display`),F.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),I.classList.remove(`persona-scale-95`,`persona-opacity-0`,`persona-scale-100`,`persona-opacity-100`),Jo(P),L.style.display=P?`flex`:`none`,Tr(),P?(zo(),Ho()):(Bo(),Uo()),qo();return}let t=Mm(r),n=e.ownerDocument.defaultView??window,i=r.launcher?.mobileBreakpoint??640,a=r.launcher?.mobileFullscreen??!0,o=n.innerWidth<=i,s=a&&o&&M,c=Pm(r).reveal;P?(F.style.removeProperty(`display`),F.style.display=t?`flex`:``,F.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),I.classList.remove(`persona-scale-95`,`persona-opacity-0`),I.classList.add(`persona-scale-100`,`persona-opacity-100`),Su?(Su.setPanelOpen(!0),Su.element.style.display=`none`):wu&&(wu.style.display=`none`)):(t?t&&(c===`overlay`||c===`push`)&&!s?(F.style.removeProperty(`display`),F.style.display=`flex`,F.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),I.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(F.style.setProperty(`display`,`none`,`important`),F.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),I.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(F.style.display=``,F.classList.add(`persona-pointer-events-none`,`persona-opacity-0`),I.classList.remove(`persona-scale-100`,`persona-opacity-100`),I.classList.add(`persona-scale-95`,`persona-opacity-0`)),Su?(Su.setPanelOpen(!1),Su.element.style.display=t?`none`:``):wu&&(wu.style.display=t?`none`:``))},Xo=(t,n=`user`)=>{if(!be()||P===t)return;let i=P;P=t,Yo();let a=(()=>{let t=r.launcher?.sidebarMode??!1,n=e.ownerDocument.defaultView??window,i=r.launcher?.mobileFullscreen??!0,a=r.launcher?.mobileBreakpoint??640,o=n.innerWidth<=a,s=Mm(r)&&i&&o,c=N()&&(r.launcher?.composerBar?.expandedSize??`fullscreen`)===`fullscreen`;return t||i&&o&&M||s||c})();if(P&&a){if(!_i){let t=e.getRootNode(),n=t instanceof ShadowRoot?t.host:e.closest(`.persona-host`);n&&(_i=Dm(n,r.launcher?.zIndex??1e5))}vi||=Am(e.ownerDocument)}else P||(_i?.(),_i=null,vi?.(),vi=null);P&&(Ou(),ho()||(Nt()===`follow`?oo(!0):lo()));let o={open:P,source:n,timestamp:Date.now()};P&&!i?O.emit(`widget:opened`,o):!P&&i&&O.emit(`widget:closed`,o),O.emit(`widget:state`,{open:P,launcherEnabled:M,voiceActive:$.active,streaming:Q.isStreaming()})},Zo={inputDisabled:!1,sendDisabled:!1},$o=()=>Zo.inputDisabled,es=()=>Cl(r.voiceRecognition?.provider)&&!!Q&&(Q.isBargeInActive()||[`listening`,`processing`,`speaking`].includes(Q.getVoiceStatus())),is=()=>Zo.inputDisabled||Zo.sendDisabled,os=()=>(Zo.inputDisabled?Zo.inputReason:void 0)??(Zo.sendDisabled?Zo.sendReason:void 0);function us(){if(!V)return;if(G.getState().phase===`streaming`){V.disabled=!1;return}let e=dn?!dn.isReady():!1;V.disabled=is()||e}function ps(){if(!wt)return;let e=G.getState(),t=r.sendButton?.visibility===`when-text`&&e.phase!==`streaming`&&e.text.trim().length===0&&e.attachments.length===0;wt.toggleAttribute(`data-persona-send-hidden`,t)}function ms(){let e=os();if(N()){let t=ct??bt;e?t.setAttribute(`title`,e):t.removeAttribute(`title`),bt.toggleAttribute(Hv,!!e)}else if(e)lt.setAttribute(`role`,`status`),lt.setAttribute(`aria-live`,`polite`),lt.setAttribute(Hv,``),lt.removeAttribute(Uv),lt.textContent=e,Ga(lt,r.statusIndicator??{},`idle`);else if(lt.hasAttribute(Hv)&&(lt.removeAttribute(`role`),lt.removeAttribute(`aria-live`),lt.removeAttribute(Hv),m)){let e=Q.getStatus();tt(lt,et(e),r.statusIndicator??{},e)}}function gs(){let e=ls(r.composer?.inputDisabled),t=ls(r.composer?.sendDisabled);Zo={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},G.setInputDisabled(e.disabled),G.setSendDisabled(t.disabled);let n=G.getState().phase===`streaming`,i=e.disabled,a=n||i;B&&(B instanceof HTMLTextAreaElement?B.disabled=i:B.setAttribute(`contenteditable`,i?`false`:`true`),B.setAttribute(`aria-disabled`,i?`true`:`false`)),Dt&&(Dt.disabled=i),kt&&(kt.disabled=i);for(let e of fn?.affordanceButtons??[])e.querySelectorAll(`button`).forEach(e=>{e.disabled=i});U&&(U.disabled=i||n&&!es()),Di.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute(`data-disabled`,a),e instanceof HTMLButtonElement||e.setAttribute(`aria-disabled`,a?`true`:`false`)}),e.buttons.forEach(e=>{e.disabled=a})}),Ls.forEach(e=>{e.toggleAttribute(`data-disabled`,a),e instanceof HTMLButtonElement?e.disabled=a:e.setAttribute(`aria-disabled`,a?`true`:`false`),e.querySelectorAll(`button`).forEach(e=>{e.disabled=a})}),bt.dataset.personaComposerStreaming=n?`true`:`false`,bt.dataset.personaComposerInputDisabled=i?`true`:`false`,bt.dataset.personaComposerSendDisabled=is()?`true`:`false`,bt.querySelectorAll(`[data-persona-composer-disable-when-streaming]`).forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=n)}),us(),ms()}let vs=e=>{G.setStreaming(e),Tt(e?`stop`:`send`),gs()},ys=()=>{$.active||B&&B.focus()};O.on(`widget:opened`,()=>{r.autoFocusInput&&setTimeout(()=>ys(),200)});let bs=null,xs=!1,Cs=!ut.hidden,ws=null,Ts=!ne,Ds=null;Z.push(()=>{Ds?.cancel(),Ds=null});let Os=t=>{let n=sg(t);if(n===nn)return;nn=n,e.setAttribute(`data-persona-conversation-state`,n);let r=an();ln(),Ts&&(Ds?.cancel(),Ds=ng(bt,n===`active`?r:an(),n===`active`?`drop`:`rise`,tn().layout===`centered`?320:260)),wo()},ks=null,js,Ms=null,Ns=null,Ps=!1,Fs=e=>{let t=tn(),n=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??`bottom`}|${t.align??``}|${t.iconPlacement}|${t.kicker??``}|${t.title}|${t.subtitle}`;(n!==ks||t.icon!==js)&&(ks=n,js=t.icon,Kh({host:ut,iconHolder:dt,kicker:pt,title:mt,subtitle:ht,starterSuggestions:at},t));let i=t.message===void 0?null:`${r.layout?.messages?.layout??`bubble`}|${t.message}`;i!==Ms&&(Ms=i,$h(ft,t.message,r));let a=e??(Q?Q.getMessages():r.initialMessages);Os(a);let o=xs,s=!o&&cg(t,a),c=s!==Cs;if(Cs=s,Ns){ws?.cancel(),ws=null,o!==Ps&&(Ps=o,o?Zh(R,ut,null):Xh(R,ut,Ns)),Gh(R,ut,!o);return}if(c&&!s&&!o&&t.dismiss===`on-first-message`&&Ts){ws=tg(ut,e=>{ws===e&&(ws=null),!Cs&&!Ns&&(Gh(R,ut,!1),wo()),e?.cancel()});return}if(ws){if(!s&&!o)return;ws.cancel(),ws=null}let l=!ut.hidden;Gh(R,ut,s),!s&&l&&wo()},Is=[],Ls=[],Rs=!1,zs=null,Bs,Vs=()=>{Ls.length=0;let e=Is.splice(0,Is.length);for(let t of e)try{t()}catch(e){console.warn(`[persona] renderWelcome cleanup threw`,e)}};Z.push(Vs);let Hs=(e,t)=>{let n=Im(e,t);if(!n)return r.debug===!0&&console.warn(`[persona] renderStarter received a suggestion with no label`),q(`span`);let i=r.suggestions?.starters,a=Bm({item:{...n,behavior:n.behavior??i?.behavior??`send`},index:t,surface:`starter`,source:`config`,variant:i?.variant??`card`,streaming:m?Q.isStreaming():!1,config:r,plugins:d,chipsConfig:r.suggestionChipsConfig,session:Q,getTextarea:()=>B,eventTarget:ut,submitPrompt:ml});return Ls.push(a),a},Ws=()=>{if(Rs)return;Rs=!0;let e=tn();zs=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`,Bs=e.icon;try{Vs(),Zh(R,ut,Ns),Ns=null,Ps=!1;let t=Q?Q.getMessages():r.initialMessages,n=cg(e,t),i=0,a=null;for(let t of d)if(t.renderWelcome&&(a=t.renderWelcome({config:e,variant:e.variant,visible:n,defaultRenderer:()=>ut,sendMessage:e=>{if(!Q||Q.isStreaming())return;let t=e.trim();t&&Q.sendMessage(t)},requestRender:()=>Ws(),renderStarter:e=>Hs(e,i++),storage:h(t.id),onCleanup:e=>{Is.push(e)}}),a))break;a&&a!==ut&&(Ns=a,Xh(R,ut,a))}finally{Rs=!1}Fs()},Ks=()=>{let e=tn();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`!==zs||e.icon!==Bs)&&Ws()},qs=()=>{Fs(),Gn||(B.placeholder=gf(G.getState().activeModeIds,r.composer?.modes)??r.copy?.inputPlaceholder??`How can I help...`,!(r.sendButton?.useIcon??!1)&&!Q?.isStreaming()&&(V.textContent=r.copy?.sendButtonLabel??`Send`)),B.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,B.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`},Js=!!r.setStoredConversationId,Ys=e=>ue(t=>{let n={...t};return delete n[e],n}),Xs=e=>{let t=A[e];return typeof t==`string`?t:null},Zs=()=>{let e=A.durableResume;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.executionId==`string`&&t.executionId.length>0&&typeof t.after==`string`&&t.after.length>0?{executionId:t.executionId,after:t.after}:null};r.clientToken&&(r={...r,getStoredSessionId:()=>Xs(`sessionId`),setStoredSessionId:e=>{ue(t=>({...t,sessionId:e}))},clearStoredSessionId:r.clearStoredSessionId??(()=>Ys(`sessionId`)),getStoredConversationId:r.getStoredConversationId??(()=>Xs(`conversationId`)),setStoredConversationId:r.setStoredConversationId??(e=>{ue(t=>({...t,conversationId:e}))}),clearStoredConversationId:r.clearStoredConversationId??(()=>Ys(`conversationId`))});let Qs=()=>r.clientToken??null,$s=e=>wv(e,Ae(),r.persistState===!1),ec=Qs(),tc=ec?$s(ec):null,nc=()=>{let e=A.pendingDisplayProjections;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.conversationId!=`string`||!Array.isArray(t.messageIds)?null:{conversationId:t.conversationId,messageIds:t.messageIds.filter(e=>typeof e==`string`)}},rc={...tc?{visitorStore:tc}:{},historyBootstrapReady:r.features?.history?.enabled===!0&&!ol()?Promise.all([ie,oe]).then(()=>{}):ie,getStoredMessageCursor:()=>Xs(`historyMessageCursor`),setStoredMessageCursor:e=>{e===null?Ys(`historyMessageCursor`):ue(t=>({...t,historyMessageCursor:e}))},getPendingDisplayProjections:nc,setPendingDisplayProjections:e=>{e?ue(t=>({...t,pendingDisplayProjections:e})):Ys(`pendingDisplayProjections`)},getStoredResumableHandle:Zs,setStoredResumableHandle:e=>{e?ue(t=>({...t,durableResume:e})):Ys(`durableResume`)},shouldResumeDurableConversation:()=>ee&&Zs()!==null,...Js?{}:{getStoredConversationRevision:()=>Xs(`conversationRevision`),setStoredConversationRevision:e=>{e===null?Ys(`conversationRevision`):ue(t=>({...t,conversationRevision:e}))}}};if(ee){let t=r.onExecutionState,n=e.ownerDocument.defaultView,i=!1,a=()=>i=!0,o=()=>i=!1;n?.addEventListener(`pagehide`,a),n?.addEventListener(`pageshow`,o),Z.push(()=>{n?.removeEventListener(`pagehide`,a),n?.removeEventListener(`pageshow`,o)}),r={...r,reconnectStream:r.reconnectStream??(e=>Q.getClient().reconnectClientTokenStream(e)),onExecutionState:e=>{(e||!i)&&rc.setStoredResumableHandle?.(e?{executionId:e.executionId,after:e.lastEventId}:null),t?.(e)}}}let ic=()=>{let e=Qs();if(e&&tc?.matches(e,Ae(),r.persistState===!1)||!e&&!tc)return;tc?.destroy(),tc=e?$s(e):null;let t={...rc};tc?t.visitorStore=tc:delete t.visitorStore,rc=t,Q.setHistoryInternals(rc)},ac=null,oc=()=>{ac??=setInterval(()=>{let e=z.querySelectorAll(`[data-tool-elapsed]`);if(e.length===0){clearInterval(ac),ac=null;return}let t=Date.now();e.forEach(e=>{let n=Number(e.getAttribute(`data-tool-elapsed`));n&&(e.textContent=e.closest(`.persona-activity-row`)?vl(t-n):Vn(t-n))})},100)},sc=(e,t)=>{if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>sc(e,t[n]));let n=e,r=t,i=Object.keys(n),a=Object.keys(r);return i.length===a.length&&i.every(e=>Object.prototype.hasOwnProperty.call(r,e)&&sc(n[e],r[e]))},cc=e=>{let{content:t,rawContent:n,llmContent:r,...i}=e;return i},lc=e=>e.role===`assistant`&&e.streaming===!0&&!e.variant&&!e.toolCall&&!e.tools&&!e.approval&&!e.reasoning&&!e.contentParts&&!e.stopReason&&!Iv(e),uc=(e,t,n)=>{if(e.length!==t.length)return!1;let r=e[n.index],i=t[n.index];return!r||!i||r.id!==n.id||i.id!==n.id?!1:(!Object.is(r.content,i.content)||!Object.is(r.rawContent,i.rawContent)||!Object.is(r.llmContent,i.llmContent))&&lc(r)&&lc(i)&&sc(cc(r),cc(i))},dc=null,fc=null,pc=null,mc=null,hc=null,gc=e=>{if(!ee)return Ia(e);hc=e,queueMicrotask(()=>{hc===e&&(hc=null,Ia(e))})},_c=e=>{dc=e;let t,n;fc=null;for(let r=e.length-1;r>=0;--r){let i=e[r];if(!t&&i.role===`user`&&(t=i),!n&&i.role===`assistant`&&(n=i),!fc&&lc(i)&&(fc={index:r,id:i.id}),t&&n&&fc)break}Io(z,e,we),f_()?.updateInlineArtifactBlocks(z,Or.artifacts,{suppressTransition:Wi}),oc(),Fs(e),Vi(e),oo(!Wi),Ao(e),e.length===0&&(yo(),da=!0,fa=!1,pa=null,ma=!1),!ca||la?(ca=!0,ua=t?.id??null,ga=n?.id??null):t&&t.id!==ua?(ua=t.id,Eo(t.id)):n&&n.id!==ga&&Do(),n&&(ga=n.id),ko(e);let r=$.lastUserMessageId;t&&t.id!==r&&($.lastUserMessageId=t.id,O.emit(`user:message`,t)),$.lastUserMessageWasVoice=!!t?.viaVoice,gc(e),qo()},vc=()=>{mc!==null&&(cancelAnimationFrame(mc),mc=null);let e=pc;pc=null,e&&_c(e)},yc=()=>{mc!==null&&cancelAnimationFrame(mc),mc=null,pc=null},bc=e=>{let t=pc??dc;Wi&&t&&fc&&uc(t,e,fc)?(pc=e,mc===null&&(mc=requestAnimationFrame(()=>{mc=null;let e=pc;pc=null,e&&_c(e)}))):e.length===0?(yc(),_c(e)):(vc(),_c(e))};Q=new fd(r,{onMessagesChanged(e){bc(e)},onStatusChanged(e){let t=r.statusIndicator??{};tt(lt,(e=>e===`idle`?t.idleText??gi.idle:e===`connecting`?t.connectingText??gi.connecting:e===`connected`?t.connectedText??gi.connected:e===`error`?t.errorText??gi.error:e===`paused`?t.pausedText??gi.paused:e===`resuming`?t.resumingText??gi.resuming:gi[e])(e),t,e),Ze()},onStreamingChanged(e){e||(Q?.getMessages().length===0?yc():vc()),Wi=e,vs(e),Ze(),Q&&Io(z,Q.getMessages(),we),e||(oo(!0),vo(),zi=!0,Q&&Bi(Q.getMessages(),di(r))),ro(),$t(e?`Responding…`:`Response complete.`),qo()},onVoiceStatusChanged(e){if(O.emit(`voice:status`,{status:e,timestamp:Date.now()}),e!==`disconnected`&&!Cl(r.voiceRecognition?.provider))return;let t=Q.getVoiceNotice();switch(t&&tl(t,1e4),e){case`listening`:if(!xa){let e=Q.getVoiceDisclosure();e&&(xa=!0,N()?(Sa=B.placeholder,B.placeholder=e,$t(e)):tl(e,1e4))}ou(),ru();break;case`processing`:ou(),iu();break;case`speaking`:ou(),au();break;default:e===`idle`&&Q.isBargeInActive()?(ou(),ru(),U?.setAttribute(`aria-label`,`End voice session`)):($.active=!1,xa=!1,Sa!==null&&(B.placeholder=Sa,Sa=null),ou(),Oa(`system`),Da||ka())}},onArtifactsState(e){Or=e,e.artifacts.length===0&&(Mr=!1),f_()?.updateInlineArtifactBlocks(z,e.artifacts,{suppressTransition:Wi}),si(),Ia()},onHistoryStateChanged(e){Ye(e)},onHistoryNotice(e){Xe(e)},onReconnect(e){let{executionId:t,lastEventId:n}=e.handle;e.phase===`paused`?O.emit(`stream:paused`,{executionId:t,after:n}):e.phase===`resuming`?O.emit(`stream:resuming`,{executionId:t,after:n,attempt:e.attempt??1}):O.emit(`stream:resumed`,{executionId:t,after:n})}},rc),Fr.current=Q,Z.push(()=>Q.cancel()),Z.push(()=>{Q.destroy(),tc?.destroy(),tc=null});let xc=null;if(Q.onReadAloudChange((e,t)=>{hr=e,gr=t,yr();let n=e??xc;e&&(xc=e);let r=n?Q.getMessages().find(e=>e.id===n)??null:null;O.emit(`message:read-aloud`,{messageId:n,message:r,state:t,timestamp:Date.now()}),t===`idle`&&(xc=null)}),m=!0,ca=!0,r.voiceRecognition?.enabled===!0&&Cl(r.voiceRecognition.provider))try{Q.setupVoice()}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Runtype voice setup failed:`,e)}let Sc=null,Cc=null,wc=!1,Tc=Q.getHistoryState(),Ec=()=>r.features?.history?.enabled===!0,Dc=e=>{e&&(Xt.textContent=``,Xt.textContent=e)},Oc=()=>{p.forEach(e=>e()),p=[];let t=Sc,n=t?.railCollapseShortcut();t&&n&&p.push(f.register({id:`history-rail-collapse`,combo:n.combo,scope:r.features?.history?.rail?.collapseShortcutScope===`page`?`page`:`widget`,when:()=>Ge&&Ke===`rail`&&t.railCollapsible()||t.railTriggerApplies(),run:()=>t.railOverlayMode()?t.toggleRailPinned():t.toggleRailCollapsed()}));for(let t of r.layout?.header?.trailingActions??[])t.shortcut&&p.push(f.register({id:`header-action-${t.id}`,combo:t.shortcut,run:()=>{let n=e.querySelector(`[data-persona-header-action="${t.id}"]`);n?n.click():r.layout?.header?.onAction?.(t.id)}}));for(let e of d)for(let t of e.shortcuts??[])p.push(f.register({...t,id:`${e.id}:${t.id}`}))};Oc();let kc=null,Ac=!1,jc=()=>{if(!_t)return;let e=r.layout?.header?.titleSource===`conversation`,t=e&&kc?.trim()||null;_t.textContent=t??r.launcher?.title??`Chat Assistant`;let n=_t.closest(`.persona-combo-btn`);if(!n)return;let i=!e||Q.getActiveConversationId()!==null;n.setAttribute(`data-persona-menu-locked`,i?`false`:`true`),n.setAttribute(`aria-haspopup`,i?`true`:`false`),i||n.setAttribute(`aria-expanded`,`false`),n.style.cursor=i?`pointer`:`default`;let a=n.querySelector(`svg`);a&&(a.style.display=i?``:`none`)},Mc=e=>{e!==kc&&(kc=e,jc())},Pc=e=>{Ac=e?.starred===!0,Mc(e&&e.title.trim()||null),jc()};jc(),L.addEventListener(`persona:title-menu-builtin`,e=>{let t=e.detail?.actionId,n=Q.getActiveConversationId();n&&(t===`delete`?Rc(e=>e.requestDeleteConversation(n)):t===`star`&&Q.canUpdateConversations()&&Rc(e=>e.updateHistoryConversation(n,{starred:!Ac})).catch(()=>{}))}),Ye=e=>{Tc=e,Sc?.historySurface?.view.setNewConversationRequired(e.recovery===`new_conversation_required`),vs(e.sendBlocked||Wi),Sc?.syncEarlierMessagesPill()},Xe=e=>{(e.code===`history_continuity_reset`||e.code===`conversation_deleted_recovered`)&&(Gi.clear(),yo(),ao()),Dc(e.message),Sc?.historySurface?.view.refresh()};let Fc={get actionManager(){return pe},get activeConversationTitle(){return kc},announceHistory:Dc,get applyRailChrome(){return Je},set applyRailChrome(e){Je=e},get artifactSplitRoot(){return Wr},get body(){return R},get config(){return r},get container(){return L},get conversationOpenPendingEl(){return bs},set conversationOpenPendingEl(e){bs=e},get conversationOpenTakeover(){return xs},set conversationOpenTakeover(e){xs=e},currentKeyPrefix:Ae,destroyCallbacks:Z,eventBus:O,get footer(){return bt},get header(){return yt},get historyChromeSync(){return Ze},set historyChromeSync(e){Ze=e},historyFeatureEnabled:Ec,get historyInternals(){return rc},set historyInternals(e){rc=e},get historyPresentation(){return Ke},set historyPresentation(e){Ke=e},get historySessionState(){return Tc},get historyVisible(){return Ge},set historyVisible(e){Ge=e},get isStreaming(){return Wi},jumpToBottomInstant:lo,get lastAppliedMessages(){return dc},set lastAppliedMessages(e){dc=e},get launcherEnabled(){return M},get launcherSurfaceInstance(){return Su},maybeFocusInput:ys,messageCache:Gi,get messagesWrapper(){return z},mount:e,get open(){return P},panel:I,panelElements:it,get persistentMetadata(){return A},set persistentMetadata(e){A=e},plugins:d,get reapplyHistoryHostChrome(){return qe},set reapplyHistoryHostChrome(e){qe=e},repinAnchoredMessage:wo,resetAnchorState:yo,restoreScrollPosition:ho,resumeAutoScroll:ao,runStorageMutation:Fa,get session(){return Q},setActiveConversationSummary:Pc,storageAdapter:k,get suppressScrollSend(){return la},set suppressScrollSend(e){la=e},syncScrollToBottomButton:ro,updateWelcome:Fs,getHistoryProviderFactory:Ov,historyErrors:{HistoryClientError:hu,HistoryProviderError:Cu},isDockedMountMode:Mm,renderLucideIcon:K,loadHistoryView:Dv,createHeaderIconButton:Km,attachTooltip:Ea},Ic=e=>(!Sc&&!wc&&(Sc=e.createHistoryShell(Fc),Sc.railCollapseShortcut()&&Oc()),Sc),Lc=()=>{if(Sc)return Promise.resolve(Sc);let e=ol();return e?Promise.resolve(Ic(e)):(Cc??=il().then(Ic,e=>{throw Cc=null,e}),Cc)},Rc=e=>{let t=ol(),n=Sc??(t?Ic(t):null);return n?e(n):Lc().then(t=>{if(!t)throw Error(`[AgentWidget] The widget was destroyed`);return e(t)})},zc=()=>{Sc?.syncHistoryPresentation()};Z.push(()=>{wc=!0}),Ec()&&Lc().catch(()=>{}).finally(ae),r.clientToken&&(r.features?.history?.enabled===!0||r.sessionInit===`mount`)&&Q.initClientSession().then(()=>{let e=Sc;if(e?.historyAvailable())return Q.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{Sc?.syncEarlierMessagesPill()}).catch(e=>{r.debug&&console.warn(`[AgentWidget] Pre-init client session failed:`,e)});let Bc=()=>Q.warmClientSession(),Vc=e=>{let t=r.sessionInit??`input`,n=Jn?.input??B,i=e.target;n&&(e.type===`input`?(t===`input`||t===`focus`)&&i===n&&e.inputType&&n.value.trim():t===`focus`&&(e.type===`keyup`?i===n&&e.key===`Tab`:(Jn?.form??ct)?.contains(i)))&&Bc()},Hc=[`input`,`pointerdown`,`keyup`];Hc.forEach(t=>e.addEventListener(t,Vc));let Uc,Wc,Gc=()=>{let e=Wc;Wc=void 0;try{typeof e==`function`&&e()}catch{}},Kc=()=>{let t=r.clientToken&&typeof r.sessionInit==`function`?r.sessionInit:void 0;if(t!==Uc){Gc(),Uc=t;try{Wc=t?.({warm:Bc,mount:e})}catch{}}};Kc(),Z.push(()=>{Hc.forEach(t=>e.removeEventListener(t,Vc)),Gc()}),(De||r.onSSEEvent)&&Q.setSSEEventCallback((e,t)=>{r.onSSEEvent?.(e,t),Ue(e,t)});let qc=()=>{let e=r.resume??(ee?rc.getStoredResumableHandle?.():null);e&&typeof r.reconnectStream==`function`&&Q.resumeFromHandle(e)};ne?ne.then(e=>{if(e){if(e.metadata&&(A=Yv(e.metadata),pe.syncFromMetadata()),e.messages?.length){la=!0;try{Q.hydrateMessages(e.messages)}finally{la=!1}Fo()}e.artifacts?.length&&Q.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),Ha(e.draft)}}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to hydrate stored state:`,e)}).finally(()=>{Ts=!0,re(),qc()}):(Ha(j),qc());let Jc=()=>{N()&&(P||(r.launcher?.composerBar?.expandOnSubmit??!0)&&Xo(!0,`auto`))},Yc=(e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[n,r]=await Promise.allSettled([e.finalize(),t.finalize()]),i=[];return n.status===`fulfilled`?i.push(n.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,n.reason),r.status===`fulfilled`?i.push(r.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,r.reason),ey(i)}}:e:t,Xc=()=>{let e=B.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>e.kind===`mention`)?e.contentSegments:void 0},Zc=!1,Qc=null,$c=()=>{B.value=``,B.style.height=`auto`,pn(),Tl()},el=null;function tl(e,t=4e3){$t(e),!N()&<&&(lt.hasAttribute(Hv)||(lt.setAttribute(Uv,``),lt.setAttribute(`role`,`status`),lt.setAttribute(`aria-live`,`polite`),lt.textContent=e,Ga(lt,r.statusIndicator??{},`idle`),el&&clearTimeout(el),el=setTimeout(()=>{if(el=null,lt?.hasAttribute(Uv)&&(lt.removeAttribute(Uv),lt.removeAttribute(`role`),lt.removeAttribute(`aria-live`),m)){let e=Q.getStatus();tt(lt,et(e),r.statusIndicator??{},e)}},t)))}function nl(){let e=G.getState().pendingSubmission;e&&(Nn(void 0),B&&(B.value=e.text,B.dispatchEvent(new Event(`input`,{bubbles:!0})),pn()),e.options.selectedModelId&&(G.setSelectedModelId(e.options.selectedModelId),Cn?.repaint()),e.options.activeModeIds?.length&&bn(e.options.activeModeIds),e.options.quote&&On(e.options.quote),B?.focus())}let rl=e=>{typeof console<`u`&&console.error(`[AgentWidget] composer.onBeforeSend failed; the draft was preserved:`,e)},al=(e={})=>{let t=(e.overrideText??B?.value??``).trim();return e.resolveInlineCommand&&t?(fn?.takeInlineCommand(t)??Promise.resolve(null)).then(n=>sl(e,t,n)):sl(e,t,null)},sl=(e,t,n)=>{if(n?.kind===`action`){$c(),fn?.clear(),mn();return}let i=n?.kind===`server`?n.mentions:null,a=n?.kind===`prompt`?n.sendText:t,o=e.pending?.contentParts;if(!kf({text:a,hasAttachments:(dn?.hasAttachments()??!1)||(o?.length??0)>0,attachmentsReady:dn?.isReady()??!0,hasMentions:fn?.hasMentions()??!1,hasServerMentions:!!i,inputDisabled:$o(),sendDisabled:is()}))return;let s=Q.isStreaming()?An():`block`;if(s===`defer-one`&&!e.pending){if(G.getState().pendingSubmission){tl(`One message is already queued. Edit or remove it first.`);return}cl({intent:e,sendText:a,serverMentions:i});return}let c={text:a,mentionRefs:[...fn?.getMentionRefs()??[],...i?.refs??[]],contentSegments:n?.kind===`prompt`?void 0:Xc(),options:{...G.getState().selectedModelId&&{selectedModelId:G.getState().selectedModelId},...G.getState().activeModeIds.length>0&&{activeModeIds:[...G.getState().activeModeIds]},...G.getState().quote&&{quote:{...G.getState().quote}}},viaVoice:e.viaVoice};e.pending&&(c.options={...e.pending.options},c.contentSegments=e.pending.contentSegments,c.mentionRefs=[...e.pending.mentionRefs],c.viaVoice=e.pending.viaVoice);let l=()=>{if(o?.length)return[...o];if(!dn?.hasAttachments())return;let e=[...dn.getContentParts()];return c.text&&e.push(Ro(c.text)),e};c.contentParts=l();let u=()=>{Zi(),Jc();let t=fn?.collectForSubmit()??null,n=Yc(t,i),a=l();e.consumeDraft!==!1&&$c();let o={selectedModelId:c.options.selectedModelId,activeModeIds:c.options.activeModeIds},u=s===`interrupt`;u&&Q.cancel(),Q.sendMessage(c.text,{contentParts:a,mentions:n??void 0,contentSegments:c.contentSegments,viaVoice:c.viaVoice,composerOptions:o,...c.options.quote&&{quote:c.options.quote},...u&&{interrupt:!0}}),dn?.hasAttachments()&&dn.clearAttachments(),t&&fn?.clear(),mn();let d=G.getState().activeModeIds,f=hf(d,r.composer?.modes);f.length!==d.length&&bn(f),G.getState().quote&&On(void 0),Ua(),sr.release(),lr()},d=r.composer?.onBeforeSend;if(!d){u();return}let f=new AbortController;Qc=f;let p=e=>{Qc=null,e.status===`error`?rl(e.error):e.status===`proceed`&&u()},m=Mf(d,c,f.signal);if(!(m instanceof Promise))p(m);else return G.setPreparing(!0),m.then(p).finally(()=>G.setPreparing(!1))};function cl(e){let t=G.getState(),n=dn?.hasAttachments()??!1,r=n?[...dn.getContentParts()]:[];n&&e.sendText&&r.push(Ro(e.sendText)),Nn(Of({text:e.sendText,contentParts:r.length?r:void 0,mentionRefs:[...fn?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:Xc(),options:{...t.selectedModelId&&{selectedModelId:t.selectedModelId},...t.activeModeIds.length>0&&{activeModeIds:[...t.activeModeIds]},...t.quote&&{quote:{...t.quote}}},viaVoice:e.intent.viaVoice})),e.intent.consumeDraft!==!1&&$c(),n&&dn.clearAttachments(),fn?.clear(),mn(),t.quote&&On(void 0),Ua(),sr.release(),lr(),$t(`Message queued. It sends when the response finishes.`)}function ll(){let e=G.getState().pendingSubmission;e&&(Nn(void 0),hl(e.text,{consumeDraft:!1,pending:e}))}function ul(e){if(r.messageActions?.showEdit!==!0)return;let t=Q.getMessages().find(t=>t.id===e);t&&Pu(t)&&Yi!==e&&(Zi(),Yi=e,Xi=bf({messageId:e,initialText:t.content,onSave:t=>dl(e,t),onCancel:()=>Zi()}),Gi.delete(e),Io(z,Q.getMessages(),we),Xi.focus())}function dl(e,t){let n=Xi;Yi=null,Xi=null,n?.destroy(),Gi.delete(e),Q.resubmitFrom(e,{reason:`edit`,replacement:{text:t,mentionRefs:[],options:{}}})?wo():Io(z,Q.getMessages(),we)}function fl(e){if(Q.isStreaming())return;let t=Mu(Q.getMessages(),e);t&&(Zi(),Q.resubmitFrom(t,{reason:`retry`})&&wo())}br={regenerate:fl,edit:ul,quote:e=>{let t=Q.getMessages().find(t=>t.id===e)?.content?.trim();t&&(On({text:t,messageId:e}),B?.focus())}};let pl=async e=>{if(!Zc){Zc=!0;try{await al({resolveInlineCommand:!0,...e})}finally{Zc=!1}}};function ml(e){is()||($c(),hl(e,{consumeDraft:!1}))}let hl=(e,t)=>{if(Zc)return;Zc=!0;let n=()=>{Zc=!1};try{let r=al({...t,overrideText:e});r instanceof Promise?r.finally(n):n()}catch(e){throw n(),e}},gl=e=>{e.preventDefault(),Q.isStreaming()?(Q.cancel(),Fe?.reset(),Re?.update()):Zc||pl()},yl=()=>r.features?.composerHistory!==!1,Sl={...Ip},wl=!1,Tl=()=>{Sl={...Ip}},El=()=>Q.getMessages().filter(e=>e.role===`user`).map(e=>e.content??``).filter(e=>e.length>0),Dl=e=>{if(!B)return;wl=!0,B.value=e,B.dispatchEvent(new Event(`input`,{bubbles:!0})),wl=!1;let t=B.value.length;B.setSelectionRange(t,t)},Ol=e=>{wl||(e.isComposing||fn?.handleInput(e.inputType??void 0),Tl())},kl=()=>({submitKey:r.composer?.submitKey,insertNewlineOnTouchEnter:r.composer?.insertNewlineOnTouchEnter,coarsePointer:rs(B)}),Al=e=>{if(B&&!$o()&&(e.isComposing||!fn?.handleKeydown(e))){if(yl()&&(e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.shiftKey&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.isComposing){let t=B.selectionStart===0&&B.selectionEnd===0,n=Lp({direction:e.key===`ArrowUp`?`up`:`down`,history:El(),currentValue:B.value,atStart:t,state:Sl});if(Sl=n.state,n.handled){e.preventDefault(),n.value!==void 0&&Dl(n.value);return}}if(as(e,kl())){if(Q.isStreaming()){if(e.preventDefault(),An()===`block`||Zc||is())return;Tl(),pl()}else Zc||is()?e.preventDefault():(Tl(),e.preventDefault(),V.click())}}},Ml=e=>{e.key!==`Escape`||e.isComposing||e.composedPath().includes(L)&&(Qc?(Qc.abort(),Qc=null,e.preventDefault(),e.stopImmediatePropagation()):Q.isStreaming()&&(Q.cancel(),Fe?.reset(),Re?.update(),Tl(),e.preventDefault(),e.stopImmediatePropagation()))},Nl=async e=>{if(r.attachments?.enabled!==!0||!dn||$o())return;let t=Gv(e.clipboardData);t.length!==0&&(e.preventDefault(),await dn.handleFiles(t))},Pl=null,Fl=!1,Il=null,Ll=null,Rl=()=>r.voiceRecognition?.completionBehavior===`review`;function zl(e){U?.setAttribute(`data-state`,e),e===`recording`?Jl():Yl()}let Bl=`--persona-voice-level`,Vl=.5,Hl=null,Ul=-1,Wl=0,Gl=()=>{let e=[],t=Et??U?.parentElement??null;return t&&e.push(t),bt&&e.push(bt),e},Kl=e=>{let t=Math.round(Math.max(0,Math.min(1,e))*100)/100;if(t!==Ul){Ul=t;for(let e of Gl())e.style.setProperty(Bl,String(t))}},ql=()=>{Ul=-1,Wl=0;for(let e of Gl())e.style.removeProperty(Bl)};function Jl(){if(Hl!==null)return;if(typeof requestAnimationFrame!=`function`){Kl(m?Q.getVoiceLevel()??Vl:Vl);return}let e=()=>{Hl=requestAnimationFrame(e);let t=m?Q.getVoiceLevel():null;t===null?Kl(Vl):(Wl+=(t-Wl)*.3,Kl(Wl))};Hl=requestAnimationFrame(e)}function Yl(){Hl!==null&&(cancelAnimationFrame(Hl),Hl=null),ql()}let Zl=()=>typeof window>`u`?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,$l=(e=`user`)=>{if(Fl||Q.isStreaming())return;let t=Zl();if(!t)return;Pl=new t;let n=r.voiceRecognition??{},i=n.pauseDuration??2e3;Pl.continuous=n.provider?.browser?.continuous??!0,Pl.interimResults=!0,Pl.lang=n.provider?.browser?.language??`en-US`;let a=B.value;Pl.onresult=e=>{let t=``,n=``;for(let r=0;r<e.results.length;r++){let i=e.results[r],a=i[0].transcript;i.isFinal?t+=a+` `:n=a}let r=a+t+n;B.value=r,pn(),Il&&clearTimeout(Il),(t||n)&&(Il=window.setTimeout(()=>{if(B.value.trim()&&Pl&&Fl){if(eu(),Rl())return;pl({viaVoice:!0})}},i))},Pl.onerror=e=>{e.error!==`no-speech`&&eu()},Pl.onend=()=>{if(Fl){let e=B.value.trim();!Rl()&&e&&e!==a.trim()&&pl({viaVoice:!0}),eu()}};try{if(Pl.start(),Fl=!0,$.active=!0,e!==`system`&&($.manuallyDeactivated=!1),Oa(e),ka(),lr(),U){let e=r.voiceRecognition??{};Ll={backgroundColor:U.style.backgroundColor,color:U.style.color,borderColor:U.style.borderColor,iconName:e.iconName??`mic`,iconSize:parseFloat(e.iconSize??``)||24};let t=e.recordingBackgroundColor,n=e.recordingIconColor,i=e.recordingBorderColor;if(U.classList.add(`persona-voice-recording`),zl(`recording`),U.style.backgroundColor=t??`var(--persona-voice-recording-bg, #ef4444)`,U.style.color=n??`var(--persona-voice-recording-indicator, #ffffff)`,n){let e=U.querySelector(`svg`);e&&e.setAttribute(`stroke`,n)}i&&(U.style.borderColor=i),U.setAttribute(`aria-label`,`Stop voice recognition`)}}catch{eu(`system`)}},eu=(e=`user`)=>{if(Fl){if(Fl=!1,Il&&=(clearTimeout(Il),null),Pl){try{Pl.stop()}catch{}Pl=null}if($.active=!1,Oa(e),ka(),lr(),U){if(U.classList.remove(`persona-voice-recording`),zl(`idle`),Ll){U.style.backgroundColor=Ll.backgroundColor,U.style.color=Ll.color,U.style.borderColor=Ll.borderColor;let e=U.querySelector(`svg`);e&&e.setAttribute(`stroke`,Ll.color||`currentColor`),Ll=null}U.setAttribute(`aria-label`,`Start voice recognition`)}}},tu=null,nu=e=>{let t=t=>{tu??=t.createMicStateStyles({mic:()=>U,config:()=>r,session:()=>Q,get original(){return Ll},set original(e){Ll=e},setMicState:zl,renderIcon:K,iconFallbackPx:24}),e(tu)},n=Uu();n?t(n):Hu().then(t,()=>{})},ru=()=>nu(e=>e.recording()),iu=()=>nu(e=>e.processing()),au=()=>nu(e=>e.speaking()),ou=()=>nu(e=>e.reset()),su=()=>{if(!$o()){if(Cl(r.voiceRecognition?.provider)){let e=Q.getVoiceStatus(),t=Q.getVoiceInterruptionMode();if(t===`none`&&(e===`processing`||e===`speaking`))return;if(t===`cancel`&&(e===`processing`||e===`speaking`)){Q.stopVoicePlayback();return}if(Q.isBargeInActive()){Q.stopVoicePlayback(),Q.deactivateBargeIn().then(()=>{$.active=!1,$.manuallyDeactivated=!0,ka(),Oa(`user`),ou()});return}Q.toggleVoice().then(()=>{$.active=Ta(),$.manuallyDeactivated=!$.active,ka(),Oa(`user`),$.active?ru():ou()})}else if(Fl){let e=B.value.trim();$.manuallyDeactivated=!0,ka(),eu(`user`),e&&!Rl()&&pl()}else $.manuallyDeactivated=!1,ka(),$l(`user`)}};In=su;let cu=()=>Q.prewarmVoice(),lu=()=>{let e=r.voiceRecognition;return e?.enabled===!0?e.prewarm??(r.clientToken?`hover`:!1):!1},uu=e=>{lu()===`hover`&&U?.contains(e.target)&&cu()},du=[`pointerover`,`pointerdown`,`focusin`];du.forEach(t=>e.addEventListener(t,uu));let fu,pu=null,mu,gu=()=>{let e=mu;mu=void 0;try{typeof e==`function`&&e()}catch{}},_u=()=>{let t=lu(),n=typeof t==`function`&&U?t:void 0,r=n?U:null;if((n!==fu||r!==pu)&&(gu(),fu=n,pu=r,n&&r))try{mu=n({warm:cu,micButton:r,mount:e})}catch{}};_u(),Z.push(()=>{du.forEach(t=>e.removeEventListener(t,uu)),gu()}),U&&Z.push(()=>{Cl(r.voiceRecognition?.provider)?(Q.isVoiceActive()&&Q.toggleVoice(),ou()):eu(`system`)});let vu=O.on(`assistant:complete`,()=>{G.getState().pendingSubmission&&setTimeout(()=>{Q.isStreaming()||ll()},0)});Z.push(vu);let yu=O.on(`assistant:complete`,()=>{Ca&&($.active||$.manuallyDeactivated||(Ca!==`assistant`||$.lastUserMessageWasVoice)&&setTimeout(()=>{!$.active&&!$.manuallyDeactivated&&(Cl(r.voiceRecognition?.provider)?Q.toggleVoice().then(()=>{$.active=Q.isVoiceActive(),Oa(`auto`),Q.isVoiceActive()&&ru()}):$l(`auto`))},600))});Z.push(yu);let bu=O.on(`action:resubmit`,()=>{setTimeout(()=>{Q&&!Q.isStreaming()&&Q.continueConversation()},100)});Z.push(bu);let xu=()=>{Xo(!P,`user`)},Su=null,wu=null;if(M&&!N()){let{instance:e,element:t}=Og({config:r,plugins:d,onToggle:xu});Su=e,e||(wu=t)}Su?e.appendChild(Su.element):wu&&e.appendChild(wu),Yo(),Vi(),qs(),Ws(),vs(Q.isStreaming()),ho()||(Nt()===`follow`?oo(!0):lo()),Aa(),he&&(!M||N()?setTimeout(()=>ys(),0):P&&setTimeout(()=>ys(),200));let Tu=null,Eu=()=>{Tu&&(Tu.disconnect(),Tu.observe(bt),Tu.observe(L),Tu.observe(ut))},Du=en(),Ou=()=>{if(N()){on(),Yo();return}let t=Mm(r),n=r.launcher?.sidebarMode??!1,i=e.ownerDocument.defaultView??window,a=r.launcher?.mobileFullscreen??!0,o=r.launcher?.mobileBreakpoint??640,s=i.innerWidth<=o,c=a&&s&&M;try{if(c){Tr(),Er=ai();return}let e=!1;ye&&(ye=!1,Tr(),e=!0);let i=ai();if(!e&&i!==Er&&(Tr(),e=!0),Er=i,e&&Jr(),!M&&!t){I.style.height=``,I.style.width=``;return}if(!n&&!t){let e=ug(r);I.style.width=e.width,I.style.maxWidth=e.maxWidth}ri(),hi()}finally{on(),ln();let t=en();if(t!==Du&&(Du=t,Fs(),Vi()),Yo(),P&&M){let t=(e.ownerDocument.defaultView??window).innerWidth<=(r.launcher?.mobileBreakpoint??640),n=r.launcher?.sidebarMode??!1,i=r.launcher?.mobileFullscreen??!0,a=Mm(r)&&i&&t,o=n||i&&t&&M||a;if(o&&!vi){let t=e.getRootNode(),n=t instanceof ShadowRoot?t.host:e.closest(`.persona-host`);n&&!_i&&(_i=Dm(n,r.launcher?.zIndex??1e5)),vi=Am(e.ownerDocument)}else o||(_i?.(),_i=null,vi?.(),vi=null)}}};Ou();let ku=e.ownerDocument.defaultView??window;if(ku.addEventListener(`resize`,Ou),Z.push(()=>ku.removeEventListener(`resize`,Ou)),typeof ResizeObserver<`u`){Tu=new ResizeObserver(()=>{ln()}),Eu(),Z.push(()=>{Tu?.disconnect(),Tu=null});let e=new ResizeObserver(()=>{zc()});e.observe(L),Z.push(()=>e.disconnect())}ku.addEventListener(`resize`,zc),Z.push(()=>ku.removeEventListener(`resize`,zc)),ta=R.scrollTop;let Au=Gp(R),ju=()=>{pi();let e=R.scrollTop,t=Gp(R),n=t<Au;if(Au=t,!Pt()){ta=e,ro();return}let{action:r,nextLastScrollTop:i}=qp({following:ea.isFollowing(),currentScrollTop:e,lastScrollTop:ta,nearBottom:Kp(R,24),userScrollThreshold:4,isAutoScrolling:ra||ia||n,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});ta=i,r===`resume`?mo()||ao():r===`pause`&&io()};if(R.addEventListener(`scroll`,ju,{passive:!0}),Z.push(()=>R.removeEventListener(`scroll`,ju)),typeof ResizeObserver<`u`){let e=new ResizeObserver(()=>{To(),Ql(z)});e.observe(z),e.observe(R),Z.push(()=>e.disconnect())}let Fu=()=>{Pt()&&ea.isFollowing()&&mo()&&io()},Iu=R.ownerDocument;Iu.addEventListener(`selectionchange`,Fu),Z.push(()=>{Iu.removeEventListener(`selectionchange`,Fu)});let Lu=/* @__PURE__ */ new Set([`PageUp`,`PageDown`,`Home`,`End`,`ArrowUp`,`ArrowDown`]),Ru=e=>{Lu.has(e.key)&&(ha(),Lt()&&Pt()&&ea.isFollowing()&&io())},zu=e=>{e.target?.closest(`a, button, [tabindex], input, textarea, select`)&&(ha(),Lt()&&Pt()&&ea.isFollowing()&&io())};R.addEventListener(`keydown`,Ru),R.addEventListener(`focusin`,zu),Z.push(()=>{R.removeEventListener(`keydown`,Ru),R.removeEventListener(`focusin`,zu)});let Bu=e=>{if(e.deltaY!==0&&ha(),!Pt())return;let t=Jp({following:ea.isFollowing(),deltaY:e.deltaY,nearBottom:Kp(R,24),resumeWhenNearBottom:!0});t===`pause`?io():t===`resume`&&!mo()&&ao()};R.addEventListener(`wheel`,Bu,{passive:!0}),R.addEventListener(`touchmove`,ha,{passive:!0}),R.addEventListener(`pointerdown`,ha,{passive:!0}),Z.push(()=>{R.removeEventListener(`touchmove`,ha),R.removeEventListener(`pointerdown`,ha)}),Z.push(()=>R.removeEventListener(`wheel`,Bu)),Vt.addEventListener(`click`,()=>{yo(),R.scrollTop=R.scrollHeight,ta=R.scrollTop,ao(),oo(!0),ro()}),Z.push(()=>Vt.remove()),Z.push(()=>{Xa(),yo()});let Vu=()=>{H&&(Oi&&=(H.removeEventListener(`click`,Oi),null),be()?(H.style.display=``,Oi=()=>{Xo(!1,`user`)},H.addEventListener(`click`,Oi)):H.style.display=`none`)};Vu(),(()=>{let{clearChatButton:e}=it;e&&e.addEventListener(`click`,()=>{let e=Sc;if(e?.historyAvailable()){e.startNewConversation({focusComposer:!0}).catch(e=>{r.debug&&console.warn(`[AgentWidget] New conversation failed:`,e)});return}Q.clearMessages(),r.layout?.topFade&&(R.scrollTop=0),R.removeAttribute(`data-persona-top-fade`),Gi.clear(),ao(),Zr(it.composerOverlay);try{localStorage.removeItem(Vv),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Vv}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Vv)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let t=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(t),k?.clear&&Fa(()=>k.clear(),`[AgentWidget] Failed to clear storage adapter:`),A={},pe.syncFromMetadata(),dn?.clearAttachments(),Ua(),Nn(void 0),On(void 0),Zi(),Pe?.clear(),Fe?.reset(),Re?.update()})})();let Wu=[[`keydown`,Al],[`input`,Ol],[`input`,pn],[`input`,mn],[`keyup`,mn],[`paste`,Nl],[`focus`,J]],Gu=e=>{if(e)for(let[t,n]of Wu)Jn?.addListener(e,t,n)},Ku=e=>{if(e)for(let[t,n]of Wu)Jn?.removeListener(e,t,n)},qu=()=>{Jn&&(Jn.addListener(Jn.form,`submit`,gl),Jn.addListener(Jn.footer,`click`,mn),Gu(B),U&&Jn.addListener(U,`click`,su),_u())};qu();let Ju=()=>{fn?.onComposerSwap((e,t)=>{Ku(t),B=e,Jn&&(Jn.input=e),Gu(e),Xn(),gs(),pn()})};Ju();let Yu=!1;function Xu(){if(!Yu){Yu=!0;try{let e=B?.value??``,t=bt.ownerDocument??document,n=B?t.activeElement===B:!1;Yl(),Jn?.destroy(),Jn=null,fn?.destroy(),fn=null;let i=null,a=()=>(i=N()?mh({config:r}):fh({config:r}),i.footer),o=Kn(a)??a();nt.replaceComposer(o),bt=nt.composer.footer;let s=i!==null&&o===i.footer;Gn=!s,Tt=s?i.setSendButtonMode:()=>{},Wn(bt),Zn(bt),$n(),er(),tr(),Ju(),ir(),ar(),or(),qu();let c=Di.indexOf(wi);if(wi.destroy(),wi=Vm(st),c>=0&&(Di[c]=wi),B&&(B.value=e),pn(),mn(),qs(),Vi(),vs(Q.isStreaming()),r.statusIndicator?.mode===`transient`&&!N()){let e=Q.getStatus();tt(lt,et(e),r.statusIndicator,e)}$.active&&zl(`recording`),Tr(),Eu(),on(),lr(),ps(),n&&B?.focus()}finally{Yu=!1}}}let Zu=e.ownerDocument??document;Zu.addEventListener(`keydown`,Ml,!0);let Qu=()=>{Va()},$u=()=>{Zu.visibilityState===`hidden`&&Va()};typeof window<`u`&&(window.addEventListener(`pagehide`,Qu),Zu.addEventListener(`visibilitychange`,$u),Z.push(()=>{window.removeEventListener(`pagehide`,Qu),Zu.removeEventListener(`visibilitychange`,$u)}));let ed=`persona-attachment-drop-active`,td=0,nd=()=>{td=0,L.classList.remove(ed)},rd=()=>r.attachments?.enabled===!0&&dn!==null&&!$o(),id=e=>{Kv(e.dataTransfer)&&rd()&&(td++,td===1&&L.classList.add(ed))},ad=e=>{Kv(e.dataTransfer)&&rd()&&(td--,td<=0&&nd())},od=e=>{Kv(e.dataTransfer)&&rd()&&(e.preventDefault(),e.dataTransfer.dropEffect=`copy`)},sd=e=>{if(!Kv(e.dataTransfer)||!rd())return;e.preventDefault(),e.stopPropagation(),nd();let t=Array.from(e.dataTransfer.files??[]);t.length!==0&&dn.handleFiles(t)};L.addEventListener(`dragenter`,id,!0),L.addEventListener(`dragleave`,ad,!0),e.addEventListener(`dragover`,od,!0),e.addEventListener(`drop`,sd,!0);let cd=e.ownerDocument,ld=e=>{rd()&&e.preventDefault()},ud=e=>{rd()&&e.preventDefault()};cd.addEventListener(`dragover`,ld),cd.addEventListener(`drop`,ud),Z.push(()=>{Jn?.destroy(),Jn=null,Yl(),Y?.destroy(),Y=null,Tn?.destroy(),Tn=null,Dn?.destroy(),Dn=null,Mn?.destroy(),Mn=null,Cn=null,wn=null,Va(),za.destroy(),el&&clearTimeout(el),Zi(),Qc?.abort(),Qc=null,dn?.destroy(),dn=null,G.destroy(),Zu.removeEventListener(`keydown`,Ml,!0),fn?.destroy()}),Z.push(()=>{L.removeEventListener(`dragenter`,id,!0),L.removeEventListener(`dragleave`,ad,!0),e.removeEventListener(`dragover`,od,!0),e.removeEventListener(`drop`,sd,!0),cd.removeEventListener(`dragover`,ld),cd.removeEventListener(`drop`,ud),nd()}),Z.push(()=>{Q.cancel()}),Su?Z.push(()=>{Su?.destroy()}):wu&&Z.push(()=>{wu?.remove()});let dd={update(t){let n=r.future?.v5Defaults===!0,a=r.toolCall,o=r.messageActions,s=r.layout?.messages,c=r.colorScheme,f=r.loadingIndicator,p=r.iterationDisplay,m=r.features?.showReasoning,h=r.features?.showToolCalls,g=r.features?.toolCallDisplay,_=r.features?.reasoningDisplay,v=r.features?.streamAnimation?.type,y=r.features?.history?.enabled===!0,b=r.features?.history?.provider,x=r.getIdentityProof,S=r.clientToken,C=r.contextMentions;r=cv({...r,features:u},t),u=r.features,r=G_(r),l(),li(),Op(e,r),b_(e,r),x_(e,r),Je(),si(),r.colorScheme!==c&&bi();let w=iv.getForInstance(r.plugins);d.length=0,d.push(...w),Oc(),M=r.launcher?.enabled??!0,me=r.launcher?.autoExpand??!1,Te=r.features?.showReasoning??!0,Ee=r.features?.showToolCalls??!0,Oe=r.features?.scrollToBottom??{};let T=Nt();ke=r.features?.scrollBehavior??{},T!==Nt()&&(yo(),ao()),va(),un(),ro();let E=De;if(De=r.features?.showEventStreamToggle??!1,De&&!E){if(Pe||(We(),Q.setSSEEventCallback((e,t)=>{r.onSSEEvent?.(e,t),Ue(e,t)})),!Un&&yt){let e=r.features?.eventStream?.classNames,t=`persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1`+(e?.toggleButton?` `+e.toggleButton:``);Un=q(`button`,t),Un.style.width=`28px`,Un.style.height=`28px`,Un.style.color=Ym.actionIconColor,Un.type=`button`,Un.setAttribute(`aria-label`,`Event Stream`),Un.title=`Event Stream`;let n=Jt(i,`18px`,`currentColor`,1.5);n&&Un.appendChild(n);let a=it.clearChatButtonWrapper,o=it.closeButtonWrapper,s=a||o;s&&s.parentNode===yt?yt.insertBefore(Un,s):yt.appendChild(Un),Un.addEventListener(`click`,()=>{ze?Hn():Bn()})}}else!De&&E&&(Hn(),Un&&=(Un.remove(),null),Pe?.clear(),Me?.destroy(),Pe=null,Me=null,Fe?.reset(),Fe=null,Ie=null);if(r.launcher?.enabled===!1&&Su&&(Su.destroy(),Su=null),r.launcher?.enabled===!1&&wu&&(wu.remove(),wu=null),r.launcher?.enabled!==!1&&!Su&&!wu){let{instance:t,element:n}=Og({config:r,plugins:d,onToggle:xu});Su=t,t||(wu=n),e.appendChild(n)}Su&&Su.update(r),jc(),vt&&r.launcher?.subtitle!==void 0&&(vt.textContent=r.launcher.subtitle);let D=r.layout?.header;if(D?.layout!==ve&&yt){let e=D?dh(r,D,{showClose:be(),onClose:()=>Xo(!1,`user`)}):Qm({config:r,showClose:be(),onClose:()=>Xo(!1,`user`)});nt.replaceHeader(e),yt=nt.header.element,gt=nt.header.iconHolder,_t=nt.header.headerTitle,vt=nt.header.headerSubtitle,H=nt.header.closeButton,ve=D?.layout,jc()}else if(D){if(gt&&(gt.style.display=D.showIcon===!1?`none`:``),_t&&(_t.style.display=D.showTitle===!1?`none`:``),vt&&(vt.style.display=D.showSubtitle===!1?`none`:``),H){let e=be()&&D.showCloseButton!==!1;H.style.display=e?``:`none`}if(it.clearChatButtonWrapper){let e=D.showClearChat;if(e!==void 0){it.clearChatButtonWrapper.style.display=e?``:`none`;let{closeButtonWrapper:t}=it;t&&!t.classList.contains(`persona-absolute`)&&(e?t.classList.remove(`persona-ml-auto`):t.classList.add(`persona-ml-auto`))}}}let k=r.layout?.showHeader!==!1;yt&&(yt.style.display=k?``:`none`);let ee=r.layout?.showFooter!==!1;bt&&(bt.style.display=ee?``:`none`),on(),ro(),M===_e?me!==ge&&Xo(me,`auto`):M?Xo(me,`auto`):(P=!0,Yo()),ge=me,_e=M,Ou(),Vu();let A=JSON.stringify(r.toolCall)!==JSON.stringify(a),te=JSON.stringify(r.messageActions)!==JSON.stringify(o),ne=JSON.stringify(r.layout?.messages)!==JSON.stringify(s),re=r.loadingIndicator?.render!==f?.render||r.loadingIndicator?.renderIdle!==f?.renderIdle||r.loadingIndicator?.showBubble!==f?.showBubble,ie=r.iterationDisplay!==p,ae=(r.features?.showReasoning??!0)!==(m??!0)||(r.features?.showToolCalls??!0)!==(h??!0)||JSON.stringify(r.features?.toolCallDisplay)!==JSON.stringify(g)||JSON.stringify(r.features?.reasoningDisplay)!==JSON.stringify(_);(r.future?.v5Defaults===!0!==n||A||te||ne||re||ie||ae)&&Q&&(Qi++,Io(z,Q.getMessages(),we));let oe=r.features?.streamAnimation?.type;if(oe!==v&&oe&&oe!==`none`){let t=Si(oe,r.features?.streamAnimation?.plugins);t&&Cm(t,e)}let j=r.launcher??{},se=j.headerIconHidden??!1,ce=r.layout?.header?.showIcon,de=se||ce===!1,fe=j.headerIconName,he=j.headerIconSize??`40px`;if(gt){let e=yt,t=e?.querySelector(`.persona-flex-col`);if(de)gt.style.display=`none`,e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(gt.style.display=``,gt.style.height=he,gt.style.width=he,e&&t&&(e.contains(gt)?gt.nextSibling!==t&&(gt.remove(),e.insertBefore(gt,t)):e.insertBefore(gt,t)),fe){let e=parseFloat(he)||24,t=K(fe,e*.6,`currentColor`,1);t?(t.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,t.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,gt.replaceChildren(t)):gt.textContent=j.agentIconText??`💬`}else if(j.iconUrl){let e=gt.querySelector(`img`);if(e)e.src=j.iconUrl,e.style.height=he,e.style.width=he;else{let e=document.createElement(`img`);e.src=j.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=he,e.style.width=he,gt.replaceChildren(e)}}else{let e=gt.querySelector(`svg`),t=gt.querySelector(`img`);(e||t)&>.replaceChildren(),gt.textContent=j.agentIconText??`💬`}let n=gt.querySelector(`img`);n&&(n.style.height=he,n.style.width=he)}}let ye=r.layout?.header?.showTitle,xe=r.layout?.header?.showSubtitle;if(_t&&(_t.style.display=ye===!1?`none`:``),vt&&(vt.style.display=xe===!1?`none`:``),H){let e=be()&&r.layout?.header?.showCloseButton!==!1;if(H.style.display=e?``:`none`,!N()){let e=j.closeButtonSize??``;H.style.height=e,H.style.width=e,H.style.minWidth=e,H.style.minHeight=e}let t=j.closeButtonPlacement??`inline`,{closeButtonWrapper:n}=it,i=t===`top-right`,a=n?.classList.contains(`persona-absolute`);if(n&&i!==a){if(n.remove(),i){n.className=`persona-absolute persona-top-4 persona-right-4 persona-z-50`;let e=Sc?.railColumn??L;e.style.position=`relative`,e.appendChild(n)}else{let e=j.clearChat?.placement??`inline`;n.className=(j.clearChat?.enabled??!0)&&e===`inline`?``:`persona-ml-auto`,yt&&yt.appendChild(n)}}if(H.style.color=j.closeButtonColor||Ym.actionIconColor,j.closeButtonBackgroundColor?(H.style.backgroundColor=j.closeButtonBackgroundColor,H.classList.remove(`hover:persona-bg-gray-100`)):(H.style.backgroundColor=``,H.classList.add(`hover:persona-bg-gray-100`)),j.closeButtonBorderWidth||j.closeButtonBorderColor){let e=j.closeButtonBorderWidth||`0px`,t=j.closeButtonBorderColor||`transparent`;H.style.border=`${e} solid ${t}`,H.classList.remove(`persona-border-none`)}else H.style.border=``,H.classList.add(`persona-border-none`);j.closeButtonBorderRadius?(H.style.borderRadius=j.closeButtonBorderRadius,H.classList.remove(`persona-rounded-full`)):(H.style.borderRadius=``,H.classList.add(`persona-rounded-full`)),j.closeButtonPaddingX?(H.style.paddingLeft=j.closeButtonPaddingX,H.style.paddingRight=j.closeButtonPaddingX):(H.style.paddingLeft=``,H.style.paddingRight=``),j.closeButtonPaddingY?(H.style.paddingTop=j.closeButtonPaddingY,H.style.paddingBottom=j.closeButtonPaddingY):(H.style.paddingTop=``,H.style.paddingBottom=``),Gm(H,j.closeButtonIconName??`x`,{iconSize:N()?fg:void 0,iconText:j.closeButtonIconText??`×`});let o=j.closeButtonTooltipText??`Close chat`,s=j.closeButtonShowTooltip??!0;H.setAttribute(`aria-label`,o),n&&Ea({anchor:H,trigger:n,text:()=>H?.getAttribute(`aria-label`)??o,enabled:s})}let{clearChatButton:Se,clearChatButtonWrapper:Ae}=it;if(Se){let e=j.clearChat??{},t=e.enabled??!0,n=r.layout?.header?.showClearChat,i=n===void 0?t:n,a=e.placement??`inline`;if(Ae){Ae.style.display=i?``:`none`;let{closeButtonWrapper:e}=it;!N()&&e&&!e.classList.contains(`persona-absolute`)&&(i?e.classList.remove(`persona-ml-auto`):e.classList.add(`persona-ml-auto`));let t=a===`top-right`,n=Ae.classList.contains(`persona-absolute`);if(!N()&&t!==n&&i){if(Ae.remove(),t){Ae.className=`persona-absolute persona-top-4 persona-z-50`,Ae.style.right=`48px`;let e=Sc?.railColumn??L;e.style.position=`relative`,e.appendChild(Ae)}else{Ae.className=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,Ae.style.right=``;let e=it.closeButtonWrapper;yt&&e&&e.parentElement===yt?yt.insertBefore(Ae,e):yt&&yt.appendChild(Ae)}let e=it.closeButtonWrapper;e&&!e.classList.contains(`persona-absolute`)&&(t?e.classList.add(`persona-ml-auto`):e.classList.remove(`persona-ml-auto`))}}if(i){if(!N()){let t=e.size??``;Se.style.height=t,Se.style.width=t,Se.style.minWidth=t,Se.style.minHeight=t}let t=e.iconColor??``;if(Se.style.color=t||Ym.actionIconColor,Gm(Se,e.iconName??`refresh-cw`,{iconSize:N()?pg:void 0}),e.backgroundColor?(Se.style.backgroundColor=e.backgroundColor,Se.classList.remove(`hover:persona-bg-gray-100`)):(Se.style.backgroundColor=``,Se.classList.add(`hover:persona-bg-gray-100`)),e.borderWidth||e.borderColor){let t=e.borderWidth||`0px`,n=e.borderColor||`transparent`;Se.style.border=`${t} solid ${n}`,Se.classList.remove(`persona-border-none`)}else Se.style.border=``,Se.classList.add(`persona-border-none`);e.borderRadius?(Se.style.borderRadius=e.borderRadius,Se.classList.remove(`persona-rounded-full`)):(Se.style.borderRadius=``,Se.classList.add(`persona-rounded-full`)),e.paddingX?(Se.style.paddingLeft=e.paddingX,Se.style.paddingRight=e.paddingX):(Se.style.paddingLeft=``,Se.style.paddingRight=``),e.paddingY?(Se.style.paddingTop=e.paddingY,Se.style.paddingBottom=e.paddingY):(Se.style.paddingTop=``,Se.style.paddingBottom=``);let n=e.tooltipText??`Clear chat`,r=e.showTooltip??!0;Se.setAttribute(`aria-label`,n),Ae&&Ea({anchor:Se,trigger:Ae,text:()=>Se?.getAttribute(`aria-label`)??n,enabled:r})}}let je=r.actionParsers&&r.actionParsers.length?r.actionParsers:[fv],Ne=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[mv.message,mv.messageAndClick];pe=gv({parsers:je,handlers:Ne,getSessionMetadata:le,updateSessionMetadata:ue,emit:O.emit,documentRef:typeof document<`u`?document:null}),we=Zv(r,pe,Ce),ic(),Q.updateConfig(r),Kc(),(r.features?.history?.enabled===!0!==y||r.features?.history?.provider!==b||r.getIdentityProof!==x||r.clientToken!==S)&&(Sc?.closeHistory({restoreFocus:!1}),Sc?.installHistoryProvider()),Sc?.syncHistoryChromeImpl(),zc(),Ec()&&!Sc&&Lc().catch(()=>{}),Io(z,Q.getMessages(),we),Vi(),qs(),Ks(),vs(Q.isStreaming()),C!==r.contextMentions&&Xu();let Le=r.voiceRecognition?.enabled===!0,Re=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),Be=Cl(r.voiceRecognition?.provider);if(Le&&(Re||Be)){if(!U||!Et){let e=_s(r);if(e){U=e.button,Et=e.wrapper;let t=wt&&wt.parentElement===Ct?wt:null;Ct?Ct.insertBefore(Et,t):ct?.appendChild(Et),Jn&&(Jn.micButton=U),Jn?.addListener(U,`click`,su),U.disabled=$o()||Q.isStreaming()&&!es()}}else{let e=r.voiceRecognition??{},t=r.sendButton??{},n=e.iconName??`mic`,i=e.iconSize,a=parseFloat(i??``)||24;U.classList.add(ds),U.classList.toggle(fs,!i),U.style.width=i??``,U.style.height=i??``,U.style.minWidth=i??``,U.style.minHeight=i??``;let o=e.iconColor??t.textColor;U.innerHTML=``;let s=K(n,a,o||`currentColor`,1.5);s?U.appendChild(s):U.textContent=`🎤`;let c=e.backgroundColor??t.backgroundColor;c?U.style.backgroundColor=c:U.style.backgroundColor=``,o?U.style.color=o:U.style.color=`var(--persona-text, #111827)`,e.borderWidth?(U.style.borderWidth=e.borderWidth,U.style.borderStyle=`solid`):(U.style.borderWidth=``,U.style.borderStyle=``),e.borderColor?U.style.borderColor=e.borderColor:U.style.borderColor=``,e.paddingX?(U.style.paddingLeft=e.paddingX,U.style.paddingRight=e.paddingX):(U.style.paddingLeft=``,U.style.paddingRight=``),e.paddingY?(U.style.paddingTop=e.paddingY,U.style.paddingBottom=e.paddingY):(U.style.paddingTop=``,U.style.paddingBottom=``);let l=e.tooltipText??`Start voice recognition`,u=e.showTooltip??!1;U.setAttribute(`aria-label`,l),Et&&Ea({anchor:U,trigger:Et,text:()=>U?.getAttribute(`aria-label`)??l,enabled:u}),Et.style.display=``,U.disabled=$o()||Q.isStreaming()&&!es()}}else U&&Et&&(Et.style.display=`none`,Cl(r.voiceRecognition?.provider)?Q.isVoiceActive()&&Q.toggleVoice():Fl&&eu());if(_u(),r.attachments?.enabled===!0){if(!Ot||!Dt){let e=r.attachments??{};At||(At=q(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),At.style.display=`none`,(B.parentElement??ct).insertBefore(At,B)),kt||(kt=document.createElement(`input`),kt.type=`file`,kt.accept=(e.allowedTypes??Qo).join(`,`),kt.multiple=(e.maxFiles??4)>1,kt.style.display=`none`,kt.setAttribute(`aria-label`,`Attach files`),(B.parentElement??ct).insertBefore(kt,B)),Ot=q(`div`,`persona-send-button-wrapper`),Dt=q(`button`,`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${ds} ${fs}`),Dt.type=`button`,Dt.setAttribute(`aria-label`,e.buttonTooltipText??`Attach file`);let t=e.buttonIconName??`paperclip`;Dt.style.fontSize=`18px`,Dt.style.lineHeight=`1`;let n=K(t,24,`currentColor`,1.5);n?Dt.appendChild(n):Dt.textContent=`📎`,Dt.addEventListener(`click`,e=>{e.preventDefault(),kt?.click()}),Ot.appendChild(Dt);let i=e.buttonTooltipText??`Attach file`;Ea({anchor:Dt,trigger:Ot,text:()=>Dt?.getAttribute(`aria-label`)??i}),St?St.append(Ot):ct.appendChild(Ot),Jn&&(Jn.attachmentButton=Dt,Jn.attachmentInput=kt??void 0,Jn.attachmentPreviews=At??void 0),!dn&&kt&&At&&(dn=vd.fromConfig(e,gn),dn.setPreviewsContainer(At),Jn?.addListener(kt,`change`,async()=>{dn&&kt?.files&&(await dn.handleFileSelect(kt.files),kt.value=``)}))}else{Ot.style.display=``;let e=r.attachments??{};kt&&(kt.accept=(e.allowedTypes??Qo).join(`,`),kt.multiple=(e.maxFiles??4)>1),dn&&dn.updateConfig({allowedTypes:e.allowedTypes,maxFileSize:e.maxFileSize,maxFiles:e.maxFiles,adapter:e.adapter})}if(L.querySelector(`.persona-attachment-drop-overlay`)?.remove(),L.appendChild(Qv(r.attachments?.dropOverlay)),Dt){let e=r.attachments??{},t=e.buttonTooltipText??`Attach file`;Dt.setAttribute(`aria-label`,t),Dt.textContent=``;let n=K(e.buttonIconName??`paperclip`,24,`currentColor`,1.5);n?Dt.appendChild(n):Dt.textContent=`📎`,Ot&&Ea({anchor:Dt,trigger:Ot,text:()=>Dt?.getAttribute(`aria-label`)??t})}}else Ot&&(Ot.style.display=`none`),dn&&dn.clearAttachments(),L.querySelector(`.persona-attachment-drop-overlay`)?.remove();let Ve=r.sendButton??{},He=Ve.useIcon??!1,Ge=Ve.iconText??`↑`,Ke=Ve.iconName,Ye=Ve.tooltipText??`Send message`,Xe=Ve.showTooltip??!1,Ze=Ve.size,Qe=parseFloat(Ze??``)||40,$e=Ve.backgroundColor,et=Ve.textColor;if(He){if(V.style.width=Ze??``,V.style.height=Ze??``,V.style.minWidth=Ze??``,V.style.minHeight=Ze??``,V.style.fontSize=`18px`,V.style.lineHeight=`1`,et?V.style.color=et:V.style.color=`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`,!Q.isStreaming()){if(V.innerHTML=``,Ke){let e=parseFloat(Ve.iconSize??``)||Math.round(Qe*.5),t=et?.trim()||`currentColor`,n=Ve.iconStrokeWidth??2,r=K(Ke,e,t,n),i=K(Ve.stopIconName??`square`,e,t,n);r&&i?V.appendChild(hs(r,i)):r?V.appendChild(r):V.textContent=Ge}else V.textContent=Ge}V.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${ds}`,$e?(V.style.backgroundColor=$e,V.classList.remove(`persona-bg-persona-primary`)):(V.style.backgroundColor=``,V.classList.add(`persona-bg-persona-primary`))}else V.textContent=r.copy?.sendButtonLabel??`Send`,V.style.width=``,V.style.height=``,V.style.minWidth=``,V.style.minHeight=``,V.style.fontSize=``,V.style.lineHeight=``,V.className=`persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer`,$e?(V.style.backgroundColor=$e,V.classList.remove(`persona-bg-persona-accent`)):V.classList.add(`persona-bg-persona-accent`),et?V.style.color=et:V.classList.add(`persona-text-white`);Ve.borderWidth?(V.style.borderWidth=Ve.borderWidth,V.style.borderStyle=`solid`):(V.style.borderWidth=``,V.style.borderStyle=``),Ve.borderColor?V.style.borderColor=Ve.borderColor:V.style.borderColor=``,Ve.paddingX?(V.style.paddingLeft=Ve.paddingX,V.style.paddingRight=Ve.paddingX):(V.style.paddingLeft=``,V.style.paddingRight=``),Ve.paddingY?(V.style.paddingTop=Ve.paddingY,V.style.paddingBottom=Ve.paddingY):(V.style.paddingTop=``,V.style.paddingBottom=``),Q.isStreaming()||V.setAttribute(`aria-label`,Ye),ps(),wt&&Ea({anchor:V,trigger:wt,text:()=>V.getAttribute(`aria-label`)??Ye,enabled:Xe}),ur(),mi();let F=mf(G.getState().activeModeIds,r.composer?.modes);G.setActiveModeIds(F),vn().length>0!=!!Tn&&ar(),Tn?.render(F,vn());for(let e of[...En.keys()])lf(e,r.composer?.modeGroups)||En.delete(e);En.forEach(e=>e.repaint()),Cn?.repaint(),Y?.resolve();let I=Ap(r,N());if(ui(),I){z.style.maxWidth=I,z.style.marginLeft=`auto`,z.style.marginRight=`auto`,z.style.width=`100%`,ft.style.maxWidth=I,ft.style.marginLeft=`auto`,ft.style.marginRight=`auto`,ft.style.width=`100%`;for(let e of[ct,st,At,lt])e&&(e.style.maxWidth=I,e.style.marginLeft=`auto`,e.style.marginRight=`auto`,e.style.width=`100%`)}else{z.style.maxWidth=``,z.style.marginLeft=``,z.style.marginRight=``,z.style.width=``,ft.style.maxWidth=``,ft.style.marginLeft=``,ft.style.marginRight=``,ft.style.width=``;for(let e of[ct,st,At,lt])e&&(e.style.maxWidth=``,e.style.marginLeft=``,e.style.marginRight=``,e.style.width=``)}let rt=r.statusIndicator??{};if(Ka(lt,ct,rt),Ga(lt,rt,Q?.getStatus()??`idle`),Q){let e=Q.getStatus();tt(lt,(e=>e===`idle`?rt.idleText??gi.idle:e===`connecting`?rt.connectingText??gi.connecting:e===`connected`?rt.connectedText??gi.connected:e===`error`?rt.errorText??gi.error:e===`paused`?rt.pausedText??gi.paused:e===`resuming`?rt.resumingText??gi.resuming:gi[e])(e),rt,e)}lt.classList.remove(`persona-text-left`,`persona-text-center`,`persona-text-right`);let R=rt.align===`left`?`persona-text-left`:rt.align===`center`?`persona-text-center`:`persona-text-right`;lt.classList.add(R),Xn(),gs(),lr(),qe()},open(){be()&&Xo(!0,`api`)},close(){be()&&Xo(!1,`api`)},toggle(){be()&&Xo(!P,`api`)},reconnect(){Q.reconnectNow()},clearChat(){kr=!1,s.clear(),a.clear(),o.clear(),c.clear(),Q.clearMessages(),r.layout?.topFade&&(R.scrollTop=0),R.removeAttribute(`data-persona-top-fade`),Gi.clear(),ao();try{localStorage.removeItem(Vv),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Vv}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Vv)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let e=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(e),k?.clear&&Fa(()=>k.clear(),`[AgentWidget] Failed to clear storage adapter:`),A={},pe.syncFromMetadata(),dn?.clearAttachments(),Ua(),Nn(void 0),On(void 0),Zi(),Pe?.clear(),Fe?.reset(),Re?.update()},setMessage(e){return!B||Q.isStreaming()||$o()?!1:(!P&&be()&&Xo(!0,`system`),B.value=e,B.dispatchEvent(new Event(`input`,{bubbles:!0})),!0)},submitMessage(e){if(Q.isStreaming()||is())return!1;let t=e?.trim()||B.value.trim();return t?(!P&&be()&&Xo(!0,`system`),B.value=``,B.style.height=`auto`,pn(),hl(t,{consumeDraft:!1}),!0):!1},getComposerState(){return G.getState()},setQuote(e){let t=e?.text?.trim();t&&On({...e,text:t})},clearQuote(){On(void 0)},startVoiceRecognition(){return Q.isStreaming()?!1:Cl(r.voiceRecognition?.provider)?(Q.isVoiceActive()||Q.isBargeInActive()||(!P&&be()&&Xo(!0,`system`),$.manuallyDeactivated=!1,ka(),Q.toggleVoice().then(()=>{$.active=Ta(),ka(),Oa(`user`),$.active&&ru()})),!0):Fl?!0:Zl()?(!P&&be()&&Xo(!0,`system`),$.manuallyDeactivated=!1,ka(),$l(`user`),!0):!1},stopVoiceRecognition(){return Cl(r.voiceRecognition?.provider)?!Q.isVoiceActive()&&!Q.isBargeInActive()?!1:((Q.isBargeInActive()?Q.deactivateBargeIn():Q.toggleVoice()).then(()=>{$.active=!1,$.manuallyDeactivated=!0,ka(),Oa(`user`),ou()}),!0):Fl?($.manuallyDeactivated=!0,ka(),eu(`user`),!0):!1},injectMessage(e){return!P&&be()&&Xo(!0,`system`),Q.injectMessage(e)},injectAssistantMessage(e){!P&&be()&&Xo(!0,`system`);let t=Q.injectAssistantMessage(e);return xe&&(xe=!1,Se&&=(clearTimeout(Se),null),setTimeout(()=>{Q&&!Q.isStreaming()&&Q.continueConversation()},100)),t},injectUserMessage(e){return!P&&be()&&Xo(!0,`system`),Q.injectUserMessage(e)},injectSystemMessage(e){return!P&&be()&&Xo(!0,`system`),Q.injectSystemMessage(e)},injectMessageBatch(e){return!P&&be()&&Xo(!0,`system`),Q.injectMessageBatch(e)},injectComponentDirective(e){return!P&&be()&&Xo(!0,`system`),Q.injectComponentDirective(e)},injectTestMessage(e){!P&&be()&&Xo(!0,`system`),Q.injectTestEvent(e)},async connectStream(e,t){return Q.connectStream(e,t)},__pushEventStreamEvent(e){De&&(We(),Ue(e.type,e.payload))},showEventStream(){De&&Bn()},hideEventStream(){ze&&Hn()},isEventStreamVisible(){return ze},listConversations(e){return Q.listConversations(e)},getActiveConversationId(){return Q.getActiveConversationId()},openConversation(e,t){return Rc(n=>n.openHistoryConversation(e,{focusComposer:t?.focus===!0}))},startNewConversation(e){return Rc(t=>t.startNewConversation({focusComposer:e?.focus===!0}))},warmSession(){Bc()},deleteConversation(e){return Rc(t=>t.deleteHistoryConversation(e))},renameConversation(e,t){return Rc(n=>n.updateHistoryConversation(e,{title:t}))},setConversationStarred(e,t){return Rc(n=>n.updateHistoryConversation(e,{starred:t}))},clearConversationHistory(e){return Rc(t=>t.clearConversationHistory(e))},resetHistoryIdentity(){return Rc(e=>e.resetHistoryIdentity())},async getVisitorToken(){let e=tc;if(!e)return null;let t=await e.get();return e===tc?t:null},getHistoryIdentityStatus(){let e=Sc?.historyProvider;return e?e.getIdentityStatus():Ec()?{state:`unavailable`,reason:`ineligible_mode`}:{state:`unavailable`,reason:`history_disabled`}},showHistory(e){return Ec()?Rc(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...e?.focus===void 0?{}:{focus:e.focus}})):Promise.resolve()},hideHistory(e){Sc?.closeHistory(e?.restoreFocus===void 0?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible(){return Ge},showArtifacts(){m_(r)&&(kr=!1,Mr=!0,si(),X?.setMobileOpen(!0))},hideArtifacts(){m_(r)&&(kr=!0,si())},upsertArtifact(e){return m_(r)?(jn(r.features?.artifacts,{artifactType:e.artifactType,...e.artifactType===`markdown`&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})===`panel`&&(kr=!1,Mr=!0),Q.upsertArtifact(e)):null},selectArtifact(e){m_(r)&&Q.selectArtifact(e)},clearArtifacts(){m_(r)&&Q.clearArtifacts()},getArtifacts(){return Q?.getArtifacts()??[]},getSelectedArtifactId(){return Q?.getSelectedArtifactId()??null},focusInput(){return M&&!P&&!N()||!B?!1:(B.focus(),!0)},async resolveApproval(e,t,n){let r=Q.getMessages().find(t=>t.variant===`approval`&&t.approval?.id===e);if(!r?.approval)throw Error(`Approval not found: ${e}`);if(r.approval.toolType===`webmcp`)Q.resolveWebMcpApproval(r.id,t);else return Q.resolveApproval(r.approval,t,n)},setFollowUpSuggestions(e){Ui(e)},clearFollowUpSuggestions(){Hi()},getMessages(){return Q.getMessages()},getStatus(){return Q.getStatus()},getPersistentMetadata(){return{...A}},updatePersistentMetadata(e){ue(e)},on(e,t){return O.on(e,t)},off(e,t){O.off(e,t)},isOpen(){return be()&&P},isVoiceActive(){return $.active},toggleReadAloud(e){Q.toggleReadAloud(e)},stopReadAloud(){Q.stopSpeaking()},getReadAloudState(e){return Q.getReadAloudState(e)},onReadAloudChange(e){return Q.onReadAloudChange(e)},getState(){return{open:be()&&P,launcherEnabled:M,voiceActive:$.active,streaming:Q.isStreaming()}},showCSATFeedback(e){!P&&be()&&Xo(!0,`system`);let t=z.querySelector(`.persona-feedback-container`);t&&t.remove();let n=zv({onSubmit:async(t,n)=>{Q.isClientTokenMode()&&await Q.submitCSATFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});z.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},showNPSFeedback(e){!P&&be()&&Xo(!0,`system`);let t=z.querySelector(`.persona-feedback-container`);t&&t.remove();let n=Bv({onSubmit:async(t,n)=>{Q.isClientTokenMode()&&await Q.submitNPSFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});z.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},async submitCSATFeedback(e,t){return Q.submitCSATFeedback(e,t)},async submitNPSFeedback(e,t){return Q.submitNPSFeedback(e,t)},destroy(){vc(),ac!=null&&(clearInterval(ac),ac=null),s.clear(),a.clear(),o.clear(),c.clear(),Z.forEach(e=>e()),F.remove(),rt?.remove(),Su?.destroy(),wu?.remove(),Oi&&H.removeEventListener(`click`,Oi)}};if(((n?.debugTools??!1)||r.debug)&&typeof window<`u`){let e=window.AgentWidgetBrowser,t={controller:dd,getMessages:dd.getMessages,getStatus:dd.getStatus,getMetadata:dd.getPersistentMetadata,updateMetadata:dd.updatePersistentMetadata,clearHistory:()=>dd.clearChat(),setVoiceActive:e=>e?dd.startVoiceRecognition():dd.stopVoiceRecognition()};window.AgentWidgetBrowser=t,Z.push(()=>{window.AgentWidgetBrowser===t&&(window.AgentWidgetBrowser=e)})}if(typeof window<`u`){let t=e.getAttribute(`data-persona-instance`)||e.id||`persona-`+Math.random().toString(36).slice(2,8),n=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&dd.focusInput()};if(window.addEventListener(`persona:focusInput`,n),Z.push(()=>{window.removeEventListener(`persona:focusInput`,n)}),De){let e=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&dd.showEventStream()},n=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&dd.hideEventStream()};window.addEventListener(`persona:showEventStream`,e),window.addEventListener(`persona:hideEventStream`,n),Z.push(()=>{window.removeEventListener(`persona:showEventStream`,e),window.removeEventListener(`persona:hideEventStream`,n)})}let r=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&dd.showHistory()},i=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&dd.hideHistory()};window.addEventListener(`persona:showHistory`,r),window.addEventListener(`persona:hideHistory`,i),Z.push(()=>{window.removeEventListener(`persona:showHistory`,r),window.removeEventListener(`persona:hideHistory`,i)});let a=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&dd.showArtifacts()},o=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&dd.hideArtifacts()},s=e=>{let n=e.detail;n?.instanceId&&n.instanceId!==t||n?.artifact&&dd.upsertArtifact(n.artifact)},c=e=>{let n=e.detail;n?.instanceId&&n.instanceId!==t||typeof n?.id==`string`&&dd.selectArtifact(n.id)},l=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&dd.clearArtifacts()};window.addEventListener(`persona:showArtifacts`,a),window.addEventListener(`persona:hideArtifacts`,o),window.addEventListener(`persona:upsertArtifact`,s),window.addEventListener(`persona:selectArtifact`,c),window.addEventListener(`persona:clearArtifacts`,l),Z.push(()=>{window.removeEventListener(`persona:showArtifacts`,a),window.removeEventListener(`persona:hideArtifacts`,o),window.removeEventListener(`persona:upsertArtifact`,s),window.removeEventListener(`persona:selectArtifact`,c),window.removeEventListener(`persona:clearArtifacts`,l)})}let pd=qv(r.persistState);if(pd&&be()){let t=Jv(pd.storage),n=`${pd.keyPrefix}widget-open`,r=`${pd.keyPrefix}widget-voice`,i=`${pd.keyPrefix}widget-voice-mode`;if(t){let a=pd.persist?.openState&&t.getItem(n)===`true`,o=pd.persist?.voiceState&&t.getItem(r)===`true`,s=pd.persist?.voiceState&&t.getItem(i)===`true`;if(a&&(Su?.setPanelOpen(!0,`auto`),setTimeout(()=>{dd.open(),setTimeout(()=>{if(o||s)dd.startVoiceRecognition();else if(pd.persist?.focusInput){let t=e.querySelector(`textarea`);t&&t.focus()}},100)},0)),pd.persist?.openState&&(O.on(`widget:opened`,()=>{t.setItem(n,`true`)}),O.on(`widget:closed`,()=>{t.setItem(n,`false`)})),pd.persist?.voiceState&&(O.on(`voice:state`,e=>{t.setItem(r,e.active?`true`:`false`)}),O.on(`user:message`,e=>{t.setItem(i,e.viaVoice?`true`:`false`)})),pd.clearOnChatClear){let e=()=>{t.removeItem(n),t.removeItem(r),t.removeItem(i)},a=()=>e();window.addEventListener(`persona:clear-chat`,a),Z.push(()=>{window.removeEventListener(`persona:clear-chat`,a)})}}}if(se&&be()&&(Su?.setPanelOpen(!0,`auto`),setTimeout(()=>{dd.open()},0)),qo(),!$i){let e=Wt(()=>{Q&&(Qi++,Gi.clear(),Io(z,Q.getMessages(),we))});Z.push(e)}x=()=>{Q&&(Qi++,Gi.clear(),Io(z,Q.getMessages(),we))},Q.getMessages().length>0&&Fo(),E=()=>{Q&&(Qi++,Gi.clear(),Io(z,Q.getMessages(),we))};let md=cn(()=>{Q&&(Qi++,Gi.clear(),Io(z,Q.getMessages(),we))});Z.push(md);let hd=p_(()=>{Q&&(Qi++,Gi.clear(),Io(z,Q.getMessages(),we),f_()?.updateInlineArtifactBlocks(z,Or.artifacts,{suppressTransition:!0}),si())});return Z.push(hd),dd};yi();const ny=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let i=/^(\d+(?:\.\d+)?)%$/i.exec(n);return i?Math.max(0,t*parseFloat(i[1])/100):420},ry=(e,t)=>{t===!1?e.style.maxHeight=``:(e.style.maxHeight=`100vh`,e.style.maxHeight=t)},iy=(e,t)=>{t===!1?(e.style.position=`relative`,e.style.top=``):(e.style.position=`sticky`,e.style.top=`0`)},ay=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement(`div`);r.style.cssText=`width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;`,n.appendChild(r);let i=r.offsetHeight>0;r.style.height=`100%`;let a=r.offsetHeight>0;r.remove(),i&&!a&&console.warn(`[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout.`+(t.maxHeight===!1?` The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.`:` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},oy=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className=`persona-host`,e.style.height=n?``:`100%`,e.style.display=n?``:`flex`,e.style.flexDirection=n?``:`column`,e.style.flex=n?``:`1 1 auto`,e.style.minHeight=n?``:`0`,e.style.minWidth=n?``:`0`},sy=e=>{e.style.position=``,e.style.top=``,e.style.bottom=``,e.style.left=``,e.style.right=``,e.style.zIndex=``,e.style.transform=``,e.style.pointerEvents=``},cy=e=>{e.style.inset=``,e.style.width=``,e.style.height=``,e.style.maxWidth=``,e.style.maxHeight=``,e.style.minWidth=``,sy(e)},ly=e=>{e.style.transition=``},uy=e=>{e.style.display=``,e.style.flexDirection=``,e.style.flex=``,e.style.minHeight=``,e.style.minWidth=``,e.style.width=``,e.style.height=``,e.style.alignItems=``,e.style.transition=``,e.style.transform=``,e.style.marginLeft=``},dy=e=>{e.style.width=``,e.style.maxWidth=``,e.style.minWidth=``,e.style.flex=`1 1 auto`},fy=(e,t)=>{e.style.width=``,e.style.minWidth=`0`,e.style.maxWidth=``,e.style.boxSizing=``,t.style.alignItems=``},py=(e,t,n,r,i)=>{i?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},my=(e,t,n,r,i,a)=>{let o=a?t:e;i===`left`?o.firstElementChild!==r&&o.replaceChildren(r,n):o.lastElementChild!==r&&o.replaceChildren(n,r)},hy=e=>{let t=Ep(e),n=t.components?.panel,r=(e,n)=>e==null||e===``?n:$f(t,e)??e;return{inset:r(n?.inset,Ff),canvasBackground:r(n?.canvasBackground,If)}},gy=(e,t,n,r)=>{t?(e.style.boxSizing=`border-box`,e.style.padding=n,e.style.background=r):(e.style.padding=``,e.style.background=``,e.style.boxSizing=``)},_y=(e,t,n,r,i,a,o,s)=>{let c=Pm(a),l=c.reveal===`push`,u=s!=null,d=s?.inset??``,f=s?.canvasBackground??``;py(e,t,n,r,l),my(e,t,n,r,c.side,l),e.dataset.personaHostLayout=`docked`,e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=o?`true`:`false`,e.style.width=`100%`,e.style.maxWidth=`100%`,e.style.minWidth=`0`,e.style.height=`100%`,e.style.minHeight=`0`,e.style.position=`relative`,n.style.display=`flex`,n.style.flexDirection=`column`,n.style.minHeight=`0`,n.style.position=`relative`,i.className=`persona-host`,i.style.height=`100%`,i.style.minHeight=`0`,i.style.minWidth=`0`,i.style.display=`flex`,i.style.flexDirection=`column`,i.style.flex=`1 1 auto`;let p=e.ownerDocument.defaultView,m=a?.launcher?.mobileFullscreen??!0,h=a?.launcher?.mobileBreakpoint??640,g=p!=null&&p.innerWidth<=h;if(m&&g&&o)e.dataset.personaDockMobileFullscreen=`true`,e.removeAttribute(`data-persona-dock-reveal`),uy(t),ly(r),cy(r),dy(n),fy(i,r),gy(r,!1,``,``),e.style.display=`flex`,e.style.flexDirection=`column`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,n.style.flex=`1 1 auto`,n.style.width=`100%`,n.style.minWidth=`0`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.position=`fixed`,r.style.inset=`0`,r.style.width=`100%`,r.style.height=`100%`,r.style.maxWidth=`100%`,r.style.minWidth=`0`,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.zIndex=String(a?.launcher?.zIndex??1e5),r.style.transform=`none`,r.style.transition=`none`,r.style.pointerEvents=`auto`,r.style.flex=`none`,l&&(t.style.display=`flex`,t.style.flexDirection=`column`,t.style.width=`100%`,t.style.height=`100%`,t.style.minHeight=`0`,t.style.minWidth=`0`,t.style.flex=`1 1 auto`,t.style.alignItems=`stretch`,t.style.transform=`none`,t.style.marginLeft=`0`,t.style.transition=`none`,n.style.flex=`1 1 auto`,n.style.width=`100%`,n.style.maxWidth=`100%`,n.style.minWidth=`0`);else if(e.removeAttribute(`data-persona-dock-mobile-fullscreen`),cy(r),ry(r,c.maxHeight),gy(r,u&&o,d,f),c.reveal===`overlay`){e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,e.dataset.personaDockReveal=`overlay`,uy(t),ly(r),dy(n),fy(i,r);let a=c.animate?`transform 180ms ease`:`none`,s=c.side===`right`?`translateX(100%)`:`translateX(-100%)`,l=o?`translateX(0)`:s;r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`none`,r.style.position=`absolute`,r.style.top=`0`,r.style.bottom=`0`,r.style.width=c.width,r.style.maxWidth=c.width,r.style.minWidth=c.width,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.transition=a,r.style.transform=l,r.style.pointerEvents=o?`auto`:`none`,r.style.zIndex=`2`,c.side===`right`?(r.style.right=`0`,r.style.left=``):(r.style.left=`0`,r.style.right=``)}else if(c.reveal===`push`){e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,e.dataset.personaDockReveal=`push`,ly(r),sy(r),fy(i,r);let a=ny(c.width,e.clientWidth),s=Math.max(0,e.clientWidth),l=c.animate?`margin-left 180ms ease`:`none`,u=c.side===`right`?o?-a:0:o?0:-a;t.style.display=`flex`,t.style.flexDirection=`row`,t.style.flex=`0 0 auto`,t.style.minHeight=`0`,t.style.minWidth=`0`,t.style.alignItems=`stretch`,t.style.height=`100%`,t.style.width=`${s+a}px`,t.style.transition=l,t.style.marginLeft=`${u}px`,t.style.transform=``,n.style.flex=`0 0 auto`,n.style.flexGrow=`0`,n.style.flexShrink=`0`,n.style.width=`${s}px`,n.style.maxWidth=`${s}px`,n.style.minWidth=`${s}px`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 auto`,r.style.flexShrink=`0`,r.style.width=c.width,r.style.minWidth=c.width,r.style.maxWidth=c.width,r.style.position=`relative`,r.style.top=``,r.style.overflow=`hidden`,r.style.transition=`none`,r.style.pointerEvents=o?`auto`:`none`}else{e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=``,uy(t),sy(r),dy(n),fy(i,r);let a=c.reveal===`emerge`;a?e.dataset.personaDockReveal=`emerge`:e.removeAttribute(`data-persona-dock-reveal`);let s=o?c.width:`0px`,l=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?`, padding 180ms ease`:``}`:`none`,f=!o;if(r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 ${s}`,r.style.width=s,r.style.maxWidth=s,r.style.minWidth=s,r.style.minHeight=`0`,iy(r,c.maxHeight),r.style.overflow=a||f?`hidden`:`visible`,r.style.transition=l,a){r.style.alignItems=c.side===`right`?`flex-start`:`flex-end`;let t=u?`calc(${ny(c.width,e.clientWidth)}px - (2 * ${d}))`:c.width;i.style.width=t,i.style.minWidth=t,i.style.maxWidth=t,i.style.boxSizing=`border-box`}}},vy=(e,t)=>{let n=e.ownerDocument.createElement(`div`);return oy(n,t),e.appendChild(n),{mode:`direct`,host:n,shell:null,syncWidgetState:()=>{},updateConfig(e){oy(n,e)},destroy(){n.remove()}}},yy=(e,t)=>{let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw Error(`Docked widget target must be attached to the DOM`);let i=e.tagName.toUpperCase();if(i===`BODY`||i===`HTML`)throw Error(`Docked widget target must be a concrete container element, not "body" or "html"`);let a=e.nextSibling,o=n.createElement(`div`),s=n.createElement(`div`),c=n.createElement(`div`),l=n.createElement(`aside`),u=n.createElement(`div`),d=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;s.dataset.personaDockRole=`push-track`,c.dataset.personaDockRole=`content`,l.dataset.personaDockRole=`panel`,u.dataset.personaDockRole=`host`,l.appendChild(u),r.insertBefore(o,e),c.appendChild(e);let f=null,p=()=>{f?.disconnect(),f=null},m=null,h=()=>{m=t?.launcher?.detachedPanel===!0?hy(t):null};h();let g=()=>{_y(o,s,c,l,u,t,d,m)},_=null,v=()=>{_?.(),_=null,t?.launcher?.detachedPanel===!0&&t?.colorScheme===`auto`&&(_=kp(()=>{h(),g()}))},y=()=>{p(),Pm(t).reveal===`push`&&typeof ResizeObserver<`u`&&(f=new ResizeObserver(()=>{g()}),f.observe(o))},b=!1,x=()=>{g(),y(),d&&!b&&o.dataset.personaDockMobileFullscreen!==`true`&&(b=!0,ay(o,Pm(t)))},S=o.ownerDocument.defaultView,C=()=>{x()};return S?.addEventListener(`resize`,C),Pm(t).reveal===`push`?(s.appendChild(c),s.appendChild(l),o.appendChild(s)):(o.appendChild(c),o.appendChild(l)),x(),v(),{mode:`docked`,host:u,shell:o,syncWidgetState(e){let t=!e.launcherEnabled||e.open;d!==t&&(d=t,x())},updateConfig(e){t=e,(t?.launcher?.enabled??!0)===!1&&(d=!0),h(),x(),v()},destroy(){S?.removeEventListener(`resize`,C),_?.(),_=null,p(),r.isConnected&&(a&&a.parentNode===r?r.insertBefore(e,a):r.appendChild(e)),o.remove()}}},by=(e,t)=>Mm(t)?yy(e,t):vy(e,t),xy=e=>{if(typeof window>`u`||typeof document>`u`)throw Error(`Chat widget can only be mounted in a browser environment`);if(typeof e==`string`){let t=document.querySelector(e);if(!t)throw Error(`Chat widget target "${e}" was not found`);return t}return e},Sy=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector(`link[data-persona]`))return;let n=t.head.querySelector(`link[data-persona]`);if(!n)return;let r=n.cloneNode(!0);e.insertBefore(r,e.firstChild)},Cy=[],wy=()=>[...Cy],Ty=e=>{let t=xy(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,i=e.config,a=by(t,i),o,s=[],c=(e,i)=>{let a=!(i?.launcher?.enabled??!0)||Mm(i),o=r.createElement(`div`);if(o.setAttribute(`data-persona-root`,`true`),a&&(o.style.height=`100%`,o.style.display=`flex`,o.style.flexDirection=`column`,o.style.flex=`1`,o.style.minHeight=`0`,o.style.minWidth=`0`),n){let t=e.attachShadow({mode:`open`});t.appendChild(o),Sy(t,r)}else e.appendChild(o),Sy(e,r);return t.id&&o.setAttribute(`data-persona-instance`,t.id),o},l=()=>{a.syncWidgetState(o.getState())},u=()=>{s.forEach(e=>e()),s=[o.on(`widget:opened`,l),o.on(`widget:closed`,l)],l()},d=()=>{let t=c(a.host,i);o=ty(t,i,{debugTools:e.debugTools}),u()},f=()=>{s.forEach(e=>e()),s=[],o.destroy()};d(),e.onChatReady?.();let p=e=>{f(),a.destroy(),a=by(t,e),i=e,d()},m=new Proxy({update(e){let t=cv(i??{},e),n=Mm(i),r=Mm(t),s=Nm(i),c=Nm(t);n!==r||s!==c?p(t):(i=t,a.updateConfig(i),o.update(e),l())},destroy(){f(),a.destroy();let t=Cy.indexOf(m);t!==-1&&Cy.splice(t,1),e.windowKey&&typeof window<`u`&&delete window[e.windowKey]}},{get(e,t,n){if(t===`host`)return a.host;if(t in e)return Reflect.get(e,t,n);let r=o[t];return typeof r==`function`?r.bind(o):r}});return Cy.push(m),e.windowKey&&typeof window<`u`&&(window[e.windowKey]=m),m},Ey=/* @__PURE__ */ new Set([`script`,`style`,`noscript`,`svg`,`path`,`meta`,`link`,`br`,`hr`]),Dy=/* @__PURE__ */ new Set([`button`,`a`,`input`,`select`,`textarea`,`details`,`summary`]),Oy=/* @__PURE__ */ new Set([`button`,`link`,`menuitem`,`tab`,`option`,`switch`,`checkbox`,`radio`,`combobox`,`listbox`,`slider`,`spinbutton`,`textbox`]),ky=/\b(product|card|item|listing|result)\b/i,Ay=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i;function jy(e){let t=typeof e.className==`string`?e.className:``;if(ky.test(t)||e.id&&ky.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith(`data-`)&&ky.test(n.value))return!0}return!1}function My(e){return Ay.test((e.textContent??``).trim())}function Ny(e){let t=e.querySelectorAll(`a[href]`);for(let e=0;e<t.length;e++){let n=t[e].getAttribute(`href`)??``;if(n&&n!==`#`&&!n.toLowerCase().startsWith(`javascript:`))return!0}return!1}function Py(e){return!!e.querySelector(`button, [role="button"], input[type="submit"], input[type="button"]`)}function Fy(e){let t=e.match(Ay);return t?t[0]:null}function Iy(e){let t=e.querySelector(`.product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]`)??e.querySelector(`a[href]`);if(t&&t.textContent?.trim()){let e=t.getAttribute(`href`);return{title:t.textContent.trim(),href:e&&e!==`#`?e:null}}let n=e.querySelector(`h1, h2, h3, h4, h5, h6`);return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:``,href:null}}function Ly(e){let t=[],n=e=>{let n=e.trim();n&&!t.includes(n)&&t.push(n)};return e.querySelectorAll(`button`).forEach(e=>n(e.textContent??``)),e.querySelectorAll(`[role="button"]`).forEach(e=>n(e.textContent??``)),e.querySelectorAll(`input[type="submit"], input[type="button"]`).forEach(e=>{n(e.value??``)}),t.slice(0,6)}function Ry(e){return!jy(e)||!My(e)||!Ny(e)&&!Py(e)?0:5200}function zy(e){return!jy(e)||My(e)||!Ny(e)||(e.textContent??``).trim().length<20||!(e.querySelector(`h1, h2, h3, h4, h5, h6, .title`)||e.querySelector(`.snippet, .description, p`))?0:2800}const By=[{id:`commerce-card`,scoreElement(e){return Ry(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity===`static`){let e=n.text.trim();return!!(e.length===0||Ay.test(e)&&e.length<32)}return!0},formatSummary(e,t){if(Ry(e)===0)return null;let{title:n,href:r}=Iy(e),i=Fy((e.textContent??``).trim())??Fy(t.text)??``,a=Ly(e);return[r&&n?`[${n}](${r})${i?`: ${i}`:``}`:n?`${n}${i?`: ${i}`:``}`:i||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(`, `)}`:``].filter(Boolean).join(`
|
|
135
|
-
`)}},{id:`result-card`,scoreElement(e){return
|
|
136
|
-
`)}}];function
|
|
134
|
+
`)}if(!o&&!n){let e=i?``:`padding-top: 1.25em !important;`,t=i?``:`z-index: ${r.launcher?.zIndex??1e5} !important;`;F.style.cssText+=`max-height: -moz-available !important; max-height: stretch !important;`+e+t}sn(),he()},ui=()=>{e.style.setProperty(`--persona-content-max-width`,Ip(r,N()))},fi=!1;function pi(){r.layout?.topFade&&R.scrollTop>1?R.setAttribute(`data-persona-top-fade`,`true`):R.removeAttribute(`data-persona-top-fade`)}let mi=()=>{pi();let t=Lp(r,N());N()&&r.composer?.placement&&r.debug===!0&&!fi&&(fi=!0,console.warn(`[persona] composer.placement is ignored in composer-bar mount mode.`));let n=tn();e.setAttribute(`data-persona-composer-placement`,t),e.setAttribute(`data-persona-conversation-state`,nn),e.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`),e.style.setProperty(`--persona-composer-anchor-gap`,n.composerGap??`24px`),ln()},hi=()=>{if(N())return;let t=Bm(r),n=r.launcher?.sidebarMode??!1;if(t||n||(r.launcher?.fullHeight??!1)||!M)return;let i=e.ownerDocument.defaultView??window,a=r.launcher?.mobileFullscreen??!0,o=r.launcher?.mobileBreakpoint??640;if(a&&i.innerWidth<=o)return;let s=vg(r);I.style.height=s.height,I.style.maxHeight=s.maxHeight};li(),Pp(e,r),O_(e,r),k_(e,r),ui(),mi(),Tr=()=>{li(),hi(),Pp(e,r),O_(e,r),k_(e,r),ui(),mi(),Dr?e.style.setProperty(`--persona-artifact-welded-outer-radius`,Dr):e.style.removeProperty(`--persona-artifact-welded-outer-radius`),Je(),qe()};let Z=[];Z.push(()=>{Sr=!0}),Z.push(()=>{p.forEach(e=>e()),f.destroy()}),Z.push(()=>{document.removeEventListener(`keydown`,Ur)}),Z.push(()=>{Zt!==null&&clearTimeout(Zt)});let _i=null,vi=null;Z.push(()=>{_i?.(),_i=null,vi?.(),vi=null}),wr&&Z.push(()=>{wr?.disconnect(),wr=null}),Z.push(()=>{Kr?.(),Kr=null,ei(),Gr&&=(Gr.remove(),null),X?.element.style.removeProperty(`width`),X?.element.style.removeProperty(`maxWidth`),X?.destroy()}),De&&Z.push(()=>{Le=!0,Ie=null,Be!==null&&(cancelAnimationFrame(Be),Be=null),Re?.destroy(),Re=null,Pe?.destroy(),Pe=null,Me=null});let yi=null,bi=()=>{yi&&=(yi(),null),r.colorScheme===`auto`&&(yi=Fp(()=>{Pp(e,r)}))};bi(),Z.push(()=>{yi&&=(yi(),null)}),Z.push(()=>{y=!0,v?.()}),Z.push(()=>{w=!0});let xi=!1;Z.push(()=>{xi=!0});let Si=(t,n)=>{let r=hm(t,n);return r||!dm.includes(t)?r:(Pm().then(r=>{if(xi)return;fm(r.wipe),fm(r.glyphCycle);let i=hm(t,n);i&&jm(i,e)}).catch(()=>{}),null)},Ci=r.features?.streamAnimation;if(Ci?.type&&Ci.type!==`none`){let t=Si(Ci.type,Ci.plugins);t&&jm(t,e),Z.push(()=>Am(e))}let wi=Ym(st),Ti=Ym(at),Ei=Ym(ot),Di=[wi,Ti,Ei];Z.push(()=>{Di.forEach(e=>e.destroy())});let Oi=null,Q,ki=null,Ai=!1,ji=0,Mi=null,Pi=e=>e.reduce((e,t)=>t.role===`user`?e+1:e,0),Fi=e=>{for(let t=e.length-1;t>=0;t--)if(oi(e[t]))return e[t].id??null;return null},Ii=!1,Li=()=>{Ii||r.debug!==!0||(Ii=!0,console.warn(`[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".`))},Ri=!1,zi=!1,Bi=(e,t)=>{Ri||r.debug!==!0||t.enabled&&!t.expose&&(Ai||zi&&(Q.isStreaming()||e.some(oi)||(Ri=!0,console.info(`[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.`))))},Vi=e=>{if(!Q)return;let t=e??Q.getMessages(),n=e=>{e.render([],Q,B,t)},i=e=>{Di.forEach(t=>{t!==e&&n(t)})};ki&&(Pi(t)>ji||Fi(t)!==Mi)&&(ki=null);let a=di(r);Bi(t,a);let o=a.enabled?ci(t):null,s=ki??o,c=ki?`host`:`agent`;if(s){let e=r.suggestions?.followUps,n=e?.placement??(e?`auto`:`composer`),a=(n===`auto`?N()?`composer`:`after-message`:n)===`after-message`?Ei:wi;i(a),a.render(s,Q,B,t,r.suggestionChipsConfig,{source:c,surface:`followUp`,variant:e?.variant??`chip`,behavior:e?.behavior??`send`,overflow:e?.overflow??`wrap`,maxItems:e?.maxItems??4,config:r,plugins:d,submitPrompt:ml});return}if(t.some(e=>e.role===`user`)){Di.forEach(n);return}let l=r.future?.v5Defaults===!0,u=en(),f=r.suggestions?.starters??(l?{}:void 0);if(f){let e=gg(tn(),t),a=f.placement??`auto`,o=a===`auto`?e?`welcome`:`composer`:a;if(o===`welcome`&&!e){Li(),Di.forEach(n);return}let s=o===`welcome`?Ti:wi;i(s),s.render(f.items??r.suggestionChips,Q,B,t,r.suggestionChipsConfig,{surface:`starter`,variant:f.variant??(l&&!u?`chip`:`card`),behavior:f.behavior??`send`,overflow:f.overflow??`wrap`,maxItems:f.maxItems??(l&&!u?3:4),config:r,plugins:d,submitPrompt:ml})}else i(wi),wi.render(r.suggestionChips,Q,B,t,r.suggestionChipsConfig,{surface:`starter`,variant:`chip`,behavior:`send`,overflow:`wrap`,maxItems:4,config:r,plugins:d,submitPrompt:ml})},Hi=()=>{ki&&(ki=null,Vi())},Ui=e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length){Hi();return}let n=Q?Q.getMessages():[];ki=t,Ai=!0,ji=Pi(n),Mi=Fi(n),Vi(n)},Wi=!1,Gi=qp(),Ki=/* @__PURE__ */ new Set,qi=/* @__PURE__ */ new Map,Ji=/* @__PURE__ */ new Map,Yi=/* @__PURE__ */ new Map,Xi=/* @__PURE__ */ new Map,Zi=null,Qi=null;function $i(){if(!Zi)return;let e=Zi;Zi=null,Qi?.destroy(),Qi=null,Gi.delete(e),L.querySelector(`#wrapper-${e}`)?.removeAttribute(`data-preserve-runtime`),Q&&zo(z,Q.getMessages(),we)}let ea=0,ta=Kt()!==null,na=Qp(),ra=0,ia=null,aa=!1,oa=!1,sa=0,ca=null,la=null,ua=!1,da=!1,fa=null,pa=!0,ma=!1,ha=null,ga=!1,_a=()=>{ga=!0,xa()},va=null,ya=null,ba=()=>{e.setAttribute(`data-persona-scrollbar`,Bt()),Bt()!==`on-scroll`&&(ya!==null&&clearTimeout(ya),ya=null,R.removeAttribute(`data-persona-scrollbar-visible`))},xa=()=>{Bt()===`on-scroll`&&(R.setAttribute(`data-persona-scrollbar-visible`,``),ya!==null&&clearTimeout(ya),ya=setTimeout(()=>{ya=null,em(R,24)&&R.removeAttribute(`data-persona-scrollbar-visible`)},1e3))};ba(),Z.push(()=>{ya!==null&&clearTimeout(ya)});let Sa=/* @__PURE__ */ new Map,Ca=!1,wa=null,$={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};lr();let Da=r.voiceRecognition?.autoResume??!1,Oa=()=>Q.isVoiceActive()||Q.isBargeInActive(),ka=!1,Aa=e=>{O.emit(`voice:state`,{active:$.active,source:e,timestamp:Date.now()})},ja=()=>{ue(e=>({...e,voiceState:{active:$.active,timestamp:Date.now(),manuallyDeactivated:$.manuallyDeactivated}}))},Ma=()=>{if(r.voiceRecognition?.enabled===!1)return;let e=iy(te.voiceState),t=!!e.active,n=Number(e.timestamp??0);$.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-n<3e4&&setTimeout(()=>{$.active||($.manuallyDeactivated=!1,Al(r.voiceRecognition?.provider)?Q.toggleVoice().then(()=>{$.active=Oa(),Aa(`restore`),$.active?tu():(ja(),el(`Tap the mic to resume your voice call`,1e4))}):Zl(`restore`))},Al(r.voiceRecognition?.provider)?0:1e3)},Na=e=>{ka=!e.persisted,$.active&&ja()};typeof window<`u`&&(window.addEventListener(`pagehide`,Na),Z.push(()=>window.removeEventListener(`pagehide`,Na)));let Pa=()=>Q?ay(Q.getMessages()).filter(e=>!e.__skipPersist):[],Fa=null,Ia=(e,t)=>{typeof console<`u`&&console.error(e,t)},La=(e,t)=>{let n=()=>{try{let n=e();return!n||typeof n.then!=`function`?null:Promise.resolve(n).catch(e=>{Ia(t,e)})}catch(e){return Ia(t,e),null}},r=Fa,i=r?r.then(()=>n()??void 0):n();if(!i)return;let a=i.finally(()=>{Fa===a&&(Fa=null)});Fa=a};function Ra(e){if(!k?.save)return;let t=e?ay(e):Q?Pa():[],n=ee&&Q?.getResumableHandle();n&&(te={...te,durableResume:{executionId:n.executionId,after:n.lastEventId}});let r={messages:t,metadata:te,artifacts:Or.artifacts,selectedArtifactId:Or.selectedId,...za?{draft:za}:{}};La(()=>k.save(r),`[AgentWidget] Failed to persist state:`)}let za,Ba=()=>!k?.save||r.persistState===!1?!1:typeof r.persistState!=`object`||r.persistState.persist?.draft!==!1,Va=kf({write:()=>{if(!Ba())return;let e=G.getState(),t=Df({text:e.text,mentionRefs:e.mentionRefs,contentSegments:Yc(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(za)&&(za=t,Ra())}});function Ha(){Ba()&&Va.schedule()}function Ua(){Va.flush()}function Wa(e){if(!Ba())return;let t=Of(e,{mentionSourceIds:(r.contextMentions?.sources??[]).map(e=>e.id),modelIds:(r.composer?.models??[]).map(e=>e.id),modes:r.composer?.modes??[]});t&&(za=e,B&&!B.value&&(B.value=t.text,B.dispatchEvent(new Event(`input`,{bubbles:!0})),pn()),t.selectedModelId&&(G.setSelectedModelId(t.selectedModelId),Cn?.repaint()),bn(t.activeModeIds??[]),t.quote&&On(t.quote),Va.cancel())}function qa(){Va.cancel(),za&&(za=void 0,Ba()&&Ra())}let Ya=null,Xa=()=>F.querySelector(`#persona-scroll-container`)||R,Za=()=>{Ya!==null&&(cancelAnimationFrame(Ya),Ya=null),aa=!1},Qa=()=>{ia!==null&&(cancelAnimationFrame(ia),ia=null),oa=!1,Za()},$a=()=>Wi&&ro()&&(Nt()!==`anchor-top`||Rt()),eo=()=>{let e=jt()||`Jump to latest`,t=$a();Vt.toggleAttribute(`data-persona-scroll-to-bottom-streaming`,t),sa>0?(qt.textContent=String(sa),qt.style.display=``,Vt.setAttribute(`aria-label`,`${e} (${sa} new)`)):(qt.textContent=``,qt.style.display=`none`,Vt.setAttribute(`aria-label`,t?`${e} (response streaming below)`:e))},to=()=>{sa!==0&&(sa=0,eo())},no=()=>{let e=ca?.spacerHeight??0;return e<=0?em(R,24):yo(e)-R.scrollTop-R.clientHeight<=24},ro=()=>Pt()?!na.isFollowing():!no(),io=()=>!!Q&&Q.getMessages().length>0,ao=()=>{if(!Mt()||Qe()){Vt.parentNode&&Vt.remove(),Vt.style.display=`none`;return}Vt.parentNode!==L&&L.appendChild(Vt),on();let e=$p(R)>0&&ro()&&io();e?eo():to(),Vt.style.display=e?``:`none`},oo=()=>{na.pause()&&(Qa(),ao())},so=()=>{na.resume(),to(),ao()},co=(e=!1)=>{Pt()&&io()&&na.isFollowing()&&(e||Wi)&&(ia!==null&&(cancelAnimationFrame(ia),ia=null),oa=!0,ia=requestAnimationFrame(()=>{ia=null,oa=!1,na.isFollowing()&&uo(Xa(),e?220:140)}))},lo=(e,t,n,r=()=>!0)=>{let i=e.scrollTop,a=t(),o=a-i;if(Za(),Math.abs(o)<1){aa=!0,e.scrollTop=a,ra=e.scrollTop,aa=!1;return}let s=performance.now();aa=!0;let c=e=>1-(1-e)**3,l=u=>{if(!r()){Za();return}let d=t();d!==a&&(a=d,o=a-i);let f=u-s,p=Math.min(f/n,1),m=c(p);e.scrollTop=i+o*m,ra=e.scrollTop,p<1?Ya=requestAnimationFrame(l):(e.scrollTop=a,ra=e.scrollTop,Ya=null,aa=!1)};Ya=requestAnimationFrame(l)},uo=(e,t=500)=>{let n=$p(e)-e.scrollTop;Math.abs(n)<1?ra=e.scrollTop:Math.abs(n)>=80?(Za(),aa=!0,e.scrollTop=$p(e),ra=e.scrollTop,aa=!1):lo(e,()=>$p(e),t,()=>na.isFollowing())},po=()=>{if(!io()){ao();return}let e=Xa();aa=!0,e.scrollTop=$p(e),ra=e.scrollTop,aa=!1,ao()},mo=e=>{let t=0,n=e;for(;n&&n!==R;)t+=n.offsetTop,n=n.offsetParent;return t},ho=()=>{let e=R.getRootNode();return(typeof e.getSelection==`function`?e.getSelection():null)??R.ownerDocument.getSelection()},go=()=>rm(ho(),R),_o=()=>{if(It()!==`last-user-turn`)return!1;let e=Q?.getMessages()??[];if(e.length<2)return!1;let t=[...e].reverse().find(e=>e.role===`user`);if(!t)return!1;let n=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(t.id):t.id.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),r=R.querySelector(`[data-message-id="${n}"]`);if(!r)return!1;let i=Math.min(Math.max(0,mo(r)-Ft()),$p(R));return aa=!0,R.scrollTop=i,ra=R.scrollTop,aa=!1,Nt()===`follow`&&!em(R,24)&&na.pause(),ao(),!0},vo=e=>{let t=Math.max(0,Math.round(e));Yt.style.height=`${t}px`,Yt.style.display=t>0?``:`none`,ca&&(ca.spacerHeight=Math.max(0,e))},yo=e=>{let t=parseFloat(getComputedStyle(R).paddingBottom)||0,n=0;for(let e of Array.from(R.children)){if(e===Yt||e.offsetHeight===0)continue;let t=mo(e)+e.offsetHeight;t>n&&(n=t)}let r=R.scrollHeight-e;return n>0?Math.min(n+t,r):r},xo=()=>{if(!ca||ca.spacerHeight<=0)return;let e=yo(ca.spacerHeight),t=Math.max(0,Math.round(R.scrollTop)+R.clientHeight-e+24);t<ca.spacerHeight&&(vo(t),ao())},So=()=>{la!==null&&(cancelAnimationFrame(la),la=null),Za(),ca=null,Yt.style.height=`0px`,Yt.style.display=`none`},Co=e=>typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),wo=e=>R.querySelector(`[data-message-id="${Co(e)}"]`),To=e=>{la!==null&&cancelAnimationFrame(la),la=requestAnimationFrame(()=>{la=null;let t=Co(e),n=R.querySelector(`[data-message-id="${t}"]`);if(!n)return;let r=mo(n),i=ca?.spacerHeight??0,a=yo(i),{targetScrollTop:o,spacerHeight:s}=im({anchorOffsetTop:r,topOffset:Ft(),viewportHeight:R.clientHeight,contentHeight:a,slack:24});ca={initialSpacerHeight:s,contentHeightAtAnchor:a,spacerHeight:s},vo(s),lo(R,()=>n.isConnected?Math.max(0,mo(n)-Ft()):o,220)})},Eo=()=>{if(Nt()!==`anchor-top`||!ca||!ha)return;let e=wo(ha);if(!e)return;Za();let t=ca.spacerHeight,n=yo(t),{targetScrollTop:r,spacerHeight:i}=im({anchorOffsetTop:mo(e),topOffset:Ft(),viewportHeight:R.clientHeight,contentHeight:n,slack:24});ca={initialSpacerHeight:i,contentHeightAtAnchor:n,spacerHeight:i},vo(i),aa=!0,R.scrollTop=r,ra=R.scrollTop,aa=!1,ao()},Do=()=>{if(Pt()){if(!na.isFollowing()||em(R,1))return;co(!Wi)}else{if(ca&&ca.initialSpacerHeight>0){let e=R.scrollHeight-ca.spacerHeight,t=am({initialSpacerHeight:ca.initialSpacerHeight,contentHeightAtAnchor:ca.contentHeightAtAnchor,currentContentHeight:e});t!==ca.spacerHeight&&vo(t)}ao()}},Oo=e=>{let t=Nt();t===`follow`?(so(),co(!0)):t===`anchor-top`&&(pa=!1,ma=!0,ga=!1,ha=e,To(e))},ko=()=>{Nt()===`anchor-top`&&(ma?pa=!1:(pa=!0,So(),so(),co(!0)))},Ao=e=>{if(fa===null)return!0;let t=wo(fa),n=wo(e);if(!t||!n)return!0;let r=mo(n)-mo(t);return Ft()+r>R.clientHeight-96},jo=e=>{if(Nt()!==`anchor-top`||!ma||ga||go())return;let t=fa===null;for(let n of e)if(!t)n.id===fa&&(t=!0);else if(Zp(n)){if(n.id===ha||!Ao(n.id))return;ha=n.id,To(n.id);return}},Mo=e=>{let t=/* @__PURE__ */ new Map;e.forEach(e=>{let n=Sa.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!n&&e.role===`assistant`&&(O.emit(`assistant:message`,e),!da&&(Nt()!==`anchor-top`||Rt())&&ro()&&(sa+=1,eo(),ao(),$t(sa===1?`1 new message below.`:`${sa} new messages below.`))),e.role===`assistant`&&(n?.streaming||Ki.has(e.id))&&e.streaming===!1&&O.emit(`assistant:complete`,e),e.variant===`approval`&&e.approval&&(n?e.approval.status!==`pending`&&O.emit(`approval:resolved`,{approval:e.approval,decision:e.approval.status}):O.emit(`approval:requested`,{approval:e.approval,message:e}))}),Sa.clear(),t.forEach((e,t)=>{Sa.set(t,e)}),Ki.clear()},No=(e,t)=>{let n=t===`user`?`user`:`assistant`,i=r.layout?.messages?.[n],a=i?.width??`content`,o=i?.maxWidth??(a===`full`?`var(--persona-message-${n}-max-width, 100%)`:void 0);e.classList.add(`persona-message-row`),e.classList.remove(`persona-message-row-user`,`persona-message-row-assistant`,`persona-message-row-system`,`persona-message-width-content`,`persona-message-width-full`),e.classList.add(`persona-message-row-${t}`,`persona-message-width-${a}`),e.classList.toggle(`persona-justify-end`,t===`user`),e.setAttribute(`data-message-role`,t),e.setAttribute(`data-message-width`,a),o?e.style.setProperty(`--persona-message-row-max-width`,o):e.style.removeProperty(`--persona-message-row-max-width`)},Po=(e,t)=>{let n=document.createElement(`div`);return n.className=`persona-flex`,n.id=`wrapper-${e}`,n.setAttribute(`data-wrapper-id`,e),No(n,t),n},Fo=(e,t,n)=>{let i=/* @__PURE__ */ new Set;for(let e of t){let t=e.variant===`tool`?`tool`:e.variant===`reasoning`?`reasoning`:null;if(!t||wl(r,t)!==`row`)continue;let n=t===`tool`?r.features?.toolCallDisplay:r.features?.reasoningDisplay;n?.expandable!==!1&&(i.add(e.id),s.observe(e,t,t===`tool`?a:o,n))}let l=document.createElement(`div`),u=!r.features?.toolCallDisplay?.grouped,f=/* @__PURE__ */ new Set;if(u)for(let t of Array.from(e.children)){let e=t.getAttribute(`data-wrapper-id`);e&&f.add(e)}let p=/* @__PURE__ */ new Map,m=(()=>{let e=d.find(e=>e.renderLoadingIndicator);if(e?.renderLoadingIndicator)return e.renderLoadingIndicator;if(r.loadingIndicator?.render)return r.loadingIndicator.render})(),h=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),g=/* @__PURE__ */ new Set,v=/* @__PURE__ */ new Map,y=/* @__PURE__ */ new Set,b=d.some(e=>e.renderAskUserQuestion),x=[],S=[],w=r.enableComponentStreaming!==!1,T=r.approval!==!1,E=[],O=r.messageActions,k=O?.showRegenerate===!0&&O.enabled!==!1&&Fr.current?.isStreaming()!==!0?zu(t):null,ee=O?.showEdit===!0&&O.enabled!==!1,te=O?.showQuote===!0&&O.enabled!==!1,ne=null,re=r.features?.reasoningDisplay?.completedVisibility,ie=e=>re===`removed`||re===`removed-when-short`&&Rn(e,r.features?.reasoningDisplay?.shortThinkThreshold),ae=r.features?.toolCallDisplay?.completedVisibility===`removed`,oe=e=>e.variant===`reasoning`&&e.reasoning?.status===`complete`?ie(e.reasoning):ae&&e.variant===`tool`&&e.toolCall?.status===`complete`&&!e.toolCall.interrupted;if(t.forEach(t=>{if(oe(t))return;if(g.add(t.id),v.set(t.id,t.role),Zi===t.id&&Qi){let e=Po(t.id,t.role);e.setAttribute(`data-persona-message-edit-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),ne={messageId:t.id,element:Qi.element};return}let i=b&&xr(t),s=T&&t.variant===`approval`&&!!t.approval,h=!i&&t.role===`assistant`&&!t.variant&&w&&Gv(t);!s&&Xi.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),Xi.delete(t.id)),!h&&Yi.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),Yi.delete(t.id));let O=xr(t)?`:${t.agentMetadata?.askUserQuestionAnswered?`a`:`u`}:${t.agentMetadata?.askUserQuestionAnswers?Object.keys(t.agentMetadata.askUserQuestionAnswers).length:0}`:``,re={canRegenerate:k===t.id,canEdit:ee&&Bu(t),canQuote:te&&!t.variant&&(t.content?.trim().length??0)>0},ie=`${re.canRegenerate?`r`:``}${re.canEdit?`e`:``}${re.canQuote?`q`:``}`,ae=Kp(t,ea)+O+`:${ie}`,A=i||s||h?null:Jp(Gi,t.id,ae);if(A){if(f.has(t.id)&&qi.get(t.id)===ae){let e=document.createElement(`div`);e.id=`wrapper-${t.id}`,e.setAttribute(`data-wrapper-id`,t.id),e.setAttribute(`data-persona-reuse`,`true`),l.appendChild(e)}else l.appendChild(A.cloneNode(!0));u&&p.set(t.id,ae),xr(t)&&t.toolCall?.id&&t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(y.add(t.toolCall.id),Rr(t));return}let j=null,se=d.find(e=>!!(t.variant===`reasoning`&&e.renderReasoning||t.variant===`tool`&&e.renderToolCall||!t.variant&&e.renderMessage)),ce=r.layout?.messages;if(xr(t)&&t.agentMetadata?.askUserQuestionAnswered===!0){Ji.delete(t.id),e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`);return}if(oi(t)&&di(r).enabled)return;if(xr(t)&&r.features?.askUserQuestion?.enabled!==!1){let e=d.find(e=>typeof e.renderAskUserQuestion==`function`);if(e&&Fr.current){let n=Ji.get(t.id),i=n!==ae,a=null;if(i){let{payload:n,complete:i}=Cr(t),o=t.id,s=()=>Fr.current?.getMessages().find(e=>e.id===o);a=e.renderAskUserQuestion({message:t,payload:n,complete:i,resolve:e=>{let t=s();t&&Fr.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=s();e?.agentMetadata?.awaitingLocalTool&&(Fr.current?.markAskUserQuestionResolved(e),Fr.current?.resolveAskUserQuestion(e,`(dismissed)`))},config:r})}if(i&&a===null&&n==null){t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(y.add(t.toolCall.id),Rr(t));return}let o=Po(t.id,t.role);o.setAttribute(`data-ask-plugin-stub`,`true`),o.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(o),x.push({messageId:t.id,fingerprint:ae,bubble:a});return}t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(y.add(t.toolCall.id),Rr(t));return}if(s){let n=C();if(!n){l.appendChild(Po(t.id,t.role));return}let i=d.find(e=>typeof e.renderApproval==`function`)??_,a=Xi.get(t.id)!==ae,o=null;if(a&&i?.renderApproval){let e=t.id,a=(t,n)=>{let r=Fr.current?.getMessages().find(t=>t.id===e);r?.approval&&(fl(r.approval)?Fr.current?.resolveWebMcpApproval(r.id,t):Fr.current?.resolveApproval(r.approval,t,n))};o=i.renderApproval({message:t,defaultRenderer:()=>n.createApprovalBubble(t,r,c),config:r,approve:e=>a(`approved`,e),deny:e=>a(`denied`,e)})}if(a&&o===null)e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),Xi.delete(t.id),j=n.createApprovalBubble(t,r,c);else{let e=Po(t.id,t.role);e.setAttribute(`data-approval-plugin-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),E.push({messageId:t.id,fingerprint:ae,bubble:o});return}}else if(se){if(t.variant===`reasoning`&&t.reasoning&&se.renderReasoning){if(!Te)return;j=se.renderReasoning({message:t,defaultRenderer:()=>Ug(t,r,o),config:r})}else if(t.variant===`tool`&&t.toolCall&&se.renderToolCall){if(!Ee)return;j=se.renderToolCall({message:t,defaultRenderer:()=>e_(t,r,a),config:r})}else se.renderMessage&&(j=se.renderMessage({message:t,defaultRenderer:()=>{let e=Yh(t,n,ce,r.messageActions,$e,{loadingIndicatorRenderer:m,widgetConfig:r,actionEligibility:re});return t.role!==`user`&&D(e,t,r,Q),e},config:r}))}if(!j&&h){let i=Kv(t);if(i){let a=Yi.get(t.id),o=a!==ae,s=r.wrapComponentDirectiveInBubble!==!1&&u_.getOptions(i.component)?.bubbleChrome!==!1,c=null;if(o){let a=Hv(i,{config:r,message:t,transform:n});if(a&&i.component===`PersonaArtifactInline`){let n=a.hasAttribute(`data-artifact-inline`)?a:a.querySelector(`[data-artifact-inline]`),r=n?.getAttribute(`data-artifact-inline`)??``,i=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(r):r,o=r?e.querySelector(`#wrapper-${t.id}`)?.querySelector(`[data-artifact-inline="${i}"]`)??null:null;n&&o&&o!==n&&b_()?.hasLiveInlineArtifactBlock(o)&&(n===a?a=o:n.replaceWith(o))}if(a){if(s){let e=document.createElement(`div`);if(e.className=[`persona-message-bubble`,`persona-rounded-2xl`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-p-4`].join(` `),e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-mb-3 persona-text-sm persona-leading-relaxed`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(a),c=e}else{let e=document.createElement(`div`);if(e.className=`persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch`,e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),e.setAttribute(`data-persona-component-directive`,`true`),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(a),c=e}}}if(c||a!=null){let e=Po(t.id,t.role);e.setAttribute(`data-component-directive-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),S.push({messageId:t.id,fingerprint:ae,bubble:c});return}}}if(!j){if(t.variant===`reasoning`&&t.reasoning){if(!Te)return;j=Ug(t,r,o)}else if(t.variant===`tool`&&t.toolCall){if(!Ee)return;j=e_(t,r,a)}else if(t.variant===`approval`&&t.approval){if(r.approval===!1)return;let e=C();if(!e)return;j=e.createApprovalBubble(t,r,c)}else{let e=r.layout?.messages;j=e?.renderUserMessage&&t.role===`user`?e.renderUserMessage({message:t,config:r,streaming:!!t.streaming}):e?.renderAssistantMessage&&t.role===`assistant`?e.renderAssistantMessage({message:t,config:r,streaming:!!t.streaming}):Yh(t,n,e,r.messageActions,$e,{loadingIndicatorRenderer:m,widgetConfig:r,actionEligibility:re}),t.role!==`user`&&j&&D(j,t,r,Q)}}let le=Po(t.id,t.role);le.appendChild(j),Yp(Gi,t.id,ae,le),l.appendChild(le),u&&p.set(t.id,ae)}),it.composerOverlay&&it.composerOverlay.querySelectorAll(`[data-persona-ask-sheet-for]`).forEach(e=>{let t=e.getAttribute(`data-persona-ask-sheet-for`);t&&!y.has(t)&&Zr(it.composerOverlay,t)}),r.features?.toolCallDisplay?.grouped){let e=[],n=[],o=r.features.toolCallDisplay.groupedMode===`summary`;t.forEach(t=>{if(t.variant===`tool`&&t.toolCall&&Ee){if(ae&&t.toolCall.status===`complete`&&!t.toolCall.interrupted)return;n.push(t)}else(t.variant!==`reasoning`||Te&&(t.reasoning?.status!==`complete`||!ie(t.reasoning)))&&((n.length>1||o&&n.length>0)&&e.push(n),n=[])}),(n.length>1||o&&n.length>0)&&e.push(n),e.forEach(e=>{let t=e.map(e=>Array.from(l.children).find(t=>t instanceof HTMLElement&&t.getAttribute(`data-wrapper-id`)===e.id)).filter(e=>!!e);if(t.length<(o?1:2))return;let n=Po(`tool-group-${e[0].id}`,`assistant`);if(n.setAttribute(`data-persona-tool-group-row`,`true`),r.features?.toolCallDisplay?.groupedMode===`collapsible`){let o=`tool-group-${e[0].id}`,c=e.some(e=>e.toolCall?.status!==`complete`),l={...e[0],id:o,toolCall:{id:o,name:`${e.length} tools`,status:c?`running`:`complete`,chunks:e.flatMap(e=>e.toolCall?.chunks??[]),success:!e.some(e=>e.toolCall?.success===!1),interrupted:!c&&e.some(e=>e.toolCall?.interrupted)}};i.add(o),s.observe(l,`tool`,a,r.features.toolCallDisplay);let u=l.toolCall?.interrupted?`${e.length} tools · Interrupted`:`${c?`Using`:`Used`} ${e.length} tools`,d=r.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall),defaultSummary:u,config:r}),f=Ol(l,r,a.has(o),d??u);f.bubble.classList.add(`persona-tool-group`),f.body.dataset.personaToolGroupStack=`true`,t[0].before(n),n.appendChild(f.bubble),t.forEach((e,t)=>{e.style.setProperty(`--persona-message-row-max-width`,`100%`),e.style.setProperty(`--persona-activity-stagger`,`${t*40}ms`),e.classList.add(`persona-activity-group-child`),f.body.appendChild(e)});return}let c=document.createElement(`div`);c.className=`persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2`,c.setAttribute(`data-persona-tool-group`,`true`);let u=document.createElement(`div`);u.className=`persona-tool-group-summary persona-text-xs persona-text-persona-muted`,u.id=`tool-group-summary-${e[0].id}`;let d=`${e.length} ${e.length===1?`tool`:`tools`}`,f=e.some(e=>e.toolCall?.interrupted)?`${d} · Interrupted`:`Called ${d}`,p=r.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall).filter(e=>!!e),defaultSummary:f,config:r});h(u,p)||(u.textContent=f);let m=document.createElement(`div`);m.className=`persona-tool-group-stack persona-flex persona-flex-col`,m.id=`tool-group-stack-${e[0].id}`,m.setAttribute(`data-persona-tool-group-stack`,`true`),c.appendChild(u),o||c.appendChild(m),n.appendChild(c),t[0].before(n),t.forEach((e,n)=>{if(o){e.remove();return}e.style.setProperty(`--persona-message-row-max-width`,`100%`);let r=document.createElement(`div`);r.className=`persona-tool-group-item persona-relative`,r.setAttribute(`data-persona-tool-group-item`,`true`),n<t.length-1&&r.setAttribute(`data-persona-tool-group-connector`,`true`),r.appendChild(e),m.appendChild(r)})})}s.prune(i),Xp(Gi,g);let A=e=>e.variant===`tool`&&!Ee||e.variant===`reasoning`&&!Te||oe(e),j=t.some(e=>e.role===`assistant`&&e.streaming&&!A(e)),se=t.length-1;for(;se>=0&&A(t[se]);)se--;let ce=se>=0?t[se]:void 0,le=se<t.length-1,ue=ce?.role===`assistant`&&!ce.streaming&&ce.variant!==`approval`&&!le;if(Wi&&t.some(e=>e.role===`user`)&&!j&&!ue){let e={config:r,streaming:!0,location:`standalone`,defaultRenderer:zh},t=d.find(e=>e.renderLoadingIndicator),n=null;if(t?.renderLoadingIndicator&&(n=t.renderLoadingIndicator(e)),n===null&&r.loadingIndicator?.render&&(n=r.loadingIndicator.render(e)),n===null&&(n=zh()),n){let e=document.createElement(`div`),t=r.loadingIndicator?.showBubble!==!1,i=r.layout?.messages?.layout??`bubble`;e.className=t?Uh(`assistant`,i).join(` `):[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-text`].join(` `),e.setAttribute(`data-typing-indicator`,`true`),t&&(e.style.color=`var(--persona-message-assistant-text, var(--persona-text))`,i!==`flat`&&(e.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,e.style.borderColor=`var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))`)),e.appendChild(n);let a=Po(`typing-indicator`,`assistant`);a.appendChild(e),l.appendChild(a)}}if(!Wi&&t.length>0){let e=t[t.length-1],n={config:r,lastMessage:e,messageCount:t.length},i=d.find(e=>e.renderIdleIndicator),a=null;if(i?.renderIdleIndicator&&(a=i.renderIdleIndicator(n)),a===null&&r.loadingIndicator?.renderIdle&&(a=r.loadingIndicator.renderIdle(n)),a){let e=document.createElement(`div`);e.className=r.loadingIndicator?.showBubble===!1?[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-primary`].join(` `):[`persona-rounded-2xl`,`persona-text-sm`,`persona-leading-relaxed`,`persona-shadow-sm`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-text-persona-primary`,`persona-px-5`,`persona-py-3`].join(` `),e.setAttribute(`data-idle-indicator`,`true`),e.appendChild(a);let t=Po(`idle-indicator`,`assistant`);t.appendChild(e),l.appendChild(t)}}ru(l),Bp(e,l),qi=p;for(let t of Array.from(e.querySelectorAll(`:scope > [data-persona-reuse]`))){let e=Gi.get(t.getAttribute(`data-wrapper-id`)??``);e?t.replaceWith(e.wrapper.cloneNode(!0)):t.remove()}if(au(e),ne){let{messageId:t,element:n}=ne,r=e.querySelector(`#wrapper-${t}`);r&&n.parentElement!==r&&(No(r,v.get(t)??`user`),r.replaceChildren(n))}if(x.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of x){let i=e.querySelector(`#wrapper-${t}`);i&&(No(i,v.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),Ji.set(t,n)))}if(Ji.size>0)for(let e of Ji.keys())g.has(e)||Ji.delete(e);if(S.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of S){let i=e.querySelector(`#wrapper-${t}`);i&&(No(i,v.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),Yi.set(t,n)))}if(Yi.size>0)for(let e of Yi.keys())g.has(e)||Yi.delete(e);if(E.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of E){let i=e.querySelector(`#wrapper-${t}`);i&&(No(i,v.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),Xi.set(t,n)))}if(Xi.size>0)for(let e of Xi.keys())g.has(e)||Xi.delete(e)},Io=!1,Lo=()=>{Io||(Io=!0,Ni().catch(()=>{}),Ut().catch(()=>{Io=!1}))},zo=(e,t,n)=>{t.length>0&&Lo(),Fo(e,t,n),yr()},Bo=null,Vo=()=>{if(Bo)return;let t=e=>{let t=e.composedPath();t.includes(F)||rt&&t.includes(rt)||$o(!1,`user`)};Bo=t,(e.ownerDocument??document).addEventListener(`pointerdown`,t,!0)},Ho=()=>{Bo&&=((e.ownerDocument??document).removeEventListener(`pointerdown`,Bo,!0),null)};Z.push(()=>Ho());let Uo=null,Wo=()=>{if(Uo)return;let t=e=>{e.key===`Escape`&&(e.isComposing||$o(!1,`user`))};Uo=t,(e.ownerDocument??document).addEventListener(`keydown`,t,!0)},Go=()=>{Uo&&=((e.ownerDocument??document).removeEventListener(`keydown`,Uo,!0),null)};Z.push(()=>Go());let Ko=!1,qo=/* @__PURE__ */ new Set,Jo=()=>r.launcher?.composerBar?.peek?.streamAnimation||r.features?.streamAnimation,Yo=()=>{if(!N())return;let t=it.peekBanner,n=it.peekTextNode;if(!t||!n)return;if(P){t.classList.remove(`persona-pill-peek--visible`);return}let r=Q?.getMessages()??[],i;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.role===`assistant`&&t.content){i=t;break}}if(!i){t.classList.remove(`persona-pill-peek--visible`);return}let a=i.content,o=!!i.streaming,s=Jo(),c=cm(s),l=c.type===`none`?null:Si(c.type,s?.plugins),u=l?.isAnimating?.(i)===!0,d=l!==null&&(o||u);d&&l&&!qo.has(l.name)&&(jm(l,e),qo.add(l.name));let f=d&&l?.containerClass?l.containerClass:null,p=n.dataset.personaPeekStreamClass??null;p&&p!==f&&(n.classList.remove(p),delete n.dataset.personaPeekStreamClass),f&&p!==f&&(n.classList.add(f),n.dataset.personaPeekStreamClass=f),d?(n.style.setProperty(`--persona-stream-step`,`${c.speed}ms`),n.style.setProperty(`--persona-stream-duration`,`${c.duration}ms`)):(n.style.removeProperty(`--persona-stream-step`),n.style.removeProperty(`--persona-stream-duration`));let m=d?gm(a,c.buffer,l,i,o):a;if(d&&c.placeholder===`skeleton`&&o&&(!m||!m.trim())){let e=document.createElement(`div`),t=Tm();t.classList.add(`persona-pill-peek__skeleton`),e.appendChild(t),Bp(n,e)}else{let e=Math.max(0,m.length-100),r=m.length>100?m.slice(-100):m,a=Rl(r);if(!d||!l){let e=m.length>100?`…${r}`:r;n.textContent!==e&&(n.textContent=e)}else{let o=a;(l.wrap===`char`||l.wrap===`word`)&&(o=Cm(a,l.wrap,`peek-${i.id}`,{skipTags:l.skipTags,startIndex:e}));let s=document.createElement(`div`);if(s.innerHTML=o,l.useCaret&&r.length>0){let e=wm(),t=s.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];n?.parentNode?n.parentNode.insertBefore(e,n.nextSibling):s.appendChild(e)}Bp(n,s),l.onAfterRender?.({container:n,bubble:t,messageId:i.id,message:i,speed:c.speed,duration:c.duration})}}let h=Wi||Ko;t.classList.toggle(`persona-pill-peek--visible`,h)};if(N()){let e=it.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),$o(!0,`user`)};e.addEventListener(`pointerdown`,t),Z.push(()=>{e.removeEventListener(`pointerdown`,t)})}let t=()=>{Ko||(Ko=!0,Yo())},n=()=>{Ko&&(Ko=!1,Yo())};I.addEventListener(`pointerenter`,t),I.addEventListener(`pointerleave`,n),Z.push(()=>{I.removeEventListener(`pointerenter`,t),I.removeEventListener(`pointerleave`,n)}),rt&&(rt.addEventListener(`pointerenter`,t),rt.addEventListener(`pointerleave`,n),Z.push(()=>{rt.removeEventListener(`pointerenter`,t),rt.removeEventListener(`pointerleave`,n)}))}let Xo=e=>{let t=r.launcher?.composerBar??{},n=t.expandedSize??`anchored`,i=t.bottomOffset??`16px`,a=t.collapsedMaxWidth,o=t.expandedMaxWidth??`880px`,s=t.expandedTopOffset??`5vh`,c=t.modalMaxWidth??`880px`,l=t.modalMaxHeight??`min(90vh, 800px)`,u=`calc(100vw - 32px)`,d=F.style;if(d.left=``,d.right=``,d.top=``,d.bottom=``,d.transform=``,d.width=``,d.maxWidth=``,d.height=``,d.maxHeight=``,rt){let e=rt.style;e.bottom=i,e.width=a??``}e&&n!==`fullscreen`&&(n===`modal`?(d.top=`50%`,d.left=`50%`,d.transform=`translate(-50%, -50%)`,d.bottom=`auto`,d.right=`auto`,d.width=c,d.maxWidth=u,d.maxHeight=l,d.height=l):(d.left=`50%`,d.transform=`translateX(-50%)`,d.bottom=`calc(${i} + var(--persona-pill-area-height, 80px))`,d.top=s,d.width=o,d.maxWidth=u))},Zo=()=>{if(P&&Lo(),!be())return;if(N()){let e=(r.launcher?.composerBar??{}).expandedSize??`anchored`,t=P?`expanded`:`collapsed`;F.dataset.state=t,F.dataset.expandedSize=e,rt&&(rt.dataset.state=t,rt.dataset.expandedSize=e),F.style.removeProperty(`display`),F.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),I.classList.remove(`persona-scale-95`,`persona-opacity-0`,`persona-scale-100`,`persona-opacity-100`),Xo(P),L.style.display=P?`flex`:`none`,Tr(),P?(Vo(),Wo()):(Ho(),Go()),Yo();return}let t=Bm(r),n=e.ownerDocument.defaultView??window,i=r.launcher?.mobileBreakpoint??640,a=r.launcher?.mobileFullscreen??!0,o=n.innerWidth<=i,s=a&&o&&M,c=Hm(r).reveal;P?(F.style.removeProperty(`display`),F.style.display=t?`flex`:``,F.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),I.classList.remove(`persona-scale-95`,`persona-opacity-0`),I.classList.add(`persona-scale-100`,`persona-opacity-100`),Su?(Su.setPanelOpen(!0),Su.element.style.display=`none`):Cu&&(Cu.style.display=`none`)):(t?t&&(c===`overlay`||c===`push`)&&!s?(F.style.removeProperty(`display`),F.style.display=`flex`,F.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),I.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(F.style.setProperty(`display`,`none`,`important`),F.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),I.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(F.style.display=``,F.classList.add(`persona-pointer-events-none`,`persona-opacity-0`),I.classList.remove(`persona-scale-100`,`persona-opacity-100`),I.classList.add(`persona-scale-95`,`persona-opacity-0`)),Su?(Su.setPanelOpen(!1),Su.element.style.display=t?`none`:``):Cu&&(Cu.style.display=t?`none`:``))},$o=(t,n=`user`)=>{if(!be()||P===t)return;let i=P;P=t,Zo();let a=(()=>{let t=r.launcher?.sidebarMode??!1,n=e.ownerDocument.defaultView??window,i=r.launcher?.mobileFullscreen??!0,a=r.launcher?.mobileBreakpoint??640,o=n.innerWidth<=a,s=Bm(r)&&i&&o,c=N()&&(r.launcher?.composerBar?.expandedSize??`fullscreen`)===`fullscreen`;return t||i&&o&&M||s||c})();if(P&&a){if(!_i){let t=e.getRootNode(),n=t instanceof ShadowRoot?t.host:e.closest(`.persona-host`);n&&(_i=Fm(n,r.launcher?.zIndex??1e5))}vi||=Rm(e.ownerDocument)}else P||(_i?.(),_i=null,vi?.(),vi=null);P&&(Ou(),_o()||(Nt()===`follow`?co(!0):po()));let o={open:P,source:n,timestamp:Date.now()};P&&!i?O.emit(`widget:opened`,o):!P&&i&&O.emit(`widget:closed`,o),O.emit(`widget:state`,{open:P,launcherEnabled:M,voiceActive:$.active,streaming:Q.isStreaming()})},es={inputDisabled:!1,sendDisabled:!1},is=()=>es.inputDisabled,os=()=>Al(r.voiceRecognition?.provider)&&!!Q&&(Q.isBargeInActive()||[`listening`,`processing`,`speaking`].includes(Q.getVoiceStatus())),us=()=>es.inputDisabled||es.sendDisabled,ps=()=>(es.inputDisabled?es.inputReason:void 0)??(es.sendDisabled?es.sendReason:void 0);function ms(){if(!V)return;if(G.getState().phase===`streaming`){V.disabled=!1;return}let e=dn?!dn.isReady():!1;V.disabled=us()||e}function gs(){if(!wt)return;let e=G.getState(),t=r.sendButton?.visibility===`when-text`&&e.phase!==`streaming`&&e.text.trim().length===0&&e.attachments.length===0;wt.toggleAttribute(`data-persona-send-hidden`,t)}function vs(){let e=ps();if(N()){let t=ct??bt;e?t.setAttribute(`title`,e):t.removeAttribute(`title`),bt.toggleAttribute(Zv,!!e)}else if(e)lt.setAttribute(`role`,`status`),lt.setAttribute(`aria-live`,`polite`),lt.setAttribute(Zv,``),lt.removeAttribute(Qv),lt.textContent=e,Ga(lt,r.statusIndicator??{},`idle`);else if(lt.hasAttribute(Zv)&&(lt.removeAttribute(`role`),lt.removeAttribute(`aria-live`),lt.removeAttribute(Zv),m)){let e=Q.getStatus();tt(lt,et(e),r.statusIndicator??{},e)}}function ys(){let e=ls(r.composer?.inputDisabled),t=ls(r.composer?.sendDisabled);es={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},G.setInputDisabled(e.disabled),G.setSendDisabled(t.disabled);let n=G.getState().phase===`streaming`,i=e.disabled,a=n||i;B&&(B instanceof HTMLTextAreaElement?B.disabled=i:B.setAttribute(`contenteditable`,i?`false`:`true`),B.setAttribute(`aria-disabled`,i?`true`:`false`)),Dt&&(Dt.disabled=i),kt&&(kt.disabled=i);for(let e of fn?.affordanceButtons??[])e.querySelectorAll(`button`).forEach(e=>{e.disabled=i});U&&(U.disabled=i||n&&!os()),Di.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute(`data-disabled`,a),e instanceof HTMLButtonElement||e.setAttribute(`aria-disabled`,a?`true`:`false`)}),e.buttons.forEach(e=>{e.disabled=a})}),zs.forEach(e=>{e.toggleAttribute(`data-disabled`,a),e instanceof HTMLButtonElement?e.disabled=a:e.setAttribute(`aria-disabled`,a?`true`:`false`),e.querySelectorAll(`button`).forEach(e=>{e.disabled=a})}),bt.dataset.personaComposerStreaming=n?`true`:`false`,bt.dataset.personaComposerInputDisabled=i?`true`:`false`,bt.dataset.personaComposerSendDisabled=us()?`true`:`false`,bt.querySelectorAll(`[data-persona-composer-disable-when-streaming]`).forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=n)}),ms(),vs()}let bs=e=>{G.setStreaming(e),Tt(e?`stop`:`send`),ys()},xs=()=>{$.active||B&&B.focus()};O.on(`widget:opened`,()=>{r.autoFocusInput&&setTimeout(()=>xs(),200)});let Cs=null,ws=!1,Ts=!ut.hidden,Ds=null,Os=!re,ks=null;Z.push(()=>{ks?.cancel(),ks=null});let js=t=>{let n=hg(t);if(n===nn)return;nn=n,e.setAttribute(`data-persona-conversation-state`,n);let r=an();ln(),Os&&(ks?.cancel(),ks=ug(bt,n===`active`?r:an(),n===`active`?`drop`:`rise`,tn().layout===`centered`?320:260)),Eo()},Ms=null,Ns,Ps=null,Fs=null,Is=!1,Ls=e=>{let t=tn(),n=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??`bottom`}|${t.align??``}|${t.iconPlacement}|${t.kicker??``}|${t.title}|${t.subtitle}`;(n!==Ms||t.icon!==Ns)&&(Ms=n,Ns=t.icon,eg({host:ut,iconHolder:dt,kicker:pt,title:mt,subtitle:ht,starterSuggestions:at},t));let i=t.message===void 0?null:`${r.layout?.messages?.layout??`bubble`}|${t.message}`;i!==Ps&&(Ps=i,sg(ft,t.message,r));let a=e??(Q?Q.getMessages():r.initialMessages);js(a);let o=ws,s=!o&&gg(t,a),c=s!==Ts;if(Ts=s,Fs){Ds?.cancel(),Ds=null,o!==Is&&(Is=o,o?ag(R,ut,null):ig(R,ut,Fs)),$h(R,ut,!o);return}if(c&&!s&&!o&&t.dismiss===`on-first-message`&&Os){Ds=lg(ut,e=>{Ds===e&&(Ds=null),!Ts&&!Fs&&($h(R,ut,!1),Eo()),e?.cancel()});return}if(Ds){if(!s&&!o)return;Ds.cancel(),Ds=null}let l=!ut.hidden;$h(R,ut,s),!s&&l&&Eo()},Rs=[],zs=[],Bs=!1,Vs=null,Hs,Ws=()=>{zs.length=0;let e=Rs.splice(0,Rs.length);for(let t of e)try{t()}catch(e){console.warn(`[persona] renderWelcome cleanup threw`,e)}};Z.push(Ws);let Ks=(e,t)=>{let n=Wm(e,t);if(!n)return r.debug===!0&&console.warn(`[persona] renderStarter received a suggestion with no label`),q(`span`);let i=r.suggestions?.starters,a=Jm({item:{...n,behavior:n.behavior??i?.behavior??`send`},index:t,surface:`starter`,source:`config`,variant:i?.variant??`card`,streaming:m?Q.isStreaming():!1,config:r,plugins:d,chipsConfig:r.suggestionChipsConfig,session:Q,getTextarea:()=>B,eventTarget:ut,submitPrompt:ml});return zs.push(a),a},qs=()=>{if(Bs)return;Bs=!0;let e=tn();Vs=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`,Hs=e.icon;try{Ws(),ag(R,ut,Fs),Fs=null,Is=!1;let t=Q?Q.getMessages():r.initialMessages,n=gg(e,t),i=0,a=null;for(let t of d)if(t.renderWelcome&&(a=t.renderWelcome({config:e,variant:e.variant,visible:n,defaultRenderer:()=>ut,sendMessage:e=>{if(!Q||Q.isStreaming())return;let t=e.trim();t&&Q.sendMessage(t)},requestRender:()=>qs(),renderStarter:e=>Ks(e,i++),storage:h(t.id),onCleanup:e=>{Rs.push(e)}}),a))break;a&&a!==ut&&(Fs=a,ig(R,ut,a))}finally{Bs=!1}Ls()},Js=()=>{let e=tn();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`!==Vs||e.icon!==Hs)&&qs()},Ys=()=>{Ls(),Gn||(B.placeholder=Sf(G.getState().activeModeIds,r.composer?.modes)??r.copy?.inputPlaceholder??`How can I help...`,!(r.sendButton?.useIcon??!1)&&!Q?.isStreaming()&&(V.textContent=r.copy?.sendButtonLabel??`Send`)),B.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,B.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`},Xs=!!r.setStoredConversationId,Zs=e=>ue(t=>{let n={...t};return delete n[e],n}),Qs=e=>{let t=te[e];return typeof t==`string`?t:null},$s=()=>{let e=te.durableResume;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.executionId==`string`&&t.executionId.length>0&&typeof t.after==`string`&&t.after.length>0?{executionId:t.executionId,after:t.after}:null};r.clientToken&&(r={...r,getStoredSessionId:()=>Qs(`sessionId`),setStoredSessionId:e=>{ue(t=>({...t,sessionId:e}))},clearStoredSessionId:r.clearStoredSessionId??(()=>Zs(`sessionId`)),getStoredConversationId:r.getStoredConversationId??(()=>Qs(`conversationId`)),setStoredConversationId:r.setStoredConversationId??(e=>{ue(t=>({...t,conversationId:e}))}),clearStoredConversationId:r.clearStoredConversationId??(()=>Zs(`conversationId`))});let ec=()=>r.clientToken??null,tc=e=>Nv(e,Ae(),r.persistState===!1),nc=ec(),rc=nc?tc(nc):null,ic=()=>{let e=te.pendingDisplayProjections;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.conversationId!=`string`||!Array.isArray(t.messageIds)?null:{conversationId:t.conversationId,messageIds:t.messageIds.filter(e=>typeof e==`string`)}},ac={...rc?{visitorStore:rc}:{},historyBootstrapReady:r.features?.history?.enabled===!0&&!dl()?Promise.all([ae,A]).then(()=>{}):ae,getStoredMessageCursor:()=>Qs(`historyMessageCursor`),setStoredMessageCursor:e=>{e===null?Zs(`historyMessageCursor`):ue(t=>({...t,historyMessageCursor:e}))},getPendingDisplayProjections:ic,setPendingDisplayProjections:e=>{e?ue(t=>({...t,pendingDisplayProjections:e})):Zs(`pendingDisplayProjections`)},getStoredResumableHandle:$s,setStoredResumableHandle:e=>{e?ue(t=>({...t,durableResume:e})):Zs(`durableResume`)},shouldResumeDurableConversation:()=>ee&&$s()!==null,...Xs?{}:{getStoredConversationRevision:()=>Qs(`conversationRevision`),setStoredConversationRevision:e=>{e===null?Zs(`conversationRevision`):ue(t=>({...t,conversationRevision:e}))}}};if(ee){let t=r.onExecutionState,n=e.ownerDocument.defaultView,i=!1,a=()=>i=!0,o=()=>i=!1;n?.addEventListener(`pagehide`,a),n?.addEventListener(`pageshow`,o),Z.push(()=>{n?.removeEventListener(`pagehide`,a),n?.removeEventListener(`pageshow`,o)}),r={...r,reconnectStream:r.reconnectStream??(e=>Q.getClient().reconnectClientTokenStream(e)),onExecutionState:e=>{(e||!i)&&ac.setStoredResumableHandle?.(e?{executionId:e.executionId,after:e.lastEventId}:null),t?.(e)}}}let oc=()=>{let e=ec();if(e&&rc?.matches(e,Ae(),r.persistState===!1)||!e&&!rc)return;rc?.destroy(),rc=e?tc(e):null;let t={...ac};rc?t.visitorStore=rc:delete t.visitorStore,ac=t,Q.setHistoryInternals(ac)},sc=null,cc=()=>{sc??=setInterval(()=>{let e=z.querySelectorAll(`[data-tool-elapsed]`);if(e.length===0){clearInterval(sc),sc=null;return}let t=Date.now();e.forEach(e=>{let n=Number(e.getAttribute(`data-tool-elapsed`));n&&(e.textContent=e.closest(`.persona-activity-row`)?Tl(t-n):Vn(t-n))})},100)},lc=e=>e.role===`user`||e.variant===`approval`||e.agentMetadata?.awaitingLocalTool===!0||xr(e),uc=(e,t)=>{if(t.length<e.length)return!1;for(let n=0;n<t.length;n+=1){let r=t[n];if(r!==e[n]){if(lc(r))return!1;r.role===`assistant`&&r.streaming&&Ki.add(r.id)}}return!0},dc=null,fc=null,pc=null,mc=null,hc=e=>{if(!ee)return Ra(e);mc=e,queueMicrotask(()=>{mc===e&&(mc=null,Ra(fc??e))})},gc=e=>{dc=e;let t,n;for(let r=e.length-1;r>=0;--r){let i=e[r];if(!t&&i.role===`user`&&(t=i),!n&&i.role===`assistant`&&(n=i),t&&n)break}zo(z,e,we),b_()?.updateInlineArtifactBlocks(z,Or.artifacts,{suppressTransition:Wi}),cc(),Ls(e),Vi(e),co(!Wi),Mo(e),e.length===0&&(So(),pa=!0,ma=!1,ha=null,ga=!1),!ua||da?(ua=!0,fa=t?.id??null,va=n?.id??null):t&&t.id!==fa?(fa=t.id,Oo(t.id)):n&&n.id!==va&&ko(),n&&(va=n.id),jo(e);let r=$.lastUserMessageId;t&&t.id!==r&&($.lastUserMessageId=t.id,O.emit(`user:message`,t)),$.lastUserMessageWasVoice=!!t?.viaVoice,hc(e),Yo()},_c=()=>{pc!==null&&(cancelAnimationFrame(pc),pc=null);let e=fc;fc=null,e&&gc(e)},vc=()=>{pc!==null&&cancelAnimationFrame(pc),pc=null,fc=null},yc=e=>{if(e.length===0){vc(),gc(e);return}let t=fc??dc;Wi&&t&&uc(t,e)?(fc=e,pc===null&&(pc=requestAnimationFrame(()=>{pc=null;let e=fc;fc=null,e&&gc(e)}))):(_c(),gc(e))};Q=new vd(r,{onMessagesChanged(e){yc(e)},onStatusChanged(e){let t=r.statusIndicator??{};tt(lt,(e=>e===`idle`?t.idleText??gi.idle:e===`connecting`?t.connectingText??gi.connecting:e===`connected`?t.connectedText??gi.connected:e===`error`?t.errorText??gi.error:e===`paused`?t.pausedText??gi.paused:e===`resuming`?t.resumingText??gi.resuming:gi[e])(e),t,e),Ze()},onStreamingChanged(e){e||(Q?.getMessages().length===0?vc():_c()),Wi=e,bs(e),Ze(),Q&&zo(z,Q.getMessages(),we),e||(co(!0),xo(),zi=!0,Q&&Bi(Q.getMessages(),di(r))),ao(),$t(e?`Responding…`:`Response complete.`),Yo()},onVoiceStatusChanged(e){if(O.emit(`voice:status`,{status:e,timestamp:Date.now()}),e!==`disconnected`&&!Al(r.voiceRecognition?.provider))return;let t=Q.getVoiceNotice();switch(t&&el(t,1e4),e){case`listening`:if(!Ca){let e=Q.getVoiceDisclosure();e&&(Ca=!0,N()?(wa=B.placeholder,B.placeholder=e,$t(e)):el(e,1e4))}ou(),tu();break;case`processing`:ou(),nu();break;case`speaking`:ou(),iu();break;default:e===`idle`&&Q.isBargeInActive()?(ou(),tu(),U?.setAttribute(`aria-label`,`End voice session`)):($.active=!1,Ca=!1,wa!==null&&(B.placeholder=wa,wa=null),ou(),Aa(`system`),ka||ja())}},onArtifactsState(e){Or=e,e.artifacts.length===0&&(Mr=!1),b_()?.updateInlineArtifactBlocks(z,e.artifacts,{suppressTransition:Wi}),si(),Ra()},onHistoryStateChanged(e){Ye(e)},onHistoryNotice(e){Xe(e)},onReconnect(e){let{executionId:t,lastEventId:n}=e.handle;e.phase===`paused`?O.emit(`stream:paused`,{executionId:t,after:n}):e.phase===`resuming`?O.emit(`stream:resuming`,{executionId:t,after:n,attempt:e.attempt??1}):O.emit(`stream:resumed`,{executionId:t,after:n})}},ac),Fr.current=Q,Z.push(()=>Q.cancel()),Z.push(()=>{Q.destroy(),rc?.destroy(),rc=null});let bc=null;if(Q.onReadAloudChange((e,t)=>{hr=e,gr=t,yr();let n=e??bc;e&&(bc=e);let r=n?Q.getMessages().find(e=>e.id===n)??null:null;O.emit(`message:read-aloud`,{messageId:n,message:r,state:t,timestamp:Date.now()}),t===`idle`&&(bc=null)}),m=!0,ua=!0,r.voiceRecognition?.enabled===!0&&Al(r.voiceRecognition.provider))try{Q.setupVoice()}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Runtype voice setup failed:`,e)}let xc=null,Sc=null,Cc=!1,wc=Q.getHistoryState(),Tc=()=>r.features?.history?.enabled===!0,Ec=e=>{e&&(Xt.textContent=``,Xt.textContent=e)},Dc=()=>{p.forEach(e=>e()),p=[];let t=xc,n=t?.railCollapseShortcut();t&&n&&p.push(f.register({id:`history-rail-collapse`,combo:n.combo,scope:r.features?.history?.rail?.collapseShortcutScope===`page`?`page`:`widget`,when:()=>Ge&&Ke===`rail`&&t.railCollapsible()||t.railTriggerApplies(),run:()=>t.railOverlayMode()?t.toggleRailPinned():t.toggleRailCollapsed()}));for(let t of r.layout?.header?.trailingActions??[])t.shortcut&&p.push(f.register({id:`header-action-${t.id}`,combo:t.shortcut,run:()=>{let n=e.querySelector(`[data-persona-header-action="${t.id}"]`);n?n.click():r.layout?.header?.onAction?.(t.id)}}));for(let e of d)for(let t of e.shortcuts??[])p.push(f.register({...t,id:`${e.id}:${t.id}`}))};Dc();let Oc=null,kc=!1,Ac=()=>{if(!_t)return;let e=r.layout?.header?.titleSource===`conversation`,t=e&&Oc?.trim()||null;_t.textContent=t??r.launcher?.title??`Chat Assistant`;let n=_t.closest(`.persona-combo-btn`);if(!n)return;let i=!e||Q.getActiveConversationId()!==null;n.setAttribute(`data-persona-menu-locked`,i?`false`:`true`),n.setAttribute(`aria-haspopup`,i?`true`:`false`),i||n.setAttribute(`aria-expanded`,`false`),n.style.cursor=i?`pointer`:`default`;let a=n.querySelector(`svg`);a&&(a.style.display=i?``:`none`)},jc=e=>{e!==Oc&&(Oc=e,Ac())},Mc=e=>{kc=e?.starred===!0,jc(e&&e.title.trim()||null),Ac()};Ac(),L.addEventListener(`persona:title-menu-builtin`,e=>{let t=e.detail?.actionId,n=Q.getActiveConversationId();n&&(t===`delete`?Ic(e=>e.requestDeleteConversation(n)):t===`star`&&Q.canUpdateConversations()&&Ic(e=>e.updateHistoryConversation(n,{starred:!kc})).catch(()=>{}))}),Ye=e=>{wc=e,xc?.historySurface?.view.setNewConversationRequired(e.recovery===`new_conversation_required`),bs(e.sendBlocked||Wi),xc?.syncEarlierMessagesPill()},Xe=e=>{(e.code===`history_continuity_reset`||e.code===`conversation_deleted_recovered`)&&(Gi.clear(),So(),so()),Ec(e.message),xc?.historySurface?.view.refresh()};let Nc={get actionManager(){return pe},get activeConversationTitle(){return Oc},announceHistory:Ec,get applyRailChrome(){return Je},set applyRailChrome(e){Je=e},get artifactSplitRoot(){return Wr},get body(){return R},get config(){return r},get container(){return L},get conversationOpenPendingEl(){return Cs},set conversationOpenPendingEl(e){Cs=e},get conversationOpenTakeover(){return ws},set conversationOpenTakeover(e){ws=e},currentKeyPrefix:Ae,destroyCallbacks:Z,eventBus:O,get footer(){return bt},get header(){return yt},get historyChromeSync(){return Ze},set historyChromeSync(e){Ze=e},historyFeatureEnabled:Tc,get historyInternals(){return ac},set historyInternals(e){ac=e},get historyPresentation(){return Ke},set historyPresentation(e){Ke=e},get historySessionState(){return wc},get historyVisible(){return Ge},set historyVisible(e){Ge=e},get isStreaming(){return Wi},jumpToBottomInstant:po,get lastAppliedMessages(){return dc},set lastAppliedMessages(e){dc=e},get launcherEnabled(){return M},get launcherSurfaceInstance(){return Su},maybeFocusInput:xs,messageCache:Gi,get messagesWrapper(){return z},mount:e,get open(){return P},panel:I,panelElements:it,get persistentMetadata(){return te},set persistentMetadata(e){te=e},plugins:d,get reapplyHistoryHostChrome(){return qe},set reapplyHistoryHostChrome(e){qe=e},repinAnchoredMessage:Eo,resetAnchorState:So,restoreScrollPosition:_o,resumeAutoScroll:so,runStorageMutation:La,get session(){return Q},setActiveConversationSummary:Mc,storageAdapter:k,get suppressScrollSend(){return da},set suppressScrollSend(e){da=e},syncScrollToBottomButton:ao,updateWelcome:Ls,getHistoryProviderFactory:Lv,historyErrors:{HistoryClientError:yu,HistoryProviderError:Du},isDockedMountMode:Bm,renderLucideIcon:K,loadHistoryView:Iv,createHeaderIconButton:eh,attachTooltip:Ea},Pc=e=>(!xc&&!Cc&&(xc=e.createHistoryShell(Nc),xc.railCollapseShortcut()&&Dc()),xc),Fc=()=>{if(xc)return Promise.resolve(xc);let e=dl();return e?Promise.resolve(Pc(e)):(Sc??=ll().then(Pc,e=>{throw Sc=null,e}),Sc)},Ic=e=>{let t=dl(),n=xc??(t?Pc(t):null);return n?e(n):Fc().then(t=>{if(!t)throw Error(`[AgentWidget] The widget was destroyed`);return e(t)})},Lc=()=>{xc?.syncHistoryPresentation()};Z.push(()=>{Cc=!0}),Tc()&&Fc().catch(()=>{}).finally(oe),r.clientToken&&(r.features?.history?.enabled===!0||r.sessionInit===`mount`)&&Q.initClientSession().then(()=>{let e=xc;if(e?.historyAvailable())return Q.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{xc?.syncEarlierMessagesPill()}).catch(e=>{r.debug&&console.warn(`[AgentWidget] Pre-init client session failed:`,e)});let zc=()=>Q.warmClientSession(),Bc=e=>{let t=r.sessionInit??`input`,n=Jn?.input??B,i=e.target;n&&(e.type===`input`?(t===`input`||t===`focus`)&&i===n&&e.inputType&&n.value.trim():t===`focus`&&(e.type===`keyup`?i===n&&e.key===`Tab`:(Jn?.form??ct)?.contains(i)))&&zc()},Vc=[`input`,`pointerdown`,`keyup`];Vc.forEach(t=>e.addEventListener(t,Bc));let Hc,Uc,Wc=()=>{let e=Uc;Uc=void 0;try{typeof e==`function`&&e()}catch{}},Gc=()=>{let t=r.clientToken&&typeof r.sessionInit==`function`?r.sessionInit:void 0;if(t!==Hc){Wc(),Hc=t;try{Uc=t?.({warm:zc,mount:e})}catch{}}};Gc(),Z.push(()=>{Vc.forEach(t=>e.removeEventListener(t,Bc)),Wc()}),(De||r.onSSEEvent)&&Q.setSSEEventCallback((e,t)=>{r.onSSEEvent?.(e,t),Ue(e,t)});let Kc=()=>{let e=r.resume??(ee?ac.getStoredResumableHandle?.():null);e&&typeof r.reconnectStream==`function`&&Q.resumeFromHandle(e)};re?re.then(e=>{if(e){if(e.metadata&&(te=iy(e.metadata),pe.syncFromMetadata()),e.messages?.length){da=!0;try{Q.hydrateMessages(e.messages)}finally{da=!1}Lo()}e.artifacts?.length&&Q.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),Wa(e.draft)}}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to hydrate stored state:`,e)}).finally(()=>{Os=!0,ie(),Kc()}):(Wa(j),Kc());let qc=()=>{N()&&(P||(r.launcher?.composerBar?.expandOnSubmit??!0)&&$o(!0,`auto`))},Jc=(e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[n,r]=await Promise.allSettled([e.finalize(),t.finalize()]),i=[];return n.status===`fulfilled`?i.push(n.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,n.reason),r.status===`fulfilled`?i.push(r.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,r.reason),ly(i)}}:e:t,Yc=()=>{let e=B.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>e.kind===`mention`)?e.contentSegments:void 0},Xc=!1,Zc=null,Qc=()=>{B.value=``,B.style.height=`auto`,pn(),bl()},$c=null;function el(e,t=4e3){$t(e),!N()&<&&(lt.hasAttribute(Zv)||(lt.setAttribute(Qv,``),lt.setAttribute(`role`,`status`),lt.setAttribute(`aria-live`,`polite`),lt.textContent=e,Ga(lt,r.statusIndicator??{},`idle`),$c&&clearTimeout($c),$c=setTimeout(()=>{if($c=null,lt?.hasAttribute(Qv)&&(lt.removeAttribute(Qv),lt.removeAttribute(`role`),lt.removeAttribute(`aria-live`),m)){let e=Q.getStatus();tt(lt,et(e),r.statusIndicator??{},e)}},t)))}function tl(){let e=G.getState().pendingSubmission;e&&(Nn(void 0),B&&(B.value=e.text,B.dispatchEvent(new Event(`input`,{bubbles:!0})),pn()),e.options.selectedModelId&&(G.setSelectedModelId(e.options.selectedModelId),Cn?.repaint()),e.options.activeModeIds?.length&&bn(e.options.activeModeIds),e.options.quote&&On(e.options.quote),B?.focus())}let nl=e=>{typeof console<`u`&&console.error(`[AgentWidget] composer.onBeforeSend failed; the draft was preserved:`,e)},rl=(e={})=>{let t=(e.overrideText??B?.value??``).trim();return e.resolveInlineCommand&&t?(fn?.takeInlineCommand(t)??Promise.resolve(null)).then(n=>il(e,t,n)):il(e,t,null)},il=(e,t,n)=>{if(n?.kind===`action`){Qc(),fn?.clear(),mn();return}let i=n?.kind===`server`?n.mentions:null,a=n?.kind===`prompt`?n.sendText:t,o=e.pending?.contentParts;if(!Ff({text:a,hasAttachments:(dn?.hasAttachments()??!1)||(o?.length??0)>0,attachmentsReady:dn?.isReady()??!0,hasMentions:fn?.hasMentions()??!1,hasServerMentions:!!i,inputDisabled:is(),sendDisabled:us()}))return;let s=Q.isStreaming()?An():`block`;if(s===`defer-one`&&!e.pending){if(G.getState().pendingSubmission){el(`One message is already queued. Edit or remove it first.`);return}al({intent:e,sendText:a,serverMentions:i});return}let c={text:a,mentionRefs:[...fn?.getMentionRefs()??[],...i?.refs??[]],contentSegments:n?.kind===`prompt`?void 0:Yc(),options:{...G.getState().selectedModelId&&{selectedModelId:G.getState().selectedModelId},...G.getState().activeModeIds.length>0&&{activeModeIds:[...G.getState().activeModeIds]},...G.getState().quote&&{quote:{...G.getState().quote}}},viaVoice:e.viaVoice};e.pending&&(c.options={...e.pending.options},c.contentSegments=e.pending.contentSegments,c.mentionRefs=[...e.pending.mentionRefs],c.viaVoice=e.pending.viaVoice);let l=()=>{if(o?.length)return[...o];if(!dn?.hasAttachments())return;let e=[...dn.getContentParts()];return c.text&&e.push(Ro(c.text)),e};c.contentParts=l();let u=()=>{$i(),qc();let t=fn?.collectForSubmit()??null,n=Jc(t,i),a=l();e.consumeDraft!==!1&&Qc();let o={selectedModelId:c.options.selectedModelId,activeModeIds:c.options.activeModeIds},u=s===`interrupt`;u&&Q.cancel(),Q.sendMessage(c.text,{contentParts:a,mentions:n??void 0,contentSegments:c.contentSegments,viaVoice:c.viaVoice,composerOptions:o,...c.options.quote&&{quote:c.options.quote},...u&&{interrupt:!0}}),dn?.hasAttachments()&&dn.clearAttachments(),t&&fn?.clear(),mn();let d=G.getState().activeModeIds,f=xf(d,r.composer?.modes);f.length!==d.length&&bn(f),G.getState().quote&&On(void 0),qa(),sr.release(),lr()},d=r.composer?.onBeforeSend;if(!d){u();return}let f=new AbortController;Zc=f;let p=e=>{Zc=null,e.status===`error`?nl(e.error):e.status===`proceed`&&u()},m=Rf(d,c,f.signal);if(!(m instanceof Promise))p(m);else return G.setPreparing(!0),m.then(p).finally(()=>G.setPreparing(!1))};function al(e){let t=G.getState(),n=dn?.hasAttachments()??!1,r=n?[...dn.getContentParts()]:[];n&&e.sendText&&r.push(Ro(e.sendText)),Nn(Pf({text:e.sendText,contentParts:r.length?r:void 0,mentionRefs:[...fn?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:Yc(),options:{...t.selectedModelId&&{selectedModelId:t.selectedModelId},...t.activeModeIds.length>0&&{activeModeIds:[...t.activeModeIds]},...t.quote&&{quote:{...t.quote}}},viaVoice:e.intent.viaVoice})),e.intent.consumeDraft!==!1&&Qc(),n&&dn.clearAttachments(),fn?.clear(),mn(),t.quote&&On(void 0),qa(),sr.release(),lr(),$t(`Message queued. It sends when the response finishes.`)}function ol(){let e=G.getState().pendingSubmission;e&&(Nn(void 0),hl(e.text,{consumeDraft:!1,pending:e}))}function sl(e){if(r.messageActions?.showEdit!==!0)return;let t=Q.getMessages().find(t=>t.id===e);t&&Bu(t)&&Zi!==e&&($i(),Zi=e,Qi=Ef({messageId:e,initialText:t.content,onSave:t=>cl(e,t),onCancel:()=>$i()}),Gi.delete(e),zo(z,Q.getMessages(),we),Qi.focus())}function cl(e,t){let n=Qi;Zi=null,Qi=null,n?.destroy(),Gi.delete(e),Q.resubmitFrom(e,{reason:`edit`,replacement:{text:t,mentionRefs:[],options:{}}})?Eo():zo(z,Q.getMessages(),we)}function ul(e){if(Q.isStreaming())return;let t=Ru(Q.getMessages(),e);t&&($i(),Q.resubmitFrom(t,{reason:`retry`})&&Eo())}br={regenerate:ul,edit:sl,quote:e=>{let t=Q.getMessages().find(t=>t.id===e)?.content?.trim();t&&(On({text:t,messageId:e}),B?.focus())}};let pl=async e=>{if(!Xc){Xc=!0;try{await rl({resolveInlineCommand:!0,...e})}finally{Xc=!1}}};function ml(e){us()||(Qc(),hl(e,{consumeDraft:!1}))}let hl=(e,t)=>{if(Xc)return;Xc=!0;let n=()=>{Xc=!1};try{let r=rl({...t,overrideText:e});r instanceof Promise?r.finally(n):n()}catch(e){throw n(),e}},gl=e=>{e.preventDefault(),Q.isStreaming()?(Q.cancel(),Fe?.reset(),Re?.update()):Xc||pl()},_l=()=>r.features?.composerHistory!==!1,vl={...Hp},yl=!1,bl=()=>{vl={...Hp}},xl=()=>Q.getMessages().filter(e=>e.role===`user`).map(e=>e.content??``).filter(e=>e.length>0),Sl=e=>{if(!B)return;yl=!0,B.value=e,B.dispatchEvent(new Event(`input`,{bubbles:!0})),yl=!1;let t=B.value.length;B.setSelectionRange(t,t)},Cl=e=>{yl||(e.isComposing||fn?.handleInput(e.inputType??void 0),bl())},El=()=>({submitKey:r.composer?.submitKey,insertNewlineOnTouchEnter:r.composer?.insertNewlineOnTouchEnter,coarsePointer:rs(B)}),kl=e=>{if(B&&!is()&&(e.isComposing||!fn?.handleKeydown(e))){if(_l()&&(e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.shiftKey&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.isComposing){let t=B.selectionStart===0&&B.selectionEnd===0,n=Up({direction:e.key===`ArrowUp`?`up`:`down`,history:xl(),currentValue:B.value,atStart:t,state:vl});if(vl=n.state,n.handled){e.preventDefault(),n.value!==void 0&&Sl(n.value);return}}if(as(e,El())){if(Q.isStreaming()){if(e.preventDefault(),An()===`block`||Xc||us())return;bl(),pl()}else Xc||us()?e.preventDefault():(bl(),e.preventDefault(),V.click())}}},jl=e=>{e.key!==`Escape`||e.isComposing||e.composedPath().includes(L)&&(Zc?(Zc.abort(),Zc=null,e.preventDefault(),e.stopImmediatePropagation()):Q.isStreaming()&&(Q.cancel(),Fe?.reset(),Re?.update(),bl(),e.preventDefault(),e.stopImmediatePropagation()))},Ml=async e=>{if(r.attachments?.enabled!==!0||!dn||is())return;let t=ey(e.clipboardData);t.length!==0&&(e.preventDefault(),await dn.handleFiles(t))},Nl=null,Pl=!1,Fl=null,Il=null,Ll=()=>r.voiceRecognition?.completionBehavior===`review`;function zl(e){U?.setAttribute(`data-state`,e),e===`recording`?Jl():Yl()}let Bl=`--persona-voice-level`,Vl=.5,Hl=null,Ul=-1,Wl=0,Gl=()=>{let e=[],t=Et??U?.parentElement??null;return t&&e.push(t),bt&&e.push(bt),e},Kl=e=>{let t=Math.round(Math.max(0,Math.min(1,e))*100)/100;if(t!==Ul){Ul=t;for(let e of Gl())e.style.setProperty(Bl,String(t))}},ql=()=>{Ul=-1,Wl=0;for(let e of Gl())e.style.removeProperty(Bl)};function Jl(){if(Hl!==null)return;if(typeof requestAnimationFrame!=`function`){Kl(m?Q.getVoiceLevel()??Vl:Vl);return}let e=()=>{Hl=requestAnimationFrame(e);let t=m?Q.getVoiceLevel():null;t===null?Kl(Vl):(Wl+=(t-Wl)*.3,Kl(Wl))};Hl=requestAnimationFrame(e)}function Yl(){Hl!==null&&(cancelAnimationFrame(Hl),Hl=null),ql()}let Xl=()=>typeof window>`u`?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Zl=(e=`user`)=>{if(Pl||Q.isStreaming())return;let t=Xl();if(!t)return;Nl=new t;let n=r.voiceRecognition??{},i=n.pauseDuration??2e3;Nl.continuous=n.provider?.browser?.continuous??!0,Nl.interimResults=!0,Nl.lang=n.provider?.browser?.language??`en-US`;let a=B.value;Nl.onresult=e=>{let t=``,n=``;for(let r=0;r<e.results.length;r++){let i=e.results[r],a=i[0].transcript;i.isFinal?t+=a+` `:n=a}let r=a+t+n;B.value=r,pn(),Fl&&clearTimeout(Fl),(t||n)&&(Fl=window.setTimeout(()=>{if(B.value.trim()&&Nl&&Pl){if(Ql(),Ll())return;pl({viaVoice:!0})}},i))},Nl.onerror=e=>{e.error!==`no-speech`&&Ql()},Nl.onend=()=>{if(Pl){let e=B.value.trim();!Ll()&&e&&e!==a.trim()&&pl({viaVoice:!0}),Ql()}};try{if(Nl.start(),Pl=!0,$.active=!0,e!==`system`&&($.manuallyDeactivated=!1),Aa(e),ja(),lr(),U){let e=r.voiceRecognition??{};Il={backgroundColor:U.style.backgroundColor,color:U.style.color,borderColor:U.style.borderColor,iconName:e.iconName??`mic`,iconSize:parseFloat(e.iconSize??``)||24};let t=e.recordingBackgroundColor,n=e.recordingIconColor,i=e.recordingBorderColor;if(U.classList.add(`persona-voice-recording`),zl(`recording`),U.style.backgroundColor=t??`var(--persona-voice-recording-bg, #ef4444)`,U.style.color=n??`var(--persona-voice-recording-indicator, #ffffff)`,n){let e=U.querySelector(`svg`);e&&e.setAttribute(`stroke`,n)}i&&(U.style.borderColor=i),U.setAttribute(`aria-label`,`Stop voice recognition`)}}catch{Ql(`system`)}},Ql=(e=`user`)=>{if(Pl){if(Pl=!1,Fl&&=(clearTimeout(Fl),null),Nl){try{Nl.stop()}catch{}Nl=null}if($.active=!1,Aa(e),ja(),lr(),U){if(U.classList.remove(`persona-voice-recording`),zl(`idle`),Il){U.style.backgroundColor=Il.backgroundColor,U.style.color=Il.color,U.style.borderColor=Il.borderColor;let e=U.querySelector(`svg`);e&&e.setAttribute(`stroke`,Il.color||`currentColor`),Il=null}U.setAttribute(`aria-label`,`Start voice recognition`)}}},$l=null,eu=e=>{let t=t=>{$l??=t.createMicStateStyles({mic:()=>U,config:()=>r,session:()=>Q,get original(){return Il},set original(e){Il=e},setMicState:zl,renderIcon:K,iconFallbackPx:24}),e($l)},n=Yu();n?t(n):Ju().then(t,()=>{})},tu=()=>eu(e=>e.recording()),nu=()=>eu(e=>e.processing()),iu=()=>eu(e=>e.speaking()),ou=()=>eu(e=>e.reset()),su=()=>{if(!is()){if(Al(r.voiceRecognition?.provider)){let e=Q.getVoiceStatus(),t=Q.getVoiceInterruptionMode();if(t===`none`&&(e===`processing`||e===`speaking`))return;if(t===`cancel`&&(e===`processing`||e===`speaking`)){Q.stopVoicePlayback();return}if(Q.isBargeInActive()){Q.stopVoicePlayback(),Q.deactivateBargeIn().then(()=>{$.active=!1,$.manuallyDeactivated=!0,ja(),Aa(`user`),ou()});return}Q.toggleVoice().then(()=>{$.active=Oa(),$.manuallyDeactivated=!$.active,ja(),Aa(`user`),$.active?tu():ou()})}else if(Pl){let e=B.value.trim();$.manuallyDeactivated=!0,ja(),Ql(`user`),e&&!Ll()&&pl()}else $.manuallyDeactivated=!1,ja(),Zl(`user`)}};In=su;let cu=()=>Q.prewarmVoice(),lu=()=>{let e=r.voiceRecognition;return e?.enabled===!0?e.prewarm??(r.clientToken?`hover`:!1):!1},uu=e=>{lu()===`hover`&&U?.contains(e.target)&&cu()},du=[`pointerover`,`pointerdown`,`focusin`];du.forEach(t=>e.addEventListener(t,uu));let fu,pu=null,mu,hu=()=>{let e=mu;mu=void 0;try{typeof e==`function`&&e()}catch{}},gu=()=>{let t=lu(),n=typeof t==`function`&&U?t:void 0,r=n?U:null;if((n!==fu||r!==pu)&&(hu(),fu=n,pu=r,n&&r))try{mu=n({warm:cu,micButton:r,mount:e})}catch{}};gu(),Z.push(()=>{du.forEach(t=>e.removeEventListener(t,uu)),hu()}),U&&Z.push(()=>{Al(r.voiceRecognition?.provider)?(Q.isVoiceActive()&&Q.toggleVoice(),ou()):Ql(`system`)});let _u=O.on(`assistant:complete`,()=>{G.getState().pendingSubmission&&setTimeout(()=>{Q.isStreaming()||ol()},0)});Z.push(_u);let vu=O.on(`assistant:complete`,()=>{Da&&($.active||$.manuallyDeactivated||(Da!==`assistant`||$.lastUserMessageWasVoice)&&setTimeout(()=>{!$.active&&!$.manuallyDeactivated&&(Al(r.voiceRecognition?.provider)?Q.toggleVoice().then(()=>{$.active=Q.isVoiceActive(),Aa(`auto`),Q.isVoiceActive()&&tu()}):Zl(`auto`))},600))});Z.push(vu);let bu=O.on(`action:resubmit`,()=>{setTimeout(()=>{Q&&!Q.isStreaming()&&Q.continueConversation()},100)});Z.push(bu);let xu=()=>{$o(!P,`user`)},Su=null,Cu=null;if(M&&!N()){let{instance:e,element:t}=Ig({config:r,plugins:d,onToggle:xu});Su=e,e||(Cu=t)}Su?e.appendChild(Su.element):Cu&&e.appendChild(Cu),Zo(),Vi(),Ys(),qs(),bs(Q.isStreaming()),_o()||(Nt()===`follow`?co(!0):po()),Ma(),he&&(!M||N()?setTimeout(()=>xs(),0):P&&setTimeout(()=>xs(),200));let wu=null,Tu=()=>{wu&&(wu.disconnect(),wu.observe(bt),wu.observe(L),wu.observe(ut))},Eu=en(),Ou=()=>{if(N()){on(),Zo();return}let t=Bm(r),n=r.launcher?.sidebarMode??!1,i=e.ownerDocument.defaultView??window,a=r.launcher?.mobileFullscreen??!0,o=r.launcher?.mobileBreakpoint??640,s=i.innerWidth<=o,c=a&&s&&M;try{if(c){Tr(),Er=ai();return}let e=!1;ye&&(ye=!1,Tr(),e=!0);let i=ai();if(!e&&i!==Er&&(Tr(),e=!0),Er=i,e&&Jr(),!M&&!t){I.style.height=``,I.style.width=``;return}if(!n&&!t){let e=vg(r);I.style.width=e.width,I.style.maxWidth=e.maxWidth}ri(),hi()}finally{on(),ln();let t=en();if(t!==Eu&&(Eu=t,Ls(),Vi()),Zo(),P&&M){let t=(e.ownerDocument.defaultView??window).innerWidth<=(r.launcher?.mobileBreakpoint??640),n=r.launcher?.sidebarMode??!1,i=r.launcher?.mobileFullscreen??!0,a=Bm(r)&&i&&t,o=n||i&&t&&M||a;if(o&&!vi){let t=e.getRootNode(),n=t instanceof ShadowRoot?t.host:e.closest(`.persona-host`);n&&!_i&&(_i=Fm(n,r.launcher?.zIndex??1e5)),vi=Rm(e.ownerDocument)}else o||(_i?.(),_i=null,vi?.(),vi=null)}}};Ou();let ku=e.ownerDocument.defaultView??window;if(ku.addEventListener(`resize`,Ou),Z.push(()=>ku.removeEventListener(`resize`,Ou)),typeof ResizeObserver<`u`){wu=new ResizeObserver(()=>{ln()}),Tu(),Z.push(()=>{wu?.disconnect(),wu=null});let e=new ResizeObserver(()=>{Lc()});e.observe(L),Z.push(()=>e.disconnect())}ku.addEventListener(`resize`,Lc),Z.push(()=>ku.removeEventListener(`resize`,Lc)),ra=R.scrollTop;let Au=$p(R),ju=()=>{pi();let e=R.scrollTop,t=$p(R),n=t<Au;if(Au=t,!Pt()){ra=e,ao();return}let{action:r,nextLastScrollTop:i}=tm({following:na.isFollowing(),currentScrollTop:e,lastScrollTop:ra,nearBottom:em(R,24),userScrollThreshold:4,isAutoScrolling:aa||oa||n,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});ra=i,r===`resume`?go()||so():r===`pause`&&oo()};if(R.addEventListener(`scroll`,ju,{passive:!0}),Z.push(()=>R.removeEventListener(`scroll`,ju)),typeof ResizeObserver<`u`){let e=new ResizeObserver(()=>{Do(),au(z)});e.observe(z),e.observe(R),Z.push(()=>e.disconnect())}let Mu=()=>{Pt()&&na.isFollowing()&&go()&&oo()},Nu=R.ownerDocument;Nu.addEventListener(`selectionchange`,Mu),Z.push(()=>{Nu.removeEventListener(`selectionchange`,Mu)});let Pu=/* @__PURE__ */ new Set([`PageUp`,`PageDown`,`Home`,`End`,`ArrowUp`,`ArrowDown`]),Fu=e=>{Pu.has(e.key)&&(_a(),Lt()&&Pt()&&na.isFollowing()&&oo())},Iu=e=>{e.target?.closest(`a, button, [tabindex], input, textarea, select`)&&(_a(),Lt()&&Pt()&&na.isFollowing()&&oo())};R.addEventListener(`keydown`,Fu),R.addEventListener(`focusin`,Iu),Z.push(()=>{R.removeEventListener(`keydown`,Fu),R.removeEventListener(`focusin`,Iu)});let Lu=e=>{if(e.deltaY!==0&&_a(),!Pt())return;let t=nm({following:na.isFollowing(),deltaY:e.deltaY,nearBottom:em(R,24),resumeWhenNearBottom:!0});t===`pause`?oo():t===`resume`&&!go()&&so()};R.addEventListener(`wheel`,Lu,{passive:!0}),R.addEventListener(`touchmove`,_a,{passive:!0}),R.addEventListener(`pointerdown`,_a,{passive:!0}),Z.push(()=>{R.removeEventListener(`touchmove`,_a),R.removeEventListener(`pointerdown`,_a)}),Z.push(()=>R.removeEventListener(`wheel`,Lu)),Vt.addEventListener(`click`,()=>{So(),R.scrollTop=R.scrollHeight,ra=R.scrollTop,so(),co(!0),ao()}),Z.push(()=>Vt.remove()),Z.push(()=>{Qa(),So()});let Vu=()=>{H&&(Oi&&=(H.removeEventListener(`click`,Oi),null),be()?(H.style.display=``,Oi=()=>{$o(!1,`user`)},H.addEventListener(`click`,Oi)):H.style.display=`none`)};Vu(),(()=>{let{clearChatButton:e}=it;e&&e.addEventListener(`click`,()=>{let e=xc;if(e?.historyAvailable()){e.startNewConversation({focusComposer:!0}).catch(e=>{r.debug&&console.warn(`[AgentWidget] New conversation failed:`,e)});return}Q.clearMessages(),r.layout?.topFade&&(R.scrollTop=0),R.removeAttribute(`data-persona-top-fade`),Gi.clear(),so(),Zr(it.composerOverlay);try{localStorage.removeItem(Xv),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xv}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Xv)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let t=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(t),k?.clear&&La(()=>k.clear(),`[AgentWidget] Failed to clear storage adapter:`),te={},pe.syncFromMetadata(),dn?.clearAttachments(),qa(),Nn(void 0),On(void 0),$i(),Pe?.clear(),Fe?.reset(),Re?.update()})})();let Hu=[[`keydown`,kl],[`input`,Cl],[`input`,pn],[`input`,mn],[`keyup`,mn],[`paste`,Ml],[`focus`,J]],Uu=e=>{if(e)for(let[t,n]of Hu)Jn?.addListener(e,t,n)},Wu=e=>{if(e)for(let[t,n]of Hu)Jn?.removeListener(e,t,n)},Gu=()=>{Jn&&(Jn.addListener(Jn.form,`submit`,gl),Jn.addListener(Jn.footer,`click`,mn),Uu(B),U&&Jn.addListener(U,`click`,su),gu())};Gu();let Ku=()=>{fn?.onComposerSwap((e,t)=>{Wu(t),B=e,Jn&&(Jn.input=e),Uu(e),Xn(),ys(),pn()})};Ku();let qu=!1;function Xu(){if(!qu){qu=!0;try{let e=B?.value??``,t=bt.ownerDocument??document,n=B?t.activeElement===B:!1;Yl(),Jn?.destroy(),Jn=null,fn?.destroy(),fn=null;let i=null,a=()=>(i=N()?Sh({config:r}):bh({config:r}),i.footer),o=Kn(a)??a();nt.replaceComposer(o),bt=nt.composer.footer;let s=i!==null&&o===i.footer;Gn=!s,Tt=s?i.setSendButtonMode:()=>{},Wn(bt),Zn(bt),$n(),er(),tr(),Ku(),ir(),ar(),or(),Gu();let c=Di.indexOf(wi);if(wi.destroy(),wi=Ym(st),c>=0&&(Di[c]=wi),B&&(B.value=e),pn(),mn(),Ys(),Vi(),bs(Q.isStreaming()),r.statusIndicator?.mode===`transient`&&!N()){let e=Q.getStatus();tt(lt,et(e),r.statusIndicator,e)}$.active&&zl(`recording`),Tr(),Tu(),on(),lr(),gs(),n&&B?.focus()}finally{qu=!1}}}let Zu=e.ownerDocument??document;Zu.addEventListener(`keydown`,jl,!0);let Qu=()=>{Ua()},$u=()=>{Zu.visibilityState===`hidden`&&Ua()};typeof window<`u`&&(window.addEventListener(`pagehide`,Qu),Zu.addEventListener(`visibilitychange`,$u),Z.push(()=>{window.removeEventListener(`pagehide`,Qu),Zu.removeEventListener(`visibilitychange`,$u)}));let ed=`persona-attachment-drop-active`,td=0,nd=()=>{td=0,L.classList.remove(ed)},rd=()=>r.attachments?.enabled===!0&&dn!==null&&!is(),id=e=>{ty(e.dataTransfer)&&rd()&&(td++,td===1&&L.classList.add(ed))},ad=e=>{ty(e.dataTransfer)&&rd()&&(td--,td<=0&&nd())},od=e=>{ty(e.dataTransfer)&&rd()&&(e.preventDefault(),e.dataTransfer.dropEffect=`copy`)},sd=e=>{if(!ty(e.dataTransfer)||!rd())return;e.preventDefault(),e.stopPropagation(),nd();let t=Array.from(e.dataTransfer.files??[]);t.length!==0&&dn.handleFiles(t)};L.addEventListener(`dragenter`,id,!0),L.addEventListener(`dragleave`,ad,!0),e.addEventListener(`dragover`,od,!0),e.addEventListener(`drop`,sd,!0);let cd=e.ownerDocument,ld=e=>{rd()&&e.preventDefault()},ud=e=>{rd()&&e.preventDefault()};cd.addEventListener(`dragover`,ld),cd.addEventListener(`drop`,ud),Z.push(()=>{Jn?.destroy(),Jn=null,Yl(),Y?.destroy(),Y=null,Tn?.destroy(),Tn=null,Dn?.destroy(),Dn=null,Mn?.destroy(),Mn=null,Cn=null,wn=null,Ua(),Va.destroy(),$c&&clearTimeout($c),$i(),Zc?.abort(),Zc=null,dn?.destroy(),dn=null,G.destroy(),Zu.removeEventListener(`keydown`,jl,!0),fn?.destroy()}),Z.push(()=>{L.removeEventListener(`dragenter`,id,!0),L.removeEventListener(`dragleave`,ad,!0),e.removeEventListener(`dragover`,od,!0),e.removeEventListener(`drop`,sd,!0),cd.removeEventListener(`dragover`,ld),cd.removeEventListener(`drop`,ud),nd()}),Z.push(()=>{Q.cancel()}),Su?Z.push(()=>{Su?.destroy()}):Cu&&Z.push(()=>{Cu?.remove()});let dd={update(t){let n=r.future?.v5Defaults===!0,a=r.toolCall,o=r.messageActions,s=r.layout?.messages,c=r.colorScheme,f=r.loadingIndicator,p=r.iterationDisplay,m=r.features?.showReasoning,h=r.features?.showToolCalls,g=r.features?.toolCallDisplay,_=r.features?.reasoningDisplay,v=r.features?.streamAnimation?.type,y=r.features?.history?.enabled===!0,b=r.features?.history?.provider,x=r.getIdentityProof,S=r.clientToken,C=r.contextMentions;r=gv({...r,features:u},t),u=r.features,r=$_(r),l(),li(),Pp(e,r),O_(e,r),k_(e,r),Je(),si(),r.colorScheme!==c&&bi();let w=fv.getForInstance(r.plugins);d.length=0,d.push(...w),Dc(),M=r.launcher?.enabled??!0,me=r.launcher?.autoExpand??!1,Te=r.features?.showReasoning??!0,Ee=r.features?.showToolCalls??!0,Oe=r.features?.scrollToBottom??{};let T=Nt();ke=r.features?.scrollBehavior??{},T!==Nt()&&(So(),so()),ba(),un(),ao();let E=De;if(De=r.features?.showEventStreamToggle??!1,De&&!E){if(Pe||(We(),Q.setSSEEventCallback((e,t)=>{r.onSSEEvent?.(e,t),Ue(e,t)})),!Un&&yt){let e=r.features?.eventStream?.classNames,t=`persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1`+(e?.toggleButton?` `+e.toggleButton:``);Un=q(`button`,t),Un.style.width=`28px`,Un.style.height=`28px`,Un.style.color=rh.actionIconColor,Un.type=`button`,Un.setAttribute(`aria-label`,`Event Stream`),Un.title=`Event Stream`;let n=Jt(i,`18px`,`currentColor`,1.5);n&&Un.appendChild(n);let a=it.clearChatButtonWrapper,o=it.closeButtonWrapper,s=a||o;s&&s.parentNode===yt?yt.insertBefore(Un,s):yt.appendChild(Un),Un.addEventListener(`click`,()=>{ze?Hn():Bn()})}}else!De&&E&&(Hn(),Un&&=(Un.remove(),null),Pe?.clear(),Me?.destroy(),Pe=null,Me=null,Fe?.reset(),Fe=null,Ie=null);if(r.launcher?.enabled===!1&&Su&&(Su.destroy(),Su=null),r.launcher?.enabled===!1&&Cu&&(Cu.remove(),Cu=null),r.launcher?.enabled!==!1&&!Su&&!Cu){let{instance:t,element:n}=Ig({config:r,plugins:d,onToggle:xu});Su=t,t||(Cu=n),e.appendChild(n)}Su&&Su.update(r),Ac(),vt&&r.launcher?.subtitle!==void 0&&(vt.textContent=r.launcher.subtitle);let D=r.layout?.header;if(D?.layout!==ve&&yt){let e=D?yh(r,D,{showClose:be(),onClose:()=>$o(!1,`user`)}):oh({config:r,showClose:be(),onClose:()=>$o(!1,`user`)});nt.replaceHeader(e),yt=nt.header.element,gt=nt.header.iconHolder,_t=nt.header.headerTitle,vt=nt.header.headerSubtitle,H=nt.header.closeButton,ve=D?.layout,Ac()}else if(D){if(gt&&(gt.style.display=D.showIcon===!1?`none`:``),_t&&(_t.style.display=D.showTitle===!1?`none`:``),vt&&(vt.style.display=D.showSubtitle===!1?`none`:``),H){let e=be()&&D.showCloseButton!==!1;H.style.display=e?``:`none`}if(it.clearChatButtonWrapper){let e=D.showClearChat;if(e!==void 0){it.clearChatButtonWrapper.style.display=e?``:`none`;let{closeButtonWrapper:t}=it;t&&!t.classList.contains(`persona-absolute`)&&(e?t.classList.remove(`persona-ml-auto`):t.classList.add(`persona-ml-auto`))}}}let k=r.layout?.showHeader!==!1;yt&&(yt.style.display=k?``:`none`);let ee=r.layout?.showFooter!==!1;bt&&(bt.style.display=ee?``:`none`),on(),ao(),M===_e?me!==ge&&$o(me,`auto`):M?$o(me,`auto`):(P=!0,Zo()),ge=me,_e=M,Ou(),Vu();let te=JSON.stringify(r.toolCall)!==JSON.stringify(a),ne=JSON.stringify(r.messageActions)!==JSON.stringify(o),re=JSON.stringify(r.layout?.messages)!==JSON.stringify(s),ie=r.loadingIndicator?.render!==f?.render||r.loadingIndicator?.renderIdle!==f?.renderIdle||r.loadingIndicator?.showBubble!==f?.showBubble,ae=r.iterationDisplay!==p,oe=(r.features?.showReasoning??!0)!==(m??!0)||(r.features?.showToolCalls??!0)!==(h??!0)||JSON.stringify(r.features?.toolCallDisplay)!==JSON.stringify(g)||JSON.stringify(r.features?.reasoningDisplay)!==JSON.stringify(_);(r.future?.v5Defaults===!0!==n||te||ne||re||ie||ae||oe)&&Q&&(ea++,zo(z,Q.getMessages(),we));let A=r.features?.streamAnimation?.type;if(A!==v&&A&&A!==`none`){let t=Si(A,r.features?.streamAnimation?.plugins);t&&jm(t,e)}let j=r.launcher??{},se=j.headerIconHidden??!1,ce=r.layout?.header?.showIcon,de=se||ce===!1,fe=j.headerIconName,he=j.headerIconSize??`40px`;if(gt){let e=yt,t=e?.querySelector(`.persona-flex-col`);if(de)gt.style.display=`none`,e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(gt.style.display=``,gt.style.height=he,gt.style.width=he,e&&t&&(e.contains(gt)?gt.nextSibling!==t&&(gt.remove(),e.insertBefore(gt,t)):e.insertBefore(gt,t)),fe){let e=parseFloat(he)||24,t=K(fe,e*.6,`currentColor`,1);t?(t.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,t.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,gt.replaceChildren(t)):gt.textContent=j.agentIconText??`💬`}else if(j.iconUrl){let e=gt.querySelector(`img`);if(e)e.src=j.iconUrl,e.style.height=he,e.style.width=he;else{let e=document.createElement(`img`);e.src=j.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=he,e.style.width=he,gt.replaceChildren(e)}}else{let e=gt.querySelector(`svg`),t=gt.querySelector(`img`);(e||t)&>.replaceChildren(),gt.textContent=j.agentIconText??`💬`}let n=gt.querySelector(`img`);n&&(n.style.height=he,n.style.width=he)}}let ye=r.layout?.header?.showTitle,xe=r.layout?.header?.showSubtitle;if(_t&&(_t.style.display=ye===!1?`none`:``),vt&&(vt.style.display=xe===!1?`none`:``),H){let e=be()&&r.layout?.header?.showCloseButton!==!1;if(H.style.display=e?``:`none`,!N()){let e=j.closeButtonSize??``;H.style.height=e,H.style.width=e,H.style.minWidth=e,H.style.minHeight=e}let t=j.closeButtonPlacement??`inline`,{closeButtonWrapper:n}=it,i=t===`top-right`,a=n?.classList.contains(`persona-absolute`);if(n&&i!==a){if(n.remove(),i){n.className=`persona-absolute persona-top-4 persona-right-4 persona-z-50`;let e=xc?.railColumn??L;e.style.position=`relative`,e.appendChild(n)}else{let e=j.clearChat?.placement??`inline`;n.className=(j.clearChat?.enabled??!0)&&e===`inline`?``:`persona-ml-auto`,yt&&yt.appendChild(n)}}if(H.style.color=j.closeButtonColor||rh.actionIconColor,j.closeButtonBackgroundColor?(H.style.backgroundColor=j.closeButtonBackgroundColor,H.classList.remove(`hover:persona-bg-gray-100`)):(H.style.backgroundColor=``,H.classList.add(`hover:persona-bg-gray-100`)),j.closeButtonBorderWidth||j.closeButtonBorderColor){let e=j.closeButtonBorderWidth||`0px`,t=j.closeButtonBorderColor||`transparent`;H.style.border=`${e} solid ${t}`,H.classList.remove(`persona-border-none`)}else H.style.border=``,H.classList.add(`persona-border-none`);j.closeButtonBorderRadius?(H.style.borderRadius=j.closeButtonBorderRadius,H.classList.remove(`persona-rounded-full`)):(H.style.borderRadius=``,H.classList.add(`persona-rounded-full`)),j.closeButtonPaddingX?(H.style.paddingLeft=j.closeButtonPaddingX,H.style.paddingRight=j.closeButtonPaddingX):(H.style.paddingLeft=``,H.style.paddingRight=``),j.closeButtonPaddingY?(H.style.paddingTop=j.closeButtonPaddingY,H.style.paddingBottom=j.closeButtonPaddingY):(H.style.paddingTop=``,H.style.paddingBottom=``),$m(H,j.closeButtonIconName??`x`,{iconSize:N()?bg:void 0,iconText:j.closeButtonIconText??`×`});let o=j.closeButtonTooltipText??`Close chat`,s=j.closeButtonShowTooltip??!0;H.setAttribute(`aria-label`,o),n&&Ea({anchor:H,trigger:n,text:()=>H?.getAttribute(`aria-label`)??o,enabled:s})}let{clearChatButton:Se,clearChatButtonWrapper:Ae}=it;if(Se){let e=j.clearChat??{},t=e.enabled??!0,n=r.layout?.header?.showClearChat,i=n===void 0?t:n,a=e.placement??`inline`;if(Ae){Ae.style.display=i?``:`none`;let{closeButtonWrapper:e}=it;!N()&&e&&!e.classList.contains(`persona-absolute`)&&(i?e.classList.remove(`persona-ml-auto`):e.classList.add(`persona-ml-auto`));let t=a===`top-right`,n=Ae.classList.contains(`persona-absolute`);if(!N()&&t!==n&&i){if(Ae.remove(),t){Ae.className=`persona-absolute persona-top-4 persona-z-50`,Ae.style.right=`48px`;let e=xc?.railColumn??L;e.style.position=`relative`,e.appendChild(Ae)}else{Ae.className=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,Ae.style.right=``;let e=it.closeButtonWrapper;yt&&e&&e.parentElement===yt?yt.insertBefore(Ae,e):yt&&yt.appendChild(Ae)}let e=it.closeButtonWrapper;e&&!e.classList.contains(`persona-absolute`)&&(t?e.classList.add(`persona-ml-auto`):e.classList.remove(`persona-ml-auto`))}}if(i){if(!N()){let t=e.size??``;Se.style.height=t,Se.style.width=t,Se.style.minWidth=t,Se.style.minHeight=t}let t=e.iconColor??``;if(Se.style.color=t||rh.actionIconColor,$m(Se,e.iconName??`refresh-cw`,{iconSize:N()?xg:void 0}),e.backgroundColor?(Se.style.backgroundColor=e.backgroundColor,Se.classList.remove(`hover:persona-bg-gray-100`)):(Se.style.backgroundColor=``,Se.classList.add(`hover:persona-bg-gray-100`)),e.borderWidth||e.borderColor){let t=e.borderWidth||`0px`,n=e.borderColor||`transparent`;Se.style.border=`${t} solid ${n}`,Se.classList.remove(`persona-border-none`)}else Se.style.border=``,Se.classList.add(`persona-border-none`);e.borderRadius?(Se.style.borderRadius=e.borderRadius,Se.classList.remove(`persona-rounded-full`)):(Se.style.borderRadius=``,Se.classList.add(`persona-rounded-full`)),e.paddingX?(Se.style.paddingLeft=e.paddingX,Se.style.paddingRight=e.paddingX):(Se.style.paddingLeft=``,Se.style.paddingRight=``),e.paddingY?(Se.style.paddingTop=e.paddingY,Se.style.paddingBottom=e.paddingY):(Se.style.paddingTop=``,Se.style.paddingBottom=``);let n=e.tooltipText??`Clear chat`,r=e.showTooltip??!0;Se.setAttribute(`aria-label`,n),Ae&&Ea({anchor:Se,trigger:Ae,text:()=>Se?.getAttribute(`aria-label`)??n,enabled:r})}}let je=r.actionParsers&&r.actionParsers.length?r.actionParsers:[bv],Ne=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Sv.message,Sv.messageAndClick];pe=wv({parsers:je,handlers:Ne,getSessionMetadata:le,updateSessionMetadata:ue,emit:O.emit,documentRef:typeof document<`u`?document:null}),we=oy(r,pe,Ce),oc(),Q.updateConfig(r),Gc(),(r.features?.history?.enabled===!0!==y||r.features?.history?.provider!==b||r.getIdentityProof!==x||r.clientToken!==S)&&(xc?.closeHistory({restoreFocus:!1}),xc?.installHistoryProvider()),xc?.syncHistoryChromeImpl(),Lc(),Tc()&&!xc&&Fc().catch(()=>{}),zo(z,Q.getMessages(),we),Vi(),Ys(),Js(),bs(Q.isStreaming()),C!==r.contextMentions&&Xu();let Le=r.voiceRecognition?.enabled===!0,Re=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),Be=Al(r.voiceRecognition?.provider);if(Le&&(Re||Be)){if(!U||!Et){let e=_s(r);if(e){U=e.button,Et=e.wrapper;let t=wt&&wt.parentElement===Ct?wt:null;Ct?Ct.insertBefore(Et,t):ct?.appendChild(Et),Jn&&(Jn.micButton=U),Jn?.addListener(U,`click`,su),U.disabled=is()||Q.isStreaming()&&!os()}}else{let e=r.voiceRecognition??{},t=r.sendButton??{},n=e.iconName??`mic`,i=e.iconSize,a=parseFloat(i??``)||24;U.classList.add(ds),U.classList.toggle(fs,!i),U.style.width=i??``,U.style.height=i??``,U.style.minWidth=i??``,U.style.minHeight=i??``;let o=e.iconColor??t.textColor;U.innerHTML=``;let s=K(n,a,o||`currentColor`,1.5);s?U.appendChild(s):U.textContent=`🎤`;let c=e.backgroundColor??t.backgroundColor;c?U.style.backgroundColor=c:U.style.backgroundColor=``,o?U.style.color=o:U.style.color=`var(--persona-text, #111827)`,e.borderWidth?(U.style.borderWidth=e.borderWidth,U.style.borderStyle=`solid`):(U.style.borderWidth=``,U.style.borderStyle=``),e.borderColor?U.style.borderColor=e.borderColor:U.style.borderColor=``,e.paddingX?(U.style.paddingLeft=e.paddingX,U.style.paddingRight=e.paddingX):(U.style.paddingLeft=``,U.style.paddingRight=``),e.paddingY?(U.style.paddingTop=e.paddingY,U.style.paddingBottom=e.paddingY):(U.style.paddingTop=``,U.style.paddingBottom=``);let l=e.tooltipText??`Start voice recognition`,u=e.showTooltip??!1;U.setAttribute(`aria-label`,l),Et&&Ea({anchor:U,trigger:Et,text:()=>U?.getAttribute(`aria-label`)??l,enabled:u}),Et.style.display=``,U.disabled=is()||Q.isStreaming()&&!os()}}else U&&Et&&(Et.style.display=`none`,Al(r.voiceRecognition?.provider)?Q.isVoiceActive()&&Q.toggleVoice():Pl&&Ql());if(gu(),r.attachments?.enabled===!0){if(!Ot||!Dt){let e=r.attachments??{};At||(At=q(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),At.style.display=`none`,(B.parentElement??ct).insertBefore(At,B)),kt||(kt=document.createElement(`input`),kt.type=`file`,kt.accept=(e.allowedTypes??Qo).join(`,`),kt.multiple=(e.maxFiles??4)>1,kt.style.display=`none`,kt.setAttribute(`aria-label`,`Attach files`),(B.parentElement??ct).insertBefore(kt,B)),Ot=q(`div`,`persona-send-button-wrapper`),Dt=q(`button`,`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${ds} ${fs}`),Dt.type=`button`,Dt.setAttribute(`aria-label`,e.buttonTooltipText??`Attach file`);let t=e.buttonIconName??`paperclip`;Dt.style.fontSize=`18px`,Dt.style.lineHeight=`1`;let n=K(t,24,`currentColor`,1.5);n?Dt.appendChild(n):Dt.textContent=`📎`,Dt.addEventListener(`click`,e=>{e.preventDefault(),kt?.click()}),Ot.appendChild(Dt);let i=e.buttonTooltipText??`Attach file`;Ea({anchor:Dt,trigger:Ot,text:()=>Dt?.getAttribute(`aria-label`)??i}),St?St.append(Ot):ct.appendChild(Ot),Jn&&(Jn.attachmentButton=Dt,Jn.attachmentInput=kt??void 0,Jn.attachmentPreviews=At??void 0),!dn&&kt&&At&&(dn=wd.fromConfig(e,gn),dn.setPreviewsContainer(At),Jn?.addListener(kt,`change`,async()=>{dn&&kt?.files&&(await dn.handleFileSelect(kt.files),kt.value=``)}))}else{Ot.style.display=``;let e=r.attachments??{};kt&&(kt.accept=(e.allowedTypes??Qo).join(`,`),kt.multiple=(e.maxFiles??4)>1),dn&&dn.updateConfig({allowedTypes:e.allowedTypes,maxFileSize:e.maxFileSize,maxFiles:e.maxFiles,adapter:e.adapter})}if(L.querySelector(`.persona-attachment-drop-overlay`)?.remove(),L.appendChild(sy(r.attachments?.dropOverlay)),Dt){let e=r.attachments??{},t=e.buttonTooltipText??`Attach file`;Dt.setAttribute(`aria-label`,t),Dt.textContent=``;let n=K(e.buttonIconName??`paperclip`,24,`currentColor`,1.5);n?Dt.appendChild(n):Dt.textContent=`📎`,Ot&&Ea({anchor:Dt,trigger:Ot,text:()=>Dt?.getAttribute(`aria-label`)??t})}}else Ot&&(Ot.style.display=`none`),dn&&dn.clearAttachments(),L.querySelector(`.persona-attachment-drop-overlay`)?.remove();let Ve=r.sendButton??{},He=Ve.useIcon??!1,Ge=Ve.iconText??`↑`,Ke=Ve.iconName,Ye=Ve.tooltipText??`Send message`,Xe=Ve.showTooltip??!1,Ze=Ve.size,Qe=parseFloat(Ze??``)||40,$e=Ve.backgroundColor,et=Ve.textColor;if(He){if(V.style.width=Ze??``,V.style.height=Ze??``,V.style.minWidth=Ze??``,V.style.minHeight=Ze??``,V.style.fontSize=`18px`,V.style.lineHeight=`1`,et?V.style.color=et:V.style.color=`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`,!Q.isStreaming()){if(V.innerHTML=``,Ke){let e=parseFloat(Ve.iconSize??``)||Math.round(Qe*.5),t=et?.trim()||`currentColor`,n=Ve.iconStrokeWidth??2,r=K(Ke,e,t,n),i=K(Ve.stopIconName??`square`,e,t,n);r&&i?V.appendChild(hs(r,i)):r?V.appendChild(r):V.textContent=Ge}else V.textContent=Ge}V.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${ds}`,$e?(V.style.backgroundColor=$e,V.classList.remove(`persona-bg-persona-primary`)):(V.style.backgroundColor=``,V.classList.add(`persona-bg-persona-primary`))}else V.textContent=r.copy?.sendButtonLabel??`Send`,V.style.width=``,V.style.height=``,V.style.minWidth=``,V.style.minHeight=``,V.style.fontSize=``,V.style.lineHeight=``,V.className=`persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer`,$e?(V.style.backgroundColor=$e,V.classList.remove(`persona-bg-persona-accent`)):V.classList.add(`persona-bg-persona-accent`),et?V.style.color=et:V.classList.add(`persona-text-white`);Ve.borderWidth?(V.style.borderWidth=Ve.borderWidth,V.style.borderStyle=`solid`):(V.style.borderWidth=``,V.style.borderStyle=``),Ve.borderColor?V.style.borderColor=Ve.borderColor:V.style.borderColor=``,Ve.paddingX?(V.style.paddingLeft=Ve.paddingX,V.style.paddingRight=Ve.paddingX):(V.style.paddingLeft=``,V.style.paddingRight=``),Ve.paddingY?(V.style.paddingTop=Ve.paddingY,V.style.paddingBottom=Ve.paddingY):(V.style.paddingTop=``,V.style.paddingBottom=``),Q.isStreaming()||V.setAttribute(`aria-label`,Ye),gs(),wt&&Ea({anchor:V,trigger:wt,text:()=>V.getAttribute(`aria-label`)??Ye,enabled:Xe}),ur(),mi();let F=bf(G.getState().activeModeIds,r.composer?.modes);G.setActiveModeIds(F),vn().length>0!=!!Tn&&ar(),Tn?.render(F,vn());for(let e of[...En.keys()])hf(e,r.composer?.modeGroups)||En.delete(e);En.forEach(e=>e.repaint()),Cn?.repaint(),Y?.resolve();let I=Ip(r,N());if(ui(),I){z.style.maxWidth=I,z.style.marginLeft=`auto`,z.style.marginRight=`auto`,z.style.width=`100%`,ft.style.maxWidth=I,ft.style.marginLeft=`auto`,ft.style.marginRight=`auto`,ft.style.width=`100%`;for(let e of[ct,st,At,lt])e&&(e.style.maxWidth=I,e.style.marginLeft=`auto`,e.style.marginRight=`auto`,e.style.width=`100%`)}else{z.style.maxWidth=``,z.style.marginLeft=``,z.style.marginRight=``,z.style.width=``,ft.style.maxWidth=``,ft.style.marginLeft=``,ft.style.marginRight=``,ft.style.width=``;for(let e of[ct,st,At,lt])e&&(e.style.maxWidth=``,e.style.marginLeft=``,e.style.marginRight=``,e.style.width=``)}let rt=r.statusIndicator??{};if(Ka(lt,ct,rt),Ga(lt,rt,Q?.getStatus()??`idle`),Q){let e=Q.getStatus();tt(lt,(e=>e===`idle`?rt.idleText??gi.idle:e===`connecting`?rt.connectingText??gi.connecting:e===`connected`?rt.connectedText??gi.connected:e===`error`?rt.errorText??gi.error:e===`paused`?rt.pausedText??gi.paused:e===`resuming`?rt.resumingText??gi.resuming:gi[e])(e),rt,e)}lt.classList.remove(`persona-text-left`,`persona-text-center`,`persona-text-right`);let R=rt.align===`left`?`persona-text-left`:rt.align===`center`?`persona-text-center`:`persona-text-right`;lt.classList.add(R),Xn(),ys(),lr(),qe()},open(){be()&&$o(!0,`api`)},close(){be()&&$o(!1,`api`)},toggle(){be()&&$o(!P,`api`)},reconnect(){Q.reconnectNow()},clearChat(){kr=!1,s.clear(),a.clear(),o.clear(),c.clear(),Q.clearMessages(),r.layout?.topFade&&(R.scrollTop=0),R.removeAttribute(`data-persona-top-fade`),Gi.clear(),so();try{localStorage.removeItem(Xv),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xv}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Xv)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let e=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(e),k?.clear&&La(()=>k.clear(),`[AgentWidget] Failed to clear storage adapter:`),te={},pe.syncFromMetadata(),dn?.clearAttachments(),qa(),Nn(void 0),On(void 0),$i(),Pe?.clear(),Fe?.reset(),Re?.update()},setMessage(e){return!B||Q.isStreaming()||is()?!1:(!P&&be()&&$o(!0,`system`),B.value=e,B.dispatchEvent(new Event(`input`,{bubbles:!0})),!0)},submitMessage(e){if(Q.isStreaming()||us())return!1;let t=e?.trim()||B.value.trim();return t?(!P&&be()&&$o(!0,`system`),B.value=``,B.style.height=`auto`,pn(),hl(t,{consumeDraft:!1}),!0):!1},getComposerState(){return G.getState()},setQuote(e){let t=e?.text?.trim();t&&On({...e,text:t})},clearQuote(){On(void 0)},startVoiceRecognition(){return Q.isStreaming()?!1:Al(r.voiceRecognition?.provider)?(Q.isVoiceActive()||Q.isBargeInActive()||(!P&&be()&&$o(!0,`system`),$.manuallyDeactivated=!1,ja(),Q.toggleVoice().then(()=>{$.active=Oa(),ja(),Aa(`user`),$.active&&tu()})),!0):Pl?!0:Xl()?(!P&&be()&&$o(!0,`system`),$.manuallyDeactivated=!1,ja(),Zl(`user`),!0):!1},stopVoiceRecognition(){return Al(r.voiceRecognition?.provider)?!Q.isVoiceActive()&&!Q.isBargeInActive()?!1:((Q.isBargeInActive()?Q.deactivateBargeIn():Q.toggleVoice()).then(()=>{$.active=!1,$.manuallyDeactivated=!0,ja(),Aa(`user`),ou()}),!0):Pl?($.manuallyDeactivated=!0,ja(),Ql(`user`),!0):!1},injectMessage(e){return!P&&be()&&$o(!0,`system`),Q.injectMessage(e)},injectAssistantMessage(e){!P&&be()&&$o(!0,`system`);let t=Q.injectAssistantMessage(e);return xe&&(xe=!1,Se&&=(clearTimeout(Se),null),setTimeout(()=>{Q&&!Q.isStreaming()&&Q.continueConversation()},100)),t},injectUserMessage(e){return!P&&be()&&$o(!0,`system`),Q.injectUserMessage(e)},injectSystemMessage(e){return!P&&be()&&$o(!0,`system`),Q.injectSystemMessage(e)},injectMessageBatch(e){return!P&&be()&&$o(!0,`system`),Q.injectMessageBatch(e)},injectComponentDirective(e){return!P&&be()&&$o(!0,`system`),Q.injectComponentDirective(e)},injectTestMessage(e){!P&&be()&&$o(!0,`system`),Q.injectTestEvent(e)},async connectStream(e,t){return Q.connectStream(e,t)},__pushEventStreamEvent(e){De&&(We(),Ue(e.type,e.payload))},showEventStream(){De&&Bn()},hideEventStream(){ze&&Hn()},isEventStreamVisible(){return ze},listConversations(e){return Q.listConversations(e)},getActiveConversationId(){return Q.getActiveConversationId()},openConversation(e,t){return Ic(n=>n.openHistoryConversation(e,{focusComposer:t?.focus===!0}))},startNewConversation(e){return Ic(t=>t.startNewConversation({focusComposer:e?.focus===!0}))},warmSession(){zc()},deleteConversation(e){return Ic(t=>t.deleteHistoryConversation(e))},renameConversation(e,t){return Ic(n=>n.updateHistoryConversation(e,{title:t}))},setConversationStarred(e,t){return Ic(n=>n.updateHistoryConversation(e,{starred:t}))},clearConversationHistory(e){return Ic(t=>t.clearConversationHistory(e))},resetHistoryIdentity(){return Ic(e=>e.resetHistoryIdentity())},async getVisitorToken(){let e=rc;if(!e)return null;let t=await e.get();return e===rc?t:null},getHistoryIdentityStatus(){let e=xc?.historyProvider;return e?e.getIdentityStatus():Tc()?{state:`unavailable`,reason:`ineligible_mode`}:{state:`unavailable`,reason:`history_disabled`}},showHistory(e){return Tc()?Ic(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...e?.focus===void 0?{}:{focus:e.focus}})):Promise.resolve()},hideHistory(e){xc?.closeHistory(e?.restoreFocus===void 0?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible(){return Ge},showArtifacts(){S_(r)&&(kr=!1,Mr=!0,si(),X?.setMobileOpen(!0))},hideArtifacts(){S_(r)&&(kr=!0,si())},upsertArtifact(e){return S_(r)?(jn(r.features?.artifacts,{artifactType:e.artifactType,...e.artifactType===`markdown`&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})===`panel`&&(kr=!1,Mr=!0),Q.upsertArtifact(e)):null},selectArtifact(e){S_(r)&&Q.selectArtifact(e)},clearArtifacts(){S_(r)&&Q.clearArtifacts()},getArtifacts(){return Q?.getArtifacts()??[]},getSelectedArtifactId(){return Q?.getSelectedArtifactId()??null},focusInput(){return M&&!P&&!N()||!B?!1:(B.focus(),!0)},async resolveApproval(e,t,n){let r=Q.getMessages().find(t=>t.variant===`approval`&&t.approval?.id===e);if(!r?.approval)throw Error(`Approval not found: ${e}`);if(fl(r.approval))Q.resolveWebMcpApproval(r.id,t);else return Q.resolveApproval(r.approval,t,n)},setFollowUpSuggestions(e){Ui(e)},clearFollowUpSuggestions(){Hi()},getMessages(){return Q.getMessages()},getStatus(){return Q.getStatus()},getPersistentMetadata(){return{...te}},updatePersistentMetadata(e){ue(e)},on(e,t){return O.on(e,t)},off(e,t){O.off(e,t)},isOpen(){return be()&&P},isVoiceActive(){return $.active},toggleReadAloud(e){Q.toggleReadAloud(e)},stopReadAloud(){Q.stopSpeaking()},getReadAloudState(e){return Q.getReadAloudState(e)},onReadAloudChange(e){return Q.onReadAloudChange(e)},getState(){return{open:be()&&P,launcherEnabled:M,voiceActive:$.active,streaming:Q.isStreaming()}},showCSATFeedback(e){!P&&be()&&$o(!0,`system`);let t=z.querySelector(`.persona-feedback-container`);t&&t.remove();let n=Jv({onSubmit:async(t,n)=>{Q.isClientTokenMode()&&await Q.submitCSATFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});z.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},showNPSFeedback(e){!P&&be()&&$o(!0,`system`);let t=z.querySelector(`.persona-feedback-container`);t&&t.remove();let n=Yv({onSubmit:async(t,n)=>{Q.isClientTokenMode()&&await Q.submitNPSFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});z.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},async submitCSATFeedback(e,t){return Q.submitCSATFeedback(e,t)},async submitNPSFeedback(e,t){return Q.submitNPSFeedback(e,t)},destroy(){_c(),sc!=null&&(clearInterval(sc),sc=null),s.clear(),a.clear(),o.clear(),c.clear(),Z.forEach(e=>e()),F.remove(),rt?.remove(),Su?.destroy(),Cu?.remove(),Oi&&H.removeEventListener(`click`,Oi)}};if(((n?.debugTools??!1)||r.debug)&&typeof window<`u`){let e=window.AgentWidgetBrowser,t={controller:dd,getMessages:dd.getMessages,getStatus:dd.getStatus,getMetadata:dd.getPersistentMetadata,updateMetadata:dd.updatePersistentMetadata,clearHistory:()=>dd.clearChat(),setVoiceActive:e=>e?dd.startVoiceRecognition():dd.stopVoiceRecognition()};window.AgentWidgetBrowser=t,Z.push(()=>{window.AgentWidgetBrowser===t&&(window.AgentWidgetBrowser=e)})}if(typeof window<`u`){let t=e.getAttribute(`data-persona-instance`)||e.id||`persona-`+Math.random().toString(36).slice(2,8),n=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&dd.focusInput()};if(window.addEventListener(`persona:focusInput`,n),Z.push(()=>{window.removeEventListener(`persona:focusInput`,n)}),De){let e=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&dd.showEventStream()},n=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&dd.hideEventStream()};window.addEventListener(`persona:showEventStream`,e),window.addEventListener(`persona:hideEventStream`,n),Z.push(()=>{window.removeEventListener(`persona:showEventStream`,e),window.removeEventListener(`persona:hideEventStream`,n)})}let r=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&dd.showHistory()},i=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&dd.hideHistory()};window.addEventListener(`persona:showHistory`,r),window.addEventListener(`persona:hideHistory`,i),Z.push(()=>{window.removeEventListener(`persona:showHistory`,r),window.removeEventListener(`persona:hideHistory`,i)});let a=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&dd.showArtifacts()},o=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&dd.hideArtifacts()},s=e=>{let n=e.detail;n?.instanceId&&n.instanceId!==t||n?.artifact&&dd.upsertArtifact(n.artifact)},c=e=>{let n=e.detail;n?.instanceId&&n.instanceId!==t||typeof n?.id==`string`&&dd.selectArtifact(n.id)},l=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&dd.clearArtifacts()};window.addEventListener(`persona:showArtifacts`,a),window.addEventListener(`persona:hideArtifacts`,o),window.addEventListener(`persona:upsertArtifact`,s),window.addEventListener(`persona:selectArtifact`,c),window.addEventListener(`persona:clearArtifacts`,l),Z.push(()=>{window.removeEventListener(`persona:showArtifacts`,a),window.removeEventListener(`persona:hideArtifacts`,o),window.removeEventListener(`persona:upsertArtifact`,s),window.removeEventListener(`persona:selectArtifact`,c),window.removeEventListener(`persona:clearArtifacts`,l)})}let fd=ny(r.persistState);if(fd&&be()){let t=ry(fd.storage),n=`${fd.keyPrefix}widget-open`,r=`${fd.keyPrefix}widget-voice`,i=`${fd.keyPrefix}widget-voice-mode`;if(t){let a=fd.persist?.openState&&t.getItem(n)===`true`,o=fd.persist?.voiceState&&t.getItem(r)===`true`,s=fd.persist?.voiceState&&t.getItem(i)===`true`;if(a&&(Su?.setPanelOpen(!0,`auto`),setTimeout(()=>{dd.open(),setTimeout(()=>{if(o||s)dd.startVoiceRecognition();else if(fd.persist?.focusInput){let t=e.querySelector(`textarea`);t&&t.focus()}},100)},0)),fd.persist?.openState&&(O.on(`widget:opened`,()=>{t.setItem(n,`true`)}),O.on(`widget:closed`,()=>{t.setItem(n,`false`)})),fd.persist?.voiceState&&(O.on(`voice:state`,e=>{t.setItem(r,e.active?`true`:`false`)}),O.on(`user:message`,e=>{t.setItem(i,e.viaVoice?`true`:`false`)})),fd.clearOnChatClear){let e=()=>{t.removeItem(n),t.removeItem(r),t.removeItem(i)},a=()=>e();window.addEventListener(`persona:clear-chat`,a),Z.push(()=>{window.removeEventListener(`persona:clear-chat`,a)})}}}if(se&&be()&&(Su?.setPanelOpen(!0,`auto`),setTimeout(()=>{dd.open()},0)),Yo(),!ta){let e=Wt(()=>{Q&&(ea++,Gi.clear(),zo(z,Q.getMessages(),we))});Z.push(e)}x=()=>{Q&&(ea++,Gi.clear(),zo(z,Q.getMessages(),we))},Q.getMessages().length>0&&Lo(),E=()=>{Q&&(ea++,Gi.clear(),zo(z,Q.getMessages(),we))};let pd=cn(()=>{Q&&(ea++,Gi.clear(),zo(z,Q.getMessages(),we))});Z.push(pd);let md=x_(()=>{Q&&(ea++,Gi.clear(),zo(z,Q.getMessages(),we),b_()?.updateInlineArtifactBlocks(z,Or.artifacts,{suppressTransition:!0}),si())});return Z.push(md),dd};yi();const dy=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let i=/^(\d+(?:\.\d+)?)%$/i.exec(n);return i?Math.max(0,t*parseFloat(i[1])/100):420},fy=(e,t)=>{t===!1?e.style.maxHeight=``:(e.style.maxHeight=`100vh`,e.style.maxHeight=t)},py=(e,t)=>{t===!1?(e.style.position=`relative`,e.style.top=``):(e.style.position=`sticky`,e.style.top=`0`)},my=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement(`div`);r.style.cssText=`width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;`,n.appendChild(r);let i=r.offsetHeight>0;r.style.height=`100%`;let a=r.offsetHeight>0;r.remove(),i&&!a&&console.warn(`[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout.`+(t.maxHeight===!1?` The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.`:` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},hy=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className=`persona-host`,e.style.height=n?``:`100%`,e.style.display=n?``:`flex`,e.style.flexDirection=n?``:`column`,e.style.flex=n?``:`1 1 auto`,e.style.minHeight=n?``:`0`,e.style.minWidth=n?``:`0`},gy=e=>{e.style.position=``,e.style.top=``,e.style.bottom=``,e.style.left=``,e.style.right=``,e.style.zIndex=``,e.style.transform=``,e.style.pointerEvents=``},_y=e=>{e.style.inset=``,e.style.width=``,e.style.height=``,e.style.maxWidth=``,e.style.maxHeight=``,e.style.minWidth=``,gy(e)},vy=e=>{e.style.transition=``},yy=e=>{e.style.display=``,e.style.flexDirection=``,e.style.flex=``,e.style.minHeight=``,e.style.minWidth=``,e.style.width=``,e.style.height=``,e.style.alignItems=``,e.style.transition=``,e.style.transform=``,e.style.marginLeft=``},by=e=>{e.style.width=``,e.style.maxWidth=``,e.style.minWidth=``,e.style.flex=`1 1 auto`},xy=(e,t)=>{e.style.width=``,e.style.minWidth=`0`,e.style.maxWidth=``,e.style.boxSizing=``,t.style.alignItems=``},Sy=(e,t,n,r,i)=>{i?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Cy=(e,t,n,r,i,a)=>{let o=a?t:e;i===`left`?o.firstElementChild!==r&&o.replaceChildren(r,n):o.lastElementChild!==r&&o.replaceChildren(n,r)},wy=e=>{let t=Mp(e),n=t.components?.panel,r=(e,n)=>e==null||e===``?n:ap(t,e)??e;return{inset:r(n?.inset,Vf),canvasBackground:r(n?.canvasBackground,Hf)}},Ty=(e,t,n,r)=>{t?(e.style.boxSizing=`border-box`,e.style.padding=n,e.style.background=r):(e.style.padding=``,e.style.background=``,e.style.boxSizing=``)},Ey=(e,t,n,r,i,a,o,s)=>{let c=Hm(a),l=c.reveal===`push`,u=s!=null,d=s?.inset??``,f=s?.canvasBackground??``;Sy(e,t,n,r,l),Cy(e,t,n,r,c.side,l),e.dataset.personaHostLayout=`docked`,e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=o?`true`:`false`,e.style.width=`100%`,e.style.maxWidth=`100%`,e.style.minWidth=`0`,e.style.height=`100%`,e.style.minHeight=`0`,e.style.position=`relative`,n.style.display=`flex`,n.style.flexDirection=`column`,n.style.minHeight=`0`,n.style.position=`relative`,i.className=`persona-host`,i.style.height=`100%`,i.style.minHeight=`0`,i.style.minWidth=`0`,i.style.display=`flex`,i.style.flexDirection=`column`,i.style.flex=`1 1 auto`;let p=e.ownerDocument.defaultView,m=a?.launcher?.mobileFullscreen??!0,h=a?.launcher?.mobileBreakpoint??640,g=p!=null&&p.innerWidth<=h;if(m&&g&&o)e.dataset.personaDockMobileFullscreen=`true`,e.removeAttribute(`data-persona-dock-reveal`),yy(t),vy(r),_y(r),by(n),xy(i,r),Ty(r,!1,``,``),e.style.display=`flex`,e.style.flexDirection=`column`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,n.style.flex=`1 1 auto`,n.style.width=`100%`,n.style.minWidth=`0`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.position=`fixed`,r.style.inset=`0`,r.style.width=`100%`,r.style.height=`100%`,r.style.maxWidth=`100%`,r.style.minWidth=`0`,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.zIndex=String(a?.launcher?.zIndex??1e5),r.style.transform=`none`,r.style.transition=`none`,r.style.pointerEvents=`auto`,r.style.flex=`none`,l&&(t.style.display=`flex`,t.style.flexDirection=`column`,t.style.width=`100%`,t.style.height=`100%`,t.style.minHeight=`0`,t.style.minWidth=`0`,t.style.flex=`1 1 auto`,t.style.alignItems=`stretch`,t.style.transform=`none`,t.style.marginLeft=`0`,t.style.transition=`none`,n.style.flex=`1 1 auto`,n.style.width=`100%`,n.style.maxWidth=`100%`,n.style.minWidth=`0`);else if(e.removeAttribute(`data-persona-dock-mobile-fullscreen`),_y(r),fy(r,c.maxHeight),Ty(r,u&&o,d,f),c.reveal===`overlay`){e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,e.dataset.personaDockReveal=`overlay`,yy(t),vy(r),by(n),xy(i,r);let a=c.animate?`transform 180ms ease`:`none`,s=c.side===`right`?`translateX(100%)`:`translateX(-100%)`,l=o?`translateX(0)`:s;r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`none`,r.style.position=`absolute`,r.style.top=`0`,r.style.bottom=`0`,r.style.width=c.width,r.style.maxWidth=c.width,r.style.minWidth=c.width,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.transition=a,r.style.transform=l,r.style.pointerEvents=o?`auto`:`none`,r.style.zIndex=`2`,c.side===`right`?(r.style.right=`0`,r.style.left=``):(r.style.left=`0`,r.style.right=``)}else if(c.reveal===`push`){e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,e.dataset.personaDockReveal=`push`,vy(r),gy(r),xy(i,r);let a=dy(c.width,e.clientWidth),s=Math.max(0,e.clientWidth),l=c.animate?`margin-left 180ms ease`:`none`,u=c.side===`right`?o?-a:0:o?0:-a;t.style.display=`flex`,t.style.flexDirection=`row`,t.style.flex=`0 0 auto`,t.style.minHeight=`0`,t.style.minWidth=`0`,t.style.alignItems=`stretch`,t.style.height=`100%`,t.style.width=`${s+a}px`,t.style.transition=l,t.style.marginLeft=`${u}px`,t.style.transform=``,n.style.flex=`0 0 auto`,n.style.flexGrow=`0`,n.style.flexShrink=`0`,n.style.width=`${s}px`,n.style.maxWidth=`${s}px`,n.style.minWidth=`${s}px`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 auto`,r.style.flexShrink=`0`,r.style.width=c.width,r.style.minWidth=c.width,r.style.maxWidth=c.width,r.style.position=`relative`,r.style.top=``,r.style.overflow=`hidden`,r.style.transition=`none`,r.style.pointerEvents=o?`auto`:`none`}else{e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=``,yy(t),gy(r),by(n),xy(i,r);let a=c.reveal===`emerge`;a?e.dataset.personaDockReveal=`emerge`:e.removeAttribute(`data-persona-dock-reveal`);let s=o?c.width:`0px`,l=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?`, padding 180ms ease`:``}`:`none`,f=!o;if(r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 ${s}`,r.style.width=s,r.style.maxWidth=s,r.style.minWidth=s,r.style.minHeight=`0`,py(r,c.maxHeight),r.style.overflow=a||f?`hidden`:`visible`,r.style.transition=l,a){r.style.alignItems=c.side===`right`?`flex-start`:`flex-end`;let t=u?`calc(${dy(c.width,e.clientWidth)}px - (2 * ${d}))`:c.width;i.style.width=t,i.style.minWidth=t,i.style.maxWidth=t,i.style.boxSizing=`border-box`}}},Dy=(e,t)=>{let n=e.ownerDocument.createElement(`div`);return hy(n,t),e.appendChild(n),{mode:`direct`,host:n,shell:null,syncWidgetState:()=>{},updateConfig(e){hy(n,e)},destroy(){n.remove()}}},Oy=(e,t)=>{let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw Error(`Docked widget target must be attached to the DOM`);let i=e.tagName.toUpperCase();if(i===`BODY`||i===`HTML`)throw Error(`Docked widget target must be a concrete container element, not "body" or "html"`);let a=e.nextSibling,o=n.createElement(`div`),s=n.createElement(`div`),c=n.createElement(`div`),l=n.createElement(`aside`),u=n.createElement(`div`),d=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;s.dataset.personaDockRole=`push-track`,c.dataset.personaDockRole=`content`,l.dataset.personaDockRole=`panel`,u.dataset.personaDockRole=`host`,l.appendChild(u),r.insertBefore(o,e),c.appendChild(e);let f=null,p=()=>{f?.disconnect(),f=null},m=null,h=()=>{m=t?.launcher?.detachedPanel===!0?wy(t):null};h();let g=()=>{Ey(o,s,c,l,u,t,d,m)},_=null,v=()=>{_?.(),_=null,t?.launcher?.detachedPanel===!0&&t?.colorScheme===`auto`&&(_=Fp(()=>{h(),g()}))},y=()=>{p(),Hm(t).reveal===`push`&&typeof ResizeObserver<`u`&&(f=new ResizeObserver(()=>{g()}),f.observe(o))},b=!1,x=()=>{g(),y(),d&&!b&&o.dataset.personaDockMobileFullscreen!==`true`&&(b=!0,my(o,Hm(t)))},S=o.ownerDocument.defaultView,C=()=>{x()};return S?.addEventListener(`resize`,C),Hm(t).reveal===`push`?(s.appendChild(c),s.appendChild(l),o.appendChild(s)):(o.appendChild(c),o.appendChild(l)),x(),v(),{mode:`docked`,host:u,shell:o,syncWidgetState(e){let t=!e.launcherEnabled||e.open;d!==t&&(d=t,x())},updateConfig(e){t=e,(t?.launcher?.enabled??!0)===!1&&(d=!0),h(),x(),v()},destroy(){S?.removeEventListener(`resize`,C),_?.(),_=null,p(),r.isConnected&&(a&&a.parentNode===r?r.insertBefore(e,a):r.appendChild(e)),o.remove()}}},ky=(e,t)=>Bm(t)?Oy(e,t):Dy(e,t),Ay=e=>{if(typeof window>`u`||typeof document>`u`)throw Error(`Chat widget can only be mounted in a browser environment`);if(typeof e==`string`){let t=document.querySelector(e);if(!t)throw Error(`Chat widget target "${e}" was not found`);return t}return e},jy=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector(`link[data-persona]`))return;let n=t.head.querySelector(`link[data-persona]`);if(!n)return;let r=n.cloneNode(!0);e.insertBefore(r,e.firstChild)},My=[],Ny=()=>[...My],Py=e=>{let t=Ay(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,i=e.config,a=ky(t,i),o,s=[],c=(e,i)=>{let a=!(i?.launcher?.enabled??!0)||Bm(i),o=r.createElement(`div`);if(o.setAttribute(`data-persona-root`,`true`),a&&(o.style.height=`100%`,o.style.display=`flex`,o.style.flexDirection=`column`,o.style.flex=`1`,o.style.minHeight=`0`,o.style.minWidth=`0`),n){let t=e.attachShadow({mode:`open`});t.appendChild(o),jy(t,r)}else e.appendChild(o),jy(e,r);return t.id&&o.setAttribute(`data-persona-instance`,t.id),o},l=()=>{a.syncWidgetState(o.getState())},u=()=>{s.forEach(e=>e()),s=[o.on(`widget:opened`,l),o.on(`widget:closed`,l)],l()},d=()=>{let t=c(a.host,i);o=uy(t,i,{debugTools:e.debugTools}),u()},f=()=>{s.forEach(e=>e()),s=[],o.destroy()};d(),e.onChatReady?.();let p=e=>{f(),a.destroy(),a=ky(t,e),i=e,d()},m=new Proxy({update(e){let t=gv(i??{},e),n=Bm(i),r=Bm(t),s=Vm(i),c=Vm(t);n!==r||s!==c?p(t):(i=t,a.updateConfig(i),o.update(e),l())},destroy(){f(),a.destroy();let t=My.indexOf(m);t!==-1&&My.splice(t,1),e.windowKey&&typeof window<`u`&&delete window[e.windowKey]}},{get(e,t,n){if(t===`host`)return a.host;if(t in e)return Reflect.get(e,t,n);let r=o[t];return typeof r==`function`?r.bind(o):r}});return My.push(m),e.windowKey&&typeof window<`u`&&(window[e.windowKey]=m),m},Fy=/* @__PURE__ */ new Set([`script`,`style`,`noscript`,`svg`,`path`,`meta`,`link`,`br`,`hr`]),Iy=/* @__PURE__ */ new Set([`button`,`a`,`input`,`select`,`textarea`,`details`,`summary`]),Ly=/* @__PURE__ */ new Set([`button`,`link`,`menuitem`,`tab`,`option`,`switch`,`checkbox`,`radio`,`combobox`,`listbox`,`slider`,`spinbutton`,`textbox`]),Ry=/\b(product|card|item|listing|result)\b/i,zy=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i;function By(e){let t=typeof e.className==`string`?e.className:``;if(Ry.test(t)||e.id&&Ry.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith(`data-`)&&Ry.test(n.value))return!0}return!1}function Vy(e){return zy.test((e.textContent??``).trim())}function Hy(e){let t=e.querySelectorAll(`a[href]`);for(let e=0;e<t.length;e++){let n=t[e].getAttribute(`href`)??``;if(n&&n!==`#`&&!n.toLowerCase().startsWith(`javascript:`))return!0}return!1}function Uy(e){return!!e.querySelector(`button, [role="button"], input[type="submit"], input[type="button"]`)}function Wy(e){let t=e.match(zy);return t?t[0]:null}function Gy(e){let t=e.querySelector(`.product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]`)??e.querySelector(`a[href]`);if(t&&t.textContent?.trim()){let e=t.getAttribute(`href`);return{title:t.textContent.trim(),href:e&&e!==`#`?e:null}}let n=e.querySelector(`h1, h2, h3, h4, h5, h6`);return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:``,href:null}}function Ky(e){let t=[],n=e=>{let n=e.trim();n&&!t.includes(n)&&t.push(n)};return e.querySelectorAll(`button`).forEach(e=>n(e.textContent??``)),e.querySelectorAll(`[role="button"]`).forEach(e=>n(e.textContent??``)),e.querySelectorAll(`input[type="submit"], input[type="button"]`).forEach(e=>{n(e.value??``)}),t.slice(0,6)}function qy(e){return!By(e)||!Vy(e)||!Hy(e)&&!Uy(e)?0:5200}function Jy(e){return!By(e)||Vy(e)||!Hy(e)||(e.textContent??``).trim().length<20||!(e.querySelector(`h1, h2, h3, h4, h5, h6, .title`)||e.querySelector(`.snippet, .description, p`))?0:2800}const Yy=[{id:`commerce-card`,scoreElement(e){return qy(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity===`static`){let e=n.text.trim();return!!(e.length===0||zy.test(e)&&e.length<32)}return!0},formatSummary(e,t){if(qy(e)===0)return null;let{title:n,href:r}=Gy(e),i=Wy((e.textContent??``).trim())??Wy(t.text)??``,a=Ky(e);return[r&&n?`[${n}](${r})${i?`: ${i}`:``}`:n?`${n}${i?`: ${i}`:``}`:i||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(`, `)}`:``].filter(Boolean).join(`
|
|
135
|
+
`)}},{id:`result-card`,scoreElement(e){return Jy(e)},formatSummary(e,t){if(Jy(e)===0)return null;let{title:n,href:r}=Gy(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
136
|
+
`)}}];function Xy(){typeof console<`u`&&typeof console.warn==`function`&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Zy(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,r=t.excludeSelector??e.excludeSelector??`.persona-host`,i=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,o=t.root??e.root,s=t.mode??`structured`,c=t.maxCandidates??Math.max(500,n*10),l=e.rules??Yy;return s===`simple`&&e.rules&&e.rules.length>0?(Xy(),l=[]):s===`simple`&&(l=[]),{mode:s,maxElements:n,maxCandidates:c,excludeSelector:r,maxTextLength:i,visibleOnly:a,root:o,rules:l}}function Qy(e){return typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/([^\w-])/g,`\\$1`)}const $y=[`data-testid`,`data-product`,`data-action`,`data-id`,`data-name`,`data-type`];function eb(e){let t=e.tagName.toLowerCase(),n=e.getAttribute(`role`);return t===`a`&&e.hasAttribute(`href`)?`navigable`:t===`input`||t===`select`||t===`textarea`||n===`textbox`||n===`combobox`||n===`listbox`||n===`spinbutton`?`input`:t===`button`||n===`button`||Iy.has(t)||n&&Ly.has(n)||e.hasAttribute(`tabindex`)||e.hasAttribute(`onclick`)||e.getAttribute(`contenteditable`)===`true`?`clickable`:`static`}function tb(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`)return!1}catch{}return e.style.display!==`none`&&e.style.visibility!==`hidden`}function nb(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute(`href`);r&&(t.href=r);let i=e.getAttribute(`aria-label`);i&&(t[`aria-label`]=i);let a=e.getAttribute(`type`);a&&(t.type=a);let o=e.getAttribute(`value`);o&&(t.value=o);let s=e.getAttribute(`name`);s&&(t.name=s);let c=e.getAttribute(`role`);c&&(t.role=c);for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];r.name.startsWith(`data-`)&&(t[r.name]=r.value)}return t}function rb(e){let t=e.tagName.toLowerCase();if(e.id){let t=`#${Qy(e.id)}`;try{if(e.ownerDocument.querySelectorAll(t).length===1)return t}catch{}}for(let n of $y){let r=e.getAttribute(n);if(r){let i=`${t}[${n}="${Qy(r)}"]`;try{if(e.ownerDocument.querySelectorAll(i).length===1)return i}catch{}}}let n=Array.from(e.classList).filter(e=>e&&!e.startsWith(`persona-`)).slice(0,3);if(n.length>0){let r=`${t}.${n.map(e=>Qy(e)).join(`.`)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let i=e.parentElement;if(i){let n=Array.from(i.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(n>=0){let t=`${r}:nth-of-type(${n+1})`;try{if(e.ownerDocument.querySelectorAll(t).length===1)return t}catch{}}}}let r=e.parentElement;if(r){let n=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(n>=0)return`${t}:nth-of-type(${n+1})`}return t}function ib(e){return e===`static`?100:3e3}function ab(e,t){let n=e.tagName.toLowerCase(),r=(e.textContent??``).trim().substring(0,t);return{selector:rb(e),tagName:n,text:r,role:e.getAttribute(`role`),interactivity:eb(e),attributes:nb(e)}}function ob(e,t,n,r){let i=ib(t.interactivity),a=null;for(let o of n){let n=o.scoreElement(e,t,r);n>0&&(i+=n,o.formatSummary&&!a&&(a=o))}return{score:i,formattingRule:a}}function sb(e,t){for(let n of e)if(t.el!==n.el&&n.formattingRule?.shouldSuppressDescendant&&n.el.contains(t.el)&&n.formattingRule.shouldSuppressDescendant(n.el,t.el,t.enriched))return!0;return!1}function cb(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=/* @__PURE__ */ new Set,i=[],a=0,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&i.length<e.maxCandidates;){if(s.nodeType===Node.ELEMENT_NODE){let t=s,c=t.tagName.toLowerCase();if(Fy.has(c)){s=o.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!tb(t)){s=o.nextNode();continue}let l=ab(t,e.maxTextLength),u=l.text.length>0,d=Object.keys(l.attributes).length>0&&!Object.keys(l.attributes).every(e=>e===`role`);if(!u&&!d||r.has(l.selector)){s=o.nextNode();continue}r.add(l.selector);let{score:f,formattingRule:p}=ob(t,l,e.rules,n);i.push({el:t,domIndex:a,enriched:l,score:f,formattingRule:p}),a+=1}s=o.nextNode()}i.sort((e,t)=>{let n=+(e.enriched.interactivity===`static`),r=+(t.enriched.interactivity===`static`);return n===r?t.score===e.score?e.domIndex-t.domIndex:t.score-e.score:n-r});let c=[];for(let t of i){if(c.length>=e.maxElements)break;sb(c,t)||c.push(t)}return c.sort((e,t)=>{let n=+(e.enriched.interactivity===`static`),r=+(t.enriched.interactivity===`static`);return n===r?n===1&&t.score!==e.score?t.score-e.score:e.domIndex-t.domIndex:n-r}),c.map(e=>{let t;if(e.formattingRule?.formatSummary){let r=e.formattingRule.formatSummary(e.el,e.enriched,n);r&&(t=r)}let r={...e.enriched};return t&&(r.formattedSummary=t),r})}function lb(e,t){let n=[],r=/* @__PURE__ */ new Set,i=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=i.currentNode;for(;a&&n.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let t=a,o=t.tagName.toLowerCase();if(Fy.has(o)){a=i.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){a=i.nextNode();continue}}catch{}if(e.visibleOnly&&!tb(t)){a=i.nextNode();continue}let s=ab(t,e.maxTextLength),c=s.text.length>0,l=Object.keys(s.attributes).length>0&&!Object.keys(s.attributes).every(e=>e===`role`);if(!c&&!l){a=i.nextNode();continue}r.has(s.selector)||(r.add(s.selector),n.push(s))}a=i.nextNode()}let o=[],s=[];for(let e of n)e.interactivity===`static`?s.push(e):o.push(e);return[...o,...s].slice(0,e.maxElements)}function ub(e={}){let t=Zy(e),n=t.root??document.body;return n?t.mode===`simple`?lb(t,n):cb(t,n):[]}function db(e,t={}){if(e.length===0)return`No page elements found.`;let n=t.mode??`structured`,r=[];if(n===`structured`){let t=e.map(e=>e.formattedSummary).filter(e=>!!e&&e.length>0);t.length>0&&r.push(`Structured summaries:\n${t.map(e=>`- ${e.split(`
|
|
137
137
|
`).join(`
|
|
138
138
|
`)}`).join(`
|
|
139
139
|
`)}`)}let i={clickable:[],navigable:[],input:[],static:[]};for(let t of e)n===`structured`&&t.formattedSummary||i[t.interactivity].push(t);if(i.clickable.length>0){let e=i.clickable.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}" (clickable)`);r.push(`Interactive elements:\n${e.join(`
|
|
@@ -142,7 +142,7 @@ import{Marked as e,Marked as t}from"marked";import n,{default as r}from"dompurif
|
|
|
142
142
|
`)}`)}if(i.static.length>0){let e=i.static.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}"`);r.push(`Content:\n${e.join(`
|
|
143
143
|
`)}`)}return r.join(`
|
|
144
144
|
|
|
145
|
-
`)}No();const
|
|
145
|
+
`)}No();const fb={palette:{colors:{primary:{500:`#111827`},accent:{600:`#1d4ed8`},gray:{50:`#ffffff`,100:`#f8fafc`,200:`#f1f5f9`,500:`#6b7280`,900:`#000000`}},radius:{sm:`0.75rem`,md:`1rem`,lg:`1.5rem`,launcher:`9999px`,button:`9999px`}},semantic:{colors:{primary:`palette.colors.primary.500`,textInverse:`palette.colors.gray.50`}}},pb={components:{panel:{borderRadius:`0`,shadow:`none`}}},mb={id:`shop`,label:`Shopping Assistant`,config:{theme:fb,launcher:{title:`Shopping Assistant`,subtitle:`Here to help you find what you need`,agentIconText:`🛍️`,position:`bottom-right`,width:xo},copy:{welcomeTitle:`Welcome to our shop!`,welcomeSubtitle:`I can help you find products and answer questions`,inputPlaceholder:`Ask me anything...`,sendButtonLabel:`Send`},suggestionChips:[`Show me what you can help with`,`Walk me through getting started`,`Answer a question about this page`]}},hb={id:`minimal`,label:`Minimal`,config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:`minimal`,showCloseButton:!1},messages:{layout:`minimal`}},theme:pb}},gb={id:`fullscreen`,label:`Fullscreen Assistant`,config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:`minimal`,showCloseButton:!1},contentMaxWidth:`72ch`},theme:pb}},_b={shop:mb,minimal:hb,fullscreen:gb};function vb(e){return _b[e]}Nn(),ti(),Z(),fi(),En(),er(),$o(),Xs(),Ri(),mn(),No();var yb=Py;function bb(){return{name:`@persona/accessibility`,version:`1.0.0`,transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:`palette.colors.primary.700`,disabled:`palette.colors.gray.300`}}}}},cssVariables:{"--persona-accessibility-focus-ring":`0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)`}}}function xb(){return{name:`@persona/animations`,version:`1.0.0`,transform(e){return{...e,palette:{...e.palette,transitions:{fast:`150ms`,normal:`200ms`,slow:`300ms`,bounce:`500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)`},easings:{easeIn:`cubic-bezier(0.4, 0, 1, 1)`,easeOut:`cubic-bezier(0, 0, 0.2, 1)`,easeInOut:`cubic-bezier(0.4, 0, 0.2, 1)`}}}},cssVariables:{"--persona-transition-fast":`150ms ease`,"--persona-transition-normal":`200ms ease`,"--persona-transition-slow":`300ms ease`}}}function Sb(e){return{name:`@persona/brand`,version:`1.0.0`,transform(t){let n={...t.palette};return e.colors?.primary&&(n.colors={...n.colors,primary:{50:Tb(e.colors.primary,.95),100:Tb(e.colors.primary,.9),200:Tb(e.colors.primary,.8),300:Tb(e.colors.primary,.7),400:Tb(e.colors.primary,.6),500:e.colors.primary,600:Tb(e.colors.primary,.8),700:Tb(e.colors.primary,.7),800:Tb(e.colors.primary,.6),900:Tb(e.colors.primary,.5),950:Tb(e.colors.primary,.45)}}),{...t,palette:n}}}}function Cb(){return{name:`@persona/reduced-motion`,version:`1.0.0`,transform(e){return{...e,palette:{...e.palette,transitions:{fast:`0ms`,normal:`0ms`,slow:`0ms`,bounce:`0ms`}}}},afterResolve(e){return{...e,"--persona-transition-fast":`0ms`,"--persona-transition-normal":`0ms`,"--persona-transition-slow":`0ms`}}}}function wb(){return{name:`@persona/high-contrast`,version:`1.0.0`,transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:`palette.colors.gray.950`,textMuted:`palette.colors.gray.700`,border:`palette.colors.gray.900`,divider:`palette.colors.gray.900`}}}}}}function Tb(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),i=parseInt(e.slice(5,7),16),a=Math.round(n+(255-n)*(1-t)),o=Math.round(r+(255-r)*(1-t)),s=Math.round(i+(255-i)*(1-t));return`#${a.toString(16).padStart(2,`0`)}${o.toString(16).padStart(2,`0`)}${s.toString(16).padStart(2,`0`)}`}function Eb(e){return{name:e.name,version:e.version,transform:e.transform||(e=>e),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}Ri();function Db(e){return e?.cdnBase?.trim().replace(/\/+$/,``).replace(/[\\'"<>`]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`)}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Li}/dist`}function Ob(e){if(e!==void 0)return typeof e==`string`?e:Array.isArray(e)?`[${e.map(e=>e.toString()).join(`, `)}]`:e.toString()}function kb(e){if(e)return{getHeaders:Ob(e.getHeaders),onFeedback:Ob(e.onFeedback),onCopy:Ob(e.onCopy),requestMiddleware:Ob(e.requestMiddleware),actionHandlers:Ob(e.actionHandlers),actionParsers:Ob(e.actionParsers),postprocessMessage:Ob(e.postprocessMessage),contextProviders:Ob(e.contextProviders),streamParser:Ob(e.streamParser)}}const Ab=`({ text, message }: any) => {
|
|
146
146
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
147
147
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
148
148
|
let cleanJson = jsonSource
|
|
@@ -155,7 +155,7 @@ import{Marked as e,Marked as t}from"marked";import n,{default as r}from"dompurif
|
|
|
155
155
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
156
156
|
} catch (e) { return null; }
|
|
157
157
|
return null;
|
|
158
|
-
}`,
|
|
158
|
+
}`,jb=`function(ctx) {
|
|
159
159
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
160
160
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
161
161
|
var cleanJson = jsonSource
|
|
@@ -168,7 +168,7 @@ import{Marked as e,Marked as t}from"marked";import n,{default as r}from"dompurif
|
|
|
168
168
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
169
169
|
} catch (e) { return null; }
|
|
170
170
|
return null;
|
|
171
|
-
}`,
|
|
171
|
+
}`,Mb=`(action: any, context: any) => {
|
|
172
172
|
if (action.type !== 'nav_then_click') return;
|
|
173
173
|
const payload = action.payload || action.raw || {};
|
|
174
174
|
const url = payload?.page;
|
|
@@ -185,7 +185,7 @@ import{Marked as e,Marked as t}from"marked";import n,{default as r}from"dompurif
|
|
|
185
185
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
186
186
|
window.location.href = targetUrl;
|
|
187
187
|
return { handled: true, displayText: text };
|
|
188
|
-
}`,
|
|
188
|
+
}`,Nb=`function(action, context) {
|
|
189
189
|
if (action.type !== 'nav_then_click') return;
|
|
190
190
|
var payload = action.payload || action.raw || {};
|
|
191
191
|
var url = payload.page;
|
|
@@ -202,27 +202,27 @@ import{Marked as e,Marked as t}from"marked";import n,{default as r}from"dompurif
|
|
|
202
202
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
203
203
|
window.location.href = targetUrl;
|
|
204
204
|
return { handled: true, displayText: text };
|
|
205
|
-
}`;function
|
|
206
|
-
`);return n.map((e,r)=>`${r===0?`${t}suggestions: `:t}${e}${r===n.length-1?`,`:``}`)}function
|
|
207
|
-
`)}function
|
|
208
|
-
`)}function
|
|
205
|
+
}`;function Pb(e){if(!e)return null;let t=e.toString();return t.includes(`createJsonStreamParser`)||t.includes(`partial-json`)?`json`:t.includes(`createRegexJsonParser`)||t.includes(`regex`)?`regex-json`:t.includes(`createXmlParser`)||t.includes(`<text>`)?`xml`:null}function Fb(e){return e.parserType??Pb(e.streamParser)??`plain`}function Ib(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([e,r])=>{typeof r==`string`&&n.push(`${t} ${e}: "${r}",`)}),n.push(`${t}},`)),n}function Lb(e,t,n){let r=[],i=e.messageActions&&Object.entries(e.messageActions).some(([e,t])=>e!==`onFeedback`&&e!==`onCopy`&&t!==void 0),a=n?.onFeedback||n?.onCopy;return(i||a)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([e,n])=>{e!==`onFeedback`&&e!==`onCopy`&&(typeof n==`string`?r.push(`${t} ${e}: "${n}",`):typeof n==`boolean`&&r.push(`${t} ${e}: ${n},`))}),n?.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function Rb(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,i=e.markdown.disableDefaultStyles!==void 0;(r||i)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([e,r])=>{typeof r==`string`?n.push(`${t} ${e}: "${r}",`):typeof r==`boolean`&&n.push(`${t} ${e}: ${r},`)}),n.push(`${t} },`)),i&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function zb(e,t){if(!e.suggestions)return[];let n=JSON.stringify(e.suggestions,null,2).split(`
|
|
206
|
+
`);return n.map((e,r)=>`${r===0?`${t}suggestions: `:t}${e}${r===n.length-1?`,`:``}`)}function Bb(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(e=>e!==`render`),i=e.layout.messages&&Object.keys(e.layout.messages).some(e=>e!==`renderUserMessage`&&e!==`renderAssistantMessage`);(r||i)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([e,r])=>{e!==`render`&&(typeof r==`string`?n.push(`${t} ${e}: "${r}",`):typeof r==`boolean`&&n.push(`${t} ${e}: ${r},`))}),n.push(`${t} },`)),i&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([e,r])=>{e!==`renderUserMessage`&&e!==`renderAssistantMessage`&&(e===`avatar`&&typeof r==`object`&&r?(n.push(`${t} avatar: {`),Object.entries(r).forEach(([e,r])=>{typeof r==`string`?n.push(`${t} ${e}: "${r}",`):typeof r==`boolean`&&n.push(`${t} ${e}: ${r},`)}),n.push(`${t} },`)):e===`timestamp`&&typeof r==`object`&&r?Object.entries(r).some(([e])=>e!==`format`)&&(n.push(`${t} timestamp: {`),Object.entries(r).forEach(([e,r])=>{e!==`format`&&(typeof r==`string`?n.push(`${t} ${e}: "${r}",`):typeof r==`boolean`&&n.push(`${t} ${e}: ${r},`))}),n.push(`${t} },`)):typeof r==`string`?n.push(`${t} ${e}: "${r}",`):typeof r==`boolean`&&n.push(`${t} ${e}: ${r},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Vb(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function Hb(e,t,n){Object.entries(t).forEach(([t,r])=>{r!==void 0&&typeof r!=`function`&&(Array.isArray(r)?e.push(`${n}${t}: ${JSON.stringify(r)},`):r&&typeof r==`object`?(e.push(`${n}${t}: {`),Hb(e,r,`${n} `),e.push(`${n}},`)):e.push(`${n}${t}: ${JSON.stringify(r)},`))})}function Ub(e,t,n,r){n&&(e.push(`${r}${t}: {`),Hb(e,n,`${r} `),e.push(`${r}},`))}function Wb(e,t,n){t.future?.v5Defaults!==void 0&&e.push(`${n}future: { v5Defaults: ${t.future.v5Defaults===!0} },`)}function Gb(e){return(e?.target??`body`).replace(/\\/g,`\\\\`).replace(/'/g,`\\'`)}function Kb(e,t=`esm`,n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let i=n?{...n,hooks:kb(n.hooks)}:void 0;return t===`esm`?qb(r,i):t===`script-installer`?Zb(r,i):t===`script-advanced`?$b(r,i):t===`react-component`?Jb(r,i):t===`react-advanced`?Yb(r,i):Qb(r,i)}function qb(e,t){let n=t?.hooks,r=Fb(e),i=r!==`plain`,a=[`import '@runtypelabs/persona/widget.css';`,`import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';`,``,`initAgentWidget({`,` target: '${Gb(t)}',`,` config: {`];return e.apiUrl&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.agentId&&a.push(` agentId: "${e.agentId}",`),e.target&&a.push(` target: "${e.target}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),i&&a.push(` parserType: "${r}",`),Wb(a,e,` `),e.theme&&typeof e.theme==`object`&&Object.keys(e.theme).length>0&&Ub(a,`theme`,e.theme,` `),e.launcher&&Ub(a,`launcher`,e.launcher,` `),e.copy&&(a.push(` copy: {`),Object.entries(e.copy).forEach(([e,t])=>{a.push(` ${e}: "${t}",`)}),a.push(` },`)),e.sendButton&&(a.push(` sendButton: {`),Object.entries(e.sendButton).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):typeof t==`boolean`&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.voiceRecognition&&(a.push(` voiceRecognition: {`),Object.entries(e.voiceRecognition).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):(typeof t==`boolean`||typeof t==`number`)&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.statusIndicator&&(a.push(` statusIndicator: {`),Object.entries(e.statusIndicator).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):typeof t==`boolean`&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.features&&(a.push(` features: {`),Object.entries(e.features).forEach(([e,t])=>{a.push(` ${e}: ${t},`)}),a.push(` },`)),a.push(...zb(e,` `)),e.suggestionChips&&e.suggestionChips.length>0&&(a.push(` suggestionChips: [`),e.suggestionChips.forEach(e=>{a.push(` "${e}",`)}),a.push(` ],`)),e.suggestionChipsConfig&&(a.push(` suggestionChipsConfig: {`),e.suggestionChipsConfig.fontFamily&&a.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&a.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&a.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&a.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),a.push(` },`)),a.push(...Ib(e,` `)),a.push(...Lb(e,` `,n)),a.push(...Rb(e,` `)),a.push(...Bb(e,` `)),a.push(...Vb(n,` `)),e.debug&&a.push(` debug: ${e.debug},`),n?.postprocessMessage?a.push(` postprocessMessage: ${n.postprocessMessage}`):a.push(` postprocessMessage: ({ text }) => markdownPostprocessor(text)`),a.push(` }`),a.push(`});`),a.join(`
|
|
207
|
+
`)}function Jb(e,t){let n=t?.hooks,r=Fb(e),i=r!==`plain`,a=[`// ChatWidget.tsx`,`'use client'; // Required for Next.js - remove for Vite/CRA`,``,`import { useEffect } from 'react';`,`import '@runtypelabs/persona/widget.css';`,`import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';`,`import type { AgentWidgetInitHandle } from '@runtypelabs/persona';`,``,`export function ChatWidget() {`,` useEffect(() => {`,` let handle: AgentWidgetInitHandle | null = null;`,``,` handle = initAgentWidget({`,` target: '${Gb(t)}',`,` config: {`];return e.apiUrl&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.agentId&&a.push(` agentId: "${e.agentId}",`),e.target&&a.push(` target: "${e.target}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),i&&a.push(` parserType: "${r}",`),Wb(a,e,` `),e.theme&&typeof e.theme==`object`&&Object.keys(e.theme).length>0&&Ub(a,`theme`,e.theme,` `),e.launcher&&Ub(a,`launcher`,e.launcher,` `),e.copy&&(a.push(` copy: {`),Object.entries(e.copy).forEach(([e,t])=>{a.push(` ${e}: "${t}",`)}),a.push(` },`)),e.sendButton&&(a.push(` sendButton: {`),Object.entries(e.sendButton).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):typeof t==`boolean`&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.voiceRecognition&&(a.push(` voiceRecognition: {`),Object.entries(e.voiceRecognition).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):(typeof t==`boolean`||typeof t==`number`)&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.statusIndicator&&(a.push(` statusIndicator: {`),Object.entries(e.statusIndicator).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):typeof t==`boolean`&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.features&&(a.push(` features: {`),Object.entries(e.features).forEach(([e,t])=>{a.push(` ${e}: ${t},`)}),a.push(` },`)),a.push(...zb(e,` `)),e.suggestionChips&&e.suggestionChips.length>0&&(a.push(` suggestionChips: [`),e.suggestionChips.forEach(e=>{a.push(` "${e}",`)}),a.push(` ],`)),e.suggestionChipsConfig&&(a.push(` suggestionChipsConfig: {`),e.suggestionChipsConfig.fontFamily&&a.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&a.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&a.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&a.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),a.push(` },`)),a.push(...Ib(e,` `)),a.push(...Lb(e,` `,n)),a.push(...Rb(e,` `)),a.push(...Bb(e,` `)),a.push(...Vb(n,` `)),e.debug&&a.push(` debug: ${e.debug},`),n?.postprocessMessage?a.push(` postprocessMessage: ${n.postprocessMessage}`):a.push(` postprocessMessage: ({ text }) => markdownPostprocessor(text)`),a.push(` }`),a.push(` });`),a.push(``),a.push(` // Cleanup on unmount`),a.push(` return () => {`),a.push(` if (handle) {`),a.push(` handle.destroy();`),a.push(` }`),a.push(` };`),a.push(` }, []);`),a.push(``),a.push(` return null; // Widget injects itself into the DOM`),a.push(`}`),a.push(``),a.push(`// Usage in your app:`),a.push(`// import { ChatWidget } from './components/ChatWidget';`),a.push(`//`),a.push(`// export default function App() {`),a.push(`// return (`),a.push(`// <div>`),a.push(`// {/* Your app content */}`),a.push(`// <ChatWidget />`),a.push(`// </div>`),a.push(`// );`),a.push(`// }`),a.join(`
|
|
208
|
+
`)}function Yb(e,t){let n=t?.hooks,r=[`// ChatWidgetAdvanced.tsx`,`'use client'; // Required for Next.js - remove for Vite/CRA`,``,`import { useEffect } from 'react';`,`import '@runtypelabs/persona/widget.css';`,`import {`,` initAgentWidget,`,` createFlexibleJsonStreamParser,`,` defaultJsonActionParser,`,` defaultActionHandlers,`,` markdownPostprocessor`,`} from '@runtypelabs/persona';`,`import type { AgentWidgetInitHandle } from '@runtypelabs/persona';`,``,`const STORAGE_KEY = 'chat-widget-state';`,`const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';`,``,`// Types for DOM elements`,`interface PageElement {`,` type: string;`,` tagName: string;`,` selector: string;`,` innerText: string;`,` href?: string;`,`}`,``,`interface DOMContext {`,` page_elements: PageElement[];`,` page_element_count: number;`,` element_types: Record<string, number>;`,` page_url: string;`,` page_title: string;`,` timestamp: string;`,`}`,``,`// DOM context provider - extracts page elements for AI context`,`const collectDOMContext = (): DOMContext => {`,` const selectors = {`,` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`,` links: 'a[href]',`,` inputs: 'input, textarea, select'`,` };`,``,` const elements: PageElement[] = [];`,` Object.entries(selectors).forEach(([type, selector]) => {`,` document.querySelectorAll(selector).forEach((element) => {`,` if (!(element instanceof HTMLElement)) return;`,` `,` // Exclude elements within the widget`,` const widgetHost = element.closest('.persona-host');`,` if (widgetHost) return;`,` `,` const text = element.innerText?.trim();`,` if (!text) return;`,``,` const selectorString =`," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :",` element.tagName.toLowerCase();`,``,` const elementData: PageElement = {`,` type,`,` tagName: element.tagName.toLowerCase(),`,` selector: selectorString,`,` innerText: text.substring(0, 200)`,` };`,``,` if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {`,` elementData.href = element.href;`,` }`,``,` elements.push(elementData);`,` });`,` });`,``,` const counts = elements.reduce((acc, el) => {`,` acc[el.type] = (acc[el.type] || 0) + 1;`,` return acc;`,` }, {} as Record<string, number>);`,``,` return {`,` page_elements: elements.slice(0, 50),`,` page_element_count: elements.length,`,` element_types: counts,`,` page_url: window.location.href,`,` page_title: document.title,`,` timestamp: new Date().toISOString()`,` };`,`};`,``,`export function ChatWidgetAdvanced() {`,` useEffect(() => {`,` let handle: AgentWidgetInitHandle | null = null;`,``,` // Load saved state`,` const loadSavedMessages = () => {`,` const savedState = localStorage.getItem(STORAGE_KEY);`,` if (savedState) {`,` try {`,` const { messages } = JSON.parse(savedState);`,` return messages || [];`,` } catch (e) {`,` console.error('Failed to load saved state:', e);`,` }`,` }`,` return [];`,` };`,``,` handle = initAgentWidget({`,` target: '${Gb(t)}',`,` config: {`];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),Wb(r,e,` `),e.theme&&typeof e.theme==`object`&&Object.keys(e.theme).length>0&&Ub(r,`theme`,e.theme,` `),e.launcher&&Ub(r,`launcher`,e.launcher,` `),e.copy&&(r.push(` copy: {`),Object.entries(e.copy).forEach(([e,t])=>{r.push(` ${e}: "${t}",`)}),r.push(` },`)),e.sendButton&&(r.push(` sendButton: {`),Object.entries(e.sendButton).forEach(([e,t])=>{typeof t==`string`?r.push(` ${e}: "${t}",`):typeof t==`boolean`&&r.push(` ${e}: ${t},`)}),r.push(` },`)),e.voiceRecognition&&(r.push(` voiceRecognition: {`),Object.entries(e.voiceRecognition).forEach(([e,t])=>{typeof t==`string`?r.push(` ${e}: "${t}",`):(typeof t==`boolean`||typeof t==`number`)&&r.push(` ${e}: ${t},`)}),r.push(` },`)),e.statusIndicator&&(r.push(` statusIndicator: {`),Object.entries(e.statusIndicator).forEach(([e,t])=>{typeof t==`string`?r.push(` ${e}: "${t}",`):typeof t==`boolean`&&r.push(` ${e}: ${t},`)}),r.push(` },`)),e.features&&(r.push(` features: {`),Object.entries(e.features).forEach(([e,t])=>{r.push(` ${e}: ${t},`)}),r.push(` },`)),r.push(...zb(e,` `)),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(` suggestionChips: [`),e.suggestionChips.forEach(e=>{r.push(` "${e}",`)}),r.push(` ],`)),e.suggestionChipsConfig&&(r.push(` suggestionChipsConfig: {`),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(` },`)),r.push(...Ib(e,` `)),r.push(...Lb(e,` `,n)),r.push(...Rb(e,` `)),r.push(...Bb(e,` `)),n?.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(` initialMessages: loadSavedMessages(),`),n?.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(` // Flexible JSON stream parser for handling structured actions`),r.push(` streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {
|
|
209
209
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
210
210
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
211
211
|
if (parsed.action === 'message') return parsed.text || '';
|
|
212
212
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
213
213
|
return parsed.text || null;
|
|
214
|
-
}),`)),n?.actionParsers?(r.push(` // Action parsers (custom merged with defaults)`),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(` // Built-in parser for markdown-wrapped JSON`),r.push(` ${
|
|
215
|
-
`)}function
|
|
216
|
-
`)}function
|
|
214
|
+
}),`)),n?.actionParsers?(r.push(` // Action parsers (custom merged with defaults)`),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(` // Built-in parser for markdown-wrapped JSON`),r.push(` ${Ab}`),r.push(` ],`)):(r.push(` // Action parsers to detect JSON actions in responses`),r.push(` actionParsers: [`),r.push(` defaultJsonActionParser,`),r.push(` // Parser for markdown-wrapped JSON`),r.push(` ${Ab}`),r.push(` ],`)),n?.actionHandlers?(r.push(` // Action handlers (custom merged with defaults)`),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(` defaultActionHandlers.message,`),r.push(` defaultActionHandlers.messageAndClick,`),r.push(` // Built-in handler for nav_then_click action`),r.push(` ${Mb}`),r.push(` ],`)):(r.push(` // Action handlers for navigation and other actions`),r.push(` actionHandlers: [`),r.push(` defaultActionHandlers.message,`),r.push(` defaultActionHandlers.messageAndClick,`),r.push(` // Handler for nav_then_click action`),r.push(` ${Mb}`),r.push(` ],`)),n?.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(` postprocessMessage: ({ text }) => markdownPostprocessor(text),`),n?.requestMiddleware?(r.push(` // Request middleware (custom merged with DOM context)`),r.push(` requestMiddleware: ({ payload, config }) => {`),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(` const merged = customResult || payload;`),r.push(` return {`),r.push(` ...merged,`),r.push(` metadata: { ...merged.metadata, ...collectDOMContext() }`),r.push(` };`),r.push(` }`)):(r.push(` requestMiddleware: ({ payload }) => {`),r.push(` return {`),r.push(` ...payload,`),r.push(` metadata: collectDOMContext()`),r.push(` };`),r.push(` }`)),r.push(` }`),r.push(` });`),r.push(``),r.push(` // Save state on message events`),r.push(` const handleMessage = () => {`),r.push(` const session = handle?.getSession?.();`),r.push(` if (session) {`),r.push(` localStorage.setItem(STORAGE_KEY, JSON.stringify({`),r.push(` messages: session.messages,`),r.push(` timestamp: new Date().toISOString()`),r.push(` }));`),r.push(` }`),r.push(` };`),r.push(``),r.push(` // Clear state on clear chat`),r.push(` const handleClearChat = () => {`),r.push(` localStorage.removeItem(STORAGE_KEY);`),r.push(` localStorage.removeItem(PROCESSED_ACTIONS_KEY);`),r.push(` };`),r.push(``),r.push(` window.addEventListener('persona:message', handleMessage);`),r.push(` window.addEventListener('persona:clear-chat', handleClearChat);`),r.push(``),r.push(` // Cleanup on unmount`),r.push(` return () => {`),r.push(` window.removeEventListener('persona:message', handleMessage);`),r.push(` window.removeEventListener('persona:clear-chat', handleClearChat);`),r.push(` if (handle) {`),r.push(` handle.destroy();`),r.push(` }`),r.push(` };`),r.push(` }, []);`),r.push(``),r.push(` return null; // Widget injects itself into the DOM`),r.push(`}`),r.push(``),r.push(`// Usage: Collects DOM context for AI-powered navigation`),r.push(`// Features:`),r.push(`// - Extracts page elements (products, buttons, links)`),r.push(`// - Persists chat history across page loads`),r.push(`// - Handles navigation actions (nav_then_click)`),r.push(`// - Processes structured JSON actions from AI`),r.push(`//`),r.push(`// Example usage in Next.js:`),r.push(`// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';`),r.push(`//`),r.push(`// export default function RootLayout({ children }) {`),r.push(`// return (`),r.push(`// <html lang="en">`),r.push(`// <body>`),r.push(`// {children}`),r.push(`// <ChatWidgetAdvanced />`),r.push(`// </body>`),r.push(`// </html>`),r.push(`// );`),r.push(`// }`),r.join(`
|
|
215
|
+
`)}function Xb(e){let t=Fb(e),n=t!==`plain`,r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.agentId&&(r.agentId=e.agentId),e.target&&(r.target=e.target),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.future?.v5Defaults!==void 0&&(r.future={v5Defaults:e.future.v5Defaults===!0}),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),e.suggestions&&(r.suggestions=e.suggestions),e.suggestionChips?.length>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let t={};Object.entries(e.toolCall).forEach(([e,n])=>{typeof n==`string`&&(t[e]=n)}),Object.keys(t).length>0&&(r.toolCall=t)}if(e.messageActions){let t={};Object.entries(e.messageActions).forEach(([e,n])=>{e!==`onFeedback`&&e!==`onCopy`&&n!==void 0&&(typeof n==`string`||typeof n==`boolean`)&&(t[e]=n)}),Object.keys(t).length>0&&(r.messageActions=t)}if(e.markdown){let t={};e.markdown.options&&(t.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(t.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(t).length>0&&(r.markdown=t)}if(e.layout){let t={};if(e.layout.header){let n={};Object.entries(e.layout.header).forEach(([e,t])=>{e!==`render`&&(typeof t==`string`||typeof t==`boolean`)&&(n[e]=t)}),Object.keys(n).length>0&&(t.header=n)}if(e.layout.messages){let n={};Object.entries(e.layout.messages).forEach(([e,t])=>{if(e!==`renderUserMessage`&&e!==`renderAssistantMessage`){if(e===`avatar`&&typeof t==`object`&&t)n.avatar=t;else if(e===`timestamp`&&typeof t==`object`&&t){let e={};Object.entries(t).forEach(([t,n])=>{t!==`format`&&(typeof n==`string`||typeof n==`boolean`)&&(e[t]=n)}),Object.keys(e).length>0&&(n.timestamp=e)}else(typeof t==`string`||typeof t==`boolean`)&&(n[e]=t)}}),Object.keys(n).length>0&&(t.messages=n)}Object.keys(t).length>0&&(r.layout=t)}return r}function Zb(e,t){let n=Xb(e),r=t?.windowKey||t?.target?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,i=JSON.stringify(r,null,0).replace(/'/g,`'`);return`<script src="${Db(t)}/install.global.js" data-config='${i}'><\/script>`}function Qb(e,t){let n=t?.hooks,r=Fb(e),i=r!==`plain`,a=Db(t),o=[`<!-- Load CSS -->`,`<link rel="stylesheet" href="${a}/widget.css" />`,``,`<!-- Load JavaScript -->`,`<script src="${a}/index.global.js"><\/script>`,``,`<!-- Initialize widget -->`,`<script>`,` var handle = window.AgentWidget.initAgentWidget({`,` target: '${Gb(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[],` config: {`];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),i&&o.push(` parserType: "${r}",`),Wb(o,e,` `),e.theme&&typeof e.theme==`object`&&Object.keys(e.theme).length>0&&Ub(o,`theme`,e.theme,` `),e.launcher&&Ub(o,`launcher`,e.launcher,` `),e.copy&&(o.push(` copy: {`),Object.entries(e.copy).forEach(([e,t])=>{o.push(` ${e}: "${t}",`)}),o.push(` },`)),e.sendButton&&(o.push(` sendButton: {`),Object.entries(e.sendButton).forEach(([e,t])=>{typeof t==`string`?o.push(` ${e}: "${t}",`):typeof t==`boolean`&&o.push(` ${e}: ${t},`)}),o.push(` },`)),e.voiceRecognition&&(o.push(` voiceRecognition: {`),Object.entries(e.voiceRecognition).forEach(([e,t])=>{typeof t==`string`?o.push(` ${e}: "${t}",`):(typeof t==`boolean`||typeof t==`number`)&&o.push(` ${e}: ${t},`)}),o.push(` },`)),e.statusIndicator&&(o.push(` statusIndicator: {`),Object.entries(e.statusIndicator).forEach(([e,t])=>{typeof t==`string`?o.push(` ${e}: "${t}",`):typeof t==`boolean`&&o.push(` ${e}: ${t},`)}),o.push(` },`)),e.features&&(o.push(` features: {`),Object.entries(e.features).forEach(([e,t])=>{o.push(` ${e}: ${t},`)}),o.push(` },`)),o.push(...zb(e,` `)),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(` suggestionChips: [`),e.suggestionChips.forEach(e=>{o.push(` "${e}",`)}),o.push(` ],`)),e.suggestionChipsConfig&&(o.push(` suggestionChipsConfig: {`),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(` },`)),o.push(...Ib(e,` `)),o.push(...Lb(e,` `,n)),o.push(...Rb(e,` `)),o.push(...Bb(e,` `)),o.push(...Vb(n,` `)),e.debug&&o.push(` debug: ${e.debug},`),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(` postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)`),o.push(` }`),o.push(` });`),o.push(`<\/script>`),o.join(`
|
|
216
|
+
`)}function $b(e,t){let n=t?.hooks,r=Xb(e),i=[`<script>`,`(function() {`,` 'use strict';`,``,` // Configuration`,` var CONFIG = ${JSON.stringify(r,null,2).split(`
|
|
217
217
|
`).map((e,t)=>t===0?e:` `+e).join(`
|
|
218
|
-
`)};`,``,` // Constants`,` var CDN_BASE = '${
|
|
218
|
+
`)};`,``,` // Constants`,` var CDN_BASE = '${Db(t)}';`,` var STORAGE_KEY = 'chat-widget-state';`,` var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';`,``,` // DOM context provider - extracts page elements for AI context`,` var domContextProvider = function() {`,` var selectors = {`,` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`,` links: 'a[href]',`,` inputs: 'input, textarea, select'`,` };`,``,` var elements = [];`,` Object.entries(selectors).forEach(function(entry) {`,` var type = entry[0], selector = entry[1];`,` document.querySelectorAll(selector).forEach(function(element) {`,` if (!(element instanceof HTMLElement)) return;`,` var widgetHost = element.closest('.persona-host');`,` if (widgetHost) return;`,` var text = element.innerText ? element.innerText.trim() : '';`,` if (!text) return;`,``,` var selectorString = element.id ? '#' + element.id :`,` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`,` element.tagName.toLowerCase();`,``,` var elementData = {`,` type: type,`,` tagName: element.tagName.toLowerCase(),`,` selector: selectorString,`,` innerText: text.substring(0, 200)`,` };`,``,` if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {`,` elementData.href = element.href;`,` }`,` elements.push(elementData);`,` });`,` });`,``,` var counts = elements.reduce(function(acc, el) {`,` acc[el.type] = (acc[el.type] || 0) + 1;`,` return acc;`,` }, {});`,``,` return {`,` page_elements: elements.slice(0, 50),`,` page_element_count: elements.length,`,` element_types: counts,`,` page_url: window.location.href,`,` page_title: document.title,`,` timestamp: new Date().toISOString()`,` };`,` };`,``,` // Load CSS dynamically`,` var loadCSS = function() {`,` if (document.querySelector('link[data-persona]')) return;`,` var link = document.createElement('link');`,` link.rel = 'stylesheet';`,` link.href = CDN_BASE + '/widget.css';`,` link.setAttribute('data-persona', 'true');`,` document.head.appendChild(link);`,` };`,``,` // Load JS dynamically`,` var loadJS = function(callback) {`,` if (window.AgentWidget) { callback(); return; }`,` var script = document.createElement('script');`,` script.src = CDN_BASE + '/index.global.js';`,` script.onload = callback;`,` script.onerror = function() { console.error('Failed to load AgentWidget'); };`,` document.head.appendChild(script);`,` };`,``,` // Create widget config with advanced features`,` var createWidgetConfig = function(agentWidget) {`,` var widgetConfig = Object.assign({}, CONFIG);`,``];return n?.getHeaders&&(i.push(` widgetConfig.getHeaders = ${n.getHeaders};`),i.push(``)),n?.contextProviders&&(i.push(` widgetConfig.contextProviders = ${n.contextProviders};`),i.push(``)),n?.streamParser?i.push(` widgetConfig.streamParser = ${n.streamParser};`):(i.push(` // Flexible JSON stream parser for handling structured actions`),i.push(` widgetConfig.streamParser = function() {`),i.push(` return agentWidget.createFlexibleJsonStreamParser(function(parsed) {
|
|
219
219
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
220
220
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
221
221
|
if (parsed.action === 'message') return parsed.text || '';
|
|
222
222
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
223
223
|
return parsed.text || null;
|
|
224
|
-
});`),i.push(` };`)),i.push(``),n?.actionParsers?(i.push(` // Action parsers (custom merged with defaults)`),i.push(` var customParsers = ${n.actionParsers};`),i.push(` widgetConfig.actionParsers = customParsers.concat([`),i.push(` agentWidget.defaultJsonActionParser,`),i.push(` ${
|
|
225
|
-
`)}Y(),Yt();const
|
|
224
|
+
});`),i.push(` };`)),i.push(``),n?.actionParsers?(i.push(` // Action parsers (custom merged with defaults)`),i.push(` var customParsers = ${n.actionParsers};`),i.push(` widgetConfig.actionParsers = customParsers.concat([`),i.push(` agentWidget.defaultJsonActionParser,`),i.push(` ${jb}`),i.push(` ]);`)):(i.push(` // Action parsers to detect JSON actions in responses`),i.push(` widgetConfig.actionParsers = [`),i.push(` agentWidget.defaultJsonActionParser,`),i.push(` ${jb}`),i.push(` ];`)),i.push(``),n?.actionHandlers?(i.push(` // Action handlers (custom merged with defaults)`),i.push(` var customHandlers = ${n.actionHandlers};`),i.push(` widgetConfig.actionHandlers = customHandlers.concat([`),i.push(` agentWidget.defaultActionHandlers.message,`),i.push(` agentWidget.defaultActionHandlers.messageAndClick,`),i.push(` ${Nb}`),i.push(` ]);`)):(i.push(` // Action handlers for navigation and other actions`),i.push(` widgetConfig.actionHandlers = [`),i.push(` agentWidget.defaultActionHandlers.message,`),i.push(` agentWidget.defaultActionHandlers.messageAndClick,`),i.push(` ${Nb}`),i.push(` ];`)),i.push(``),n?.requestMiddleware?(i.push(` // Request middleware (custom merged with DOM context)`),i.push(` widgetConfig.requestMiddleware = function(ctx) {`),i.push(` var customResult = (${n.requestMiddleware})(ctx);`),i.push(` var merged = customResult || ctx.payload;`),i.push(` return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });`),i.push(` };`)):(i.push(` // Send DOM context with each request`),i.push(` widgetConfig.requestMiddleware = function(ctx) {`),i.push(` return Object.assign({}, ctx.payload, { metadata: domContextProvider() });`),i.push(` };`)),i.push(``),n?.postprocessMessage?i.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(i.push(` // Markdown postprocessor`),i.push(` widgetConfig.postprocessMessage = function(ctx) {`),i.push(` return agentWidget.markdownPostprocessor(ctx.text);`),i.push(` };`)),i.push(``),(n?.onFeedback||n?.onCopy)&&(i.push(` // Message action callbacks`),i.push(` widgetConfig.messageActions = widgetConfig.messageActions || {};`),n?.onFeedback&&i.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&i.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),i.push(``)),i.push(` return widgetConfig;`,` };`,``,` // Initialize widget`,` var init = function() {`,` var agentWidget = window.AgentWidget;`,` if (!agentWidget) {`,` console.error('AgentWidget not loaded');`,` return;`,` }`,``,` var widgetConfig = createWidgetConfig(agentWidget);`,``,` // Load saved state`,` var savedState = localStorage.getItem(STORAGE_KEY);`,` if (savedState) {`,` try {`,` var parsed = JSON.parse(savedState);`,` widgetConfig.initialMessages = parsed.messages || [];`,` } catch (e) {`,` console.error('Failed to load saved state:', e);`,` }`,` }`,``,` // Initialize widget`,` var handle = agentWidget.initAgentWidget({`,` target: '${Gb(t)}',`,` useShadowDom: false,`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[],` config: widgetConfig`,` });`,``,` // Save state on message events`,` window.addEventListener('persona:message', function() {`,` var session = handle.getSession ? handle.getSession() : null;`,` if (session) {`,` localStorage.setItem(STORAGE_KEY, JSON.stringify({`,` messages: session.messages,`,` timestamp: new Date().toISOString()`,` }));`,` }`,` });`,``,` // Clear state on clear chat`,` window.addEventListener('persona:clear-chat', function() {`,` localStorage.removeItem(STORAGE_KEY);`,` localStorage.removeItem(PROCESSED_ACTIONS_KEY);`,` });`,` };`,``,` // Wait for framework hydration to complete (Next.js, Nuxt, etc.)`,` // This prevents the framework from removing dynamically added CSS during reconciliation`,` var waitForHydration = function(callback) {`,` var executed = false;`,` `,` var execute = function() {`,` if (executed) return;`,` executed = true;`,` callback();`,` };`,``,` var afterDom = function() {`,` // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)`,` if (typeof requestIdleCallback !== 'undefined') {`,` requestIdleCallback(function() {`,` // Double requestAnimationFrame ensures at least one full paint cycle completed`,` requestAnimationFrame(function() {`,` requestAnimationFrame(execute);`,` });`,` }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway`,` } else {`,` // Strategy 2: Fallback for Safari (no requestIdleCallback)`,` // 300ms is typically enough for hydration on most pages`,` setTimeout(execute, 300);`,` }`,` };`,``,` if (document.readyState === 'loading') {`,` document.addEventListener('DOMContentLoaded', afterDom);`,` } else {`,` // DOM already ready, but still wait for potential hydration`,` afterDom();`,` }`,` };`,``,` // Boot sequence: wait for hydration, then load CSS and JS, then initialize`,` // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation`,` waitForHydration(function() {`,` loadCSS();`,` loadJS(function() {`,` init();`,` });`,` });`,`})();`,`<\/script>`),i.join(`
|
|
225
|
+
`)}Y(),Yt();const ex={desktop:{w:1280,h:800},mobile:{w:390,h:844}},tx=.1,nx=.15,rx=1.5;function ix(){if(document.querySelector(`style[data-persona-dc-styles]`))return;let e=document.createElement(`style`);e.setAttribute(`data-persona-dc-styles`,``),e.textContent=`
|
|
226
226
|
/* ── Root ── */
|
|
227
227
|
.persona-dc-root {
|
|
228
228
|
display: flex;
|
|
@@ -463,9 +463,9 @@ import{Marked as e,Marked as t}from"marked";import n,{default as r}from"dompurif
|
|
|
463
463
|
min-height: 300px;
|
|
464
464
|
}
|
|
465
465
|
}
|
|
466
|
-
`,document.head.appendChild(e)}function
|
|
466
|
+
`,document.head.appendChild(e)}function ax(e,t){let n=e.clientWidth-48-40,r=e.clientHeight-48-40;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function ox(e,t,n,r,i){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=i===`mobile`?`${32*r}px`:`10px`,t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin=`top left`,t.style.transform=`scale(${r})`}function sx(e,t){let{items:n,initialIndex:r=0,initialDevice:i=`desktop`,initialColorScheme:a=`light`,showZoomControls:o=!0,showDeviceToggle:s=!0,showColorSchemeToggle:c=!0,onChange:l}=t;if(n.length===0)throw Error(`createDemoCarousel: items array must not be empty`);ix();let u=Math.max(0,Math.min(r,n.length-1)),d=i,f=a,p=null,m=1,h=!1,g=q(`div`,`persona-dc-root`),_=q(`div`,`persona-dc-toolbar`),v=q(`div`,`persona-dc-toolbar-lead`),y=q(`div`,`persona-dc-toolbar-trail`),b=lh({icon:`chevron-left`,label:`Previous demo`,size:14,onClick:()=>fe(-1)}),S=q(`div`);S.style.position=`relative`;let C=q(`button`,`persona-dc-title-btn`);C.type=`button`,C.setAttribute(`aria-expanded`,`false`),C.setAttribute(`aria-haspopup`,`listbox`);let w=q(`span`,`persona-dc-title-text`),T=q(`span`,`persona-dc-title-chevron`),E=Jt(x,12,`currentColor`,2);E&&T.appendChild(E),C.append(w,T);let D=q(`div`,`persona-dc-dropdown`);D.setAttribute(`role`,`listbox`),D.style.display=`none`;let O=!1;function k(){D.innerHTML=``;for(let e=0;e<n.length;e++){let t=n[e],r=q(`button`,`persona-dc-dropdown-item`);r.type=`button`,r.setAttribute(`role`,`option`),r.setAttribute(`aria-current`,e===u?`true`:`false`);let i=q(`span`);if(i.textContent=t.title,r.appendChild(i),t.description){let e=q(`span`,`persona-dc-dropdown-desc`);e.textContent=t.description,r.appendChild(e)}r.addEventListener(`click`,()=>{te(),pe(e)}),D.appendChild(r)}}function ee(){O=!O,D.style.display=O?``:`none`,C.setAttribute(`aria-expanded`,O?`true`:`false`),O&&k()}function te(){O&&(O=!1,D.style.display=`none`,C.setAttribute(`aria-expanded`,`false`))}C.addEventListener(`click`,e=>{e.stopPropagation(),ee()});let ne=()=>te();document.addEventListener(`click`,ne),S.append(C,D);let re=lh({icon:`chevron-right`,label:`Next demo`,size:14,onClick:()=>fe(1)}),ie=q(`span`,`persona-dc-counter`);v.append(b,S,re,ie);let ae=null;s&&(ae=dh({items:[{id:`desktop`,icon:`monitor`,label:`Desktop`},{id:`mobile`,icon:`smartphone`,label:`Mobile`}],selectedId:d,onSelect:e=>{d=e,ce.dataset.device=d,p=null,M()}}),y.appendChild(ae.element));let oe=null;if(o){let e=q(`div`,`persona-dc-zoom-controls`),t=lh({icon:`minus`,label:`Zoom out`,size:14,onClick:()=>{p=Math.max(nx,(p??m)-tx),M()}});oe=q(`span`,`persona-dc-zoom-level`),oe.title=`Reset to 100%`,oe.style.cursor=`pointer`,oe.addEventListener(`click`,()=>{p=1,M()});let n=lh({icon:`plus`,label:`Zoom in`,size:14,onClick:()=>{p=Math.min(rx,(p??m)+tx),M()}}),r=lh({icon:`maximize`,label:`Fit to view`,size:14,onClick:()=>{p=null,M()}});e.append(t,oe,n,r),y.appendChild(e)}if(c){let e=q(`div`,`persona-dc-separator`);y.appendChild(e);let t=dh({items:[{id:`light`,icon:`sun`,label:`Light`},{id:`dark`,icon:`moon`,label:`Dark`}],selectedId:f,onSelect:e=>{f=e,ce.dataset.colorScheme=f,ue()}});y.appendChild(t.element)}let A=q(`div`,`persona-dc-separator`);y.appendChild(A);let j=lh({icon:`external-link`,label:`Open in new tab`,size:14,onClick:()=>{window.open(n[u].url,`_blank`)}});y.appendChild(j),_.append(v,y);let se=q(`div`,`persona-dc-stage`),ce=q(`div`,`persona-dc-iframe-wrapper`);ce.dataset.device=d,ce.dataset.colorScheme=f;let le=q(`iframe`,`persona-dc-iframe`);le.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-forms`),le.setAttribute(`loading`,`lazy`),le.title=n[u].title,ce.appendChild(le),se.appendChild(ce),g.append(_,se),e.appendChild(g);function ue(){try{let e=le.contentDocument?.body;if(!e)return;f===`dark`?e.classList.add(`theme-dark`):e.classList.remove(`theme-dark`)}catch{}}le.addEventListener(`load`,()=>ue());function de(){let e=n[u];w.textContent=e.title,ie.textContent=`${u+1} / ${n.length}`,le.title=e.title}function fe(e){pe(((u+e)%n.length+n.length)%n.length)}function pe(e){e<0||e>=n.length||(u=e,le.src=n[u].url,de(),l?.(u,n[u]))}function M(){if(h)return;let e=ex[d]??ex.desktop;m=ax(se,e);let t=Math.max(nx,Math.min(rx,p??m));ox(ce,le,e,t,d),oe&&(oe.textContent=`${Math.round(t*100)}%`)}let me=new ResizeObserver(()=>M());me.observe(se),de(),le.src=n[u].url,requestAnimationFrame(()=>M());function he(){h||(h=!0,me.disconnect(),document.removeEventListener(`click`,ne),g.remove())}return{element:g,goTo:pe,next:()=>fe(1),prev:()=>fe(-1),getIndex:()=>u,setDevice(e){d=e,ce.dataset.device=e,ae?.setSelected(e),p=null,M()},setColorScheme(e){f=e,ce.dataset.colorScheme=e},setZoom(e){p=e,M()},destroy:he}}ed(),Ri();const cx=16e3,lx=/* @__PURE__ */ new Map([[`idle_timeout`,`Voice call ended after a quiet period.`],[`max_duration`,`This voice call reached its time limit.`],[`provider_ended`,`The voice session ended.`],[`quota`,`Voice is unavailable right now.`],[`auth_expired`,`Voice session expired. Tap the mic to reconnect.`]]),ux=[`provider_error`,`server_restart`],dx=`Voice connection lost.`;function fx(e,t){let n=t.slice(0,4e3).trim(),r=8e3-(n?n.length+2:0)-20,i=[];for(let t of e.slice(-12).reverse()){let e=t.content.replace(/\s+/g,` `).trim();if(!e)continue;e.length>2e3&&(e=`${e.slice(0,1999)}…`);let n=`${t.role===`user`?`User`:`Assistant`}: ${e}`;if(n.length+1>r)break;r-=n.length+1,i.unshift(n)}let a=i.length>0?[`Conversation so far:\n${i.join(`
|
|
467
467
|
`)}`]:[];return n&&a.push(n),a.join(`
|
|
468
468
|
|
|
469
|
-
`)}function ix(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===1380533830?new Uint8Array(e,44):new Uint8Array(e)}function ax(e){let t=e.replace(/\/+$/,``);return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,`ws`):`${typeof window<`u`&&window.location?.protocol===`https:`?`wss:`:`ws:`}//${t}`}function ox(e){return ax(e).replace(/^ws/i,`http`)}function sx(e){return typeof e!=`number`||!Number.isFinite(e)?3e4:Math.min(6e5,Math.max(3e4,Math.round(e)))}var cx=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e){this.config=e,this.type=`runtype`,this.#e=null,this.#t=null,this.#n=[],this.#r=null,this.#i=null,this.#a=null,this.#o=[],this.#s=0,this.#c=null,this.#l=!1,this.#u=!1,this.#d=0,this.#f=!1,this.#p=-1/0,this.#m=null,this.#h=!1,this.#g=!1,this.#_=0,this.#v=0,this.#b=!1,this.bridge=null,this.#x=!1,this.#S=/* @__PURE__ */ new Set,this.#C=/* @__PURE__ */ new Map,this.#w=/* @__PURE__ */ new Set,this.#E=null,this.#D=null,this.#k=!1,this.#A=!1,this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F=/* @__PURE__ */ new Set,this.#I=/* @__PURE__ */ new Set,this.#L=null,this.#R=!1,this.#z=/* @__PURE__ */ new Set,this.#B=/* @__PURE__ */ new Set,this.#V=null,this.#H=/* @__PURE__ */ new Set,this.#U=null,this.#W=/* @__PURE__ */ new Map,this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}async connect(){}setSessionBridge(e){this.bridge=e}prewarm(){if(this.#l||this.#m)return;let e=this.config?.agentId,t=this.config?.clientToken,n=this.config?.host;if(!e||!t||!n)return;let r=Date.now();if(!(r-this.#p<3e4)){this.#p=r;try{this.config?.prewarmMode===`attach`?this.#Z(n,e,t):this.#X(n,e,t)}catch{}}}#X(e,t,n){if(typeof fetch!=`function`)return;let r=`${ox(e)}/v1/client/agents/${encodeURIComponent(t)}/voice/prewarm`;fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${n}`},keepalive:!0}).catch(()=>{})}#Z(e,t,n){let r=new URLSearchParams,i=this.config?.attachIdleMs,a=sx(i);i!==void 0&&r.set(`attachIdleMs`,String(a));let o=new WebSocket(this.#te(e,t,r),[`runtype.bearer`,`runtype.attach`,n]);o.binaryType=`arraybuffer`;let s=()=>{},c={ws:o,state:`connecting`,ready:new Promise(e=>{s=e}),settle:s,openedAt:0,idleTimer:void 0};this.#m=c,o.onopen=()=>{this.#m===c&&(c.state=o.protocol===`runtype.attach`?`attached`:`live`,c.openedAt=Date.now(),this.#Q(c,a),c.state===`attached`&&o.send(`{"type":"ping"}`),c.settle())},o.onmessage=e=>{if(this.#m!==c||typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}t.type===`attached`&&typeof t.idleMs==`number`&&this.#Q(c,t.idleMs-(Date.now()-c.openedAt))},o.onerror=()=>{},o.onclose=()=>{this.#m===c&&this.#$()}}#Q(e,t){clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{this.#m===e&&this.#$()},Math.max(0,t))}#$(){let e=this.#m;if(!e)return;this.#m=null,clearTimeout(e.idleTimer);let{ws:t}=e;if(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,e.settle(),t.readyState===WebSocket.CONNECTING||t.readyState===WebSocket.OPEN)try{t.close(1e3,`prewarm released`)}catch{}}async#ee(){let e=this.#m;if(!e)return null;if(e.state===`connecting`){let t;await Promise.race([e.ready,new Promise(e=>{t=setTimeout(e,5e3)})]),clearTimeout(t)}return this.#m===e?e.state===`connecting`||e.ws.readyState!==WebSocket.OPEN?(this.#$(),null):(this.#m=null,clearTimeout(e.idleTimer),{ws:e.ws,live:e.state===`live`}):null}#te(e,t,n){let r=[`partial_transcript`,`context`];this.bridge&&this.config?.clientDelegation!==!1&&(r.push(`client_delegation`,`delegation_update`,`delegation_read_back`,`delegation_stream`),this.bridge.clientTools?.()&&r.push(`client_tools`)),n&&r.unshift(`attach`);let i=new URLSearchParams({voiceProtocol:`runtype-browser-v1`,clientVersion:`persona/${Li}`,voiceCapabilities:`full-duplex-v1`,clientCapabilities:r.join(`,`)});return n?.forEach((e,t)=>i.set(t,e)),`${ax(e)}/ws/agents/${encodeURIComponent(t)}/voice?${i}`}async startListening(){if(this.#l)return;let e=this.#A;e||(this.#k=!1,this.#D=null),this.#A=!1;let t=this.config?.agentId,n=this.config?.clientToken,r=this.config?.host;if(!t)throw Error(`Runtype voice requires an agentId`);if(!n)throw Error(`Runtype voice requires a clientToken`);if(!r)throw Error(`Runtype voice requires a host (or widget apiUrl)`);let i=++this.#d;this.#f=!1,this.#l=!0;try{let a=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:$b,channelCount:1,echoCancellation:!0}});if(i!==this.#d){a.getTracks().forEach(e=>e.stop());return}this.#r=a;let o=new(window.AudioContext||window.webkitAudioContext)({sampleRate:$b});if(this.#t=o,o.state===`suspended`){if(await Promise.race([o.resume().catch(()=>{}),new Promise(t=>setTimeout(t,e?500:1e3))]),i!==this.#d)return;if(o.state!==`running`)throw Error(e?this.#D=`${nx} Tap the mic to reconnect.`:`Audio blocked until a tap`)}let s=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new qu(24e3);if(i!==this.#d){s.destroy(),a.getTracks().forEach(e=>e.stop()),o.close().catch(()=>{});return}this.#c=s,this.#he(),this.#ie(o,a,i);let c=await this.#ee();if(i!==this.#d){c?.ws.close(1e3,`client ended call`);return}if(c){let{ws:e}=c;this.#e=e,this.#ne(e,i),c.live||e.send(`{"type":"start"}`),this.#ae(e),this.#be(`listening`);return}let l=new WebSocket(this.#te(r,t),[`runtype.bearer`,n]);l.binaryType=`arraybuffer`,this.#e=l,l.onopen=()=>{i===this.#d&&(this.#ae(l),this.#be(`listening`))},this.#ne(l,i)}catch(e){throw this.#ye(),this.#xe(e),this.#be(`error`),e}}#ne(e,t){e.onmessage=e=>this.#oe(e,t),e.onerror=()=>{t!==this.#d||this.#E||(this.#xe(/* @__PURE__ */ Error(`Voice connection failed`)),this.#be(`error`),this.#ye())},e.onclose=e=>{if(this.#f){this.#f=!1;return}if(t!==this.#d)return;let n=this.#E??(e.code===4408?{reason:`idle_timeout`}:null);if(n)this.#re(n.reason,n.message);else{if(e.code!==1e3){let t=e.code?` (code ${e.code})`:``;this.#xe(/* @__PURE__ */ Error(`Voice connection closed${t}`)),this.#be(`error`)}else this.#be(`idle`);this.#ye()}}}#re(e,t){let n=tx.includes(e)&&!this.#k;if(this.#ye(),n)this.#k=!0,this.#l=!0,this.#D=e===`provider_error`?`${nx} Reconnecting…`:`Reconnecting…`,this.#O=setTimeout(()=>{this.#l=!1,this.#A=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#be(`idle`);else{if(tx.includes(e))return this.#D=nx,this.#xe(/* @__PURE__ */ Error(nx)),this.#be(`error`);if(e===`error`)return this.#be(`error`);this.#D=e===`quota`&&t||ex.get(e)||null,this.#be(`idle`)}}takeNotice(){let e=this.#D;return this.#D=null,e}getDisclosure(){let e=this.config?.disclosureText;return this.#l&&this.#h&&e!==!1?e||`You're talking to an AI assistant. Voice is processed by OpenAI.`:null}async stopListening(){this.#ye(),this.#be(`idle`)}async disconnect(){this.#ye(),this.#be(`disconnected`),this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}stopPlayback(){this.#ve();let e=this.#e;e&&e.readyState===WebSocket.OPEN&&(this.#h&&(this.#_=Date.now()+2e3,e.send(`{"type":"cancel"}`)),this.#be(`listening`))}getInterruptionMode(){return`barge-in`}isBargeInActive(){return this.#l}onLevel(e){this.#n.push(e)}async deactivateBargeIn(){this.#ye(),this.#be(`idle`)}#ie(e,t,n){let r=e.createMediaStreamSource(t);this.#i=r;let i=e.createScriptProcessor(4096,1,1);this.#a=i,i.onaudioprocess=e=>{if(n!==this.#d)return;let t=this.#e,r=t?.readyState===WebSocket.OPEN;if(t&&!r&&t.readyState!==WebSocket.CONNECTING)return;let i=e.inputBuffer.getChannelData(0),a=new Int16Array(i.length),o=0;for(let e=0;e<i.length;e++){let t=Math.max(-1,Math.min(1,i[e]));o+=t*t,a[e]=t<0?t*32768:t*32767}if(t&&r)this.#ae(t),t.send(a.buffer);else for(this.#o.push(a.buffer),this.#s+=a.byteLength;this.#s>256e3;)this.#s-=this.#o.shift().byteLength;if(this.#n.length>0){let e=Math.sqrt(o/i.length),t=Math.max(0,Math.min(1,e*4));for(let e of this.#n)e(t)}},r.connect(i),i.connect(e.destination)}#ae(e){for(let t of this.#o)e.send(t);this.#o=[],this.#s=0}#oe(e,t){if(t!==this.#d)return;if(e.data instanceof ArrayBuffer){this.#pe(e.data,t);return}let n;try{n=JSON.parse(e.data)}catch{return}switch(n.type){case`session_config`:n.speechMode&&(this.#h=n.speechMode===`speech_to_speech`,this.#c?.setContinuousMode?.(this.#h)),Array.isArray(n.capabilities)&&(this.#S=new Set(n.capabilities)),typeof n.callId==`string`&&(this.#T=n.callId),this.#x=this.#h&&this.#S.has(`client_delegation`)&&!!this.bridge,this.#h&&!this.#u&&this.#be(`listening`),this.#S.has(`context`)&&!this.#j&&(this.#j=!0,this.#M=this.#se()),this.#x&&this.#S.has(`client_tools`)&&!this.#V&&(this.#V=this.bridge?.clientTools?.()?.open({send:e=>{let n=this.#e;return t!==this.#d||n?.readyState!==WebSocket.OPEN?!1:(n.send(JSON.stringify(e)),!0)},cancelled:e=>this.#w.has(e)}).catch(()=>null)??null);break;case`client_tool_call`:{let e=String(n.delegationId);this.#V&&!this.#W.has(e)&&(this.#W.set(e,this.#U),this.#F.add(e)),this.#V?.then(e=>e?.call(n));break}case`transcript_update`:{let e=n.role===`assistant`?`assistant`:`user`,r=n.utteranceId??n.turnId;if(!r||e===`assistant`&&this.#me())break;let i=String(r);if(e===`user`)n.final===!0&&(this.#ce(t),this.#U={id:i,text:String(n.text??``)}),this.#R=!1;else{if(this.#S.has(`delegation_read_back`)){let e=n.delegationId;(typeof e==`string`&&this.#F.has(e)&&!this.#z.has(i)||this.#R&&!this.#z.has(i))&&(this.#B.add(i),this.#R=!1)}else this.#R&&!this.#z.has(i)&&(this.#B.add(i),this.#R=!1);if(this.#z.add(i),this.#B.has(i))break}this.#Se(e,n.text??``,n.final===!0,{turnId:i,...typeof n.startMs==`number`&&{startMs:n.startMs},...typeof n.endMs==`number`&&{endMs:n.endMs},...this.#x&&{caption:!0}});break}case`delegation_started`:case`delegation_completed`:{let e=String(n.delegationId??n.turnId);if(n.type===`delegation_started`){this.#ce(t),this.#H.add(e),this.#F.delete(e),this.#W.delete(e)&&this.#V?.then(t=>t?.abort(e));let r=n.input;this.#x&&r&&this.#fe(e,{delegationId:e,userText:String(r.text??``),userUtteranceIds:Array.isArray(r.userUtteranceIds)?r.userUtteranceIds.filter(e=>typeof e==`string`):[],messages:Array.isArray(r.messages)?r.messages:[]},t)}else if(n.route===`direct`&&this.#V&&!this.#H.has(e)){let t=this.#W.get(e)??this.#U;this.#W.delete(e),this.#H.add(e),this.#F.add(e),this.bridge?.recordDirectTurn?.({delegationId:e,userText:t?.text??``,userUtteranceIds:t?[t.id]:[],assistantText:typeof n.text==`string`?n.text:``})}n.type===`delegation_completed`&&n.speak!==!1&&this.#F.has(e)&&!this.#I.delete(e)&&!this.#S.has(`delegation_read_back`)&&this.#ue(e),this.#g=n.type===`delegation_started`,!this.#u&&!this.#me()&&this.#be(this.#g?`processing`:`listening`);break}case`delegation_progress`:{let e=String(n.delegationId);this.#F.has(e)&&!this.#I.has(e)&&!this.#w.has(e)&&(this.#I.add(e),this.#ue(e));break}case`delegation_cancelled`:this.#de(String(n.delegationId),n.reason!==`session_ending`&&n.reason!==`provider_cancelled`);break;case`warning`:console.warn(`[Persona voice] ${n.code}: ${n.message??``}`,this.#T??``),n.delegationId&&(n.code===`UNKNOWN_DELEGATION`||n.code===`LATE_RESULT_LIMIT`)&&this.#de(String(n.delegationId));break;case`audio_clear`:this.#ve(),this.#_=0,this.#be(`listening`);break;case`transcript_interim`:this.#be(`listening`),this.#Se(`user`,n.text??``,!1);break;case`transcript_final`:{let e=n.role===`assistant`?`assistant`:`user`;this.#be(e===`user`?`processing`:`speaking`),this.#Se(e,n.text??``,!0);break}case`audio_end`:this.#c?this.#c.markStreamEnd():(this.#u=!1,this.#be(`listening`));break;case`metrics`:this.#Ce({llmMs:n.llm_ms,ttsMs:n.tts_ms,firstAudioMs:n.first_audio_ms,totalMs:n.total_ms});break;case`error`:this.#xe(Error(n.error||`Voice error`)),this.#be(`error`);break;case`session_end`:this.#E={reason:String(n.reason),...typeof n.message==`string`&&{message:n.message}}}}async#se(){let e=this.bridge?.getHistory()??[],t=``;try{let e=this.config?.callContext;t=String((typeof e==`function`?await e():e)??``)}catch{}return rx(e,t)}#ce(e){let t=this.#M;if(!t)return;this.#M=null;let n=!1,r=t.then(t=>{let r=this.#e;!n&&t&&e===this.#d&&r?.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:`context`,text:t}))});this.#N={done:r,drop:()=>n=!0}}async#le(){let e=this.#N;if(!e)return;let t,n=await Promise.race([e.done.then(()=>!1),new Promise(e=>{t=setTimeout(()=>e(!0),2e3)})]);clearTimeout(t),n&&e.drop()}#ue(e){this.#R=!0,this.#L=e}#de(e,t=!1){this.#w.add(e),this.#L===e&&(this.#R=!1),this.#I.delete(e),this.#H.has(e)||this.#F.delete(e),this.#V?.then(t=>t?.abort(e)),this.bridge?.dropDelegation?.(e,t),this.#C.get(e)?.abort()}#fe(e,t,n){let r=this.bridge,i=({type:t,...r})=>{let i=this.#e;return n!==this.#d||i?.readyState!==WebSocket.OPEN||this.#w.has(e)?!1:(i.send(JSON.stringify({type:t,delegationId:e,...r})),!0)},a=(e,t,n,r=0)=>i({type:e,status:t,text:n,...r>0&&{streamedChars:r}});this.#P=this.#P.then(async()=>{if(n!==this.#d||this.#w.has(e))return;let o=null,s=this.#S.has(`delegation_stream`)&&this.#S.has(`delegation_read_back`),c=t=>{o=(o??this.#le()).then(()=>{i({type:`delegation_delta`,text:t})&&this.#F.add(e)})},l=await r.runDelegatedTurn(s?{...t,stream:c}:t).catch(()=>({status:`failed`,text:``}));await this.#le(),await o;let u=s?l.streamedChars??0:0,d=!!l.followUp,f=d&&this.#S.has(`delegation_update`);if(!a(f?`delegation_update`:`delegation_result`,d&&!f?`completed`:l.status,l.text,u)||(l.status!==`failed`&&l.inChat!==!1&&this.#F.add(e),!l.followUp))return;let p=new AbortController;this.#C.set(e,p),l.followUp({signal:p.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,54e4),readBack:f,onUpdate:e=>a(`delegation_update`,`pending_approval`,e)}).then(t=>{this.#C.delete(e),f&&t&&!p.signal.aborted&&a(`delegation_result`,t.status,t.text)})})}#pe(e,t){if(t!==this.#d||!this.#c||this.#me())return;let n=ix(e);n.length!==0&&(this.#u||(this.#u=!0,this.#be(`speaking`)),this.#he(),this.#c.enqueue(n),this.#h&&this.#ge(n.length))}#me(){return Date.now()<this.#_}#he(){if(this.#b||!this.#c)return;this.#b=!0;let e=this.#d;this.#c.onFinished(()=>{e===this.#d&&(this.#b=!1,this.#_e())})}#ge(e){let t=Date.now();this.#v=Math.max(t,this.#v)+e/48,clearTimeout(this.#y),this.#y=setTimeout(()=>this.#_e(),this.#v-t+300)}#_e(){this.#u=!1,this.#v=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#be(this.#g?`processing`:`listening`)}#ve(){this.#c?.flush(),this.#b=!1,this.#he(),this.#u=!1,this.#v=0,clearTimeout(this.#y)}#ye(){this.#d+=1,this.#l=!1,this.#u=!1,this.#$(),this.#h=!1,this.#g=!1,this.#x=!1,this.#S=/* @__PURE__ */ new Set;for(let e of this.#C.values())e.abort();if(this.#C.clear(),this.#w.clear(),this.#T=void 0,this.#E=null,clearTimeout(this.#O),this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F.clear(),this.#I.clear(),this.#L=null,this.#R=!1,this.#z.clear(),this.#B.clear(),this.#V?.then(e=>e?.close()),this.#V=null,this.#H.clear(),this.#W.clear(),this.#U=null,this.#b=!1,this.#_=0,this.#v=0,clearTimeout(this.#y),this.#o=[],this.#s=0,this.#a&&=(this.#a.onaudioprocess=null,this.#a.disconnect(),null),this.#i&&=(this.#i.disconnect(),null),this.#r&&=(this.#r.getTracks().forEach(e=>e.stop()),null),this.#t&&=(this.#t.close().catch(()=>{}),null),this.#c&&=(this.#c.destroy(),null),this.#e){this.#f=!0;try{this.#e.close(1e3,`client ended call`)}catch{}this.#e=null}}onResult(e){this.#G.push(e)}onError(e){this.#K.push(e)}onStatusChange(e){this.#q.push(e)}onTranscript(e){this.#J.push(e)}onMetrics(e){this.#Y.push(e)}#be(e){this.#q.forEach(t=>t(e))}#xe(e){this.#K.forEach(t=>t(e))}#Se(e,t,n,r){this.#J.forEach(i=>i(e,t,n,r))}#Ce(e){this.#Y.forEach(t=>t(e))}},lx=class{#e;#t;#n;#r;#i;#a;constructor(e={}){this.config=e,this.type=`browser`,this.#e=null,this.#t=[],this.#n=[],this.#r=[],this.#i=!1,this.#a=typeof window<`u`?window:void 0}async connect(){this.#r.forEach(e=>e(`connected`))}async startListening(){try{if(this.#i)throw Error(`Already listening`);if(!this.#a)throw Error(`Window object not available`);let e=this.#a.SpeechRecognition||this.#a.webkitSpeechRecognition;if(!e)throw Error(`Browser speech recognition not supported`);this.#e=new e,this.#e.lang=this.config?.language||`en-US`,this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.onresult=e=>{let t=Array.from(e.results).map(e=>e[0]).map(e=>e.transcript).join(``),n=e.results[e.results.length-1].isFinal;this.#t.forEach(e=>e({text:t,confidence:n?.8:.5,provider:`browser`})),n&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=e=>{this.#n.forEach(t=>t(Error(e.error))),this.#r.forEach(e=>e(`error`))},this.#e.onstart=()=>{this.#i=!0,this.#r.forEach(e=>e(`listening`))},this.#e.onend=()=>{this.#i=!1,this.#r.forEach(e=>e(`idle`))},this.#e.start()}catch(e){throw this.#n.forEach(t=>t(e)),this.#r.forEach(e=>e(`error`)),e}}async stopListening(){this.#e&&=(this.#e.stop(),null),this.#i=!1,this.#r.forEach(e=>e(`idle`))}onResult(e){this.#t.push(e)}onError(e){this.#n.push(e)}onStatusChange(e){this.#r.push(e)}async disconnect(){await this.stopListening(),this.#r.forEach(e=>e(`disconnected`))}static isSupported(){return`SpeechRecognition`in window||`webkitSpeechRecognition`in window}};function ux(e){switch(e.type){case`runtype`:if(!e.runtype)throw Error(`Runtype voice provider requires configuration`);return new cx(e.runtype);case`browser`:if(!lx.isSupported())throw Error(`Browser speech recognition not supported`);return new lx(e.browser||{});case`custom`:{let t=e.custom;if(!t)throw Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t==`function`?t():t;if(!n||typeof n.startListening!=`function`)throw Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw Error(`Unknown voice provider type: ${e.type}`)}}function dx(e){if(e?.type===`custom`&&e.custom)return ux({type:`custom`,custom:e.custom});if(e?.type===`runtype`&&e.runtype)return ux({type:`runtype`,runtype:e.runtype});if(lx.isSupported())return ux({type:`browser`,browser:e?.browser||{language:`en-US`}});throw Error(`No supported voice providers available`)}function fx(e){try{return dx(e),!0}catch{return!1}}const px=(e,t)=>({ok:!1,reason:e,message:t}),mx=e=>e.startsWith(`webmcp:`)?e.slice(7):e,hx={warn(e,...t){typeof console<`u`&&typeof console.warn==`function`&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};var gx=class{#e;#t;#n=!1;#r=null;#i=!1;#a;constructor(e,t){this.config=e,this.#a=t,this.#e=e.onConfirm??null,this.#t=3e4}setConfirmHandler(e){this.#e=e}isOperational(){return this.config.enabled!==!0||!this.#n?!1:this.#l()!==null}async snapshotForDispatch(){if(await this.#s(),this.config.enabled!==!0)return[];let e=this.#l();if(!e)return[];let t;try{t=(await e.getTools()).filter(Ox)}catch(e){return hx.warn(`getTools() threw: shipping an empty WebMCP snapshot.`,e),[]}this.#a.recordToolDisplayTitles(t);let n=typeof location<`u`?location.origin:``;return t.filter(e=>this.#d(e.name)).map(e=>{let t=yx(e.annotations);return{name:e.name,description:e.description,parametersSchema:bx(e.inputSchema),origin:`webmcp`,...n?{pageOrigin:n}:{},...t?{annotations:t}:{},...t?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(e,t,n){let r=await this.#o(e,t,n,!1);return r.ok?xx(r.raw):Cx(r.message)}async executeVoiceToolCall(e,t,n={}){let r=await this.#o(e,t,n.signal,n.autoConfirmReadOnly===!0);return r.ok?Tx(r.raw):{status:r.reason===`aborted`?`failed`:r.reason,error:{message:r.message}}}watchToolChanges(e){let t=!1,n=null;return this.#s().then(()=>{if(t||this.config.enabled!==!0)return;let r=this.#l();r&&typeof r.addEventListener==`function`&&(n=r,n.addEventListener(`toolchange`,e))}),()=>{t=!0,n?.removeEventListener(`toolchange`,e),n=null}}async#o(e,t,n,r){if(await this.#s(),this.config.enabled!==!0)return px(`failed`,`WebMCP is not enabled on this widget.`);let i=this.#l();if(!i){let e=typeof document<`u`&&!!document.modelContext;return px(`failed`,e?`WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).`:`WebMCP bridge is not operational on this page (document.modelContext not available).`)}let a=mx(e),o;try{o=(await i.getTools()).filter(Ox)}catch(e){let t=e instanceof Error?e.message:String(e);return px(`failed`,`Failed to read WebMCP registry: ${t}`)}this.#a.recordToolDisplayTitles(o);let s=o.find(e=>e.name===a);if(!s)return px(`stale`,`WebMCP tool not registered on this page: ${a}`);if(!this.#d(a))return px(`stale`,`WebMCP tool not allowed by client allowlist: ${a}`);if(n?.aborted)return px(`aborted`,`Aborted by cancel()`);let c=this.#a.getToolDisplayTitle(a),l=yx(s.annotations),u={toolName:a,args:t,description:s.description,...l?{annotations:l}:{},...c?{title:c}:{},...n?{signal:n}:{},reason:`gate`};if(!(r&&l?.readOnlyHint===!0)&&!await this.#u(u))return px(`denied`,`User declined the tool call.`);if(n?.aborted)return px(`aborted`,`Aborted by cancel()`);let d=new AbortController,f=!1,p=setTimeout(()=>{f=!0,d.abort()},this.#t),m=()=>d.abort();n&&(n.aborted?d.abort():n.addEventListener(`abort`,m,{once:!0}));try{return{ok:!0,raw:await i.executeTool(s,Sx(t),{signal:d.signal})}}catch(e){if(f)return px(`timeout`,`WebMCP tool '${a}' timed out after ${this.#t}ms`);if(n?.aborted)return px(`aborted`,`Aborted by cancel()`);let t=e instanceof Error?e.message:String(e);return px(`failed`,t)}finally{clearTimeout(p),n&&n.removeEventListener(`abort`,m)}}#s(){return this.config.enabled===!0?(this.#r||=this.#c(),this.#r):Promise.resolve()}async#c(){try{if(this.#l()){this.#n=!0;return}let e=await this.#a.loadPolyfill();`initializeWebMCPPolyfill`in e?e.initializeWebMCPPolyfill():e.installWebMCP(),this.#n=!0}catch(e){hx.warn(`Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.`,e),this.#n=!1}}#l(){if(typeof document>`u`)return null;let e=document.modelContext;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.getTools!=`function`||typeof t.executeTool!=`function`?(this.#i||(this.#i=!0,hx.warn(`document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).`)),null):e}async#u(e){let t=this.#e??Ex;try{return await t(e)}catch(t){return hx.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,t),!1}}#d(e){let t=this.config.allowlist;return!t||t.length===0||t.some(t=>_x(e,t))}};const _x=(e,t)=>{if(t===`*`)return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`^`+n.replace(/\*/g,`.*`)+`$`).test(e)},vx={type:`object`,properties:{}},yx=e=>{if(!e||typeof e!=`object`)return;let t={};for(let n of[`readOnlyHint`,`destructiveHint`,`consequentialHint`,`untrustedContentHint`,`idempotentHint`,`openWorldHint`,`debugging`]){let r=e[n];typeof r==`boolean`&&(t[n]=r)}return Object.keys(t).length>0?t:void 0},bx=e=>{if(e===void 0||e===``)return{...vx};if(typeof e==`object`)return e!==null&&!Array.isArray(e)?e:{...vx};try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{...vx}}catch{return{...vx}}},xx=e=>{if(e==null)return{content:[{type:`text`,text:``}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:`text`,text:e}]}}return typeof t==`object`&&t&&Array.isArray(t.content)?t:{content:[{type:`text`,text:typeof t==`string`?t:kx(t)}]}},Sx=e=>{let t;try{t=JSON.stringify(e)??`{}`}catch{t=`{}`}let n=JSON.parse(t);if(typeof n!=`object`||!n)throw TypeError(`WebMCP tool arguments must be an object or array.`);return Object.defineProperty(n,Symbol.toPrimitive,{value:()=>t}),n},Cx=e=>({isError:!0,content:[{type:`text`,text:e}]}),wx=e=>Array.isArray(e)?e.map(e=>e&&typeof e==`object`&&typeof e.text==`string`?e.text:``).filter(Boolean).join(`
|
|
470
|
-
`):``,
|
|
469
|
+
`)}function px(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===1380533830?new Uint8Array(e,44):new Uint8Array(e)}function mx(e){let t=e.replace(/\/+$/,``);return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,`ws`):`${typeof window<`u`&&window.location?.protocol===`https:`?`wss:`:`ws:`}//${t}`}function hx(e){return mx(e).replace(/^ws/i,`http`)}function gx(e){return typeof e!=`number`||!Number.isFinite(e)?3e4:Math.min(6e5,Math.max(3e4,Math.round(e)))}var _x=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e){this.config=e,this.type=`runtype`,this.#e=null,this.#t=null,this.#n=[],this.#r=null,this.#i=null,this.#a=null,this.#o=[],this.#s=0,this.#c=null,this.#l=!1,this.#u=!1,this.#d=0,this.#f=!1,this.#p=-1/0,this.#m=null,this.#h=!1,this.#g=!1,this.#_=0,this.#v=0,this.#b=!1,this.bridge=null,this.#x=!1,this.#S=/* @__PURE__ */ new Set,this.#C=/* @__PURE__ */ new Map,this.#w=/* @__PURE__ */ new Set,this.#E=null,this.#D=null,this.#k=!1,this.#A=!1,this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F=/* @__PURE__ */ new Set,this.#I=/* @__PURE__ */ new Set,this.#L=null,this.#R=!1,this.#z=/* @__PURE__ */ new Set,this.#B=/* @__PURE__ */ new Set,this.#V=null,this.#H=/* @__PURE__ */ new Set,this.#U=null,this.#W=/* @__PURE__ */ new Map,this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}async connect(){}setSessionBridge(e){this.bridge=e}prewarm(){if(this.#l||this.#m)return;let e=this.config?.agentId,t=this.config?.clientToken,n=this.config?.host;if(!e||!t||!n)return;let r=Date.now();if(!(r-this.#p<3e4)){this.#p=r;try{this.config?.prewarmMode===`attach`?this.#Z(n,e,t):this.#X(n,e,t)}catch{}}}#X(e,t,n){if(typeof fetch!=`function`)return;let r=`${hx(e)}/v1/client/agents/${encodeURIComponent(t)}/voice/prewarm`;fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${n}`},keepalive:!0}).catch(()=>{})}#Z(e,t,n){let r=new URLSearchParams,i=this.config?.attachIdleMs,a=gx(i);i!==void 0&&r.set(`attachIdleMs`,String(a));let o=new WebSocket(this.#te(e,t,r),[`runtype.bearer`,`runtype.attach`,n]);o.binaryType=`arraybuffer`;let s=()=>{},c={ws:o,state:`connecting`,ready:new Promise(e=>{s=e}),settle:s,openedAt:0,idleTimer:void 0};this.#m=c,o.onopen=()=>{this.#m===c&&(c.state=o.protocol===`runtype.attach`?`attached`:`live`,c.openedAt=Date.now(),this.#Q(c,a),c.state===`attached`&&o.send(`{"type":"ping"}`),c.settle())},o.onmessage=e=>{if(this.#m!==c||typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}t.type===`attached`&&typeof t.idleMs==`number`&&this.#Q(c,t.idleMs-(Date.now()-c.openedAt))},o.onerror=()=>{},o.onclose=()=>{this.#m===c&&this.#$()}}#Q(e,t){clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{this.#m===e&&this.#$()},Math.max(0,t))}#$(){let e=this.#m;if(!e)return;this.#m=null,clearTimeout(e.idleTimer);let{ws:t}=e;if(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,e.settle(),t.readyState===WebSocket.CONNECTING||t.readyState===WebSocket.OPEN)try{t.close(1e3,`prewarm released`)}catch{}}async#ee(){let e=this.#m;if(!e)return null;if(e.state===`connecting`){let t;await Promise.race([e.ready,new Promise(e=>{t=setTimeout(e,5e3)})]),clearTimeout(t)}return this.#m===e?e.state===`connecting`||e.ws.readyState!==WebSocket.OPEN?(this.#$(),null):(this.#m=null,clearTimeout(e.idleTimer),{ws:e.ws,live:e.state===`live`}):null}#te(e,t,n){let r=`partial_transcript,context`;this.bridge&&this.config?.clientDelegation!==!1&&(r+=`,client_delegation,delegation_update,delegation_read_back,delegation_stream`,this.bridge.clientTools?.()&&(r+=`,client_tools,prior_tool_results`)),n&&(r=`attach,${r}`);let i=new URLSearchParams({voiceProtocol:`runtype-browser-v1`,clientVersion:`persona/${Li}`,voiceCapabilities:`full-duplex-v1`,clientCapabilities:r});return n?.forEach((e,t)=>i.set(t,e)),`${mx(e)}/ws/agents/${encodeURIComponent(t)}/voice?${i}`}async startListening(){if(this.#l)return;let e=this.#A;e||(this.#k=!1,this.#D=null),this.#A=!1;let t=this.config?.agentId,n=this.config?.clientToken,r=this.config?.host;if(!t)throw Error(`Runtype voice requires an agentId`);if(!n)throw Error(`Runtype voice requires a clientToken`);if(!r)throw Error(`Runtype voice requires a host (or widget apiUrl)`);let i=++this.#d;this.#f=!1,this.#l=!0;try{let a=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:cx,channelCount:1,echoCancellation:!0}});if(i!==this.#d){a.getTracks().forEach(e=>e.stop());return}this.#r=a;let o=new(window.AudioContext||window.webkitAudioContext)({sampleRate:cx});if(this.#t=o,o.state===`suspended`){if(await Promise.race([o.resume().catch(()=>{}),new Promise(t=>setTimeout(t,e?500:1e3))]),i!==this.#d)return;if(o.state!==`running`)throw Error(e?this.#D=`${dx} Tap the mic to reconnect.`:`Audio blocked until a tap`)}let s=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new $u(24e3);if(i!==this.#d){s.destroy(),a.getTracks().forEach(e=>e.stop()),o.close().catch(()=>{});return}this.#c=s,this.#he(),this.#ie(o,a,i);let c=await this.#ee();if(i!==this.#d){c?.ws.close(1e3,`client ended call`);return}if(c){let{ws:e}=c;this.#e=e,this.#ne(e,i),c.live||e.send(`{"type":"start"}`),this.#ae(e),this.#be(`listening`);return}let l=new WebSocket(this.#te(r,t),[`runtype.bearer`,n]);l.binaryType=`arraybuffer`,this.#e=l,l.onopen=()=>{i===this.#d&&(this.#ae(l),this.#be(`listening`))},this.#ne(l,i)}catch(e){throw this.#ye(),this.#xe(e),this.#be(`error`),e}}#ne(e,t){e.onmessage=e=>this.#oe(e,t),e.onerror=()=>{t!==this.#d||this.#E||(this.#xe(/* @__PURE__ */ Error(`Voice connection failed`)),this.#be(`error`),this.#ye())},e.onclose=e=>{if(this.#f){this.#f=!1;return}if(t!==this.#d)return;let n=this.#E??(e.code===4408?{reason:`idle_timeout`}:null);if(n)this.#re(n.reason,n.message);else{if(e.code!==1e3){let t=e.code?` (code ${e.code})`:``;this.#xe(/* @__PURE__ */ Error(`Voice connection closed${t}`)),this.#be(`error`)}else this.#be(`idle`);this.#ye()}}}#re(e,t){let n=ux.includes(e)&&!this.#k;if(this.#ye(),n)this.#k=!0,this.#l=!0,this.#D=e===`provider_error`?`${dx} Reconnecting…`:`Reconnecting…`,this.#O=setTimeout(()=>{this.#l=!1,this.#A=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#be(`idle`);else{if(ux.includes(e))return this.#D=dx,this.#xe(/* @__PURE__ */ Error(dx)),this.#be(`error`);if(e===`error`)return this.#be(`error`);this.#D=e===`quota`&&t||lx.get(e)||null,this.#be(`idle`)}}takeNotice(){let e=this.#D;return this.#D=null,e}getDisclosure(){let e=this.config?.disclosureText;return this.#l&&this.#h&&e!==!1?e||`You're talking to an AI assistant. Voice is processed by OpenAI.`:null}async stopListening(){this.#ye(),this.#be(`idle`)}async disconnect(){this.#ye(),this.#be(`disconnected`),this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}stopPlayback(){this.#ve();let e=this.#e;e&&e.readyState===WebSocket.OPEN&&(this.#h&&(this.#_=Date.now()+2e3,e.send(`{"type":"cancel"}`)),this.#be(`listening`))}getInterruptionMode(){return`barge-in`}isBargeInActive(){return this.#l}onLevel(e){this.#n.push(e)}async deactivateBargeIn(){this.#ye(),this.#be(`idle`)}#ie(e,t,n){let r=e.createMediaStreamSource(t);this.#i=r;let i=e.createScriptProcessor(4096,1,1);this.#a=i,i.onaudioprocess=e=>{if(n!==this.#d)return;let t=this.#e,r=t?.readyState===WebSocket.OPEN;if(t&&!r&&t.readyState!==WebSocket.CONNECTING)return;let i=e.inputBuffer.getChannelData(0),a=new Int16Array(i.length),o=0;for(let e=0;e<i.length;e++){let t=Math.max(-1,Math.min(1,i[e]));o+=t*t,a[e]=t<0?t*32768:t*32767}if(t&&r)this.#ae(t),t.send(a.buffer);else for(this.#o.push(a.buffer),this.#s+=a.byteLength;this.#s>256e3;)this.#s-=this.#o.shift().byteLength;if(this.#n.length>0){let e=Math.sqrt(o/i.length),t=Math.max(0,Math.min(1,e*4));for(let e of this.#n)e(t)}},r.connect(i),i.connect(e.destination)}#ae(e){for(let t of this.#o)e.send(t);this.#o=[],this.#s=0}#oe(e,t){if(t!==this.#d)return;if(e.data instanceof ArrayBuffer){this.#pe(e.data,t);return}let n;try{n=JSON.parse(e.data)}catch{return}switch(n.type){case`session_config`:n.speechMode&&(this.#h=n.speechMode===`speech_to_speech`,this.#c?.setContinuousMode?.(this.#h)),Array.isArray(n.capabilities)&&(this.#S=new Set(n.capabilities)),typeof n.callId==`string`&&(this.#T=n.callId),this.#x=this.#h&&this.#S.has(`client_delegation`)&&!!this.bridge,this.#h&&!this.#u&&this.#be(`listening`),this.#S.has(`context`)&&!this.#j&&(this.#j=!0,this.#M=this.#se()),this.#x&&this.#S.has(`client_tools`)&&!this.#V&&(this.#V=this.bridge.clientTools?.()?.open({send:e=>{let n=this.#e;return t!==this.#d||n?.readyState!==WebSocket.OPEN?!1:(n.send(JSON.stringify(e)),!0)},cancelled:e=>this.#w.has(e)}).catch(()=>null)??null);break;case`client_tool_call`:{let e=String(n.delegationId);this.#V&&!this.#W.has(e)&&(this.#W.set(e,this.#U),this.#F.add(e)),this.#V?.then(e=>e?.call(n));break}case`transcript_update`:{let e=n.role===`assistant`?`assistant`:`user`,r=n.utteranceId??n.turnId;if(!r||e===`assistant`&&this.#me())break;let i=String(r);if(e===`user`)n.final===!0&&(this.#ce(t),this.#U={id:i,text:String(n.text??``)}),this.#R=!1;else{if(this.#S.has(`delegation_read_back`)){let e=n.delegationId;(typeof e==`string`&&this.#F.has(e)&&!this.#z.has(i)||this.#R&&!this.#z.has(i))&&(this.#B.add(i),this.#R=!1)}else this.#R&&!this.#z.has(i)&&(this.#B.add(i),this.#R=!1);if(this.#z.add(i),this.#B.has(i))break}this.#Se(e,n.text??``,n.final===!0,{turnId:i,...typeof n.startMs==`number`&&{startMs:n.startMs},...typeof n.endMs==`number`&&{endMs:n.endMs},...this.#x&&{caption:!0}});break}case`delegation_started`:case`delegation_completed`:{let e=String(n.delegationId??n.turnId);if(n.type===`delegation_started`){this.#ce(t),this.#H.add(e),this.#F.delete(e),this.#W.delete(e)&&this.#V?.then(t=>t?.abort(e));let r=n.input;this.#x&&r&&this.#fe(e,{delegationId:e,userText:String(r.text??``),userUtteranceIds:Array.isArray(r.userUtteranceIds)?r.userUtteranceIds.filter(e=>typeof e==`string`):[],messages:Array.isArray(r.messages)?r.messages:[],priorToolResults:r.priorToolResults},t)}else if(n.route===`direct`&&this.#V&&!this.#H.has(e)){let t=this.#W.get(e)??this.#U;this.#W.delete(e),this.#H.add(e),this.#F.add(e),this.bridge?.recordDirectTurn?.({delegationId:e,userText:t?.text??``,userUtteranceIds:t?[t.id]:[],assistantText:typeof n.text==`string`?n.text:``})}n.type===`delegation_completed`&&n.speak!==!1&&this.#F.has(e)&&!this.#I.delete(e)&&!this.#S.has(`delegation_read_back`)&&this.#ue(e),this.#g=n.type===`delegation_started`,!this.#u&&!this.#me()&&this.#be(this.#g?`processing`:`listening`);break}case`delegation_progress`:{let e=String(n.delegationId);this.#F.has(e)&&!this.#I.has(e)&&!this.#w.has(e)&&(this.#I.add(e),this.#ue(e));break}case`delegation_cancelled`:this.#de(String(n.delegationId),n.reason!==`session_ending`&&n.reason!==`provider_cancelled`);break;case`warning`:console.warn(`[Persona voice] ${n.code}: ${n.message??``}`,this.#T??``),n.delegationId&&(n.code===`UNKNOWN_DELEGATION`||n.code===`LATE_RESULT_LIMIT`)&&this.#de(String(n.delegationId));break;case`audio_clear`:this.#ve(),this.#_=0,this.#be(`listening`);break;case`transcript_interim`:this.#be(`listening`),this.#Se(`user`,n.text??``,!1);break;case`transcript_final`:{let e=n.role===`assistant`?`assistant`:`user`;this.#be(e===`user`?`processing`:`speaking`),this.#Se(e,n.text??``,!0);break}case`audio_end`:this.#c?this.#c.markStreamEnd():(this.#u=!1,this.#be(`listening`));break;case`metrics`:this.#Ce({llmMs:n.llm_ms,ttsMs:n.tts_ms,firstAudioMs:n.first_audio_ms,totalMs:n.total_ms});break;case`error`:this.#xe(Error(n.error||`Voice error`)),this.#be(`error`);break;case`session_end`:this.#E={reason:String(n.reason),...typeof n.message==`string`&&{message:n.message}}}}async#se(){let e=this.bridge?.getHistory()??[],t=``;try{let e=this.config?.callContext;t=String((typeof e==`function`?await e():e)??``)}catch{}return fx(e,t)}#ce(e){let t=this.#M;if(!t)return;this.#M=null;let n=!1,r=t.then(t=>{let r=this.#e;!n&&t&&e===this.#d&&r?.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:`context`,text:t}))});this.#N={done:r,drop:()=>n=!0}}async#le(){let e=this.#N;if(!e)return;let t,n=await Promise.race([e.done.then(()=>!1),new Promise(e=>{t=setTimeout(()=>e(!0),2e3)})]);clearTimeout(t),n&&e.drop()}#ue(e){this.#R=!0,this.#L=e}#de(e,t=!1){this.#w.add(e),this.#L===e&&(this.#R=!1),this.#I.delete(e),this.#H.has(e)||this.#F.delete(e),this.#V?.then(t=>t?.abort(e)),this.bridge?.dropDelegation?.(e,t),this.#C.get(e)?.abort()}#fe(e,t,n){let r=this.bridge,i=({type:t,...r})=>{let i=this.#e;return n!==this.#d||i?.readyState!==WebSocket.OPEN||this.#w.has(e)?!1:(i.send(JSON.stringify({type:t,delegationId:e,...r})),!0)},a=(e,t,n,r=0)=>i({type:e,status:t,text:n,...r>0&&{streamedChars:r}});this.#P=this.#P.then(async()=>{if(n!==this.#d||this.#w.has(e))return;let o=null,s=this.#S.has(`delegation_stream`)&&this.#S.has(`delegation_read_back`),c=t=>{o=(o??this.#le()).then(()=>{i({type:`delegation_delta`,text:t})&&this.#F.add(e)})},l=await r.runDelegatedTurn(s?{...t,stream:c}:t).catch(()=>({status:`failed`,text:``}));await this.#le(),await o;let u=s?l.streamedChars??0:0,d=!!l.followUp,f=d&&this.#S.has(`delegation_update`);if(!a(f?`delegation_update`:`delegation_result`,d&&!f?`completed`:l.status,l.text,u)||(l.status!==`failed`&&l.inChat!==!1&&this.#F.add(e),!l.followUp))return;let p=new AbortController;this.#C.set(e,p),l.followUp({signal:p.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,54e4),readBack:f,onUpdate:e=>a(`delegation_update`,`pending_approval`,e)}).then(t=>{this.#C.delete(e),f&&t&&!p.signal.aborted&&a(`delegation_result`,t.status,t.text)})})}#pe(e,t){if(t!==this.#d||!this.#c||this.#me())return;let n=px(e);n.length!==0&&(this.#u||(this.#u=!0,this.#be(`speaking`)),this.#he(),this.#c.enqueue(n),this.#h&&this.#ge(n.length))}#me(){return Date.now()<this.#_}#he(){if(this.#b||!this.#c)return;this.#b=!0;let e=this.#d;this.#c.onFinished(()=>{e===this.#d&&(this.#b=!1,this.#_e())})}#ge(e){let t=Date.now();this.#v=Math.max(t,this.#v)+e/48,clearTimeout(this.#y),this.#y=setTimeout(()=>this.#_e(),this.#v-t+300)}#_e(){this.#u=!1,this.#v=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#be(this.#g?`processing`:`listening`)}#ve(){this.#c?.flush(),this.#b=!1,this.#he(),this.#u=!1,this.#v=0,clearTimeout(this.#y)}#ye(){this.#d+=1,this.#l=!1,this.#u=!1,this.#$(),this.#h=!1,this.#g=!1,this.#x=!1,this.#S=/* @__PURE__ */ new Set;for(let e of this.#C.values())e.abort();if(this.#C.clear(),this.#w.clear(),this.#T=void 0,this.#E=null,clearTimeout(this.#O),this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F.clear(),this.#I.clear(),this.#L=null,this.#R=!1,this.#z.clear(),this.#B.clear(),this.#V?.then(e=>e?.close()),this.#V=null,this.#H.clear(),this.#W.clear(),this.#U=null,this.#b=!1,this.#_=0,this.#v=0,clearTimeout(this.#y),this.#o=[],this.#s=0,this.#a&&=(this.#a.onaudioprocess=null,this.#a.disconnect(),null),this.#i&&=(this.#i.disconnect(),null),this.#r&&=(this.#r.getTracks().forEach(e=>e.stop()),null),this.#t&&=(this.#t.close().catch(()=>{}),null),this.#c&&=(this.#c.destroy(),null),this.#e){this.#f=!0;try{this.#e.close(1e3,`client ended call`)}catch{}this.#e=null}}onResult(e){this.#G.push(e)}onError(e){this.#K.push(e)}onStatusChange(e){this.#q.push(e)}onTranscript(e){this.#J.push(e)}onMetrics(e){this.#Y.push(e)}#be(e){this.#q.forEach(t=>t(e))}#xe(e){this.#K.forEach(t=>t(e))}#Se(e,t,n,r){this.#J.forEach(i=>i(e,t,n,r))}#Ce(e){this.#Y.forEach(t=>t(e))}},vx=class{#e;#t;#n;#r;#i;#a;constructor(e={}){this.config=e,this.type=`browser`,this.#e=null,this.#t=[],this.#n=[],this.#r=[],this.#i=!1,this.#a=typeof window<`u`?window:void 0}async connect(){this.#r.forEach(e=>e(`connected`))}async startListening(){try{if(this.#i)throw Error(`Already listening`);if(!this.#a)throw Error(`Window object not available`);let e=this.#a.SpeechRecognition||this.#a.webkitSpeechRecognition;if(!e)throw Error(`Browser speech recognition not supported`);this.#e=new e,this.#e.lang=this.config?.language||`en-US`,this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.onresult=e=>{let t=Array.from(e.results).map(e=>e[0]).map(e=>e.transcript).join(``),n=e.results[e.results.length-1].isFinal;this.#t.forEach(e=>e({text:t,confidence:n?.8:.5,provider:`browser`})),n&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=e=>{this.#n.forEach(t=>t(Error(e.error))),this.#r.forEach(e=>e(`error`))},this.#e.onstart=()=>{this.#i=!0,this.#r.forEach(e=>e(`listening`))},this.#e.onend=()=>{this.#i=!1,this.#r.forEach(e=>e(`idle`))},this.#e.start()}catch(e){throw this.#n.forEach(t=>t(e)),this.#r.forEach(e=>e(`error`)),e}}async stopListening(){this.#e&&=(this.#e.stop(),null),this.#i=!1,this.#r.forEach(e=>e(`idle`))}onResult(e){this.#t.push(e)}onError(e){this.#n.push(e)}onStatusChange(e){this.#r.push(e)}async disconnect(){await this.stopListening(),this.#r.forEach(e=>e(`disconnected`))}static isSupported(){return`SpeechRecognition`in window||`webkitSpeechRecognition`in window}};function yx(e){switch(e.type){case`runtype`:if(!e.runtype)throw Error(`Runtype voice provider requires configuration`);return new _x(e.runtype);case`browser`:if(!vx.isSupported())throw Error(`Browser speech recognition not supported`);return new vx(e.browser||{});case`custom`:{let t=e.custom;if(!t)throw Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t==`function`?t():t;if(!n||typeof n.startListening!=`function`)throw Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw Error(`Unknown voice provider type: ${e.type}`)}}function bx(e){if(e?.type===`custom`&&e.custom)return yx({type:`custom`,custom:e.custom});if(e?.type===`runtype`&&e.runtype)return yx({type:`runtype`,runtype:e.runtype});if(vx.isSupported())return yx({type:`browser`,browser:e?.browser||{language:`en-US`}});throw Error(`No supported voice providers available`)}function xx(e){try{return bx(e),!0}catch{return!1}}const Sx=(e,t)=>({ok:!1,reason:e,message:t}),Cx=e=>e.startsWith(`webmcp:`)?e.slice(7):e,wx={warn(e,...t){typeof console<`u`&&typeof console.warn==`function`&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};var Tx=class{#e;#t;#n=!1;#r=null;#i=!1;#a;constructor(e,t){this.config=e,this.#a=t,this.#e=e.onConfirm??null,this.#t=3e4}setConfirmHandler(e){this.#e=e}isOperational(){return this.config.enabled!==!0||!this.#n?!1:this.#l()!==null}async snapshotForDispatch(){if(await this.#s(),this.config.enabled!==!0)return[];let e=this.#l();if(!e)return[];let t;try{t=(await e.getTools()).filter(Lx)}catch(e){return wx.warn(`getTools() threw: shipping an empty WebMCP snapshot.`,e),[]}this.#a.recordToolDisplayTitles(t);let n=typeof location<`u`?location.origin:``;return t.filter(e=>this.#d(e.name)).map(e=>{let t=Ox(e.annotations);return{name:e.name,description:e.description,parametersSchema:kx(e.inputSchema),origin:`webmcp`,...n?{pageOrigin:n}:{},...t?{annotations:t}:{},...t?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(e,t,n){let r=await this.#o(e,t,n,!1);return r.ok?Ax(r.raw):Mx(r.message)}async executeVoiceToolCall(e,t,n={}){let r=await this.#o(e,t,n.signal,n.autoConfirmReadOnly===!0);return r.ok?Px(r.raw):{status:r.reason===`aborted`?`failed`:r.reason,error:{message:r.message}}}watchToolChanges(e){let t=!1,n=null;return this.#s().then(()=>{if(t||this.config.enabled!==!0)return;let r=this.#l();r&&typeof r.addEventListener==`function`&&(n=r,n.addEventListener(`toolchange`,e))}),()=>{t=!0,n?.removeEventListener(`toolchange`,e),n=null}}async#o(e,t,n,r){if(await this.#s(),this.config.enabled!==!0)return Sx(`failed`,`WebMCP is not enabled on this widget.`);let i=this.#l();if(!i){let e=typeof document<`u`&&!!document.modelContext;return Sx(`failed`,e?`WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).`:`WebMCP bridge is not operational on this page (document.modelContext not available).`)}let a=Cx(e),o;try{o=(await i.getTools()).filter(Lx)}catch(e){let t=e instanceof Error?e.message:String(e);return Sx(`failed`,`Failed to read WebMCP registry: ${t}`)}this.#a.recordToolDisplayTitles(o);let s=o.find(e=>e.name===a);if(!s)return Sx(`stale`,`WebMCP tool not registered on this page: ${a}`);if(!this.#d(a))return Sx(`stale`,`WebMCP tool not allowed by client allowlist: ${a}`);if(n?.aborted)return Sx(`aborted`,`Aborted by cancel()`);let c=this.#a.getToolDisplayTitle(a),l=Ox(s.annotations),u={toolName:a,args:t,description:s.description,...l?{annotations:l}:{},...c?{title:c}:{},...n?{signal:n}:{},reason:`gate`};if(!(r&&l?.readOnlyHint===!0)&&!await this.#u(u))return Sx(`denied`,`User declined the tool call.`);if(n?.aborted)return Sx(`aborted`,`Aborted by cancel()`);let d=new AbortController,f=!1,p=setTimeout(()=>{f=!0,d.abort()},this.#t),m=()=>d.abort();n&&(n.aborted?d.abort():n.addEventListener(`abort`,m,{once:!0}));try{return{ok:!0,raw:await i.executeTool(s,jx(t),{signal:d.signal})}}catch(e){if(f)return Sx(`timeout`,`WebMCP tool '${a}' timed out after ${this.#t}ms`);if(n?.aborted)return Sx(`aborted`,`Aborted by cancel()`);let t=e instanceof Error?e.message:String(e);return Sx(`failed`,t)}finally{clearTimeout(p),n&&n.removeEventListener(`abort`,m)}}#s(){return this.config.enabled===!0?(this.#r||=this.#c(),this.#r):Promise.resolve()}async#c(){try{if(this.#l()){this.#n=!0;return}let e=await this.#a.loadPolyfill();`initializeWebMCPPolyfill`in e?e.initializeWebMCPPolyfill():e.installWebMCP(),this.#n=!0}catch(e){wx.warn(`Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.`,e),this.#n=!1}}#l(){if(typeof document>`u`)return null;let e=document.modelContext;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.getTools!=`function`||typeof t.executeTool!=`function`?(this.#i||(this.#i=!0,wx.warn(`document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).`)),null):e}async#u(e){let t=this.#e??Fx;try{return await t(e)}catch(t){return wx.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,t),!1}}#d(e){let t=this.config.allowlist;return!t||t.length===0||t.some(t=>Ex(e,t))}};const Ex=(e,t)=>{if(t===`*`)return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`^`+n.replace(/\*/g,`.*`)+`$`).test(e)},Dx={type:`object`,properties:{}},Ox=e=>{if(!e||typeof e!=`object`)return;let t={};for(let n of[`readOnlyHint`,`destructiveHint`,`consequentialHint`,`untrustedContentHint`,`idempotentHint`,`openWorldHint`,`debugging`]){let r=e[n];typeof r==`boolean`&&(t[n]=r)}return Object.keys(t).length>0?t:void 0},kx=e=>{if(e===void 0||e===``)return{...Dx};if(typeof e==`object`)return e!==null&&!Array.isArray(e)?e:{...Dx};try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{...Dx}}catch{return{...Dx}}},Ax=e=>{if(e==null)return{content:[{type:`text`,text:``}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:`text`,text:e}]}}return typeof t==`object`&&t&&Array.isArray(t.content)?t:{content:[{type:`text`,text:typeof t==`string`?t:Rx(t)}]}},jx=e=>{let t;try{t=JSON.stringify(e)??`{}`}catch{t=`{}`}let n=JSON.parse(t);if(typeof n!=`object`||!n)throw TypeError(`WebMCP tool arguments must be an object or array.`);return Object.defineProperty(n,Symbol.toPrimitive,{value:()=>t}),n},Mx=e=>({isError:!0,content:[{type:`text`,text:e}]}),Nx=e=>Array.isArray(e)?e.map(e=>e&&typeof e==`object`&&typeof e.text==`string`?e.text:``).filter(Boolean).join(`
|
|
470
|
+
`):``,Px=e=>{if(e==null)return{status:`completed`};let t;try{t=JSON.parse(e)}catch{return{status:`completed`,result:e}}return typeof t==`object`&&t&&t.isError===!0?{status:`failed`,error:{message:Nx(t.content)||`The page tool reported an error.`}}:t===void 0?{status:`completed`}:{status:`completed`,result:t}},Fx=async e=>{if(typeof window>`u`||typeof window.confirm!=`function`)return!1;let t=Ix(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`\n\nArguments:\n${t}`:``)+(e.description?`\n\n${e.description}`:``);return window.confirm(n)},Ix=e=>{if(e==null)return``;try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+`…`:t}catch{return String(e)}},Lx=e=>(e.window===void 0||typeof window<`u`&&e.window===window)&&(e.origin===void 0||typeof location<`u`&&e.origin===location.origin),Rx=e=>{if(e===void 0)return``;try{return JSON.stringify(e)}catch{return String(e)}};En();var zx=class extends Tx{constructor(e){super(e,{recordToolDisplayTitles:bn,getToolDisplayTitle:xn,loadPolyfill:Tn})}};function Bx(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}function Vx(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n.startsWith(r)?0:e.replace(/([a-z])([A-Z])/g,`$1 $2`).split(/[\s\-_/.]+/).some(e=>e.toLowerCase().startsWith(r))?1:Bx(r,n)?2:3}function Hx(e,t){let n=e.recencyScore??0,r=t.recencyScore??0;return r===n?e.label.localeCompare(t.label):r-n}function Ux(e,t){let n=t.trim();if(!n)return[...e].sort(Hx);let r=[];for(let t of e){let e=Vx(t.label,n);e!==3&&r.push({item:t,tier:e})}return r.sort((e,t)=>e.tier===t.tier?Hx(e.item,t.item):e.tier-t.tier),r.map(e=>e.item)}function Wx(e){let t=e.replace(/^\s+/,``),n=t.search(/\s/);return n===-1?{name:t,args:``}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function Gx(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>Ux(e.items,t),resolve:e.resolve}}function Kx(e){let t=e.commands.map(e=>({id:e.name,label:e.name,description:e.description,iconName:e.iconName,command:e.kind??`prompt`,insertMode:e.insertMode,submitOnSelect:e.submitOnSelect,action:e.action,commandArgsPlaceholder:e.argsPlaceholder})),n=new Map(e.commands.map(e=>[e.name,e])),r=new Map(t.map(e=>[e.id,e]));return{id:e.id,label:e.label,matchCommand:e=>r.get(e),resolveOn:`submit`,search:e=>Ux(t,Wx(e).name),resolve:(e,t)=>{let r=n.get(e.id);return r?r.kind===`server`?{context:(typeof r.data==`function`?r.data(t.args):r.data)??{}}:{insertText:typeof r.prompt==`function`?r.prompt(t.args):r.prompt??``}:{}}}}function qx(e,t){let n=t.orientation??`horizontal`,r=n===`vertical`?`ArrowUp`:`ArrowLeft`,i=n===`vertical`?`ArrowDown`:`ArrowRight`;e.setAttribute(`role`,`tablist`);let a=[],o=!1,s=e=>{typeof e.scrollIntoView==`function`&&e.scrollIntoView({block:`nearest`,inline:`nearest`})},c=e=>{let t=e;return a.findIndex(e=>e===t||e.contains(t))},l=e=>{let n=c(e.target);if(n<0)return;let o=n;if(e.key===i)o=Math.min(n+1,a.length-1);else if(e.key===r)o=Math.max(n-1,0);else if(e.key===`Home`)o=0;else if(e.key===`End`)o=a.length-1;else return;e.preventDefault(),o!==n&&t.onSelect(o)},u=e=>{let t=c(e.target);t>=0&&s(a[t])};return e.addEventListener(`keydown`,l),e.addEventListener(`focusin`,u),{beforeRender(){o=typeof document<`u`&&e.contains(document.activeElement)},render(e,t){if(a=e,e.forEach((e,n)=>{e.setAttribute(`role`,`tab`);let r=n===t;e.setAttribute(`aria-selected`,r?`true`:`false`),e.tabIndex=r||t<0&&n===0?0:-1}),o){let n=(t>=0?e[t]:void 0)??e[0];n&&typeof n.focus==`function`&&(s(n),n.focus())}},destroy(){e.removeEventListener(`keydown`,l),e.removeEventListener(`focusin`,u)}}}mn(),En(),er(),ti(),fi(),Z(),Ri(),No(),$o();export{mi as ASK_USER_QUESTION_CLIENT_TOOL,pi as ASK_USER_QUESTION_PARAMETERS_SCHEMA,nr as ASK_USER_QUESTION_TOOL_NAME,Eu as AgentWidgetClient,vd as AgentWidgetSession,wd as AttachmentManager,Hu as BrowserSpeechEngine,np as DEFAULT_COMPONENTS,So as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,xo as DEFAULT_FLOATING_LAUNCHER_WIDTH,Xf as DEFAULT_PALETTE,$f as DEFAULT_SEMANTIC,Mo as DEFAULT_WIDGET_CONFIG,Du as HistoryProviderError,_b as PRESETS,gb as PRESET_FULLSCREEN,hb as PRESET_MINIMAL,mb as PRESET_SHOP,Uu as ReadAloudController,ii as SUGGEST_REPLIES_CLIENT_TOOL,ri as SUGGEST_REPLIES_PARAMETERS_SCHEMA,ni as SUGGEST_REPLIES_TOOL_NAME,gp as THEME_ZONES,Li as VERSION,vn as WEBMCP_TOOL_PREFIX,zx as WebMcpBridge,bb as accessibilityPlugin,xb as animationsPlugin,Q_ as applyFeaturePreferences,Pp as applyThemeVariables,sh as attachHeaderToContainer,Sb as brandPlugin,bh as buildComposer,mh as buildDefaultHeader,oh as buildHeader,yh as buildHeaderWithLayout,gh as buildMinimalHeader,hi as builtInClientToolsForDispatch,Dn as canonicalArtifactDisplayMode,ub as collectEnrichedPageContext,u_ as componentRegistry,wv as createActionManager,uy as createAgentExperience,Yr as createAskUserQuestionBubble,bx as createBestAvailableVoiceProvider,Xh as createBubbleWithLayout,Jv as createCSATFeedback,ph as createComboButton,Uv as createComponentMiddleware,Bv as createComponentStreamParser,Kl as createDefaultSanitizer,sx as createDemoCarousel,Hl as createDirectivePostprocessor,ch as createDropdownMenu,Qn as createFlexibleJsonStreamParser,lh as createIconButton,zo as createImagePart,Zn as createJsonStreamParser,uh as createLabelButton,kv as createLocalStorageAdapter,Pl as createMarkdownProcessor,Fl as createMarkdownProcessorFromConfig,Jh as createMessageActions,Yv as createNPSFeedback,Yn as createPlainTextParser,Eb as createPlugin,Xn as createRegexJsonParser,qx as createRovingTablist,Kx as createSlashCommandsSource,fh as createSplitButton,Yh as createStandardBubble,Gx as createStaticMentionSource,Ro as createTextPart,up as createTheme,Fp as createThemeObserver,dh as createToggleGroup,zh as createTypingIndicator,yx as createVoiceProvider,ky as createWidgetHostLayout,$n as createXmlParser,yb as default,Sv as defaultActionHandlers,bv as defaultJsonActionParser,Ux as defaultMentionFilter,Yy as defaultParseRules,Dp as detectColorScheme,Ul as directivePostprocessor,Xr as ensureAskUserQuestionSheet,Rl as escapeHtml,Kv as extractComponentDirectiveFromMessage,Bo as fileToImagePart,db as formatEnrichedContext,Js as generateAssistantMessageId,Kb as generateCodeSnippet,Ks as generateMessageId,rb as generateStableSelector,qs as generateUserMessageId,Mp as getActiveTheme,Ny as getAgentWidgetHandles,kp as getColorScheme,Fo as getDisplayText,vh as getHeaderLayout,Lo as getImageParts,vb as getPreset,Gv as hasComponentDirective,Io as hasImages,_h as headerLayouts,wb as highContrastPlugin,Py as initAgentWidget,xr as isAskUserQuestionMessage,Vv as isComponentDirectiveType,Bm as isDockedMountMode,Ou as isHistoryProviderError,oi as isSuggestRepliesMessage,xx as isVoiceSupported,wn as isWebMcpToolName,gg as isWelcomeVisible,ci as latestAgentSuggestions,mm as listRegisteredStreamAnimations,Ut as loadMarkdownParsers,Ll as markdownPostprocessor,bo as mergeWithDefaults,Po as normalizeContent,On as normalizeMediaType,Wt as onMarkdownParsersReady,Cr as parseAskUserQuestionPayload,si as parseSuggestRepliesPayload,K_ as parseWidgetPreferenceSlice,Vu as pickBestVoice,fv as pluginRegistry,Cb as reducedMotionPlugin,un as registerIcons,fm as registerStreamAnimationPlugin,Zr as removeAskUserQuestionSheet,Hv as renderComponentDirective,Bh as renderLoadingIndicatorWithFallback,K as renderLucideIcon,An as resolveArtifactDisplay,jn as resolveArtifactDisplayMode,$_ as resolveConfigPreferences,Hm as resolveDockConfig,ql as resolveSanitizer,op as resolveTokens,mg as resolveWelcomeConfig,Cn as stripWebMcpPrefix,hp as themeToCssVariables,pm as unregisterStreamAnimationPlugin,Vo as validateImageFile,sp as validateTheme};
|
|
471
471
|
//# sourceMappingURL=index.js.map
|