@runtypelabs/persona 4.26.1 → 4.28.0

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.
Files changed (61) hide show
  1. package/dist/approval-ui.d.cts +18 -0
  2. package/dist/approval-ui.d.ts +18 -0
  3. package/dist/artifacts-ui.d.cts +18 -0
  4. package/dist/artifacts-ui.d.ts +18 -0
  5. package/dist/chunk-AALCT54S.js +1 -0
  6. package/dist/{client-history-GOZWBDA5.js → client-history-LV3KHEFA.js} +1 -1
  7. package/dist/client-history.js +1 -1
  8. package/dist/client-stream-N22JHTLE.js +4 -0
  9. package/dist/client-stream.js +3 -3
  10. package/dist/codegen.cjs +1 -1
  11. package/dist/codegen.js +1 -1
  12. package/dist/context-mentions.d.cts +18 -0
  13. package/dist/context-mentions.d.ts +18 -0
  14. package/dist/event-stream-view.d.cts +18 -0
  15. package/dist/event-stream-view.d.ts +18 -0
  16. package/dist/forms-ui.d.cts +26 -0
  17. package/dist/forms-ui.d.ts +26 -0
  18. package/dist/index.cjs +57 -57
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +34 -0
  21. package/dist/index.d.ts +34 -0
  22. package/dist/index.global.js +1 -1
  23. package/dist/index.global.js.map +1 -1
  24. package/dist/index.js +58 -58
  25. package/dist/index.js.map +1 -1
  26. package/dist/session-reconnect.d.cts +18 -0
  27. package/dist/session-reconnect.d.ts +18 -0
  28. package/dist/smart-dom-reader.d.cts +18 -0
  29. package/dist/smart-dom-reader.d.ts +18 -0
  30. package/dist/theme-editor-preview.cjs +66 -66
  31. package/dist/theme-editor-preview.d.cts +18 -0
  32. package/dist/theme-editor-preview.d.ts +18 -0
  33. package/dist/theme-editor-preview.js +31 -31
  34. package/dist/theme-editor.d.cts +18 -0
  35. package/dist/theme-editor.d.ts +18 -0
  36. package/dist/voice-runtime-LVUMPUDS.js +17 -0
  37. package/dist/voice-runtime.cjs +7 -7
  38. package/dist/voice-runtime.d.cts +33 -0
  39. package/dist/voice-runtime.d.ts +33 -0
  40. package/dist/voice-runtime.js +7 -7
  41. package/package.json +1 -1
  42. package/src/client-stream.ts +10 -3
  43. package/src/client.interrupt.test.ts +18 -0
  44. package/src/client.test.ts +20 -0
  45. package/src/client.ts +7 -0
  46. package/src/session.ts +16 -3
  47. package/src/session.voice.test.ts +199 -3
  48. package/src/types.ts +24 -0
  49. package/src/ui.composer-defer-one.test.ts +17 -0
  50. package/src/ui.ts +49 -12
  51. package/src/voice/__fixtures__/voice-wire/server/session_end-provider-error.json +6 -0
  52. package/src/voice/__fixtures__/voice-wire/server/session_end-unknown-reason.json +4 -0
  53. package/src/voice/__fixtures__/voice-wire/server/session_end.json +5 -0
  54. package/src/voice/runtype-voice-provider.ts +205 -21
  55. package/src/voice/voice-clause-buffer.test.ts +143 -0
  56. package/src/voice/voice-clause-buffer.ts +187 -0
  57. package/src/voice/voice-delegation.ts +111 -13
  58. package/src/voice/voice.test.ts +433 -2
  59. package/dist/chunk-GKPCIQPB.js +0 -1
  60. package/dist/client-stream-42FOI3EC.js +0 -4
  61. package/dist/voice-runtime-XLU6YK2N.js +0 -17
package/dist/index.js CHANGED
@@ -1,33 +1,33 @@
1
- var RM=Object.defineProperty;var $e=(e,t)=>()=>(e&&(t=e(e=0)),t);var Qs=(e,t)=>{for(var n in t)RM(e,n,{get:t[n],enumerable:!0})};var it,ln=$e(()=>{"use strict";it=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:d=>{o=d,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(g=>(r=g,g)).catch(g=>{throw s=null,g}),s),provide:d=>{r=d},getSync:()=>r}}});var hb={};Qs(hb,{DOMPurify:()=>OM,Marked:()=>WM});import{Marked as WM}from"marked";import OM from"dompurify";var yb=$e(()=>{"use strict"});var _t,Mr=$e(()=>{"use strict";_t=(e,t=24,n="currentColor",o=2)=>{if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let i=s[0],l=s[1];if(!l)return;let c=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([p,d])=>{p!=="stroke"&&c.setAttribute(p,String(d))}),r.appendChild(c)}),r}});var pO,YE,Gc,hg=$e(()=>{"use strict";ln();({setLoader:pO,load:YE}=it({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")})),Gc=YE});import{Activity as XE,ArrowDown as QE,ArrowLeft as JE,ArrowRight as ZE,ArrowUp as eT,ArrowUpRight as tT,AtSign as nT,Bot as oT,Check as rT,ChevronDown as sT,ChevronLeft as iT,ChevronRight as aT,ChevronUp as lT,Clipboard as cT,ClipboardCopy as dT,CodeXml as pT,Copy as uT,Download as gT,Ellipsis as fT,EllipsisVertical as mT,ExternalLink as hT,Eye as yT,File as bT,FileCode as vT,FileSpreadsheet as CT,FileText as wT,History as ST,ImagePlus as AT,Loader as xT,LoaderCircle as MT,Maximize as ET,Menu as TT,MessageSquare as PT,Mic as kT,Minimize as LT,Minus as HT,PanelLeft as IT,Paperclip as RT,Pencil as WT,Plus as OT,Quote as BT,RefreshCw as _T,Search as DT,Send as NT,ShieldAlert as FT,ShieldCheck as $T,ShieldX as UT,Square as VT,Star as jT,ThumbsDown as qT,ThumbsUp as zT,Trash as KT,Trash2 as GT,Upload as YT,Volume2 as XT,X as QT}from"lucide";var JT,ZT,Js,zi,Ki,Yc,bg,wb,vg,eP,Sb,yg,tP,nP,ue,Tt=$e(()=>{"use strict";Mr();hg();JT={activity:XE,"arrow-down":QE,"arrow-up":eT,"arrow-up-right":tT,bot:oT,"chevron-down":sT,"chevron-up":lT,"chevron-right":aT,"chevron-left":iT,check:rT,clipboard:cT,"clipboard-copy":dT,"code-xml":pT,copy:uT,file:bT,"file-code":vT,"file-spreadsheet":CT,"file-text":wT,"image-plus":AT,loader:xT,"loader-circle":MT,mic:kT,paperclip:RT,quote:BT,"refresh-cw":_T,search:DT,send:NT,"shield-alert":FT,"shield-check":$T,"shield-x":UT,square:VT,"thumbs-down":qT,"thumbs-up":zT,upload:YT,"volume-2":XT,x:QT,"at-sign":nT,"arrow-left":JE,"arrow-right":ZE,"external-link":hT,ellipsis:fT,"ellipsis-vertical":mT,menu:TT,"panel-left":IT,plus:OT,minus:HT,pencil:WT,trash:KT,"trash-2":GT,download:gT,maximize:ET,minimize:LT,"message-square":PT,star:jT,eye:yT,history:ST},ZT=["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"],Js=new Map(Object.entries(JT)),zi=new Set,Ki=!1,Yc=new Set,bg=e=>{let t=[...Yc];e&&Yc.clear();for(let n of t)try{n()}catch{}},wb=e=>Ki?()=>{}:(Yc.add(e),()=>{Yc.delete(e)}),vg=()=>{let e=0;for(let t of[...zi]){let n=Js.get(t.name);if(!n)continue;zi.delete(t),e++;let o=_t(n,t.size,t.color,t.strokeWidth);if(o)for(t.el.removeAttribute("data-persona-icon-pending");o.firstChild;)t.el.appendChild(o.firstChild)}return e},eP=e=>{for(let[t,n]of Object.entries(e))Js.set(t,n);vg()>0&&!Ki&&bg(!1)},Sb=e=>{if(!Ki){for(let[t,n]of Object.entries(e))Js.has(t)||Js.set(t,n);Ki=!0,vg(),bg(!0)}},yg=!1,tP=()=>{Gc().then(e=>{if(!Ki){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))Js.has(t)||Js.set(t,n);Ki=!0,vg(),bg(!0)}}).catch(e=>{yg=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},nP=(e,t,n)=>{let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-icon-pending","true"),o},ue=(e,t=24,n="currentColor",o=2)=>{let r=Js.get(e);if(r)return _t(r,t,n,o);if(ZT.includes(e)){yg&&(yg=!1);let s=nP(t,n,o);if(zi.size>=500){let i=zi.values().next().value;i&&zi.delete(i)}return zi.add({el:s,name:e,size:t,color:n,strokeWidth:o}),tP(),s}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}});function Mb(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${oP(t.join(""))}`}function xb(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function oP(e){let t=xb(e,0).toString(36),n=xb(e,2654435761).toString(36);return`${t}.${n}`}var Xc,Cg,Qc,Gi,Ab,Eb,Zs,Jc,ei=$e(()=>{"use strict";Xc="webmcp:",Cg=new Map,Qc=e=>{Cg.clear();for(let t of e){let n=t.title?.trim();n&&Cg.set(t.name,n)}},Gi=e=>Cg.get(Eb(e)),Ab=null;Eb=e=>e.startsWith(Xc)?e.slice(Xc.length):e,Zs=e=>e.startsWith(Xc),Jc=()=>Ab?Ab():import("@mcp-b/webmcp-polyfill")});function Qn(e){return e==="card"?"collapsed":e}function ti(e){return e.split(";",1)[0].trim().toLowerCase()}function rP(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(ti(r)===t)return{mode:Qn(s),selector:ti(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(ti(r)===o)return{mode:Qn(s),selector:o}}function Tb(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:Qn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?ti(t.file.mimeType):void 0,c=l?rP(o.files.byMediaType,l):void 0;if(l&&c)return{mode:c.mode,matchedBy:{type:"mediaType",mediaType:l,selector:c.selector}};if(o.files.default)return{mode:Qn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:Qn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:Qn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:Qn(i),matchedBy:{type:"preferredMode"}}:o.default?{mode:Qn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Er(e,t){return Tb(e,t).mode}function al(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 Yi=$e(()=>{"use strict"});import{parse as Pb,STR as kb,OBJ as Lb}from"partial-json";var Zc,Xi,sP,Hb,iP,aP,Ib,lP,Rb,ed,cl,td,wg,nd,ll,cP,dl,Sg,Ag,xg,dP,Mg,ss=$e(()=>{"use strict";Zc=e=>e.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Xi=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)}},sP=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Hb=e=>e.status==="complete"?sP(e):e.status==="pending"?"Waiting":"",iP=15e3,aP=1200,Ib=(e,t)=>{let n=t?.durationMs??iP,o=t?.chars??aP;return typeof e.durationMs=="number"?e.durationMs<n:(e.chunks??[]).join("").length<o},lP=e=>{let n=(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 n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`},Rb=e=>e.status==="complete"?lP(e):"Using tool...",ed=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},cl=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 ed(t)},td=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return ed(t)},wg=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=cl(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},nd=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=r.exec(n))!==null;)i.index>s&&ll(o,n.slice(s,i.index),[]),i[1]!==void 0?ll(o,i[1],["bold"]):i[2]!==void 0?ll(o,i[2],["italic"]):i[3]!==void 0&&ll(o,i[3],["dim"]),s=i.index+i[0].length;return s<n.length&&ll(o,n.slice(s),[]),o},ll=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},cP=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
1
+ var DE=Object.defineProperty;var $e=(e,t)=>()=>(e&&(t=e(e=0)),t);var Qs=(e,t)=>{for(var n in t)DE(e,n,{get:t[n],enumerable:!0})};var it,ln=$e(()=>{"use strict";it=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:d=>{o=d,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(g=>(r=g,g)).catch(g=>{throw s=null,g}),s),provide:d=>{r=d},getSync:()=>r}}});var Cb={};Qs(Cb,{DOMPurify:()=>FE,Marked:()=>NE});import{Marked as NE}from"marked";import FE from"dompurify";var wb=$e(()=>{"use strict"});var Bt,Er=$e(()=>{"use strict";Bt=(e,t=24,n="currentColor",o=2)=>{if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let i=s[0],l=s[1];if(!l)return;let c=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([p,d])=>{p!=="stroke"&&c.setAttribute(p,String(d))}),r.appendChild(c)}),r}});var vO,eT,Xc,vg=$e(()=>{"use strict";ln();({setLoader:vO,load:eT}=it({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")})),Xc=eT});import{Activity as tT,ArrowDown as nT,ArrowLeft as oT,ArrowRight as rT,ArrowUp as sT,ArrowUpRight as iT,AtSign as aT,Bot as lT,Check as cT,ChevronDown as dT,ChevronLeft as pT,ChevronRight as uT,ChevronUp as gT,Clipboard as fT,ClipboardCopy as mT,CodeXml as hT,Copy as yT,Download as bT,Ellipsis as vT,EllipsisVertical as CT,ExternalLink as wT,Eye as ST,File as AT,FileCode as xT,FileSpreadsheet as ET,FileText as MT,History as TT,ImagePlus as kT,Loader as PT,LoaderCircle as LT,Maximize as HT,Menu as IT,MessageSquare as RT,Mic as WT,Minimize as OT,Minus as _T,PanelLeft as BT,Paperclip as DT,Pencil as NT,Plus as FT,Quote as $T,RefreshCw as UT,Search as VT,Send as jT,ShieldAlert as qT,ShieldCheck as zT,ShieldX as KT,Square as GT,Star as YT,ThumbsDown as XT,ThumbsUp as QT,Trash as JT,Trash2 as ZT,Upload as ek,Volume2 as tk,X as nk}from"lucide";var ok,rk,Js,zi,Ki,Qc,wg,Eb,Sg,sk,Mb,Cg,ik,ak,ue,Tt=$e(()=>{"use strict";Er();vg();ok={activity:tT,"arrow-down":nT,"arrow-up":sT,"arrow-up-right":iT,bot:lT,"chevron-down":dT,"chevron-up":gT,"chevron-right":uT,"chevron-left":pT,check:cT,clipboard:fT,"clipboard-copy":mT,"code-xml":hT,copy:yT,file:AT,"file-code":xT,"file-spreadsheet":ET,"file-text":MT,"image-plus":kT,loader:PT,"loader-circle":LT,mic:WT,paperclip:DT,quote:$T,"refresh-cw":UT,search:VT,send:jT,"shield-alert":qT,"shield-check":zT,"shield-x":KT,square:GT,"thumbs-down":XT,"thumbs-up":QT,upload:ek,"volume-2":tk,x:nk,"at-sign":aT,"arrow-left":oT,"arrow-right":rT,"external-link":wT,ellipsis:vT,"ellipsis-vertical":CT,menu:IT,"panel-left":BT,plus:FT,minus:_T,pencil:NT,trash:JT,"trash-2":ZT,download:bT,maximize:HT,minimize:OT,"message-square":RT,star:YT,eye:ST,history:TT},rk=["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"],Js=new Map(Object.entries(ok)),zi=new Set,Ki=!1,Qc=new Set,wg=e=>{let t=[...Qc];e&&Qc.clear();for(let n of t)try{n()}catch{}},Eb=e=>Ki?()=>{}:(Qc.add(e),()=>{Qc.delete(e)}),Sg=()=>{let e=0;for(let t of[...zi]){let n=Js.get(t.name);if(!n)continue;zi.delete(t),e++;let o=Bt(n,t.size,t.color,t.strokeWidth);if(o)for(t.el.removeAttribute("data-persona-icon-pending");o.firstChild;)t.el.appendChild(o.firstChild)}return e},sk=e=>{for(let[t,n]of Object.entries(e))Js.set(t,n);Sg()>0&&!Ki&&wg(!1)},Mb=e=>{if(!Ki){for(let[t,n]of Object.entries(e))Js.has(t)||Js.set(t,n);Ki=!0,Sg(),wg(!0)}},Cg=!1,ik=()=>{Xc().then(e=>{if(!Ki){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))Js.has(t)||Js.set(t,n);Ki=!0,Sg(),wg(!0)}}).catch(e=>{Cg=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},ak=(e,t,n)=>{let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-icon-pending","true"),o},ue=(e,t=24,n="currentColor",o=2)=>{let r=Js.get(e);if(r)return Bt(r,t,n,o);if(rk.includes(e)){Cg&&(Cg=!1);let s=ak(t,n,o);if(zi.size>=500){let i=zi.values().next().value;i&&zi.delete(i)}return zi.add({el:s,name:e,size:t,color:n,strokeWidth:o}),ik(),s}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}});function Pb(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${lk(t.join(""))}`}function kb(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function lk(e){let t=kb(e,0).toString(36),n=kb(e,2654435761).toString(36);return`${t}.${n}`}var Jc,Ag,Zc,Gi,Tb,Lb,Zs,ed,ei=$e(()=>{"use strict";Jc="webmcp:",Ag=new Map,Zc=e=>{Ag.clear();for(let t of e){let n=t.title?.trim();n&&Ag.set(t.name,n)}},Gi=e=>Ag.get(Lb(e)),Tb=null;Lb=e=>e.startsWith(Jc)?e.slice(Jc.length):e,Zs=e=>e.startsWith(Jc),ed=()=>Tb?Tb():import("@mcp-b/webmcp-polyfill")});function Jn(e){return e==="card"?"collapsed":e}function ti(e){return e.split(";",1)[0].trim().toLowerCase()}function ck(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(ti(r)===t)return{mode:Jn(s),selector:ti(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(ti(r)===o)return{mode:Jn(s),selector:o}}function Hb(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:Jn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?ti(t.file.mimeType):void 0,c=l?ck(o.files.byMediaType,l):void 0;if(l&&c)return{mode:c.mode,matchedBy:{type:"mediaType",mediaType:l,selector:c.selector}};if(o.files.default)return{mode:Jn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:Jn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:Jn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:Jn(i),matchedBy:{type:"preferredMode"}}:o.default?{mode:Jn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Mr(e,t){return Hb(e,t).mode}function al(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 Yi=$e(()=>{"use strict"});import{parse as Ib,STR as Rb,OBJ as Wb}from"partial-json";var td,Xi,dk,Ob,pk,uk,_b,gk,Bb,nd,cl,od,xg,rd,ll,fk,dl,Eg,Mg,Tg,mk,kg,ss=$e(()=>{"use strict";td=e=>e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Xi=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)}},dk=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Ob=e=>e.status==="complete"?dk(e):e.status==="pending"?"Waiting":"",pk=15e3,uk=1200,_b=(e,t)=>{let n=t?.durationMs??pk,o=t?.chars??uk;return typeof e.durationMs=="number"?e.durationMs<n:(e.chunks??[]).join("").length<o},gk=e=>{let n=(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 n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`},Bb=e=>e.status==="complete"?gk(e):"Using tool...",nd=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},cl=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 nd(t)},od=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return nd(t)},xg=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=cl(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},rd=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=r.exec(n))!==null;)i.index>s&&ll(o,n.slice(s,i.index),[]),i[1]!==void 0?ll(o,i[1],["bold"]):i[2]!==void 0?ll(o,i[2],["italic"]):i[3]!==void 0&&ll(o,i[3],["dim"]),s=i.index+i[0].length;return s<n.length&&ll(o,n.slice(s),[]),o},ll=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},fk=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
3
3
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(i);if(l&&l[1])try{return l[1].replace(/\\n/g,`
4
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},dl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Sg=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ag=()=>{let e=cP();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)}},xg=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=Pb(n,kb|Lb);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Zc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Zc(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},dP=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?Zc(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Zc(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let l=Pb(s,kb|Lb),c=r(l);c!==null&&(t=c)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Mg=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}}});var x,X,Wn,Xe=$e(()=>{"use strict";x=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},X=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,i]of Object.entries(t.attrs))o.setAttribute(s,i);if(t.style){let s=o.style,i=t.style;for(let l of Object.keys(i)){let c=i[l];c!=null&&(s[l]=c)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Wn=(...e)=>e.filter(Boolean).join(" ")});import{parse as pP,ARR as uP,OBJ as gP,STR as fP}from"partial-json";var od,pl,Qi,mP,hP,Ob,Bb,yP,bP,vP,CP,wP,Eg,Tg,_b,Pg,Db,SP,AP,Wb,Nb,is,rd,as,ul,xP,MP,Fb,$b,EP,TP,PP,Ub,kP,LP,ni,Vb,yo,HP,Ji,ls,IP,RP,sd,jb,qb,kg,WP,OP,BP,Lg,cs,Hg,ds,id,gl=$e(()=>{"use strict";Xe();od="ask_user_question",pl=8,Qi="data-persona-ask-sheet-for",mP="Other",hP="Other\u2026",Ob="Type your own answer here",Bb="Send",yP="Next",bP="Back",vP="Submit all",CP="Skip",wP=3,Eg="data-ask-current-index",Tg="data-ask-question-count",_b="data-ask-answers",Pg="data-ask-grouped",Db="data-ask-layout",SP=e=>e.layout==="pills"?"pills":"rows",AP=e=>e.getAttribute(Db)==="pills"?"pills":"rows",Wb=!1,Nb=e=>e.replace(/["\\]/g,"\\$&"),is=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===od,rd=e=>e?.features?.askUserQuestion??{},as=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 o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=pP(r,fP|gP|uP);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ul=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>pl&&!Wb&&(Wb=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${pl}.`)),t.slice(0,pl)},xP=e=>ul(e)[0]??null,MP=(e,t)=>ul(e)[t]??null,Fb=(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))},$b=(e,t,n)=>{if(e!=="rows")return null;let o=x("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=x("span","persona-ask-row-check");o.appendChild(r)}else{let r=x("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},EP=(e,t,n,o)=>{let s=x("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let i=x("span","persona-ask-row-content"),l=x("span","persona-ask-row-label");if(l.textContent=e.label,i.appendChild(l),e.description){let p=x("span","persona-ask-row-description");p.textContent=e.description,i.appendChild(p)}s.appendChild(i);let c=$b(n,o,t);c&&s.appendChild(c)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},TP=e=>{let n=x("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 n.setAttribute("aria-hidden","true"),n},PP=(e,t,n,o)=>{let s=x("div",o==="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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let i=!!e?.multiSelect,c=(Array.isArray(e?.options)?e.options:[]).filter(d=>d&&typeof d.label=="string"&&d.label.length>0);if(c.length===0&&!n){for(let d=0;d<wP;d++)s.appendChild(TP(o));return s}if(c.forEach((d,g)=>{s.appendChild(EP(d,g,o,i))}),e?.allowFreeText!==!1){let d=o==="rows"?mP:hP;if(o==="rows"){let g=x("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");g.setAttribute("data-ask-user-action","focus-free-text"),g.setAttribute("data-option-index",String(c.length)),g.setAttribute("data-ask-other-row","true");let f=x("span","persona-ask-row-content"),h=document.createElement("input");h.type="text",h.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",h.placeholder=t.freeTextPlaceholder??Ob,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",t.freeTextLabel??d),f.appendChild(h),g.appendChild(f);let y=$b(o,i,c.length);y&&g.appendChild(y),s.appendChild(g)}else{let g=x("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");g.type="button",g.setAttribute("data-ask-user-action","open-free-text"),g.textContent=t.freeTextLabel??d,s.appendChild(g)}}return s},Ub=(e,t)=>{let o=x("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");o.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??Ob,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=x("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Bb,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},kP=e=>{let t=x("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=x("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Bb,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},LP=(e,t,n)=>{let o=x("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=x("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??bP,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=x("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=x("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??CP,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=x("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let c=e===t-1;return l.textContent=c?n.submitAllLabel??vP:n.nextLabel??yP,l.setAttribute("data-ask-user-action",c?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},ni=e=>{let t=e.getAttribute(_b);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Vb=(e,t)=>{e.setAttribute(_b,JSON.stringify(t))},yo=e=>{let t=Number(e.getAttribute(Eg)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},HP=(e,t)=>{e.setAttribute(Eg,String(Math.max(0,Math.floor(t))))},Ji=e=>{let t=Number(e.getAttribute(Tg)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},ls=e=>e.getAttribute(Pg)==="true",IP=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let l=n[i];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},RP=(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)))},sd=(e,t)=>{let{payload:n}=as(t),o=ul(n),r=ni(e),s={},i=new Set;return o.forEach((l,c)=>{let p=typeof l?.question=="string"?l.question:"";p&&(i.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),i.add(p),Object.prototype.hasOwnProperty.call(r,c)&&(s[p]=r[c]))}),s},jb=e=>{let t=ni(e),n=yo(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(c=>r.add(c));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(c=>{let p=c.getAttribute("data-option-label")??"",d=r.has(p);c.setAttribute("aria-pressed",d?"true":"false"),c.classList.toggle("persona-ask-pill-selected",d)});let i=new Set(Array.from(s).map(c=>c.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!i.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},qb=e=>{if(!ls(e))return;let t=ni(e),n=yo(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=l.length===0}},kg=(e,t,n)=>{let o=rd(n),r=AP(e),{payload:s,complete:i}=as(t),l=ls(e),c=yo(e),p=Ji(e),d=l?MP(s,c):xP(s),g=!!d?.multiSelect,f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=l?`${c+1}/${p}`:"");let h=e.querySelector('[data-ask-stepper="true"]');h&&h.remove();let y=e.querySelector('[data-ask-question="true"]');if(y){let L=typeof d?.question=="string"?d.question:"";y.textContent=L,y.classList.toggle("persona-ask-question-skeleton",!L&&!i)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let L=PP(d,o,i,r);v.replaceWith(L)}if(r!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Ub(o,r))}let C=e.querySelector('[data-ask-multi-actions="true"]');!l&&g&&!C?e.appendChild(kP(o)):(!g||l)&&C&&C.remove(),e.setAttribute("data-multi-select",g?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(l){let L=LP(c,p,o);A?A.replaceWith(L):e.appendChild(L)}else A&&A.remove();jb(e),qb(e)},WP=(e,t,n)=>{let o=rd(t),r=SP(o),s=e.toolCall.id,i=ul(n),l=Math.max(1,i.length),c=l>1,p=IP(e,i),d=c?RP(e,l):0,g=x("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(Qi,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(Tg,String(l)),g.setAttribute(Eg,String(d)),g.setAttribute(Pg,c?"true":"false"),g.setAttribute(Db,r),Vb(g,p),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Fb(g,o);let f=x("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=x("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",f.appendChild(h);let y=x("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",f.appendChild(y),g.appendChild(f);let C=x("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");return C.setAttribute("data-ask-pill-list","true"),C.setAttribute("role","group"),g.appendChild(C),r!=="rows"&&g.appendChild(Ub(o,r)),kg(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},OP=(e,t,n)=>{let{payload:o}=as(t),r=Math.max(1,ul(o).length);r>Ji(e)&&(e.setAttribute(Tg,String(r)),r>1&&!ls(e)&&e.setAttribute(Pg,"true")),kg(e,t,n)},BP=(e,t)=>{let n=x("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 o=rd(t);Fb(n,o);let r=x("span","persona-ask-stub-label"),{complete:s}=as(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Lg=(e,t,n)=>{if(!n||!is(e)||rd(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Qi}]`).forEach(p=>{p.getAttribute(Qi)!==r&&p.remove()});let i=n.querySelector(`[${Qi}="${Nb(r)}"]`);if(i){OP(i,e,t);return}let{payload:l}=as(e),c=WP(e,t,l);n.appendChild(c)},cs=(e,t)=>{if(!e)return;let n=t?`[${Qi}="${Nb(t)}"]`:`[${Qi}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Hg=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ds=(e,t)=>{let n=ni(e),o=yo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Vb(e,n),jb(e),qb(e)},id=(e,t,n,o)=>{let r=Ji(e),s=Math.max(0,Math.min(r-1,o));HP(e,s),kg(e,t,n)}});var Xo,Kb,Ig,Gb,Zi,Yb,Rg,zb,_P,ps,ea=$e(()=>{"use strict";Xo="suggest_replies",Kb={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},Ig={name:Xo,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:Kb,origin:"sdk",annotations:{readOnlyHint:!0}},Gb=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Zi=e=>e.variant==="tool"&&e.toolCall?.name===Xo,Yb=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 o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let i={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(i.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(i.description=s.description.trim()),[i]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Rg=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Zi(n))continue;let o=Yb(n.toolCall?.args);return o.length>0?o:null}return null},zb=new Set,_P=(e,t,n)=>{let o=`${e}:${t}:${n}`;zb.has(o)||(zb.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},ps=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=i=>{let l=t?.[i],c=n?.[i];l===void 0||c===void 0||l!==c&&_P(i,c,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}}});var Xb,Qb,ta,ad=$e(()=>{"use strict";gl();ea();Xb={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:pl,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},Qb={name:od,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:Xb,origin:"sdk",annotations:{readOnlyHint:!0}},ta=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Qb),ps(e).expose&&t.push(Ig),t}});var Kt,Tn,na,ld,Lo=$e(()=>{"use strict";Kt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Tn=1e5,na=Tn+1,ld="https://api.runtype.com"});async function Jb(e,t,n){let o={"Content-Type":"application/json",...e.headers};e.getHeaders&&Object.assign(o,await e.getHeaders());let r={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},s=(p,d)=>fetch(`${e.clientApiBase()}${p}`,{method:"POST",headers:o,body:JSON.stringify({...d,...r})}),i=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return s(i);let{sessionId:l}=await e.initSession(),c=await s("/v1/client/approve",{sessionId:l});if(c.status===404){let p=await c.clone().json().catch(()=>null);if(!p||p.error==="Not Found")return s(i)}return c}async function Zb(e,t,n,o){let r=e.isClientTokenMode(),s=r?e.getClientApiUrl("resume"):`${e.config.apiUrl?.replace(/\/+$/,"")||ld}/resume`,i,l=null;if(r){let d=await e.initSession();i=d.sessionId,d.durableRecovery?.enabled===!0&&(l=await e.readVisitorToken())}let c={"Content-Type":"application/json",...l?{"X-Visitor-Token":l}:{},...e.headers};e.getHeaders&&Object.assign(c,await e.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(i&&(p.sessionId=i),r&&i){let d=[...ta(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:g,commit:f}=await e.sendWithClientToolsDiff(i,d,h=>{let y={...p,...h};return e.debug&&console.debug("[AgentWidgetClient] client token resume",y),fetch(s,{method:"POST",headers:c,body:JSON.stringify(y),signal:o?.signal})},{emptyMeansReplace:!0});return g.ok&&f(),g}return fetch(s,{method:"POST",headers:c,body:JSON.stringify(p),signal:o?.signal})}var ev=$e(()=>{"use strict";ad();Lo()});var cd={};Qs(cd,{preferFinalStructuredContent:()=>nv,resolveApproval:()=>Jb,resumeFlow:()=>Zb,streamResponse:()=>FP});function DP(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}function nv(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=tv(n);if(!tv(o))return e;if(!r||o===n||o.startsWith(n))return t;let i=dl(e);return dl(t)!==null&&i===null?t:e}async function NP(e,t,n,o,r,s,i){if(!e.parseSSEEvent)return!1;try{let l=await e.parseSSEEvent(t);if(l===null)return!1;let c=d=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...d!==void 0&&{partId:d}};return o.current=g,r(g),g},p=d=>o.current?o.current:c(d);if(l.text!==void 0){l.partId!==void 0&&i.current!==null&&l.partId!==i.current&&(o.current&&(o.current.streaming=!1,r(o.current)),c(l.partId)),l.partId!==void 0&&(i.current=l.partId);let d=p(l.partId);l.partId!==void 0&&!d.partId&&(d.partId=l.partId),d.content+=l.text,r(d)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),i.current=null,n({type:"status",status:"idle"})),l.error&&(i.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async function FP(e,t,n,o,r){let s=t.getReader(),i=new TextDecoder,l="",c=Date.now(),p=0,d=()=>c+p++,g=D=>{let S=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,F=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,z=D.tools?D.tools.map(K=>({...K,chunks:K.chunks?[...K.chunks]:void 0})):void 0;return{...D,reasoning:S,toolCall:F,tools:z}},f=D=>{if(D.role!=="assistant"||D.variant)return!0;let S=Array.isArray(D.contentParts)&&D.contentParts.length>0,F=typeof D.rawContent=="string"&&D.rawContent.trim()!=="";return typeof D.content=="string"&&D.content.trim()!==""||S||F||!!D.stopReason},h=D=>{f(D)&&n({type:"message",message:g(D)})},y=null,v=null,C={current:null},A={current:null},L=null,I="",H=new Map,_=new Map,V=new Map,te=new Map,W=new Map,j=o,Y=!1,E=()=>{if(y)return y;let D,S="",F=L;return!Y&&j?(D=j,Y=!0,S=r??""):j&&F?D=`${j}_${F}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:D,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},h(y),y},T=D=>{let S=te.get(D);if(S)return S;let F={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:D,status:"streaming",chunks:[]}};return te.set(D,F),h(F),F},B=new Set,P=new Map,Q=new Set,U=new Map,de=D=>{if(!D)return!1;let S=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return S==="emit_artifact_markdown"||S==="emit_artifact_component"},pe=D=>{let S=W.get(D);if(S)return S;let F={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:D,status:"pending"}};return W.set(D,F),h(F),F},ge=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let S=Number(D);if(!Number.isNaN(S)&&Number.isFinite(S))return S;let F=Date.parse(D);if(!Number.isNaN(F))return F}return Date.now()},ke=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},xe=new Map,Le=new Map,mt=(D,S)=>{let F=ke(S),z=Le.get(D.id),K=nv(z,F);D.rawContent=K;let Z=xe.get(D.id),ye=Be=>{let Ge=D.content??"";Be.trim()!==""&&(Ge.trim().length===0||Be.startsWith(Ge)||Be.trimStart().startsWith(Ge.trim()))&&(D.content=Be)},be=()=>{if(Z){let Be=Z.close?.();Be instanceof Promise&&Be.catch(()=>{})}xe.delete(D.id),Le.delete(D.id),D.streaming=!1,h(D)};if(!Z){ye(F),be();return}let Ae=dl(K);if(Ae!==null&&Ae.trim()!==""){ye(Ae),be();return}let tt=Be=>{let Ge=typeof Be=="string"?Be:Be?.text??null;if(Ge!==null&&Ge.trim()!=="")return Ge;let cn=Z.getExtractedText();return cn!==null&&cn.trim()!==""?cn:F},bt;try{bt=Z.processChunk(K)}catch{ye(F),be();return}if(bt instanceof Promise){bt.then(Be=>{ye(tt(Be)),be()}).catch(()=>{ye(F),be()});return}ye(tt(bt)),be()},Ve=null,Re=(D,S,F,z)=>{D.rawContent=S,xe.has(D.id)||xe.set(D.id,e.createStreamParser());let K=xe.get(D.id),Z=S.trim().startsWith("{")||S.trim().startsWith("[");if(Z&&Le.set(D.id,S),K.__isPlainTextParser===!0){D.content=z!==void 0?S:D.content+F,Le.delete(D.id),xe.delete(D.id),D.rawContent=void 0,h(D);return}let be=K.processChunk(S);if(be instanceof Promise)be.then(Ae=>{let tt=typeof Ae=="string"?Ae:Ae?.text??null;tt!==null&&tt.trim()!==""?(D.content=tt,h(D)):!Z&&!S.trim().startsWith("<")&&(D.content=z!==void 0?S:D.content+F,Le.delete(D.id),xe.delete(D.id),D.rawContent=void 0,h(D))}).catch(()=>{D.content=z!==void 0?S:D.content+F,Le.delete(D.id),xe.delete(D.id),D.rawContent=void 0,h(D)});else{let Ae=typeof be=="string"?be:be?.text??null;Ae!==null&&Ae.trim()!==""?(D.content=Ae,h(D)):!Z&&!S.trim().startsWith("<")&&(D.content=z!==void 0?S:D.content+F,Le.delete(D.id),xe.delete(D.id),D.rawContent=void 0,h(D))}},$=(D,S)=>{let F=S??D.content;if(F==null||F===""){D.streaming=!1,h(D);return}let K=Le.get(D.id)??ke(F);D.rawContent=K;let Z=xe.get(D.id),ye=null,be=!1;if(Z&&(ye=Z.getExtractedText(),ye===null&&(ye=dl(K)),ye===null)){let Ae=Z.processChunk(K);Ae instanceof Promise?(be=!0,Ae.then(tt=>{let bt=typeof tt=="string"?tt:tt?.text??null;bt!==null&&(D.content=bt,D.streaming=!1,xe.delete(D.id),Le.delete(D.id),h(D))}).catch(()=>{})):ye=typeof Ae=="string"?Ae:Ae?.text??null}if(!be){ye!==null&&ye.trim()!==""?D.content=ye:Le.has(D.id)||(D.content=ke(F));let Ae=xe.get(D.id);if(Ae){let tt=Ae.close?.();tt instanceof Promise&&tt.catch(()=>{}),xe.delete(D.id)}Le.delete(D.id),D.streaming=!1,h(D)}},We=(D,S,F)=>{let z=_.get(D);if(z)return z;let K={id:`nested-${S}-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...F?{variant:F}:{},...F==="reasoning"?{reasoning:{id:D,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:S}};return _.set(D,K),h(K),K},me=[],dt,Qt=new Map,St=0,Se="agent",It=!1,yt=null,Pe=null,Ke=e.config().iterationDisplay??"separate";for(dt=()=>{for(let D=0;D<me.length;D++){let S=me[D];if(!It&&Se!=="flow"&&typeof S.stepType=="string"&&(Se="flow"),S.type==="reasoning_start"){let F=typeof S.id=="string"?S.id:null,z=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(F&&z){H.set(F,z),We(F,z,"reasoning");continue}let K=S.id,Z=T(K);Z.reasoning=Z.reasoning??{id:K,status:"streaming",chunks:[]},Z.reasoning.startedAt=Z.reasoning.startedAt??Date.now(),Z.reasoning.completedAt=void 0,Z.reasoning.durationMs=void 0,(S.scope==="loop"||S.scope==="turn")&&(Z.reasoning.scope=S.scope),Z.streaming=!0,Z.reasoning.status="streaming",h(Z)}else if(S.type==="reasoning_delta"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)&&_.has(F)){let Z=_.get(F),ye=S.delta;ye&&Z.reasoning&&(Z.reasoning.chunks.push(String(ye)),h(Z));continue}let z=S.id,K=T(z);K.reasoning=K.reasoning??{id:z,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Date.now(),S.delta&&K.reasoning.chunks.push(S.delta),K.reasoning.status="streaming",K.streaming=!0,h(K)}else if(S.type==="reasoning_complete"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)&&_.has(F)){let ye=_.get(F);if(ye.reasoning){let be=typeof S.text=="string"?S.text:"";be&&ye.reasoning.chunks.length===0&&ye.reasoning.chunks.push(be),ye.reasoning.status="complete",ye.streaming=!1,h(ye)}H.delete(F),_.delete(F);continue}let z=S.id,K=typeof S.text=="string"?S.text:"";!te.get(z)&&(K||S.scope==="loop")&&T(z);let Z=te.get(z);if(Z?.reasoning){(S.scope==="loop"||S.scope==="turn")&&(Z.reasoning.scope=S.scope),K&&Z.reasoning.chunks.length===0&&Z.reasoning.chunks.push(K),Z.reasoning.status="complete",Z.reasoning.completedAt=Date.now();let ye=Z.reasoning.startedAt??Date.now();Z.reasoning.durationMs=Math.max(0,(Z.reasoning.completedAt??Date.now())-ye),Z.streaming=!1,h(Z)}}else if(S.type==="tool_start"){y&&(y.streaming=!1,h(y),y=null),typeof S.iteration=="number"&&(St=S.iteration);let F=S.toolCallId,z=S.toolName;if(de(z)){B.add(F);continue}let K=pe(F),Z=K.toolCall??{id:F,status:"pending"};Z.name=z??Z.name,Z.status="running",Z.success=void 0,Z.error=void 0,Z.duration=void 0,S.parameters!==void 0&&(Z.args=S.parameters),Z.startedAt=Z.startedAt??ge(S.startedAt),Z.completedAt=void 0,Z.durationMs=void 0,K.toolCall=Z,K.streaming=!0,S.executionId&&(K.agentMetadata={executionId:S.executionId,iteration:S.iteration}),h(K)}else if(S.type==="tool_output_delta"){let F=S.toolCallId;if(B.has(F))continue;let z=pe(F),K=z.toolCall??{id:F,status:"running"};K.startedAt=K.startedAt??Date.now();let Z=S.delta;Z&&(K.chunks=K.chunks??[],K.chunks.push(String(Z))),K.status="running",z.toolCall=K,z.streaming=!0,S.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:S.executionId,iteration:St}),h(z)}else if(S.type==="tool_complete"){let F=S.toolCallId;if(B.has(F)){B.delete(F);continue}let z=pe(F),K=z.toolCall??{id:F,status:"running"};K.status="complete",S.result!==void 0&&(K.result=S.result),K.name=S.toolName??K.name,K.success=S.success,K.error=S.error,K.completedAt=Date.now();let Z=S.executionTime;if(typeof Z=="number")K.durationMs=Z,K.duration=Z;else{let ye=K.startedAt??Date.now();K.durationMs=Math.max(0,(K.completedAt??Date.now())-ye)}z.toolCall=K,z.streaming=!1,S.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:S.executionId,iteration:S.iteration??St}),h(z)}else if(S.type==="await"&&S.toolName){let F=typeof S.toolCallId=="string"&&S.toolCallId.length>0?S.toolCallId:void 0,z=F??S.toolId??`local-${d()}`,K=pe(z),Z=S.toolName,ye=S.origin==="webmcp"&&!Zs(Z)?`webmcp:${Z}`:Z,be=Zs(ye),Ae=K.toolCall??{id:z,status:"pending"};Ae.name=ye,Ae.args=S.parameters,Ae.status=be?"running":"complete",Ae.chunks=Ae.chunks??[],Ae.startedAt=Ae.startedAt??ge(S.awaitedAt),be?(Ae.completedAt=void 0,Ae.duration=void 0,Ae.durationMs=void 0):Ae.completedAt=Ae.completedAt??Ae.startedAt,K.toolCall=Ae,K.streaming=!1,K.agentMetadata={...K.agentMetadata,executionId:S.executionId??K.agentMetadata?.executionId,awaitingLocalTool:!0,...F?{webMcpToolCallId:F}:{}},h(K)}else if(S.type==="text_start"){let F=typeof S.id=="string"?S.id:null,z=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(F&&z){H.set(F,z);continue}let K=y;K&&(Se==="flow"?($(K),Ve=K):(K.streaming=!1,h(K)),y=null),L=typeof S.id=="string"?S.id:L,I=""}else if(S.type==="text_delta"){let F=typeof S.id=="string"?S.id:null,z=F?H.get(F):void 0;if(F&&z){let ye=typeof S.delta=="string"?S.delta:"",be=(V.get(F)??"")+ye;if(V.set(F,be),be.trim()==="")continue;let Ae=We(F,z);Ae.agentMetadata={...Ae.agentMetadata,executionId:S.executionId,parentToolId:z},Re(Ae,be,ye,void 0);continue}if(L=typeof S.id=="string"?S.id:L,Se==="flow"){let ye=typeof S.delta=="string"?S.delta:"";if(I+=ye,I.trim()==="")continue;let be=E();be.agentMetadata={executionId:S.executionId,iteration:St},Re(be,I,ye,void 0),v=be;continue}let K=typeof S.delta=="string"?S.delta:"";I+=K;let Z=E();Z.agentMetadata={executionId:S.executionId,iteration:St,turnId:yt??void 0,agentName:Pe?.agentName},Re(Z,I,K,void 0),v=Z}else if(S.type==="text_complete"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)){let K=_.get(F);K&&$(K),H.delete(F),V.delete(F),_.delete(F);continue}let z=y;z&&(Se==="flow"?($(z),Ve=z):((z.content??"")===""&&typeof S.text=="string"&&(z.content=S.text),z.streaming=!1,h(z)),y=null),L=null,I=""}else if(S.type==="step_complete"){if(S.stepType==="tool")continue;if(S.success===!1){let F=S.error||"Step failed";n({type:"error",error:new Error(F)});let z=y;z&&z.streaming&&(z.streaming=!1,h(z)),n({type:"status",status:"idle"});continue}{let F=Ve;Ve=null;let z=S.stopReason,Z=(S.result&&typeof S.result=="object"?S.result:null)?.response;if(F)z&&(F.stopReason=z),Z!=null?mt(F,Z):F.streaming!==!1&&(xe.delete(F.id),Le.delete(F.id),F.streaming=!1,h(F));else{let ye=Z!=null&&Z!=="";if(ye||z){let be=E();z&&(be.stopReason=z),ye?$(be,Z):(be.streaming=!1,h(be))}}continue}}else if(S.type==="execution_start")Se=S.kind==="flow"?"flow":"agent",It=!0,Se==="agent"&&(Pe={executionId:S.executionId,agentId:S.agentId??"virtual",agentName:S.agentName??""});else if(S.type==="turn_start"){let F=typeof S.iteration=="number"?S.iteration:St;if(F!==St){if(Ke==="separate"&&F>1){let z=y;z&&(z.streaming=!1,h(z),y=null)}St=F}yt=typeof S.id=="string"?S.id:null,v=null}else if(S.type==="tool_input_delta"){let F=S.toolCallId;if(F){let z=W.get(F);z?.toolCall&&(z.toolCall.chunks=z.toolCall.chunks??[],z.toolCall.chunks.push(S.delta??""),h(z))}}else if(S.type==="tool_input_complete"){if(B.has(S.toolCallId))continue;let F=pe(S.toolCallId),z=F.toolCall;z.args=S.parameters,z.name=S.toolName??z.name,h(F)}else if(S.type==="turn_complete"){let F=S.stopReason,z=y??v;if(F&&z!==null){let K=S.id;(!K||z.agentMetadata?.turnId===K)&&(z.stopReason=F,h(z))}yt===S.id&&(yt=null)}else if(S.type==="media_start"){let F=String(S.id);Qt.set(F,{mediaType:typeof S.mediaType=="string"?S.mediaType:void 0,toolCallId:S.toolCallId,parts:[]})}else if(S.type==="media_delta"){let F=Qt.get(String(S.id));F&&typeof S.delta=="string"&&F.parts.push(S.delta)}else if(S.type==="media_complete"){let F=String(S.id),z=Qt.get(F);Qt.delete(F);let K=(typeof S.mediaType=="string"?S.mediaType:void 0)??z?.mediaType??"application/octet-stream",Z=typeof S.data=="string"?S.data:void 0,ye=typeof S.url=="string"?S.url:z&&z.parts.length>0?z.parts.join(""):void 0,be=null;if(Z)be={type:"media",data:Z,mediaType:K};else if(ye){let Be=K.toLowerCase();be={type:Be==="image"||Be.startsWith("image/")?"image-url":"file-url",url:ye,mediaType:K}}let Ae=S.toolCallId??z?.toolCallId,tt=be?[be]:[],bt=[];for(let Be of tt){if(!Be||typeof Be!="object")continue;let Ge=Be,cn=typeof Ge.type=="string"?Ge.type:void 0,vo=typeof Ge.mediaType=="string"?Ge.mediaType.toLowerCase():"",ut=null,ht="";if(cn==="media"){let Dt=typeof Ge.data=="string"?Ge.data:void 0;if(!Dt)continue;ht=vo.length>0?vo:"application/octet-stream",ut=`data:${ht};base64,${Dt}`}else if(cn==="image-url"){let Dt=typeof Ge.url=="string"?Ge.url:void 0;if(!Dt)continue;ht=vo,ut=Dt}else if(cn==="file-url"){let Dt=typeof Ge.url=="string"?Ge.url:void 0;if(!Dt)continue;ht=vo,ut=Dt}else continue;if(ut)if(cn==="image-url"||ht.startsWith("image/"))bt.push({type:"image",image:ut,...ht.includes("/")?{mimeType:ht}:{}});else if(ht.startsWith("audio/"))bt.push({type:"audio",audio:ut,mimeType:ht});else if(ht.startsWith("video/"))bt.push({type:"video",video:ut,mimeType:ht});else{let Dt=ht||"application/octet-stream";bt.push({type:"file",data:ut,mimeType:Dt,filename:DP(Dt)})}}if(bt.length>0){let Be=d(),Ge=Ae,vo={id:`agent-media-${typeof Ge=="string"&&Ge.length>0?`${Ge}-${Be}`:String(Be)}`,role:"assistant",content:"",contentParts:bt,createdAt:new Date().toISOString(),streaming:!1,sequence:Be,agentMetadata:{executionId:S.executionId,iteration:St}};h(vo);let ut=y;ut&&(ut.streaming=!1,h(ut)),y=null,C.current=null}}else if(S.type==="execution_complete"){let F=y;F&&(S.kind==="flow"&&F.streaming!==!1?$(F):(F.streaming=!1,h(F)),y=null),L=null,I="",Ve=null,n({type:"status",status:"idle",terminal:!0})}else if(S.type==="execution_error"){let F=typeof S.error=="string"?S.error:S.error?.message??"Execution error";n({type:"error",error:new Error(F)})}else if(S.type!=="ping"){if(S.type==="approval_start"){let F=S.approvalId??`approval-${d()}`,z={id:`approval-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:F,status:"pending",agentId:Pe?.agentId??"virtual",executionId:S.executionId??Pe?.executionId??"",toolName:S.toolName??"",toolType:S.toolType,description:S.description??`Execute ${S.toolName??"tool"}`,...typeof S.reason=="string"&&S.reason?{reason:S.reason}:{},parameters:S.parameters,...typeof S.toolCallId=="string"&&S.toolCallId?{toolCallId:S.toolCallId}:{}}};h(z)}else if(S.type==="approval_complete"){let F=S.approvalId;if(F){let K={id:`approval-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:F,status:S.decision??"approved",agentId:Pe?.agentId??"virtual",executionId:S.executionId??Pe?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};h(K)}}else if(S.type==="artifact_start"||S.type==="artifact_delta"||S.type==="artifact_update"||S.type==="artifact_complete"){if(S.type==="artifact_start"){let F=S.artifactType,z=String(S.id),K=typeof S.title=="string"?S.title:void 0,Z=S.file,ye;if(Z&&typeof Z=="object"&&!Array.isArray(Z)&&typeof Z.path=="string"&&typeof Z.mimeType=="string"&&(ye={path:Z.path,mimeType:Z.mimeType,...typeof Z.language=="string"?{language:Z.language}:{}}),n({type:"artifact_start",id:z,artifactType:F,title:K,component:typeof S.component=="string"?S.component:void 0,...ye?{file:ye}:{}}),U.set(z,{markdown:"",title:K,file:ye}),!Q.has(z)){Q.add(z);let be=Er(e.config().features?.artifacts,{artifactType:F,...ye?{file:ye}:{}}),Ae=typeof S.component=="string"?S.component:void 0,tt={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:al(be,{artifactId:z,title:K,artifactType:F,status:"streaming",...ye?{file:ye}:{},...Ae?{component:Ae}:{}})};P.set(z,tt),h(tt)}}else if(S.type==="artifact_delta"){let F=String(S.id),z=typeof S.delta=="string"?S.delta:String(S.delta??"");n({type:"artifact_delta",id:F,artDelta:z});let K=U.get(F);K&&(K.markdown+=z)}else if(S.type==="artifact_update"){let F=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?S.props:{};n({type:"artifact_update",id:String(S.id),props:F,component:typeof S.component=="string"?S.component:void 0});let z=U.get(String(S.id));z&&(z.props={...z.props??{},...F})}else if(S.type==="artifact_complete"){let F=String(S.id);n({type:"artifact_complete",id:F});let z=P.get(F);if(z){z.streaming=!1;try{let K=JSON.parse(z.rawContent??"{}");if(K.props){K.props.status="complete";let Z=U.get(F);Z?.markdown&&(K.props.markdown=Z.markdown),Z?.file&&(K.props.file=Z.file),K.component==="PersonaArtifactInline"&&Z?.props&&Object.keys(Z.props).length>0&&(K.props.componentProps=Z.props)}z.rawContent=JSON.stringify(K)}catch{}U.delete(F),h(z),P.delete(F)}}}else if(S.type==="error"&&S.recoverable===!1&&S.error!=null&&S.error!==""){let F=typeof S.error=="string"?S.error:S.error?.message!=null?String(S.error.message):"Execution error";n({type:"error",error:new Error(F)});let z=y;z&&z.streaming&&(z.streaming=!1,h(z)),n({type:"status",status:"idle"})}}}me.length=0};;){let{done:D,value:S}=await s.read();if(D)break;l+=i.decode(S,{stream:!0});let F=l.split(`
4
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},dl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Eg=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Mg=()=>{let e=fk();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)}},Tg=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=Ib(n,Rb|Wb);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?td(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=td(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},mk=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?td(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?td(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let l=Ib(s,Rb|Wb),c=r(l);c!==null&&(t=c)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},kg=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}}});var x,X,On,Qe=$e(()=>{"use strict";x=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},X=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,i]of Object.entries(t.attrs))o.setAttribute(s,i);if(t.style){let s=o.style,i=t.style;for(let l of Object.keys(i)){let c=i[l];c!=null&&(s[l]=c)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},On=(...e)=>e.filter(Boolean).join(" ")});import{parse as hk,ARR as yk,OBJ as bk,STR as vk}from"partial-json";var sd,pl,Qi,Ck,wk,Nb,Fb,Sk,Ak,xk,Ek,Mk,Pg,Lg,$b,Hg,Ub,Tk,kk,Db,Vb,is,id,as,ul,Pk,Lk,jb,qb,Hk,Ik,Rk,zb,Wk,Ok,ni,Kb,bo,_k,Ji,ls,Bk,Dk,ad,Gb,Yb,Ig,Nk,Fk,$k,Rg,cs,Wg,ds,ld,gl=$e(()=>{"use strict";Qe();sd="ask_user_question",pl=8,Qi="data-persona-ask-sheet-for",Ck="Other",wk="Other\u2026",Nb="Type your own answer here",Fb="Send",Sk="Next",Ak="Back",xk="Submit all",Ek="Skip",Mk=3,Pg="data-ask-current-index",Lg="data-ask-question-count",$b="data-ask-answers",Hg="data-ask-grouped",Ub="data-ask-layout",Tk=e=>e.layout==="pills"?"pills":"rows",kk=e=>e.getAttribute(Ub)==="pills"?"pills":"rows",Db=!1,Vb=e=>e.replace(/["\\]/g,"\\$&"),is=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===sd,id=e=>e?.features?.askUserQuestion??{},as=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 o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=hk(r,vk|bk|yk);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ul=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>pl&&!Db&&(Db=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${pl}.`)),t.slice(0,pl)},Pk=e=>ul(e)[0]??null,Lk=(e,t)=>ul(e)[t]??null,jb=(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))},qb=(e,t,n)=>{if(e!=="rows")return null;let o=x("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=x("span","persona-ask-row-check");o.appendChild(r)}else{let r=x("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Hk=(e,t,n,o)=>{let s=x("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let i=x("span","persona-ask-row-content"),l=x("span","persona-ask-row-label");if(l.textContent=e.label,i.appendChild(l),e.description){let p=x("span","persona-ask-row-description");p.textContent=e.description,i.appendChild(p)}s.appendChild(i);let c=qb(n,o,t);c&&s.appendChild(c)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Ik=e=>{let n=x("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 n.setAttribute("aria-hidden","true"),n},Rk=(e,t,n,o)=>{let s=x("div",o==="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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let i=!!e?.multiSelect,c=(Array.isArray(e?.options)?e.options:[]).filter(d=>d&&typeof d.label=="string"&&d.label.length>0);if(c.length===0&&!n){for(let d=0;d<Mk;d++)s.appendChild(Ik(o));return s}if(c.forEach((d,g)=>{s.appendChild(Hk(d,g,o,i))}),e?.allowFreeText!==!1){let d=o==="rows"?Ck:wk;if(o==="rows"){let g=x("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");g.setAttribute("data-ask-user-action","focus-free-text"),g.setAttribute("data-option-index",String(c.length)),g.setAttribute("data-ask-other-row","true");let f=x("span","persona-ask-row-content"),h=document.createElement("input");h.type="text",h.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",h.placeholder=t.freeTextPlaceholder??Nb,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",t.freeTextLabel??d),f.appendChild(h),g.appendChild(f);let y=qb(o,i,c.length);y&&g.appendChild(y),s.appendChild(g)}else{let g=x("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");g.type="button",g.setAttribute("data-ask-user-action","open-free-text"),g.textContent=t.freeTextLabel??d,s.appendChild(g)}}return s},zb=(e,t)=>{let o=x("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");o.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??Nb,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=x("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Fb,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Wk=e=>{let t=x("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=x("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Fb,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Ok=(e,t,n)=>{let o=x("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=x("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Ak,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=x("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=x("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??Ek,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=x("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let c=e===t-1;return l.textContent=c?n.submitAllLabel??xk:n.nextLabel??Sk,l.setAttribute("data-ask-user-action",c?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},ni=e=>{let t=e.getAttribute($b);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Kb=(e,t)=>{e.setAttribute($b,JSON.stringify(t))},bo=e=>{let t=Number(e.getAttribute(Pg)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},_k=(e,t)=>{e.setAttribute(Pg,String(Math.max(0,Math.floor(t))))},Ji=e=>{let t=Number(e.getAttribute(Lg)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},ls=e=>e.getAttribute(Hg)==="true",Bk=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let l=n[i];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},Dk=(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)))},ad=(e,t)=>{let{payload:n}=as(t),o=ul(n),r=ni(e),s={},i=new Set;return o.forEach((l,c)=>{let p=typeof l?.question=="string"?l.question:"";p&&(i.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),i.add(p),Object.prototype.hasOwnProperty.call(r,c)&&(s[p]=r[c]))}),s},Gb=e=>{let t=ni(e),n=bo(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(c=>r.add(c));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(c=>{let p=c.getAttribute("data-option-label")??"",d=r.has(p);c.setAttribute("aria-pressed",d?"true":"false"),c.classList.toggle("persona-ask-pill-selected",d)});let i=new Set(Array.from(s).map(c=>c.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!i.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},Yb=e=>{if(!ls(e))return;let t=ni(e),n=bo(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=l.length===0}},Ig=(e,t,n)=>{let o=id(n),r=kk(e),{payload:s,complete:i}=as(t),l=ls(e),c=bo(e),p=Ji(e),d=l?Lk(s,c):Pk(s),g=!!d?.multiSelect,f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=l?`${c+1}/${p}`:"");let h=e.querySelector('[data-ask-stepper="true"]');h&&h.remove();let y=e.querySelector('[data-ask-question="true"]');if(y){let L=typeof d?.question=="string"?d.question:"";y.textContent=L,y.classList.toggle("persona-ask-question-skeleton",!L&&!i)}let b=e.querySelector('[data-ask-pill-list="true"]');if(b){let L=Rk(d,o,i,r);b.replaceWith(L)}if(r!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(zb(o,r))}let C=e.querySelector('[data-ask-multi-actions="true"]');!l&&g&&!C?e.appendChild(Wk(o)):(!g||l)&&C&&C.remove(),e.setAttribute("data-multi-select",g?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(l){let L=Ok(c,p,o);A?A.replaceWith(L):e.appendChild(L)}else A&&A.remove();Gb(e),Yb(e)},Nk=(e,t,n)=>{let o=id(t),r=Tk(o),s=e.toolCall.id,i=ul(n),l=Math.max(1,i.length),c=l>1,p=Bk(e,i),d=c?Dk(e,l):0,g=x("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(Qi,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(Lg,String(l)),g.setAttribute(Pg,String(d)),g.setAttribute(Hg,c?"true":"false"),g.setAttribute(Ub,r),Kb(g,p),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),jb(g,o);let f=x("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=x("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",f.appendChild(h);let y=x("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",f.appendChild(y),g.appendChild(f);let C=x("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");return C.setAttribute("data-ask-pill-list","true"),C.setAttribute("role","group"),g.appendChild(C),r!=="rows"&&g.appendChild(zb(o,r)),Ig(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Fk=(e,t,n)=>{let{payload:o}=as(t),r=Math.max(1,ul(o).length);r>Ji(e)&&(e.setAttribute(Lg,String(r)),r>1&&!ls(e)&&e.setAttribute(Hg,"true")),Ig(e,t,n)},$k=(e,t)=>{let n=x("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 o=id(t);jb(n,o);let r=x("span","persona-ask-stub-label"),{complete:s}=as(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Rg=(e,t,n)=>{if(!n||!is(e)||id(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Qi}]`).forEach(p=>{p.getAttribute(Qi)!==r&&p.remove()});let i=n.querySelector(`[${Qi}="${Vb(r)}"]`);if(i){Fk(i,e,t);return}let{payload:l}=as(e),c=Nk(e,t,l);n.appendChild(c)},cs=(e,t)=>{if(!e)return;let n=t?`[${Qi}="${Vb(t)}"]`:`[${Qi}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Wg=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ds=(e,t)=>{let n=ni(e),o=bo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Kb(e,n),Gb(e),Yb(e)},ld=(e,t,n,o)=>{let r=Ji(e),s=Math.max(0,Math.min(r-1,o));_k(e,s),Ig(e,t,n)}});var Xo,Qb,Og,Jb,Zi,Zb,_g,Xb,Uk,ps,ea=$e(()=>{"use strict";Xo="suggest_replies",Qb={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},Og={name:Xo,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:Qb,origin:"sdk",annotations:{readOnlyHint:!0}},Jb=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Zi=e=>e.variant==="tool"&&e.toolCall?.name===Xo,Zb=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 o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let i={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(i.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(i.description=s.description.trim()),[i]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},_g=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Zi(n))continue;let o=Zb(n.toolCall?.args);return o.length>0?o:null}return null},Xb=new Set,Uk=(e,t,n)=>{let o=`${e}:${t}:${n}`;Xb.has(o)||(Xb.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},ps=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=i=>{let l=t?.[i],c=n?.[i];l===void 0||c===void 0||l!==c&&Uk(i,c,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}}});var ev,tv,ta,cd=$e(()=>{"use strict";gl();ea();ev={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:pl,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},tv={name:sd,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:ev,origin:"sdk",annotations:{readOnlyHint:!0}},ta=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(tv),ps(e).expose&&t.push(Og),t}});var Kt,Tn,na,dd,Lo=$e(()=>{"use strict";Kt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Tn=1e5,na=Tn+1,dd="https://api.runtype.com"});async function nv(e,t,n){let o={"Content-Type":"application/json",...e.headers};e.getHeaders&&Object.assign(o,await e.getHeaders());let r={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},s=(p,d)=>fetch(`${e.clientApiBase()}${p}`,{method:"POST",headers:o,body:JSON.stringify({...d,...r})}),i=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return s(i);let{sessionId:l}=await e.initSession(),c=await s("/v1/client/approve",{sessionId:l});if(c.status===404){let p=await c.clone().json().catch(()=>null);if(!p||p.error==="Not Found")return s(i)}return c}async function ov(e,t,n,o){let r=e.isClientTokenMode(),s=r?e.getClientApiUrl("resume"):`${e.config.apiUrl?.replace(/\/+$/,"")||dd}/resume`,i,l=null;if(r){let d=await e.initSession();i=d.sessionId,d.durableRecovery?.enabled===!0&&(l=await e.readVisitorToken())}let c={"Content-Type":"application/json",...l?{"X-Visitor-Token":l}:{},...e.headers};e.getHeaders&&Object.assign(c,await e.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(i&&(p.sessionId=i),r&&i){let d=[...ta(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:g,commit:f}=await e.sendWithClientToolsDiff(i,d,h=>{let y={...p,...h};return e.debug&&console.debug("[AgentWidgetClient] client token resume",y),fetch(s,{method:"POST",headers:c,body:JSON.stringify(y),signal:o?.signal})},{emptyMeansReplace:!0});return g.ok&&f(),g}return fetch(s,{method:"POST",headers:c,body:JSON.stringify(p),signal:o?.signal})}var rv=$e(()=>{"use strict";cd();Lo()});var pd={};Qs(pd,{preferFinalStructuredContent:()=>iv,resolveApproval:()=>nv,resumeFlow:()=>ov,streamResponse:()=>qk});function Vk(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}function iv(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=sv(n);if(!sv(o))return e;if(!r||o===n||o.startsWith(n))return t;let i=dl(e);return dl(t)!==null&&i===null?t:e}async function jk(e,t,n,o,r,s,i){if(!e.parseSSEEvent)return!1;try{let l=await e.parseSSEEvent(t);if(l===null)return!1;let c=d=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...d!==void 0&&{partId:d}};return o.current=g,r(g),g},p=d=>o.current?o.current:c(d);if(l.text!==void 0){l.partId!==void 0&&i.current!==null&&l.partId!==i.current&&(o.current&&(o.current.streaming=!1,r(o.current)),c(l.partId)),l.partId!==void 0&&(i.current=l.partId);let d=p(l.partId);l.partId!==void 0&&!d.partId&&(d.partId=l.partId),d.content+=l.text,r(d)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),i.current=null,n({type:"status",status:"idle"})),l.error&&(i.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async function qk(e,t,n,o,r){let s=t.getReader(),i=new TextDecoder,l="",c=Date.now(),p=0,d=()=>c+p++,g=D=>{let S=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,F=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,q=D.tools?D.tools.map(K=>({...K,chunks:K.chunks?[...K.chunks]:void 0})):void 0;return{...D,reasoning:S,toolCall:F,tools:q}},f=D=>{if(D.role!=="assistant"||D.variant)return!0;let S=Array.isArray(D.contentParts)&&D.contentParts.length>0,F=typeof D.rawContent=="string"&&D.rawContent.trim()!=="";return typeof D.content=="string"&&D.content.trim()!==""||S||F||!!D.stopReason},h=D=>{f(D)&&n({type:"message",message:g(D)})},y=null,b=null,C={current:null},A={current:null},L=null,I="",H=new Map,B=new Map,V=new Map,te=new Map,W=new Map,j=o,Y=!1,M=()=>{if(y)return y;let D,S="",F=L;return!Y&&j?(D=j,Y=!0,S=r??""):j&&F?D=`${j}_${F}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:D,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},h(y),y},T=D=>{let S=te.get(D);if(S)return S;let F={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:D,status:"streaming",chunks:[]}};return te.set(D,F),h(F),F},_=new Set,k=new Map,Q=new Set,U=new Map,de=D=>{if(!D)return!1;let S=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return S==="emit_artifact_markdown"||S==="emit_artifact_component"},pe=D=>{let S=W.get(D);if(S)return S;let F={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:D,status:"pending"}};return W.set(D,F),h(F),F},ge=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let S=Number(D);if(!Number.isNaN(S)&&Number.isFinite(S))return S;let F=Date.parse(D);if(!Number.isNaN(F))return F}return Date.now()},Pe=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},Ae=new Map,Le=new Map,mt=(D,S)=>{let F=Pe(S),q=Le.get(D.id),K=iv(q,F);D.rawContent=K;let Z=Ae.get(D.id),ye=_e=>{let Ye=D.content??"";_e.trim()!==""&&(Ye.trim().length===0||_e.startsWith(Ye)||_e.trimStart().startsWith(Ye.trim()))&&(D.content=_e)},xe=()=>{if(Z){let _e=Z.close?.();_e instanceof Promise&&_e.catch(()=>{})}Ae.delete(D.id),Le.delete(D.id),D.streaming=!1,h(D)};if(!Z){ye(F),xe();return}let be=dl(K);if(be!==null&&be.trim()!==""){ye(be),xe();return}let ot=_e=>{let Ye=typeof _e=="string"?_e:_e?.text??null;if(Ye!==null&&Ye.trim()!=="")return Ye;let cn=Z.getExtractedText();return cn!==null&&cn.trim()!==""?cn:F},bt;try{bt=Z.processChunk(K)}catch{ye(F),xe();return}if(bt instanceof Promise){bt.then(_e=>{ye(ot(_e)),xe()}).catch(()=>{ye(F),xe()});return}ye(ot(bt)),xe()},Ve=null,Re=(D,S,F,q)=>{D.rawContent=S,Ae.has(D.id)||Ae.set(D.id,e.createStreamParser());let K=Ae.get(D.id),Z=S.trim().startsWith("{")||S.trim().startsWith("[");if(Z&&Le.set(D.id,S),K.__isPlainTextParser===!0){D.content=q!==void 0?S:D.content+F,Le.delete(D.id),Ae.delete(D.id),D.rawContent=void 0,h(D);return}let xe=K.processChunk(S);if(xe instanceof Promise)xe.then(be=>{let ot=typeof be=="string"?be:be?.text??null;ot!==null&&ot.trim()!==""?(D.content=ot,h(D)):!Z&&!S.trim().startsWith("<")&&(D.content=q!==void 0?S:D.content+F,Le.delete(D.id),Ae.delete(D.id),D.rawContent=void 0,h(D))}).catch(()=>{D.content=q!==void 0?S:D.content+F,Le.delete(D.id),Ae.delete(D.id),D.rawContent=void 0,h(D)});else{let be=typeof xe=="string"?xe:xe?.text??null;be!==null&&be.trim()!==""?(D.content=be,h(D)):!Z&&!S.trim().startsWith("<")&&(D.content=q!==void 0?S:D.content+F,Le.delete(D.id),Ae.delete(D.id),D.rawContent=void 0,h(D))}},$=(D,S)=>{let F=S??D.content;if(F==null||F===""){D.streaming=!1,h(D);return}let K=Le.get(D.id)??Pe(F);D.rawContent=K;let Z=Ae.get(D.id),ye=null,xe=!1;if(Z&&(ye=Z.getExtractedText(),ye===null&&(ye=dl(K)),ye===null)){let be=Z.processChunk(K);be instanceof Promise?(xe=!0,be.then(ot=>{let bt=typeof ot=="string"?ot:ot?.text??null;bt!==null&&(D.content=bt,D.streaming=!1,Ae.delete(D.id),Le.delete(D.id),h(D))}).catch(()=>{})):ye=typeof be=="string"?be:be?.text??null}if(!xe){ye!==null&&ye.trim()!==""?D.content=ye:Le.has(D.id)||(D.content=Pe(F));let be=Ae.get(D.id);if(be){let ot=be.close?.();ot instanceof Promise&&ot.catch(()=>{}),Ae.delete(D.id)}Le.delete(D.id),D.streaming=!1,h(D)}},We=(D,S,F)=>{let q=B.get(D);if(q)return q;let K={id:`nested-${S}-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...F?{variant:F}:{},...F==="reasoning"?{reasoning:{id:D,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:S}};return B.set(D,K),h(K),K},me=[],dt,Qt=new Map,St=0,Se="agent",It=!1,yt=null,ke=null,Ge=e.config().iterationDisplay??"separate";for(dt=()=>{for(let D=0;D<me.length;D++){let S=me[D];if(!It&&Se!=="flow"&&typeof S.stepType=="string"&&(Se="flow"),S.type==="reasoning_start"){let F=typeof S.id=="string"?S.id:null,q=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(F&&q){H.set(F,q),We(F,q,"reasoning");continue}let K=S.id,Z=T(K);Z.reasoning=Z.reasoning??{id:K,status:"streaming",chunks:[]},Z.reasoning.startedAt=Z.reasoning.startedAt??Date.now(),Z.reasoning.completedAt=void 0,Z.reasoning.durationMs=void 0,(S.scope==="loop"||S.scope==="turn")&&(Z.reasoning.scope=S.scope),Z.streaming=!0,Z.reasoning.status="streaming",h(Z)}else if(S.type==="reasoning_delta"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)&&B.has(F)){let Z=B.get(F),ye=S.delta;ye&&Z.reasoning&&(Z.reasoning.chunks.push(String(ye)),h(Z));continue}let q=S.id,K=T(q);K.reasoning=K.reasoning??{id:q,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Date.now(),S.delta&&K.reasoning.chunks.push(S.delta),K.reasoning.status="streaming",K.streaming=!0,h(K)}else if(S.type==="reasoning_complete"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)&&B.has(F)){let ye=B.get(F);if(ye.reasoning){let xe=typeof S.text=="string"?S.text:"";xe&&ye.reasoning.chunks.length===0&&ye.reasoning.chunks.push(xe),ye.reasoning.status="complete",ye.streaming=!1,h(ye)}H.delete(F),B.delete(F);continue}let q=S.id,K=typeof S.text=="string"?S.text:"";!te.get(q)&&(K||S.scope==="loop")&&T(q);let Z=te.get(q);if(Z?.reasoning){(S.scope==="loop"||S.scope==="turn")&&(Z.reasoning.scope=S.scope),K&&Z.reasoning.chunks.length===0&&Z.reasoning.chunks.push(K),Z.reasoning.status="complete",Z.reasoning.completedAt=Date.now();let ye=Z.reasoning.startedAt??Date.now();Z.reasoning.durationMs=Math.max(0,(Z.reasoning.completedAt??Date.now())-ye),Z.streaming=!1,h(Z)}}else if(S.type==="tool_start"){y&&(y.streaming=!1,h(y),y=null),typeof S.iteration=="number"&&(St=S.iteration);let F=S.toolCallId,q=S.toolName;if(de(q)){_.add(F);continue}let K=pe(F),Z=K.toolCall??{id:F,status:"pending"};Z.name=q??Z.name,Z.status="running",Z.success=void 0,Z.error=void 0,Z.duration=void 0,S.parameters!==void 0&&(Z.args=S.parameters),Z.startedAt=Z.startedAt??ge(S.startedAt),Z.completedAt=void 0,Z.durationMs=void 0,K.toolCall=Z,K.streaming=!0,S.executionId&&(K.agentMetadata={executionId:S.executionId,iteration:S.iteration}),h(K)}else if(S.type==="tool_output_delta"){let F=S.toolCallId;if(_.has(F))continue;let q=pe(F),K=q.toolCall??{id:F,status:"running"};K.startedAt=K.startedAt??Date.now();let Z=S.delta;Z&&(K.chunks=K.chunks??[],K.chunks.push(String(Z))),K.status="running",q.toolCall=K,q.streaming=!0,S.executionId&&(q.agentMetadata=q.agentMetadata??{executionId:S.executionId,iteration:St}),h(q)}else if(S.type==="tool_complete"){let F=S.toolCallId;if(_.has(F)){_.delete(F);continue}let q=pe(F),K=q.toolCall??{id:F,status:"running"};K.status="complete",S.result!==void 0&&(K.result=S.result),K.name=S.toolName??K.name,K.success=S.success,K.error=S.error,K.completedAt=Date.now();let Z=S.executionTime;if(typeof Z=="number")K.durationMs=Z,K.duration=Z;else{let ye=K.startedAt??Date.now();K.durationMs=Math.max(0,(K.completedAt??Date.now())-ye)}q.toolCall=K,q.streaming=!1,S.executionId&&(q.agentMetadata=q.agentMetadata??{executionId:S.executionId,iteration:S.iteration??St}),h(q)}else if(S.type==="await"&&S.toolName){let F=typeof S.toolCallId=="string"&&S.toolCallId.length>0?S.toolCallId:void 0,q=F??S.toolId??`local-${d()}`,K=pe(q),Z=S.toolName,ye=S.origin==="webmcp"&&!Zs(Z)?`webmcp:${Z}`:Z,xe=Zs(ye),be=K.toolCall??{id:q,status:"pending"};be.name=ye,be.args=S.parameters,be.status=xe?"running":"complete",be.chunks=be.chunks??[],be.startedAt=be.startedAt??ge(S.awaitedAt),xe?(be.completedAt=void 0,be.duration=void 0,be.durationMs=void 0):be.completedAt=be.completedAt??be.startedAt,K.toolCall=be,K.streaming=!1,K.agentMetadata={...K.agentMetadata,executionId:S.executionId??K.agentMetadata?.executionId,awaitingLocalTool:!0,...F?{webMcpToolCallId:F}:{}},h(K)}else if(S.type==="text_start"){let F=typeof S.id=="string"?S.id:null,q=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(F&&q){H.set(F,q);continue}let K=y;K&&(Se==="flow"?($(K),Ve=K):(K.streaming=!1,h(K)),y=null),L=typeof S.id=="string"?S.id:L,I=""}else if(S.type==="text_delta"){let F=typeof S.id=="string"?S.id:null,q=F?H.get(F):void 0;if(F&&q){let ye=typeof S.delta=="string"?S.delta:"",xe=(V.get(F)??"")+ye;if(V.set(F,xe),xe.trim()==="")continue;let be=We(F,q);be.agentMetadata={...be.agentMetadata,executionId:S.executionId,parentToolId:q},Re(be,xe,ye,void 0);continue}if(L=typeof S.id=="string"?S.id:L,Se==="flow"){let ye=typeof S.delta=="string"?S.delta:"";if(I+=ye,I.trim()==="")continue;let xe=M();xe.agentMetadata={executionId:S.executionId,iteration:St},Re(xe,I,ye,void 0),b=xe;continue}let K=typeof S.delta=="string"?S.delta:"";I+=K;let Z=M();Z.agentMetadata={executionId:S.executionId,iteration:St,turnId:yt??void 0,agentName:ke?.agentName},Re(Z,I,K,void 0),b=Z}else if(S.type==="text_complete"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)){let K=B.get(F);K&&$(K),H.delete(F),V.delete(F),B.delete(F);continue}let q=y;q&&(Se==="flow"?($(q),Ve=q):((q.content??"")===""&&typeof S.text=="string"&&(q.content=S.text),q.streaming=!1,h(q)),y=null),L=null,I=""}else if(S.type==="step_complete"){if(S.stepType==="tool")continue;if(S.success===!1){let F=S.error||"Step failed";n({type:"error",error:new Error(F)});let q=y;q&&q.streaming&&(q.streaming=!1,h(q)),n({type:"status",status:"idle"});continue}{let F=Ve;Ve=null;let q=S.stopReason,Z=(S.result&&typeof S.result=="object"?S.result:null)?.response;if(F)q&&(F.stopReason=q),Z!=null?mt(F,Z):F.streaming!==!1&&(Ae.delete(F.id),Le.delete(F.id),F.streaming=!1,h(F));else{let ye=Z!=null&&Z!=="";if(ye||!!q&&q!=="end_turn"&&q!=="unknown"){let be=M();q&&(be.stopReason=q),ye?$(be,Z):(be.streaming=!1,h(be))}}continue}}else if(S.type==="execution_start")Se=S.kind==="flow"?"flow":"agent",It=!0,Se==="agent"&&(ke={executionId:S.executionId,agentId:S.agentId??"virtual",agentName:S.agentName??""});else if(S.type==="turn_start"){let F=typeof S.iteration=="number"?S.iteration:St;if(F!==St){if(Ge==="separate"&&F>1){let q=y;q&&(q.streaming=!1,h(q),y=null)}St=F}yt=typeof S.id=="string"?S.id:null,b=null}else if(S.type==="tool_input_delta"){let F=S.toolCallId;if(F){let q=W.get(F);q?.toolCall&&(q.toolCall.chunks=q.toolCall.chunks??[],q.toolCall.chunks.push(S.delta??""),h(q))}}else if(S.type==="tool_input_complete"){if(_.has(S.toolCallId))continue;let F=pe(S.toolCallId),q=F.toolCall;q.args=S.parameters,q.name=S.toolName??q.name,h(F)}else if(S.type==="turn_complete"){let F=S.stopReason,q=y??b;if(F&&q!==null){let K=S.id;(!K||q.agentMetadata?.turnId===K)&&(q.stopReason=F,h(q))}yt===S.id&&(yt=null)}else if(S.type==="media_start"){let F=String(S.id);Qt.set(F,{mediaType:typeof S.mediaType=="string"?S.mediaType:void 0,toolCallId:S.toolCallId,parts:[]})}else if(S.type==="media_delta"){let F=Qt.get(String(S.id));F&&typeof S.delta=="string"&&F.parts.push(S.delta)}else if(S.type==="media_complete"){let F=String(S.id),q=Qt.get(F);Qt.delete(F);let K=(typeof S.mediaType=="string"?S.mediaType:void 0)??q?.mediaType??"application/octet-stream",Z=typeof S.data=="string"?S.data:void 0,ye=typeof S.url=="string"?S.url:q&&q.parts.length>0?q.parts.join(""):void 0,xe=null;if(Z)xe={type:"media",data:Z,mediaType:K};else if(ye){let _e=K.toLowerCase();xe={type:_e==="image"||_e.startsWith("image/")?"image-url":"file-url",url:ye,mediaType:K}}let be=S.toolCallId??q?.toolCallId,ot=xe?[xe]:[],bt=[];for(let _e of ot){if(!_e||typeof _e!="object")continue;let Ye=_e,cn=typeof Ye.type=="string"?Ye.type:void 0,Co=typeof Ye.mediaType=="string"?Ye.mediaType.toLowerCase():"",ut=null,ht="";if(cn==="media"){let Dt=typeof Ye.data=="string"?Ye.data:void 0;if(!Dt)continue;ht=Co.length>0?Co:"application/octet-stream",ut=`data:${ht};base64,${Dt}`}else if(cn==="image-url"){let Dt=typeof Ye.url=="string"?Ye.url:void 0;if(!Dt)continue;ht=Co,ut=Dt}else if(cn==="file-url"){let Dt=typeof Ye.url=="string"?Ye.url:void 0;if(!Dt)continue;ht=Co,ut=Dt}else continue;if(ut)if(cn==="image-url"||ht.startsWith("image/"))bt.push({type:"image",image:ut,...ht.includes("/")?{mimeType:ht}:{}});else if(ht.startsWith("audio/"))bt.push({type:"audio",audio:ut,mimeType:ht});else if(ht.startsWith("video/"))bt.push({type:"video",video:ut,mimeType:ht});else{let Dt=ht||"application/octet-stream";bt.push({type:"file",data:ut,mimeType:Dt,filename:Vk(Dt)})}}if(bt.length>0){let _e=d(),Ye=be,Co={id:`agent-media-${typeof Ye=="string"&&Ye.length>0?`${Ye}-${_e}`:String(_e)}`,role:"assistant",content:"",contentParts:bt,createdAt:new Date().toISOString(),streaming:!1,sequence:_e,agentMetadata:{executionId:S.executionId,iteration:St}};h(Co);let ut=y;ut&&(ut.streaming=!1,h(ut)),y=null,C.current=null}}else if(S.type==="execution_complete"){let F=y;F&&(S.kind==="flow"&&F.streaming!==!1?$(F):(F.streaming=!1,h(F)),y=null),L=null,I="",Ve=null,n({type:"status",status:"idle",terminal:!0})}else if(S.type==="execution_error"){let F=typeof S.error=="string"?S.error:S.error?.message??"Execution error";n({type:"error",error:new Error(F)})}else if(S.type!=="ping"){if(S.type==="approval_start"){let F=S.approvalId??`approval-${d()}`,q={id:`approval-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:F,status:"pending",agentId:ke?.agentId??"virtual",executionId:S.executionId??ke?.executionId??"",toolName:S.toolName??"",toolType:S.toolType,description:S.description??`Execute ${S.toolName??"tool"}`,...typeof S.reason=="string"&&S.reason?{reason:S.reason}:{},parameters:S.parameters,...typeof S.toolCallId=="string"&&S.toolCallId?{toolCallId:S.toolCallId}:{}}};h(q)}else if(S.type==="approval_complete"){let F=S.approvalId;if(F){let K={id:`approval-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:F,status:S.decision??"approved",agentId:ke?.agentId??"virtual",executionId:S.executionId??ke?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};h(K)}}else if(S.type==="artifact_start"||S.type==="artifact_delta"||S.type==="artifact_update"||S.type==="artifact_complete"){if(S.type==="artifact_start"){let F=S.artifactType,q=String(S.id),K=typeof S.title=="string"?S.title:void 0,Z=S.file,ye;if(Z&&typeof Z=="object"&&!Array.isArray(Z)&&typeof Z.path=="string"&&typeof Z.mimeType=="string"&&(ye={path:Z.path,mimeType:Z.mimeType,...typeof Z.language=="string"?{language:Z.language}:{}}),n({type:"artifact_start",id:q,artifactType:F,title:K,component:typeof S.component=="string"?S.component:void 0,...ye?{file:ye}:{}}),U.set(q,{markdown:"",title:K,file:ye}),!Q.has(q)){Q.add(q);let xe=Mr(e.config().features?.artifacts,{artifactType:F,...ye?{file:ye}:{}}),be=typeof S.component=="string"?S.component:void 0,ot={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:al(xe,{artifactId:q,title:K,artifactType:F,status:"streaming",...ye?{file:ye}:{},...be?{component:be}:{}})};k.set(q,ot),h(ot)}}else if(S.type==="artifact_delta"){let F=String(S.id),q=typeof S.delta=="string"?S.delta:String(S.delta??"");n({type:"artifact_delta",id:F,artDelta:q});let K=U.get(F);K&&(K.markdown+=q)}else if(S.type==="artifact_update"){let F=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?S.props:{};n({type:"artifact_update",id:String(S.id),props:F,component:typeof S.component=="string"?S.component:void 0});let q=U.get(String(S.id));q&&(q.props={...q.props??{},...F})}else if(S.type==="artifact_complete"){let F=String(S.id);n({type:"artifact_complete",id:F});let q=k.get(F);if(q){q.streaming=!1;try{let K=JSON.parse(q.rawContent??"{}");if(K.props){K.props.status="complete";let Z=U.get(F);Z?.markdown&&(K.props.markdown=Z.markdown),Z?.file&&(K.props.file=Z.file),K.component==="PersonaArtifactInline"&&Z?.props&&Object.keys(Z.props).length>0&&(K.props.componentProps=Z.props)}q.rawContent=JSON.stringify(K)}catch{}U.delete(F),h(q),k.delete(F)}}}else if(S.type==="error"&&S.recoverable===!1&&S.error!=null&&S.error!==""){let F=typeof S.error=="string"?S.error:S.error?.message!=null?String(S.error.message):"Execution error";n({type:"error",error:new Error(F)});let q=y;q&&q.streaming&&(q.streaming=!1,h(q)),n({type:"status",status:"idle"})}}}me.length=0};;){let{done:D,value:S}=await s.read();if(D)break;l+=i.decode(S,{stream:!0});let F=l.split(`
5
5
 
6
- `);l=F.pop()??"";for(let z of F){let K=z.split(`
7
- `),Z="message",ye="",be=null;for(let Ge of K)Ge.startsWith("event:")?Z=Ge.replace("event:","").trim():Ge.startsWith("data:")?ye+=Ge.replace("data:","").trim():Ge.startsWith("id:")&&(be=Ge.slice(3).trim());let Ae=()=>{be!==null&&be!==""&&n({type:"cursor",id:be})};if(!ye){Ae();continue}let tt;try{tt=JSON.parse(ye)}catch(Ge){n({type:"error",error:Ge instanceof Error?Ge:new Error("Failed to parse chat stream payload")});continue}let bt=tt!==null&&typeof tt=="object"&&!Array.isArray(tt)?tt:null,Be=Z!=="message"?Z:typeof bt?.type=="string"?bt.type:"message";if(e.onSSEEvent?.(Be,tt),e.parseSSEEvent){C.current=y;let Ge=await NP(e,tt,n,C,h,d,A);if(C.current&&C.current!==y&&(y=C.current),Ge){Ae();continue}}bt&&(me.push({...bt,type:Be}),dt()),Ae()}}dt()}var tv,Wg=$e(()=>{"use strict";ei();Yi();ss();ev();tv=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<")});var iv,sv=$e(()=>{iv="4.26.1"});var Jn,oa=$e(()=>{"use strict";sv();Jn=iv});var dd={};Qs(dd,{deleteAllConversations:()=>ek,deleteConversation:()=>ZP,finalizeDisplayProjections:()=>JP,getConversation:()=>QP,historyErrorFor:()=>fv,listConversations:()=>XP,readErrorCode:()=>Bg,recoverFromUnauthorized:()=>gv,resetVisitor:()=>tk});function qP(e,t,n){let o=new URLSearchParams;for(let[s,i]of Object.entries(n))i===void 0||i===""||o.set(s,String(i));let r=o.toString();return`${e.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}function zP(e,t){if(t)return t;let n=e.config.features?.history?.scope;return n||(e.config.getIdentityProof?"verified-user":"browser")}async function KP(e,t,n){let o=e.config.getIdentityProof;if(!o)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&e.setHistoryIdentityStatus({state:"identity_provider_failed"}),new e.HistoryClientError("identity_provider_failed","The identity proof provider failed")}if(r)return r;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 GP(e,t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await e.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new e.HistoryClientError("proof_not_admitted",cv);return r}async function Bg(e,t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async function gv(e,t,n,o){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new e.HistoryClientError("invalid_identity_proof",dv);if(r.includes("visitor token required"))throw new e.HistoryClientError("visitor_token_missing",pv);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new e.HistoryClientError("visitor_identity_mismatch",uv);return e.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError("unauthorized",t||"History request was not authorized")}async function fv(e,t,n){let o=await Bg(e,t);if(t.status===404)return new e.HistoryClientError("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new e.HistoryClientError("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&o.includes("identity_proof_not_admitted"))return n&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new e.HistoryClientError("proof_not_admitted",cv);if(t.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new e.HistoryClientError("invalid_identity_proof",dv)):r.includes("visitor token required")?new e.HistoryClientError("visitor_token_missing",pv):r.includes("visitor_identity_mismatch")?new e.HistoryClientError("visitor_identity_mismatch",uv):new e.HistoryClientError("unauthorized",o||"History request was not authorized")}return new e.HistoryClientError("request_failed",o||`History request failed (${t.status})`)}function YP(e,t,n,o){let r=t?.toLowerCase()??null;if(n){if(r==="admitted"){o&&e.setHistoryIdentityStatus({state:"verified"});return}throw o&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="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(r==="admitted")throw new e.HistoryClientError("identity_contract_violation","Server admitted an identity proof that was never sent");o&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function ra(e,t,n){_g(e);let o=n.trackIdentity!==!1,r=await e.initSession(),s=null;zP(e,n.scope)==="verified-user"&&(s=await KP(e,r,o),s&&(r=await GP(e,r,s,o)));let i=e.historyInternals.visitorStore,l=!1;for(;;){let c=i?.revision()??0,p=await e.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new e.HistoryClientError("visitor_token_missing","No visitor credential is stored for this browser");let d=await fetch(qP(e,t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Jn,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(d.status===401&&!l){l=!0,r=await gv(e,await Bg(e,d),s,o);continue}if(!d.ok)throw await fv(e,d,o);let g=d.headers.get("X-History-Identity-Status"),f=await d.json().catch(()=>{});if(i&&i.revision()!==c)throw new e.HistoryClientError("credential_changed","The visitor credential changed while the request was in flight");return YP(e,g,s!==null,o),f}}function _g(e){if(!e.isClientTokenMode())throw new 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 XP(e,t){let n=await ra(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(lv),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async function QP(e,t,n){let o=await ra(e,`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:lv(o),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async function JP(e,t,n){_g(e);let o=0;for(let c of n){let p=c.displayContent.length;if(p>av)throw new e.HistoryClientError("payload_too_large",`displayContent exceeds the ${av} character limit`);o+=p}if(o>Og)throw new e.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${Og} character limit`);await e.initSession();let r=e.historyInternals.visitorStore,s=r?.revision()??0,i=await ra(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=Og,trackIdentity:!1}),l=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return l&&e.clientSession?.conversationId===t&&(r?.revision()??0)===s&&e.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async function ZP(e,t,n){let o=await ra(e,`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async function ek(e,t){let n=await ra(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 tk(e){_g(e),e.setHistoryIdentityStatus({state:"resetting"});try{await ra(e,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var av,Og,lv,cv,dv,pv,uv,Dg=$e(()=>{"use strict";oa();av=32768,Og=49152,lv=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:""}},cv="The identity proof was not admitted; account history is unavailable",dv="The identity proof was rejected",pv="The request carried no visitor credential",uv="The stored visitor belongs to a different signed-in user"});var hv,yv=$e(()=>{"use strict";gl();hv=e=>{let{mount:t,overlay:n,sessionRef:o}=e,r=(d,g,f)=>{let h=g.trim();if(!h||!o.current)return;let y=d.getAttribute("data-tool-call-id")??"",v=f.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:y,answer:h,answers:f.structured,values:f.values??(f.source==="multi"?h.split(", "):[h]),isFreeText:v,source:f.source},bubbles:!0,composed:!0})),cs(n,y);let C=o.current.getMessages().find(A=>A.toolCall?.id===y);C?.agentMetadata?.awaitingLocalTool?o.current.resolveAskUserQuestion(C,f.structured??h):o.current.sendMessage(h)},s=d=>{let g=o.current;if(!g)return;let f=d.getAttribute("data-tool-call-id")??"",h=g.getMessages().find(y=>y.toolCall?.id===f);h&&g.persistAskUserQuestionProgress(h,{answers:sd(d,h),currentIndex:yo(d)})},i=d=>Object.entries(d).map(([g,f])=>`${g}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),l=d=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=yo(d),f=Ji(d);if(g>=f-1)return;let h=o.current?.getMessages().find(y=>y.toolCall?.id===d.getAttribute("data-tool-call-id"));h&&(id(d,h,e.config(),g+1),s(d))};return{click:d=>{let f=d.target.closest("[data-ask-user-action]");if(!f)return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;let y=f.getAttribute("data-ask-user-action");if(d.preventDefault(),d.stopPropagation(),y==="dismiss"){let v=h.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),cs(n,v);let C=o.current?.getMessages().find(A=>A.toolCall?.id===v);C?.agentMetadata?.awaitingLocalTool&&(o.current?.markAskUserQuestionResolved(C),o.current?.resolveAskUserQuestion(C,"(dismissed)"));return}if(y==="pick"){let v=f.getAttribute("data-option-label");if(!v)return;let C=h.getAttribute("data-multi-select")==="true",A=ls(h);if(A&&C){let L=ni(h)[yo(h)],I=new Set(Array.isArray(L)?L:[]);I.has(v)?I.delete(v):I.add(v),ds(h,Array.from(I)),s(h);return}if(A){ds(h,v),s(h),l(h);return}if(C){let L=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",L?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!L);let I=h.querySelector('[data-ask-user-action="submit-multi"]');I&&(I.disabled=Hg(h).length===0);return}r(h,v,{source:"pick",values:[v]});return}if(y==="submit-multi"){let v=Hg(h);if(v.length===0)return;r(h,v.join(", "),{source:"multi",values:v});return}if(y==="open-free-text"){let v=h.querySelector('[data-ask-free-text-row="true"]');v&&(v.classList.remove("persona-hidden"),v.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(y==="focus-free-text"){h.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(y==="submit-free-text"){let C=h.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!C.trim())return;if(ls(h)){ds(h,C.trim()),s(h),l(h);return}r(h,C,{source:"free-text"});return}if(y==="next"||y==="back"){if(!o.current)return;let v=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(_=>_.toolCall?.id===v);if(!C)return;let L=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(L){let _=ni(h)[yo(h)];(typeof _!="string"||_!==L)&&ds(h,L)}let I=y==="next"?1:-1,H=yo(h)+I;id(h,C,e.config(),H),s(h);return}if(y==="submit-all"){if(!o.current)return;let v=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(_=>_.toolCall?.id===v);if(!C)return;let L=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";L&&ds(h,L);let I=sd(h,C);o.current.persistAskUserQuestionProgress(C,{answers:I,currentIndex:yo(h)});let H=i(I);r(h,H||"(submitted)",{source:"submit-all",structured:I});return}if(y==="skip"){if(!o.current)return;let v=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(V=>V.toolCall?.id===v);if(!C)return;let A=ls(h),L=yo(h),I=Ji(h),H=L>=I-1;if(!A){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),cs(n,v),C.agentMetadata?.awaitingLocalTool&&(o.current.markAskUserQuestionResolved(C),o.current.resolveAskUserQuestion(C,"(dismissed)"));return}ds(h,"");let _=h.querySelector('[data-ask-free-text-input="true"]');if(_&&(_.value=""),H){let V=sd(h,C),te=i(V);r(h,te||"(skipped)",{source:"submit-all",structured:V});return}id(h,C,e.config(),L+1),s(h);return}},keydown:d=>{if(d.key!=="Enter")return;let f=d.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;d.preventDefault();let y=f.value;if(y.trim()){if(ls(h)){ds(h,y.trim()),s(h),l(h);return}r(h,y,{source:"free-text"})}}}}});function rk(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
8
- `:o===""||bv.test(o)}function sk(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let i=e[s];if(i===n)return rk(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(i===`
9
- `||i==="\uFFFC"||!r&&bv.test(i))return null;s--}return null}function vv(e,t,n){for(let o of n){let r=sk(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Cv(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}var bv,wv=$e(()=>{"use strict";bv=/\s/});function Sv(e){let t={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},n=(e.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[t,...n]}var Av=$e(()=>{"use strict"});var pd=$e(()=>{"use strict"});function Tv(e){e.delayMs!==void 0&&(xv=gd(e.delayMs)),e.skipDelayMs!==void 0&&(Mv=gd(e.skipDelayMs))}function Pv(e){ud.get(e)?.hide()}function yn(e){ud.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:i=ik,viewportPadding:l=ak}=e,c=()=>t.ownerDocument,p=()=>c().defaultView??window,d=null,g=null,f=null,h=null,y,v=!1,C=!1,A=!1,L=()=>(typeof o=="function"?o():o).trim(),I=()=>(typeof r=="function"?r():r??"").trim(),H=()=>gd(e.delayMs??xv),_=()=>gd(e.skipDelayMs??Mv),V=()=>{y!==void 0&&(p().clearTimeout(y),y=void 0)},te=()=>{V();let ge=d!==null;h?.(),h=null,d?.remove(),d=null,g=null,f=null,ge&&ck(_())},W=()=>{if(!d)return;let ge=c(),ke=p(),xe=t.getBoundingClientRect(),Le=d.getBoundingClientRect(),mt=ge.documentElement.clientWidth||ke.innerWidth,Ve=ge.documentElement.clientHeight||ke.innerHeight,Re=mt-l-Le.width,$=xe.left+xe.width/2-Le.width/2,We=Fg($,l,Re),me=xe.top-l,dt=Ve-l-xe.bottom,Qt=Le.height+i,St=me>=Qt||me>=dt?"top":"bottom",Se=St==="top"?xe.top-i-Le.height:xe.bottom+i,It=Ve-l-Le.height,yt=Fg(Se,l,It),Pe=xe.left+xe.width/2,Ke=Math.max(Ng,Le.width-Ng),D=Fg(Pe-We,Ng,Ke);d.dataset.placement=St,d.style.left=`${We}px`,d.style.top=`${yt}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${D}px`)},j=()=>{if(A||!s||d||!t.isConnected||dk(t))return;let ge=L(),ke=pk(t);if(!ge||!ke)return;let xe=c(),Le=p();d=xe.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(na);let mt=Le.getComputedStyle?.(t);if(mt){for(let Qt of uk){let St=mt.getPropertyValue(Qt).trim();St&&d.style.setProperty(Qt,St)}mt.fontFamily&&(d.style.fontFamily=mt.fontFamily)}g=xe.createElement("span"),g.className="persona-control-tooltip__label",g.textContent=ge,d.appendChild(g);let Ve=I();Ve&&(f=xe.createElement("span"),f.className="persona-control-tooltip__hint",f.textContent=Ve,d.appendChild(f));let Re=xe.createElement("span");Re.className="persona-control-tooltip__arrow",d.appendChild(Re),ke.appendChild(d),W(),d.dataset.state="open";let $=()=>{if(!t.isConnected){te();return}g&&(g.textContent=L()),f&&(f.textContent=I()),W()};Le.addEventListener("scroll",$,!0),Le.addEventListener("resize",$);let We=t.getRootNode(),me=kv(We)?We:xe.documentElement,dt=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||te()});dt?.observe(me,{childList:!0,subtree:!0}),h=()=>{Le.removeEventListener("scroll",$,!0),Le.removeEventListener("resize",$),dt?.disconnect()}},Y=ge=>{if(!(A||d)){if(V(),ge||H()<=0||lk()){j();return}y=p().setTimeout(()=>{y=void 0,j()},H())}},E=()=>{v||C?Y(C):te()},T=()=>{let ge=p();(!ge.matchMedia||!ge.matchMedia("(hover: none)").matches)&&(v=!0,E())},B=()=>{v=!1,E()},P=()=>{try{C=t.matches(":focus-visible")}catch{C=!0}E()},Q=()=>{C=!1,E()},U=()=>{v=!1,C=!1,te()},de=ge=>{ge.key==="Escape"&&U()};n.addEventListener("mouseenter",T),n.addEventListener("mouseleave",B),t.addEventListener("focus",P),t.addEventListener("blur",Q),t.addEventListener("keydown",de),t.addEventListener("click",U);let pe={get isOpen(){return d!==null},show:j,hide:te,reposition:W,destroy:()=>{A||(A=!0,te(),n.removeEventListener("mouseenter",T),n.removeEventListener("mouseleave",B),t.removeEventListener("focus",P),t.removeEventListener("blur",Q),t.removeEventListener("keydown",de),t.removeEventListener("click",U),ud.delete(t))}};return ud.set(t,pe),pe}var ik,ak,Ng,xv,Mv,Ev,gd,lk,ck,ud,$g,dk,kv,pk,Fg,uk,sa=$e(()=>{"use strict";Lo();pd();ik=8,ak=8,Ng=10,xv=200,Mv=300,Ev=0,gd=e=>Math.max(0,e);lk=()=>Date.now()<Ev,ck=e=>{Ev=e>0?Date.now()+e:0},ud=new WeakMap,$g="data-persona-tooltip-suppressed",dk=e=>typeof e.closest=="function"&&e.closest(`[${$g}]`)!==null;kv=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,pk=e=>{let t=e.getRootNode?.();return kv(t)?t:e.ownerDocument.body},Fg=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),uk=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"]});var gk,ri,Ug,Vg=$e(()=>{"use strict";gk=(e,t)=>e.visible!==!1&&(e.mode!=="transient"||t==="connecting"||t==="paused"||t==="resuming"||t==="error"),ri=(e,t,n)=>{let o=t.mode==="transient",r=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=gk(t,n)||o&&r&&t.visible!==!1?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},Ug=(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 Ho(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Lv(s)&&Lv(r)?n[o]=Ho(s,r):n[o]=r}return n}var Lv,fd=$e(()=>{"use strict";Lv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function md(e,t=""){return Object.entries(e).flatMap(([n,o])=>{let r=t?`${t}.${n}`:n;return qg(o)?md(o,r):[r]})}function Hv(e,t){for(let n of t.split(".")){if(!qg(e)||!Object.prototype.hasOwnProperty.call(e,n))return"absent";if(e=e[n],e===void 0)return"clear"}return"explicit"}function Iv(e,t){return e?.[jg]??t.filter(n=>Hv(e,n)==="explicit")}function zg(e,t){return Object.defineProperty(e,jg,{value:t,enumerable:!0,configurable:!0}),e}function Kg(e,t,n){return zg(e,Iv(t,md(n)))}function Rv(e,t,n){let o=t[jg];if(o)return o;let r=new Set(Iv(e,n));for(let s of n){let i=Hv(t,s);i==="clear"&&r.delete(s),i==="explicit"&&r.add(s)}return[...r]}function Wv(e,t,n){let o={...e};for(let r of t){if(n.includes(r))continue;let s=r.split("."),i=o;for(let l of s.slice(0,-1)){let c=i[l];if(!qg(c)){i=void 0;break}i[l]={...c},i=i[l]}i&&delete i[s[s.length-1]]}return o}var jg,qg,Gg=$e(()=>{"use strict";jg=Symbol("persona.defaultsProvenance"),qg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var Ov,Yg,si,hd,fk,Pr,Xg,Qg,Bv,ia=$e(()=>{"use strict";Ov="var(--persona-components-panel-width)",Yg=Symbol("persona.panelAliasProvenance"),si=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),hd=(e,t)=>si(e,t)&&e[t]!==void 0,fk=e=>({launcherWidth:hd(e?.launcher,"width"),legacyLauncherWidth:hd(e,"launcherWidth"),sidebarWidth:hd(e?.launcher,"sidebarWidth"),dockWidth:hd(e?.launcher?.dock,"width")}),Pr=e=>{let t=e?.[Yg];return t?{...t}:fk(e)},Xg=(e,t)=>(Object.defineProperty(e,Yg,{value:t,enumerable:!0,configurable:!0}),e),Qg=(e,t)=>Xg(e,Pr(t)),Bv=(e,t)=>{let n=t[Yg];if(n)return{...n};let o=Pr(e);return si(t,"launcherWidth")&&(o.legacyLauncherWidth=t.launcherWidth!==void 0),si(t,"launcher")&&t.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(si(t.launcher,"width")&&(o.launcherWidth=t.launcher?.width!==void 0),si(t.launcher,"sidebarWidth")&&(o.sidebarWidth=t.launcher?.sidebarWidth!==void 0),si(t.launcher,"dock")&&t.launcher?.dock===void 0?o.dockWidth=!1:si(t.launcher?.dock,"width")&&(o.dockWidth=t.launcher?.dock?.width!==void 0),o)}});function us(e){return e?.future?.v5Defaults===!0?"v5":"v4"}function Dv(e){let t=us(e)==="v5"?ii:bk;return Ho(yk,t)}function _v(e,t){if(!(!e&&!t))return e?t?Ho(e,t):e:t}function yl(e){let t=Dv(e);return e?Kg(Qg({...t,...e,theme:_v(t.theme,e.theme),darkTheme:_v(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,o=e.features?.artifacts,r=t.features?.scrollToBottom,s=e.features?.scrollToBottom,i=t.features?.scrollBehavior,l=e.features?.scrollBehavior,c=t.features?.streamAnimation,p=e.features?.streamAnimation,d=t.features?.askUserQuestion,g=e.features?.askUserQuestion,f=t.features?.history,h=e.features?.history,y=n===void 0&&o===void 0?void 0:{...n,...o,layout:{...n?.layout,...o?.layout}},v=r===void 0&&s===void 0?void 0:{...r,...s},C=i===void 0&&l===void 0?void 0:{...i,...l},A=c===void 0&&p===void 0?void 0:{...c,...p},L=d===void 0&&g===void 0?void 0:{...d,...g,styles:{...d?.styles,...g?.styles}},I=f===void 0&&h===void 0?void 0:{...f,...h,copy:{...f?.copy,...h?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...v!==void 0?{scrollToBottom:v}:{},...C!==void 0?{scrollBehavior:C}:{},...y!==void 0?{artifacts:y}:{},...A!==void 0?{streamAnimation:A}:{},...L!==void 0?{askUserQuestion:L}:{},...I!==void 0?{history:I}:{}}})(),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,ii):Kg(Qg(t),void 0,ii)}var aa,mk,hl,Jg,kr,ai,hk,yk,bk,vk,ii,Ck,bo=$e(()=>{"use strict";fd();Gg();ia();pd();aa="min(440px, calc(100vw - 24px))",mk="440px",hl="40px",Jg="How can I help...",kr={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},ai={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},hk={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:aa,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:hl,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)"},yk={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:hk,copy:{inputPlaceholder:Jg,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",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:kr,reasoningDisplay:ai,streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",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},bk={},vk={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},ii={launcher:vk,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"}}}};Ck=Dv()});function wk(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Zg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function bl(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Sk(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Io(e){return{type:"text",text:e}}function ef(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Ak(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function xk(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){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 Ek(e){return Nv.includes(e)||e.startsWith("image/")}function yd(e){return Ek(e.type)}function Fv(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function $v(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;yd(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Uv(e,t=Lr,n=10*1024*1024){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 Tk(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Vv(e,t){let n=Tk(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 la,Nv,Mk,Lr,Hr=$e(()=>{"use strict";la="[Image]";Nv=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Mk=["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"],Lr=[...Nv,...Mk]});function tf(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 o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function bd(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function jv(e,t){e.style.maxHeight=`${t*tf(e)}px`,e.style.overflowY="auto"}function vl(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 qv(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function zv(e,t){if(e.key!=="Enter"||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,o=t.submitKey??"enter";return o==="none"?!1:o==="mod-enter"?n:n||!qv(t)}function Pk(e){return(e.submitKey??"enter")!=="enter"||qv(e)?"enter":"send"}function vd(e,t){e.setAttribute("enterkeyhint",Pk(t))}function Cd(e,t){let n=t?.autocomplete;e.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(r,s)=>{s===void 0?e.removeAttribute(r):e.setAttribute(r,s)};o("autocapitalize",typeof t?.autocapitalize=="string"?t.autocapitalize:void 0),o("spellcheck",typeof t?.spellcheck=="boolean"?String(t.spellcheck):void 0),o("inputmode",typeof t?.inputmode=="string"&&t.inputmode?t.inputmode:void 0),o("aria-label",typeof t?.ariaLabel=="string"&&t.ariaLabel?t.ariaLabel:void 0)}function nf(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 wd=$e(()=>{"use strict"});var Zn,Ro,rf,qn,Sd,Ad,Lk,sf,xd,ca,Md,Ed,Td,gs=$e(()=>{"use strict";Vg();Xe();Tt();bo();Hr();sa();wd();Zn="persona-composer-control",Ro="persona-composer-control--glyph",rf=40,qn=24,Sd=(e,t,n)=>{let o=e.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(e);for(let s of n){let i=r.getPropertyValue(s).trim();i?t.style.setProperty(s,i):t.style.removeProperty(s)}},Ad=(e,t)=>{let n=x("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??Jg,n.dir="auto",vd(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:vl(n)}),Cd(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 o=bd(e?.composer?.maxLines,t?.defaultMaxLines??3),r=`${o*20}px`;n.style.maxHeight=r,n.style.overflowY="auto";let s=()=>{let l=n.style.maxHeight;if(l!==r){let p=parseFloat(l);if(Number.isFinite(p)&&p>0)return p}let c=o*tf(n);return r=`${c}px`,n.style.maxHeight=r,c},i=()=>{n.addEventListener("input",()=>{n.style.height="auto";let l=Math.min(n.scrollHeight,s());n.style.height=`${l}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:i}},Lk="[data-persona-glyph-stack]",sf=(e,t,n="send")=>{let o=X("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"),o.append(e,t),o},xd=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",i=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",c=e?.copy?.sendButtonLabel??"Send",p=e?.copy?.stopButtonLabel??"Stop",d=t.showTooltip??!1,g=t.size,f=parseFloat(g??"")||rf,h=t.backgroundColor,y=t.textColor,v=x("div","persona-send-button-wrapper"),C=X("button",{className:Wn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${Zn}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!y&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?g:void 0,height:n?g:void 0,minWidth:n?g:void 0,minHeight:n?g:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?y||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":y||void 0,backgroundColor:n&&h||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}}),A=null,L=null,I=null;if(n){let V=parseFloat(t.iconSize??"")||Math.round(f*.5),te=t.iconStrokeWidth??2,W=y?.trim()||"currentColor";if(r&&(A=ue(r,V,W,te)),L=ue(s,V,W,te),!t.iconSize)for(let j of[A,L])j&&(j.style.width=`var(--persona-components-composer-sendIconSize, ${V}px)`,j.style.height=`var(--persona-components-composer-sendIconSize, ${V}px)`);A&&L?(I=sf(A,L),C.appendChild(I)):A?C.appendChild(A):(C.textContent=o,L=null)}else C.textContent=c;C.setAttribute("aria-label",i),v.appendChild(C),yn({anchor:C,trigger:v,text:()=>C.getAttribute("aria-label")??"",enabled:d});let H="send";return{button:C,wrapper:v,setMode:V=>{if(V===H)return;H=V;let te=V==="stop"?l:i;C.setAttribute("aria-label",te),C.setAttribute("data-persona-send-mode",V),n?(C.querySelector(Lk)??I)?.setAttribute("data-mode",V):C.textContent=V==="stop"?p:c},glyphStack:I}},ca=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype",s=t.provider?.type==="custom";if(!(o||r||s))return null;let l=t.iconName??"mic",c=t.iconSize,p=parseFloat(c??"")||qn,d=t.backgroundColor??e?.sendButton?.backgroundColor,g=t.iconColor??e?.sendButton?.textColor,f=x("div","persona-send-button-wrapper"),h=X("button",{className:Wn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Zn,!c&&Ro),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:d||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}}),v=ue(l,p,g||"currentColor",1.5);v?h.appendChild(v):h.textContent="\u{1F3A4}",f.appendChild(h);let C=t.tooltipText??"Start voice recognition",A=t.showTooltip??!1;return yn({anchor:h,trigger:f,text:()=>h.getAttribute("aria-label")??C,enabled:A}),{button:h,wrapper:f}},Md=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=x("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 o=x("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??Lr).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",s=x("div","persona-send-button-wrapper"),i=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Zn} ${Ro}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=ue(r,qn,"currentColor",1.5);l?i.appendChild(l):i.textContent="\u{1F4CE}",i.addEventListener("click",p=>{p.preventDefault(),o.click()}),s.appendChild(i);let c=t.buttonTooltipText??"Attach file";return yn({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:s,input:o,previewsContainer:n}},Ed=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=x("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),ri(o,t,"idle");let r=t.idleText??"Online";if(t.idleLink){let s=x("a");s.href=t.idleLink,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r,s.style.color="inherit",s.style.textDecoration="none",o.appendChild(s)}else o.textContent=r;return o},Td=()=>X("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}})});function Pd(e){let{config:t,onOpen:n}=e,o=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",s=x("div","persona-send-button-wrapper"),i=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Zn} ${Ro}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=ue(o,qn,"currentColor",1.5);return l?i.appendChild(l):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),n()}),s.appendChild(i),yn({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:s}}var af=$e(()=>{"use strict";Xe();Tt();sa();gs()});var LB,Hk,kd,lf=$e(()=>{"use strict";ln();({setLoader:LB,load:Hk}=it({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")})),kd=Hk});var RB,Ik,Ld,cf=$e(()=>{"use strict";ln();({setLoader:RB,load:Ik}=it({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0})),Ld=Ik});function Cl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=X("span",{className:Wn("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 o=ue(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=x("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(X("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}var df=$e(()=>{"use strict";Xe();Tt()});function Kv(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:o,createMentionButton:r}=e.deps??Rk,s=e.config.contextMentions;if(!s?.enabled)return null;let i=Sv(s).filter(W=>W.sources.length>0);if(i.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let l=i.filter(W=>W.sources.some(j=>typeof j.matchCommand=="function")),c=W=>l.some(j=>j.trigger?j.position==="line-start"?W.split(`
10
- `).some(E=>E.startsWith(j.trigger)):(j.position==="anywhere"?W:W.split(`
11
- `)[0]).startsWith(j.trigger):!1),p=(W,j)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${W}`,{detail:j}))}catch{}},d=!e.chipRow,g=e.chipRow??X("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),f=null,h=null,y=e.textarea,v=null,C=null,A=null,L=null,I=()=>{if(f)return Promise.resolve(f);if(h)return h;let W=t().then(j=>(j.setMentionIconRenderer(o),f=j.mountContextMentions({mentionConfig:s,textarea:e.textarea,composerInput:v??void 0,anchor:e.anchor,contextRow:g,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:te,emit:p}),f)).catch(j=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",j),h===W&&(h=null),null));return h=W,W},H=()=>{n().then(W=>{let j=W.mountInlineComposer({textarea:e.textarea,renderToken:E=>Cl(E,{render:s.renderMentionToken}),onMentionRemoved:E=>f?.untrackMention(E)});v=j.input,C=j.destroy;let Y=y;Y.replaceWith(j.element),y=j.element,L={next:j.element,prev:Y},A?.(j.element,Y),f?f.rebindComposer(j.input):h&&h.then(E=>E?.rebindComposer(j.input))}).catch(W=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",W)})};s.display==="inline"&&H();let _=[],V=new Map;for(let W of i){if(!W.showButton)continue;let j=r({config:{...s,buttonIconName:W.buttonIconName,buttonTooltipText:W.buttonTooltipText},onOpen:()=>{I().then(Y=>Y?.openMenu(W.trigger))}});_.push(j),V.set(W.trigger,j.button)}let te=(W,j,Y)=>{let E=V.get(j);E&&(E.setAttribute("aria-expanded",W?"true":"false"),W?E.setAttribute("aria-controls",Y):E.removeAttribute("aria-controls"))};return{affordanceButtons:_.map(W=>W.wrapper),contextRow:g,handleInput:W=>{if(f){f.handleInput();return}if(!Cv(W))return;let j=y,Y=j.selectionStart??0;vv(j.value,Y,i)&&I().then(E=>E?.handleInput())},handleKeydown:W=>{if(f?.isMenuOpen())return f.handleKeydown(W);if(W.key==="Backspace"&&f?.hasMentions()&&!L){let j=y,Y=j.selectionStart===0&&j.selectionEnd===0;if((j.value.length===0||Y)&&f.removeLastChip())return W.preventDefault(),!0}return!1},isMenuOpen:()=>f?.isMenuOpen()??!1,hasMentions:()=>f?.hasMentions()??!1,getMentionRefs:()=>f?.getMentionRefs()??[],collectForSubmit:()=>f?.collectForSubmit()??null,takeInlineCommand:async W=>c(W)?(f??await I())?.dispatchInlineCommand(W)??null:null,clear:()=>f?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:W=>{A=W,L&&W(L.next,L.prev)},destroy:()=>{f?.destroy(),C?.();for(let W of _)W.wrapper.remove();d&&g.remove()}}}var Rk,Gv=$e(()=>{"use strict";Xe();wv();Av();af();lf();Tt();cf();df();Rk={loadContextMentions:()=>kd(),loadContextMentionsInline:()=>Ld(),renderLucideIcon:(...e)=>ue(...e),createMentionButton:(...e)=>Pd(...e)}});var Hd={};Qs(Hd,{createAskUserSheetHandlers:()=>hv,createContextMentionOrchestrator:()=>Kv});var pf=$e(()=>{"use strict";yv();Gv()});var Wd={};Qs(Wd,{resolveApproval:()=>Dk,resolveAskUserQuestion:()=>Nk,resolveWebMcpToolCall:()=>Uk,resolveWebMcpToolCallBatch:()=>Qv});async function Dk(e,t,n,o){let r=`approval-${t.id}`,s=`approval-error-${t.id}`,i={};e.s.approvalTokens.set(r,i);let l={...t,status:n,resolvedAt:Date.now()},c=e.s.messages.find(f=>f.id===r),p={id:r,role:"assistant",content:"",createdAt:c?.createdAt??new Date().toISOString(),...c?.sequence!==void 0?{sequence:c.sequence}:{},streaming:!1,variant:"approval",approval:l};e.s.upsertMessage(p),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let d=e.s.config.approval,g=d&&typeof d=="object"?d.onDecision:void 0;try{let f;if(g?f=await g({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):f=await e.s.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),f){let h=null;if(f instanceof Response){if(!f.ok){let y=await f.json().catch(()=>null),v=y?.message??y?.error??`Approval request failed: ${f.status}`,C=y?.code==="APPROVAL_ALREADY_RESOLVED"||f.status===404&&/no paused execution/i.test(String(y?.error)),A=e.s.messages.find(L=>L.id===r);throw e.s.approvalTokens.get(r)===i&&A?.approval?.resolvedAt===l.resolvedAt&&(e.s.upsertMessage({...p,approval:C?{...l,status:"timeout"}:t}),C&&e.settleApprovalPausedToolCall(r),e.s.upsertMessage({id:s,role:"assistant",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})),new Error(v)}h=f.body}else f instanceof ReadableStream&&(h=f);e.s.approvalTokens.get(r)===i&&e.s.messages.some(y=>y.id===s)&&(e.s.messages=e.s.messages.filter(y=>y.id!==s),e.s.callbacks.onMessagesChanged([...e.s.messages])),h?await e.s.connectStream(h,{allowReentry:!0}):(n==="denied"&&(e.settleApprovalPausedToolCall(r),e.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})),e.setStreaming(!1),e.s.abortController=null)}else e.setStreaming(!1),e.s.abortController=null}catch(f){let h=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,h||e.s.callbacks.onError?.(f instanceof Error?f:new Error(String(f)))}finally{e.s.approvalTokens.get(r)===i&&e.s.approvalTokens.delete(r)}}async function Nk(e,t,n){if(e.s.messages.find(d=>d.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){e.s.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof n=="string"?void 0:n;if(i===void 0&&typeof n=="string"){let d=t.toolCall?.args,g=Array.isArray(d?.questions)?d.questions:[];if(g.length===1){let f=typeof g[0]?.question=="string"?g[0].question:"";f&&(i={[f]:n})}}e.s.markAskUserQuestionResolved(t,i),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let l=t.toolCall.id,c=t.toolCall?.args,p=Array.isArray(c?.questions)?c.questions:[];if(p.length===0){let d=typeof n=="string"?n:Object.entries(n).map(([g,f])=>`${g}: ${Array.isArray(f)?f.join(", "):f}`).join(" | ");e.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})}else{let d=i??{};p.forEach((g,f)=>{let h=typeof g?.question=="string"?g.question:"";if(!h)return;let y=d[h],v=Array.isArray(y)?y.join(", "):typeof y=="string"?y:"";e.appendMessage({id:`ask-user-q-${l}-${f}`,role:"assistant",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}),e.appendMessage({id:`ask-user-a-${l}-${f}`,role:"user",content:v||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})})}try{let d=await e.s.client.resumeFlow(r,{[s]:n},{after:e.resumeAfter(r)});if(!d.ok){let g=await d.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${d.status}`)}d.body?await e.s.connectStream(d.body,{allowReentry:!0}):(e.setStreaming(!1),e.s.abortController=null)}catch(d){let g=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,g||e.s.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}function Fk(e,t){let o=[e.s.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}function Xv(e,t){return t.toolCall?.name!==Xo?!1:(e.s.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function $k(e,t){let n=Fk(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 Rd(e,t,n,o,r=Date.now(),s){e.s.messages.some(i=>i.id===t.id)&&e.s.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async function Qv(e,t,n){let o=[],r=new AbortController;e.s.webMcpResolveControllers.add(r),e.setStreaming(!0);let s=async c=>{let p=c.toolCall?.name,d=c.toolCall?.id;if(!p||!d)return null;let g=`${t}:${d}`;if(e.s.webMcpInflightKeys.has(g)||e.s.webMcpResolvedKeys.has(g)||Xv(e,c))return null;e.s.webMcpInflightKeys.add(g),o.push(g);let f=$k(e,c),h=c.agentMetadata?.webMcpToolCallId??p;if(p===Xo)return{dedupeKey:g,resumeKey:h,output:Gb(),toolMessage:c,startedAt:f,completedAt:Date.now()};let y=e.s.client.executeWebMcpToolCall(p,c.toolCall?.args,r.signal),v;if(!y)v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{v=await y}catch(C){let A=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));return A||e.s.callbacks.onError?.(C instanceof Error?C:new Error(String(C))),Rd(e,c,gf(A?"Aborted by cancel()":_k(C)),f),e.s.webMcpInflightKeys.delete(g),null}return r.signal.aborted?(Rd(e,c,gf("Aborted by cancel()"),f),e.s.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:h,output:v,toolMessage:c,startedAt:f,completedAt:Date.now()}},i;if(e.s.config.webmcp?.execution==="sequential"){i=[];for(let c of n)i.push(await s(c))}else i=await Promise.all(n.map(s));let l=[];try{if(l=i.filter(g=>g!==null),l.length===0)return;let c={};for(let g of l)c[g.resumeKey]=g.output;let p=await e.s.client.resumeFlow(t,c,{signal:r.signal,after:e.resumeAfter(t)});if(!p.ok){let g=await p.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${p.status}`)}let d=l[0].dedupeKey;for(let g of l){e.s.webMcpResolvedKeys.add(g.dedupeKey);let f=g.toolMessage.toolCall?.name,h=g.toolMessage.agentMetadata?.webMcpToolCallId;Rd(e,g.toolMessage,g.output,g.startedAt,g.completedAt,{...f===Xo?{suggestRepliesResolved:!0}:{},...f&&h?{clientToolAnswer:{toolCallId:h,toolName:f,args:g.toolMessage.toolCall?.args,result:g.output,batch:d}}:{}})}p.body&&await e.s.connectStream(p.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))e.s.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let d of l)Rd(e,d.toolMessage,gf("Aborted by cancel()"),d.startedAt)}finally{for(let c of o)e.s.webMcpInflightKeys.delete(c);e.s.webMcpResolveControllers.delete(r),e.s.webMcpResolveControllers.size===0&&!e.s.abortController&&e.setStreaming(!1)}}async function Uk(e,t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){e.s.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let i=`${n}:__no_tool_id__:${o}`;if(e.s.webMcpInflightKeys.has(i)||e.s.webMcpResolvedKeys.has(i))return;e.s.webMcpInflightKeys.add(i);try{await Vk(e,n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),e.s.webMcpResolvedKeys.add(i)}catch(l){e.s.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{e.s.webMcpInflightKeys.delete(i)}return}let s=`${n}:${r}`;if(!(e.s.webMcpInflightKeys.has(s)||e.s.webMcpResolvedKeys.has(s)||Xv(e,t)))return Qv(e,n,[t])}async function Vk(e,t,n,o,r){let s=await e.s.client.resumeFlow(t,{[n]:o},{signal:r?.signal,after:e.resumeAfter(t)});if(!s.ok){let i=await s.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await e.s.connectStream(s.body,{allowReentry:!0}):e.s.webMcpResolveControllers.size===0&&(e.setStreaming(!1),e.s.abortController=null)}var gf,_k,ff=$e(()=>{"use strict";ea();gf=e=>({isError:!0,content:[{type:"text",text:e}]}),_k=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t});function hf(e){if(!e)return eC;let t={...eC};for(let n of Kk){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var Kk,eC,tC=$e(()=>{"use strict";Kk=["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"],eC={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 rC(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,i=!1,l=null,c=[],p=()=>{for(let H of c.splice(0))try{H()}catch(_){yf("renderHistoryView cleanup",_)}},d=(H,_)=>{for(let V of t){let te=V[H];if(te)try{let W=te(_);if(W)return W}catch(W){yf(H,W)}}return null},g=()=>({presentation:e.getPresentation(),config:n}),f={header:H=>i?d("renderHistoryHeader",Object.freeze({...g(),returnSurface:e.getReturnSurface(),identityStatus:Ir(H.identityStatus),pendingAction:oC(H.pendingAction),copy:Ir(H.copy),actions:Object.freeze({close:v.close,startNewConversation:v.startNewConversation}),defaultRenderer:H.defaultRenderer})):null,conversation:H=>i?d("renderHistoryConversation",Object.freeze({...g(),conversation:nC(H.conversation),active:H.active,pending:H.pending,open:H.open,requestDelete:H.requestDelete,defaultRenderer:H.defaultRenderer})):null,state:H=>i?d("renderHistoryState",Object.freeze({...g(),state:Ir(H.state),identityStatus:Ir(H.identityStatus),copy:Ir(H.copy),...H.retry?{retry:H.retry}:{},...H.startNewConversation?{startNewConversation:H.startNewConversation}:{},defaultRenderer:H.defaultRenderer})):null},h=t.flatMap(H=>(H.railSections??[]).map(_=>({..._,placement:_.placement??"above-conversations",items:[],render:V=>_.render(Object.freeze({collapsed:V,presentation:e.getPresentation(),actions:v}))}))),y=e.createView({slots:f,renderDom:!1,onModelChange:()=>I(),railSections:h}),v=Object.freeze({...y.operations,close:e.close}),C=()=>(i=!0,y.setDomRenderEnabled(!0),y.element),A=H=>Object.freeze({conversations:Object.freeze(H.conversations.map(nC)),activeConversationId:H.activeConversationId,state:Ir(H.state),pendingAction:oC(H.pendingAction),identityStatus:Ir(H.identityStatus),nextCursor:H.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:Ir(y.copy),actions:v,defaultRenderer:C,requestRender:()=>I(),onCleanup:_=>{c.push(_)}}),L=()=>{i=!1;let H=null;for(let V of t)if(V.renderHistoryView){try{H=V.renderHistoryView(A(y.getModel()))}catch(te){yf("renderHistoryView",te),H=null}if(H)break}let _=!H||H.contains(y.element);return i=_,y.setDomRenderEnabled(_),H??y.element};function I(){if(!(!s||o||r)){r=!0;try{p();let H=L();if(H===l)return;let _=l;l=H,e.onElementChanged(H,_)}finally{r=!1}}}return s=!0,I(),{view:y,get element(){return l??y.element},requestRender:I,dispose:()=>{o=!0,p()}}}var yf,Ir,nC,oC,sC=$e(()=>{"use strict";yf=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},Ir=e=>Object.freeze({...e}),nC=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),oC=e=>e?Ir(e):null});var iC,bf,Gk,Od,Bd,Yk,aC,_d,wl,Xk,Qk,lC,Dd=$e(()=>{"use strict";iC=null,bf=()=>{if(iC!==null)return iC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},Gk="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Od=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Bd=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),n=t.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of t)if(r==="mod"||r==="cmd"||r==="ctrl")o.mod=!0;else if(r==="shift")o.shift=!0;else if(r==="alt"||r==="option")o.alt=!0;else return Od("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Od("unsupported",e),null):(n==="space"&&(o.key=" "),o)},Yk=e=>Gk.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),aC=(e,t)=>{let n=Bd(e);if(!n)return"";let o=bf(),r=Yk(n.key);if(!t&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[t?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},_d=e=>aC(e,!1),wl=e=>aC(e,!0),Xk=(e,t)=>t.key?.toLowerCase()===e.key&&(bf()?t.metaKey:t.ctrlKey)===e.mod&&!(bf()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Qk=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},lC=e=>{let t=new Map,n=e?.ownerDocument??(typeof document<"u"?document:null),o=(s,i)=>{if((s.scope??"widget")==="page")return!0;if(!e)return!1;let l=i.composedPath?.();return l?.length?l.includes(e):e.contains(i.target)},r=s=>{if(s.isComposing||!t.size)return;let i=s.composedPath?.()[0]??s.target;for(let l of t.values())if(Xk(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&Qk(i))){s.preventDefault();try{l.run(s)}catch(c){Od(`${l.id} threw on`,l.combo),console.warn(c)}return}};return n?.addEventListener("keydown",r),{register(s){let i=Bd(s.combo);if(!i)return()=>{};let l=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(l);return c?(Od(`${c.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:i}),s.element?.setAttribute("aria-keyshortcuts",wl(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}}});function cC(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Nd(e){return typeof e=="string"?e:void 0}function e0(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?Io(t.text):null;case"image":return typeof t.image=="string"?ef(t.image,{mimeType:Nd(t.mimeType),alt:Nd(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?Fv(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...Nd(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...Nd(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function t0(e,t){let n=cC(t),o=e.map(i=>cC(i.timestamp)),r=new Array(e.length),s=0;for(;s<o.length;){let i=o[s];if(i!==null){r[s]=i,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let c=l-s+1,p=s>0?r[s-1]:null,d=l+1<o.length?o[l+1]:null,g=d!==null&&n!==null?Math.min(d,n):d??n;for(let f=0;f<c;f+=1)r[s+f]=g!==null?g-(c-f):p!==null?p+f+1:Zk+f;s=l+1}return r.map(i=>new Date(i).toISOString())}function dC(e,t){let n=t0(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!Jk.includes(r.role))return;let i=r.role,l=n[s];if(r.displayAvailable===!1){let c={historyDisplayUnavailable:!0};o.push({id:r.id,role:i,content:"",createdAt:l,agentMetadata:c});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:i,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:i,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let c=r.content.map(e0).filter(d=>d!==null),p=Zg(c);o.push({id:r.id,role:i,content:p||(bl(c)?la:""),createdAt:l,...c.length>0&&{contentParts:c}});return}o.push({id:r.id,role:i,content:"",createdAt:l})}),o}function Sl(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 Al(e,t){let n=new Map;for(let o of e)n.set(o.id,o);for(let o of t)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=o.sequence??0,c=r.sequence??0;return l!==c?l-c:o.id.localeCompare(r.id)})}var Jk,Zk,Fd=$e(()=>{"use strict";Hr();Jk=["user","assistant","system"],Zk=0});function r0(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let o=n0.get(e.code)??"unavailable";return new n(o,vf(o),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new n("unavailable",vf("unavailable"))}function pC(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,o=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],r={scopes:o},s=c=>{if(!o.includes(c))throw new t("unsupported_scope",vf("unsupported_scope"))},i=async(c,p)=>{s(c);try{return await p()}catch(d){throw r0(d,e.errors)}},l=c=>{let p=!1;return{conversationId:c.session.conversationId??"",conversationRevision:c.session.conversationRevision??"",async commit(){p||(p=!0,c.commit(),await e.onActivationCommitted(c.session))},discard(){p||(p=!0,c.discard())}}};return{capabilities:r,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(c){return n().subscribeHistoryIdentityStatus(c)},subscribeAvailability(c){return n().subscribeHistoryAvailability(c)},async list(c){return i(c.context.scope,async()=>{let p=await n().listConversations({...c.cursor?{cursor:c.cursor}:{},...c.limit!==void 0?{limit:c.limit}:{},...c.targetId?{targetId:c.targetId}:{},scope:c.context.scope});return{items:p.data,nextCursor:p.nextCursor}})},async getPage(c,p){return i(p.context.scope,async()=>{let d=await n().getConversation(c,{...p.cursor?{messageCursor:p.cursor}:{},scope:p.context.scope}),g=dC(d.messages,{...p.beforeCreatedAt?{beforeCreatedAt:p.beforeCreatedAt}:{}});return{summary:d.summary,messages:Al([],g),conversationRevision:d.conversationRevision??"",nextCursor:d.nextMessageCursor}})},async prepareOpen(c,p){return i(p.context.scope,async()=>l(await n().prepareConversationSession(c)))},async prepareStartNew(c){return i(c.context.scope,async()=>l(await n().prepareNewConversationSession()))},async delete(c,p){await i(p.context.scope,()=>n().deleteConversation(c,{scope:p.context.scope}))},async deleteAll(c){return i(c.context.scope,()=>n().deleteAllConversations({...c.targetId!==void 0?{targetId:c.targetId}:{},scope:c.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var n0,o0,vf,uC=$e(()=>{"use strict";Fd();n0=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"]]),o0=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."]]),vf=e=>o0.get(e)??"Conversation history is unavailable right now."});var $d={};Qs($d,{createHistoryShell:()=>s0});var s0,Cf=$e(()=>{"use strict";tC();sC();Xe();Dd();Lo();uC();s0=e=>{let o=hf(e.config.features?.history?.copy),r=null,s=!1,i=null,l=null,c="conversation",p=null,d=null,g=null,f=null,h=0,y=null,v=null,C=null,A=`persona-history-${Math.random().toString(36).slice(2,8)}`,L=()=>e.historyFeatureEnabled()&&!!r&&!s,I=()=>{let M=e.session.getStatus();return e.isStreaming||M==="paused"||M==="resuming"},H=()=>{let M=e.config.features?.history?.scope;if(M)return M;let N=e.config.getIdentityProof?"verified-user":"browser",ee=r?.capabilities.scopes;return!ee||ee.includes(N)?N:ee[0]??N},_=()=>l?.scope??H(),V=()=>e.session.getClientSession()?.targetId??null,te=M=>`${M.state}:${"reason"in M?M.reason:""}`,W=M=>{let N=te(M);N!==f&&(f=N,e.eventBus.emit("history:identityStatusChanged",{status:M,timestamp:Date.now()}))},j=null,Y=null,E=()=>{if(!e.historyFeatureEnabled())return null;let M=e.getHistoryProviderFactory();if(M)return M();let N=e.config.features?.history?.provider;return N?typeof N!="function"?N:(j!==N&&(j=N,Y=N()),Y):e.session.isClientTokenMode()?pC({errors:e.historyErrors,client:e.session.getClient(),getIdentityProofConfigured:()=>typeof e.config.getIdentityProof=="function",onActivationCommitted:ee=>e.session.bindActivatedSession(ee),getClient:()=>e.session.getClient()}):null},T=()=>{v?.(),v=null,C?.(),C=null,s=!1,r=E();let M={...e.historyInternals};r?M.historyProvider=r:delete M.historyProvider,e.historyInternals=M,e.session.setHistoryInternals(e.historyInternals),r&&(v=r.subscribeAvailability?.(N=>{s=!N,N||Sn({restoreFocus:!1}),$n()})??null,C=r.subscribeIdentityStatus(N=>W(N)),f=te(r.getIdentityStatus()))},B=()=>{let M=e.config.features?.history?.presentation??"panel";if(M==="panel"||M==="auto"&&!(!e.launcherEnabled||e.isDockedMountMode(e.config)))return"panel";let N=e.artifactSplitRoot??e.container;return(N.getBoundingClientRect().width||N.clientWidth)>=720?"rail":"panel"},P=(M,N)=>{N?(M.setAttribute("aria-hidden","true"),M.setAttribute("inert","")):(M.removeAttribute("aria-hidden"),M.removeAttribute("inert"))},Q="data-persona-history-suppressed",U=null,de=null,pe=null,ge=null,ke=null,xe="",Le=()=>e.header===ke?xe:e.config.layout?.showHeader===!1?"none":"",mt=()=>e.historyPresentation==="panel"&&!!pe&&ge===pe.element&&e.config.layout?.showHeader!==!1&&Le()!=="none",Ve=()=>{for(let M of Array.from(e.header.children))M!==U&&M.setAttribute(Q,"")},Re=()=>{for(let M of Array.from(e.container.querySelectorAll(`[${Q}]`)))M.removeAttribute(Q)},$=()=>{let M=pe;if(!M)return;if(Array.from(e.header.children).some(ce=>ce!==U&&!ce.hasAttribute(Q))){de&&de!==e.header&&(de.style.removeProperty("min-height"),de=null);let ce=e.header.offsetHeight;ce>0&&(e.header.style.minHeight=`${ce}px`,de=e.header)}U||(U=x("div","persona-history-header-host")),M.setHeaderPlacement("external");let ee=M.getHeaderElement();ee.parentNode!==U&&U.replaceChildren(ee),U.parentNode!==e.header&&e.header.appendChild(U),Ve()},We=()=>{de&&(de.style.removeProperty("min-height"),de=null),U&&(pe?.setHeaderPlacement("inline"),U.remove(),U=null,Re())},me=null,dt=()=>{if(me){if(e.body.style.display="none",P(e.body,!0),e.footer.hidden=!0,P(e.footer,!0),mt()){$(),e.header.style.display=Le(),P(e.header,!1);return}We(),e.header.style.display="none",P(e.header,!0)}};e.reapplyHistoryHostChrome=dt;let Qt=M=>{let N=e.body.style.display,ee=e.footer.hidden,ce=e.footer,He=e.header,Nt=e.header.style.display;ke=He,xe=Nt,me=()=>{me=null,We(),ke=null,e.body.style.display=N,P(e.body,!1),ce.hidden=ee,P(ce,!1),e.footer!==ce&&(e.footer.hidden=!1,P(e.footer,!1)),He.style.display=Nt,P(He,!1),e.header!==He&&(e.header.style.display=e.config.layout?.showHeader===!1?"none":"",P(e.header,!1))},e.footer.parentNode?.insertBefore(M,e.footer),dt()},St=null,Se=null,It=null,yt=null,Pe=()=>[e.header,e.panelElements.closeButtonWrapper,e.panelElements.clearChatButtonWrapper,e.body,e.footer],Ke=52,D=()=>e.config.features?.history?.rail?.collapsible!==!1,S=()=>e.config.features?.history?.rail?.side==="right"?"right":"left",F=200,z=400,K=M=>Math.min(z,Math.max(F,Math.round(M))),Z=()=>e.config.features?.history?.rail?.resizable===!0,ye,be=()=>{if(ye===void 0&&(ye=null,e.config.persistState!==!1))try{let M=Number(window.localStorage.getItem(`${e.currentKeyPrefix()}rail-width`));M&&(ye=M)}catch{}return ye},Ae=()=>K(be()??e.config.features?.history?.rail?.width??260),tt=M=>{if(ye=M,e.config.persistState!==!1)try{window.localStorage.setItem(`${e.currentKeyPrefix()}rail-width`,String(M))}catch{}},bt=()=>D()&&e.config.features?.history?.rail?.collapsedBehavior==="overlay",Be=!1,Ge=M=>{let N=x("img");return N.src=M,N.alt="",N.setAttribute("aria-hidden","true"),N},cn=()=>{let M=e.config.features?.history?.rail?.brand;if(!M)return;let N=!1,ee;return ce=>{if(M.render)try{return M.render({collapsed:ce})??null}catch(He){return N||(N=!0,console.warn("[persona] history rail brand threw",He)),null}return ee===void 0&&(M.iconUrl?ee=Ge(M.iconUrl):ee=M.icon?e.renderLucideIcon(M.icon,20):null),ee?ee.cloneNode(!0):null}},vo=()=>e.config.features?.history?.rail?.sections?.map(M=>{let N=!1,ee=ce=>{N||(N=!0,console.warn("[persona] history rail section threw",M.id,ce))};return{id:M.id,title:M.title,placement:M.placement??"above-conversations",items:M.items.map(ce=>{let He;return{id:ce.id,label:ce.label,badge:ce.badge,iconNode:()=>{if(He!==void 0)return He;try{ce.renderIcon?He=ce.renderIcon()??null:ce.iconUrl?He=Ge(ce.iconUrl):He=ce.icon?e.renderLucideIcon(ce.icon,20):null}catch(Nt){ee(Nt),He=null}return He},onSelect:()=>{try{ce.onSelect()}catch(Nt){ee(Nt)}}}})}})??[],ut=M=>{let N=vo();for(let ee of M)N.some(ce=>ce.id===ee.id)?console.warn("[persona] duplicate history rail section id",ee.id):N.push(ee);return N.length?N:void 0},ht=null,Dt=()=>`${e.currentKeyPrefix()}rail-collapsed`,hi=()=>{if(ht===null&&(ht=e.config.features?.history?.rail?.defaultCollapsed===!0,e.config.persistState!==!1))try{let M=window.localStorage.getItem(Dt());M&&(ht=M==="1")}catch{}return ht},nn=M=>{if(ht=M,e.config.persistState!==!1)try{window.localStorage.setItem(Dt(),M?"1":"0")}catch{}},Cn=()=>e.historyPresentation==="rail"&&D()&&!bt()&&hi(),ro=()=>{},yi=()=>{if(bt()){ro();return}nn(!hi()),i?.view.setCollapsed(Cn()),e.applyRailChrome(),e.repinAnchoredMessage()},bi=()=>{let M=e.config.features?.history?.rail?.collapseShortcut;return!M||!Bd(M)?null:{combo:M,hint:_d(M),aria:wl(M)}},Ia=300,rr="var(--persona-history-overlay-margin,8px)",dn=null,Nn=null,sr=0,Fn=null,ir=null,Oo=!1,_r=0,Jl=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Kn=()=>L()&&bt()&&(e.historyPresentation??B())==="rail",nh=()=>e.historyVisible&&!Be,ar=()=>{ir!==null&&clearTimeout(ir),ir=null},As=()=>{e.loadHistoryView().catch(()=>{})},Pn=()=>{ar(),Be&&(ir=setTimeout(()=>{ir=null,!(Oo||!Be)&&(Fn?.contains(document.activeElement)||Sn({restoreFocus:!1}))},Ia))},Ye=(M,N)=>{let ee=Fn?.getBoundingClientRect();if(!ee)return!1;let ce=dn?.getBoundingClientRect(),He=ce?Math.min(ce.top,ee.top):ee.top;return M>=ee.left&&M<=ee.right&&N>=He&&N<=ee.bottom||!!ce&&M>=ce.left&&M<=ce.right&&N>=ce.top&&N<=ce.bottom},we=M=>{Be&&(Oo=Ye(M.clientX,M.clientY),Oo?ar():ir===null&&Pn())},Gt=M=>{e.historyVisible||!Kn()||(Be=!0,qe({invoker:dn,keyboard:M?.keyboard===!0}).then(()=>{e.historyVisible?!Oo&&document.activeElement!==dn&&Sn():Be=!1}))},Qe=()=>{let M=ge?.querySelector('[data-persona-history-focus="collapse"]');M&&(M.setAttribute("aria-label",Be?o.expandLabel:o.collapseLabel),M.setAttribute("aria-expanded",Be?"false":"true"))},ve=()=>{nn(!1);let M=i;if(!Be||!M){qe({invoker:dn});return}let N=document.activeElement===dn;Be=!1,vi(),M.element.remove(),Pt(M.element),Qe(),N&&gt(),e.repinAnchoredMessage(),$n()},se=()=>{nn(!0),Sn()};ro=()=>{!e.historyVisible||Be?ve():se()};let Me=()=>{let M=bi(),N=e.createHeaderIconButton({ariaLabel:o.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":A,...M?{"aria-keyshortcuts":M.aria}:{}}}),ee=N.button;ee.addEventListener("mouseenter",()=>{Oo=!0,ar(),!(Jl()||Date.now()<_r)&&Gt()}),ee.addEventListener("mouseleave",()=>{Oo=!1,_r=0,Pn()}),ee.addEventListener("focus",()=>{e.historyVisible||As()}),ee.addEventListener("click",ce=>{L()&&(ce.detail!==0&&Jl()&&!e.historyVisible?Gt():ve())}),dn=ee,Nn=N.wrapper},lr=()=>{if(Nn&&!Nn.isConnected&&(Nn=null,dn=null),!Kn()){Nn?.remove(),Nn=null,dn=null;return}dn||Me();let M=Nn,N=dn;if(!M||!N)return;let ee=S()!=="right"?e.header.firstChild:null;(ee??e.header.lastChild)!==M&&e.header.insertBefore(M,ee),M.style.display=nh()||sr>0?"none":"",N.setAttribute("aria-label",o.expandLabel),N.setAttribute("aria-expanded",e.historyVisible?"true":"false"),Fn&&e.applyRailChrome()},Dr=M=>{if(!Be)return;let N=M.target;N instanceof Node&&(Fn?.contains(N)||Nn?.contains(N)||N instanceof Element&&N.closest('.persona-dropdown-menu,[role="alertdialog"]')||Sn({restoreFocus:!1}))};document.addEventListener("pointerdown",Dr,!0),e.destroyCallbacks.push(()=>{document.removeEventListener("pointerdown",Dr,!0),document.removeEventListener("pointermove",we),ae?.(),ar()});let so=null,ae=null,Ee=16,wn=M=>{tt(K(M)),e.applyRailChrome(),e.repinAnchoredMessage()},nt=()=>{let M=x("div","persona-rail-resizer");return M.tabIndex=0,M.setAttribute("role","separator"),M.setAttribute("aria-orientation","vertical"),M.setAttribute("aria-valuemin",String(F)),M.setAttribute("aria-valuemax",String(z)),M.addEventListener("pointerdown",N=>{let ee=Se;if(!ee||N.button!==0)return;N.preventDefault(),ae?.();let ce=N.clientX,He=ee.getBoundingClientRect().width||Ae(),Nt=S()==="right"?-1:1,Rt=He,Wt=e.mount.ownerDocument;ee.style.transition="none";let Ue=he=>{Rt=K(He+Nt*(he.clientX-ce)),ee.style.flex=`0 0 ${Rt}px`,M.setAttribute("aria-valuenow",String(Rt))},st=()=>{ae=null,Wt.removeEventListener("pointermove",Ue),Wt.removeEventListener("pointerup",st),Wt.removeEventListener("pointercancel",st),ee.style.removeProperty("transition");try{M.releasePointerCapture(N.pointerId)}catch{}wn(Rt)};ae=st,Wt.addEventListener("pointermove",Ue),Wt.addEventListener("pointerup",st),Wt.addEventListener("pointercancel",st);try{M.setPointerCapture(N.pointerId)}catch{}}),M.addEventListener("keydown",N=>{let ee=S()==="right"?-Ee:Ee,ce=Ae(),He=N.key==="ArrowRight"?ce+ee:N.key==="ArrowLeft"?ce-ee:N.key==="Home"?F:N.key==="End"?z:null;He!==null&&(N.preventDefault(),wn(He))}),M},Jt=(M,N)=>{if(!Z()||Cn()){ae?.(),so?.remove();return}let ee=so??nt();so=ee,ee.setAttribute("aria-label",o.resizeLabel),ee.setAttribute("aria-valuenow",String(Ae())),ee.nextElementSibling!==N&&M.insertBefore(ee,N)};e.applyRailChrome=()=>{i?.view.setRailSide(S());let M=S()==="right",N=Fn;if(N){let Wt=dn?dn.getBoundingClientRect().bottom-e.container.getBoundingClientRect().top:0;N.style.top=`calc(${Math.max(0,Math.round(Wt))}px + ${rr})`,N.style.width=`${Ae()}px`,N.style.left=M?"":rr,N.style.right=M?rr:""}let ee=Se,ce=St,He=It;if(!ee||!ce||!He)return;ee.style.flex=`0 0 ${Cn()?Ke:Ae()}px`;let Nt="1px solid var(--persona-divider,#e5e7eb)";ee.style.borderRight=M?"":Nt,ee.style.borderLeft=M?Nt:"";let Rt=M?He:ee;ce.firstElementChild!==Rt&&ce.append(Rt,M?ee:He),Jt(ce,M?ee:He)};let Zl=M=>{if(yt&&Se){yt.replaceWith(M),yt=null,e.applyRailChrome();return}let N=x("div","persona-history-rail-shell");N.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let ee=x("div","persona-history-rail-conversation");ee.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let ce=x("div","persona-history-rail-host");ce.style.cssText="display:flex;min-height:0;overflow:hidden",e.container.insertBefore(N,e.header.parentNode===e.container?e.header:e.body);for(let He of Pe())He?.parentNode===e.container&&ee.appendChild(He);N.append(ce,ee),ce.appendChild(M),St=N,Se=ce,It=ee,e.applyRailChrome()},Ln=()=>{if(St)return;let M=x("div","persona-history-rail-placeholder");M.style.cssText="flex:1 1 auto;min-height:0",yt=M,Zl(M),e.repinAnchoredMessage()},ec=()=>{yt&&(vi(),e.repinAnchoredMessage())},Qp=M=>{let N=x("div","persona-history-rail-overlay");N.style.cssText=`position:absolute;bottom:${rr};display:flex;overflow:hidden;z-index:${na-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(M),document.addEventListener("pointermove",we),Fn=N,e.applyRailChrome(),Qe()},vi=()=>{me?.(),Fn&&(Oo&&(_r=Date.now()+150),document.removeEventListener("pointermove",we),Fn.remove(),Fn=null);let M=St;if(M){ae?.();for(let N of Pe())N&&M.contains(N)&&e.container.insertBefore(N,M);M.remove(),St=null,Se=null,It=null,yt=null}},je=M=>{ge=M,M.id=A,M.style.flex="1 1 auto",M.style.minHeight="0"},Pt=M=>{je(M),(e.historyPresentation!=="rail"||Be)&&ec(),e.historyPresentation!=="rail"?Qt(M):Be?Qp(M):Zl(M)},Bo=()=>{if(lr(),Fr(),!e.historyVisible||!i)return;let M=B();if(M===e.historyPresentation)return;let N=document.activeElement,ee=N instanceof HTMLElement&&(i.element.contains(N)||U?.contains(N)===!0)?N:null;vi(),i.element.remove(),i.view.setHeaderPlacement("inline"),e.historyPresentation=M,i.view.setPresentation(M),i.view.setCollapsed(Cn()),i.requestRender(),i.element.isConnected||Pt(i.element),ee?.isConnected?ee.focus():gt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),$n()},_o=(M,N)=>U?.querySelector(N)??M.querySelector(N),gt=()=>{let M=i?.element??ge;if(!M)return;let N=_o(M,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(N){N.focus();return}let ee=_o(M,".persona-history-title")??M;ee.tabIndex=-1,ee.focus()},qe=async M=>{if(!L()||e.historyVisible)return;let N=r;if(!N)return;if(!Be&&Kn()&&hi()){lr();return}Ci();let ee=++h;c=M?.returnSurface??"conversation",p=M?.invoker??d;let ce=Kn()&&!Be;ce&&(sr+=1,lr(),Ln());let He;try{He=await e.loadHistoryView()}catch{e.announceHistory(o.openHistoryLabel),ce&&(sr-=1,ee===h&&(ec(),lr()));return}if(ce&&(sr-=1),ee!==h||e.historyVisible)return;l={scope:H()},e.historyPresentation=B(),e.historyVisible=!0;let Nt=e.historyPresentation==="panel"&&e.config.layout?.showHeader!==!1&&e.header.style.display!=="none"?"external":"inline",Rt=e.config.features?.history?.rowAvatar,Wt=bi(),Ue=Wt?{hint:Wt.hint,aria:Wt.aria}:null,st={provider:N,context:l,targetId:V(),presentation:e.historyPresentation,collapsible:D(),collapsed:Cn(),railSide:S(),renderRailHeader:e.config.features?.history?.rail?.renderHeader,railBrand:cn(),onToggleCollapse:yi,...Ue?{collapseShortcut:Ue}:{},headerPlacement:Nt,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:Rt===!1?!1:typeof Rt=="string"?Rt: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:he=>An(he,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:he=>e.setActiveConversationSummary(he),attachTooltip:e.attachTooltip,onStartNew:()=>Co({focusComposer:!0}),onClose:()=>Sn(),onRequestDeleteConversation:he=>$t(he),onRequestClearHistory:()=>Ts(),...N.resetDevice?{onRequestResetIdentity:()=>Oa()}:{}};i=rC({plugins:e.plugins,config:e.config,getPresentation:()=>e.historyPresentation??"panel",getReturnSurface:()=>c,close:()=>Sn(),createView:({slots:he,renderDom:Si,onModelChange:io,railSections:dr})=>(pe=He.createHistoryView({...st,railSections:ut(dr),slots:he,renderDom:Si,onModelChange:io,onAnnounce:e.announceHistory}),pe),onElementChanged:(he,Si)=>{if(!Si?.isConnected)return Pt(he);je(he),Si.replaceWith(he),dt()}}),i.view.setNewConversationRequired(e.historySessionState.recovery==="new_conversation_required"),M?.focus!==!1&&(e.historyPresentation!=="rail"||M?.keyboard===!0)&&gt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),$n(),e.eventBus.emit("history:opened",{presentation:e.historyPresentation,returnSurface:c,timestamp:Date.now()})},Ci=()=>{},Sn=M=>{if(!e.historyVisible)return;h+=1;let N=c,ee=p,ce=i,He=M?.restoreFocus!==!1;e.historyVisible=!1;let Nt=!1,Rt=null,Wt=()=>{if(!Nt){if(Nt=!0,Ci=()=>{},Rt!==null&&clearTimeout(Rt),Be=!1,ar(),vi(),ce?.dispose(),ce?.view.destroy(),ce?.element.remove(),i===ce&&(i=null,pe=null,ge=null,e.historyPresentation=null,l=null,p=null),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),$n(),He){let st=ee??d;st?.isConnected?st.focus():e.maybeFocusInput()}e.eventBus.emit("history:closed",{returnSurface:N,timestamp:Date.now()})}},Ue=ce&&ce.element===ce.view.element?ce.view.playExit():null;if(!Ue){Wt();return}Ci=Wt,Rt=setTimeout(Wt,250),Ue.then(Wt)},xs=M=>{if(!(M.key!=="Escape"||!e.historyVisible||!i)){if(e.historyPresentation==="rail"){let N=M.target;if(!(N instanceof Node)||!(i.element.contains(N)||Be&&Nn?.contains(N)===!0))return}M.preventDefault(),M.stopPropagation(),Sn()}};e.container.addEventListener("keydown",xs),e.destroyCallbacks.push(()=>e.container.removeEventListener("keydown",xs));let Hn=0,tc=250,fe=null,pn=()=>{fe&&clearTimeout(fe),fe=null};e.destroyCallbacks.push(pn);let kt=()=>{pn();let M=e.conversationOpenPendingEl;M&&(e.conversationOpenTakeover=!0,M.hidden=!1,e.messagesWrapper.style.display="none",e.updateWelcome())},on=()=>{Hn+=1,pn(),e.conversationOpenPendingEl&&(e.conversationOpenPendingEl.remove(),e.conversationOpenPendingEl=null,e.conversationOpenTakeover=!1,e.messagesWrapper.style.removeProperty("display"),P(e.footer,!1),e.updateWelcome())},At=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;e.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},un=(M,N)=>X("div",{className:Wn("persona-conversation-loading-bubble",N&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:M}}),nc=()=>X("div",{className:"persona-conversation-loading-body"},un("58%",!1),un("72%",!0),un("44%",!1)),Nr=M=>{e.conversationOpenPendingEl?.remove(),e.conversationOpenPendingEl=M,M.hidden=!e.conversationOpenTakeover,e.body.insertBefore(M,e.messagesWrapper),pn(),e.conversationOpenTakeover||(fe=setTimeout(kt,tc)),P(e.footer,!0)},Jp=()=>{let M={config:e.config,streaming:!1,location:"conversation-open",defaultRenderer:nc},N=null,ee=e.plugins.find(ce=>ce.renderLoadingIndicator);ee?.renderLoadingIndicator&&(N=ee.renderLoadingIndicator(M)),N===null&&e.config.loadingIndicator?.render&&(N=e.config.loadingIndicator.render(M)),Nr(X("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":o.openConversationLoadingLabel}},N??nc()))},Zp=M=>{let N=()=>{An(M,{focusComposer:!0}).catch(()=>{})},ee=L()?()=>{on(),qe()}:void 0,ce=(Wt,Ue)=>{let st=X("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:Wt});return st.addEventListener("click",Ue),st},He=()=>X("div",{className:"persona-conversation-loading-error-body"},X("p",{className:"persona-conversation-loading-error-title",text:o.openConversationErrorTitle}),X("div",{className:"persona-conversation-loading-error-actions"},ce(o.openConversationRetryLabel,N),ee?ce(o.openConversationBackLabel,ee):null)),Nt=Object.freeze({conversationId:M,config:e.config,copy:Object.freeze({title:o.openConversationErrorTitle,retryLabel:o.openConversationRetryLabel,backLabel:o.openConversationBackLabel}),retry:N,...ee?{back:ee}:{},defaultRenderer:He}),Rt=null;for(let Wt of e.plugins)if(Wt.renderHistoryOpenError){try{Rt=Wt.renderHistoryOpenError(Nt)}catch(Ue){console.warn("[persona] renderHistoryOpenError threw",Ue),Rt=null}if(Rt)break}Nr(X("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},Rt??He())),kt()};e.eventBus.on("history:closed",()=>{e.conversationOpenPendingEl&&P(e.footer,!0)});let An=async(M,{focusComposer:N=!1}={})=>{let ee=_(),ce=!!i;i?.view.setActiveConversationId(M),on();let He=Hn;Jp(),e.historyVisible&&(e.historyPresentation==="panel"||Be)&&Sn({restoreFocus:!1}),e.suppressScrollSend=!0;try{await e.session.openConversation(M,{scope:ee})}catch(Nt){throw He===Hn&&Zp(M),Nt}finally{e.suppressScrollSend=!1}He===Hn&&(on(),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.restoreScrollPosition()||e.jumpToBottomInstant(),At(),Yt(),ce||e.setActiveConversationSummary(null),e.eventBus.emit("history:conversationOpened",{conversationId:M,title:e.activeConversationTitle,scope:ee,timestamp:Date.now()}),N&&e.maybeFocusInput())},Co=async({focusComposer:M=!1}={})=>{on(),await e.session.startNewConversation({scope:_()}),e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.jumpToBottomInstant(),Yt();let N=e.session.getActiveConversationId();i?.view.setActiveConversationId(N),e.eventBus.emit("history:conversationStarted",{conversationId:N,timestamp:Date.now()}),e.historyVisible&&(e.historyPresentation==="panel"||Be)&&Sn({restoreFocus:!1}),M&&e.maybeFocusInput()},Ms=async(M,N)=>{let ee=await e.session.updateConversation(M,{...N,...N.title!==void 0?{title:N.title.trim()}:{}});return i?.view.applyConversationSummary(ee),!i&&M===e.session.getActiveConversationId()&&e.setActiveConversationSummary(ee),ee},oc=async M=>{let N=_(),ee=e.session.getActiveConversationId()===M;await e.session.deleteConversation(M,{scope:N}),i?.view.removeConversationSummary(M),ee&&(e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Yt()),e.eventBus.emit("history:conversationDeleted",{conversationId:M,scope:N,wasActive:ee,timestamp:Date.now()})},Ra=async M=>{let N=M?.scope??_(),ee=M?.allTargets?null:M?.targetId??V(),ce=await e.session.clearConversationHistory({...ee?{targetId:ee}:{},scope:N});return e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Yt(),e.eventBus.emit("history:cleared",{deleted:ce.deleted,scope:N,targetId:ee,timestamp:Date.now()}),ce},Wa=async()=>{if(!r?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let M=!1;try{M=(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 N=e.storageAdapter;N?.clear&&e.runStorageMutation(()=>N.clear(),"[AgentWidget] Failed to clear storage adapter:"),e.resetAnchorState(),e.resumeAutoScroll(),Yt(),Sn({restoreFocus:!1}),e.maybeFocusInput(),e.open||e.launcherSurfaceInstance?.launcher.element.focus()}return e.announceHistory(M?o.identityResetNotice:o.identityResetUnconfirmedNotice),e.eventBus.emit("history:identityReset",{remoteRevocationConfirmed:M,timestamp:Date.now()}),{remoteRevocationConfirmed:M}},wi=()=>e.artifactSplitRoot?e.panel:e.container,Es=async M=>{let N=await e.loadHistoryView().catch(()=>null);return typeof N?.showHistoryConfirm=="function"?N.showHistoryConfirm(M):window.confirm(`${M.title}
6
+ `);l=F.pop()??"";for(let q of F){let K=q.split(`
7
+ `),Z="message",ye="",xe=null;for(let Ye of K)Ye.startsWith("event:")?Z=Ye.replace("event:","").trim():Ye.startsWith("data:")?ye+=Ye.replace("data:","").trim():Ye.startsWith("id:")&&(xe=Ye.slice(3).trim());let be=()=>{xe!==null&&xe!==""&&n({type:"cursor",id:xe})};if(!ye){be();continue}let ot;try{ot=JSON.parse(ye)}catch(Ye){n({type:"error",error:Ye instanceof Error?Ye:new Error("Failed to parse chat stream payload")});continue}let bt=ot!==null&&typeof ot=="object"&&!Array.isArray(ot)?ot:null,_e=Z!=="message"?Z:typeof bt?.type=="string"?bt.type:"message";if(e.onSSEEvent?.(_e,ot),e.parseSSEEvent){C.current=y;let Ye=await jk(e,ot,n,C,h,d,A);if(C.current&&C.current!==y&&(y=C.current),Ye){be();continue}}bt&&(me.push({...bt,type:_e}),dt()),be()}}dt()}var sv,Bg=$e(()=>{"use strict";ei();Yi();ss();rv();sv=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<")});var dv,cv=$e(()=>{dv="4.28.0"});var Zn,oa=$e(()=>{"use strict";cv();Zn=dv});var ud={};Qs(ud,{deleteAllConversations:()=>sP,deleteConversation:()=>rP,finalizeDisplayProjections:()=>oP,getConversation:()=>nP,historyErrorFor:()=>bv,listConversations:()=>tP,readErrorCode:()=>Ng,recoverFromUnauthorized:()=>yv,resetVisitor:()=>iP});function Xk(e,t,n){let o=new URLSearchParams;for(let[s,i]of Object.entries(n))i===void 0||i===""||o.set(s,String(i));let r=o.toString();return`${e.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}function Qk(e,t){if(t)return t;let n=e.config.features?.history?.scope;return n||(e.config.getIdentityProof?"verified-user":"browser")}async function Jk(e,t,n){let o=e.config.getIdentityProof;if(!o)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&e.setHistoryIdentityStatus({state:"identity_provider_failed"}),new e.HistoryClientError("identity_provider_failed","The identity proof provider failed")}if(r)return r;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 Zk(e,t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await e.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new e.HistoryClientError("proof_not_admitted",gv);return r}async function Ng(e,t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async function yv(e,t,n,o){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new e.HistoryClientError("invalid_identity_proof",fv);if(r.includes("visitor token required"))throw new e.HistoryClientError("visitor_token_missing",mv);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new e.HistoryClientError("visitor_identity_mismatch",hv);return e.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError("unauthorized",t||"History request was not authorized")}async function bv(e,t,n){let o=await Ng(e,t);if(t.status===404)return new e.HistoryClientError("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new e.HistoryClientError("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&o.includes("identity_proof_not_admitted"))return n&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new e.HistoryClientError("proof_not_admitted",gv);if(t.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&e.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new e.HistoryClientError("invalid_identity_proof",fv)):r.includes("visitor token required")?new e.HistoryClientError("visitor_token_missing",mv):r.includes("visitor_identity_mismatch")?new e.HistoryClientError("visitor_identity_mismatch",hv):new e.HistoryClientError("unauthorized",o||"History request was not authorized")}return new e.HistoryClientError("request_failed",o||`History request failed (${t.status})`)}function eP(e,t,n,o){let r=t?.toLowerCase()??null;if(n){if(r==="admitted"){o&&e.setHistoryIdentityStatus({state:"verified"});return}throw o&&e.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="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(r==="admitted")throw new e.HistoryClientError("identity_contract_violation","Server admitted an identity proof that was never sent");o&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function ra(e,t,n){Fg(e);let o=n.trackIdentity!==!1,r=await e.initSession(),s=null;Qk(e,n.scope)==="verified-user"&&(s=await Jk(e,r,o),s&&(r=await Zk(e,r,s,o)));let i=e.historyInternals.visitorStore,l=!1;for(;;){let c=i?.revision()??0,p=await e.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new e.HistoryClientError("visitor_token_missing","No visitor credential is stored for this browser");let d=await fetch(Xk(e,t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Zn,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(d.status===401&&!l){l=!0,r=await yv(e,await Ng(e,d),s,o);continue}if(!d.ok)throw await bv(e,d,o);let g=d.headers.get("X-History-Identity-Status"),f=await d.json().catch(()=>{});if(i&&i.revision()!==c)throw new e.HistoryClientError("credential_changed","The visitor credential changed while the request was in flight");return eP(e,g,s!==null,o),f}}function Fg(e){if(!e.isClientTokenMode())throw new 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 tP(e,t){let n=await ra(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(uv),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async function nP(e,t,n){let o=await ra(e,`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:uv(o),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async function oP(e,t,n){Fg(e);let o=0;for(let c of n){let p=c.displayContent.length;if(p>pv)throw new e.HistoryClientError("payload_too_large",`displayContent exceeds the ${pv} character limit`);o+=p}if(o>Dg)throw new e.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${Dg} character limit`);await e.initSession();let r=e.historyInternals.visitorStore,s=r?.revision()??0,i=await ra(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=Dg,trackIdentity:!1}),l=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return l&&e.clientSession?.conversationId===t&&(r?.revision()??0)===s&&e.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async function rP(e,t,n){let o=await ra(e,`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async function sP(e,t){let n=await ra(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 iP(e){Fg(e),e.setHistoryIdentityStatus({state:"resetting"});try{await ra(e,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var pv,Dg,uv,gv,fv,mv,hv,$g=$e(()=>{"use strict";oa();pv=32768,Dg=49152,uv=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:""}},gv="The identity proof was not admitted; account history is unavailable",fv="The identity proof was rejected",mv="The request carried no visitor credential",hv="The stored visitor belongs to a different signed-in user"});var Cv,wv=$e(()=>{"use strict";gl();Cv=e=>{let{mount:t,overlay:n,sessionRef:o}=e,r=(d,g,f)=>{let h=g.trim();if(!h||!o.current)return;let y=d.getAttribute("data-tool-call-id")??"",b=f.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:y,answer:h,answers:f.structured,values:f.values??(f.source==="multi"?h.split(", "):[h]),isFreeText:b,source:f.source},bubbles:!0,composed:!0})),cs(n,y);let C=o.current.getMessages().find(A=>A.toolCall?.id===y);C?.agentMetadata?.awaitingLocalTool?o.current.resolveAskUserQuestion(C,f.structured??h):o.current.sendMessage(h)},s=d=>{let g=o.current;if(!g)return;let f=d.getAttribute("data-tool-call-id")??"",h=g.getMessages().find(y=>y.toolCall?.id===f);h&&g.persistAskUserQuestionProgress(h,{answers:ad(d,h),currentIndex:bo(d)})},i=d=>Object.entries(d).map(([g,f])=>`${g}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),l=d=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=bo(d),f=Ji(d);if(g>=f-1)return;let h=o.current?.getMessages().find(y=>y.toolCall?.id===d.getAttribute("data-tool-call-id"));h&&(ld(d,h,e.config(),g+1),s(d))};return{click:d=>{let f=d.target.closest("[data-ask-user-action]");if(!f)return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;let y=f.getAttribute("data-ask-user-action");if(d.preventDefault(),d.stopPropagation(),y==="dismiss"){let b=h.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:b},bubbles:!0,composed:!0})),cs(n,b);let C=o.current?.getMessages().find(A=>A.toolCall?.id===b);C?.agentMetadata?.awaitingLocalTool&&(o.current?.markAskUserQuestionResolved(C),o.current?.resolveAskUserQuestion(C,"(dismissed)"));return}if(y==="pick"){let b=f.getAttribute("data-option-label");if(!b)return;let C=h.getAttribute("data-multi-select")==="true",A=ls(h);if(A&&C){let L=ni(h)[bo(h)],I=new Set(Array.isArray(L)?L:[]);I.has(b)?I.delete(b):I.add(b),ds(h,Array.from(I)),s(h);return}if(A){ds(h,b),s(h),l(h);return}if(C){let L=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",L?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!L);let I=h.querySelector('[data-ask-user-action="submit-multi"]');I&&(I.disabled=Wg(h).length===0);return}r(h,b,{source:"pick",values:[b]});return}if(y==="submit-multi"){let b=Wg(h);if(b.length===0)return;r(h,b.join(", "),{source:"multi",values:b});return}if(y==="open-free-text"){let b=h.querySelector('[data-ask-free-text-row="true"]');b&&(b.classList.remove("persona-hidden"),b.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(y==="focus-free-text"){h.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(y==="submit-free-text"){let C=h.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!C.trim())return;if(ls(h)){ds(h,C.trim()),s(h),l(h);return}r(h,C,{source:"free-text"});return}if(y==="next"||y==="back"){if(!o.current)return;let b=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(B=>B.toolCall?.id===b);if(!C)return;let L=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(L){let B=ni(h)[bo(h)];(typeof B!="string"||B!==L)&&ds(h,L)}let I=y==="next"?1:-1,H=bo(h)+I;ld(h,C,e.config(),H),s(h);return}if(y==="submit-all"){if(!o.current)return;let b=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(B=>B.toolCall?.id===b);if(!C)return;let L=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";L&&ds(h,L);let I=ad(h,C);o.current.persistAskUserQuestionProgress(C,{answers:I,currentIndex:bo(h)});let H=i(I);r(h,H||"(submitted)",{source:"submit-all",structured:I});return}if(y==="skip"){if(!o.current)return;let b=h.getAttribute("data-tool-call-id")??"",C=o.current.getMessages().find(V=>V.toolCall?.id===b);if(!C)return;let A=ls(h),L=bo(h),I=Ji(h),H=L>=I-1;if(!A){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:b},bubbles:!0,composed:!0})),cs(n,b),C.agentMetadata?.awaitingLocalTool&&(o.current.markAskUserQuestionResolved(C),o.current.resolveAskUserQuestion(C,"(dismissed)"));return}ds(h,"");let B=h.querySelector('[data-ask-free-text-input="true"]');if(B&&(B.value=""),H){let V=ad(h,C),te=i(V);r(h,te||"(skipped)",{source:"submit-all",structured:V});return}ld(h,C,e.config(),L+1),s(h);return}},keydown:d=>{if(d.key!=="Enter")return;let f=d.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;d.preventDefault();let y=f.value;if(y.trim()){if(ls(h)){ds(h,y.trim()),s(h),l(h);return}r(h,y,{source:"free-text"})}}}}});function cP(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
8
+ `:o===""||Sv.test(o)}function dP(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let i=e[s];if(i===n)return cP(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(i===`
9
+ `||i==="\uFFFC"||!r&&Sv.test(i))return null;s--}return null}function Av(e,t,n){for(let o of n){let r=dP(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function xv(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}var Sv,Ev=$e(()=>{"use strict";Sv=/\s/});function Mv(e){let t={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},n=(e.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[t,...n]}var Tv=$e(()=>{"use strict"});var gd=$e(()=>{"use strict"});function Hv(e){e.delayMs!==void 0&&(kv=md(e.delayMs)),e.skipDelayMs!==void 0&&(Pv=md(e.skipDelayMs))}function Iv(e){fd.get(e)?.hide()}function yn(e){fd.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:i=pP,viewportPadding:l=uP}=e,c=()=>t.ownerDocument,p=()=>c().defaultView??window,d=null,g=null,f=null,h=null,y,b=!1,C=!1,A=!1,L=()=>(typeof o=="function"?o():o).trim(),I=()=>(typeof r=="function"?r():r??"").trim(),H=()=>md(e.delayMs??kv),B=()=>md(e.skipDelayMs??Pv),V=()=>{y!==void 0&&(p().clearTimeout(y),y=void 0)},te=()=>{V();let ge=d!==null;h?.(),h=null,d?.remove(),d=null,g=null,f=null,ge&&fP(B())},W=()=>{if(!d)return;let ge=c(),Pe=p(),Ae=t.getBoundingClientRect(),Le=d.getBoundingClientRect(),mt=ge.documentElement.clientWidth||Pe.innerWidth,Ve=ge.documentElement.clientHeight||Pe.innerHeight,Re=mt-l-Le.width,$=Ae.left+Ae.width/2-Le.width/2,We=Vg($,l,Re),me=Ae.top-l,dt=Ve-l-Ae.bottom,Qt=Le.height+i,St=me>=Qt||me>=dt?"top":"bottom",Se=St==="top"?Ae.top-i-Le.height:Ae.bottom+i,It=Ve-l-Le.height,yt=Vg(Se,l,It),ke=Ae.left+Ae.width/2,Ge=Math.max(Ug,Le.width-Ug),D=Vg(ke-We,Ug,Ge);d.dataset.placement=St,d.style.left=`${We}px`,d.style.top=`${yt}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${D}px`)},j=()=>{if(A||!s||d||!t.isConnected||mP(t))return;let ge=L(),Pe=hP(t);if(!ge||!Pe)return;let Ae=c(),Le=p();d=Ae.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(na);let mt=Le.getComputedStyle?.(t);if(mt){for(let Qt of yP){let St=mt.getPropertyValue(Qt).trim();St&&d.style.setProperty(Qt,St)}mt.fontFamily&&(d.style.fontFamily=mt.fontFamily)}g=Ae.createElement("span"),g.className="persona-control-tooltip__label",g.textContent=ge,d.appendChild(g);let Ve=I();Ve&&(f=Ae.createElement("span"),f.className="persona-control-tooltip__hint",f.textContent=Ve,d.appendChild(f));let Re=Ae.createElement("span");Re.className="persona-control-tooltip__arrow",d.appendChild(Re),Pe.appendChild(d),W(),d.dataset.state="open";let $=()=>{if(!t.isConnected){te();return}g&&(g.textContent=L()),f&&(f.textContent=I()),W()};Le.addEventListener("scroll",$,!0),Le.addEventListener("resize",$);let We=t.getRootNode(),me=Rv(We)?We:Ae.documentElement,dt=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||te()});dt?.observe(me,{childList:!0,subtree:!0}),h=()=>{Le.removeEventListener("scroll",$,!0),Le.removeEventListener("resize",$),dt?.disconnect()}},Y=ge=>{if(!(A||d)){if(V(),ge||H()<=0||gP()){j();return}y=p().setTimeout(()=>{y=void 0,j()},H())}},M=()=>{b||C?Y(C):te()},T=()=>{let ge=p();(!ge.matchMedia||!ge.matchMedia("(hover: none)").matches)&&(b=!0,M())},_=()=>{b=!1,M()},k=()=>{try{C=t.matches(":focus-visible")}catch{C=!0}M()},Q=()=>{C=!1,M()},U=()=>{b=!1,C=!1,te()},de=ge=>{ge.key==="Escape"&&U()};n.addEventListener("mouseenter",T),n.addEventListener("mouseleave",_),t.addEventListener("focus",k),t.addEventListener("blur",Q),t.addEventListener("keydown",de),t.addEventListener("click",U);let pe={get isOpen(){return d!==null},show:j,hide:te,reposition:W,destroy:()=>{A||(A=!0,te(),n.removeEventListener("mouseenter",T),n.removeEventListener("mouseleave",_),t.removeEventListener("focus",k),t.removeEventListener("blur",Q),t.removeEventListener("keydown",de),t.removeEventListener("click",U),fd.delete(t))}};return fd.set(t,pe),pe}var pP,uP,Ug,kv,Pv,Lv,md,gP,fP,fd,jg,mP,Rv,hP,Vg,yP,sa=$e(()=>{"use strict";Lo();gd();pP=8,uP=8,Ug=10,kv=200,Pv=300,Lv=0,md=e=>Math.max(0,e);gP=()=>Date.now()<Lv,fP=e=>{Lv=e>0?Date.now()+e:0},fd=new WeakMap,jg="data-persona-tooltip-suppressed",mP=e=>typeof e.closest=="function"&&e.closest(`[${jg}]`)!==null;Rv=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,hP=e=>{let t=e.getRootNode?.();return Rv(t)?t:e.ownerDocument.body},Vg=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),yP=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"]});var bP,ri,qg,zg=$e(()=>{"use strict";bP=(e,t)=>e.visible!==!1&&(e.mode!=="transient"||t==="connecting"||t==="paused"||t==="resuming"||t==="error"),ri=(e,t,n)=>{let o=t.mode==="transient",r=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=bP(t,n)||o&&r&&t.visible!==!1?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},qg=(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 Ho(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Wv(s)&&Wv(r)?n[o]=Ho(s,r):n[o]=r}return n}var Wv,hd=$e(()=>{"use strict";Wv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function yd(e,t=""){return Object.entries(e).flatMap(([n,o])=>{let r=t?`${t}.${n}`:n;return Gg(o)?yd(o,r):[r]})}function Ov(e,t){for(let n of t.split(".")){if(!Gg(e)||!Object.prototype.hasOwnProperty.call(e,n))return"absent";if(e=e[n],e===void 0)return"clear"}return"explicit"}function _v(e,t){return e?.[Kg]??t.filter(n=>Ov(e,n)==="explicit")}function Yg(e,t){return Object.defineProperty(e,Kg,{value:t,enumerable:!0,configurable:!0}),e}function Xg(e,t,n){return Yg(e,_v(t,yd(n)))}function Bv(e,t,n){let o=t[Kg];if(o)return o;let r=new Set(_v(e,n));for(let s of n){let i=Ov(t,s);i==="clear"&&r.delete(s),i==="explicit"&&r.add(s)}return[...r]}function Dv(e,t,n){let o={...e};for(let r of t){if(n.includes(r))continue;let s=r.split("."),i=o;for(let l of s.slice(0,-1)){let c=i[l];if(!Gg(c)){i=void 0;break}i[l]={...c},i=i[l]}i&&delete i[s[s.length-1]]}return o}var Kg,Gg,Qg=$e(()=>{"use strict";Kg=Symbol("persona.defaultsProvenance"),Gg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var Nv,Jg,si,bd,vP,kr,Zg,ef,Fv,ia=$e(()=>{"use strict";Nv="var(--persona-components-panel-width)",Jg=Symbol("persona.panelAliasProvenance"),si=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),bd=(e,t)=>si(e,t)&&e[t]!==void 0,vP=e=>({launcherWidth:bd(e?.launcher,"width"),legacyLauncherWidth:bd(e,"launcherWidth"),sidebarWidth:bd(e?.launcher,"sidebarWidth"),dockWidth:bd(e?.launcher?.dock,"width")}),kr=e=>{let t=e?.[Jg];return t?{...t}:vP(e)},Zg=(e,t)=>(Object.defineProperty(e,Jg,{value:t,enumerable:!0,configurable:!0}),e),ef=(e,t)=>Zg(e,kr(t)),Fv=(e,t)=>{let n=t[Jg];if(n)return{...n};let o=kr(e);return si(t,"launcherWidth")&&(o.legacyLauncherWidth=t.launcherWidth!==void 0),si(t,"launcher")&&t.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(si(t.launcher,"width")&&(o.launcherWidth=t.launcher?.width!==void 0),si(t.launcher,"sidebarWidth")&&(o.sidebarWidth=t.launcher?.sidebarWidth!==void 0),si(t.launcher,"dock")&&t.launcher?.dock===void 0?o.dockWidth=!1:si(t.launcher?.dock,"width")&&(o.dockWidth=t.launcher?.dock?.width!==void 0),o)}});function us(e){return e?.future?.v5Defaults===!0?"v5":"v4"}function Uv(e){let t=us(e)==="v5"?ii:AP;return Ho(SP,t)}function $v(e,t){if(!(!e&&!t))return e?t?Ho(e,t):e:t}function yl(e){let t=Uv(e);return e?Xg(ef({...t,...e,theme:$v(t.theme,e.theme),darkTheme:$v(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,o=e.features?.artifacts,r=t.features?.scrollToBottom,s=e.features?.scrollToBottom,i=t.features?.scrollBehavior,l=e.features?.scrollBehavior,c=t.features?.streamAnimation,p=e.features?.streamAnimation,d=t.features?.askUserQuestion,g=e.features?.askUserQuestion,f=t.features?.history,h=e.features?.history,y=n===void 0&&o===void 0?void 0:{...n,...o,layout:{...n?.layout,...o?.layout}},b=r===void 0&&s===void 0?void 0:{...r,...s},C=i===void 0&&l===void 0?void 0:{...i,...l},A=c===void 0&&p===void 0?void 0:{...c,...p},L=d===void 0&&g===void 0?void 0:{...d,...g,styles:{...d?.styles,...g?.styles}},I=f===void 0&&h===void 0?void 0:{...f,...h,copy:{...f?.copy,...h?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...b!==void 0?{scrollToBottom:b}:{},...C!==void 0?{scrollBehavior:C}:{},...y!==void 0?{artifacts:y}:{},...A!==void 0?{streamAnimation:A}:{},...L!==void 0?{askUserQuestion:L}:{},...I!==void 0?{history:I}:{}}})(),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,ii):Xg(ef(t),void 0,ii)}var aa,CP,hl,tf,Pr,ai,wP,SP,AP,xP,ii,EP,vo=$e(()=>{"use strict";hd();Qg();ia();gd();aa="min(440px, calc(100vw - 24px))",CP="440px",hl="40px",tf="How can I help...",Pr={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},ai={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},wP={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:aa,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:hl,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)"},SP={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:wP,copy:{inputPlaceholder:tf,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",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:Pr,reasoningDisplay:ai,streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",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},AP={},xP={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},ii={launcher:xP,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"}}}};EP=Uv()});function MP(e){return typeof e=="string"?[{type:"text",text:e}]:e}function nf(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function bl(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function TP(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Io(e){return{type:"text",text:e}}function of(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function kP(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function PP(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){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 HP(e){return Vv.includes(e)||e.startsWith("image/")}function vd(e){return HP(e.type)}function jv(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function qv(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;vd(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function zv(e,t=Lr,n=10*1024*1024){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 IP(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Kv(e,t){let n=IP(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 la,Vv,LP,Lr,Hr=$e(()=>{"use strict";la="[Image]";Vv=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],LP=["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"],Lr=[...Vv,...LP]});function rf(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 o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function Cd(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function Gv(e,t){e.style.maxHeight=`${t*rf(e)}px`,e.style.overflowY="auto"}function vl(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 Yv(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Xv(e,t){if(e.key!=="Enter"||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,o=t.submitKey??"enter";return o==="none"?!1:o==="mod-enter"?n:n||!Yv(t)}function RP(e){return(e.submitKey??"enter")!=="enter"||Yv(e)?"enter":"send"}function wd(e,t){e.setAttribute("enterkeyhint",RP(t))}function Sd(e,t){let n=t?.autocomplete;e.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(r,s)=>{s===void 0?e.removeAttribute(r):e.setAttribute(r,s)};o("autocapitalize",typeof t?.autocapitalize=="string"?t.autocapitalize:void 0),o("spellcheck",typeof t?.spellcheck=="boolean"?String(t.spellcheck):void 0),o("inputmode",typeof t?.inputmode=="string"&&t.inputmode?t.inputmode:void 0),o("aria-label",typeof t?.ariaLabel=="string"&&t.ariaLabel?t.ariaLabel:void 0)}function sf(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 Ad=$e(()=>{"use strict"});var eo,Ro,lf,zn,xd,Ed,OP,cf,Md,ca,Td,kd,Pd,gs=$e(()=>{"use strict";zg();Qe();Tt();vo();Hr();sa();Ad();eo="persona-composer-control",Ro="persona-composer-control--glyph",lf=40,zn=24,xd=(e,t,n)=>{let o=e.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(e);for(let s of n){let i=r.getPropertyValue(s).trim();i?t.style.setProperty(s,i):t.style.removeProperty(s)}},Ed=(e,t)=>{let n=x("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??tf,n.dir="auto",wd(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:vl(n)}),Sd(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 o=Cd(e?.composer?.maxLines,t?.defaultMaxLines??3),r=`${o*20}px`;n.style.maxHeight=r,n.style.overflowY="auto";let s=()=>{let l=n.style.maxHeight;if(l!==r){let p=parseFloat(l);if(Number.isFinite(p)&&p>0)return p}let c=o*rf(n);return r=`${c}px`,n.style.maxHeight=r,c},i=()=>{n.addEventListener("input",()=>{n.style.height="auto";let l=Math.min(n.scrollHeight,s());n.style.height=`${l}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:i}},OP="[data-persona-glyph-stack]",cf=(e,t,n="send")=>{let o=X("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"),o.append(e,t),o},Md=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",i=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",c=e?.copy?.sendButtonLabel??"Send",p=e?.copy?.stopButtonLabel??"Stop",d=t.showTooltip??!1,g=t.size,f=parseFloat(g??"")||lf,h=t.backgroundColor,y=t.textColor,b=x("div","persona-send-button-wrapper"),C=X("button",{className:On("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${eo}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!y&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?g:void 0,height:n?g:void 0,minWidth:n?g:void 0,minHeight:n?g:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?y||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":y||void 0,backgroundColor:n&&h||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}}),A=null,L=null,I=null;if(n){let V=parseFloat(t.iconSize??"")||Math.round(f*.5),te=t.iconStrokeWidth??2,W=y?.trim()||"currentColor";if(r&&(A=ue(r,V,W,te)),L=ue(s,V,W,te),!t.iconSize)for(let j of[A,L])j&&(j.style.width=`var(--persona-components-composer-sendIconSize, ${V}px)`,j.style.height=`var(--persona-components-composer-sendIconSize, ${V}px)`);A&&L?(I=cf(A,L),C.appendChild(I)):A?C.appendChild(A):(C.textContent=o,L=null)}else C.textContent=c;C.setAttribute("aria-label",i),b.appendChild(C),yn({anchor:C,trigger:b,text:()=>C.getAttribute("aria-label")??"",enabled:d});let H="send";return{button:C,wrapper:b,setMode:V=>{if(V===H)return;H=V;let te=V==="stop"?l:i;C.setAttribute("aria-label",te),C.setAttribute("data-persona-send-mode",V),n?(C.querySelector(OP)??I)?.setAttribute("data-mode",V):C.textContent=V==="stop"?p:c},glyphStack:I}},ca=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype",s=t.provider?.type==="custom";if(!(o||r||s))return null;let l=t.iconName??"mic",c=t.iconSize,p=parseFloat(c??"")||zn,d=t.backgroundColor??e?.sendButton?.backgroundColor,g=t.iconColor??e?.sendButton?.textColor,f=x("div","persona-send-button-wrapper"),h=X("button",{className:On("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",eo,!c&&Ro),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:d||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}}),b=ue(l,p,g||"currentColor",1.5);b?h.appendChild(b):h.textContent="\u{1F3A4}",f.appendChild(h);let C=t.tooltipText??"Start voice recognition",A=t.showTooltip??!1;return yn({anchor:h,trigger:f,text:()=>h.getAttribute("aria-label")??C,enabled:A}),{button:h,wrapper:f}},Td=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=x("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 o=x("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??Lr).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",s=x("div","persona-send-button-wrapper"),i=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${eo} ${Ro}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=ue(r,zn,"currentColor",1.5);l?i.appendChild(l):i.textContent="\u{1F4CE}",i.addEventListener("click",p=>{p.preventDefault(),o.click()}),s.appendChild(i);let c=t.buttonTooltipText??"Attach file";return yn({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:s,input:o,previewsContainer:n}},kd=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=x("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),ri(o,t,"idle");let r=t.idleText??"Online";if(t.idleLink){let s=x("a");s.href=t.idleLink,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r,s.style.color="inherit",s.style.textDecoration="none",o.appendChild(s)}else o.textContent=r;return o},Pd=()=>X("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}})});function Ld(e){let{config:t,onOpen:n}=e,o=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",s=x("div","persona-send-button-wrapper"),i=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${eo} ${Ro}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=ue(o,zn,"currentColor",1.5);return l?i.appendChild(l):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),n()}),s.appendChild(i),yn({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:s}}var df=$e(()=>{"use strict";Qe();Tt();sa();gs()});var D_,_P,Hd,pf=$e(()=>{"use strict";ln();({setLoader:D_,load:_P}=it({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")})),Hd=_P});var $_,BP,Id,uf=$e(()=>{"use strict";ln();({setLoader:$_,load:BP}=it({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0})),Id=BP});function Cl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=X("span",{className:On("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 o=ue(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=x("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(X("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}var gf=$e(()=>{"use strict";Qe();Tt()});function Qv(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:o,createMentionButton:r}=e.deps??DP,s=e.config.contextMentions;if(!s?.enabled)return null;let i=Mv(s).filter(W=>W.sources.length>0);if(i.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let l=i.filter(W=>W.sources.some(j=>typeof j.matchCommand=="function")),c=W=>l.some(j=>j.trigger?j.position==="line-start"?W.split(`
10
+ `).some(M=>M.startsWith(j.trigger)):(j.position==="anywhere"?W:W.split(`
11
+ `)[0]).startsWith(j.trigger):!1),p=(W,j)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${W}`,{detail:j}))}catch{}},d=!e.chipRow,g=e.chipRow??X("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),f=null,h=null,y=e.textarea,b=null,C=null,A=null,L=null,I=()=>{if(f)return Promise.resolve(f);if(h)return h;let W=t().then(j=>(j.setMentionIconRenderer(o),f=j.mountContextMentions({mentionConfig:s,textarea:e.textarea,composerInput:b??void 0,anchor:e.anchor,contextRow:g,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:te,emit:p}),f)).catch(j=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",j),h===W&&(h=null),null));return h=W,W},H=()=>{n().then(W=>{let j=W.mountInlineComposer({textarea:e.textarea,renderToken:M=>Cl(M,{render:s.renderMentionToken}),onMentionRemoved:M=>f?.untrackMention(M)});b=j.input,C=j.destroy;let Y=y;Y.replaceWith(j.element),y=j.element,L={next:j.element,prev:Y},A?.(j.element,Y),f?f.rebindComposer(j.input):h&&h.then(M=>M?.rebindComposer(j.input))}).catch(W=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",W)})};s.display==="inline"&&H();let B=[],V=new Map;for(let W of i){if(!W.showButton)continue;let j=r({config:{...s,buttonIconName:W.buttonIconName,buttonTooltipText:W.buttonTooltipText},onOpen:()=>{I().then(Y=>Y?.openMenu(W.trigger))}});B.push(j),V.set(W.trigger,j.button)}let te=(W,j,Y)=>{let M=V.get(j);M&&(M.setAttribute("aria-expanded",W?"true":"false"),W?M.setAttribute("aria-controls",Y):M.removeAttribute("aria-controls"))};return{affordanceButtons:B.map(W=>W.wrapper),contextRow:g,handleInput:W=>{if(f){f.handleInput();return}if(!xv(W))return;let j=y,Y=j.selectionStart??0;Av(j.value,Y,i)&&I().then(M=>M?.handleInput())},handleKeydown:W=>{if(f?.isMenuOpen())return f.handleKeydown(W);if(W.key==="Backspace"&&f?.hasMentions()&&!L){let j=y,Y=j.selectionStart===0&&j.selectionEnd===0;if((j.value.length===0||Y)&&f.removeLastChip())return W.preventDefault(),!0}return!1},isMenuOpen:()=>f?.isMenuOpen()??!1,hasMentions:()=>f?.hasMentions()??!1,getMentionRefs:()=>f?.getMentionRefs()??[],collectForSubmit:()=>f?.collectForSubmit()??null,takeInlineCommand:async W=>c(W)?(f??await I())?.dispatchInlineCommand(W)??null:null,clear:()=>f?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:W=>{A=W,L&&W(L.next,L.prev)},destroy:()=>{f?.destroy(),C?.();for(let W of B)W.wrapper.remove();d&&g.remove()}}}var DP,Jv=$e(()=>{"use strict";Qe();Ev();Tv();df();pf();Tt();uf();gf();DP={loadContextMentions:()=>Hd(),loadContextMentionsInline:()=>Id(),renderLucideIcon:(...e)=>ue(...e),createMentionButton:(...e)=>Ld(...e)}});var Rd={};Qs(Rd,{createAskUserSheetHandlers:()=>Cv,createContextMentionOrchestrator:()=>Qv});var ff=$e(()=>{"use strict";wv();Jv()});var _d={};Qs(_d,{resolveApproval:()=>VP,resolveAskUserQuestion:()=>jP,resolveWebMcpToolCall:()=>KP,resolveWebMcpToolCallBatch:()=>tC});async function VP(e,t,n,o){let r=`approval-${t.id}`,s=`approval-error-${t.id}`,i={};e.s.approvalTokens.set(r,i);let l={...t,status:n,resolvedAt:Date.now()},c=e.s.messages.find(f=>f.id===r),p={id:r,role:"assistant",content:"",createdAt:c?.createdAt??new Date().toISOString(),...c?.sequence!==void 0?{sequence:c.sequence}:{},streaming:!1,variant:"approval",approval:l};e.s.upsertMessage(p),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let d=e.s.config.approval,g=d&&typeof d=="object"?d.onDecision:void 0;try{let f;if(g?f=await g({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):f=await e.s.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),f){let h=null;if(f instanceof Response){if(!f.ok){let y=await f.json().catch(()=>null),b=y?.message??y?.error??`Approval request failed: ${f.status}`,C=y?.code==="APPROVAL_ALREADY_RESOLVED"||f.status===404&&/no paused execution/i.test(String(y?.error)),A=e.s.messages.find(L=>L.id===r);throw e.s.approvalTokens.get(r)===i&&A?.approval?.resolvedAt===l.resolvedAt&&(e.s.upsertMessage({...p,approval:C?{...l,status:"timeout"}:t}),C&&e.settleApprovalPausedToolCall(r),e.s.upsertMessage({id:s,role:"assistant",content:b,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})),new Error(b)}h=f.body}else f instanceof ReadableStream&&(h=f);e.s.approvalTokens.get(r)===i&&e.s.messages.some(y=>y.id===s)&&(e.s.messages=e.s.messages.filter(y=>y.id!==s),e.s.callbacks.onMessagesChanged([...e.s.messages])),h?await e.s.connectStream(h,{allowReentry:!0}):(n==="denied"&&(e.settleApprovalPausedToolCall(r),e.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})),e.setStreaming(!1),e.s.abortController=null)}else e.setStreaming(!1),e.s.abortController=null}catch(f){let h=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,h||e.s.callbacks.onError?.(f instanceof Error?f:new Error(String(f)))}finally{e.s.approvalTokens.get(r)===i&&e.s.approvalTokens.delete(r)}}async function jP(e,t,n){if(e.s.messages.find(d=>d.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){e.s.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof n=="string"?void 0:n;if(i===void 0&&typeof n=="string"){let d=t.toolCall?.args,g=Array.isArray(d?.questions)?d.questions:[];if(g.length===1){let f=typeof g[0]?.question=="string"?g[0].question:"";f&&(i={[f]:n})}}e.s.markAskUserQuestionResolved(t,i),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let l=t.toolCall.id,c=t.toolCall?.args,p=Array.isArray(c?.questions)?c.questions:[];if(p.length===0){let d=typeof n=="string"?n:Object.entries(n).map(([g,f])=>`${g}: ${Array.isArray(f)?f.join(", "):f}`).join(" | ");e.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})}else{let d=i??{};p.forEach((g,f)=>{let h=typeof g?.question=="string"?g.question:"";if(!h)return;let y=d[h],b=Array.isArray(y)?y.join(", "):typeof y=="string"?y:"";e.appendMessage({id:`ask-user-q-${l}-${f}`,role:"assistant",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}),e.appendMessage({id:`ask-user-a-${l}-${f}`,role:"user",content:b||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})})}try{let d=await e.s.client.resumeFlow(r,{[s]:n},{after:e.resumeAfter(r)});if(!d.ok){let g=await d.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${d.status}`)}d.body?await e.s.connectStream(d.body,{allowReentry:!0}):(e.setStreaming(!1),e.s.abortController=null)}catch(d){let g=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,g||e.s.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}function qP(e,t){let o=[e.s.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}function eC(e,t){return t.toolCall?.name!==Xo?!1:(e.s.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function zP(e,t){let n=qP(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 Od(e,t,n,o,r=Date.now(),s){e.s.messages.some(i=>i.id===t.id)&&e.s.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async function tC(e,t,n){let o=[],r=new AbortController;e.s.webMcpResolveControllers.add(r),e.setStreaming(!0);let s=async c=>{let p=c.toolCall?.name,d=c.toolCall?.id;if(!p||!d)return null;let g=`${t}:${d}`;if(e.s.webMcpInflightKeys.has(g)||e.s.webMcpResolvedKeys.has(g)||eC(e,c))return null;e.s.webMcpInflightKeys.add(g),o.push(g);let f=zP(e,c),h=c.agentMetadata?.webMcpToolCallId??p;if(p===Xo)return{dedupeKey:g,resumeKey:h,output:Jb(),toolMessage:c,startedAt:f,completedAt:Date.now()};let y=e.s.client.executeWebMcpToolCall(p,c.toolCall?.args,r.signal),b;if(!y)b={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{b=await y}catch(C){let A=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));return A||e.s.callbacks.onError?.(C instanceof Error?C:new Error(String(C))),Od(e,c,hf(A?"Aborted by cancel()":UP(C)),f),e.s.webMcpInflightKeys.delete(g),null}return r.signal.aborted?(Od(e,c,hf("Aborted by cancel()"),f),e.s.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:h,output:b,toolMessage:c,startedAt:f,completedAt:Date.now()}},i;if(e.s.config.webmcp?.execution==="sequential"){i=[];for(let c of n)i.push(await s(c))}else i=await Promise.all(n.map(s));let l=[];try{if(l=i.filter(g=>g!==null),l.length===0)return;let c={};for(let g of l)c[g.resumeKey]=g.output;let p=await e.s.client.resumeFlow(t,c,{signal:r.signal,after:e.resumeAfter(t)});if(!p.ok){let g=await p.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${p.status}`)}let d=l[0].dedupeKey;for(let g of l){e.s.webMcpResolvedKeys.add(g.dedupeKey);let f=g.toolMessage.toolCall?.name,h=g.toolMessage.agentMetadata?.webMcpToolCallId;Od(e,g.toolMessage,g.output,g.startedAt,g.completedAt,{...f===Xo?{suggestRepliesResolved:!0}:{},...f&&h?{clientToolAnswer:{toolCallId:h,toolName:f,args:g.toolMessage.toolCall?.args,result:g.output,batch:d}}:{}})}p.body&&await e.s.connectStream(p.body,{allowReentry:!0})}catch(c){if(!(c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"))))e.s.callbacks.onError?.(c instanceof Error?c:new Error(String(c)));else for(let d of l)Od(e,d.toolMessage,hf("Aborted by cancel()"),d.startedAt)}finally{for(let c of o)e.s.webMcpInflightKeys.delete(c);e.s.webMcpResolveControllers.delete(r),e.s.webMcpResolveControllers.size===0&&!e.s.abortController&&e.setStreaming(!1)}}async function KP(e,t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){e.s.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let i=`${n}:__no_tool_id__:${o}`;if(e.s.webMcpInflightKeys.has(i)||e.s.webMcpResolvedKeys.has(i))return;e.s.webMcpInflightKeys.add(i);try{await GP(e,n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),e.s.webMcpResolvedKeys.add(i)}catch(l){e.s.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{e.s.webMcpInflightKeys.delete(i)}return}let s=`${n}:${r}`;if(!(e.s.webMcpInflightKeys.has(s)||e.s.webMcpResolvedKeys.has(s)||eC(e,t)))return tC(e,n,[t])}async function GP(e,t,n,o,r){let s=await e.s.client.resumeFlow(t,{[n]:o},{signal:r?.signal,after:e.resumeAfter(t)});if(!s.ok){let i=await s.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await e.s.connectStream(s.body,{allowReentry:!0}):e.s.webMcpResolveControllers.size===0&&(e.setStreaming(!1),e.s.abortController=null)}var hf,UP,yf=$e(()=>{"use strict";ea();hf=e=>({isError:!0,content:[{type:"text",text:e}]}),UP=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t});function vf(e){if(!e)return rC;let t={...rC};for(let n of JP){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var JP,rC,sC=$e(()=>{"use strict";JP=["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"],rC={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 lC(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,i=!1,l=null,c=[],p=()=>{for(let H of c.splice(0))try{H()}catch(B){Cf("renderHistoryView cleanup",B)}},d=(H,B)=>{for(let V of t){let te=V[H];if(te)try{let W=te(B);if(W)return W}catch(W){Cf(H,W)}}return null},g=()=>({presentation:e.getPresentation(),config:n}),f={header:H=>i?d("renderHistoryHeader",Object.freeze({...g(),returnSurface:e.getReturnSurface(),identityStatus:Ir(H.identityStatus),pendingAction:aC(H.pendingAction),copy:Ir(H.copy),actions:Object.freeze({close:b.close,startNewConversation:b.startNewConversation}),defaultRenderer:H.defaultRenderer})):null,conversation:H=>i?d("renderHistoryConversation",Object.freeze({...g(),conversation:iC(H.conversation),active:H.active,pending:H.pending,open:H.open,requestDelete:H.requestDelete,defaultRenderer:H.defaultRenderer})):null,state:H=>i?d("renderHistoryState",Object.freeze({...g(),state:Ir(H.state),identityStatus:Ir(H.identityStatus),copy:Ir(H.copy),...H.retry?{retry:H.retry}:{},...H.startNewConversation?{startNewConversation:H.startNewConversation}:{},defaultRenderer:H.defaultRenderer})):null},h=t.flatMap(H=>(H.railSections??[]).map(B=>({...B,placement:B.placement??"above-conversations",items:[],render:V=>B.render(Object.freeze({collapsed:V,presentation:e.getPresentation(),actions:b}))}))),y=e.createView({slots:f,renderDom:!1,onModelChange:()=>I(),railSections:h}),b=Object.freeze({...y.operations,close:e.close}),C=()=>(i=!0,y.setDomRenderEnabled(!0),y.element),A=H=>Object.freeze({conversations:Object.freeze(H.conversations.map(iC)),activeConversationId:H.activeConversationId,state:Ir(H.state),pendingAction:aC(H.pendingAction),identityStatus:Ir(H.identityStatus),nextCursor:H.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:Ir(y.copy),actions:b,defaultRenderer:C,requestRender:()=>I(),onCleanup:B=>{c.push(B)}}),L=()=>{i=!1;let H=null;for(let V of t)if(V.renderHistoryView){try{H=V.renderHistoryView(A(y.getModel()))}catch(te){Cf("renderHistoryView",te),H=null}if(H)break}let B=!H||H.contains(y.element);return i=B,y.setDomRenderEnabled(B),H??y.element};function I(){if(!(!s||o||r)){r=!0;try{p();let H=L();if(H===l)return;let B=l;l=H,e.onElementChanged(H,B)}finally{r=!1}}}return s=!0,I(),{view:y,get element(){return l??y.element},requestRender:I,dispose:()=>{o=!0,p()}}}var Cf,Ir,iC,aC,cC=$e(()=>{"use strict";Cf=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},Ir=e=>Object.freeze({...e}),iC=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),aC=e=>e?Ir(e):null});var dC,wf,ZP,Bd,Dd,e0,pC,Nd,wl,t0,n0,uC,Fd=$e(()=>{"use strict";dC=null,wf=()=>{if(dC!==null)return dC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},ZP="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Bd=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Dd=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),n=t.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of t)if(r==="mod"||r==="cmd"||r==="ctrl")o.mod=!0;else if(r==="shift")o.shift=!0;else if(r==="alt"||r==="option")o.alt=!0;else return Bd("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Bd("unsupported",e),null):(n==="space"&&(o.key=" "),o)},e0=e=>ZP.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),pC=(e,t)=>{let n=Dd(e);if(!n)return"";let o=wf(),r=e0(n.key);if(!t&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[t?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},Nd=e=>pC(e,!1),wl=e=>pC(e,!0),t0=(e,t)=>t.key?.toLowerCase()===e.key&&(wf()?t.metaKey:t.ctrlKey)===e.mod&&!(wf()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,n0=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},uC=e=>{let t=new Map,n=e?.ownerDocument??(typeof document<"u"?document:null),o=(s,i)=>{if((s.scope??"widget")==="page")return!0;if(!e)return!1;let l=i.composedPath?.();return l?.length?l.includes(e):e.contains(i.target)},r=s=>{if(s.isComposing||!t.size)return;let i=s.composedPath?.()[0]??s.target;for(let l of t.values())if(t0(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&n0(i))){s.preventDefault();try{l.run(s)}catch(c){Bd(`${l.id} threw on`,l.combo),console.warn(c)}return}};return n?.addEventListener("keydown",r),{register(s){let i=Dd(s.combo);if(!i)return()=>{};let l=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(l);return c?(Bd(`${c.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:i}),s.element?.setAttribute("aria-keyshortcuts",wl(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}}});function gC(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function $d(e){return typeof e=="string"?e:void 0}function s0(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?Io(t.text):null;case"image":return typeof t.image=="string"?of(t.image,{mimeType:$d(t.mimeType),alt:$d(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?jv(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...$d(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...$d(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function i0(e,t){let n=gC(t),o=e.map(i=>gC(i.timestamp)),r=new Array(e.length),s=0;for(;s<o.length;){let i=o[s];if(i!==null){r[s]=i,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let c=l-s+1,p=s>0?r[s-1]:null,d=l+1<o.length?o[l+1]:null,g=d!==null&&n!==null?Math.min(d,n):d??n;for(let f=0;f<c;f+=1)r[s+f]=g!==null?g-(c-f):p!==null?p+f+1:r0+f;s=l+1}return r.map(i=>new Date(i).toISOString())}function fC(e,t){let n=i0(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!o0.includes(r.role))return;let i=r.role,l=n[s];if(r.displayAvailable===!1){let c={historyDisplayUnavailable:!0};o.push({id:r.id,role:i,content:"",createdAt:l,agentMetadata:c});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:i,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:i,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let c=r.content.map(s0).filter(d=>d!==null),p=nf(c);o.push({id:r.id,role:i,content:p||(bl(c)?la:""),createdAt:l,...c.length>0&&{contentParts:c}});return}o.push({id:r.id,role:i,content:"",createdAt:l})}),o}function Sl(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 Al(e,t){let n=new Map;for(let o of e)n.set(o.id,o);for(let o of t)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=o.sequence??0,c=r.sequence??0;return l!==c?l-c:o.id.localeCompare(r.id)})}var o0,r0,Ud=$e(()=>{"use strict";Hr();o0=["user","assistant","system"],r0=0});function c0(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let o=a0.get(e.code)??"unavailable";return new n(o,Sf(o),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new n("unavailable",Sf("unavailable"))}function mC(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,o=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],r={scopes:o},s=c=>{if(!o.includes(c))throw new t("unsupported_scope",Sf("unsupported_scope"))},i=async(c,p)=>{s(c);try{return await p()}catch(d){throw c0(d,e.errors)}},l=c=>{let p=!1;return{conversationId:c.session.conversationId??"",conversationRevision:c.session.conversationRevision??"",async commit(){p||(p=!0,c.commit(),await e.onActivationCommitted(c.session))},discard(){p||(p=!0,c.discard())}}};return{capabilities:r,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(c){return n().subscribeHistoryIdentityStatus(c)},subscribeAvailability(c){return n().subscribeHistoryAvailability(c)},async list(c){return i(c.context.scope,async()=>{let p=await n().listConversations({...c.cursor?{cursor:c.cursor}:{},...c.limit!==void 0?{limit:c.limit}:{},...c.targetId?{targetId:c.targetId}:{},scope:c.context.scope});return{items:p.data,nextCursor:p.nextCursor}})},async getPage(c,p){return i(p.context.scope,async()=>{let d=await n().getConversation(c,{...p.cursor?{messageCursor:p.cursor}:{},scope:p.context.scope}),g=fC(d.messages,{...p.beforeCreatedAt?{beforeCreatedAt:p.beforeCreatedAt}:{}});return{summary:d.summary,messages:Al([],g),conversationRevision:d.conversationRevision??"",nextCursor:d.nextMessageCursor}})},async prepareOpen(c,p){return i(p.context.scope,async()=>l(await n().prepareConversationSession(c)))},async prepareStartNew(c){return i(c.context.scope,async()=>l(await n().prepareNewConversationSession()))},async delete(c,p){await i(p.context.scope,()=>n().deleteConversation(c,{scope:p.context.scope}))},async deleteAll(c){return i(c.context.scope,()=>n().deleteAllConversations({...c.targetId!==void 0?{targetId:c.targetId}:{},scope:c.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var a0,l0,Sf,hC=$e(()=>{"use strict";Ud();a0=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"]]),l0=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."]]),Sf=e=>l0.get(e)??"Conversation history is unavailable right now."});var Vd={};Qs(Vd,{createHistoryShell:()=>d0});var d0,Af=$e(()=>{"use strict";sC();cC();Qe();Fd();Lo();hC();d0=e=>{let o=vf(e.config.features?.history?.copy),r=null,s=!1,i=null,l=null,c="conversation",p=null,d=null,g=null,f=null,h=0,y=null,b=null,C=null,A=`persona-history-${Math.random().toString(36).slice(2,8)}`,L=()=>e.historyFeatureEnabled()&&!!r&&!s,I=()=>{let E=e.session.getStatus();return e.isStreaming||E==="paused"||E==="resuming"},H=()=>{let E=e.config.features?.history?.scope;if(E)return E;let N=e.config.getIdentityProof?"verified-user":"browser",ee=r?.capabilities.scopes;return!ee||ee.includes(N)?N:ee[0]??N},B=()=>l?.scope??H(),V=()=>e.session.getClientSession()?.targetId??null,te=E=>`${E.state}:${"reason"in E?E.reason:""}`,W=E=>{let N=te(E);N!==f&&(f=N,e.eventBus.emit("history:identityStatusChanged",{status:E,timestamp:Date.now()}))},j=null,Y=null,M=()=>{if(!e.historyFeatureEnabled())return null;let E=e.getHistoryProviderFactory();if(E)return E();let N=e.config.features?.history?.provider;return N?typeof N!="function"?N:(j!==N&&(j=N,Y=N()),Y):e.session.isClientTokenMode()?mC({errors:e.historyErrors,client:e.session.getClient(),getIdentityProofConfigured:()=>typeof e.config.getIdentityProof=="function",onActivationCommitted:ee=>e.session.bindActivatedSession(ee),getClient:()=>e.session.getClient()}):null},T=()=>{b?.(),b=null,C?.(),C=null,s=!1,r=M();let E={...e.historyInternals};r?E.historyProvider=r:delete E.historyProvider,e.historyInternals=E,e.session.setHistoryInternals(e.historyInternals),r&&(b=r.subscribeAvailability?.(N=>{s=!N,N||Sn({restoreFocus:!1}),$n()})??null,C=r.subscribeIdentityStatus(N=>W(N)),f=te(r.getIdentityStatus()))},_=()=>{let E=e.config.features?.history?.presentation??"panel";if(E==="panel"||E==="auto"&&!(!e.launcherEnabled||e.isDockedMountMode(e.config)))return"panel";let N=e.artifactSplitRoot??e.container;return(N.getBoundingClientRect().width||N.clientWidth)>=720?"rail":"panel"},k=(E,N)=>{N?(E.setAttribute("aria-hidden","true"),E.setAttribute("inert","")):(E.removeAttribute("aria-hidden"),E.removeAttribute("inert"))},Q="data-persona-history-suppressed",U=null,de=null,pe=null,ge=null,Pe=null,Ae="",Le=()=>e.header===Pe?Ae:e.config.layout?.showHeader===!1?"none":"",mt=()=>e.historyPresentation==="panel"&&!!pe&&ge===pe.element&&e.config.layout?.showHeader!==!1&&Le()!=="none",Ve=()=>{for(let E of Array.from(e.header.children))E!==U&&E.setAttribute(Q,"")},Re=()=>{for(let E of Array.from(e.container.querySelectorAll(`[${Q}]`)))E.removeAttribute(Q)},$=()=>{let E=pe;if(!E)return;if(Array.from(e.header.children).some(ce=>ce!==U&&!ce.hasAttribute(Q))){de&&de!==e.header&&(de.style.removeProperty("min-height"),de=null);let ce=e.header.offsetHeight;ce>0&&(e.header.style.minHeight=`${ce}px`,de=e.header)}U||(U=x("div","persona-history-header-host")),E.setHeaderPlacement("external");let ee=E.getHeaderElement();ee.parentNode!==U&&U.replaceChildren(ee),U.parentNode!==e.header&&e.header.appendChild(U),Ve()},We=()=>{de&&(de.style.removeProperty("min-height"),de=null),U&&(pe?.setHeaderPlacement("inline"),U.remove(),U=null,Re())},me=null,dt=()=>{if(me){if(e.body.style.display="none",k(e.body,!0),e.footer.hidden=!0,k(e.footer,!0),mt()){$(),e.header.style.display=Le(),k(e.header,!1);return}We(),e.header.style.display="none",k(e.header,!0)}};e.reapplyHistoryHostChrome=dt;let Qt=E=>{let N=e.body.style.display,ee=e.footer.hidden,ce=e.footer,He=e.header,Nt=e.header.style.display;Pe=He,Ae=Nt,me=()=>{me=null,We(),Pe=null,e.body.style.display=N,k(e.body,!1),ce.hidden=ee,k(ce,!1),e.footer!==ce&&(e.footer.hidden=!1,k(e.footer,!1)),He.style.display=Nt,k(He,!1),e.header!==He&&(e.header.style.display=e.config.layout?.showHeader===!1?"none":"",k(e.header,!1))},e.footer.parentNode?.insertBefore(E,e.footer),dt()},St=null,Se=null,It=null,yt=null,ke=()=>[e.header,e.panelElements.closeButtonWrapper,e.panelElements.clearChatButtonWrapper,e.body,e.footer],Ge=52,D=()=>e.config.features?.history?.rail?.collapsible!==!1,S=()=>e.config.features?.history?.rail?.side==="right"?"right":"left",F=200,q=400,K=E=>Math.min(q,Math.max(F,Math.round(E))),Z=()=>e.config.features?.history?.rail?.resizable===!0,ye,xe=()=>{if(ye===void 0&&(ye=null,e.config.persistState!==!1))try{let E=Number(window.localStorage.getItem(`${e.currentKeyPrefix()}rail-width`));E&&(ye=E)}catch{}return ye},be=()=>K(xe()??e.config.features?.history?.rail?.width??260),ot=E=>{if(ye=E,e.config.persistState!==!1)try{window.localStorage.setItem(`${e.currentKeyPrefix()}rail-width`,String(E))}catch{}},bt=()=>D()&&e.config.features?.history?.rail?.collapsedBehavior==="overlay",_e=!1,Ye=E=>{let N=x("img");return N.src=E,N.alt="",N.setAttribute("aria-hidden","true"),N},cn=()=>{let E=e.config.features?.history?.rail?.brand;if(!E)return;let N=!1,ee;return ce=>{if(E.render)try{return E.render({collapsed:ce})??null}catch(He){return N||(N=!0,console.warn("[persona] history rail brand threw",He)),null}return ee===void 0&&(E.iconUrl?ee=Ye(E.iconUrl):ee=E.icon?e.renderLucideIcon(E.icon,20):null),ee?ee.cloneNode(!0):null}},Co=()=>e.config.features?.history?.rail?.sections?.map(E=>{let N=!1,ee=ce=>{N||(N=!0,console.warn("[persona] history rail section threw",E.id,ce))};return{id:E.id,title:E.title,placement:E.placement??"above-conversations",items:E.items.map(ce=>{let He;return{id:ce.id,label:ce.label,badge:ce.badge,iconNode:()=>{if(He!==void 0)return He;try{ce.renderIcon?He=ce.renderIcon()??null:ce.iconUrl?He=Ye(ce.iconUrl):He=ce.icon?e.renderLucideIcon(ce.icon,20):null}catch(Nt){ee(Nt),He=null}return He},onSelect:()=>{try{ce.onSelect()}catch(Nt){ee(Nt)}}}})}})??[],ut=E=>{let N=Co();for(let ee of E)N.some(ce=>ce.id===ee.id)?console.warn("[persona] duplicate history rail section id",ee.id):N.push(ee);return N.length?N:void 0},ht=null,Dt=()=>`${e.currentKeyPrefix()}rail-collapsed`,hi=()=>{if(ht===null&&(ht=e.config.features?.history?.rail?.defaultCollapsed===!0,e.config.persistState!==!1))try{let E=window.localStorage.getItem(Dt());E&&(ht=E==="1")}catch{}return ht},nn=E=>{if(ht=E,e.config.persistState!==!1)try{window.localStorage.setItem(Dt(),E?"1":"0")}catch{}},Cn=()=>e.historyPresentation==="rail"&&D()&&!bt()&&hi(),so=()=>{},yi=()=>{if(bt()){so();return}nn(!hi()),i?.view.setCollapsed(Cn()),e.applyRailChrome(),e.repinAnchoredMessage()},bi=()=>{let E=e.config.features?.history?.rail?.collapseShortcut;return!E||!Dd(E)?null:{combo:E,hint:Nd(E),aria:wl(E)}},Ia=300,rr="var(--persona-history-overlay-margin,8px)",dn=null,Nn=null,sr=0,Fn=null,ir=null,Oo=!1,Br=0,Zl=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Gn=()=>L()&&bt()&&(e.historyPresentation??_())==="rail",sh=()=>e.historyVisible&&!_e,ar=()=>{ir!==null&&clearTimeout(ir),ir=null},As=()=>{e.loadHistoryView().catch(()=>{})},kn=()=>{ar(),_e&&(ir=setTimeout(()=>{ir=null,!(Oo||!_e)&&(Fn?.contains(document.activeElement)||Sn({restoreFocus:!1}))},Ia))},Xe=(E,N)=>{let ee=Fn?.getBoundingClientRect();if(!ee)return!1;let ce=dn?.getBoundingClientRect(),He=ce?Math.min(ce.top,ee.top):ee.top;return E>=ee.left&&E<=ee.right&&N>=He&&N<=ee.bottom||!!ce&&E>=ce.left&&E<=ce.right&&N>=ce.top&&N<=ce.bottom},we=E=>{_e&&(Oo=Xe(E.clientX,E.clientY),Oo?ar():ir===null&&kn())},Gt=E=>{e.historyVisible||!Gn()||(_e=!0,qe({invoker:dn,keyboard:E?.keyboard===!0}).then(()=>{e.historyVisible?!Oo&&document.activeElement!==dn&&Sn():_e=!1}))},Je=()=>{let E=ge?.querySelector('[data-persona-history-focus="collapse"]');E&&(E.setAttribute("aria-label",_e?o.expandLabel:o.collapseLabel),E.setAttribute("aria-expanded",_e?"false":"true"))},ve=()=>{nn(!1);let E=i;if(!_e||!E){qe({invoker:dn});return}let N=document.activeElement===dn;_e=!1,vi(),E.element.remove(),kt(E.element),Je(),N&&gt(),e.repinAnchoredMessage(),$n()},se=()=>{nn(!0),Sn()};so=()=>{!e.historyVisible||_e?ve():se()};let Ee=()=>{let E=bi(),N=e.createHeaderIconButton({ariaLabel:o.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":A,...E?{"aria-keyshortcuts":E.aria}:{}}}),ee=N.button;ee.addEventListener("mouseenter",()=>{Oo=!0,ar(),!(Zl()||Date.now()<Br)&&Gt()}),ee.addEventListener("mouseleave",()=>{Oo=!1,Br=0,kn()}),ee.addEventListener("focus",()=>{e.historyVisible||As()}),ee.addEventListener("click",ce=>{L()&&(ce.detail!==0&&Zl()&&!e.historyVisible?Gt():ve())}),dn=ee,Nn=N.wrapper},lr=()=>{if(Nn&&!Nn.isConnected&&(Nn=null,dn=null),!Gn()){Nn?.remove(),Nn=null,dn=null;return}dn||Ee();let E=Nn,N=dn;if(!E||!N)return;let ee=S()!=="right"?e.header.firstChild:null;(ee??e.header.lastChild)!==E&&e.header.insertBefore(E,ee),E.style.display=sh()||sr>0?"none":"",N.setAttribute("aria-label",o.expandLabel),N.setAttribute("aria-expanded",e.historyVisible?"true":"false"),Fn&&e.applyRailChrome()},Dr=E=>{if(!_e)return;let N=E.target;N instanceof Node&&(Fn?.contains(N)||Nn?.contains(N)||N instanceof Element&&N.closest('.persona-dropdown-menu,[role="alertdialog"]')||Sn({restoreFocus:!1}))};document.addEventListener("pointerdown",Dr,!0),e.destroyCallbacks.push(()=>{document.removeEventListener("pointerdown",Dr,!0),document.removeEventListener("pointermove",we),ae?.(),ar()});let io=null,ae=null,Me=16,wn=E=>{ot(K(E)),e.applyRailChrome(),e.repinAnchoredMessage()},Ze=()=>{let E=x("div","persona-rail-resizer");return E.tabIndex=0,E.setAttribute("role","separator"),E.setAttribute("aria-orientation","vertical"),E.setAttribute("aria-valuemin",String(F)),E.setAttribute("aria-valuemax",String(q)),E.addEventListener("pointerdown",N=>{let ee=Se;if(!ee||N.button!==0)return;N.preventDefault(),ae?.();let ce=N.clientX,He=ee.getBoundingClientRect().width||be(),Nt=S()==="right"?-1:1,Rt=He,Wt=e.mount.ownerDocument;ee.style.transition="none";let Ue=he=>{Rt=K(He+Nt*(he.clientX-ce)),ee.style.flex=`0 0 ${Rt}px`,E.setAttribute("aria-valuenow",String(Rt))},st=()=>{ae=null,Wt.removeEventListener("pointermove",Ue),Wt.removeEventListener("pointerup",st),Wt.removeEventListener("pointercancel",st),ee.style.removeProperty("transition");try{E.releasePointerCapture(N.pointerId)}catch{}wn(Rt)};ae=st,Wt.addEventListener("pointermove",Ue),Wt.addEventListener("pointerup",st),Wt.addEventListener("pointercancel",st);try{E.setPointerCapture(N.pointerId)}catch{}}),E.addEventListener("keydown",N=>{let ee=S()==="right"?-Me:Me,ce=be(),He=N.key==="ArrowRight"?ce+ee:N.key==="ArrowLeft"?ce-ee:N.key==="Home"?F:N.key==="End"?q:null;He!==null&&(N.preventDefault(),wn(He))}),E},Jt=(E,N)=>{if(!Z()||Cn()){ae?.(),io?.remove();return}let ee=io??Ze();io=ee,ee.setAttribute("aria-label",o.resizeLabel),ee.setAttribute("aria-valuenow",String(be())),ee.nextElementSibling!==N&&E.insertBefore(ee,N)};e.applyRailChrome=()=>{i?.view.setRailSide(S());let E=S()==="right",N=Fn;if(N){let Wt=dn?dn.getBoundingClientRect().bottom-e.container.getBoundingClientRect().top:0;N.style.top=`calc(${Math.max(0,Math.round(Wt))}px + ${rr})`,N.style.width=`${be()}px`,N.style.left=E?"":rr,N.style.right=E?rr:""}let ee=Se,ce=St,He=It;if(!ee||!ce||!He)return;ee.style.flex=`0 0 ${Cn()?Ge:be()}px`;let Nt="1px solid var(--persona-divider,#e5e7eb)";ee.style.borderRight=E?"":Nt,ee.style.borderLeft=E?Nt:"";let Rt=E?He:ee;ce.firstElementChild!==Rt&&ce.append(Rt,E?ee:He),Jt(ce,E?ee:He)};let ec=E=>{if(yt&&Se){yt.replaceWith(E),yt=null,e.applyRailChrome();return}let N=x("div","persona-history-rail-shell");N.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let ee=x("div","persona-history-rail-conversation");ee.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let ce=x("div","persona-history-rail-host");ce.style.cssText="display:flex;min-height:0;overflow:hidden",e.container.insertBefore(N,e.header.parentNode===e.container?e.header:e.body);for(let He of ke())He?.parentNode===e.container&&ee.appendChild(He);N.append(ce,ee),ce.appendChild(E),St=N,Se=ce,It=ee,e.applyRailChrome()},Hn=()=>{if(St)return;let E=x("div","persona-history-rail-placeholder");E.style.cssText="flex:1 1 auto;min-height:0",yt=E,ec(E),e.repinAnchoredMessage()},tc=()=>{yt&&(vi(),e.repinAnchoredMessage())},eu=E=>{let N=x("div","persona-history-rail-overlay");N.style.cssText=`position:absolute;bottom:${rr};display:flex;overflow:hidden;z-index:${na-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(E),document.addEventListener("pointermove",we),Fn=N,e.applyRailChrome(),Je()},vi=()=>{me?.(),Fn&&(Oo&&(Br=Date.now()+150),document.removeEventListener("pointermove",we),Fn.remove(),Fn=null);let E=St;if(E){ae?.();for(let N of ke())N&&E.contains(N)&&e.container.insertBefore(N,E);E.remove(),St=null,Se=null,It=null,yt=null}},je=E=>{ge=E,E.id=A,E.style.flex="1 1 auto",E.style.minHeight="0"},kt=E=>{je(E),(e.historyPresentation!=="rail"||_e)&&tc(),e.historyPresentation!=="rail"?Qt(E):_e?eu(E):ec(E)},_o=()=>{if(lr(),Fr(),!e.historyVisible||!i)return;let E=_();if(E===e.historyPresentation)return;let N=document.activeElement,ee=N instanceof HTMLElement&&(i.element.contains(N)||U?.contains(N)===!0)?N:null;vi(),i.element.remove(),i.view.setHeaderPlacement("inline"),e.historyPresentation=E,i.view.setPresentation(E),i.view.setCollapsed(Cn()),i.requestRender(),i.element.isConnected||kt(i.element),ee?.isConnected?ee.focus():gt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),$n()},Bo=(E,N)=>U?.querySelector(N)??E.querySelector(N),gt=()=>{let E=i?.element??ge;if(!E)return;let N=Bo(E,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(N){N.focus();return}let ee=Bo(E,".persona-history-title")??E;ee.tabIndex=-1,ee.focus()},qe=async E=>{if(!L()||e.historyVisible)return;let N=r;if(!N)return;if(!_e&&Gn()&&hi()){lr();return}Ci();let ee=++h;c=E?.returnSurface??"conversation",p=E?.invoker??d;let ce=Gn()&&!_e;ce&&(sr+=1,lr(),Hn());let He;try{He=await e.loadHistoryView()}catch{e.announceHistory(o.openHistoryLabel),ce&&(sr-=1,ee===h&&(tc(),lr()));return}if(ce&&(sr-=1),ee!==h||e.historyVisible)return;l={scope:H()},e.historyPresentation=_(),e.historyVisible=!0;let Nt=e.historyPresentation==="panel"&&e.config.layout?.showHeader!==!1&&e.header.style.display!=="none"?"external":"inline",Rt=e.config.features?.history?.rowAvatar,Wt=bi(),Ue=Wt?{hint:Wt.hint,aria:Wt.aria}:null,st={provider:N,context:l,targetId:V(),presentation:e.historyPresentation,collapsible:D(),collapsed:Cn(),railSide:S(),renderRailHeader:e.config.features?.history?.rail?.renderHeader,railBrand:cn(),onToggleCollapse:yi,...Ue?{collapseShortcut:Ue}:{},headerPlacement:Nt,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:Rt===!1?!1:typeof Rt=="string"?Rt: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:he=>An(he,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:he=>e.setActiveConversationSummary(he),attachTooltip:e.attachTooltip,onStartNew:()=>wo({focusComposer:!0}),onClose:()=>Sn(),onRequestDeleteConversation:he=>$t(he),onRequestClearHistory:()=>Ts(),...N.resetDevice?{onRequestResetIdentity:()=>Oa()}:{}};i=lC({plugins:e.plugins,config:e.config,getPresentation:()=>e.historyPresentation??"panel",getReturnSurface:()=>c,close:()=>Sn(),createView:({slots:he,renderDom:Si,onModelChange:ao,railSections:dr})=>(pe=He.createHistoryView({...st,railSections:ut(dr),slots:he,renderDom:Si,onModelChange:ao,onAnnounce:e.announceHistory}),pe),onElementChanged:(he,Si)=>{if(!Si?.isConnected)return kt(he);je(he),Si.replaceWith(he),dt()}}),i.view.setNewConversationRequired(e.historySessionState.recovery==="new_conversation_required"),E?.focus!==!1&&(e.historyPresentation!=="rail"||E?.keyboard===!0)&&gt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),$n(),e.eventBus.emit("history:opened",{presentation:e.historyPresentation,returnSurface:c,timestamp:Date.now()})},Ci=()=>{},Sn=E=>{if(!e.historyVisible)return;h+=1;let N=c,ee=p,ce=i,He=E?.restoreFocus!==!1;e.historyVisible=!1;let Nt=!1,Rt=null,Wt=()=>{if(!Nt){if(Nt=!0,Ci=()=>{},Rt!==null&&clearTimeout(Rt),_e=!1,ar(),vi(),ce?.dispose(),ce?.view.destroy(),ce?.element.remove(),i===ce&&(i=null,pe=null,ge=null,e.historyPresentation=null,l=null,p=null),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),$n(),He){let st=ee??d;st?.isConnected?st.focus():e.maybeFocusInput()}e.eventBus.emit("history:closed",{returnSurface:N,timestamp:Date.now()})}},Ue=ce&&ce.element===ce.view.element?ce.view.playExit():null;if(!Ue){Wt();return}Ci=Wt,Rt=setTimeout(Wt,250),Ue.then(Wt)},xs=E=>{if(!(E.key!=="Escape"||!e.historyVisible||!i)){if(e.historyPresentation==="rail"){let N=E.target;if(!(N instanceof Node)||!(i.element.contains(N)||_e&&Nn?.contains(N)===!0))return}E.preventDefault(),E.stopPropagation(),Sn()}};e.container.addEventListener("keydown",xs),e.destroyCallbacks.push(()=>e.container.removeEventListener("keydown",xs));let In=0,nc=250,fe=null,pn=()=>{fe&&clearTimeout(fe),fe=null};e.destroyCallbacks.push(pn);let Pt=()=>{pn();let E=e.conversationOpenPendingEl;E&&(e.conversationOpenTakeover=!0,E.hidden=!1,e.messagesWrapper.style.display="none",e.updateWelcome())},on=()=>{In+=1,pn(),e.conversationOpenPendingEl&&(e.conversationOpenPendingEl.remove(),e.conversationOpenPendingEl=null,e.conversationOpenTakeover=!1,e.messagesWrapper.style.removeProperty("display"),k(e.footer,!1),e.updateWelcome())},At=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;e.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},un=(E,N)=>X("div",{className:On("persona-conversation-loading-bubble",N&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:E}}),oc=()=>X("div",{className:"persona-conversation-loading-body"},un("58%",!1),un("72%",!0),un("44%",!1)),Nr=E=>{e.conversationOpenPendingEl?.remove(),e.conversationOpenPendingEl=E,E.hidden=!e.conversationOpenTakeover,e.body.insertBefore(E,e.messagesWrapper),pn(),e.conversationOpenTakeover||(fe=setTimeout(Pt,nc)),k(e.footer,!0)},tu=()=>{let E={config:e.config,streaming:!1,location:"conversation-open",defaultRenderer:oc},N=null,ee=e.plugins.find(ce=>ce.renderLoadingIndicator);ee?.renderLoadingIndicator&&(N=ee.renderLoadingIndicator(E)),N===null&&e.config.loadingIndicator?.render&&(N=e.config.loadingIndicator.render(E)),Nr(X("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":o.openConversationLoadingLabel}},N??oc()))},nu=E=>{let N=()=>{An(E,{focusComposer:!0}).catch(()=>{})},ee=L()?()=>{on(),qe()}:void 0,ce=(Wt,Ue)=>{let st=X("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:Wt});return st.addEventListener("click",Ue),st},He=()=>X("div",{className:"persona-conversation-loading-error-body"},X("p",{className:"persona-conversation-loading-error-title",text:o.openConversationErrorTitle}),X("div",{className:"persona-conversation-loading-error-actions"},ce(o.openConversationRetryLabel,N),ee?ce(o.openConversationBackLabel,ee):null)),Nt=Object.freeze({conversationId:E,config:e.config,copy:Object.freeze({title:o.openConversationErrorTitle,retryLabel:o.openConversationRetryLabel,backLabel:o.openConversationBackLabel}),retry:N,...ee?{back:ee}:{},defaultRenderer:He}),Rt=null;for(let Wt of e.plugins)if(Wt.renderHistoryOpenError){try{Rt=Wt.renderHistoryOpenError(Nt)}catch(Ue){console.warn("[persona] renderHistoryOpenError threw",Ue),Rt=null}if(Rt)break}Nr(X("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},Rt??He())),Pt()};e.eventBus.on("history:closed",()=>{e.conversationOpenPendingEl&&k(e.footer,!0)});let An=async(E,{focusComposer:N=!1}={})=>{let ee=B(),ce=!!i;i?.view.setActiveConversationId(E),on();let He=In;tu(),e.historyVisible&&(e.historyPresentation==="panel"||_e)&&Sn({restoreFocus:!1}),e.suppressScrollSend=!0;try{await e.session.openConversation(E,{scope:ee})}catch(Nt){throw He===In&&nu(E),Nt}finally{e.suppressScrollSend=!1}He===In&&(on(),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.restoreScrollPosition()||e.jumpToBottomInstant(),At(),Yt(),ce||e.setActiveConversationSummary(null),e.eventBus.emit("history:conversationOpened",{conversationId:E,title:e.activeConversationTitle,scope:ee,timestamp:Date.now()}),N&&e.maybeFocusInput())},wo=async({focusComposer:E=!1}={})=>{on(),await e.session.startNewConversation({scope:B()}),e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.jumpToBottomInstant(),Yt();let N=e.session.getActiveConversationId();i?.view.setActiveConversationId(N),e.eventBus.emit("history:conversationStarted",{conversationId:N,timestamp:Date.now()}),e.historyVisible&&(e.historyPresentation==="panel"||_e)&&Sn({restoreFocus:!1}),E&&e.maybeFocusInput()},Es=async(E,N)=>{let ee=await e.session.updateConversation(E,{...N,...N.title!==void 0?{title:N.title.trim()}:{}});return i?.view.applyConversationSummary(ee),!i&&E===e.session.getActiveConversationId()&&e.setActiveConversationSummary(ee),ee},rc=async E=>{let N=B(),ee=e.session.getActiveConversationId()===E;await e.session.deleteConversation(E,{scope:N}),i?.view.removeConversationSummary(E),ee&&(e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Yt()),e.eventBus.emit("history:conversationDeleted",{conversationId:E,scope:N,wasActive:ee,timestamp:Date.now()})},Ra=async E=>{let N=E?.scope??B(),ee=E?.allTargets?null:E?.targetId??V(),ce=await e.session.clearConversationHistory({...ee?{targetId:ee}:{},scope:N});return e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Yt(),e.eventBus.emit("history:cleared",{deleted:ce.deleted,scope:N,targetId:ee,timestamp:Date.now()}),ce},Wa=async()=>{if(!r?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let E=!1;try{E=(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 N=e.storageAdapter;N?.clear&&e.runStorageMutation(()=>N.clear(),"[AgentWidget] Failed to clear storage adapter:"),e.resetAnchorState(),e.resumeAutoScroll(),Yt(),Sn({restoreFocus:!1}),e.maybeFocusInput(),e.open||e.launcherSurfaceInstance?.launcher.element.focus()}return e.announceHistory(E?o.identityResetNotice:o.identityResetUnconfirmedNotice),e.eventBus.emit("history:identityReset",{remoteRevocationConfirmed:E,timestamp:Date.now()}),{remoteRevocationConfirmed:E}},wi=()=>e.artifactSplitRoot?e.panel:e.container,Ms=async E=>{let N=await e.loadHistoryView().catch(()=>null);return typeof N?.showHistoryConfirm=="function"?N.showHistoryConfirm(E):window.confirm(`${E.title}
12
12
 
13
- ${M.description}`)},$t=async M=>await Es({host:wi(),title:o.deleteConversationConfirmTitle,description:o.deleteConversationConfirm,confirmLabel:o.deleteConversationConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await oc(M),"deleted"):"cancelled",Ts=async()=>{let M=_()==="verified-user";return await Es({host:wi(),title:o.clearHistoryConfirmTitle,description:M?o.clearHistoryVerifiedConfirm:o.clearHistoryConfirm,confirmLabel:o.clearHistoryConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Ra(),"cleared"):"cancelled"},Oa=async()=>{if(!await Es({host:wi(),title:o.resetIdentityConfirmTitle,description:o.resetIdentityConfirm,confirmLabel:o.resetIdentityConfirmLabel,cancelLabel:o.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:N}=await Wa();return{outcome:"reset",remoteRevocationConfirmed:N}},Zt=x("button","persona-history-earlier");Zt.type="button",Zt.textContent=o.showEarlierMessagesLabel,Zt.setAttribute("data-persona-history-earlier",""),Object.assign(Zt.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 Yt=()=>{if(!(L()&&!!e.historySessionState.nextMessageCursor&&!!e.session.getActiveConversationId())){Zt.remove();return}Zt.textContent=o.showEarlierMessagesLabel,Zt.parentNode!==e.body&&e.body.insertBefore(Zt,e.body.firstChild)};Zt.addEventListener("click",()=>{let M=e.session.getActiveConversationId(),N=e.historySessionState.nextMessageCursor;if(!M||!N||Zt.disabled)return;Zt.disabled=!0;let ee=e.body.scrollHeight,ce=e.body.scrollTop;e.session.loadOlderMessages(M,N,{scope:_()}).then(()=>{e.body.scrollTop=ce+(e.body.scrollHeight-ee),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Zt.disabled=!1,Yt()})});let wo=()=>{let M=e.createHeaderIconButton({ariaLabel:o.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 M.button.addEventListener("click",N=>{if(!(!L()||I())){if(e.historyVisible){Sn();return}qe({invoker:M.button,keyboard:N.detail===0})}}),M},Fr=()=>{if(!L()){g?.remove(),d=null,g=null;return}if(g&&!g.isConnected&&(d=null,g=null),!d&&e.header){let ce=wo();d=ce.button,g=ce.wrapper;let He=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;He?.parentNode&&e.header.contains(He)?He.parentNode.insertBefore(g,He):e.header.appendChild(g)}if(!d||!g)return;let M=Kn()||e.historyVisible&&e.historyPresentation==="rail";if(g.style.display=M?"none":"",M){document.activeElement===d&&gt();return}let N=I();d.disabled=N,d.setAttribute("aria-disabled",N?"true":"false");let ee=N?o.openHistoryBusyLabel:o.openHistoryLabel;d.setAttribute("aria-label",ee),(e.config.features?.history?.presentation??"panel")==="panel"?(d.removeAttribute("aria-expanded"),d.removeAttribute("aria-controls")):(d.setAttribute("aria-expanded",e.historyVisible?"true":"false"),d.setAttribute("aria-controls",A))},cr=!1,Ps=()=>{let M=e.panelElements.clearChatButton;if(M){if(L()){cr||(y=M.getAttribute("aria-label")??"",cr=!0),M.setAttribute("aria-label",o.newConversationLabel),M.removeAttribute("title");return}cr&&(cr=!1,y&&M.setAttribute("aria-label",y))}},$n=()=>{o=hf(e.config.features?.history?.copy),Fr(),lr(),Ps(),Yt()};return e.historyChromeSync=$n,T(),$n(),e.destroyCallbacks.push(()=>{v?.(),C?.(),h+=1,Ci(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:L,historyScope:H,installHistoryProvider:T,syncHistoryChromeImpl:$n,syncHistoryPresentation:Bo,syncEarlierMessagesPill:Yt,openHistory:qe,closeHistory:Sn,openHistoryConversation:An,startNewConversation:Co,updateHistoryConversation:Ms,deleteHistoryConversation:oc,requestDeleteConversation:$t,clearConversationHistory:Ra,resetHistoryIdentity:Wa,railCollapseShortcut:bi,railCollapsible:D,railTriggerApplies:Kn,railOverlayMode:bt,toggleRailCollapsed:yi,toggleRailPinned:()=>ro(),get historyProvider(){return r},get historySurface(){return i},get railShell(){return St},get railHost(){return Se},get railColumn(){return It}}}});var ga,Lf=$e(()=>{"use strict";ga=class{#e=null;#n=0;#o=[];#t=[];#s=[];#r=!1;#p=!1;#f=0;#i=!1;#g=!1;#l;#c=[];#a=0;#E=!1;#h;#S;#v;#A=null;constructor(t=24e3,n={}){this.#S=t;let o=Math.max(0,n.prebufferMs??0);this.#v=Math.round(t*o/1e3),this.#l=this.#v>0}#d(){if(!this.#e){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.#e=new o({sampleRate:this.#S})}let t=this.#e;return t.state==="suspended"&&!this.#g&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.#A){let r=new Uint8Array(this.#A.length+t.length);r.set(this.#A),r.set(t,this.#A.length),n=r,this.#A=null}if(n.length%2!==0&&(this.#A=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.#x(n);o.length!==0&&(this.#l?(this.#c.push(o),this.#a+=o.length,clearTimeout(this.#h),this.#a>=this.#v?this.#u():this.#E&&(this.#h=setTimeout(()=>this.#u(),this.#v/this.#S*1e3))):this.#m(o))}markStreamEnd(){this.#c.length>0&&this.#u(),this.#p=!0,this.#C()}flush(){for(let t of this.#o){t.onended=null;try{t.stop(),t.disconnect()}catch{}}this.#o=[],this.#f=0,this.#n=0,this.#r=!1,this.#p=!1,this.#t=[],this.#s=[],this.#A=null,this.#c=[],this.#a=0,this.#l=this.#v>0,this.#i=!1,clearTimeout(this.#h)}setContinuousMode(t){this.#E=t}isPlaying(){return this.#r}onFinished(t){this.#t.push(t)}onStarted(t){this.#s.push(t)}pause(){this.#g=!0,this.#e&&this.#e.state==="running"&&this.#e.suspend()}resume(){this.#g=!1,this.#e&&this.#e.state==="suspended"&&this.#e.resume()}async destroy(){this.flush(),this.#e&&(await this.#e.close(),this.#e=null)}#u(){this.#l=!1;let t=this.#c;this.#c=[],this.#a=0;for(let n of t)this.#m(n)}#m(t){if(t.length===0)return;let n=this.#d(),o=n.createBuffer(1,t.length,this.#S);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.#n===0?this.#n=s:this.#n<s&&(this.#n=s,this.#v>0&&(this.#l=!0)),r.start(this.#n),this.#n+=o.duration,this.#o.push(r),this.#f++,this.#r=!0,!this.#i){this.#i=!0;let i=this.#s.slice();this.#s=[];for(let l of i)l()}r.onended=()=>{let i=this.#o.indexOf(r);i!==-1&&(this.#o.splice(i,1),this.#f--,this.#C())}}#C(){if(this.#p&&this.#f<=0&&this.#c.length===0){this.#r=!1,this.#p=!1;let t=this.#t.slice();this.#t=[];for(let n of t)n()}}#x(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let i=r.getInt16(s*2,!0);o[s]=i/32768}return o}}});function j0(e){return e.replace(/\/+$/,"")}async function q0(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 Jd,qC=$e(()=>{"use strict";Lf();Jd=class{constructor(t){this.id="runtype-tts";this.supportsPause=!0;this.#e=null;this.#n=null;this.#o=0;this.#t=t}#e;#n;#o;#t;#s(){return this.#n??=Promise.resolve(this.#t.createPlaybackEngine?this.#t.createPlaybackEngine():new ga(24e3,{prebufferMs:this.#t.prebufferMs??200})).then(t=>this.#e=t)}speak(t,n){let o=++this.#o;this.#r(o,t,n)}async#r(t,n,o){try{let r=await this.#s();if(t!==this.#o)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.#o&&o.onStart?.()}),r.onFinished(()=>{t===this.#o&&o.onEnd?.()});let s=`${j0(this.#t.host)}/v1/agents/${encodeURIComponent(this.#t.agentId)}/speak`,i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.#t.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.#t.voice,format:"pcm"})});if(t!==this.#o)return;if(!i.ok||!i.body)throw new Error(await q0(i));let l=i.body.getReader();for(;;){let{done:c,value:p}=await l.read();if(t!==this.#o){await l.cancel().catch(()=>{});return}if(c)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(t!==this.#o)return;let s=r instanceof Error?r:new Error(String(r));this.#t.onError?.(s),o.onError?.(s)}}pause(){this.#e?.pause()}resume(){this.#e?.resume()}stop(){this.#o++,this.#e?.flush()}destroy(){this.#o++,this.#e?.destroy(),this.#e=null,this.#n=null}}});var Zd,zC=$e(()=>{"use strict";Zd=class{constructor(t,n,o={}){this.id="fallback";this.#n=t,this.#o=n,this.#t=o,this.#e=t}#e;#n;#o;#t;get supportsPause(){return this.#e.supportsPause}speak(t,n){this.#e=this.#n;let o=!1;this.#n.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.#t.onFallback?.(r),this.#e=this.#o,this.#o.speak(t,n)}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#n.destroy?.(),this.#o.destroy?.()}}});var KC={};Qs(KC,{FallbackSpeechEngine:()=>Zd,RuntypeSpeechEngine:()=>Jd});var GC=$e(()=>{"use strict";qC();zC()});import{Marked as DM}from"marked";import NM from"dompurify";ln();var{setLoader:nO,load:BM,provide:_M,getSync:fg}=it({fallbackImport:()=>Promise.resolve().then(()=>(yb(),hb))}),Kc=new Set,bb=()=>{let e=[...Kc];Kc.clear();for(let t of e)try{t()}catch{}};var mg=()=>{let e=fg();return e?Promise.resolve(e):BM().then(t=>(bb(),t))},il=e=>fg()?()=>{}:(Kc.add(e),()=>{Kc.delete(e)}),vb=e=>{_M(e),bb()},Yo=fg;vb({Marked:DM,DOMPurify:NM});import{Ban as FM,Bell as $M,Bookmark as UM,Building as VM,Calendar as jM,CalendarDays as qM,Camera as zM,ChartColumn as KM,CircleCheck as GM,CircleX as YM,Clock as XM,CreditCard as QM,DollarSign as JM,EyeOff as ZM,Files as eE,Film as tE,Flag as nE,Folder as oE,FolderOpen as rE,Funnel as sE,Gift as iE,Globe as aE,Hash as lE,Headphones as cE,Heart as dE,House as pE,Image as uE,Info as gE,Key as fE,Lightbulb as mE,Link as hE,Lock as yE,Mail as bE,MapPin as vE,MessageCircle as CE,Monitor as wE,Moon as SE,Package as AE,Pause as xE,PenLine as ME,Percent as EE,Phone as TE,Play as PE,Receipt as kE,RotateCw as LE,Save as HE,Settings as IE,Share as RE,Shield as WE,ShoppingBag as OE,ShoppingCart as BE,Smartphone as _E,Sparkles as DE,Store as NE,Sun as FE,Tag as $E,Timer as UE,TriangleAlert as VE,Truck as jE,User as qE,VolumeX as zE,Wallet as KE,Zap as GE}from"lucide";var Cb={user:qE,mail:bE,phone:TE,calendar:jM,clock:XM,building:VM,"map-pin":vE,lock:yE,key:fE,"credit-card":QM,hash:lE,globe:aE,link:hE,"circle-check":GM,"circle-x":YM,"triangle-alert":VE,info:gE,ban:FM,shield:WE,house:pE,"pen-line":ME,save:HE,share:RE,funnel:sE,settings:IE,"rotate-cw":LE,"shopping-cart":BE,"shopping-bag":OE,package:AE,truck:jE,tag:$E,gift:iE,receipt:kE,wallet:KE,store:NE,"dollar-sign":JM,percent:EE,play:PE,pause:xE,"volume-x":zE,camera:zM,image:uE,film:tE,headphones:cE,"message-circle":CE,bell:$M,heart:dE,"eye-off":ZM,bookmark:UM,"calendar-days":qM,timer:UE,folder:oE,"folder-open":rE,files:eE,"chart-column":KM,sparkles:DE,zap:GE,sun:FE,moon:SE,flag:nE,lightbulb:mE,monitor:wE,smartphone:_E};Tt();Sb(Cb);Wg();ln();var{setLoader:FO,load:$P,provide:UP,getSync:VP}=it({fallbackImport:()=>Promise.resolve().then(()=>(Wg(),cd))});var oi=$P,ov=UP,rv=VP;ov(cd);Dg();ln();var{setLoader:GO,load:nk,provide:ok}=it({fallbackImport:()=>Promise.resolve().then(()=>(Dg(),dd))});var Tr=nk,mv=ok;mv(dd);pf();ln();var{setLoader:XB,load:Wk,provide:Ok,getSync:Bk}=it({fallbackImport:()=>Promise.resolve().then(()=>(pf(),Hd))});var Id=Wk,Yv=Ok,uf=Bk;Yv(Hd);ff();ln();var{setLoader:t_,load:jk,provide:qk,getSync:zk}=it({fallbackImport:()=>Promise.resolve().then(()=>(ff(),Wd))});var mf=jk,Jv=qk,Zv=zk;Jv(Wd);Cf();ln();var{setLoader:b_,load:i0,provide:a0,getSync:l0}=it({fallbackImport:()=>Promise.resolve().then(()=>(Cf(),$d))});var gC=i0,fC=a0,Ud=l0;fC($d);Mr();bo();Xe();Tt();import{Circle as m0,Clock as h0}from"lucide";Xe();Mr();import{ChevronDown as c0,ChevronUp as d0}from"lucide";var p0=["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"],u0="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",g0="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",f0=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Vd=(e,t)=>{let n=x("div",["persona-message-bubble",e,...p0].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},jd=e=>{let t=x("button",e.expandable?u0:g0);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},wf=(e,t,n)=>{e.innerHTML="";let o=_t(t?d0:c0,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},da=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=x("div","persona-flex persona-items-center");wf(o,n.expanded,n.iconColor);let r=x("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(o),e.append(t,r),o},qd=e=>{let t=x("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?.();f0(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},zd=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&wf(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"},Kd=(e,t,n)=>{let o=n.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!r||!s)return;r.setAttribute("aria-expanded",o?"true":"false");let c=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");c&&wf(c,o,n.iconColor),s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")};function Gd(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[n]:{...t==="tool"?kr:ai,...e?.future?.v5Defaults===!0?ii.features?.[n]:{},...e?.features?.[n]}}}}function fs(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[n]?.variant??(e?.future?.v5Defaults?"row":"card")}function xl(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 Rr(e,t,n,o){if(fs(n,o)!=="row")return e;e.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,e.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(e.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let r=e.querySelector(":scope > button");if(!r)return e;r.className="persona-activity-header";let s=o==="tool"?t.toolCall:t.reasoning,i=s?.status!=="complete",l=t.approval?.status??t.toolCall?.approvalStatus,c=l==="denied"?"denied":l==="pending"?"awaiting-approval":t.toolCall?.success===!1?"error":i?s?.status==="pending"?"pending":"running":"done";e.dataset.activityState=c;let p=x("span","persona-activity-icon");p.dataset.activityIcon=c;let d={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},g=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,f=g?ue(g,16,"currentColor",2):c==="pending"?_t(m0,16,"currentColor",2):c==="awaiting-approval"?_t(h0,16,"currentColor",2):ue(d[c],16,"currentColor",2);f&&p.appendChild(f),r.querySelector(".persona-reasoning-header-icon")?.remove();let h=o==="tool"?"toolCallDisplay":"reasoningDisplay",y=n.features?.[h]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((y==="always"||y==="active"&&c!=="done")&&r.prepend(p),o==="tool"&&s){let L=x("span","persona-activity-duration");i&&s.startedAt&&L.setAttribute("data-tool-elapsed",String(s.startedAt));let I=(o==="tool"?t.toolCall?.duration:void 0)??s.durationMs??(s.completedAt!==void 0&&s.startedAt!==void 0?s.completedAt-s.startedAt:void 0);L.textContent=I===void 0?"":xl(I),r.appendChild(L)}r.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),r.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let A=e.querySelector(":scope > .persona-border-t");return A?.classList.add("persona-activity-body"),A&&(A.id=`activity-details-${t.id}`,r.setAttribute("aria-controls",A.id)),e}function mC(e){let t=new Set,n=new Set,o=new Set,r=new Map,s=i=>{clearTimeout(r.get(i)),r.delete(i)};return{observe(i,l,c,p={}){let d=l==="tool"?i.toolCall:i.reasoning;if(!(!d||n.has(i.id))&&(!t.has(i.id)&&d.status!=="complete"&&d.chunks?.some(Boolean)&&(t.add(i.id),p.autoExpand!==!1&&c.add(i.id)),t.has(i.id)&&d.status==="complete"&&!o.has(i.id))){if(o.add(i.id),p.autoCollapseDelay===!1)return;r.set(i.id,setTimeout(()=>{r.delete(i.id),c.delete(i.id),e(i.id,l)},p.autoCollapseDelay??1e3))}},manual(i){n.add(i),s(i)},prune(i){for(let l of new Set([...t,...n,...o]))i.has(l)||(s(l),t.delete(l),n.delete(l),o.delete(l))},clear(){for(let i of r.keys())s(i);t.clear(),n.clear(),o.clear()}}}function hC(e,t,n,o){let r=x("div","");r.id=`bubble-${e.id}`,r.dataset.messageId=e.id;let s=x("button","");s.type="button",s.dataset.expandHeader="true",s.dataset.bubbleType="tool",s.setAttribute("aria-expanded",String(n));let i=x("div","");typeof o=="string"?i.textContent=o:i.appendChild(o),da(s,i,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let l=x("div","persona-border-t");return l.id=`activity-details-${e.id}`,l.style.display=n?"":"none",s.setAttribute("aria-controls",l.id),r.append(s,l),Rr(r,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:"row"}}},"tool"),r.dataset.personaToolGroup="true",t.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(r.dataset.activityGroupShimmer="true"),{bubble:r,body:l}}Vg();function yC(e,t){let n=e.voiceRecognition,o=t.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function On(e){return e?.type==="runtype"||e?.type==="custom"}var y0=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function bC(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:y0()}catch{return!1}}var b0=e=>{if(!e)return;let t={},n=e;if(n.heading){let o=n.heading;t.heading=(r,s,i)=>o({type:"heading",raw:i,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;t.code=(r,s,i)=>o({type:"code",raw:"",text:r,lang:s,escaped:i})}if(n.blockquote){let o=n.blockquote;t.blockquote=r=>o({type:"blockquote",raw:"",text:r,tokens:[]})}if(n.table){let o=n.table;t.table=(r,s)=>o({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:s})}if(n.link){let o=n.link;t.link=(r,s,i)=>o({type:"link",raw:"",href:r,title:s??null,text:i,tokens:[]})}if(n.image){let o=n.image;t.image=(r,s,i)=>o({type:"image",raw:"",href:r,title:s??null,text:i})}if(n.list){let o=n.list;t.list=(r,s,i)=>o({type:"list",raw:"",ordered:s,start:i,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;t.listitem=(r,s,i)=>o({type:"list_item",raw:"",task:s,checked:i,loose:!1,text:r,tokens:[]})}if(n.paragraph){let o=n.paragraph;t.paragraph=r=>o({type:"paragraph",raw:"",text:r,tokens:[]})}if(n.codespan){let o=n.codespan;t.codespan=r=>o({type:"codespan",raw:"",text:r})}if(n.strong){let o=n.strong;t.strong=r=>o({type:"strong",raw:"",text:r,tokens:[]})}if(n.em){let o=n.em;t.em=r=>o({type:"em",raw:"",text:r,tokens:[]})}if(n.del){let o=n.del;t.del=r=>o({type:"del",raw:"",text:r,tokens:[]})}if(n.html){let o=n.html;t.html=r=>o({type:"html",raw:r,text:r})}if(n.text){let o=n.text;t.text=r=>o({type:"text",raw:r,text:r})}if(n.checkbox){let o=n.checkbox;t.checkbox=r=>o({checked:r})}return n.hr&&(t.hr=n.hr),n.br&&(t.br=n.br),t},Yd=e=>{let t=null;return n=>{let o=Yo();if(!o)return ms(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let i=b0(e?.renderer);i&&t.use({renderer:i})}return t.parse(n)}},Xd=e=>e?Yd({markedOptions:e.options,renderer:e.renderer}):Yd(),v0=Yd(),CC=e=>v0(e),ms=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),wC=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),vC=e=>`%%FORM_PLACEHOLDER_${e}%%`,SC=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=vC(t.length);return t.push({token:i,type:String(s.type)}),i}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=vC(t.length);return t.push({token:s,type:r}),s}),n},C0=e=>{let t=Xd(e);return n=>{let o=[],r=SC(n,o),s=t(r);return o.forEach(({token:i,type:l})=>{let c=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${wC(l)}"></div>`;s=s.replace(c,d)}),s}},w0=e=>{let t=[],n=SC(e,t),o=CC(n);return t.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${wC(s)}"></div>`;o=o.replace(i,c)}),o};var S0={ALLOWED_TAGS:["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"],ALLOWED_ATTR:["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"]},A0=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,AC=()=>{let e=null;return t=>{let n=Yo();if(!n)return ms(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let i=s.attrValue;i.toLowerCase().startsWith("data:")&&!A0.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,S0)}},Sf=e=>e===!1?null:typeof e=="function"?e:AC();var xC=/^\s*\|?[\s:|-]*-[\s:|-]*$/,MC=e=>e.includes("|"),EC=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},x0=e=>`| ${e.join(" | ")} |`,M0=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,E0=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),TC=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
14
- `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!MC(r)||xC.test(r)||!xC.test(s))continue;let i=EC(r).length;if(i<1)continue;let l=M0(i);t[o+1]!==l&&(t[o+1]=l,n=!0);let c=o+2;for(;c<t.length;c++){let p=t[c];if(p.trim()===""||!MC(p))break;let d=x0(E0(EC(p),i));t[c]!==d&&(t[c]=d,n=!0)}o=c-1}return n?t.join(`
15
- `):e};var PC="var(--persona-md-table-scroll-fade, 24px)",kC=new WeakSet;function HC(e){e.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function LC(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":PC),e.style.setProperty("--persona-fade-r",r<=1?"0px":PC)}function Af(e){kC.has(e)||(kC.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&LC(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(LC)}ei();ln();var{setLoader:$_,load:T0}=it({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var IC=T0;var P0="agent_",k0="flow_";function RC(e){return e.startsWith(P0)?{kind:"agentId",agentId:e}:e.startsWith(k0)?{kind:"flowId",flowId:e}:null}function WC(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let i=n.slice(0,o),l=n.slice(o+1);if(i==="runtype"){let p=RC(l);if(p)return p;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let c=t?.[i];if(!c)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(l).payload}}let r=RC(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new 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 L0(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ml(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function li(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function OC(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}ad();var H0=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),I0=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),R0=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=H0(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:I0(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},xf=(e,t)=>{let n=[],o=[],r=[],s="",i,l=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:r}),o=[],r=[])};for(let c of e){let p=R0(c);if(p){let g=c.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(g===void 0||g!==i)&&l(),o.length===0&&(s=c.createdAt,i=g),o.some(f=>f.toolCallId===p.call.toolCallId)||(o.push(p.call),r.push(p.result));continue}let d=t(c);d&&(l(),n.push(d))}return l(),n};ss();oa();Fd();Lo();var W0="https://api.runtype.com/v1/dispatch",tn=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},BC=e=>"reason"in e?e.reason:void 0,O0="The identity proof was rejected",Mf=(e,t)=>e instanceof tn&&e.code===t,Ef=e=>e.voiceCaption?!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),_C=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),DC=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function B0(e){switch(e){case"json":return xg;case"regex-json":return Ag;case"xml":return Mg;default:return Sg}}var pa=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.#g=null;this.clientSession=null;this.#l=null;this.#c=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#a=null;this.#E=!1;this.#h=!1;this.#S=!1;this.#v=null;this.#A=new Set;this.#d=new Set;this.webMcpBridge=null;this.#u=null;this.#$=null;this.#de=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=t.apiUrl??W0,this.#n={"Content-Type":"application/json","X-Persona-Version":Jn,...t.headers},this.debug=!!t.debug,this.#o=t.streamParser??B0(t.parserType),this.#t=t.contextProviders??[],this.#s=t.requestMiddleware,this.#r=t.customFetch,this.#p=t.parseSSEEvent,this.#f=t.getHeaders,t.webmcp?.enabled===!0&&(this.#u=this.#C(t.webmcp))}#e;#n;#o;#t;#s;#r;#p;#f;#i;#g;#l;#c;#a;#E;#h;#S;#v;#A;#d;#u;#m;#C(t){return IC().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:Qc,getToolDisplayTitle:Gi,loadPolyfill:Jc});return this.#m!==void 0&&o.setConfirmHandler(this.#m),this.webMcpBridge=o,o}).catch(n=>(this.#u=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#x(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#u||(this.#u=this.#C(this.config.webmcp)),this.#u)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.#i=t}setWebMcpConfirmHandler(t){this.#m=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.config.webmcp?.enabled!==!0?null:this.#x().then(r=>r?r.executeToolCall(t,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#i}isClientTokenMode(){return!!this.config.clientToken}#y(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=WC(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.#y().agentId)}#b(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ld}#H(t){return`${this.#b()}/v1/client/${t}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(t){let n=await this.initSession(),o=!1;for(;;){let r=n.conversationId,s=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!r||!s)throw new tn("visitor_token_missing","Durable recovery is not enabled for this client session");let i=`${this.#b()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:t.after}),c=await fetch(`${i}?${l}`,{method:"GET",headers:{"X-Persona-Version":Jn,"X-Visitor-Token":s},signal:t.signal});if(c.status===401&&!o){o=!0;let p=await Tr();n=await p.recoverFromUnauthorized(this.#W(),await p.readErrorCode(this.#W(),c),null,!0);continue}if(!c.ok)throw await(await Tr()).historyErrorFor(this.#W(),c,!0);return c}}async warmSession(){let t=this.clientSession;return!this.isClientTokenMode()||this.#l||t&&new Date<t.expiresAt||this.#c===t?null:(this.#c=t,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#l)return this.#l;let t=this.#l=this.#K().then(n=>this.#l!==t?this.initSession():(this.clientSession=n,this.#c=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#l===t&&(this.#l=null)});return t}#k(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#E}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}#M(){if(!this.#E){this.#B({state:"unavailable",reason:"history_disabled"}),this.#E=!0,!this.#h&&typeof console<"u"&&(this.#h=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.#d])t(!1)}}getHistoryIdentityStatus(){return this.#v??this.#I()}subscribeHistoryIdentityStatus(t){return this.#A.add(t),()=>{this.#A.delete(t)}}subscribeHistoryAvailability(t){return this.#d.add(t),this.#E&&t(!1),()=>{this.#d.delete(t)}}#I(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#E?{state:"unavailable",reason:"history_disabled"}:this.#Y():{state:"unavailable",reason:"ineligible_mode"}}#Y(){let t=this.#v;return t?.state==="browser_only"?t:this.#j()}#j(){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"}}#B(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&BC(n)===BC(t);if(this.#v=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.#A])r(t)}}async#T(t){let n=this.#k()&&!t.omitVisitorFields,o=!t.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.#y(),i=s.agentId??s.flowId,l=n||t.durableResume?t.conversationId:void 0,c={token:this.config.clientToken,...i&&{flowId:i},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&t.identityProof?{identityProof:t.identityProof}:{},...l?{conversationId:l}:t.storedSessionId?{sessionId:t.storedSessionId}:{}};t.signal?.throwIfAborted();let p=await fetch(this.#H("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Jn},body:JSON.stringify(c),signal:t.signal});if(!p.ok){let g=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&g.error==="visitor_history_disabled"){if(this.#M(),l)throw new tn("history_disabled","Visitor history is disabled for this surface");return this.#T({...t,omitVisitorFields:!0})}throw p.status===403&&g.error==="durable_recovery_disabled"?new tn("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&p.status===401&&g.error==="visitor_required"?new tn("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new tn("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${g.hint||g.error}`):p.status===403?new Error(`Origin not allowed: ${g.hint||g.error}`):new Error(g.error||"Failed to initialize session")}let d=await p.json();return d.visitor?.token&&await this.historyInternals.visitorStore?.set(d.visitor.token),{sessionId:d.sessionId,expiresAt:new Date(d.expiresAt),flow:d.flow,...d.conversationId?{conversationId:d.conversationId}:{},...d.targetId?{targetId:d.targetId}:{},...d.conversationRevision?{conversationRevision:d.conversationRevision}:{},...d.durableRecovery?{durableRecovery:d.durableRecovery}:{},...d.visitor?{visitor:d.visitor}:{},config:{welcomeMessage:d.config.welcomeMessage,placeholder:d.config.placeholder,theme:d.config.theme}}}async#K(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#k()&&!n)return this.#_(t,!1);let o=await this.readVisitorToken();if(t&&o)try{let r=await this.#T({conversationId:t,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#D(r,t,!1)}catch(r){if(!Mf(r,"not_found")&&!Mf(r,"visitor_required")&&!Mf(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#_(t,!0)}return this.#_(t,!1)}async#_(t,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#F(t,n)):this.#F(t,n)}async#F(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.#T({storedSessionId:o}),s=await this.#te(r);return this.#D(s,t,n)}async#ee(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.#T({storedSessionId:n,identityProof:t}),s=this.#D(r,o,!1);return this.clientSession=s,this.#l=null,this.#c=!1,this.resetClientToolsFingerprint(),s}async#te(t){if(!t.visitor?.token||this.#S||!this.#k()&&t.durableRecovery?.enabled!==!0)return t;this.#S=!0;try{return await this.#T({storedSessionId:t.sessionId})}catch{return t}finally{this.#S=!1}}#D(t,n,o){let r=t.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}#X(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.#c=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(t,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.#k())throw new tn("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new tn("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.#T({conversationId:t,identityProof:o});return this.#X(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.#T({});return this.#X(t)}handleExternalCredentialChange(){this.clearClientSession(),this.#k()&&this.#B(this.#j())}clearClientSession(){this.clientSession=null,this.#l=null,this.#c=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#a=null}#Z(){return`${this.#b()}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.#Z(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Jn},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.#c=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async#ne(t){t?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let r,s;try{let i=Promise.resolve().then(()=>o());r=t?await Promise.race([i,new Promise((l,c)=>{s=()=>c(t.reason),t.addEventListener("abort",s,{once:!0}),t.aborted&&s()})]):await i}catch{throw t?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{s&&t?.removeEventListener("abort",s)}if(typeof r!="string"||!r.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:r}}#$;#U(){let t=this;return this.#$??={get config(){return t.config},headers:this.#n,getHeaders:this.#f,debug:this.debug,clientApiBase:()=>t.#b(),getClientApiUrl:n=>t.#H(n),getWebMcpBridge:()=>t.#x(),sendWithClientToolsDiff:(n,o,r,s)=>t.#re(n,o,r,s),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}#de;#W(){let t=this;return this.#de??={HistoryClientError:tn,get config(){return t.config},get historyInternals(){return t.historyInternals},get clientSession(){return t.clientSession},clientApiBase:()=>t.#b(),setHistoryIdentityStatus:n=>t.#B(n),browserOnlyStatus:()=>t.#Y(),derivedBrowserOnly:()=>t.#j(),reinitWithProof:n=>t.#ee(n),isHistoryCapable:()=>t.#k(),clearClientSession:()=>t.clearClientSession(),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}async listConversations(t){return(await Tr()).listConversations(this.#W(),t)}async getConversation(t,n){return(await Tr()).getConversation(this.#W(),t,n)}async finalizeDisplayProjections(t,n){return(await Tr()).finalizeDisplayProjections(this.#W(),t,n)}async deleteConversation(t,n){return(await Tr()).deleteConversation(this.#W(),t,n)}async deleteAllConversations(t){return(await Tr()).deleteAllConversations(this.#W(),t)}async resetVisitor(){return(await Tr()).resetVisitor(this.#W())}async dispatch(t,n){return t.signal?.throwIfAborted(),oi().catch(()=>{}),this.isClientTokenMode()?this.#be(t,n):this.isAgentMode()?this.#pe(t,n):this.#oe(t,n)}async#be(t,n){let o=OC();this.#g=o;let r=()=>this.#g===o,s=i=>{r()&&n(i)};n({type:"status",status:"connecting"});try{let i=()=>{if(t.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},l=this.clientSession??await this.initSession();i();let c=async()=>{i();let A=l,L=A.durableRecovery?.enabled===!0;if(L&&(!A.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");i();let I=await this.#T({...L||this.#k()?{conversationId:A.conversationId,durableResume:L}:{storedSessionId:A.sessionId},signal:t.signal});if(i(),A.conversationId&&I.conversationId!==A.conversationId||L&&I.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.#D(I,A.conversationId??null,!1),this.clientSession=l,this.#c=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await c();let p=await this.#N(t.messages),d=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([A])=>A!=="sessionId"&&A!=="session_id")):void 0,g=this.#k(),f={sessionId:l.sessionId,messages:t.messages.filter(Ef).map(A=>{let L=g?Sl(A):void 0;return{id:A.id,role:A.role,content:A.contentParts??A.llmContent??A.rawContent??A.content,...L!==void 0&&{displayContent:L}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...d&&Object.keys(d).length>0&&{metadata:d},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"}},h=async()=>{i();let A=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return i(),this.#re(l.sessionId,p.clientTools,async L=>{i();let I=await this.#ne(t.signal);i();let H={...f,sessionId:l.sessionId,...L,...I&&{identityProof:I}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...H,...I&&{identityProof:{provider:I.provider,token:"[REDACTED]"}}}),fetch(this.#H("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Jn,...A?{"X-Visitor-Token":A}:{}},body:JSON.stringify(H),signal:t.signal})})},y=await h();if(i(),y.response.status===401){let A=await y.response.clone().json().catch(()=>null);i(),A?.error==="Session not found or expired"&&(await c(),y=await h(),i())}let{response:v,commit:C}=y;if(!v.ok){let A=await v.json().catch(()=>({error:"Chat request failed"}));if(v.status===401&&A.error==="invalid_identity_proof"){let I=new tn("invalid_identity_proof",O0);throw s({type:"error",error:I}),I}if(v.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let I=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:I}),I}if(v.status===429){let I=new Error(A.hint||"Message limit reached for this session.");throw s({type:"error",error:I}),I}if(v.status===410&&A.error==="conversation_deleted"){let I=new tn("conversation_deleted","This conversation was deleted");throw s({type:"error",error:I}),I}let L=new Error(A.error||"Failed to send message");throw s({type:"error",error:L}),L}if(!v.body){let A=new Error("No response body received");throw s({type:"error",error:A}),A}C(),s({type:"status",status:"connected"});try{await this.#G(v.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(i){let l=i instanceof Error?i:new Error(String(i));throw!(l instanceof tn)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async#oe(t,n){n({type:"status",status:"connecting"});let o=await this.#N(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.#n};if(this.#f)try{let i=await this.#f();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.#r)try{s=await this.#r(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.#G(s.body,n)}finally{n({type:"status",status:"idle"})}}async#pe(t,n){n({type:"status",status:"connecting"});let o=await this.#L(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.#n};if(this.#f)try{let i=await this.#f();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.#r)try{s=await this.#r(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.#G(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.#G(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){return(await oi()).resolveApproval(this.#U(),t,n)}async#re(t,n,o,r){let s=!!(n&&n.length>0),i=s?Mb(n):void 0,l=this.clientToolsFingerprintSessionId===t,c=s&&l&&this.lastSentClientToolsFingerprint===i,p=!s&&r?.emptyMeansReplace===!0&&this.#a===t,d=!1,g;for(let f=0;;f++){if(g=await o({...s&&(d||!c)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),g.status===409&&f===0&&s&&(await g.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){d=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,s?this.#a=t:p&&(this.#a=null)}}}async resumeFlow(t,n,o){return(await oi()).resumeFlow(this.#U(),t,n,o)}#se(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async#q(t){let n={};this.#t.length&&await Promise.all(this.#t.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.#se(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#R(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}#O(t,n){let o=n?.selectedModelId;return!o||!("model"in t)?t:this.config.composer?.models?.some(s=>s.id===o)?{...t,model:o}:t}async#L(t,n){let o=this.#y().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=xf(_C(t),p=>Ef(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?DC(p):null),s=this.#R(n),i={agent:this.#O(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(i.composerOptions=s);let l=[...ta(this.config),...await(await this.#x())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#q(t);return c&&(i.context=c),i}async#N(t,n){let o=xf(_C(t),p=>Ef(p)?DC(p):null),r=this.#y(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,d]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=d);let i=[...ta(this.config),...await(await this.#x())?.snapshotForDispatch()??[]];i.length>0&&(s.clientTools=i);let l=await this.#q(t);l&&(s.context=l);let c=this.#R(n);if(c&&(s.composerOptions=c),this.#s)try{let p=await this.#s({payload:{...s},config:this.config});if(p&&typeof p=="object"){let d=p;return s.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=s.clientTools),d}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async#G(t,n,o,r){let{streamResponse:s}=rv()??await oi();return s({config:()=>this.config,createStreamParser:this.#o,parseSSEEvent:this.#p,onSSEEvent:(i,l)=>this.#i?.(i,l)},t,n,o,r)}};var hs=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function _0(e){return e instanceof hs}ei();ea();Hr();Yi();Hr();function D0(e){let t=0;for(let n of e.split(`
16
- `)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>t&&(t=o[1].length)}return t}function NC(e,t){let n="`".repeat(Math.max(3,D0(t)+1));return`${n}${e}
13
+ ${E.description}`)},$t=async E=>await Ms({host:wi(),title:o.deleteConversationConfirmTitle,description:o.deleteConversationConfirm,confirmLabel:o.deleteConversationConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await rc(E),"deleted"):"cancelled",Ts=async()=>{let E=B()==="verified-user";return await Ms({host:wi(),title:o.clearHistoryConfirmTitle,description:E?o.clearHistoryVerifiedConfirm:o.clearHistoryConfirm,confirmLabel:o.clearHistoryConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Ra(),"cleared"):"cancelled"},Oa=async()=>{if(!await Ms({host:wi(),title:o.resetIdentityConfirmTitle,description:o.resetIdentityConfirm,confirmLabel:o.resetIdentityConfirmLabel,cancelLabel:o.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:N}=await Wa();return{outcome:"reset",remoteRevocationConfirmed:N}},Zt=x("button","persona-history-earlier");Zt.type="button",Zt.textContent=o.showEarlierMessagesLabel,Zt.setAttribute("data-persona-history-earlier",""),Object.assign(Zt.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 Yt=()=>{if(!(L()&&!!e.historySessionState.nextMessageCursor&&!!e.session.getActiveConversationId())){Zt.remove();return}Zt.textContent=o.showEarlierMessagesLabel,Zt.parentNode!==e.body&&e.body.insertBefore(Zt,e.body.firstChild)};Zt.addEventListener("click",()=>{let E=e.session.getActiveConversationId(),N=e.historySessionState.nextMessageCursor;if(!E||!N||Zt.disabled)return;Zt.disabled=!0;let ee=e.body.scrollHeight,ce=e.body.scrollTop;e.session.loadOlderMessages(E,N,{scope:B()}).then(()=>{e.body.scrollTop=ce+(e.body.scrollHeight-ee),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Zt.disabled=!1,Yt()})});let So=()=>{let E=e.createHeaderIconButton({ariaLabel:o.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 E.button.addEventListener("click",N=>{if(!(!L()||I())){if(e.historyVisible){Sn();return}qe({invoker:E.button,keyboard:N.detail===0})}}),E},Fr=()=>{if(!L()){g?.remove(),d=null,g=null;return}if(g&&!g.isConnected&&(d=null,g=null),!d&&e.header){let ce=So();d=ce.button,g=ce.wrapper;let He=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;He?.parentNode&&e.header.contains(He)?He.parentNode.insertBefore(g,He):e.header.appendChild(g)}if(!d||!g)return;let E=Gn()||e.historyVisible&&e.historyPresentation==="rail";if(g.style.display=E?"none":"",E){document.activeElement===d&&gt();return}let N=I();d.disabled=N,d.setAttribute("aria-disabled",N?"true":"false");let ee=N?o.openHistoryBusyLabel:o.openHistoryLabel;d.setAttribute("aria-label",ee),(e.config.features?.history?.presentation??"panel")==="panel"?(d.removeAttribute("aria-expanded"),d.removeAttribute("aria-controls")):(d.setAttribute("aria-expanded",e.historyVisible?"true":"false"),d.setAttribute("aria-controls",A))},cr=!1,ks=()=>{let E=e.panelElements.clearChatButton;if(E){if(L()){cr||(y=E.getAttribute("aria-label")??"",cr=!0),E.setAttribute("aria-label",o.newConversationLabel),E.removeAttribute("title");return}cr&&(cr=!1,y&&E.setAttribute("aria-label",y))}},$n=()=>{o=vf(e.config.features?.history?.copy),Fr(),lr(),ks(),Yt()};return e.historyChromeSync=$n,T(),$n(),e.destroyCallbacks.push(()=>{b?.(),C?.(),h+=1,Ci(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:L,historyScope:H,installHistoryProvider:T,syncHistoryChromeImpl:$n,syncHistoryPresentation:_o,syncEarlierMessagesPill:Yt,openHistory:qe,closeHistory:Sn,openHistoryConversation:An,startNewConversation:wo,updateHistoryConversation:Es,deleteHistoryConversation:rc,requestDeleteConversation:$t,clearConversationHistory:Ra,resetHistoryIdentity:Wa,railCollapseShortcut:bi,railCollapsible:D,railTriggerApplies:Gn,railOverlayMode:bt,toggleRailCollapsed:yi,toggleRailPinned:()=>so(),get historyProvider(){return r},get historySurface(){return i},get railShell(){return St},get railHost(){return Se},get railColumn(){return It}}}});var ga,Rf=$e(()=>{"use strict";ga=class{#e=null;#n=0;#o=[];#t=[];#s=[];#r=!1;#p=!1;#f=0;#i=!1;#u=!1;#c;#l=[];#a=0;#M=!1;#h;#x;#S;#E=null;constructor(t=24e3,n={}){this.#x=t;let o=Math.max(0,n.prebufferMs??0);this.#S=Math.round(t*o/1e3),this.#c=this.#S>0}#d(){if(!this.#e){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.#e=new o({sampleRate:this.#x})}let t=this.#e;return t.state==="suspended"&&!this.#u&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.#E){let r=new Uint8Array(this.#E.length+t.length);r.set(this.#E),r.set(t,this.#E.length),n=r,this.#E=null}if(n.length%2!==0&&(this.#E=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.#C(n);o.length!==0&&(this.#c?(this.#l.push(o),this.#a+=o.length,clearTimeout(this.#h),this.#a>=this.#S?this.#g():this.#M&&(this.#h=setTimeout(()=>this.#g(),this.#S/this.#x*1e3))):this.#m(o))}markStreamEnd(){this.#l.length>0&&this.#g(),this.#p=!0,this.#A()}flush(){for(let t of this.#o){t.onended=null;try{t.stop(),t.disconnect()}catch{}}this.#o=[],this.#f=0,this.#n=0,this.#r=!1,this.#p=!1,this.#t=[],this.#s=[],this.#E=null,this.#l=[],this.#a=0,this.#c=this.#S>0,this.#i=!1,clearTimeout(this.#h)}setContinuousMode(t){this.#M=t}isPlaying(){return this.#r}onFinished(t){this.#t.push(t)}onStarted(t){this.#s.push(t)}pause(){this.#u=!0,this.#e&&this.#e.state==="running"&&this.#e.suspend()}resume(){this.#u=!1,this.#e&&this.#e.state==="suspended"&&this.#e.resume()}async destroy(){this.flush(),this.#e&&(await this.#e.close(),this.#e=null)}#g(){this.#c=!1;let t=this.#l;this.#l=[],this.#a=0;for(let n of t)this.#m(n)}#m(t){if(t.length===0)return;let n=this.#d(),o=n.createBuffer(1,t.length,this.#x);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.#n===0?this.#n=s:this.#n<s&&(this.#n=s,this.#S>0&&(this.#c=!0)),r.start(this.#n),this.#n+=o.duration,this.#o.push(r),this.#f++,this.#r=!0,!this.#i){this.#i=!0;let i=this.#s.slice();this.#s=[];for(let l of i)l()}r.onended=()=>{let i=this.#o.indexOf(r);i!==-1&&(this.#o.splice(i,1),this.#f--,this.#A())}}#A(){if(this.#p&&this.#f<=0&&this.#l.length===0){this.#r=!1,this.#p=!1;let t=this.#t.slice();this.#t=[];for(let n of t)n()}}#C(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let i=r.getInt16(s*2,!0);o[s]=i/32768}return o}}});function Y0(e){return e.replace(/\/+$/,"")}async function X0(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 ep,YC=$e(()=>{"use strict";Rf();ep=class{constructor(t){this.id="runtype-tts";this.supportsPause=!0;this.#e=null;this.#n=null;this.#o=0;this.#t=t}#e;#n;#o;#t;#s(){return this.#n??=Promise.resolve(this.#t.createPlaybackEngine?this.#t.createPlaybackEngine():new ga(24e3,{prebufferMs:this.#t.prebufferMs??200})).then(t=>this.#e=t)}speak(t,n){let o=++this.#o;this.#r(o,t,n)}async#r(t,n,o){try{let r=await this.#s();if(t!==this.#o)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.#o&&o.onStart?.()}),r.onFinished(()=>{t===this.#o&&o.onEnd?.()});let s=`${Y0(this.#t.host)}/v1/agents/${encodeURIComponent(this.#t.agentId)}/speak`,i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.#t.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.#t.voice,format:"pcm"})});if(t!==this.#o)return;if(!i.ok||!i.body)throw new Error(await X0(i));let l=i.body.getReader();for(;;){let{done:c,value:p}=await l.read();if(t!==this.#o){await l.cancel().catch(()=>{});return}if(c)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(t!==this.#o)return;let s=r instanceof Error?r:new Error(String(r));this.#t.onError?.(s),o.onError?.(s)}}pause(){this.#e?.pause()}resume(){this.#e?.resume()}stop(){this.#o++,this.#e?.flush()}destroy(){this.#o++,this.#e?.destroy(),this.#e=null,this.#n=null}}});var tp,XC=$e(()=>{"use strict";tp=class{constructor(t,n,o={}){this.id="fallback";this.#n=t,this.#o=n,this.#t=o,this.#e=t}#e;#n;#o;#t;get supportsPause(){return this.#e.supportsPause}speak(t,n){this.#e=this.#n;let o=!1;this.#n.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.#t.onFallback?.(r),this.#e=this.#o,this.#o.speak(t,n)}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#n.destroy?.(),this.#o.destroy?.()}}});var QC={};Qs(QC,{FallbackSpeechEngine:()=>tp,RuntypeSpeechEngine:()=>ep});var JC=$e(()=>{"use strict";YC();XC()});import{Marked as VE}from"marked";import jE from"dompurify";ln();var{setLoader:dO,load:$E,provide:UE,getSync:yg}=it({fallbackImport:()=>Promise.resolve().then(()=>(wb(),Cb))}),Yc=new Set,Sb=()=>{let e=[...Yc];Yc.clear();for(let t of e)try{t()}catch{}};var bg=()=>{let e=yg();return e?Promise.resolve(e):$E().then(t=>(Sb(),t))},il=e=>yg()?()=>{}:(Yc.add(e),()=>{Yc.delete(e)}),Ab=e=>{UE(e),Sb()},Yo=yg;Ab({Marked:VE,DOMPurify:jE});import{Ban as qE,Bell as zE,Bookmark as KE,Building as GE,Calendar as YE,CalendarDays as XE,Camera as QE,ChartColumn as JE,CircleCheck as ZE,CircleX as eM,Clock as tM,CreditCard as nM,DollarSign as oM,EyeOff as rM,Files as sM,Film as iM,Flag as aM,Folder as lM,FolderOpen as cM,Funnel as dM,Gift as pM,Globe as uM,Hash as gM,Headphones as fM,Heart as mM,House as hM,Image as yM,Info as bM,Key as vM,Lightbulb as CM,Link as wM,Lock as SM,Mail as AM,MapPin as xM,MessageCircle as EM,Monitor as MM,Moon as TM,Package as kM,Pause as PM,PenLine as LM,Percent as HM,Phone as IM,Play as RM,Receipt as WM,RotateCw as OM,Save as _M,Settings as BM,Share as DM,Shield as NM,ShoppingBag as FM,ShoppingCart as $M,Smartphone as UM,Sparkles as VM,Store as jM,Sun as qM,Tag as zM,Timer as KM,TriangleAlert as GM,Truck as YM,User as XM,VolumeX as QM,Wallet as JM,Zap as ZM}from"lucide";var xb={user:XM,mail:AM,phone:IM,calendar:YE,clock:tM,building:GE,"map-pin":xM,lock:SM,key:vM,"credit-card":nM,hash:gM,globe:uM,link:wM,"circle-check":ZE,"circle-x":eM,"triangle-alert":GM,info:bM,ban:qE,shield:NM,house:hM,"pen-line":LM,save:_M,share:DM,funnel:dM,settings:BM,"rotate-cw":OM,"shopping-cart":$M,"shopping-bag":FM,package:kM,truck:YM,tag:zM,gift:pM,receipt:WM,wallet:JM,store:jM,"dollar-sign":oM,percent:HM,play:RM,pause:PM,"volume-x":QM,camera:QE,image:yM,film:iM,headphones:fM,"message-circle":EM,bell:zE,heart:mM,"eye-off":rM,bookmark:KE,"calendar-days":XE,timer:KM,folder:lM,"folder-open":cM,files:sM,"chart-column":JE,sparkles:VM,zap:ZM,sun:qM,moon:TM,flag:aM,lightbulb:CM,monitor:MM,smartphone:UM};Tt();Mb(xb);Bg();ln();var{setLoader:GO,load:zk,provide:Kk,getSync:Gk}=it({fallbackImport:()=>Promise.resolve().then(()=>(Bg(),pd))});var oi=zk,av=Kk,lv=Gk;av(pd);$g();ln();var{setLoader:n_,load:aP,provide:lP}=it({fallbackImport:()=>Promise.resolve().then(()=>($g(),ud))});var Tr=aP,vv=lP;vv(ud);ff();ln();var{setLoader:rB,load:NP,provide:FP,getSync:$P}=it({fallbackImport:()=>Promise.resolve().then(()=>(ff(),Rd))});var Wd=NP,Zv=FP,mf=$P;Zv(Rd);yf();ln();var{setLoader:cB,load:YP,provide:XP,getSync:QP}=it({fallbackImport:()=>Promise.resolve().then(()=>(yf(),_d))});var bf=YP,nC=XP,oC=QP;nC(_d);Af();ln();var{setLoader:MB,load:p0,provide:u0,getSync:g0}=it({fallbackImport:()=>Promise.resolve().then(()=>(Af(),Vd))});var yC=p0,bC=u0,jd=g0;bC(Vd);Er();vo();Qe();Tt();import{Circle as C0,Clock as w0}from"lucide";Qe();Er();import{ChevronDown as f0,ChevronUp as m0}from"lucide";var h0=["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"],y0="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",b0="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",v0=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),qd=(e,t)=>{let n=x("div",["persona-message-bubble",e,...h0].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},zd=e=>{let t=x("button",e.expandable?y0:b0);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},xf=(e,t,n)=>{e.innerHTML="";let o=Bt(t?m0:f0,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},da=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=x("div","persona-flex persona-items-center");xf(o,n.expanded,n.iconColor);let r=x("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(o),e.append(t,r),o},Kd=e=>{let t=x("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?.();v0(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Gd=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&xf(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"},Yd=(e,t,n)=>{let o=n.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!r||!s)return;r.setAttribute("aria-expanded",o?"true":"false");let c=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");c&&xf(c,o,n.iconColor),s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")};function Xd(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[n]:{...t==="tool"?Pr:ai,...e?.future?.v5Defaults===!0?ii.features?.[n]:{},...e?.features?.[n]}}}}function fs(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[n]?.variant??(e?.future?.v5Defaults?"row":"card")}function xl(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 Rr(e,t,n,o){if(fs(n,o)!=="row")return e;e.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,e.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(e.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let r=e.querySelector(":scope > button");if(!r)return e;r.className="persona-activity-header";let s=o==="tool"?t.toolCall:t.reasoning,i=s?.status!=="complete",l=t.approval?.status??t.toolCall?.approvalStatus,c=l==="denied"?"denied":l==="pending"?"awaiting-approval":t.toolCall?.success===!1?"error":i?s?.status==="pending"?"pending":"running":"done";e.dataset.activityState=c;let p=x("span","persona-activity-icon");p.dataset.activityIcon=c;let d={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},g=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,f=g?ue(g,16,"currentColor",2):c==="pending"?Bt(C0,16,"currentColor",2):c==="awaiting-approval"?Bt(w0,16,"currentColor",2):ue(d[c],16,"currentColor",2);f&&p.appendChild(f),r.querySelector(".persona-reasoning-header-icon")?.remove();let h=o==="tool"?"toolCallDisplay":"reasoningDisplay",y=n.features?.[h]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((y==="always"||y==="active"&&c!=="done")&&r.prepend(p),o==="tool"&&s){let L=x("span","persona-activity-duration");i&&s.startedAt&&L.setAttribute("data-tool-elapsed",String(s.startedAt));let I=(o==="tool"?t.toolCall?.duration:void 0)??s.durationMs??(s.completedAt!==void 0&&s.startedAt!==void 0?s.completedAt-s.startedAt:void 0);L.textContent=I===void 0?"":xl(I),r.appendChild(L)}r.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),r.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let A=e.querySelector(":scope > .persona-border-t");return A?.classList.add("persona-activity-body"),A&&(A.id=`activity-details-${t.id}`,r.setAttribute("aria-controls",A.id)),e}function vC(e){let t=new Set,n=new Set,o=new Set,r=new Map,s=i=>{clearTimeout(r.get(i)),r.delete(i)};return{observe(i,l,c,p={}){let d=l==="tool"?i.toolCall:i.reasoning;if(!(!d||n.has(i.id))&&(!t.has(i.id)&&d.status!=="complete"&&d.chunks?.some(Boolean)&&(t.add(i.id),p.autoExpand!==!1&&c.add(i.id)),t.has(i.id)&&d.status==="complete"&&!o.has(i.id))){if(o.add(i.id),p.autoCollapseDelay===!1)return;r.set(i.id,setTimeout(()=>{r.delete(i.id),c.delete(i.id),e(i.id,l)},p.autoCollapseDelay??1e3))}},manual(i){n.add(i),s(i)},prune(i){for(let l of new Set([...t,...n,...o]))i.has(l)||(s(l),t.delete(l),n.delete(l),o.delete(l))},clear(){for(let i of r.keys())s(i);t.clear(),n.clear(),o.clear()}}}function CC(e,t,n,o){let r=x("div","");r.id=`bubble-${e.id}`,r.dataset.messageId=e.id;let s=x("button","");s.type="button",s.dataset.expandHeader="true",s.dataset.bubbleType="tool",s.setAttribute("aria-expanded",String(n));let i=x("div","");typeof o=="string"?i.textContent=o:i.appendChild(o),da(s,i,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let l=x("div","persona-border-t");return l.id=`activity-details-${e.id}`,l.style.display=n?"":"none",s.setAttribute("aria-controls",l.id),r.append(s,l),Rr(r,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:"row"}}},"tool"),r.dataset.personaToolGroup="true",t.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(r.dataset.activityGroupShimmer="true"),{bubble:r,body:l}}zg();function wC(e,t){let n=e.voiceRecognition,o=t.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function Ln(e){return e?.type==="runtype"||e?.type==="custom"}var S0=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function SC(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:S0()}catch{return!1}}var A0=e=>{if(!e)return;let t={},n=e;if(n.heading){let o=n.heading;t.heading=(r,s,i)=>o({type:"heading",raw:i,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;t.code=(r,s,i)=>o({type:"code",raw:"",text:r,lang:s,escaped:i})}if(n.blockquote){let o=n.blockquote;t.blockquote=r=>o({type:"blockquote",raw:"",text:r,tokens:[]})}if(n.table){let o=n.table;t.table=(r,s)=>o({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:s})}if(n.link){let o=n.link;t.link=(r,s,i)=>o({type:"link",raw:"",href:r,title:s??null,text:i,tokens:[]})}if(n.image){let o=n.image;t.image=(r,s,i)=>o({type:"image",raw:"",href:r,title:s??null,text:i})}if(n.list){let o=n.list;t.list=(r,s,i)=>o({type:"list",raw:"",ordered:s,start:i,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;t.listitem=(r,s,i)=>o({type:"list_item",raw:"",task:s,checked:i,loose:!1,text:r,tokens:[]})}if(n.paragraph){let o=n.paragraph;t.paragraph=r=>o({type:"paragraph",raw:"",text:r,tokens:[]})}if(n.codespan){let o=n.codespan;t.codespan=r=>o({type:"codespan",raw:"",text:r})}if(n.strong){let o=n.strong;t.strong=r=>o({type:"strong",raw:"",text:r,tokens:[]})}if(n.em){let o=n.em;t.em=r=>o({type:"em",raw:"",text:r,tokens:[]})}if(n.del){let o=n.del;t.del=r=>o({type:"del",raw:"",text:r,tokens:[]})}if(n.html){let o=n.html;t.html=r=>o({type:"html",raw:r,text:r})}if(n.text){let o=n.text;t.text=r=>o({type:"text",raw:r,text:r})}if(n.checkbox){let o=n.checkbox;t.checkbox=r=>o({checked:r})}return n.hr&&(t.hr=n.hr),n.br&&(t.br=n.br),t},Qd=e=>{let t=null;return n=>{let o=Yo();if(!o)return ms(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let i=A0(e?.renderer);i&&t.use({renderer:i})}return t.parse(n)}},Jd=e=>e?Qd({markedOptions:e.options,renderer:e.renderer}):Qd(),x0=Qd(),xC=e=>x0(e),ms=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),EC=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),AC=e=>`%%FORM_PLACEHOLDER_${e}%%`,MC=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=AC(t.length);return t.push({token:i,type:String(s.type)}),i}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=AC(t.length);return t.push({token:s,type:r}),s}),n},E0=e=>{let t=Jd(e);return n=>{let o=[],r=MC(n,o),s=t(r);return o.forEach(({token:i,type:l})=>{let c=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${EC(l)}"></div>`;s=s.replace(c,d)}),s}},M0=e=>{let t=[],n=MC(e,t),o=xC(n);return t.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${EC(s)}"></div>`;o=o.replace(i,c)}),o};var T0={ALLOWED_TAGS:["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"],ALLOWED_ATTR:["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"]},k0=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,TC=()=>{let e=null;return t=>{let n=Yo();if(!n)return ms(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let i=s.attrValue;i.toLowerCase().startsWith("data:")&&!k0.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,T0)}},Ef=e=>e===!1?null:typeof e=="function"?e:TC();var kC=/^\s*\|?[\s:|-]*-[\s:|-]*$/,PC=e=>e.includes("|"),LC=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},P0=e=>`| ${e.join(" | ")} |`,L0=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,H0=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),HC=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
14
+ `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!PC(r)||kC.test(r)||!kC.test(s))continue;let i=LC(r).length;if(i<1)continue;let l=L0(i);t[o+1]!==l&&(t[o+1]=l,n=!0);let c=o+2;for(;c<t.length;c++){let p=t[c];if(p.trim()===""||!PC(p))break;let d=P0(H0(LC(p),i));t[c]!==d&&(t[c]=d,n=!0)}o=c-1}return n?t.join(`
15
+ `):e};var IC="var(--persona-md-table-scroll-fade, 24px)",RC=new WeakSet;function OC(e){e.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function WC(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":IC),e.style.setProperty("--persona-fade-r",r<=1?"0px":IC)}function Mf(e){RC.has(e)||(RC.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&WC(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(WC)}ei();ln();var{setLoader:YB,load:I0}=it({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var _C=I0;var R0="agent_",W0="flow_";function BC(e){return e.startsWith(R0)?{kind:"agentId",agentId:e}:e.startsWith(W0)?{kind:"flowId",flowId:e}:null}function DC(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let i=n.slice(0,o),l=n.slice(o+1);if(i==="runtype"){let p=BC(l);if(p)return p;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let c=t?.[i];if(!c)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(l).payload}}let r=BC(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new 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 O0(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function El(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function li(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function NC(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}cd();var _0=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),B0=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),D0=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=_0(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:B0(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},Tf=(e,t)=>{let n=[],o=[],r=[],s="",i,l=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:r}),o=[],r=[])};for(let c of e){let p=D0(c);if(p){let g=c.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(g===void 0||g!==i)&&l(),o.length===0&&(s=c.createdAt,i=g),o.some(f=>f.toolCallId===p.call.toolCallId)||(o.push(p.call),r.push(p.result));continue}let d=t(c);d&&(l(),n.push(d))}return l(),n};ss();oa();Ud();Lo();var N0="https://api.runtype.com/v1/dispatch",tn=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},FC=e=>"reason"in e?e.reason:void 0,F0="The identity proof was rejected",kf=(e,t)=>e instanceof tn&&e.code===t,Pf=e=>e.voiceCaption?!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),$C=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),UC=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function $0(e){switch(e){case"json":return Tg;case"regex-json":return Mg;case"xml":return kg;default:return Eg}}var pa=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.#u=null;this.clientSession=null;this.#c=null;this.#l=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#a=null;this.#M=!1;this.#h=!1;this.#x=!1;this.#S=null;this.#E=new Set;this.#d=new Set;this.webMcpBridge=null;this.#g=null;this.#z=null;this.#ie=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=t.apiUrl??N0,this.#n={"Content-Type":"application/json","X-Persona-Version":Zn,...t.headers},this.debug=!!t.debug,this.#o=t.streamParser??$0(t.parserType),this.#t=t.contextProviders??[],this.#s=t.requestMiddleware,this.#r=t.customFetch,this.#p=t.parseSSEEvent,this.#f=t.getHeaders,t.webmcp?.enabled===!0&&(this.#g=this.#A(t.webmcp))}#e;#n;#o;#t;#s;#r;#p;#f;#i;#u;#c;#l;#a;#M;#h;#x;#S;#E;#d;#g;#m;#A(t){return _C().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:Zc,getToolDisplayTitle:Gi,loadPolyfill:ed});return this.#m!==void 0&&o.setConfirmHandler(this.#m),this.webMcpBridge=o,o}).catch(n=>(this.#g=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#C(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#g||(this.#g=this.#A(this.config.webmcp)),this.#g)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.#i=t}setWebMcpConfirmHandler(t){this.#m=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.config.webmcp?.enabled!==!0?null:this.#C().then(r=>r?r.executeToolCall(t,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#i}isClientTokenMode(){return!!this.config.clientToken}#b(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=DC(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.#b().agentId)}#y(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||dd}#I(t){return`${this.#y()}/v1/client/${t}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(t){let n=await this.initSession(),o=!1;for(;;){let r=n.conversationId,s=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!r||!s)throw new tn("visitor_token_missing","Durable recovery is not enabled for this client session");let i=`${this.#y()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:t.after}),c=await fetch(`${i}?${l}`,{method:"GET",headers:{"X-Persona-Version":Zn,"X-Visitor-Token":s},signal:t.signal});if(c.status===401&&!o){o=!0;let p=await Tr();n=await p.recoverFromUnauthorized(this.#W(),await p.readErrorCode(this.#W(),c),null,!0);continue}if(!c.ok)throw await(await Tr()).historyErrorFor(this.#W(),c,!0);return c}}async warmSession(){let t=this.clientSession;return!this.isClientTokenMode()||this.#c||t&&new Date<t.expiresAt||this.#l===t?null:(this.#l=t,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#c)return this.#c;let t=this.#c=this.#J().then(n=>this.#c!==t?this.initSession():(this.clientSession=n,this.#l=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#c===t&&(this.#c=null)});return t}#T(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#M}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}#w(){if(!this.#M){this.#q({state:"unavailable",reason:"history_disabled"}),this.#M=!0,!this.#h&&typeof console<"u"&&(this.#h=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.#d])t(!1)}}getHistoryIdentityStatus(){return this.#S??this.#_()}subscribeHistoryIdentityStatus(t){return this.#E.add(t),()=>{this.#E.delete(t)}}subscribeHistoryAvailability(t){return this.#d.add(t),this.#M&&t(!1),()=>{this.#d.delete(t)}}#_(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#M?{state:"unavailable",reason:"history_disabled"}:this.#Q():{state:"unavailable",reason:"ineligible_mode"}}#Q(){let t=this.#S;return t?.state==="browser_only"?t:this.#G()}#G(){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"}}#q(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&FC(n)===FC(t);if(this.#S=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.#E])r(t)}}async#k(t){let n=this.#T()&&!t.omitVisitorFields,o=!t.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.#b(),i=s.agentId??s.flowId,l=n||t.durableResume?t.conversationId:void 0,c={token:this.config.clientToken,...i&&{flowId:i},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&t.identityProof?{identityProof:t.identityProof}:{},...l?{conversationId:l}:t.storedSessionId?{sessionId:t.storedSessionId}:{}};t.signal?.throwIfAborted();let p=await fetch(this.#I("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Zn},body:JSON.stringify(c),signal:t.signal});if(!p.ok){let g=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&g.error==="visitor_history_disabled"){if(this.#w(),l)throw new tn("history_disabled","Visitor history is disabled for this surface");return this.#k({...t,omitVisitorFields:!0})}throw p.status===403&&g.error==="durable_recovery_disabled"?new tn("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&p.status===401&&g.error==="visitor_required"?new tn("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new tn("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${g.hint||g.error}`):p.status===403?new Error(`Origin not allowed: ${g.hint||g.error}`):new Error(g.error||"Failed to initialize session")}let d=await p.json();return d.visitor?.token&&await this.historyInternals.visitorStore?.set(d.visitor.token),{sessionId:d.sessionId,expiresAt:new Date(d.expiresAt),flow:d.flow,...d.conversationId?{conversationId:d.conversationId}:{},...d.targetId?{targetId:d.targetId}:{},...d.conversationRevision?{conversationRevision:d.conversationRevision}:{},...d.durableRecovery?{durableRecovery:d.durableRecovery}:{},...d.visitor?{visitor:d.visitor}:{},config:{welcomeMessage:d.config.welcomeMessage,placeholder:d.config.placeholder,theme:d.config.theme}}}async#J(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#T()&&!n)return this.#B(t,!1);let o=await this.readVisitorToken();if(t&&o)try{let r=await this.#k({conversationId:t,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#P(r,t,!1)}catch(r){if(!kf(r,"not_found")&&!kf(r,"visitor_required")&&!kf(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#B(t,!0)}return this.#B(t,!1)}async#B(t,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#R(t,n)):this.#R(t,n)}async#R(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.#k({storedSessionId:o}),s=await this.#re(r);return this.#P(s,t,n)}async#Z(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.#k({storedSessionId:n,identityProof:t}),s=this.#P(r,o,!1);return this.clientSession=s,this.#c=null,this.#l=!1,this.resetClientToolsFingerprint(),s}async#re(t){if(!t.visitor?.token||this.#x||!this.#T()&&t.durableRecovery?.enabled!==!0)return t;this.#x=!0;try{return await this.#k({storedSessionId:t.sessionId})}catch{return t}finally{this.#x=!1}}#P(t,n,o){let r=t.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}#F(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.#l=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(t,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.#T())throw new tn("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new tn("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.#k({conversationId:t,identityProof:o});return this.#F(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.#k({});return this.#F(t)}handleExternalCredentialChange(){this.clearClientSession(),this.#T()&&this.#q(this.#G())}clearClientSession(){this.clientSession=null,this.#c=null,this.#l=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#a=null}#U(){return`${this.#y()}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.#U(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Zn},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.#l=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async#se(t){t?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let r,s;try{let i=Promise.resolve().then(()=>o());r=t?await Promise.race([i,new Promise((l,c)=>{s=()=>c(t.reason),t.addEventListener("abort",s,{once:!0}),t.aborted&&s()})]):await i}catch{throw t?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{s&&t?.removeEventListener("abort",s)}if(typeof r!="string"||!r.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:r}}#z;#D(){let t=this;return this.#z??={get config(){return t.config},headers:this.#n,getHeaders:this.#f,debug:this.debug,clientApiBase:()=>t.#y(),getClientApiUrl:n=>t.#I(n),getWebMcpBridge:()=>t.#C(),sendWithClientToolsDiff:(n,o,r,s)=>t.#Y(n,o,r,s),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}#ie;#W(){let t=this;return this.#ie??={HistoryClientError:tn,get config(){return t.config},get historyInternals(){return t.historyInternals},get clientSession(){return t.clientSession},clientApiBase:()=>t.#y(),setHistoryIdentityStatus:n=>t.#q(n),browserOnlyStatus:()=>t.#Q(),derivedBrowserOnly:()=>t.#G(),reinitWithProof:n=>t.#Z(n),isHistoryCapable:()=>t.#T(),clearClientSession:()=>t.clearClientSession(),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}async listConversations(t){return(await Tr()).listConversations(this.#W(),t)}async getConversation(t,n){return(await Tr()).getConversation(this.#W(),t,n)}async finalizeDisplayProjections(t,n){return(await Tr()).finalizeDisplayProjections(this.#W(),t,n)}async deleteConversation(t,n){return(await Tr()).deleteConversation(this.#W(),t,n)}async deleteAllConversations(t){return(await Tr()).deleteAllConversations(this.#W(),t)}async resetVisitor(){return(await Tr()).resetVisitor(this.#W())}async dispatch(t,n){return t.signal?.throwIfAborted(),oi().catch(()=>{}),this.isClientTokenMode()?this.#be(t,n):this.isAgentMode()?this.#ae(t,n):this.#ve(t,n)}async#be(t,n){let o=NC();this.#u=o;let r=()=>this.#u===o,s=i=>{r()&&n(i)};n({type:"status",status:"connecting"});try{let i=()=>{if(t.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},l=this.clientSession??await this.initSession();i();let c=async()=>{i();let A=l,L=A.durableRecovery?.enabled===!0;if(L&&(!A.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");i();let I=await this.#k({...L||this.#T()?{conversationId:A.conversationId,durableResume:L}:{storedSessionId:A.sessionId},signal:t.signal});if(i(),A.conversationId&&I.conversationId!==A.conversationId||L&&I.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.#P(I,A.conversationId??null,!1),this.clientSession=l,this.#l=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await c();let p=await this.#$(t.messages),d=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([A])=>A!=="sessionId"&&A!=="session_id")):void 0,g=this.#T(),f={sessionId:l.sessionId,messages:t.messages.filter(Pf).map(A=>{let L=g?Sl(A):void 0;return{id:A.id,role:A.role,content:A.contentParts??A.llmContent??A.rawContent??A.content,...L!==void 0&&{displayContent:L}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...d&&Object.keys(d).length>0&&{metadata:d},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"},...t.voiceSpoken&&{voice:{spoken:!0}}},h=async()=>{i();let A=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return i(),this.#Y(l.sessionId,p.clientTools,async L=>{i();let I=await this.#se(t.signal);i();let H={...f,sessionId:l.sessionId,...L,...I&&{identityProof:I}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...H,...I&&{identityProof:{provider:I.provider,token:"[REDACTED]"}}}),fetch(this.#I("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Zn,...A?{"X-Visitor-Token":A}:{}},body:JSON.stringify(H),signal:t.signal})})},y=await h();if(i(),y.response.status===401){let A=await y.response.clone().json().catch(()=>null);i(),A?.error==="Session not found or expired"&&(await c(),y=await h(),i())}let{response:b,commit:C}=y;if(!b.ok){let A=await b.json().catch(()=>({error:"Chat request failed"}));if(b.status===401&&A.error==="invalid_identity_proof"){let I=new tn("invalid_identity_proof",F0);throw s({type:"error",error:I}),I}if(b.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let I=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:I}),I}if(b.status===429){let I=new Error(A.hint||"Message limit reached for this session.");throw s({type:"error",error:I}),I}if(b.status===410&&A.error==="conversation_deleted"){let I=new tn("conversation_deleted","This conversation was deleted");throw s({type:"error",error:I}),I}let L=new Error(A.error||"Failed to send message");throw s({type:"error",error:L}),L}if(!b.body){let A=new Error("No response body received");throw s({type:"error",error:A}),A}C(),s({type:"status",status:"connected"});try{await this.#ne(b.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(i){let l=i instanceof Error?i:new Error(String(i));throw!(l instanceof tn)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async#ve(t,n){n({type:"status",status:"connecting"});let o=await this.#$(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.#n};if(this.#f)try{let i=await this.#f();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.#r)try{s=await this.#r(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.#ne(s.body,n)}finally{n({type:"status",status:"idle"})}}async#ae(t,n){n({type:"status",status:"connecting"});let o=await this.#H(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.#n};if(this.#f)try{let i=await this.#f();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.#r)try{s=await this.#r(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.#e,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.#ne(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.#ne(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){return(await oi()).resolveApproval(this.#D(),t,n)}async#Y(t,n,o,r){let s=!!(n&&n.length>0),i=s?Pb(n):void 0,l=this.clientToolsFingerprintSessionId===t,c=s&&l&&this.lastSentClientToolsFingerprint===i,p=!s&&r?.emptyMeansReplace===!0&&this.#a===t,d=!1,g;for(let f=0;;f++){if(g=await o({...s&&(d||!c)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),g.status===409&&f===0&&s&&(await g.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){d=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,s?this.#a=t:p&&(this.#a=null)}}}async resumeFlow(t,n,o){return(await oi()).resumeFlow(this.#D(),t,n,o)}#ue(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async#V(t){let n={};this.#t.length&&await Promise.all(this.#t.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.#ue(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#O(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}#N(t,n){let o=n?.selectedModelId;return!o||!("model"in t)?t:this.config.composer?.models?.some(s=>s.id===o)?{...t,model:o}:t}async#H(t,n){let o=this.#b().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=Tf($C(t),p=>Pf(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?UC(p):null),s=this.#O(n),i={agent:this.#N(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(i.composerOptions=s);let l=[...ta(this.config),...await(await this.#C())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#V(t);return c&&(i.context=c),i}async#$(t,n){let o=Tf($C(t),p=>Pf(p)?UC(p):null),r=this.#b(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,d]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=d);let i=[...ta(this.config),...await(await this.#C())?.snapshotForDispatch()??[]];i.length>0&&(s.clientTools=i);let l=await this.#V(t);l&&(s.context=l);let c=this.#O(n);if(c&&(s.composerOptions=c),this.#s)try{let p=await this.#s({payload:{...s},config:this.config});if(p&&typeof p=="object"){let d=p;return s.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=s.clientTools),d}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async#ne(t,n,o,r){let{streamResponse:s}=lv()??await oi();return s({config:()=>this.config,createStreamParser:this.#o,parseSSEEvent:this.#p,onSSEEvent:(i,l)=>this.#i?.(i,l)},t,n,o,r)}};var hs=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function U0(e){return e instanceof hs}ei();ea();Hr();Yi();Hr();function V0(e){let t=0;for(let n of e.split(`
16
+ `)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>t&&(t=o[1].length)}return t}function VC(e,t){let n="`".repeat(Math.max(3,V0(t)+1));return`${n}${e}
17
17
  ${t}
18
- ${n}`}var N0=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function F0(e){let t=e?.text?.trim()??"";return t?NC(N0(e),t):""}function FC(e){let t=F0(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[Io(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
18
+ ${n}`}var j0=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function q0(e){let t=e?.text?.trim()??"";return t?VC(j0(e),t):""}function jC(e){let t=q0(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[Io(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
19
19
 
20
- `)}:{}}function Qd(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function $C(e,t){let n=e.findIndex(r=>r.id===t);if(n===-1||e[n].role!=="user")return null;let o=n+1;for(;o<e.length&&e[o].role!=="user";)o+=1;return{start:n,end:o}}function Tf(e,t){let n=e.findIndex(o=>o.id===t);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(e[o].role==="user")return e[o].id;return null}function UC(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return Tf(e,n.id)?n.id:null}return null}function Pf(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}Fd();function El(e){let t=["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)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var ci=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let i=s.find(l=>l.name===t.voice);i&&(r.voice=i)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):El(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=i=>{let l=i.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var ua=class{#e=null;#n=null;#o="idle";#t=new Set;#s=0;#r;constructor(t){this.#r=t}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(t){return this.#n===t?this.#o:"idle"}activeMessageId(){return this.#n}onChange(t){return this.#t.add(t),()=>this.#t.delete(t)}toggle(t,n){if(this.#n===t){if(this.#o==="playing"){this.#e?.supportsPause?(this.#e.pause(),this.#p(t,"paused")):this.stop();return}if(this.#o==="paused"){this.#e?.resume(),this.#p(t,"playing");return}if(this.#o==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.#s;this.#e?.stop(),this.#p(t,"loading");try{if(!this.#e){let r=await this.#r();if(o!==this.#s)return;if(!r){this.#p(null,"idle");return}this.#e=r}this.#e.speak(n,{onStart:()=>{o===this.#s&&this.#p(t,"playing")},onEnd:()=>{o===this.#s&&this.#p(null,"idle")},onError:()=>{o===this.#s&&this.#p(null,"idle")}})}catch{o===this.#s&&this.#p(null,"idle")}}stop(){this.#s++,this.#e?.stop(),this.#p(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#t.clear()}#p(t,n){this.#n=n==="idle"?null:t,this.#o=n;for(let o of this.#t)o(this.#n,this.#o)}};var Tl=class{#e;#n=!1;start(t){this.#e=t,this.#n=!1}cancel(){this.#n=!0}accepts(t){return!this.#n&&(!t||!this.#e||t===this.#e)}};ln();var{setLoader:mD,load:$0,getSync:U0}=it({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")});var Pl=$0,VC=U0;function kf(e){if(!e)return"";let t=V0(e);return jC(t!==null?t:e)}function V0(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 o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function jC(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(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
20
+ `)}:{}}function Zd(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function qC(e,t){let n=e.findIndex(r=>r.id===t);if(n===-1||e[n].role!=="user")return null;let o=n+1;for(;o<e.length&&e[o].role!=="user";)o+=1;return{start:n,end:o}}function Lf(e,t){let n=e.findIndex(o=>o.id===t);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(e[o].role==="user")return e[o].id;return null}function zC(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return Lf(e,n.id)?n.id:null}return null}function Hf(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}Ud();function Ml(e){let t=["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)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var ci=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let i=s.find(l=>l.name===t.voice);i&&(r.voice=i)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Ml(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=i=>{let l=i.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var ua=class{#e=null;#n=null;#o="idle";#t=new Set;#s=0;#r;constructor(t){this.#r=t}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(t){return this.#n===t?this.#o:"idle"}activeMessageId(){return this.#n}onChange(t){return this.#t.add(t),()=>this.#t.delete(t)}toggle(t,n){if(this.#n===t){if(this.#o==="playing"){this.#e?.supportsPause?(this.#e.pause(),this.#p(t,"paused")):this.stop();return}if(this.#o==="paused"){this.#e?.resume(),this.#p(t,"playing");return}if(this.#o==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.#s;this.#e?.stop(),this.#p(t,"loading");try{if(!this.#e){let r=await this.#r();if(o!==this.#s)return;if(!r){this.#p(null,"idle");return}this.#e=r}this.#e.speak(n,{onStart:()=>{o===this.#s&&this.#p(t,"playing")},onEnd:()=>{o===this.#s&&this.#p(null,"idle")},onError:()=>{o===this.#s&&this.#p(null,"idle")}})}catch{o===this.#s&&this.#p(null,"idle")}}stop(){this.#s++,this.#e?.stop(),this.#p(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#t.clear()}#p(t,n){this.#n=n==="idle"?null:t,this.#o=n;for(let o of this.#t)o(this.#n,this.#o)}};var Tl=class{#e;#n=!1;start(t){this.#e=t,this.#n=!1}cancel(){this.#n=!0}accepts(t){return!this.#n&&(!t||!this.#e||t===this.#e)}};ln();var{setLoader:AD,load:z0,getSync:K0}=it({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")});var kl=z0,KC=K0;function If(e){if(!e)return"";let t=G0(e);return GC(t!==null?t:e)}function G0(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 o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function GC(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(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
21
21
  `),t=t.replace(/\n{2,}/g,`
22
- `),t.trim()}var YC=null;var Hf=()=>YC?YC():Promise.resolve().then(()=>(GC(),KC));ln();var{setLoader:ED,load:z0}=it({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")});var XC=z0;var K0=["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"];function G0(e,t){return K0.some(n=>e[n]!==t[n])}var Qo=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function If(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="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?`${o}
22
+ `),t.trim()}var ZC=null;var Wf=()=>ZC?ZC():Promise.resolve().then(()=>(JC(),QC));ln();var{setLoader:WD,load:Q0}=it({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")});var ew=Q0;var J0=["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"];function Z0(e,t){return J0.some(n=>e[n]!==t[n])}var Qo=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function Of(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="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?`${o}
23
23
 
24
- _Details: ${n.message}_`:o}var QC=e=>Zs(e)||e===Xo,kl=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.#e=new Map;this.abortController=null;this.#o=Date.now();this.clientSession=null;this.agentExecution=null;this.#t=null;this.#s=null;this.#r=!1;this.#p=null;this.#f=null;this.#i=null;this.artifacts=new Map;this.#g=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.#l=0;this.webMcpApprovalResolvers=new Map;this.#c=0;this.approvalTokens=new Map;this.webMcpAwaitBatches=new Map;this.#a=null;this.#E=null;this.#h=0;this.#S=0;this.#v=!1;this.#A="disconnected";this.#d=null;this.#u=null;this.#m=null;this.#C=0;this.#x=!1;this.#y=null;this.#b=!1;this.#H=null;this.#k=new Map;this.#M=null;this.#I=new Map;this.#Y=null;this.#j=null;this.#B=!1;this.#T=null;this.#K=null;this.#_=!1;this.#F=null;this.#D=null;this.#X=null;this.#Z=new Tl;this.#ne=Promise.resolve();this.#$=null;this.#U=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new ua(()=>this.#de());this.#Ze=null;this.#le=0;this.handleEvent=t=>{let n=this.#U;if(n&&(t.type==="error"||t.type==="status"&&t.status==="error"?n.failed=!0:t.type==="message"&&t.message.role==="assistant"&&(n.dropped||this.ttsSpokenMessageIds.add(t.message.id),n.ids.includes(t.message.id)||n.ids.push(t.message.id))),t.type==="message"){this.upsertMessage(t.message),t.message.variant==="approval"&&t.message.approval&&t.message.approval.status!=="pending"&&this.#e.set(t.message.id,this.#n),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.#s=t.message.id),(t.message.variant==="approval"||t.message.agentMetadata?.awaitingLocalTool===!0)&&mf().catch(()=>{});let o=t.message.toolCall,r=!!o?.name&&(Zs(o.name)||o.name===Xo&&ps(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&r&&this.#et(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.#st(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.#it()){this.#Pe();return}if(this.#z(t.status),t.status==="connecting")this.#P(!0);else if(t.status==="idle"||t.status==="error"){this.#De()||this.#Ae(),this.webMcpResolveControllers.size===0&&(this.#P(!1),this.abortController=null,this.#Ke(),this.#qe());let o=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":o||(this.agentExecution.status="complete")),this.#tt()}}else t.type==="error"?(this.#z("error"),this.#Ae(),this.webMcpResolveControllers.size===0&&(this.#P(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.#rt(t)};this.historyInternals=this.#se(o),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.#V()})),this.messages=this.#ce(this.messages),this.client=new pa(t,this.historyInternals),this.#Le(),this.#Be();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.#g=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#he(),this.callbacks.onStatusChanged(this.status),this.#te(),this.#ee()}#e;#n;#o;#t;#s;#r;#p;#f;#i;#g;#l;#c;#a;#E;#h;#S;#v;#A;#d;#u;#m;#C;#x;#y;#b;#H;#k;#M;#I;#Y;#j;#B;#T;#K;#_;#F;#ee(){this.config.voiceRecognition?.provider&&Pl().catch(()=>{})}#te(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||Hf().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return bC(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#v}getVoiceStatus(){return this.#A}getVoiceDisclosure(){return this.#a?.getDisclosure?.()??null}getVoiceLevel(){return this.#a?.onLevel?this.#S:null}getVoiceInterruptionMode(){return this.#a?.getInterruptionMode?this.#a.getInterruptionMode():"none"}stopVoicePlayback(){this.#a?.stopPlayback&&(this.#Z.cancel(),this.#$?.cancel(),this.#a.stopPlayback())}isBargeInActive(){return this.#a?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#a?.deactivateBargeIn&&await this.#a.deactivateBargeIn()}#D;#X;#Z;#ne;#$;#U;#de(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=ci.isSupported()?new ci({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,i=t.browserFallback!==!1;if(o&&r&&s)return Hf().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:c})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&n?new c(p,n,{onFallback:d=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${d.message}`)}):p});if(i&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.#ne,r=++this.#h;this.#E=Pl().then(async s=>{await o,r===this.#h&&this.#W(s,s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.#h&&(this.#E=null)})}catch(n){console.error("Failed to setup voice:",n)}}#W(t,n){this.#a=n;let o=this;t.wireSessionVoice({session:this,provider:()=>o.#a,generation:()=>o.#h,get keyed(){return o.#$},set keyed(r){o.#$=r},get pendingUser(){return o.#D},set pendingUser(r){o.#D=r},get pendingAssistant(){return o.#X},set pendingAssistant(r){o.#X=r},turns:()=>o.#Z,busy:()=>o.#be(),setStreaming:r=>o.#P(r),setDelegation:r=>{o.#U=r},setLevel:r=>{o.#S=r},setStatus:r=>{o.#A=r,o.#v=r==="listening"},settlePending:r=>o.#pe(r)},n,t.KeyedVoiceTranscript,t.createVoiceSessionBridge)}async toggleVoice(){if(!this.#a&&this.#E&&await this.#E,!this.#a){console.error("Voice not configured");return}if(this.#v)await this.#a.stopListening();else{this.stopSpeaking();try{await this.#a.startListening()}catch(t){console.error("Failed to start voice:",t)}}}prewarmVoice(){if(!On(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let t=this.#h,n=()=>{let o=this.#a;!o?.prewarm||t!==this.#h||this.#v||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.#a&&this.#E){this.#E.then(n,()=>{});return}n()}#be(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#r||this.status==="resuming"}cleanupVoice(){let t=this.#a!==null;if(this.#h++,this.#E=null,this.#a){let n=this.#a;this.#a=null,this.#ne=this.#oe(n)}this.#v=!1,this.#A="disconnected",this.#pe(!0),this.#$?.settle(),this.#$=null,this.#Z=new Tl,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#oe(t){try{await t.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}#pe(t){let n=t?this.#D:null,o=this.#X;!n&&!o||(o&&this.#Z.cancel(),t&&(this.#D=null),this.#X=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(r=>r.id!==n&&r.id!==o?[r]:r.id===o&&!r.content.trim()?[]:[{...r,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.#P(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine,prewarmMode:t.runtype?.prewarmMode,attachIdleMs:t.runtype?.attachIdleMs,clientDelegation:t.runtype?.clientDelegation,callContext:t.runtype?.callContext,approvalTimeoutMs:t.runtype?.approvalTimeoutMs,disclosureText:t.runtype?.disclosureText}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#j=this.historyInternals.getStoredConversationRevision?.()??null,this.#B=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}warmClientSession(){let t=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,t)})}setClientSession(t,n){this.clientSession=t,this.#re(t,n)}#re(t,n=!this.messages.length){if(this.#x||!t.config.welcomeMessage||!n)return;let o=this.messages[0],r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.#V()};this.#J(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}setHistoryInternals(t){this.historyInternals=this.#se(t),this.client.setHistoryInternals(this.historyInternals),this.#Le()}destroy(){this.cleanupVoice(),this.#T?.(),this.#T=null,this.#K=null}#se(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.#Fe(o),n?.(o)}}}get#q(){return this.historyInternals.historyProvider??null}#R(){let t=this.#q;if(!t)throw new Qo("history_unavailable","No conversation history provider is installed");return t}#O(t){let n=this.#R(),o=t??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",s=o??(n.capabilities.scopes.includes(r)?r:n.capabilities.scopes[0]??r);if(!n.capabilities.scopes.includes(s))throw new hs("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.#d,conversationRevision:this.#u,nextMessageCursor:this.#m,recovery:this.#y,sendBlocked:this.#b}}getActiveConversationId(){return this.#d}#L(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#N(t,n){this.callbacks.onHistoryNotice?.({code:t,message:n})}async awaitHistorySettled(){let t=this.#H;t&&await t.catch(()=>{});let n=this.#M;n&&await n.catch(()=>{})}#G(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new Qo("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.#R().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.#O(t?.scope)})}async openConversation(t,n){let o=this.#R();this.#G();let r=this.#O(n?.scope);await this.awaitHistorySettled();let s=++this.#C,i=await o.getPage(t,{context:r});if(s!==this.#C)throw new Qo("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.#C)throw l.discard(),new Qo("superseded","A later selection won");this.#x=!0;try{await this.#ie(l)}finally{this.#x=!1}this.#d=l.conversationId||t,this.#u=l.conversationRevision||i.conversationRevision||null,this.#m=i.nextCursor,this.#y=null,this.#b=!1,this.#we();for(let c of i.messages)this.#I.set(c.id,c.content);return this.#ae(),this.hydrateMessages(i.messages),this.#L(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,n,o){let r=this.#R(),s=this.#O(o?.scope),i=n??this.#m;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${t} ${i}`,c=this.#k.get(l);if(c)return c;let p=this.#xe(r,t,i,s).finally(()=>{this.#k.delete(l)});return this.#k.set(l,p),p}async#xe(t,n,o,r){let s=this.messages[0]?.createdAt,i=await t.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.#d&&this.#d!==n)return{messages:[],nextMessageCursor:i.nextCursor};let l=Al(this.messages,i.messages);this.messages=this.#ce(l.map(c=>this.#Ce(c))),this.#m=i.nextCursor;for(let c of i.messages)this.#I.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#L(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let n=this.#R(),o=this.#O(t?.scope);await this.awaitHistorySettled();let r=++this.#C,s=await n.prepareStartNew({context:o});if(r!==this.#C)throw s.discard(),new Qo("superseded","A later action won");await this.#ue(s)}async#ue(t){this.#ge(),await this.#ie(t),this.#d=t.conversationId||null,this.#u=t.conversationRevision||null,this.#m=null,this.#y=null,this.#b=!1,this.#ae(),this.#L()}async deleteConversation(t,n){let o=this.#R(),r=this.#O(n?.scope);await this.awaitHistorySettled(),await o.delete(t,{context:r}),t===this.#d&&await this.#ve(r)}async updateConversation(t,n,o){let r=this.#R();if(!r.update)throw new Qo("history_unavailable","This history provider cannot update conversations");let s=this.#O(o?.scope);return await this.awaitHistorySettled(),r.update(t,n,{context:s})}canUpdateConversations(){return typeof this.#q?.update=="function"}async clearConversationHistory(t){let n=this.#R(),o=this.#O(t?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:o});return await this.#ve(o),r}async resetHistoryDevice(){let t=this.#R();if(!t.resetDevice)throw new Qo("history_unavailable","This history provider cannot reset the device");this.#C+=1,this.#M=null;try{return await t.resetDevice()}finally{this.#ge(),this.#d=null,this.#u=null,this.#m=null,this.#y=null,this.#b=!1,this.#L()}}async#ve(t){this.#C+=1,this.#M=null,this.#ge(),this.#d=null,this.#u=null,this.#m=null,this.#b=!0,this.#y=null,this.#L(),await this.#Q(t)}async#Q(t){let n=this.#q;if(!n){this.#b=!1,this.#L();return}try{let o=await n.prepareStartNew({context:t});await this.#ue(o)}catch{this.#b=!0,this.#y="new_conversation_required",this.#L(),this.#N("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#w(){if(!(this.#y!=="new_conversation_required"||!this.#q)&&(this.#y=null,await this.#Q(this.#O()),this.#y==="new_conversation_required"))throw new Qo("new_conversation_required","A new conversation is required before sending")}async#ie(t){await t.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.#d=t.conversationId,this.#u=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.#x||this.#re(t)}#ae(){this.#d?this.config.setStoredConversationId?.(this.#d):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#u),this.historyInternals.setStoredMessageCursor?.(this.#m)}#we(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Te(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#I.clear(),this.#fe(null)}#ge(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#le++,this.messages=[],this.#we(),this.#k.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#P(!1),this.#z("idle"),this.callbacks.onMessagesChanged([...this.messages])}#Fe(t){this.#C+=1,this.#M=null,this.#b=!0,this.#ge(),this.#d=t.conversationId,this.#u=null,this.#m=null,this.#y=null,this.#L(),this.#N("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#H=Promise.resolve().then(()=>{this.#b=!1,this.#H=null,this.#L()})}#Le(){let t=this.historyInternals.visitorStore??null;t!==this.#K&&(this.#T?.(),this.#T=null,this.#K=t,t&&(this.#T=t.subscribe(n=>this.#$e(n))))}#$e(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#C+=1,this.#M=null,this.#_=!0,this.#F=null;let n=this.messages.length>0;n||this.#d!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#ge():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#k.clear(),this.#fe(null)),this.#d=null,this.#u=null,this.#m=null,this.#y=null,this.#L(),n&&this.#N("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#Ue(){return this.#_?(this.#F||(this.#F=this.#Ve().finally(()=>{this.#F=null})),this.#F):Promise.resolve()}async#Ve(){if(!this.isClientTokenMode()){this.#_=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.#_=!1}catch{}}reconcileBootConversation(t){let n=this.#q,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#d;if(!n||!o)return Promise.resolve();let r=this.#O(t?.scope);this.#b=!0,this.#L();let s=this.#je(n,o,r).finally(()=>{this.#b=this.#y!==null,this.#H===s&&(this.#H=null),this.#L()});return this.#H=s,s}async#je(t,n,o){this.#d=n;let r=this.clientSession?.conversationRevision??this.#u??null,s=this.#B?this.#j:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#B=!1,this.#m=this.historyInternals.getStoredMessageCursor?.()??this.#m,await this.replayPendingProjections(),r&&s&&r===s){this.#u=r;return}let i=await t.getPage(n,{context:o}),l=new Set(i.messages.map(g=>g.id)),c=this.messages.some(g=>l.has(g.id)),p=i.messages[0]?.createdAt,d;if(!c)d=i.messages.map(g=>this.#Ce(g));else{let g=this.#t?this.#s:null,f=this.messages.filter(h=>l.has(h.id)||h.id===g?!0:p!==void 0&&h.createdAt<p);d=Al(f,i.messages).map(h=>this.#Ce(h))}this.#m=i.nextCursor,this.#u=i.conversationRevision||r||null,this.#I.clear();for(let g of i.messages)this.#I.set(g.id,g.content);this.#ae(),this.messages=this.#ce(d),this.callbacks.onMessagesChanged([...this.messages])}#Me(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#fe(t){this.#Y=t,this.historyInternals.setPendingDisplayProjections?.(t)}#He(){return this.historyInternals.getPendingDisplayProjections?.()??this.#Y}#Ie(t){if(this.#Me())for(let n of t){let o=Sl(n);o!==void 0&&this.#I.set(n.id,o)}}#qe(){if(!this.#Me())return;let t=this.#d;if(!t)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Sl(o);r!==void 0&&this.#I.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.#fe({conversationId:t,messageIds:n.map(o=>o.id)}),this.#Re(t,n))}#Re(t,n){let r=(this.#M??Promise.resolve()).catch(()=>{}).then(()=>this.#We(t,n,!1)).finally(()=>{this.#M===r&&(this.#M=null)});this.#M=r}async#We(t,n,o){if(this.#d!==t)return;let r=n.filter(s=>this.#I.get(s.id)!==s.displayContent);if(r.length===0){this.#Ee(t,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.#I.set(i.id,i.displayContent);this.#d===t&&s&&(this.#u=s),this.#Ee(t,n)}catch(s){if(!o&&this.#ze(s)){await this.#We(t,r,!0);return}if(s instanceof tn&&(s.code==="not_found"||s.code==="conversation_deleted")){this.#Ee(t,n);return}this.#N("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#ze(t){return t instanceof tn?t.code==="request_failed":t instanceof Error}#Ee(t,n){let o=this.#He();if(!o||o.conversationId!==t)return;let r=new Set(n.map(i=>i.id)),s=o.messageIds.filter(i=>!r.has(i));this.#fe(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.#Me())return;let t=this.#He();if(!t)return;if(this.#d&&t.conversationId!==this.#d){this.#fe(null);return}let n=[];for(let o of t.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.#fe(null);return}this.#Re(t.conversationId,n),await this.#M?.catch(()=>{})}#Ke(){this.#d&&(this.#u=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Oe(){await this.awaitHistorySettled(),await this.#Ue(),this.#y==="new_conversation_required"&&await this.#w()}static#Ge(t){return t instanceof tn&&t.code==="conversation_deleted"}async#Ye(t,n,o,r,s){this.#Ie(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt},this.handleEvent);return}catch(i){if(!e.#Ge(i))throw i;let l=await this.#Xe(r);if(!l)throw i;this.#Ie([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions},this.handleEvent)}}async#Xe(t){let n=this.messages.find(r=>r.id===t);if(!n)return null;let o={...n};this.#C+=1,this.#M=null,this.#ge(),this.#d=null,this.#u=null,this.#m=null,this.#x=!0;try{let r=this.#q;if(r){let s=await r.prepareStartNew({context:this.#O()});await this.#ue(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.#b=!0,this.#y="new_conversation_required",this.#L(),this.#N("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#x=!1}return this.#J(o),this.#P(!0),this.#N("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=yC(this.config,o),s=G0(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&On(o.voiceRecognition.provider)&&this.setupVoice());let i=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),i&&this.#_e();return}this.#me(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new pa(this.config,this.historyInternals),i&&this.#_e(),this.#Be(),l&&this.client.setSSEEventCallback(l)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:i,createdAt:l,sequence:c,streaming:p=!1,voiceProcessing:d,voiceCaption:g,rawContent:f}=t,y={id:i??(n==="user"?Ml():n==="assistant"?li():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:c??this.#V(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...d!==void 0&&{voiceProcessing:d},...g&&{voiceCaption:g},...f!==void 0&&{rawContent:f}};return this.upsertMessage(y),y}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:i,contentParts:l,id:c,createdAt:p,sequence:d,streaming:g=!1,voiceProcessing:f,rawContent:h}=o,v={id:c??(r==="user"?Ml():r==="assistant"?li():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:d??this.#V(),streaming:g,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...f!==void 0&&{voiceProcessing:f},...h!==void 0&&{rawContent:h}};n.push(v)}return this.messages=this.#ce([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:i,createdAt:l,sequence:c}=t,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...i!==void 0&&{id:i},...l!==void 0&&{createdAt:l},...c!==void 0&&{sequence:c}})}async#Qe(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
24
+ _Details: ${n.message}_`:o}var tw=e=>Zs(e)||e===Xo,Pl=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.#e=new Map;this.abortController=null;this.#o=Date.now();this.clientSession=null;this.agentExecution=null;this.#t=null;this.#s=null;this.#r=!1;this.#p=null;this.#f=null;this.#i=null;this.artifacts=new Map;this.#u=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.#c=0;this.webMcpApprovalResolvers=new Map;this.#l=0;this.approvalTokens=new Map;this.webMcpAwaitBatches=new Map;this.#a=null;this.#M=null;this.#h=0;this.#x=0;this.#S=!1;this.#E="disconnected";this.#d=null;this.#g=null;this.#m=null;this.#A=0;this.#C=!1;this.#b=null;this.#y=!1;this.#I=null;this.#T=new Map;this.#w=null;this.#_=new Map;this.#Q=null;this.#G=null;this.#q=!1;this.#k=null;this.#J=null;this.#B=!1;this.#R=null;this.#P=null;this.#F=null;this.#U=new Tl;this.#se=Promise.resolve();this.#z=null;this.#D=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new ua(()=>this.#ie());this.#Ze=null;this.#de=0;this.handleEvent=t=>{let n=this.#D,o=!1;if(n&&(t.type==="error"||t.type==="status"&&t.status==="error"?n.failed=!0:t.type==="message"&&t.message.role==="assistant"&&(n.dropped||this.ttsSpokenMessageIds.add(t.message.id),n.ids.includes(t.message.id)||n.ids.push(t.message.id),o=!0)),t.type==="message"){this.upsertMessage(t.message),o&&n.onUpdate?.(),t.message.variant==="approval"&&t.message.approval&&t.message.approval.status!=="pending"&&this.#e.set(t.message.id,this.#n),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.#s=t.message.id),(t.message.variant==="approval"||t.message.agentMetadata?.awaitingLocalTool===!0)&&bf().catch(()=>{});let r=t.message.toolCall,s=!!r?.name&&(Zs(r.name)||r.name===Xo&&ps(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&s&&this.#et(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.#st(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.#it()){this.#We();return}if(this.#K(t.status),t.status==="connecting")this.#L(!0);else if(t.status==="idle"||t.status==="error"){this.#Ve()||this.#Pe(),this.webMcpResolveControllers.size===0&&(this.#L(!1),this.abortController=null,this.#Ke(),this.#qe());let r=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":r||(this.agentExecution.status="complete")),this.#tt()}}else t.type==="error"?(this.#K("error"),this.#Pe(),this.webMcpResolveControllers.size===0&&(this.#L(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.#rt(t)};this.historyInternals=this.#ue(o),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.#j()})),this.messages=this.#pe(this.messages),this.client=new pa(t,this.historyInternals),this.#Ae(),this.#$e();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.#u=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#he(),this.callbacks.onStatusChanged(this.status),this.#re(),this.#Z()}#e;#n;#o;#t;#s;#r;#p;#f;#i;#u;#c;#l;#a;#M;#h;#x;#S;#E;#d;#g;#m;#A;#C;#b;#y;#I;#T;#w;#_;#Q;#G;#q;#k;#J;#B;#R;#Z(){this.config.voiceRecognition?.provider&&kl().catch(()=>{})}#re(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||Wf().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return SC(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#S}getVoiceStatus(){return this.#E}getVoiceNotice(){return this.#a?.takeNotice?.()??null}getVoiceDisclosure(){return this.#a?.getDisclosure?.()??null}getVoiceLevel(){return this.#a?.onLevel?this.#x:null}getVoiceInterruptionMode(){return this.#a?.getInterruptionMode?this.#a.getInterruptionMode():"none"}stopVoicePlayback(){this.#a?.stopPlayback&&(this.#U.cancel(),this.#z?.cancel(),this.#a.stopPlayback())}isBargeInActive(){return this.#a?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#a?.deactivateBargeIn&&await this.#a.deactivateBargeIn()}#P;#F;#U;#se;#z;#D;#ie(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=ci.isSupported()?new ci({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,i=t.browserFallback!==!1;if(o&&r&&s)return Wf().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:c})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&n?new c(p,n,{onFallback:d=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${d.message}`)}):p});if(i&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.#se,r=++this.#h;this.#M=kl().then(async s=>{await o,r===this.#h&&this.#W(s,s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.#h&&(this.#M=null)})}catch(n){console.error("Failed to setup voice:",n)}}#W(t,n){this.#a=n;let o=this;t.wireSessionVoice({session:this,provider:()=>o.#a,generation:()=>o.#h,get keyed(){return o.#z},set keyed(r){o.#z=r},get pendingUser(){return o.#P},set pendingUser(r){o.#P=r},get pendingAssistant(){return o.#F},set pendingAssistant(r){o.#F=r},turns:()=>o.#U,busy:()=>o.#be(),setStreaming:r=>o.#L(r),setDelegation:r=>{o.#D=r},setLevel:r=>{o.#x=r},setStatus:r=>{o.#E=r,o.#S=r==="listening"},settlePending:r=>o.#ae(r)},n,t.KeyedVoiceTranscript,t.createVoiceSessionBridge)}async toggleVoice(){if(!this.#a&&this.#M&&await this.#M,!this.#a){console.error("Voice not configured");return}if(this.#S)await this.#a.stopListening();else{this.stopSpeaking();try{await this.#a.startListening()}catch(t){console.error("Failed to start voice:",t)}}}prewarmVoice(){if(!Ln(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let t=this.#h,n=()=>{let o=this.#a;!o?.prewarm||t!==this.#h||this.#S||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.#a&&this.#M){this.#M.then(n,()=>{});return}n()}#be(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#r||this.status==="resuming"}cleanupVoice(){let t=this.#a!==null;if(this.#h++,this.#M=null,this.#a){let n=this.#a;this.#a=null,this.#se=this.#ve(n)}this.#S=!1,this.#E="disconnected",this.#ae(!0),this.#z?.settle(),this.#z=null,this.#U=new Tl,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#ve(t){try{await t.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}#ae(t){let n=t?this.#P:null,o=this.#F;!n&&!o||(o&&this.#U.cancel(),t&&(this.#P=null),this.#F=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(r=>r.id!==n&&r.id!==o?[r]:r.id===o&&!r.content.trim()?[]:[{...r,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.#L(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine,prewarmMode:t.runtype?.prewarmMode,attachIdleMs:t.runtype?.attachIdleMs,clientDelegation:t.runtype?.clientDelegation,callContext:t.runtype?.callContext,approvalTimeoutMs:t.runtype?.approvalTimeoutMs,disclosureText:t.runtype?.disclosureText}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#G=this.historyInternals.getStoredConversationRevision?.()??null,this.#q=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}warmClientSession(){let t=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,t)})}setClientSession(t,n){this.clientSession=t,this.#Y(t,n)}#Y(t,n=!this.messages.length){if(this.#C||!t.config.welcomeMessage||!n)return;let o=this.messages[0],r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.#j()};this.#te(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}setHistoryInternals(t){this.historyInternals=this.#ue(t),this.client.setHistoryInternals(this.historyInternals),this.#Ae()}destroy(){this.cleanupVoice(),this.#k?.(),this.#k=null,this.#J=null}#ue(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.#He(o),n?.(o)}}}get#V(){return this.historyInternals.historyProvider??null}#O(){let t=this.#V;if(!t)throw new Qo("history_unavailable","No conversation history provider is installed");return t}#N(t){let n=this.#O(),o=t??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",s=o??(n.capabilities.scopes.includes(r)?r:n.capabilities.scopes[0]??r);if(!n.capabilities.scopes.includes(s))throw new hs("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.#d,conversationRevision:this.#g,nextMessageCursor:this.#m,recovery:this.#b,sendBlocked:this.#y}}getActiveConversationId(){return this.#d}#H(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#$(t,n){this.callbacks.onHistoryNotice?.({code:t,message:n})}async awaitHistorySettled(){let t=this.#I;t&&await t.catch(()=>{});let n=this.#w;n&&await n.catch(()=>{})}#ne(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new Qo("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.#O().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.#N(t?.scope)})}async openConversation(t,n){let o=this.#O();this.#ne();let r=this.#N(n?.scope);await this.awaitHistorySettled();let s=++this.#A,i=await o.getPage(t,{context:r});if(s!==this.#A)throw new Qo("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.#A)throw l.discard(),new Qo("superseded","A later selection won");this.#C=!0;try{await this.#Me(l)}finally{this.#C=!1}this.#d=l.conversationId||t,this.#g=l.conversationRevision||i.conversationRevision||null,this.#m=i.nextCursor,this.#b=null,this.#y=!1,this.#fe();for(let c of i.messages)this.#_.set(c.id,c.content);return this.#Se(),this.hydrateMessages(i.messages),this.#H(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,n,o){let r=this.#O(),s=this.#N(o?.scope),i=n??this.#m;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${t} ${i}`,c=this.#T.get(l);if(c)return c;let p=this.#Le(r,t,i,s).finally(()=>{this.#T.delete(l)});return this.#T.set(l,p),p}async#Le(t,n,o,r){let s=this.messages[0]?.createdAt,i=await t.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.#d&&this.#d!==n)return{messages:[],nextMessageCursor:i.nextCursor};let l=Al(this.messages,i.messages);this.messages=this.#pe(l.map(c=>this.#xe(c))),this.#m=i.nextCursor;for(let c of i.messages)this.#_.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#H(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let n=this.#O(),o=this.#N(t?.scope);await this.awaitHistorySettled();let r=++this.#A,s=await n.prepareStartNew({context:o});if(r!==this.#A)throw s.discard(),new Qo("superseded","A later action won");await this.#ge(s)}async#ge(t){this.#X(),await this.#Me(t),this.#d=t.conversationId||null,this.#g=t.conversationRevision||null,this.#m=null,this.#b=null,this.#y=!1,this.#Se(),this.#H()}async deleteConversation(t,n){let o=this.#O(),r=this.#N(n?.scope);await this.awaitHistorySettled(),await o.delete(t,{context:r}),t===this.#d&&await this.#Ce(r)}async updateConversation(t,n,o){let r=this.#O();if(!r.update)throw new Qo("history_unavailable","This history provider cannot update conversations");let s=this.#N(o?.scope);return await this.awaitHistorySettled(),r.update(t,n,{context:s})}canUpdateConversations(){return typeof this.#V?.update=="function"}async clearConversationHistory(t){let n=this.#O(),o=this.#N(t?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:o});return await this.#Ce(o),r}async resetHistoryDevice(){let t=this.#O();if(!t.resetDevice)throw new Qo("history_unavailable","This history provider cannot reset the device");this.#A+=1,this.#w=null;try{return await t.resetDevice()}finally{this.#X(),this.#d=null,this.#g=null,this.#m=null,this.#b=null,this.#y=!1,this.#H()}}async#Ce(t){this.#A+=1,this.#w=null,this.#X(),this.#d=null,this.#g=null,this.#m=null,this.#y=!0,this.#b=null,this.#H(),await this.#we(t)}async#we(t){let n=this.#V;if(!n){this.#y=!1,this.#H();return}try{let o=await n.prepareStartNew({context:t});await this.#ge(o)}catch{this.#y=!0,this.#b="new_conversation_required",this.#H(),this.#$("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#Ee(){if(!(this.#b!=="new_conversation_required"||!this.#V)&&(this.#b=null,await this.#we(this.#N()),this.#b==="new_conversation_required"))throw new Qo("new_conversation_required","A new conversation is required before sending")}async#Me(t){await t.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.#d=t.conversationId,this.#g=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.#C||this.#Y(t)}#Se(){this.#d?this.config.setStoredConversationId?.(this.#d):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#g),this.historyInternals.setStoredMessageCursor?.(this.#m)}#fe(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Re(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#_.clear(),this.#oe(null)}#X(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#de++,this.messages=[],this.#fe(),this.#T.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#L(!1),this.#K("idle"),this.callbacks.onMessagesChanged([...this.messages])}#He(t){this.#A+=1,this.#w=null,this.#y=!0,this.#X(),this.#d=t.conversationId,this.#g=null,this.#m=null,this.#b=null,this.#H(),this.#$("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#I=Promise.resolve().then(()=>{this.#y=!1,this.#I=null,this.#H()})}#Ae(){let t=this.historyInternals.visitorStore??null;t!==this.#J&&(this.#k?.(),this.#k=null,this.#J=t,t&&(this.#k=t.subscribe(n=>this.#Te(n))))}#Te(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#A+=1,this.#w=null,this.#B=!0,this.#R=null;let n=this.messages.length>0;n||this.#d!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#X():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#T.clear(),this.#oe(null)),this.#d=null,this.#g=null,this.#m=null,this.#b=null,this.#H(),n&&this.#$("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#ee(){return this.#B?(this.#R||(this.#R=this.#v().finally(()=>{this.#R=null})),this.#R):Promise.resolve()}async#v(){if(!this.isClientTokenMode()){this.#B=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.#B=!1}catch{}}reconcileBootConversation(t){let n=this.#V,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#d;if(!n||!o)return Promise.resolve();let r=this.#N(t?.scope);this.#y=!0,this.#H();let s=this.#le(n,o,r).finally(()=>{this.#y=this.#b!==null,this.#I===s&&(this.#I=null),this.#H()});return this.#I=s,s}async#le(t,n,o){this.#d=n;let r=this.clientSession?.conversationRevision??this.#g??null,s=this.#q?this.#G:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#q=!1,this.#m=this.historyInternals.getStoredMessageCursor?.()??this.#m,await this.replayPendingProjections(),r&&s&&r===s){this.#g=r;return}let i=await t.getPage(n,{context:o}),l=new Set(i.messages.map(g=>g.id)),c=this.messages.some(g=>l.has(g.id)),p=i.messages[0]?.createdAt,d;if(!c)d=i.messages.map(g=>this.#xe(g));else{let g=this.#t?this.#s:null,f=this.messages.filter(h=>l.has(h.id)||h.id===g?!0:p!==void 0&&h.createdAt<p);d=Al(f,i.messages).map(h=>this.#xe(h))}this.#m=i.nextCursor,this.#g=i.conversationRevision||r||null,this.#_.clear();for(let g of i.messages)this.#_.set(g.id,g.content);this.#Se(),this.messages=this.#pe(d),this.callbacks.onMessagesChanged([...this.messages])}#ce(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#oe(t){this.#Q=t,this.historyInternals.setPendingDisplayProjections?.(t)}#_e(){return this.historyInternals.getPendingDisplayProjections?.()??this.#Q}#Be(t){if(this.#ce())for(let n of t){let o=Sl(n);o!==void 0&&this.#_.set(n.id,o)}}#qe(){if(!this.#ce())return;let t=this.#d;if(!t)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Sl(o);r!==void 0&&this.#_.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.#oe({conversationId:t,messageIds:n.map(o=>o.id)}),this.#De(t,n))}#De(t,n){let r=(this.#w??Promise.resolve()).catch(()=>{}).then(()=>this.#Ne(t,n,!1)).finally(()=>{this.#w===r&&(this.#w=null)});this.#w=r}async#Ne(t,n,o){if(this.#d!==t)return;let r=n.filter(s=>this.#_.get(s.id)!==s.displayContent);if(r.length===0){this.#Ie(t,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.#_.set(i.id,i.displayContent);this.#d===t&&s&&(this.#g=s),this.#Ie(t,n)}catch(s){if(!o&&this.#ze(s)){await this.#Ne(t,r,!0);return}if(s instanceof tn&&(s.code==="not_found"||s.code==="conversation_deleted")){this.#Ie(t,n);return}this.#$("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#ze(t){return t instanceof tn?t.code==="request_failed":t instanceof Error}#Ie(t,n){let o=this.#_e();if(!o||o.conversationId!==t)return;let r=new Set(n.map(i=>i.id)),s=o.messageIds.filter(i=>!r.has(i));this.#oe(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.#ce())return;let t=this.#_e();if(!t)return;if(this.#d&&t.conversationId!==this.#d){this.#oe(null);return}let n=[];for(let o of t.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.#oe(null);return}this.#De(t.conversationId,n),await this.#w?.catch(()=>{})}#Ke(){this.#d&&(this.#g=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Fe(){await this.awaitHistorySettled(),await this.#ee(),this.#b==="new_conversation_required"&&await this.#Ee()}static#Ge(t){return t instanceof tn&&t.code==="conversation_deleted"}async#Ye(t,n,o,r,s){this.#Be(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt,voiceSpoken:s?.voiceSpoken},this.handleEvent);return}catch(i){if(!e.#Ge(i))throw i;let l=await this.#Xe(r);if(!l)throw i;this.#Be([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,voiceSpoken:s?.voiceSpoken},this.handleEvent)}}async#Xe(t){let n=this.messages.find(r=>r.id===t);if(!n)return null;let o={...n};this.#A+=1,this.#w=null,this.#X(),this.#d=null,this.#g=null,this.#m=null,this.#C=!0;try{let r=this.#V;if(r){let s=await r.prepareStartNew({context:this.#N()});await this.#ge(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.#y=!0,this.#b="new_conversation_required",this.#H(),this.#$("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#C=!1}return this.#te(o),this.#L(!0),this.#$("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=wC(this.config,o),s=Z0(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&Ln(o.voiceRecognition.provider)&&this.setupVoice());let i=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),i&&this.#Ue();return}this.#me(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new pa(this.config,this.historyInternals),i&&this.#Ue(),this.#$e(),l&&this.client.setSSEEventCallback(l)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:i,createdAt:l,sequence:c,streaming:p=!1,voiceProcessing:d,voiceCaption:g,rawContent:f}=t,y={id:i??(n==="user"?El():n==="assistant"?li():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:c??this.#j(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...d!==void 0&&{voiceProcessing:d},...g&&{voiceCaption:g},...f!==void 0&&{rawContent:f}};return this.upsertMessage(y),y}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:i,contentParts:l,id:c,createdAt:p,sequence:d,streaming:g=!1,voiceProcessing:f,rawContent:h}=o,b={id:c??(r==="user"?El():r==="assistant"?li():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:d??this.#j(),streaming:g,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...f!==void 0&&{voiceProcessing:f},...h!==void 0&&{rawContent:h}};n.push(b)}return this.messages=this.#pe([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:i,createdAt:l,sequence:c}=t,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...i!==void 0&&{id:i},...l!==void 0&&{createdAt:l},...c!==void 0&&{sequence:c}})}async#Qe(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
25
25
 
26
26
  `),i=[s,n].filter(Boolean).join(`
27
27
 
28
- `),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(l){let p=[];s&&p.push(Io(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(c){let p=[];i&&p.push(Io(i)),p.push(...r.contentParts),t.contentParts=p}else s&&(t.llmContent=i);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim(),r=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0)&&!r)return;this.#U&&!n?.voiceTurn&&(this.#U.failed=!0,this.#U=null),(this.#H||this.#M||this.#b||this.#_)&&await this.#Oe(),this.stopSpeaking(),this.abortController?.abort(),this.#me(),this.#le++,this.#ye();let s=n?.voiceTurn?.userMessageId,i=s?this.messages.find(h=>h.id===s&&h.role==="user"):void 0,l=i?.id??Ml(),c=li();this.#s=null;let p=n?.contentParts&&bl(n.contentParts)?la:"",d={id:l,role:"user",content:o||p,createdAt:new Date().toISOString(),sequence:this.#V(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};i?(i.viaVoice=!0,delete i.voiceCaption,i.content.trim()!==o&&(i.llmContent=o),this.callbacks.onMessagesChanged([...this.messages])):this.#J(d),this.#P(!0);let g=new AbortController;if(this.abortController=g,n?.mentions){let h=this.messages.find(y=>y.id===l)??d;if(await this.#Qe(h,o,n.mentions.finalize),g.signal.aborted||this.abortController!==g)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let h=this.messages.find(v=>v.id===l)??d,y=FC({quote:n.quote,text:h.llmContent??h.content,contentParts:h.contentParts});y.contentParts&&(h.contentParts=y.contentParts),y.llmContent!==void 0&&(h.llmContent=y.llmContent),(y.contentParts||y.llmContent!==void 0)&&(h.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let f=i?[...this.messages.filter(h=>h!==i),{...i,createdAt:new Date().toISOString()}]:[...this.messages];try{await this.#Ye(f,g,c,l,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(h){if(this.status==="resuming"||this.#r)return;this.#U&&(this.#U.failed=!0);let y=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));if(!y){let v=If(h,this.config.errorMessage);if(v){let C={id:c,role:"assistant",createdAt:new Date().toISOString(),content:v,sequence:this.#V()};this.#J(C)}}this.#z("idle"),this.#P(!1),this.abortController=null,y||(h instanceof Error?this.callbacks.onError?.(h):this.callbacks.onError?.(new Error(String(h))))}}resubmitFrom(t,n){let o=$C(this.messages,t);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,i=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!i?.trim()||(l?.length??0)>0||!s&&(r.llmContent?.trim()?.length??0)>0))return!1;let p=s?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}},d=s?this.#Je(s.options):r.composerOptions,g=s?s.contentSegments:r.contentSegments,f=s?s.options?.quote:void 0,h=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(i??"",{...l?.length?{contentParts:[...l]}:{},...g?.length?{contentSegments:[...g]}:{},...d?{composerOptions:d}:{},...f?{quote:f}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:h===!0}),!0}#Je(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.#H||this.#M||this.#b||this.#_)&&await this.#Oe(),this.abortController?.abort(),this.#ye();let t=li();this.#s=null,this.#P(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.#r)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let i=If(r,this.config.errorMessage);if(i){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.#V()};this.#J(l)}}this.#z("idle"),this.#P(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.#s=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let i of this.messages)i.streaming&&i.id!==o&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#P(!0);let s={};try{await this.client.processStream(t,i=>{let l=this.#n;this.#n=s;try{this.handleEvent(i)}finally{this.#n=l}},n?.assistantMessageId,n?.seedContent),this.#ke(s)}catch(i){if(this.status==="resuming"||this.#r){this.#pt(s);return}this.#ke(s),this.#z("error"),this.webMcpResolveControllers.size===0&&(this.#P(!1),this.abortController=null),this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))}}#Be(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.#c}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}#Ze;#le;#Se(t){let n=this.#Ze??={s:this,setStreaming:s=>this.#P(s),appendMessage:s=>this.#J(s),nextSequence:()=>this.#V(),settleApprovalPausedToolCall:s=>this.#Ne(s),resumeAfter:s=>this.#t?.executionId===s?this.#t.lastEventId:void 0},o=Zv();if(o)return t(o,n);let r=this.#le;return mf().then(s=>r===this.#le?t(s,n):void 0,s=>{this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))})}resolveApproval(t,n,o){return this.#Se((r,s)=>r.resolveApproval(s,t,n,o))}resolveAskUserQuestion(t,n){return this.#Se((o,r)=>o.resolveAskUserQuestion(r,t,n))}resolveWebMcpToolCall(t){return this.#Se((n,o)=>n.resolveWebMcpToolCall(o,t))}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}#et(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.#l;queueMicrotask(()=>{s===this.#l&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}#tt(){if(this.webMcpAwaitBatches.size===0)return;let t=this.#l;queueMicrotask(()=>{if(t===this.#l)for(let n of[...this.webMcpAwaitBatches.keys()])this.#nt(n)})}#nt(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.#Se((r,s)=>r.resolveWebMcpToolCallBatch(s,t,o))}#me(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.#l++}cancel(){this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#le++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#P(!1),this.#z("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#le++,this.messages=[],this.agentExecution=null,this.#Te(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#P(!1),this.#z("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.#g}selectArtifact(t){this.#g=t,this.#he()}clearArtifacts(){this.#Te()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.#g=n,this.#he(),t.transcript!==!1&&this.#ot(o),o}#ot(t){let n=`artifact-ref-${t.id}`,o=Er(this.config.features?.artifacts,t),r=al(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...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}:{}}),s=this.messages.find(i=>i.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}#_e(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(i=>i.id===`artifact-ref-${n.id}`);if(!o)continue;let r=Er(this.config.features?.artifacts,n),s=al(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}#Te(){this.artifacts.size===0&&this.#g===null||(this.artifacts.clear(),this.#g=null,this.#he())}#he(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#g})}#rt(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.#g=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.#he()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#le++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#ce(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.#V()}))),this.#P(!1),this.#z("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.#g=n,this.#he()}#st(t){let n=this.agentExecution?.executionId;if(!n||!this.#s||this.agentExecution?.status!=="running")return;let o=this.#t===null;this.#t={executionId:n,lastEventId:t,assistantMessageId:this.#s,status:"running"},this.#dt(o)}#it(){return this.#t!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#De()}#De(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}#Pe(){this.#r||!this.#t||typeof this.config.reconnectStream!="function"||(this.#r=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#t}),this.#P(!0),this.#z("resuming"),this.#at().then(t=>{this.#r&&this.#t&&t.begin()}))}#at(){return this.#p?Promise.resolve(this.#p):(this.#f||(this.#f=XC().then(({createReconnectController:t})=>{let n=t(this.#lt());return this.#p=n,n}),this.#f.catch(()=>{this.#f=null})),this.#f)}#lt(){let t=this;return{get config(){return t.config},getResumable:()=>t.#t,clearResumable:()=>t.#Ae(),getStatus:()=>t.status,setStatus:n=>t.#z(n),setStreaming:n=>t.#P(n),setReconnecting:n=>{t.#r=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.#J(n),nextSequence:()=>t.#V(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>If(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.#r){this.#p?.wake();return}this.#Pe()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.#r)return;let n=this.#ct();n||(n=li(),this.#J({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.#V()})),this.#s=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.#t={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.#Pe()}#ct(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}#ye(){this.#r=!1,this.#p?.teardown(),this.#Ae()}#Ae(){this.#i&&(clearTimeout(this.#i),this.#i=null);let t=this.#t!==null;this.#t=null,t&&this.config.onExecutionState?.(null)}#dt(t){let n=this.config.onExecutionState;if(n){if(t){this.#i&&(clearTimeout(this.#i),this.#i=null),n(this.#t);return}this.#i||(this.#i=setTimeout(()=>{this.#i=null,this.config.onExecutionState?.(this.#t)},500))}}getResumableHandle(){return this.#t}#z(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}#P(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&(this.#ke(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(t){let n=this.config.textToSpeech;if(!n?.enabled||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(i=>i.role==="assistant"&&i.content&&!i.voiceProcessing);if(!r||t&&!t.includes(r.id))return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=kf(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(t){return El(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=kf(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}#ke(t){for(let[n,o]of[...this.#e])o===t&&(this.#e.delete(n),this.#Ne(n))}#pt(t){for(let[n,o]of this.#e)o===t&&this.#e.set(n,void 0)}#Ne(t){let n=this.messages.find(l=>l.id===t)?.approval,o=n?.toolCallId,r=o&&this.messages.find(l=>l.toolCall?.id===o),s=r&&r.toolCall;if(!s||s.status==="complete"||n.status==="pending")return;let i={...s,status:"complete",approvalStatus:n.status,completedAt:Date.now(),...n.status==="approved"?{superseded:!0}:{success:!1,error:n.status==="denied"?"Denied":"Approval timed out"}};this.upsertMessage({...r,streaming:!1,toolCall:i})}#J(t){let n=this.#Ce(t);this.messages=this.#ce([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.#Ce(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.#J(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let i={...r,...n};r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(i.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(i.agentMetadata={...i.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let l=r.agentMetadata?.clientToolAnswer;if(l&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:l}),r.approval&&n.approval&&r.approval.id===n.approval.id){let g=r.approval,f=n.approval;i.approval={...g,...f,executionId:f.executionId||g.executionId,toolName:f.toolName||g.toolName,description:f.description||g.description,toolType:f.toolType??g.toolType,reason:f.reason??g.reason,parameters:f.parameters??g.parameters,toolCallId:f.toolCallId??g.toolCallId}}let c=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(c&&QC(c)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let g=`${p}:${d}`,f=this.webMcpInflightKeys.has(g),h=this.webMcpResolvedKeys.has(g),y=r.toolCall?.name,v=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&y!==void 0&&QC(y)&&r.toolCall?.status==="complete";(f||h||v)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.#ce(this.messages),this.callbacks.onMessagesChanged([...this.messages])}#Ce(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.#V()}}#V(){return this.#o++}#ce(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=n.sequence??0,l=o.sequence??0;return i!==l?i-l:n.id.localeCompare(o.id)})}};Xe();Mr();Tt();Hr();import{File as Y0,FileCode as X0,FileSpreadsheet as Q0,FileText as Rf,X as J0}from"lucide";var Z0={add:e=>$v(e)},eL=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,ep={allowedTypes:Lr,maxFileSize:10*1024*1024,maxFiles:4};function tL(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function nL(e){return e==="application/pdf"?Rf:e.startsWith("text/")?Rf:e.includes("word")?Rf:e.includes("excel")||e.includes("spreadsheet")?Q0:e==="application/json"?X0:Y0}var fa=class e{constructor(t={}){this.attachments=[];this.#e=null;this.#n=new Map;this.#o=!1;this.config={allowedTypes:t.allowedTypes??ep.allowedTypes,maxFileSize:t.maxFileSize??ep.maxFileSize,maxFiles:t.maxFiles??ep.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}#e;#n;#o;#t(){return typeof this.config.adapter?.add=="function"}#s(){return this.#t()?this.config.adapter:Z0}setPreviewsContainer(t){this.#e=t}remountPreviews(t){if(this.#e=t,t){t.innerHTML="";for(let n of this.attachments)this.#g(n)}this.#a()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:ep.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange),t.adapter!==void 0&&(this.config.adapter=t.adapter)}isReady(){return this.attachments.every(t=>t.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart).filter(t=>t!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(!t.length||this.#o)return;let n=[];for(let o of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=Uv(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let i=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,i);continue}let s={id:tL(),file:o,previewUrl:yd(o)?URL.createObjectURL(o):null,contentPart:null,status:this.#t()?"uploading":"processing",progress:this.#t()?0:void 0};this.attachments.push(s),this.#g(s),n.push(s)}this.#a(),this.#i(),await Promise.all(n.map(o=>this.#r(o)))}async#r(t){let n=new AbortController;this.#n.set(t.id,n);let o=()=>this.#o||n.signal.aborted||this.#n.get(t.id)!==n||!this.attachments.includes(t);try{let r=await this.#s().add(t.file,{signal:n.signal,onProgress:s=>{o()||t.status!=="uploading"||(t.progress=eL(s),this.#l(t),this.#i())}});if(o())return;t.contentPart=r,t.status="ready",t.progress=void 0,t.error=void 0}catch(r){if(o())return;t.status="error",t.progress=void 0,t.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.#n.get(t.id)===n&&this.#n.delete(t.id)}this.#l(t),this.#i()}retryAttachment(t){let n=this.attachments.find(o=>o.id===t);!n||n.status!=="error"||this.#o||(n.status=this.#t()?"uploading":"processing",n.progress=this.#t()?0:void 0,n.error=void 0,this.#l(n),this.#i(),this.#r(n))}#p(t){let n=this.#n.get(t);n&&(this.#n.delete(t),n.abort())}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];this.#p(t),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.#e?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),o.status==="ready"&&o.contentPart&&this.#f(o.contentPart),this.#a(),this.#i()}#f(t){let n=this.config.adapter?.remove;if(n)try{let o=n(t,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let t of this.attachments)this.#p(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#n.clear(),this.#e&&(this.#e.innerHTML=""),this.#a(),this.#i()}destroy(){if(!this.#o){this.#o=!0;for(let t of this.#n.values())t.abort();this.#n.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#e=null}}#i(){this.#o||this.config.onAttachmentsChange?.(this.getAttachments())}#g(t){if(!this.#e)return;let n=yd(t.file),o=x("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let d=x("img");d.src=t.previewUrl,d.alt=t.file.name,d.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",d.style.width="48px",d.style.height="48px",d.style.objectFit="cover",d.style.borderRadius="8px",o.appendChild(d)}else{let d=x("div");d.style.width="48px",d.style.height="48px",d.style.borderRadius="8px",d.style.backgroundColor="var(--persona-container, #f3f4f6)",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.display="flex",d.style.flexDirection="column",d.style.alignItems="center",d.style.justifyContent="center",d.style.gap="2px",d.style.overflow="hidden";let g=nL(t.file.type),f=_t(g,20,"var(--persona-muted, #6b7280)",1.5);f&&d.appendChild(f);let h=x("span");h.textContent=Vv(t.file.type,t.file.name),h.style.fontSize="8px",h.style.fontWeight="600",h.style.color="var(--persona-muted, #6b7280)",h.style.textTransform="uppercase",h.style.lineHeight="1",d.appendChild(h),o.appendChild(d)}let r=X("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=x("div","persona-attachment-progress");s.appendChild(x("div","persona-attachment-progress__bar"));let i=X("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=ue("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?i.appendChild(l):i.textContent="\u21BB",i.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),this.retryAttachment(t.id)}),r.append(s,i),o.appendChild(r);let c=x("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");c.type="button",c.setAttribute("aria-label","Remove attachment"),c.style.position="absolute",c.style.top="-4px",c.style.insetInlineEnd="-4px",c.style.width="18px",c.style.height="18px",c.style.borderRadius="50%",c.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",c.style.border="none",c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center",c.style.justifyContent="center",c.style.padding="0";let p=_t(J0,10,"var(--persona-text-inverse, #ffffff)",2);p?c.appendChild(p):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(c),this.#e.appendChild(o),this.#c(o,t)}#l(t){let n=this.#e?.querySelector(`[data-attachment-id="${t.id}"]`);n&&this.#c(n,t)}#c(t,n){t.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";t.setAttribute("aria-busy",o?"true":"false"),t.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let r=t.querySelector(".persona-attachment-progress__bar");if(r){let s=n.progress;r.style.width=typeof s=="number"?`${Math.round(s*100)}%`:""}}#a(){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})}};var JC=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),oL=(e,t)=>e.length===t.length&&e.every((n,o)=>{let r=t[o];return n.id===r.id&&n.name===r.name&&n.mimeType===r.mimeType&&n.size===r.size&&n.status===r.status&&n.progress===r.progress&&n.error===r.error});function ZC(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,n=null,o=!1,r=!1,s=()=>e.preparing?"preparing":e.streaming?"streaming":"idle",i=()=>{let d=s();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(g=>Object.freeze({...g}))),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:d,inputDisabled:e.inputDisabled,sendDisabled:d!=="idle"||e.sendDisabled||e.inputDisabled})},l=()=>(n||(n=i()),n),c=()=>{if(o=!1,r||t.size===0)return;let d=l();for(let g of[...t])try{g(d)}catch(f){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",f)}},p=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(c))};return{getState:l,subscribe:d=>(t.add(d),()=>t.delete(d)),setText:d=>{e.text!==d&&(e.text=d,p())},setAttachments:d=>{oL(e.attachments,d)||(e.attachments=[...d],p())},setMentionRefs:d=>{JC(e.mentionRefs,d)||(e.mentionRefs=[...d],p())},setSelectedModelId:d=>{e.selectedModelId!==d&&(e.selectedModelId=d,p())},setActiveModeIds:d=>{JC(e.activeModeIds,d)||(e.activeModeIds=[...d],p())},setQuote:d=>{let g=e.quote;g?.text===d?.text&&g?.messageId===d?.messageId&&g?.sourceLabel===d?.sourceLabel||(e.quote=d?{...d}:void 0,p())},setPendingSubmission:d=>{e.pendingSubmission!==d&&(e.pendingSubmission=d,p())},setPreparing:d=>{e.preparing!==d&&(e.preparing=d,p())},setStreaming:d=>{e.streaming!==d&&(e.streaming=d,p())},setInputDisabled:d=>{e.inputDisabled!==d&&(e.inputDisabled=d,p())},setSendDisabled:d=>{e.sendDisabled!==d&&(e.sendDisabled=d,p())},flush:()=>{o&&c()},destroy:()=>{r=!0,o=!1,t.clear()}}}Xe();var zn=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},ew=(e,t)=>{let n=x("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function tw(e,t={}){let n=zn(e,"[data-persona-composer-form]"),o=zn(e,"[data-persona-composer-input]");if(!n||!o){let A=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||o))throw new Error(A);return typeof console<"u"&&console.warn(A),null}let r={header:zn(e,"[data-persona-composer-header]"),body:zn(e,"[data-persona-composer-body]"),actionsStart:zn(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:zn(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:zn(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:zn(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:zn(e,"[data-persona-composer-status]")},s=new Set,i=r.header;i||(s.add("header"),i=ew("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(i,n):e.appendChild(i));let l=r.body??o.parentElement??n,c=(C,A,L,I,H)=>{if(A)return A;s.add(C);let _=ew(L,I);return H.appendChild(_),_},p=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),d=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),g=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),f=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[],y=(C,A)=>C.target===A.target&&C.type===A.type&&C.handler===A.handler,v=zn(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:n,input:o,header:i,body:l,actionsStart:p,actionsEnd:d,suggestions:g,status:f,attachmentInput:v,attachmentPreviews:zn(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:zn(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:zn(e,"[data-persona-composer-submit]")??void 0,micButton:zn(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(C,A,L,I)=>{C.addEventListener(A,L,I),h.push({target:C,type:A,handler:L,options:I})},removeListener:(C,A,L,I)=>{C.removeEventListener(A,L,I),h=h.filter(H=>!y(H,{target:C,type:A,handler:L}))},destroy:()=>{for(let C of h)C.target.removeEventListener(C.type,C.handler,C.options);h=[]}}}Xe();Tt();sa();gs();function rL(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function tp(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:i,verticalOffset:l,zIndex:c=2147483e3,onOpen:p,onDismiss:d}=e,g=e.container??rL(t),f=!1,h=null,y=()=>{if(!f)return;let A=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${A.width}px`),i&&(n.style.maxWidth=`${A.width}px`);let L=n.getBoundingClientRect(),I=l?.()??null,H=I!=null?A.top+I:A.top,_=o==="top-start"||o==="top-end"?H-r-L.height:A.bottom+r,te=o==="bottom-end"||o==="top-end"?A.right-L.width:A.left,W=i?.()??null;if(W!=null){let j=Math.max(A.left,A.right-L.width);te=Math.min(Math.max(A.left+W,A.left),j)}n.style.top=`${_}px`,n.style.left=`${te}px`},v=()=>{f&&(f=!1,h&&(h(),h=null),n.remove())},C=()=>{if(f)return;f=!0,c!=null&&(n.style.zIndex=String(c)),g.appendChild(n),y();let A=(t.ownerDocument??document).defaultView??window,L=t.ownerDocument??document,I=()=>{if(!t.isConnected){v(),d?.("anchor-removed");return}y()},H=V=>{let te=typeof V.composedPath=="function"?V.composedPath():[];te.includes(n)||te.includes(t)||(v(),d?.("outside"))},_=A.setTimeout(()=>{L.addEventListener("pointerdown",H,!0)},0);A.addEventListener("scroll",I,!0),A.addEventListener("resize",I),h=()=>{A.clearTimeout(_),L.removeEventListener("pointerdown",H,!0),A.removeEventListener("scroll",I,!0),A.removeEventListener("resize",I)},p?.()};return{get isOpen(){return f},open:C,close:v,toggle:()=>f?v():C(),reposition:y,destroy:v}}Xe();Tt();gs();var sL='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',iL=["--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"],Wf="data-persona-menu-focus",aL=new Set(["ArrowDown","ArrowUp","Home","End"]);function nw(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(sL)??e}var lL=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function ow(e){let t=e.label,n=!1,o=x("div","persona-send-button-wrapper"),r=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Zn} ${Ro}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=X("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{let P=e.getButtonSize?.()??"";r.style.width=P,r.style.height=P,r.style.minWidth=P,r.style.minHeight=P,r.style.lineHeight="1",r.replaceChildren();let Q=ue("plus",qn,"currentColor",1.5);Q?r.appendChild(Q):r.textContent="+"},l=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),s.setAttribute("aria-label",t)};l(),i();let c=[],p=-1,d=!1,g=()=>{let Q=s.getRootNode().activeElement;return Q instanceof HTMLElement?Q:null},f=()=>{let P=g();for(let Q of c){let U=!!P&&nw(Q)===P;Q.toggleAttribute(Wf,U&&d)}},h=()=>c.filter(P=>P.isConnected||s.contains(P)).map(nw).filter(P=>!lL(P)),y=(P,Q)=>{P.forEach((U,de)=>{U.setAttribute("tabindex",de===Q?"0":"-1")})},v=P=>{let Q=h();if(Q.length===0)return;let U=(P%Q.length+Q.length)%Q.length;p=U,y(Q,U),Q[U].focus(),f()},C=()=>o.ownerDocument??document,A=null,L=null,I=null,H=()=>{A&&(C().removeEventListener("focusin",A,!0),A=null)},_=()=>{L&&(s.removeEventListener("focusin",L),L=null),I&&(s.removeEventListener("pointerdown",I,!0),I=null)},V=null,te=()=>(V||(V=tp({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),H()}})),V),W=()=>V?.isOpen===!0,j=(P=!1)=>{if(W()){V?.close(),r.setAttribute("aria-expanded","false"),H(),_(),p=-1,d=!1;for(let Q of c)Q.removeAttribute(Wf);P&&r.focus()}},Y=(P=0,Q=!1)=>{if(n||W())return;d=Q,Sd(r,s,iL),te().open(),r.setAttribute("aria-expanded","true");let U=h();y(U,-1),v(P<0?U.length-1:P),A=de=>{let pe=typeof de.composedPath=="function"?de.composedPath():[];pe.includes(s)||pe.includes(o)||j()},C().addEventListener("focusin",A,!0),L=()=>f(),s.addEventListener("focusin",L),I=()=>{d=!1},s.addEventListener("pointerdown",I,!0)},E=P=>{P.preventDefault(),P.stopPropagation(),W()?j(!0):Y(0)},T=P=>{if(P.key==="ArrowDown"||P.key==="Enter"||P.key===" "){P.preventDefault(),d=!0,W()?v(0):Y(0,!0);return}P.key==="ArrowUp"&&(P.preventDefault(),d=!0,W()?v(-1):Y(-1,!0))},B=P=>{switch(aL.has(P.key)&&(d=!0),P.key){case"ArrowDown":P.preventDefault(),v(p+1);return;case"ArrowUp":P.preventDefault(),v(p-1);return;case"Home":P.preventDefault(),v(0);return;case"End":P.preventDefault(),v(h().length-1);return;case"Escape":P.preventDefault(),P.stopPropagation(),j(!0);return;case"Tab":j(!0);return;default:}};return r.addEventListener("click",E),r.addEventListener("keydown",T),s.addEventListener("keydown",B),{trigger:o,triggerButton:r,panel:s,setItems:P=>{for(let U of c)P.includes(U)||U.removeAttribute(Wf);if(c=[...P],!W())return;let Q=h();y(Q,Math.min(p,Q.length-1)),f()},isOpen:W,open:()=>Y(0),close:j,setLabel:P=>{P!==t&&(t=P,l())},applyButtonSize:i,destroy:()=>{n=!0,H(),_(),r.removeEventListener("click",E),r.removeEventListener("keydown",T),s.removeEventListener("keydown",B),V?.destroy(),V=null,o.remove(),s.remove(),c=[]}}}var Jo={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},rw="data-persona-composer-action",Of="data-persona-composer-disable-when-streaming",cL="core:overflow",dL=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function pL(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 o=x("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=e,t.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function Bf(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let o=n.getComputedStyle(e),r=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,t-r)}var sw=(e,t)=>{!e||typeof console>"u"||console.warn(t)},uL=(e,t)=>t.includes(":")?t:`${e}:${t}`;function gL(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){sw(t,`[Persona] composer action "${l.id}" is already contributed by ${iw(c)}; the ${iw(l)} copy is ignored.`);return}o.set(l.id,l),n.push(l)};for(let l of e.builtIns)s({id:l.id,placement:l.placement,presentation:"bar",order:l.order,sequence:r++,source:"core",builtIn:l});let i=(l,c,p)=>{let d=p?uL(p,l.id):l.id,g=l.order??Jo.custom;l.placement==="end"&&g>=Jo.send&&(sw(t,`[Persona] composer action "${d}" ordered at ${g} would render after send; clamped to ${Jo.send-1}.`),g=Jo.send-1),s({id:d,placement:l.placement,presentation:l.presentation??"bar",order:g,sequence:r++,source:c,pluginId:p,action:l})};for(let l of e.configActions??[])i(l,"config");for(let l of e.plugins){if(!l.contributeComposerActions)continue;let c;try{c=l.contributeComposerActions(e.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,p);continue}for(let p of c??[])i(p,"plugin",l.id)}return n.sort((l,c)=>l.order===c.order?l.sequence-c.sequence:l.order-c.order)}var iw=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",aw=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,fL=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function mL(e,t){if(!e||e==="always")return!0;let n=fL(t);return e==="when-text"?n:!n}var ys=e=>e.kind==="custom",_f=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,hL=e=>{let t=_f(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},yL='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function bL(e){let t="",n=o=>{if(o.nodeType===Node.TEXT_NODE){t+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let r=o;typeof r.matches=="function"&&r.matches(yL)||o.childNodes.forEach(n)};return n(e),t.trim()}var vL=e=>bL(e).length===0;function lw(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(E,T)=>{let B=E.button;if(!B)return;B.setAttribute("role","menuitem"),B.setAttribute("tabindex","-1"),B.className="persona-composer-overflow-menu__item";for(let U of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])B.style[U]="";B.style.lineHeight="1",T.tooltipText?B.setAttribute("title",T.tooltipText):B.removeAttribute("title"),B.replaceChildren();let P=x("span","persona-composer-overflow-menu__icon");if(T.iconName){let U=ue(T.iconName,16,"currentColor",1.5);U&&P.appendChild(U)}let Q=x("span","persona-composer-overflow-menu__label");Q.textContent=T.shortLabel??T.label,B.append(P,Q)},i=(E,T)=>{let B=E.button;if(!B)return;if(B.setAttribute("aria-label",T.label),T.pressed===void 0?B.removeAttribute("aria-pressed"):B.setAttribute("aria-pressed",T.pressed?"true":"false"),B.toggleAttribute(Of,T.disableWhenStreaming===!0),E.mode==="menu"){E.tooltip?.destroy(),E.tooltip=void 0,s(E,T);return}B.removeAttribute("role"),B.removeAttribute("tabindex"),B.removeAttribute("title");let P=r(),Q=!!T.shortLabel;if(B.className=Wn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Zn,Ro,Q&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),B.style.width=P&&!Q?P:"",B.style.height=P??"",B.style.minWidth=P&&!Q?P:"",B.style.minHeight=P??"",B.style.fontSize=Q?"":"18px",B.style.lineHeight="1",B.style.color=T.iconColor??"",B.style.backgroundColor=T.backgroundColor??"",B.replaceChildren(),T.iconName){let U=ue(T.iconName,qn,"currentColor",1.5);U&&B.appendChild(U)}if(Q){let U=x("span","persona-composer-action-button__label");U.textContent=T.shortLabel,B.appendChild(U)}else B.firstChild||(B.textContent=T.label);E.tooltip?.destroy(),E.tooltip=yn({anchor:B,trigger:E.element,text:()=>T.tooltipText??T.label,enabled:!!T.tooltipText})},l=(E,T)=>{let B=E.action,P=X("button",{attrs:{type:"button"}}),Q=P;if(T==="bar"){let pe=x("div","persona-send-button-wrapper");pe.appendChild(P),Q=pe}Q.setAttribute(rw,E.id);let U={resolved:E,element:Q,button:P,owned:!0,managed:!0,busy:!1,visible:!0,mode:T},de=pe=>{if(pe.preventDefault(),pe.stopPropagation(),U.busy||P.disabled)return;let ge=U.resolved.action;U.mode==="menu"&&h?.close(!0);let ke;try{ke=ge.onSelect(e.actionContext,pe)}catch(xe){e.reportError(xe,{actionId:U.resolved.id});return}!ke||typeof ke.then!="function"||(U.busy=!0,P.setAttribute("aria-busy","true"),ke.catch(xe=>{e.reportError(xe,{actionId:U.resolved.id})}).finally(()=>{U.busy=!1,P.removeAttribute("aria-busy")}))};return P.addEventListener("click",de),U.detach=()=>P.removeEventListener("click",de),i(U,B),U},c=E=>{let T=E.action,B;try{B=T.render({...e.actionContext,id:E.id,action:T})}catch(P){return e.reportError(P,{actionId:E.id}),null}return B?.element?(B.element.setAttribute(rw,E.id),B.element.toggleAttribute(Of,T.disableWhenStreaming===!0),{resolved:E,element:B.element,owned:!0,managed:!0,destroy:B.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(E,T)=>{if(E.builtIn){let P=E.builtIn.element;return P?{resolved:E,element:P,owned:!1,managed:E.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let B=E.action;return B?ys(B)?c(E):l(E,T):null},d=E=>{if(E.detach?.(),E.tooltip?.destroy(),E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0,E.owned){try{E.destroy?.()}catch(T){e.reportError(T,{actionId:E.resolved.id})}E.element.remove()}},g=(E,T)=>{for(let B=0;B<T.length;B++){let P=T[B];if(!P.managed)continue;let Q=null;for(let U=B+1;U<T.length;U++){let de=T[U];if(!de.managed&&de.element.parentElement===E){Q=de.element;break}}Q?(P.element.parentElement!==E||P.element.nextSibling!==Q)&&E.insertBefore(P.element,Q):E.lastChild!==P.element&&E.appendChild(P.element)}},f=(E,T)=>{if(E.button){E.button.disabled=T;return}if(!E.owned)return;let B=E.element;B.toggleAttribute("data-disabled",T),B.setAttribute("aria-disabled",T?"true":"false");let P=B instanceof HTMLButtonElement||B instanceof HTMLSelectElement||B instanceof HTMLInputElement||B instanceof HTMLTextAreaElement?B:B.querySelector("button, select, input, textarea");P&&(P.disabled=T)},h=null,y=null,v=null,C=0,A=()=>{let E=e.getOverflow?.();return E?.enabled===!0?E:void 0},L=()=>(h?h.setLabel(e.getOverflowLabel?.()??"More actions"):h=ow({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),I=E=>{y!==E&&(v?.disconnect(),y=E,C=Bf(E),!(typeof ResizeObserver>"u")&&(v=new ResizeObserver(T=>{let P=T[T.length-1]?.contentRect?.width??Bf(E);P!==C&&(C=P,j())}),v.observe(E)))},H=(E,T)=>{let B=pL(E.collapseAutoActionsBelow,T);if(B===null)return!1;let P=C||Bf(T);return P>0&&P<B},_=(E,T,B)=>{if(!T)return"bar";if(E.resolved.builtIn){let Q=dL(E.resolved.id);return Q&&T.includeBuiltIns?.includes(Q)?"menu":"bar"}let P=E.resolved.presentation;return P==="overflow"||P==="auto"&&B?"menu":"bar"},V=E=>{let T=E.menuSlot;if(!T)return;if(!vL(E.element)){E.menuLabel?.remove(),E.menuLabel=void 0;return}let B=hL(E.element);if(!B){E.menuLabel?.remove(),E.menuLabel=void 0;return}E.menuLabel||(E.menuLabel=x("span","persona-composer-overflow-menu__label")),E.menuLabel.textContent!==B&&(E.menuLabel.textContent=B),E.menuLabel.parentElement!==T&&T.appendChild(E.menuLabel)},te=(E,T)=>{if(E.mode===T)return E;let B=E.resolved.action;if(B&&!ys(B)){d(E),t.delete(E.resolved.id);let P=l(E.resolved,T);return t.set(E.resolved.id,P),P}if(T==="menu"){let P=X("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[$g]:""}});P.appendChild(E.element),Pv(_f(E.element)),E.menuSlot=P;let Q=U=>{let de=_f(E.element);if(de.disabled)return;let pe=U.target===de||de.contains(U.target);h?.close(!0),pe||de.click()};P.addEventListener("click",Q,!0),E.detachMenuSlot=()=>P.removeEventListener("click",Q,!0),E.managed=!0,V(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=T,E},W=(E,T)=>{let B=T.map(P=>P.menuSlot??P.element);for(B.forEach((P,Q)=>{let U=E.children[Q];U!==P&&(U?E.insertBefore(P,U):E.appendChild(P))});E.children.length>B.length;)E.lastElementChild?.remove()},j=()=>{if(o)return;let E=e.getBindings();if(!E)return;let T=e.getState(),B=T.phase==="streaming",P=A();P&&I(E.footer);let Q=P?H(P,E.footer):!1,U={start:[],end:[]},de=[];for(let pe of n){let ge=t.get(pe.id);if(!ge)continue;let ke=pe.action,xe=ke?aw(ke.visible,T,!0)&&mL(ke.visibility,T):!0;if(ge.visible!==xe&&(ge.visible=xe,!xe&&ge.managed&&(ge.menuSlot??ge.element).remove()),!!xe){if(ge=te(ge,_(ge,P,Q)),ke){let Le=aw(ke.disabled,T,!1)||ke.disableWhenStreaming===!0&&B;f(ge,Le),!ys(ke)&&ke.pressed!==void 0&&ge.button?.setAttribute("aria-pressed",ke.pressed?"true":"false")}ge.mode==="menu"?(V(ge),de.push(ge)):U[pe.placement].push(ge)}}if(de.length>0){let pe=L();W(pe.panel,de),pe.setItems(de.map(Le=>Le.menuSlot??Le.element)),pe.applyButtonSize();let ge=Number.isFinite(P?.order)?P?.order:Jo.overflow,ke=U.start.findIndex(Le=>Le.resolved.order>ge),xe={resolved:{id:cL,placement:"start",presentation:"bar",order:ge,sequence:-1,source:"core"},element:pe.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};U.start.splice(ke<0?U.start.length:ke,0,xe)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));g(E.actionsStart,U.start),g(E.actionsEnd,U.end)};return{resolve:()=>{if(o)return;let E=gL(e.collect()),T=new Set(E.map(B=>B.id));for(let[B,P]of t)T.has(B)||(d(P),t.delete(B));for(let B of E){let P=t.get(B.id);if(!P){let pe=p(B,"bar");pe&&t.set(B.id,pe);continue}let Q=P.resolved.action,U=B.action;if(!!Q!=!!U||Q&&U&&ys(Q)!==ys(U)||Q&&U&&ys(Q)&&ys(U)&&Q.render!==U.render){d(P),t.delete(B.id);let pe=p(B,P.mode);pe&&t.set(B.id,pe);continue}P.resolved=B,B.builtIn?(P.managed=B.builtIn.managed===!0||P.mode==="menu",B.builtIn.element&&P.mode==="bar"&&(P.element=B.builtIn.element)):U&&!ys(U)?i(P,U):U&&P.element.toggleAttribute(Of,U.disableWhenStreaming===!0)}n=E,j()},sync:j,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,v?.disconnect(),v=null,y=null;for(let E of t.values())d(E);t.clear(),h?.destroy(),h=null,n=[]}}}}Xe();Tt();gs();var CL="core:model",wL=700,cw=16,SL=["--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"],dw=()=>{let e=X("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=X("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function pw(e){let t=e.label??"Model",n=e.presentation??"native",o=null,r=c=>{let p=e.getSelectedModelId();return c.find(d=>d.id===p)??c[0]},s=()=>{let c=X("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),p="",d=()=>{let v=e.getModels(),C=v.map(A=>`${A.id}:${A.label}`).join("|");C!==p&&(p=C,c.replaceChildren(...v.map(A=>{let L=X("option",{attrs:{value:A.id}});return L.textContent=A.label,L}))),c.value=r(v)?.id??""};d(),o=d;let g=()=>{c.value&&e.onSelect(c.value)};c.addEventListener("change",g);let f=v=>v.stopPropagation();c.addEventListener("click",f);let{wrapper:h,chevron:y}=dw();return h.append(c,y),{element:h,destroy:()=>{o===d&&(o=null),c.removeEventListener("change",g),c.removeEventListener("click",f)}}},i=()=>{let c=X("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"}}),p=x("span","persona-composer-model-picker-label"),d=x("span","persona-composer-model-picker-suffix");c.append(p,d);let g=X("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),f=new Map,h="",y=null,v=()=>y?.isOpen===!0,C=(T=!1)=>{v()&&(y?.close(),c.setAttribute("aria-expanded","false"),T&&c.focus())},A=T=>{let B=[...f.values()];if(B.length===0)return;let P=(T%B.length+B.length)%B.length;B[P].focus()},L=T=>{if(v())return;y||(y=tp({anchor:c,content:g,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),Sd(c,g,SL),y.open(),c.setAttribute("aria-expanded","true");let P=[...f.keys()].indexOf(r(e.getModels())?.id??"");A(T??(P>=0?P:0))},I=T=>{C(!0),e.onSelect(T)},H=T=>{T.preventDefault(),T.stopPropagation();let B=T.currentTarget.getAttribute("data-persona-model-option");B&&I(B)},_=T=>{let B=X("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":T.id}});if(T.icon){let pe=ue(T.icon,cw,"currentColor",1.5);if(pe){let ge=x("span","persona-composer-model-option-icon");ge.appendChild(pe),B.appendChild(ge)}}let P=x("span","persona-composer-model-option-body"),Q=x("span","persona-composer-model-option-label");if(Q.textContent=T.label,P.appendChild(Q),T.description){let pe=x("span","persona-composer-model-option-description");pe.textContent=T.description,P.appendChild(pe)}B.appendChild(P);let U=x("span","persona-composer-model-option-check");U.setAttribute("aria-hidden","true");let de=ue("check",cw,"currentColor",2);return de&&U.appendChild(de),B.appendChild(U),B.addEventListener("click",H),B},V=()=>{let T=e.getModels(),B=T.map(U=>`${U.id}:${U.label}:${U.icon??""}:${U.description??""}`).join("|");if(B!==h){h=B;for(let U of f.values())U.removeEventListener("click",H);f.clear(),g.replaceChildren(...T.map(U=>{let de=_(U);return f.set(U.id,de),de}))}let P=r(T);for(let[U,de]of f)de.setAttribute("aria-selected",String(U===P?.id));p.textContent=P?.label??"";let Q=e.getSuffix?.()??"";d.textContent=Q,c.setAttribute("aria-label",[t,[P?.label,Q].filter(Boolean).join(" ")].filter(Boolean).join(": "))};V(),o=V;let te=T=>{T.preventDefault(),T.stopPropagation(),v()?C(!0):L()},W=T=>{if(T.key==="ArrowDown"){T.preventDefault(),v()?A(0):L(0);return}T.key==="ArrowUp"&&(T.preventDefault(),v()?A(-1):L(-1))},j=T=>{let B=[...f.values()],P=B.indexOf(T.target?.closest?.(".persona-composer-model-option"));switch(T.key){case"ArrowDown":T.preventDefault(),A(P+1);return;case"ArrowUp":T.preventDefault(),A(P-1);return;case"Home":T.preventDefault(),A(0);return;case"End":T.preventDefault(),A(B.length-1);return;case"Escape":T.preventDefault(),T.stopPropagation(),C(!0);return;case"Tab":C(!0);return;default:}};c.addEventListener("click",te),c.addEventListener("keydown",W),g.addEventListener("keydown",j);let{wrapper:Y,chevron:E}=dw();return Y.append(c,E),{element:Y,destroy:()=>{o===V&&(o=null),c.removeEventListener("click",te),c.removeEventListener("keydown",W),g.removeEventListener("keydown",j);for(let T of f.values())T.removeEventListener("click",H);f.clear(),y?.destroy(),y=null,g.remove()}}};return{action:{id:CL,kind:"custom",placement:"end",order:wL,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?i():s()},repaint:()=>o?.()}}Xe();Tt();Xe();var Df="[data-persona-composer-chip-row]";function np(e){e.style.display=e.childElementCount>0?"flex":"none"}function Nf(e){let t=e.querySelector(Df);if(t)return t;let n=X("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===e?e.insertBefore(n,o):e.appendChild(n),n}var AL=":scope > [data-persona-composer-mode]";function uw(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=p=>{let d=X("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let y=x("span","persona-mention-chip-icon"),v=ue(p.iconName,12,"currentColor",1.5);v&&y.appendChild(v),d.appendChild(y)}let g=x("span","persona-mention-chip-label");g.textContent=p.shortLabel??p.label,d.appendChild(g);let f=X("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=ue("x",12,"currentColor",2);return h?f.appendChild(h):f.textContent="\xD7",f.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),e.onRemove(p.id)}),d.appendChild(f),d},i=()=>Array.from(t.querySelectorAll(AL)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let d=()=>{p.remove(),np(t)},g=t.ownerDocument.defaultView,f=typeof g?.getComputedStyle=="function"?g.getComputedStyle(p).animationName:"";if(!f||f==="none"){d();return}p.addEventListener("animationend",d,{once:!0}),p.addEventListener("animationcancel",d,{once:!0})},c=()=>{for(let p of i())p.remove()};return{element:t,render:(p,d)=>{if(o)return;let g=d.filter(v=>p.includes(v.id)),f=g.map(v=>`${v.id}:${v.shortLabel??v.label}`).join("|");if(f===n)return;n=f;let h=new Map;for(let v of i()){let C=v.getAttribute("data-persona-composer-mode");C&&g.some(L=>L.id===C)&&!v.hasAttribute("data-persona-chip-exit")?h.set(C,v):v.hasAttribute("data-persona-chip-exit")||l(v)}let y=t.firstChild;for(let v of g){let C=h.get(v.id);C||(C=s(v),r.has(v.id)||(C.setAttribute("data-persona-chip-enter",""),C.addEventListener("animationend",()=>C?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(v.id),C!==y&&t.insertBefore(C,y),y=C.nextSibling}np(t)},destroy:()=>{o=!0,c(),np(t)}}}Xe();Tt();var gw=e=>`core:mode:${e}`;var Ff=e=>Math.min(300+e,499),fw=e=>`core:mode-group:${e}`;function op(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function xL(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function mw(e,t){return e?.length?e.filter(n=>!op(n.groupId,t)&&!xL(n.groupId,t)):[]}var ML=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function hw(e,t,n,o){let r=n.find(l=>l.id===t);if(!r)return[...e];let s=e.includes(t),i=new Set(e);if(s)i.delete(t);else{if(ML(r,o)==="single"){let l=n.filter(c=>c.groupId===r.groupId).map(c=>c.id);i=new Set([...i].filter(c=>!l.includes(c)))}i.add(t)}return n.filter(l=>i.has(l.id)).map(l=>l.id)}function rp(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function yw(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function bw(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var EL=16;function vw(e){let t=null;return{action:{id:fw(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=X("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,s="",i=p=>{p.preventDefault(),p.stopPropagation();let g=p.currentTarget.getAttribute("data-persona-composer-mode");!g||e.getActiveIds().includes(g)&&e.getGroup()?.selection==="single"||e.onSelect(g)},l=p=>{let d=X("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let f=ue(p.iconName,EL,"currentColor",1.5);f&&d.appendChild(f)}let g=x("span","persona-composer-segmented-label");return g.textContent=p.shortLabel??p.label,d.appendChild(g),d.addEventListener("click",i),d},c=()=>{let p=e.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let d=e.getModes(),g=d.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(g!==s){s=g;for(let y of r.values())y.removeEventListener("click",i);r.clear();let h=d.map(y=>{let v=l(y);return r.set(y.id,v),v});o.replaceChildren(...h)}let f=e.getActiveIds();for(let[h,y]of r)y.setAttribute("aria-pressed",String(f.includes(h)))};return c(),t=c,{element:o,destroy:()=>{t===c&&(t=null);for(let p of r.values())p.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}Xe();Tt();function Cw(e){let t=X("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let n="",o=!1,r=s=>{let i=x("span","persona-composer-quote-bar"),l=x("div","persona-composer-quote-content");if(s.sourceLabel){let g=x("div","persona-composer-quote-source");g.textContent=s.sourceLabel,l.appendChild(g)}let c=X("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=Qd(s.text),l.appendChild(c);let p=X("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),d=ue("x",12,"currentColor",2);d?p.appendChild(d):p.textContent="\xD7",p.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,l,p)};return{element:t,render:s=>{if(o)return;let i=s?`${s.sourceLabel??""}\0${s.text}`:"";if(i!==n){if(n=i,!s){t.replaceChildren(),t.style.display="none";return}r(s),t.style.display="flex"}},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}Xe();Tt();function ww(e){let t=X("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let n,o=!1,r=(i,l,c,p)=>{let d=X("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),g=ue(i,12,"currentColor",2);return g?d.appendChild(g):d.textContent=l,d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),p()}),d},s=i=>{let l=Qd(i.text??"",90);if(l)return l;let c=i.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(i.mentionRefs?.length??0)>0?i.mentionRefs.map(d=>d.label).join(", "):"Queued message"};return{element:t,render:i=>{if(o||i===n)return;if(n=i,!i){t.replaceChildren(),t.style.display="none";return}let l=x("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let c=X("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=s(i),t.replaceChildren(l,c,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}Xe();function Sw(e){let t=X("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=X("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 o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=x("div","persona-message-edit-actions"),s=(l,c,p,d)=>{let g=X("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[p]:""},text:l});return g.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),d()}),g},i=()=>{let l=n.value.trim();l&&e.onSave(l)};return r.append(s(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),s(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",i)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),e.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),i())}),t.append(n,r),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let l=n.value.length;n.setSelectionRange(l,l),o()},destroy:()=>{t.replaceChildren(),t.remove()}}}function Aw(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 xw(e,t){if(!e||typeof e.text!="string")return;let n=new Set(t.mentionSourceIds),o=(e.mentionRefs??[]).filter(c=>n.has(c.sourceId)),r=o.length===(e.mentionRefs?.length??0)&&o.length>0,s=new Set(t.modes.map(c=>c.id)),i=(e.activeModeIds??[]).filter(c=>s.has(c)),l=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...r?{mentionRefs:o}:{},...r&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...l?{selectedModelId:l}:{},...i.length?{activeModeIds:i}:{},...e.quote?.text?{quote:e.quote}:{}}}function Mw(e){let t=e.delay??500,n=null,o=!1,r=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(r(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{o||n===null||(r(),e.write())},cancel:r,destroy:()=>{o=!0,r()}}}function Ew(e){return e.wrapped||e.text.includes(`
29
- `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function Tw(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function Pw(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),o=Number.parseFloat(n.lineHeight),r=Number.parseFloat(n.fontSize),s=Number.isFinite(o)&&o>0?o:Number.isFinite(r)&&r>0?r*1.4:0;if(!s)return!1;let i=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-i>s*1.5}function kw(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}wd();function $f(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 Hw(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var TL=e=>typeof e?.then=="function";function Lw(e,t){return t===!1?{status:"canceled"}:!t||typeof t!="object"?{status:"proceed"}:(typeof t.text=="string"&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options}),{status:"proceed"})}function Iw(e,t,n){let o;try{o=e($f(t),{signal:n})}catch(r){return{status:"error",error:r}}return TL(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:Lw(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):Lw(t,o)}lf();cf();af();Hr();var sp=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?"circle":"pill"),ip={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"};bo();bo();var lp="16px",cp="transparent",PL=(()=>{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})(),Ll={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:PL,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"}},ap={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"}},eo={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:aa,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:lp,canvasBackground:cp,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"}}},kL=Ll.colors.gray,LL={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},Ww={...Ll,colors:{...Ll.colors,gray:kL}},HL={...Ll,colors:{...Ll.colors,gray:LL},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}},IL=Ww,Ow=ap,RL={...ap,colors:{...ap.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...ap.typography,fontSize:"14px",lineHeight:"1.5"}},WL=Ow,dp=eo,OL={...eo,launcher:ip,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:{...eo.input,borderRadius:"palette.radius.full"},introCard:{...eo.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...eo.suggestion.chip,fontWeight:"400"},card:{...eo.suggestion.card,fontWeight:"400"},list:{...eo.suggestion.list,fontWeight:"400"}},panel:{...eo.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...eo.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:{...eo.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...eo.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:{...eo.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...eo.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)"}},BL=dp,_L=e=>us({future:e}),Vf=e=>_L(e)==="v5"?{palette:HL,semantic:RL,components:OL}:{palette:Ww,semantic:Ow,components:dp};function vn(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?vn(e,o):o}function jf(e){let t={};function n(o,r){for(let[s,i]of Object.entries(o)){let l=`${r}.${s}`;if(typeof i=="string"){let c=vn(e,i);c!==void 0&&(t[l]={path:l,value:c,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof i=="object"&&i!==null&&n(i,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Bw(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 _w(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=_w(s,r):n[o]=r}return n}function DL(e,t){return t?_w(e,t):e}function pp(e,t={}){let n=Vf(t.future),o={palette:n.palette,semantic:n.semantic,components:n.components},r={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:DL(o.components,e?.components)},s=e?.components?.activity;for(let p of["toolBubble","reasoningBubble"])for(let d of["rowHeight","labelSize","iconSize","indent","bodySurface"])s?.[d]!==void 0&&(r.components[p][d]=s[d]);let i=e?.components?.collapsibleWidget?.surface;i!==void 0&&s?.bodySurface===void 0&&(r.components.activity={...r.components.activity,bodySurface:i});let l=e?.components?.header;l?.padding!==void 0&&l.minimalPadding===void 0&&(r.components.header.minimalPadding=r.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(r.components.message.fullscreenGap=r.components.message.gap),t.validate!==!1){let p=Bw(r);if(!p.valid)throw new Error(`Theme validation failed: ${p.errors.map(d=>d.message).join(", ")}`)}if(t.plugins)for(let p of t.plugins)r=p.transform(r);return r}var Uf=e=>e.trim()==="0"?"0px":e,Rw="--persona-",NL=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let i=t.slice(1);if(!/^[0-9a-f]+$/.test(i))return;i.length===3||i.length===4?n=[0,1,2].map(l=>parseInt(i[l]+i[l],16)):(i.length===6||i.length===8)&&(n=[0,2,4].map(l=>parseInt(i.slice(l,l+2),16)))}else{let i=t.match(/^rgba?\(([^)]+)\)$/);if(i){let l=i[1].split(/[,/\s]+/).filter(Boolean);l.length>=3&&(n=l.slice(0,3).map(c=>{let p=c.endsWith("%"),d=parseFloat(p?c.slice(0,-1):c);return p?d/100*255:d}))}}if(!n||n.some(i=>!Number.isFinite(i)))return;let[o,r,s]=n.map(i=>{let l=Math.max(0,Math.min(255,i))/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*s},FL=.179,bn=(e,t)=>{for(let[n,...o]of t){let r;for(let s of o)if(r=s.charCodeAt(0)===61?s.slice(1):e[Rw+s],r!==void 0)break;r!==void 0&&(e[Rw+n]=r)}};function qf(e){let t=jf(e),n={};for(let[$,We]of Object.entries(t)){let me=$.replace(/\./g,"-");n[`--persona-${me}`]=We.value}bn(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 o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],bn(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"]]),bn(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"]}`,bn(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"]??lp,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??cp,bn(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"]]),bn(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],i=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??n["--persona-divider"],bn(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"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??i??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??i??n["--persona-muted"],bn(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=e.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let c=n["--persona-components-history-railHeader-background"];c&&(n["--persona-history-rail-header-bg"]=c);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let d=n["--persona-components-history-railHeader-minHeight"];d&&(n["--persona-history-rail-header-min-height"]=d);for(let[$,We]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let me=n[`--persona-components-history-overlay-${$}`];me&&(n[`--persona-history-overlay-${We}`]=me)}for(let[$,We]of[["background","bg"],["borderRadius","radius"]]){let me=n[`--persona-components-history-menu-${$}`];me&&(n[`--persona-history-menu-${We}`]=me)}let g=e.components?.history?.motion;if(g){let $=dt=>{if(dt===void 0)return;let Qt=String(dt).trim();return/^\d+(\.\d+)?$/.test(Qt)?`${Qt}ms`:Qt},We=$(g.enterDurationMs);We!==void 0&&(n["--persona-history-enter-ms"]=We);let me=$(g.exitDurationMs);me!==void 0&&(n["--persona-history-exit-ms"]=me),g.enterEasing&&(n["--persona-history-enter-easing"]=g.enterEasing),g.exitEasing&&(n["--persona-history-exit-easing"]=g.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 $ of["scrim","shadow"]){let We=n[`--persona-components-history-confirm-${$}`];We&&(n[`--persona-history-confirm-${$}`]=We)}for(let[$,We]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let me=n[`--persona-components-tooltip-${$}`];me&&(n[`--persona-tooltip-${We}`]=me)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[$,We]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let me=n[`--persona-components-messageActions-${$}`];me&&(n[`--persona-message-action-${We}`]=me)}bn(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],y=n["--persona-components-introCard-shadow"],v=(!h||h==="transparent"||h==="none")&&(!y||y==="none"),C=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=v&&C==="1.5rem"?"1.5rem 0":C,bn(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"]]),bn(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 A=n["--persona-components-markdown-heading-h1-fontSize"];A&&(n["--persona-md-h1-size"]=A);let L=n["--persona-components-markdown-heading-h1-fontWeight"];L&&(n["--persona-md-h1-weight"]=L);let I=n["--persona-components-markdown-heading-h2-fontSize"];I&&(n["--persona-md-h2-size"]=I);let H=n["--persona-components-markdown-heading-h2-fontWeight"];H&&(n["--persona-md-h2-weight"]=H);let _=n["--persona-components-markdown-prose-fontFamily"];_&&_!=="inherit"&&(n["--persona-md-prose-font-family"]=_),bn(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"]]),bn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),bn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),bn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),bn(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"]]);let V=[["container","surface"],["surface","surface"],["border","border"]];for(let[$,We]of V){let me=n[`--persona-components-collapsibleWidget-${$}`]??n[`--persona-${We}`];me!==void 0&&(n[`--persona-cw-${$}`]=me,n[`--cw-${$}`]=me)}bn(n,[["message-border","components-message-border","border"]]),bn(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 te=e.components,W=te?.iconButton;W&&(W.background&&(n["--persona-icon-btn-bg"]=W.background),W.border&&(n["--persona-icon-btn-border"]=W.border),W.color&&(n["--persona-icon-btn-color"]=W.color),W.padding&&(n["--persona-icon-btn-padding"]=W.padding),W.borderRadius&&(n["--persona-icon-btn-radius"]=W.borderRadius),W.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=W.hoverBackground),W.hoverColor&&(n["--persona-icon-btn-hover-color"]=W.hoverColor),W.activeBackground&&(n["--persona-icon-btn-active-bg"]=W.activeBackground),W.activeBorder&&(n["--persona-icon-btn-active-border"]=W.activeBorder));let j=te?.labelButton;j&&(j.background&&(n["--persona-label-btn-bg"]=j.background),j.border&&(n["--persona-label-btn-border"]=j.border),j.color&&(n["--persona-label-btn-color"]=j.color),j.padding&&(n["--persona-label-btn-padding"]=j.padding),j.borderRadius&&(n["--persona-label-btn-radius"]=j.borderRadius),j.hoverBackground&&(n["--persona-label-btn-hover-bg"]=j.hoverBackground),j.fontSize&&(n["--persona-label-btn-font-size"]=j.fontSize),j.gap&&(n["--persona-label-btn-gap"]=j.gap));let Y=te?.toggleGroup;Y&&(Y.gap&&(n["--persona-toggle-group-gap"]=Y.gap),Y.borderRadius&&(n["--persona-toggle-group-radius"]=Y.borderRadius));let E=te?.artifact;if(E?.toolbar){let $=E.toolbar;$.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=$.iconHoverColor),$.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=$.iconHoverBackground),$.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=$.iconPadding),$.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=$.iconBorderRadius),$.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=$.iconBorder),$.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Uf($.toggleGroupGap)),$.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=$.toggleBorderRadius),$.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Uf($.toggleGroupPadding)),$.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=$.toggleGroupBorder),$.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=$.toggleGroupBorderRadius),$.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=vn(e,$.toggleGroupBackground)??$.toggleGroupBackground),$.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=$.copyBackground),$.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=$.copyBorder),$.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=$.copyColor),$.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Uf($.copyBorderRadius)),$.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=$.copyPadding),$.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=$.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??$.copyMenuBackground),$.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=$.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??$.copyMenuBorder),$.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=$.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??$.copyMenuShadow),$.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=$.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??$.copyMenuBorderRadius),$.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=$.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??$.copyMenuItemHoverBackground),$.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=$.iconBackground),$.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=$.toolbarBorder)}if(E?.tab){let $=E.tab;$.background&&(n["--persona-artifact-tab-bg"]=$.background),$.activeBackground&&(n["--persona-artifact-tab-active-bg"]=$.activeBackground),$.activeBorder&&(n["--persona-artifact-tab-active-border"]=$.activeBorder),$.borderRadius&&(n["--persona-artifact-tab-radius"]=$.borderRadius),$.textColor&&(n["--persona-artifact-tab-color"]=$.textColor),$.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=$.hoverBackground),$.listBackground&&(n["--persona-artifact-tab-list-bg"]=$.listBackground),$.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=$.listBorderColor),$.listPadding&&(n["--persona-artifact-tab-list-padding"]=$.listPadding)}if(E?.pane){let $=E.pane;if($.toolbarBackground){let We=vn(e,$.toolbarBackground)??$.toolbarBackground;n["--persona-artifact-toolbar-bg"]=We}}if(E?.card){let $=E.card;$.background&&(n["--persona-artifact-card-bg"]=$.background),$.border&&(n["--persona-artifact-card-border"]=$.border),$.borderRadius&&(n["--persona-artifact-card-radius"]=$.borderRadius),$.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=$.hoverBackground),$.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=$.hoverBorderColor)}if(E?.inline){let $=E.inline;$.background&&(n["--persona-artifact-inline-bg"]=vn(e,$.background)??$.background),$.border&&(n["--persona-artifact-inline-border"]=$.border),$.borderRadius&&(n["--persona-artifact-inline-radius"]=$.borderRadius),$.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=vn(e,$.chromeBackground)??$.chromeBackground),$.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=vn(e,$.chromeBorder)??$.chromeBorder),$.titleColor&&(n["--persona-artifact-inline-title-color"]=vn(e,$.titleColor)??$.titleColor),$.mutedColor&&(n["--persona-artifact-inline-muted-color"]=vn(e,$.mutedColor)??$.mutedColor),$.frameHeight&&(n["--persona-artifact-inline-frame-height"]=$.frameHeight)}let T=te?.code;T&&(T.keywordColor&&(n["--persona-code-keyword-color"]=T.keywordColor),T.stringColor&&(n["--persona-code-string-color"]=T.stringColor),T.commentColor&&(n["--persona-code-comment-color"]=T.commentColor),T.numberColor&&(n["--persona-code-number-color"]=T.numberColor),T.tagColor&&(n["--persona-code-tag-color"]=T.tagColor),T.attrColor&&(n["--persona-code-attr-color"]=T.attrColor),T.propertyColor&&(n["--persona-code-property-color"]=T.propertyColor),T.lineNumberColor&&(n["--persona-code-line-number-color"]=T.lineNumberColor),T.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=T.gutterBorderColor),T.background&&(n["--persona-code-bg"]=vn(e,T.background)??T.background));let B=n["--persona-surface"],P=n["--persona-container"],Q=n["--persona-palette-colors-gray-100"]??"#f3f4f6",U=n["--persona-palette-colors-gray-200"]??"#e5e7eb",de=n["--persona-palette-colors-gray-300"]??"#d1d5db",pe=!P||P===B,ge=NL(B??n["--persona-background"]),ke=pe&&ge!==void 0&&ge<FL,xe=ke?"rgba(255, 255, 255, 0.08)":Q,Le=ke?"rgba(255, 255, 255, 0.12)":U,mt=ke?"rgba(255, 255, 255, 0.16)":de,Ve=pe?xe:P,Re=pe?Le:P;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??Ve,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Re,pe&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??mt),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??Ve,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??Ve,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??Ve,n}var $L={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"};fd();var UL=e=>!!e&&"launcher"in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode==="docked"),Dw=(e,t)=>{if(!t||!UL(t))return e;let n=t.theme?.components?.panel?.width,o=t.darkTheme?.components?.panel?.width;return(ma(t)==="dark"?o??n:n)!=null?e:{...e,components:{...e.components,panel:{...e.components.panel,width:us(t)==="v5"?"400px":"420px"}}}},VL={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"}}},Hl={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)"}}}},zf=VL,jL={...zf,colors:{...zf.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"}}},qL=Hl,zL={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:{...Hl.components,button:{...Hl.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:{...Hl.components?.eventStream,badge:{...Hl.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"}}}}},KL=e=>us({future:e})==="v5"?{palette:jL,components:zL}:{palette:zf,components:qL},Nw=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},up=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",GL=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":up()},ma=e=>GL(e),YL=(e,t={})=>pp(e,t),XL=(e,t={})=>{let n=KL(t.future),o=Ho(n.components,e??{})??{};return pp({...o,palette:{...o.palette,colors:us(t)==="v5"?Ho(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})},Zo=e=>{let t=ma(e),n=Nw(e?.theme),o=sp(e)==="circle"?ip:{...dp.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=Ho({components:{launcher:o}},n),s=Nw(e?.darkTheme);return Dw(t==="dark"?XL(Ho(r??{},s??{}),{future:e?.future}):YL(r,{future:e?.future}),e)},QL=e=>qf(e),ha=(e,t)=>{let n=Zo(t),o=QL(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",ma(t)),e.setAttribute("data-persona-defaults",us(t))},Il=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(up())});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)"),o=()=>e(up());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};fd();Tt();Mr();Xe();import{Activity as gA,Check as fA,Copy as mA}from"lucide";var bs=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var gp="24px",Kf=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",Rl=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},Fw=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);sa();pd();Dd();import{Idiomorph as JL}from"idiomorph";var fp=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;JL.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let i=r.textContent??"",l=s.textContent??"";if(i!==l)return}return!1}}}}})};var $w=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Gf={index:-1,draft:""};function Uw(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,i=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!i&&!r)return{handled:!1,state:s};if(!i){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!i)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function Vw(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 jw(){return new Map}function qw(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function zw(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Kw(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Gw(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function Yw(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function er(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function di(e,t){return er(e)-e.scrollTop<=t}function Xw(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:i=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:p=!1}=e,d=n-o;return i||Math.abs(d)<s?{action:"none",delta:d,nextLastScrollTop:n}:!t&&r&&(!p||d>0)?{action:"resume",delta:d,nextLastScrollTop:n}:t&&l&&d<0?{action:"pause",delta:d,nextLastScrollTop:n}:t&&c&&!r?{action:"pause",delta:d,nextLastScrollTop:n}:{action:"none",delta:d,nextLastScrollTop:n}}function Qw(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function Jw(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Yf(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:n}}function Zw(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}Lo();var Wl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},ZL=["pre","code","a","script","style"],mp=e=>({type:e?.type??Wl.type,placeholder:e?.placeholder??Wl.placeholder,speed:e?.speed??Wl.speed,duration:e?.duration??Wl.duration,buffer:e?.buffer??Wl.buffer}),tS=[{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"}],Ol=new Map;for(let e of tS)Ol.set(e.name,e);var nS=["wipe","glyph-cycle"],hp=e=>{Ol.set(e.name,e)},eH=e=>{tS.some(t=>t.name===e)||Ol.delete(e)},tH=()=>Array.from(Ol.keys()),Bl=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Ol.get(e)??null,yp=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
30
- `);return s<0?"":e.slice(0,s)}return e},nH=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},oH=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},Xf=/\s/,rH=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},sH=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=0;for(;l<s.length;)if(Xf.test(s[l])){let c=l;for(;c<s.length&&Xf.test(s[c]);)c+=1;i.appendChild(o.createTextNode(s.slice(l,c))),l=c}else{let c=o.createElement("span");c.className="persona-stream-word-group";let p=l;for(;p<s.length&&!Xf.test(s[p]);)c.appendChild(nH(o,s[p],t,n.value)),n.value+=1,p+=1;i.appendChild(c),l=p}r.replaceChild(i,e)},iH=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let c of l)c&&(/^\s+$/.test(c)?i.appendChild(o.createTextNode(c)):(i.appendChild(oH(o,c,t,n.value)),n.value+=1));r.replaceChild(i,e)},_l=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??ZL).map(g=>g.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],c=i.nextNode();for(;c;)rH(c,s)||l.push(c),c=i.nextNode();let p={value:o?.startIndex??0},d=t==="char"?sH:iH;for(let g of l)d(g,n,p);return r.innerHTML},bp=(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},Dl=(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},eS=new WeakMap,aH=(e,t)=>{if(!e.styles)return;let n=eS.get(t);if(n||(n=new Set,eS.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))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)},Qf=new WeakMap,lH=(e,t)=>{if(!e.onAttach)return;let n=Qf.get(t);if(n||(n=new Map,Qf.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},oS=e=>{let t=Qf.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Nl=(e,t)=>{aH(e,t),lH(e,t)};ln();var{setLoader:d1,load:cH}=it({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var rS=cH;Lo();function Jf(e,t=Tn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),i=s.position==="static"||s.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var Fl=0,vs=null;function Zf(e=document){if(Fl++,Fl===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;vs={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Fl=Math.max(0,Fl-1),Fl===0&&vs)){let n=e.body,o=e.defaultView??window;n.style.overflow=vs.originalOverflow,n.style.position=vs.originalPosition,n.style.top=vs.originalTop,n.style.width=vs.originalWidth,o.scrollTo(0,vs.scrollY),vs=null}}}ia();var $l={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ht=e=>(e?.launcher?.mountMode??"floating")==="docked",Cs=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",to=e=>{let t=e?.launcher?.dock,n=Pr(e).dockWidth?t?.width:vn(Zo(e),"components.panel.width");return{side:t?.side??$l.side,width:n??$l.width,animate:t?.animate??$l.animate,reveal:t?.reveal??$l.reveal,maxHeight:t?.maxHeight??$l.maxHeight}};Xe();Xe();Tt();Mr();import{ArrowRight as dH}from"lucide";var em=e=>e==="followUp"?"follow-up":e,tm=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},sS=new WeakSet,pH=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,uH=e=>{pH()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},nm=e=>{let{item:t,index:n,surface:o,source:r,variant:s,streaming:i,config:l,plugins:c,chipsConfig:p,session:d,getTextarea:g,eventTarget:f,submitPrompt:h}=e,y=o==="followUp",v=t.behavior,C=()=>{if(d.isStreaming())return;let I={suggestion:{...t},surface:o,source:r,behavior:v},H=f.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:I,bubbles:!0,composed:!0,cancelable:!0}));if(y&&f.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!H)return;for(let V of c)if(V.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let _=g();if(v==="fill"){_.value=t.prompt,_.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),_.focus();return}if(h){h(t.prompt);return}_.value="",d.sendMessage(t.prompt)},A=()=>{let I=x("button",`persona-suggestion persona-suggestion--${s}`);if(I.type="button",I.disabled=i,I.dataset.suggestionId=t.id,I.dataset.emphasis=t.emphasis,I.dataset.behavior=v,s==="chip"&&(p?.fontWeight&&(I.style.fontWeight=p.fontWeight),p?.paddingX&&(I.style.paddingLeft=p.paddingX,I.style.paddingRight=p.paddingX),p?.paddingY&&(I.style.paddingTop=p.paddingY,I.style.paddingBottom=p.paddingY)),t.icon){let _=ue(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);_&&(_.classList.add("persona-suggestion__icon"),t.iconColor&&(_.style.color=t.iconColor),I.appendChild(_))}let H=x("span","persona-suggestion__copy");if(H.appendChild(X("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&H.appendChild(X("span",{className:"persona-suggestion__description",text:t.description})),I.appendChild(H),s!=="chip"){let _=_t(dH,16,"currentColor",1.8);_&&(_.classList.add("persona-suggestion__arrow"),I.appendChild(_))}return I.addEventListener("click",C),I},L=null;for(let I of c)if(I.renderSuggestion&&(L=I.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:i,config:l,defaultRenderer:A,select:C}),L))break;return L??=A(),L.dataset.suggestionId||=t.id,L.dataset.behavior||=v,L.dataset.emphasis||=t.emphasis,L instanceof HTMLButtonElement||L.setAttribute("aria-disabled",i?"true":"false"),L},Ul=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let d=Math.max(0,e.scrollWidth-e.clientWidth);if(d<=1){s();return}let g=getComputedStyle(e).direction==="rtl",f=Math.min(d,Math.max(0,Math.abs(e.scrollLeft))),h=4,y=f<=h,v=f>=d-h,C=g?!v:!y,A=g?!y:!v;e.toggleAttribute("data-scroll-left",C),e.toggleAttribute("data-scroll-right",A)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",l,{passive:!0});let c=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),c?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(d,g,f,h,y,v)=>{e.replaceChildren(),t.length=0,n.length=0;let C=v?.source??"config",A=v?.surface??(C==="config"?"starter":"followUp"),L=A==="followUp",I=v?.variant??"chip",H=v?.behavior??"send",_=v?.overflow??"wrap",V=v?.config??{},te=v?.plugins??[],W=typeof v?.maxItems=="number"?Math.max(0,Math.floor(v.maxItems)):void 0,j=L?"followUps":"starters";!sS.has(V)&&V.debug===!0&&I!=="chip"&&V.suggestions?.[j]?.overflow!==void 0&&(sS.add(V),console.info(`[persona] suggestions.${j}.overflow applies to the "chip" variant only; the "${I}" variant manages its own stacking.`));let Y=U=>U.map(tm).filter(de=>de!==null).map(de=>({...de,behavior:de.behavior??H})),E=Y(d??[]);te.forEach(U=>{U.transformSuggestions&&(E=Y(U.transformSuggestions({suggestions:E.map(de=>({...de})),surface:A,source:C,config:V})))});let T=W===void 0?E:E.slice(0,W);if(!T.length){e.hidden=!0,o=null,s();return}if(!L&&(h??g.getMessages()).some(de=>de.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=em(A),e.dataset.variant=I,e.dataset.overflow=_;let B=document.createDocumentFragment(),P=g.isStreaming();T.forEach((U,de)=>{let pe=nm({item:U,index:de,surface:A,source:C,variant:I,streaming:P,config:V,plugins:te,chipsConfig:y,session:g,getTextarea:()=>f,eventTarget:e,submitPrompt:v?.submitPrompt});B.appendChild(pe),n.push(pe),[...pe instanceof HTMLButtonElement?[pe]:[],...Array.from(pe.querySelectorAll("button"))].forEach(ke=>{t.includes(ke)||(ke.disabled=P,t.push(ke))})}),e.appendChild(B),i(),l();let Q=JSON.stringify({normalized:T,surface:A,variant:I,source:C});Q!==o&&(o=Q,uH(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:T.map(U=>({...U})),surface:A,source:C,variant:I},bubbles:!0,composed:!0})),L&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:T.map(U=>U.prompt)},bubbles:!0,composed:!0})))}}};var no={"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"};Lo();Xe();Tt();bo();Xe();Tt();sa();var gH="persona-header-control",fH="persona-header-control--glyph",mH="persona-header-control--sparse",hH=20,yH={x:[1.4,1.05]},iS="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",bH="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",vp=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,i]=yH[t]??[1,1.5],l=!o;e.classList.toggle(fH,l),e.classList.toggle(mH,l&&s!==1);let c=parseFloat(o??"")||hH,p=ue(t,`${Math.round(c*s)}px`,"currentColor",i);p?(p.style.display="block",l||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(p)):r&&(e.textContent=r)},ya=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:i=iS,size:l,iconSize:c,color:p,backgroundColor:d,borderWidth:g,borderColor:f,borderRadius:h,paddingX:y,paddingY:v,hidden:C,extraClassName:A,attrs:L}=e,I=x("div",i),H=!!(g||f),_=X("button",{className:Wn(gH,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"persona-bg-transparent hover:persona-bg-gray-100",!H&&"persona-border-none",!h&&"persona-rounded-full",A),attrs:{type:"button","aria-label":t,...L},style:{width:l,height:l,minWidth:l,minHeight:l,display:C?"none":void 0,color:p||Bn.actionIconColor,backgroundColor:d,border:H?`${g||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:h,paddingLeft:y,paddingRight:y,paddingTop:v,paddingBottom:v}});return r?vp(_,r,{iconSize:c,iconText:s}):s&&(_.textContent=s),I.appendChild(_),yn({anchor:_,trigger:I,text:()=>_.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:_,wrapper:I}},ba=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=iS,buttonSize:r,iconSize:s}=t,i=e?.launcher??{},l=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:p,wrapper:d}=ya({ariaLabel:l,tooltip:c,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??i.closeButtonSize,iconSize:s,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:d}},va=(e,t={})=>{let{wrapperClassName:n=bH,buttonSize:o,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},l=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:p,wrapper:d}=ya({ariaLabel:l,tooltip:c,iconName:i.iconName??"refresh-cw",wrapperClassName:n,size:o??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:p,wrapper:d}};var Bn={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)"},om={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)"},vH={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)"},ws=e=>{let{config:t,showClose:n=!0}=e,o=X("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:Bn.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)))"}}),r=t?.launcher??{},s=r.headerIconSize??hl,i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,c=r.headerIconName,p=X("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(c){let _=parseFloat(s)||24,V=ue(c,_*.6,"currentColor",1);V?(V.style.width=`calc(${_}px * var(--persona-components-header-iconScale, 0.6))`,V.style.height=`calc(${_}px * var(--persona-components-header-iconScale, 0.6))`,p.replaceChildren(V)):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let _=x("img");_.src=t.launcher.iconUrl,_.alt="",_.className="persona-rounded-xl persona-object-cover",_.style.height=s,_.style.width=s,p.replaceChildren(_)}else p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let d=x("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=X("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Bn.titleColor,...om}}),f=X("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Bn.subtitleColor,...vH}});d.append(g,f),l?o.append(d):o.append(p,d);let h=r.clearChat??{},y=h.enabled??!0,v=h.placement??"inline",C=null,A=null;if(y){let V=va(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});C=V.button,A=V.wrapper,v==="top-right"&&(A.style.right="48px"),v==="inline"&&o.appendChild(A)}let L=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&v==="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",{button:I,wrapper:H}=ba(t,{showClose:n,wrapperClassName:L});return i!=="top-right"&&o.appendChild(H),{header:o,iconHolder:p,headerTitle:g,headerSubtitle:f,closeButton:I,closeButtonWrapper:H,clearChatButton:C,clearChatButtonWrapper:A}},Ca=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};Xe();Xe();Tt();Lo();function wa(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:i}=e,l=x("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(na)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let y of t){if(y.dividerBefore){let A=document.createElement("hr");l.appendChild(A)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",y.id),y.destructive&&v.setAttribute("data-destructive",""),y.icon){let A=ue(y.icon,16,"currentColor",1.5);A&&v.appendChild(A)}let C=document.createElement("span");C.textContent=y.label,v.appendChild(C),v.addEventListener("click",A=>{A.stopPropagation(),g(),n(y.id)}),l.appendChild(v)}let c=null;function p(){if(!s)return;let y=o.getBoundingClientRect();l.style.top=`${y.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-y.right}px`,l.style.left="auto"):(l.style.left=`${y.left}px`,l.style.right="auto")}function d(){let y=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),y&&i?.(!0),requestAnimationFrame(()=>{let v=C=>{!l.contains(C.target)&&!o.contains(C.target)&&g()};document.addEventListener("click",v,!0),c=()=>document.removeEventListener("click",v,!0)})}function g(){let y=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),c?.(),c=null,y&&i?.(!1)}function f(){l.classList.contains("persona-hidden")?d():g()}function h(){g(),l.remove()}return s&&s.appendChild(l),{element:l,show:d,hide:g,toggle:f,destroy:h}}Xe();Tt();function oo(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:i,onClick:l,aria:c}=e,p=x("button",Wn(!i&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ue(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),l&&p.addEventListener("click",l),c)for(let[g,f]of Object.entries(c))p.setAttribute(g,f);return p}function aS(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:i,onClick:l,aria:c}=e,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,i&&(p+=" "+i);let d=x("button",p);if(d.type="button",d.setAttribute("aria-label",n),t){let f=ue(t,s??14,"currentColor",2);f&&d.appendChild(f)}let g=x("span");if(g.textContent=n,d.appendChild(g),l&&d.addEventListener("click",l),c)for(let[f,h]of Object.entries(c))d.setAttribute(f,h);return d}function Cp(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=x("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let i=n,l=[];function c(){for(let d of l)d.btn.setAttribute("aria-pressed",d.id===i?"true":"false")}for(let d of t){let g;d.icon?g=oo({icon:d.icon,label:d.label,className:d.className,onClick:()=>{i=d.id,c(),o(d.id)}}):(g=x("button","persona-icon-btn"+(d.className?" "+d.className:"")),g.type="button",g.setAttribute("aria-label",d.label),g.title=d.label,g.textContent=d.label,g.addEventListener("click",()=>{i=d.id,c(),o(d.id)})),g.setAttribute("aria-pressed",d.id===i?"true":"false"),l.push({id:d.id,btn:g}),s.appendChild(g)}function p(d){i=d,c()}return{element:s,setSelected:p}}function CH(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:i,onPrimary:l,position:c="bottom-left",portal:p,chevronLabel:d="More options",chevronIconSize:g,className:f,primaryClassName:h,chevronClassName:y}=e,v=x("div","persona-split-btn"+(f?" "+f:"")),C={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:l},A=r&&n?oo({...C,icon:n,size:o??14}):aS({...C,icon:n,iconSize:o??14}),L=oo({icon:"chevron-down",label:d,size:g??14,className:"persona-split-btn-chevron"+(y?" "+y:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});v.append(A,L);let I=null,H=()=>{if(I)return I;let _=(typeof p=="function"?p():p)??void 0;return I=wa({items:s,onSelect:i,anchor:v,position:c,portal:_,onOpenChange:V=>{L.setAttribute("aria-expanded",V?"true":"false")}}),_||v.appendChild(I.element),I};return v.isConnected?H():requestAnimationFrame(()=>{I||H()}),L.addEventListener("click",_=>{_.stopPropagation(),H().toggle()}),{element:v,primaryButton:A,chevronButton:L,openMenu:()=>H().show(),closeMenu:()=>I?.hide(),toggleMenu:()=>H().toggle(),destroy:()=>{I?.destroy(),v.remove()}}}function rm(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:c}=e,p=x("div","persona-combo-btn"+(l?" "+l:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",t);let d=x("span","persona-combo-btn-label");d.textContent=t,p.appendChild(d);let g=ue(n,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",p.appendChild(g)),c&&(p.style.borderRadius=c.borderRadius??"10px",p.style.padding=c.padding??"6px 4px 6px 12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=c.background??"",p.style.borderColor=c.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}));let f=wa({items:o,onSelect:y=>{p.setAttribute("aria-expanded","false"),r(y)},anchor:p,position:s,portal:i});i||p.appendChild(f.element);let h=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",y=>{if(y.stopPropagation(),h())return;let v=!f.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",v?"false":"true"),f.toggle()}),p.addEventListener("keydown",y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),p.click())}),{element:p,setLabel:y=>{d.textContent=y,p.setAttribute("aria-label",y)},open:()=>{p.setAttribute("aria-expanded","true"),f.show()},close:()=>{p.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let y=!f.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",y?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),p.remove()}}}Dd();var lS=e=>{let t=ws({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function wH(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=ya({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?_d(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let i=wl(o.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(o.menuItems?.length){let i=wa({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(i.element),r.addEventListener("click",l=>{l.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>n?.(o.id));e.appendChild(s)}}var cS=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,i=t?.launcher??{},l=x("div","persona-flex persona-items-center persona-justify-between");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=Bn.minHeight,l.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=r?.titleMenu,p,d;if(c){let H=rm({label:i.title??"Chat Assistant",menuItems:c.menuItems,onSelect:_=>{let V=W=>{W===!1&&H.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:_}}))},te=c.onSelect(_);te instanceof Promise?te.then(V,()=>{}):V(te)},hover:c.hover,className:""});p=H.element,p.style.color=Bn.titleColor,d=p.querySelector(".persona-combo-btn-label")??p}else{if(p=x("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=x("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Bn.titleColor,Object.assign(d.style,om),d.textContent=i.title??"Chat Assistant",p.appendChild(d),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let _=r.onTitleClick;p.addEventListener("click",V=>{V.target.closest("button")||_()}),p.addEventListener("keydown",V=>{(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),_())})}let H=r?.titleRowHover;H&&(p.style.borderRadius=H.borderRadius??"10px",p.style.padding=H.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=H.background??"",p.style.borderColor=H.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let g="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:f,wrapper:h}=ba(t,{showClose:n,wrapperClassName:g});o&&f.addEventListener("click",o);let y=x("div","persona-flex persona-items-center persona-gap-1");c||wH(y,r?.trailingActions,r?.onAction??s);let v=i.clearChat??{},C=null,A=null;if(v.enabled??!0){let H=v.placement??"inline",_=va(t,{wrapperClassName:H==="top-right"?"persona-absolute persona-top-4 persona-z-50":g});C=_.button,A=_.wrapper,H==="top-right"?A.style.right="48px":y.appendChild(A)}y.appendChild(h),l.appendChild(y);let L=x("div");L.style.display="none";let I=x("span");return I.style.display="none",{header:l,iconHolder:L,headerTitle:d,headerSubtitle:I,closeButton:f,closeButtonWrapper:h,clearChatButton:C,clearChatButtonWrapper:A}},sm={default:lS,minimal:cS},dS=e=>sm[e]??sm.default,Vl=(e,t,n)=>{if(t?.render){let i=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=x("div");l.style.display="none";let c=x("span"),p=x("span"),d=x("button");d.style.display="none";let g=x("div");return g.style.display="none",{header:i,iconHolder:l,headerTitle:c,headerSubtitle:p,closeButton:d,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=dS(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};Xe();gs();var Sa=e=>{let{config:t}=e,n=X("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"}}),o=Td(),r=X("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:s,attachAutoResize:i}=Ad(t);i();let l=xd(t),c=ca(t),p=Md(t),d=Ed(t),g=X("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(g),p&&(p.previewsContainer.style.gap="8px",g.append(p.previewsContainer),r.append(p.input)),r.append(s);let f=X("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=X("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),y=X("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&h.append(p.wrapper),c&&y.append(c.wrapper),y.append(l.wrapper),f.append(h,y),r.append(f),r.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==c?.button&&v.target!==c?.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&s.focus()}),t?.statusIndicator?.mode==="transient"?n.append(o,d,r):n.append(o,r,d),{footer:n,suggestions:o,composerForm:r,header:g,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:d,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:f,leftActions:h,rightActions:y,setSendButtonMode:l.setMode}};Xe();Mr();gs();wd();import{ChevronUp as SH,MessageSquare as AH}from"lucide";var pS=()=>{let e=X("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=x("span","persona-pill-peek__icon"),n=_t(AH,16,"currentColor",1.5);n&&t.appendChild(n);let o=x("span","persona-pill-peek__text"),r=x("span","persona-pill-peek__caret"),s=_t(SH,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},wp=e=>{let{config:t}=e,n=X("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Td(),r=Ed(t);r.style.display="none";let{textarea:s,attachAutoResize:i}=Ad(t,{defaultMaxLines:5});i();let l=xd(t),c=ca(t),p=Md(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let d=X("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),g=X("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&g.append(p.wrapper);let f=X("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&f.append(c.wrapper),f.append(l.wrapper),d.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==c?.button&&v.target!==c?.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&s.focus()}),p&&d.append(p.input),d.append(g,s,f);let h=X("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(h),p&&h.append(p.previewsContainer),n.append(o,d,r);let y=d;return{footer:n,suggestions:o,composerForm:d,header:h,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:y,leftActions:g,rightActions:f,setSendButtonMode:l.setMode}};Xe();Tt();Xe();df();Tt();Hr();var xH=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}},MH=(e,t)=>{if(!e)return null;let n=xH(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},EH=(e,t)=>{let n=x("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},TH=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},am=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(":"))},lm=320,hS=320,PH=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),kH=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),LH=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),HH=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),IH=e=>{if(!e||e.length===0)return null;let t=X("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=X("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=x("span","persona-mention-chip-icon"),s=ue(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(X("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},RH=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Cl(o.ref,{readonly:!0,render:t}))}return n},uS="\uE000",gS="\uE001",WH=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=f=>`${uS}${r}:${f}${gS}`,i=t.map((f,h)=>f.kind==="text"?f.text:s(h)).join(""),l=n(i);if(!t.every((f,h)=>f.kind==="text"||l.includes(s(h)))){e.replaceChildren(RH(t,o));return}e.innerHTML=l;let p=new RegExp(`${uS}${r}:(\\d+)${gS}`),d=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),g=[];for(let f=d.nextNode();f;f=d.nextNode())g.push(f);for(let f of g){let h=f;for(let y=p.exec(h.data);y;y=p.exec(h.data)){let v=t[Number(y[1])],C=h.splitText(y.index);C.data=C.data.slice(y[0].length),v?.kind==="mention"&&C.parentNode?.insertBefore(Cl(v.ref,{readonly:!0,render:o}),C),h=C}}},OH=(e,t,n)=>{if(e.length===0)return null;try{let o=x("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,i=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,c)=>{let p=x("img");p.alt=l.alt?.trim()||`Attached image ${c+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${lm}px`,p.style.maxHeight=`${hS}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let d=!1;r+=1,p.addEventListener("error",()=>{d||(d=!0,r=Math.max(0,r-1),p.remove(),r===0&&i())}),p.addEventListener("load",()=>{d=!0}),TH(l.image)?(p.src=l.image,o.appendChild(p)):(d=!0,r=Math.max(0,r-1),p.remove())}),r===0?(i(),null):o}catch{return n?.(),null}},BH=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!am(o.audio))return;let r=x("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${lm}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},_H=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!am(o.video))return;let r=x("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${lm}px`,r.style.maxHeight=`${hS}px`,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}},DH=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!am(o.data))return;let r=x("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.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}},Aa=()=>{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 o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},yS=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Aa};if(t){let r=t(o);if(r!==null)return r}return Aa()},NH=(e,t)=>{let n=x("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"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=x("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,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},fS=(e,t,n="div")=>{let o=x(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},jl=(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");break}return n},mS={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"}},FH=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=mS[n??"bubble"]??mS.bubble;o.padding&&(e.style.padding=`var(--persona-message-${r}-padding, ${s.padding})`),o.fontSize&&(e.style.fontSize=`var(--persona-message-${r}-font-size, ${s.fontSize})`),o.lineHeight&&(e.style.lineHeight=`var(--persona-message-${r}-line-height, ${s.lineHeight})`),o.fontFamily&&(e.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},Sp="custom:",$H=e=>`${Sp}${e}`,bS=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),vS=(e,t,n,o)=>{let r=t.showCopy??!0,s=t.showUpvote??!1,i=t.showDownvote??!1,l=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&o?.canRegenerate===!0,p=(t.showEdit??!1)&&o?.canEdit===!0,d=(t.showQuote??!1)&&o?.canQuote!==!1,g=bS(t,e.role);if(!r&&!s&&!i&&!l&&!c&&!p&&!d&&g.length===0){let I=x("div");return I.style.display="none",I.id=`actions-${e.id}`,I.setAttribute("data-actions-for",e.id),I}let f=t.visibility??"hover",h=t.align??"right",y=t.layout??"pill-inside",v={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],C={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[y],A=x("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${v} ${C} ${f==="hover"?"persona-message-actions-hover":""}`);A.id=`actions-${e.id}`,A.setAttribute("data-actions-for",e.id);let L=(I,H,_)=>{let V=oo({icon:I,label:H,size:14,className:"persona-message-action-btn",chromeless:!0});return V.setAttribute("data-action",_),V};r&&A.appendChild(L("copy","Copy message","copy")),l&&A.appendChild(L("volume-2","Read aloud","read-aloud")),s&&A.appendChild(L("thumbs-up","Upvote","upvote")),i&&A.appendChild(L("thumbs-down","Downvote","downvote")),c&&A.appendChild(L("refresh-cw","Regenerate response","regenerate")),p&&A.appendChild(L("pencil","Edit message","edit")),d&&A.appendChild(L("quote","Quote message","quote"));for(let I of g)A.appendChild(L(I.iconName??"ellipsis",I.label,$H(I.id)));return A},ql=(e,t,n,o,r,s)=>{let i=n??{},l=i.layout??"bubble",c=i.avatar,p=i.timestamp,d=c?.show??!1,g=p?.show??!1,f=c?.position??"left",h=p?.position??"below",y=jl(e.role,l),v=x("div",y.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let C=Vf(s?.widgetConfig?.future).components.message,A=s?.widgetConfig?.theme?.components?.message;FH(v,e.role,l,e.role==="user"?{...C.user,...A?.user,...s?.widgetConfig?.darkTheme?.components?.message?.user}:{...C.assistant,...A?.assistant,...s?.widgetConfig?.darkTheme?.components?.message?.assistant}),l==="flat"?(v.style.backgroundColor="transparent",v.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let L=PH(e),I=e.content?.trim()??"",_=L.length>0&&I===la,V=mp(s?.widgetConfig?.features?.streamAnimation),te=s?.widgetConfig?.features?.streamAnimation?.plugins,W=e.role==="assistant"&&V.type!=="none"?Bl(V.type,te):null,j=e.role==="assistant"&&W?.isAnimating?.(e)===!0,Y=e.role==="assistant"&&W!==null&&(!!e.streaming||j);Y&&W?.bubbleClass&&v.classList.add(W.bubbleClass);let E=document.createElement("div");E.classList.add("persona-message-content"),e.streaming&&E.classList.add("persona-content-streaming"),Y&&W&&(W.containerClass&&E.classList.add(W.containerClass),E.style.setProperty("--persona-stream-step",`${V.speed}ms`),E.style.setProperty("--persona-stream-duration",`${V.duration}ms`));let T=Y?yp(e.content??"",V.buffer,W,e,!!e.streaming):e.content??"",B=()=>{let Re=t({text:T,message:e,streaming:!!e.streaming,raw:e.rawContent});return Y&&W?.wrap==="char"?_l(Re,"char",e.id,{skipTags:W.skipTags}):Y&&W?.wrap==="word"?_l(Re,"word",e.id,{skipTags:W.skipTags}):Re},P=null;if(_?(P=document.createElement("div"),P.innerHTML=B(),P.style.display="none",E.appendChild(P)):e.contentSegments?.length?WH(E,e.contentSegments,Re=>t({text:Re,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):E.innerHTML=B(),Y&&W?.useCaret&&!_&&I){let Re=bp(),$=E.querySelectorAll(".persona-stream-char, .persona-stream-word"),We=$[$.length-1];if(We?.parentNode)We.parentNode.insertBefore(Re,We.nextSibling);else{let me=E.lastElementChild;me?me.appendChild(Re):E.appendChild(Re)}}if(g&&h==="inline"&&e.createdAt){let Re=fS(e,p,"span");Re.classList.add("persona-timestamp-inline");let $=E.lastElementChild;$?$.appendChild(Re):E.appendChild(Re)}if(L.length>0){let Re=OH(L,!_&&!!I,()=>{_&&P&&(P.style.display="")});Re?v.appendChild(Re):_&&P&&(P.style.display="")}let Q=kH(e);if(Q.length>0){let Re=BH(Q);Re&&v.appendChild(Re)}let U=LH(e);if(U.length>0){let Re=_H(U);Re&&v.appendChild(Re)}let de=HH(e);if(de.length>0){let Re=DH(de);Re&&v.appendChild(Re)}let pe=e.contentSegments?.length?null:IH(e.contextMentions);if(pe&&v.appendChild(pe),v.appendChild(E),g&&h==="below"&&e.createdAt){let Re=fS(e,p);Re.classList.add("persona-mt-1"),v.appendChild(Re)}let ge=e.role==="assistant"?MH(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Re=!!(T&&T.trim()),$=V.placeholder==="skeleton",We=$&&V.buffer==="line"&&Re;if(Re)We&&v.appendChild(Dl());else if($)v.appendChild(Dl());else{let me=yS("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);me&&v.appendChild(me)}}ge&&e.stopReason&&!e.streaming&&(I||(E.style.display="none"),v.appendChild(EH(e.stopReason,ge)));let ke=e.role==="assistant"&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&o?.enabled!==!1,xe=s?.actionEligibility,Le=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&xe?.canEdit===!0||o?.showQuote===!0&&xe?.canQuote===!0||bS(o,"user").length>0);if((ke||Le)&&o){let Re=vS(e,Le?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,xe);v.appendChild(Re)}if(!d||e.role==="system")return v;let mt=x("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ve=NH(c,e.role);return f==="right"||f==="left"&&e.role==="user"?mt.append(v,Ve):mt.append(Ve,v),mt},UH=(e,t,n,o,r,s)=>{let i=n??{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):ql(e,t,n,o,r,s)};var VH=40,jH=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=ue(t.name,VH);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(X("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(X("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},CS=(e,t,n={})=>{let o=X("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=x("p","persona-welcome-kicker");r.hidden=!0;let s=x("h2","persona-welcome-title"),i=x("p","persona-welcome-subtitle"),l=X("div",{className:"persona-welcome-head-text"},r,s),c=X("div",{className:"persona-welcome-title-row"},o,l);return{host:X("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,i,t),iconHolder:o,kicker:r,title:s,subtitle:i,starterSuggestions:t}},xa=(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)},xp=(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==="",jH(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-plugin",wS="data-persona-welcome-overlay",Ap="persona-welcome-overlay-active",cm=new WeakMap,dm=(e,t,n)=>{n.setAttribute(qH,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(wS,""),e.classList.contains(Ap)||(cm.set(e,e.scrollTop),e.classList.add(Ap),e.scrollTop=0)},pm=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(wS),e.classList.contains(Ap)&&(e.classList.remove(Ap),e.scrollTop=cm.get(e)??e.scrollTop,cm.delete(e))},SS=()=>{let e=X("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Mp=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=X("div",{className:jl("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="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(X("div",{className:"persona-flex"},r)),e.hidden=!1},AS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,xS=(e,t)=>{if(AS()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,i=0;if(o){let y=getComputedStyle(o);r=parseFloat(y.rowGap)||0;let v=e.previousElementSibling,C=e.nextElementSibling,L=o.getBoundingClientRect().top+(parseFloat(y.borderTopWidth)||0)+(parseFloat(y.paddingTop)||0)-o.scrollTop;s=Math.max(0,v?n.top-v.getBoundingClientRect().bottom-r:n.top-L),i=Math.max(0,C?C.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let c=getComputedStyle(e),p=parseFloat(c.paddingTop)||0,d=parseFloat(c.paddingBottom)||0,g=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${d}px`,marginTop:`${s}px`,marginBottom:`${i}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),f=!1,h=()=>{f||(f=!0,e.style.overflow=l,t(g))};return g.finished.then(h).catch(h),g},MS=(e,t,n,o=260)=>{if(t<=1||AS()||typeof e.animate!="function"||!e.isConnected)return null;let r=n==="drop"?-t:t;return e.animate([{transform:`translateY(${r}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var zH="Hello \u{1F44B}",KH="I can answer questions and help you get things done here.",ES=new WeakSet,_n=(e,t)=>!!e&&e[t]!==void 0,GH=(e,t)=>{!e||e.debug!==!0||!t.length||ES.has(e)||(ES.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},zl=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!=="docked")=>{let n=e?.welcome,o=e?.copy,r=e?.future?.v5Defaults===!0,s=n?.layout??(r?"centered":"top"),i=_n(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=i==="hero"&&!r&&n?.layout===void 0?"on-first-message":_n(n,"dismiss")?n.dismiss:r||i==="hero"?"on-first-message":"never",c=[];_n(n,"title")&&_n(o,"welcomeTitle")&&c.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),_n(n,"subtitle")&&_n(o,"welcomeSubtitle")&&c.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),_n(n,"variant")&&_n(o,"showWelcomeCard")&&c.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),i==="hero"&&_n(n,"message")&&c.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!r&&n?.layout===void 0&&i==="hero"&&_n(n,"dismiss")&&n.dismiss!=="on-first-message"&&c.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let p=n?.anchor??(s==="centered"&&t?"center":"bottom"),d=Rl(n?.anchorComposerTop)!==null;return _n(n,"anchorComposerTop")&&!d&&c.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&(_n(n,"anchorComposerTop")||_n(n,"composerGap"))&&c.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),GH(e,c),{title:_n(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":zH),kicker:n?.kicker??"",subtitle:_n(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":KH),icon:n?.icon,align:n?.align==="start"||n?.align==="center"?n.align:s==="centered"?"center":void 0,iconPlacement:n?.icon&&typeof n.icon!="function"&&n.icon.placement==="inline"?"inline":"above",variant:i,dismiss:l,message:i==="hero"?void 0:n?.message,layout:s,anchor:p,anchorComposerTop:d?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||gp}},TS=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",pi=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");ia();var YH="var(--persona-components-panel-maxWidth)",PS="var(--persona-components-panel-height)",XH="var(--persona-components-panel-maxHeight)",ui=e=>{let t=Pr(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0,r=o===0?`max(200px, ${PS})`:`max(200px, calc(${PS} - ${o}px))`;return{width:n??Ov,maxWidth:n??YH,height:r,maxHeight:XH}},kS="16px",gm="10px",fm="14px",LS=e=>{let t=e?.launcher?.enabled??!0,n=Ht(e);if(Cs(e)){let p=e?.launcher?.composerBar??{},d=x("div","persona-widget-wrapper persona-fixed persona-transition");d.setAttribute("data-persona-composer-bar",""),d.dataset.state="collapsed",d.dataset.expandedSize=p.expandedSize??"anchored",d.style.zIndex=String(e?.launcher?.zIndex??Tn);let g=x("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");g.style.width="100%",d.appendChild(g);let f=x("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=p.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Tn),{wrapper:d,panel:g,pillRoot:f}}if(n){let p=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),d=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(d),{wrapper:p,panel:d}}if(!t){let p=x("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),d=x("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),g=Pr(e),h=g.launcherWidth||g.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?ui(e).width:"100%";return p.style.width=h,d.style.width="100%",p.appendChild(d),{wrapper:p,panel:d}}let r=e?.launcher??{},s=r.position&&no[r.position]?no[r.position]:no["bottom-right"],i=x("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??Tn);let l=x("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=ui(e);return l.style.width=c.width,l.style.maxWidth=c.maxWidth,i.appendChild(l),{wrapper:i,panel:l}},mm=e=>{let t=X("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":em(e)}});return t.hidden=!0,t},HS=(e,t)=>{let n=mm("starter"),o=CS(e,n,{flatShadow:Ht(e)}),r=zl(e);xp(o,r),xa(t,o.host,pi(r,e?.initialMessages));let s=SS();return Mp(s,r.message,e),{welcome:o,greetingHost:s}},QH=(e,t)=>{let n=x("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:o,wrapper:r}=ba(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:kS,iconSize:gm});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,i=null,l=null;if(s){let te=va(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:kS,iconSize:fm});i=te.button,l=te.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let c=X("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=X("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"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:d,greetingHost:g}=HS(e,p),{host:f,title:h,subtitle:y}=d,v=d.starterSuggestions,C=x("div","persona-widget-messages persona-flex persona-flex-col");C.style.gap="var(--persona-components-message-gap, 12px)";let A=mm("followUp"),L=bs(e,!0);L&&(C.style.maxWidth=L,C.style.marginLeft="auto",C.style.marginRight="auto",C.style.width="100%"),p.append(f,g,C,A);let I=X("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"}}),H=wp({config:e}),{root:_,textNode:V}=pS();return n.append(c,r,p,I),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:C,starterSuggestions:v,transcriptSuggestions:A,composerOverlay:I,suggestions:H.suggestions,textarea:H.textarea,sendButton:H.sendButton,sendButtonWrapper:H.sendButtonWrapper,micButton:H.micButton,micButtonWrapper:H.micButtonWrapper,composerForm:H.composerForm,statusText:H.statusText,welcomeHost:f,welcomeIconHolder:d.iconHolder,greetingHost:g,introKicker:d.kicker,introTitle:h,introSubtitle:y,closeButton:o,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:l,iconHolder:x("span"),headerTitle:x("span"),headerSubtitle:x("span"),header:c,footer:H.footer,attachmentButton:H.attachmentButton,attachmentButtonWrapper:H.attachmentButtonWrapper,attachmentInput:H.attachmentInput,attachmentPreviewsContainer:H.attachmentPreviewsContainer,actionsRow:H.actionsRow,leftActions:H.leftActions,rightActions:H.rightActions,setSendButtonMode:H.setSendButtonMode,peekBanner:_,peekTextNode:V}},IS=(e,t=!0)=>{if(Cs(e))return QH(e,t);let n=X("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"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?Vl(e,o,{showClose:t}):ws({config:e,showClose:t}),i=X("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"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:c}=HS(e,i),{host:p,title:d,subtitle:g}=l,f=l.starterSuggestions,h=x("div","persona-widget-messages persona-flex persona-flex-col");h.style.gap="var(--persona-components-message-gap, 12px)";let y=mm("followUp"),v=bs(e,!1);v&&(h.style.maxWidth=v,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),i.append(p,c,h,y);let C=Sa({config:e}),A=e?.layout?.showFooter!==!1;r?Ca(n,s,e):(s.header.style.display="none",Ca(n,s,e)),n.append(i);let L=X("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 A||(C.footer.style.display="none"),n.append(C.footer),n.append(L),{container:n,body:i,messagesWrapper:h,starterSuggestions:f,transcriptSuggestions:y,composerOverlay:L,suggestions:C.suggestions,textarea:C.textarea,sendButton:C.sendButton,sendButtonWrapper:C.sendButtonWrapper,micButton:C.micButton,micButtonWrapper:C.micButtonWrapper,composerForm:C.composerForm,statusText:C.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:c,introKicker:l.kicker,introTitle:d,introSubtitle:g,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions,setSendButtonMode:C.setSendButtonMode}};gs();Xe();Tt();Lo();var hm=(e,t)=>{let n=x("button");n.type="button",n.innerHTML=`
28
+ `),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(l){let p=[];s&&p.push(Io(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(c){let p=[];i&&p.push(Io(i)),p.push(...r.contentParts),t.contentParts=p}else s&&(t.llmContent=i);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim(),r=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0)&&!r)return;this.#D&&!n?.voiceTurn&&(this.#D.failed=!0,this.#D=null),(this.#I||this.#w||this.#y||this.#B)&&await this.#Fe(),this.stopSpeaking(),this.abortController?.abort(),this.#me(),this.#de++,this.#ye();let s=n?.voiceTurn?.userMessageId,i=s?this.messages.find(h=>h.id===s&&h.role==="user"):void 0,l=i?.id??El(),c=li();this.#s=null;let p=n?.contentParts&&bl(n.contentParts)?la:"",d={id:l,role:"user",content:o||p,createdAt:new Date().toISOString(),sequence:this.#j(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};i?(i.viaVoice=!0,delete i.voiceCaption,i.content.trim()!==o&&(i.llmContent=o),this.callbacks.onMessagesChanged([...this.messages])):this.#te(d),this.#L(!0);let g=new AbortController;if(this.abortController=g,n?.mentions){let h=this.messages.find(y=>y.id===l)??d;if(await this.#Qe(h,o,n.mentions.finalize),g.signal.aborted||this.abortController!==g)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let h=this.messages.find(b=>b.id===l)??d,y=jC({quote:n.quote,text:h.llmContent??h.content,contentParts:h.contentParts});y.contentParts&&(h.contentParts=y.contentParts),y.llmContent!==void 0&&(h.llmContent=y.llmContent),(y.contentParts||y.llmContent!==void 0)&&(h.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let f=i?[...this.messages.filter(h=>h!==i),{...i,createdAt:new Date().toISOString()}]:[...this.messages];try{await this.#Ye(f,g,c,l,{composerOptions:n?.composerOptions,interrupt:n?.interrupt,voiceSpoken:!!n?.voiceTurn})}catch(h){if(this.status==="resuming"||this.#r)return;this.#D&&(this.#D.failed=!0);let y=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));if(!y){let b=Of(h,this.config.errorMessage);if(b){let C={id:c,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.#j()};this.#te(C)}}this.#K("idle"),this.#L(!1),this.abortController=null,y||(h instanceof Error?this.callbacks.onError?.(h):this.callbacks.onError?.(new Error(String(h))))}}resubmitFrom(t,n){let o=qC(this.messages,t);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,i=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!i?.trim()||(l?.length??0)>0||!s&&(r.llmContent?.trim()?.length??0)>0))return!1;let p=s?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}},d=s?this.#Je(s.options):r.composerOptions,g=s?s.contentSegments:r.contentSegments,f=s?s.options?.quote:void 0,h=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(i??"",{...l?.length?{contentParts:[...l]}:{},...g?.length?{contentSegments:[...g]}:{},...d?{composerOptions:d}:{},...f?{quote:f}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:h===!0}),!0}#Je(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.#I||this.#w||this.#y||this.#B)&&await this.#Fe(),this.abortController?.abort(),this.#ye();let t=li();this.#s=null,this.#L(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.#r)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let i=Of(r,this.config.errorMessage);if(i){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.#j()};this.#te(l)}}this.#K("idle"),this.#L(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.#s=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let i of this.messages)i.streaming&&i.id!==o&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#L(!0);let s={};try{await this.client.processStream(t,i=>{let l=this.#n;this.#n=s;try{this.handleEvent(i)}finally{this.#n=l}},n?.assistantMessageId,n?.seedContent),this.#Oe(s)}catch(i){if(this.status==="resuming"||this.#r){this.#pt(s);return}this.#Oe(s),this.#K("error"),this.webMcpResolveControllers.size===0&&(this.#L(!1),this.abortController=null),this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))}}#$e(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.#l}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}#Ze;#de;#ke(t){let n=this.#Ze??={s:this,setStreaming:s=>this.#L(s),appendMessage:s=>this.#te(s),nextSequence:()=>this.#j(),settleApprovalPausedToolCall:s=>this.#je(s),resumeAfter:s=>this.#t?.executionId===s?this.#t.lastEventId:void 0},o=oC();if(o)return t(o,n);let r=this.#de;return bf().then(s=>r===this.#de?t(s,n):void 0,s=>{this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))})}resolveApproval(t,n,o){return this.#ke((r,s)=>r.resolveApproval(s,t,n,o))}resolveAskUserQuestion(t,n){return this.#ke((o,r)=>o.resolveAskUserQuestion(r,t,n))}resolveWebMcpToolCall(t){return this.#ke((n,o)=>n.resolveWebMcpToolCall(o,t))}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}#et(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.#c;queueMicrotask(()=>{s===this.#c&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}#tt(){if(this.webMcpAwaitBatches.size===0)return;let t=this.#c;queueMicrotask(()=>{if(t===this.#c)for(let n of[...this.webMcpAwaitBatches.keys()])this.#nt(n)})}#nt(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.#ke((r,s)=>r.resolveWebMcpToolCallBatch(s,t,o))}#me(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.#c++}cancel(){this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#de++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#L(!1),this.#K("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#de++,this.messages=[],this.agentExecution=null,this.#Re(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#L(!1),this.#K("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.#u}selectArtifact(t){this.#u=t,this.#he()}clearArtifacts(){this.#Re()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.#u=n,this.#he(),t.transcript!==!1&&this.#ot(o),o}#ot(t){let n=`artifact-ref-${t.id}`,o=Mr(this.config.features?.artifacts,t),r=al(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...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}:{}}),s=this.messages.find(i=>i.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}#Ue(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(i=>i.id===`artifact-ref-${n.id}`);if(!o)continue;let r=Mr(this.config.features?.artifacts,n),s=al(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}#Re(){this.artifacts.size===0&&this.#u===null||(this.artifacts.clear(),this.#u=null,this.#he())}#he(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#u})}#rt(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.#u=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.#he()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.#ye(),this.#me(),this.#de++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#pe(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.#j()}))),this.#L(!1),this.#K("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.#u=n,this.#he()}#st(t){let n=this.agentExecution?.executionId;if(!n||!this.#s||this.agentExecution?.status!=="running")return;let o=this.#t===null;this.#t={executionId:n,lastEventId:t,assistantMessageId:this.#s,status:"running"},this.#dt(o)}#it(){return this.#t!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#Ve()}#Ve(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}#We(){this.#r||!this.#t||typeof this.config.reconnectStream!="function"||(this.#r=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#t}),this.#L(!0),this.#K("resuming"),this.#at().then(t=>{this.#r&&this.#t&&t.begin()}))}#at(){return this.#p?Promise.resolve(this.#p):(this.#f||(this.#f=ew().then(({createReconnectController:t})=>{let n=t(this.#lt());return this.#p=n,n}),this.#f.catch(()=>{this.#f=null})),this.#f)}#lt(){let t=this;return{get config(){return t.config},getResumable:()=>t.#t,clearResumable:()=>t.#Pe(),getStatus:()=>t.status,setStatus:n=>t.#K(n),setStreaming:n=>t.#L(n),setReconnecting:n=>{t.#r=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.#te(n),nextSequence:()=>t.#j(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>Of(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.#r){this.#p?.wake();return}this.#We()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.#r)return;let n=this.#ct();n||(n=li(),this.#te({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.#j()})),this.#s=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.#t={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.#We()}#ct(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}#ye(){this.#r=!1,this.#p?.teardown(),this.#Pe()}#Pe(){this.#i&&(clearTimeout(this.#i),this.#i=null);let t=this.#t!==null;this.#t=null,t&&this.config.onExecutionState?.(null)}#dt(t){let n=this.config.onExecutionState;if(n){if(t){this.#i&&(clearTimeout(this.#i),this.#i=null),n(this.#t);return}this.#i||(this.#i=setTimeout(()=>{this.#i=null,this.config.onExecutionState?.(this.#t)},500))}}getResumableHandle(){return this.#t}#K(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}#L(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&(this.#Oe(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(t){let n=this.config.textToSpeech;if(!n?.enabled||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(i=>i.role==="assistant"&&i.content&&!i.voiceProcessing);if(!r||t&&!t.includes(r.id))return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=If(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(t){return Ml(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=If(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}#Oe(t){for(let[n,o]of[...this.#e])o===t&&(this.#e.delete(n),this.#je(n))}#pt(t){for(let[n,o]of this.#e)o===t&&this.#e.set(n,void 0)}#je(t){let n=this.messages.find(l=>l.id===t)?.approval,o=n?.toolCallId,r=o&&this.messages.find(l=>l.toolCall?.id===o),s=r&&r.toolCall;if(!s||s.status==="complete"||n.status==="pending")return;let i={...s,status:"complete",approvalStatus:n.status,completedAt:Date.now(),...n.status==="approved"?{superseded:!0}:{success:!1,error:n.status==="denied"?"Denied":"Approval timed out"}};this.upsertMessage({...r,streaming:!1,toolCall:i})}#te(t){let n=this.#xe(t);this.messages=this.#pe([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.#xe(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.#te(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let i={...r,...n};r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(i.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(i.agentMetadata={...i.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let l=r.agentMetadata?.clientToolAnswer;if(l&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:l}),r.approval&&n.approval&&r.approval.id===n.approval.id){let g=r.approval,f=n.approval;i.approval={...g,...f,executionId:f.executionId||g.executionId,toolName:f.toolName||g.toolName,description:f.description||g.description,toolType:f.toolType??g.toolType,reason:f.reason??g.reason,parameters:f.parameters??g.parameters,toolCallId:f.toolCallId??g.toolCallId}}let c=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(c&&tw(c)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let g=`${p}:${d}`,f=this.webMcpInflightKeys.has(g),h=this.webMcpResolvedKeys.has(g),y=r.toolCall?.name,b=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&y!==void 0&&tw(y)&&r.toolCall?.status==="complete";(f||h||b)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.#pe(this.messages),this.callbacks.onMessagesChanged([...this.messages])}#xe(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.#j()}}#j(){return this.#o++}#pe(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=n.sequence??0,l=o.sequence??0;return i!==l?i-l:n.id.localeCompare(o.id)})}};Qe();Er();Tt();Hr();import{File as eL,FileCode as tL,FileSpreadsheet as nL,FileText as _f,X as oL}from"lucide";var rL={add:e=>qv(e)},sL=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,np={allowedTypes:Lr,maxFileSize:10*1024*1024,maxFiles:4};function iL(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function aL(e){return e==="application/pdf"?_f:e.startsWith("text/")?_f:e.includes("word")?_f:e.includes("excel")||e.includes("spreadsheet")?nL:e==="application/json"?tL:eL}var fa=class e{constructor(t={}){this.attachments=[];this.#e=null;this.#n=new Map;this.#o=!1;this.config={allowedTypes:t.allowedTypes??np.allowedTypes,maxFileSize:t.maxFileSize??np.maxFileSize,maxFiles:t.maxFiles??np.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}#e;#n;#o;#t(){return typeof this.config.adapter?.add=="function"}#s(){return this.#t()?this.config.adapter:rL}setPreviewsContainer(t){this.#e=t}remountPreviews(t){if(this.#e=t,t){t.innerHTML="";for(let n of this.attachments)this.#u(n)}this.#a()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:np.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange),t.adapter!==void 0&&(this.config.adapter=t.adapter)}isReady(){return this.attachments.every(t=>t.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart).filter(t=>t!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(!t.length||this.#o)return;let n=[];for(let o of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=zv(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let i=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,i);continue}let s={id:iL(),file:o,previewUrl:vd(o)?URL.createObjectURL(o):null,contentPart:null,status:this.#t()?"uploading":"processing",progress:this.#t()?0:void 0};this.attachments.push(s),this.#u(s),n.push(s)}this.#a(),this.#i(),await Promise.all(n.map(o=>this.#r(o)))}async#r(t){let n=new AbortController;this.#n.set(t.id,n);let o=()=>this.#o||n.signal.aborted||this.#n.get(t.id)!==n||!this.attachments.includes(t);try{let r=await this.#s().add(t.file,{signal:n.signal,onProgress:s=>{o()||t.status!=="uploading"||(t.progress=sL(s),this.#c(t),this.#i())}});if(o())return;t.contentPart=r,t.status="ready",t.progress=void 0,t.error=void 0}catch(r){if(o())return;t.status="error",t.progress=void 0,t.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.#n.get(t.id)===n&&this.#n.delete(t.id)}this.#c(t),this.#i()}retryAttachment(t){let n=this.attachments.find(o=>o.id===t);!n||n.status!=="error"||this.#o||(n.status=this.#t()?"uploading":"processing",n.progress=this.#t()?0:void 0,n.error=void 0,this.#c(n),this.#i(),this.#r(n))}#p(t){let n=this.#n.get(t);n&&(this.#n.delete(t),n.abort())}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];this.#p(t),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.#e?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),o.status==="ready"&&o.contentPart&&this.#f(o.contentPart),this.#a(),this.#i()}#f(t){let n=this.config.adapter?.remove;if(n)try{let o=n(t,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let t of this.attachments)this.#p(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#n.clear(),this.#e&&(this.#e.innerHTML=""),this.#a(),this.#i()}destroy(){if(!this.#o){this.#o=!0;for(let t of this.#n.values())t.abort();this.#n.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#e=null}}#i(){this.#o||this.config.onAttachmentsChange?.(this.getAttachments())}#u(t){if(!this.#e)return;let n=vd(t.file),o=x("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let d=x("img");d.src=t.previewUrl,d.alt=t.file.name,d.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",d.style.width="48px",d.style.height="48px",d.style.objectFit="cover",d.style.borderRadius="8px",o.appendChild(d)}else{let d=x("div");d.style.width="48px",d.style.height="48px",d.style.borderRadius="8px",d.style.backgroundColor="var(--persona-container, #f3f4f6)",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.display="flex",d.style.flexDirection="column",d.style.alignItems="center",d.style.justifyContent="center",d.style.gap="2px",d.style.overflow="hidden";let g=aL(t.file.type),f=Bt(g,20,"var(--persona-muted, #6b7280)",1.5);f&&d.appendChild(f);let h=x("span");h.textContent=Kv(t.file.type,t.file.name),h.style.fontSize="8px",h.style.fontWeight="600",h.style.color="var(--persona-muted, #6b7280)",h.style.textTransform="uppercase",h.style.lineHeight="1",d.appendChild(h),o.appendChild(d)}let r=X("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=x("div","persona-attachment-progress");s.appendChild(x("div","persona-attachment-progress__bar"));let i=X("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=ue("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?i.appendChild(l):i.textContent="\u21BB",i.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),this.retryAttachment(t.id)}),r.append(s,i),o.appendChild(r);let c=x("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");c.type="button",c.setAttribute("aria-label","Remove attachment"),c.style.position="absolute",c.style.top="-4px",c.style.insetInlineEnd="-4px",c.style.width="18px",c.style.height="18px",c.style.borderRadius="50%",c.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",c.style.border="none",c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center",c.style.justifyContent="center",c.style.padding="0";let p=Bt(oL,10,"var(--persona-text-inverse, #ffffff)",2);p?c.appendChild(p):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(c),this.#e.appendChild(o),this.#l(o,t)}#c(t){let n=this.#e?.querySelector(`[data-attachment-id="${t.id}"]`);n&&this.#l(n,t)}#l(t,n){t.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";t.setAttribute("aria-busy",o?"true":"false"),t.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let r=t.querySelector(".persona-attachment-progress__bar");if(r){let s=n.progress;r.style.width=typeof s=="number"?`${Math.round(s*100)}%`:""}}#a(){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})}};var nw=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),lL=(e,t)=>e.length===t.length&&e.every((n,o)=>{let r=t[o];return n.id===r.id&&n.name===r.name&&n.mimeType===r.mimeType&&n.size===r.size&&n.status===r.status&&n.progress===r.progress&&n.error===r.error});function ow(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,n=null,o=!1,r=!1,s=()=>e.preparing?"preparing":e.streaming?"streaming":"idle",i=()=>{let d=s();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(g=>Object.freeze({...g}))),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:d,inputDisabled:e.inputDisabled,sendDisabled:d!=="idle"||e.sendDisabled||e.inputDisabled})},l=()=>(n||(n=i()),n),c=()=>{if(o=!1,r||t.size===0)return;let d=l();for(let g of[...t])try{g(d)}catch(f){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",f)}},p=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(c))};return{getState:l,subscribe:d=>(t.add(d),()=>t.delete(d)),setText:d=>{e.text!==d&&(e.text=d,p())},setAttachments:d=>{lL(e.attachments,d)||(e.attachments=[...d],p())},setMentionRefs:d=>{nw(e.mentionRefs,d)||(e.mentionRefs=[...d],p())},setSelectedModelId:d=>{e.selectedModelId!==d&&(e.selectedModelId=d,p())},setActiveModeIds:d=>{nw(e.activeModeIds,d)||(e.activeModeIds=[...d],p())},setQuote:d=>{let g=e.quote;g?.text===d?.text&&g?.messageId===d?.messageId&&g?.sourceLabel===d?.sourceLabel||(e.quote=d?{...d}:void 0,p())},setPendingSubmission:d=>{e.pendingSubmission!==d&&(e.pendingSubmission=d,p())},setPreparing:d=>{e.preparing!==d&&(e.preparing=d,p())},setStreaming:d=>{e.streaming!==d&&(e.streaming=d,p())},setInputDisabled:d=>{e.inputDisabled!==d&&(e.inputDisabled=d,p())},setSendDisabled:d=>{e.sendDisabled!==d&&(e.sendDisabled=d,p())},flush:()=>{o&&c()},destroy:()=>{r=!0,o=!1,t.clear()}}}Qe();var Kn=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},rw=(e,t)=>{let n=x("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function sw(e,t={}){let n=Kn(e,"[data-persona-composer-form]"),o=Kn(e,"[data-persona-composer-input]");if(!n||!o){let A=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||o))throw new Error(A);return typeof console<"u"&&console.warn(A),null}let r={header:Kn(e,"[data-persona-composer-header]"),body:Kn(e,"[data-persona-composer-body]"),actionsStart:Kn(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Kn(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Kn(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Kn(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Kn(e,"[data-persona-composer-status]")},s=new Set,i=r.header;i||(s.add("header"),i=rw("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(i,n):e.appendChild(i));let l=r.body??o.parentElement??n,c=(C,A,L,I,H)=>{if(A)return A;s.add(C);let B=rw(L,I);return H.appendChild(B),B},p=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),d=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),g=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),f=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[],y=(C,A)=>C.target===A.target&&C.type===A.type&&C.handler===A.handler,b=Kn(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:n,input:o,header:i,body:l,actionsStart:p,actionsEnd:d,suggestions:g,status:f,attachmentInput:b,attachmentPreviews:Kn(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Kn(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Kn(e,"[data-persona-composer-submit]")??void 0,micButton:Kn(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(C,A,L,I)=>{C.addEventListener(A,L,I),h.push({target:C,type:A,handler:L,options:I})},removeListener:(C,A,L,I)=>{C.removeEventListener(A,L,I),h=h.filter(H=>!y(H,{target:C,type:A,handler:L}))},destroy:()=>{for(let C of h)C.target.removeEventListener(C.type,C.handler,C.options);h=[]}}}Qe();Tt();sa();gs();function cL(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function op(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:i,verticalOffset:l,zIndex:c=2147483e3,onOpen:p,onDismiss:d}=e,g=e.container??cL(t),f=!1,h=null,y=()=>{if(!f)return;let A=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${A.width}px`),i&&(n.style.maxWidth=`${A.width}px`);let L=n.getBoundingClientRect(),I=l?.()??null,H=I!=null?A.top+I:A.top,B=o==="top-start"||o==="top-end"?H-r-L.height:A.bottom+r,te=o==="bottom-end"||o==="top-end"?A.right-L.width:A.left,W=i?.()??null;if(W!=null){let j=Math.max(A.left,A.right-L.width);te=Math.min(Math.max(A.left+W,A.left),j)}n.style.top=`${B}px`,n.style.left=`${te}px`},b=()=>{f&&(f=!1,h&&(h(),h=null),n.remove())},C=()=>{if(f)return;f=!0,c!=null&&(n.style.zIndex=String(c)),g.appendChild(n),y();let A=(t.ownerDocument??document).defaultView??window,L=t.ownerDocument??document,I=()=>{if(!t.isConnected){b(),d?.("anchor-removed");return}y()},H=V=>{let te=typeof V.composedPath=="function"?V.composedPath():[];te.includes(n)||te.includes(t)||(b(),d?.("outside"))},B=A.setTimeout(()=>{L.addEventListener("pointerdown",H,!0)},0);A.addEventListener("scroll",I,!0),A.addEventListener("resize",I),h=()=>{A.clearTimeout(B),L.removeEventListener("pointerdown",H,!0),A.removeEventListener("scroll",I,!0),A.removeEventListener("resize",I)},p?.()};return{get isOpen(){return f},open:C,close:b,toggle:()=>f?b():C(),reposition:y,destroy:b}}Qe();Tt();gs();var dL='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',pL=["--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"],Bf="data-persona-menu-focus",uL=new Set(["ArrowDown","ArrowUp","Home","End"]);function iw(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(dL)??e}var gL=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function aw(e){let t=e.label,n=!1,o=x("div","persona-send-button-wrapper"),r=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${eo} ${Ro}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=X("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{let k=e.getButtonSize?.()??"";r.style.width=k,r.style.height=k,r.style.minWidth=k,r.style.minHeight=k,r.style.lineHeight="1",r.replaceChildren();let Q=ue("plus",zn,"currentColor",1.5);Q?r.appendChild(Q):r.textContent="+"},l=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),s.setAttribute("aria-label",t)};l(),i();let c=[],p=-1,d=!1,g=()=>{let Q=s.getRootNode().activeElement;return Q instanceof HTMLElement?Q:null},f=()=>{let k=g();for(let Q of c){let U=!!k&&iw(Q)===k;Q.toggleAttribute(Bf,U&&d)}},h=()=>c.filter(k=>k.isConnected||s.contains(k)).map(iw).filter(k=>!gL(k)),y=(k,Q)=>{k.forEach((U,de)=>{U.setAttribute("tabindex",de===Q?"0":"-1")})},b=k=>{let Q=h();if(Q.length===0)return;let U=(k%Q.length+Q.length)%Q.length;p=U,y(Q,U),Q[U].focus(),f()},C=()=>o.ownerDocument??document,A=null,L=null,I=null,H=()=>{A&&(C().removeEventListener("focusin",A,!0),A=null)},B=()=>{L&&(s.removeEventListener("focusin",L),L=null),I&&(s.removeEventListener("pointerdown",I,!0),I=null)},V=null,te=()=>(V||(V=op({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),H()}})),V),W=()=>V?.isOpen===!0,j=(k=!1)=>{if(W()){V?.close(),r.setAttribute("aria-expanded","false"),H(),B(),p=-1,d=!1;for(let Q of c)Q.removeAttribute(Bf);k&&r.focus()}},Y=(k=0,Q=!1)=>{if(n||W())return;d=Q,xd(r,s,pL),te().open(),r.setAttribute("aria-expanded","true");let U=h();y(U,-1),b(k<0?U.length-1:k),A=de=>{let pe=typeof de.composedPath=="function"?de.composedPath():[];pe.includes(s)||pe.includes(o)||j()},C().addEventListener("focusin",A,!0),L=()=>f(),s.addEventListener("focusin",L),I=()=>{d=!1},s.addEventListener("pointerdown",I,!0)},M=k=>{k.preventDefault(),k.stopPropagation(),W()?j(!0):Y(0)},T=k=>{if(k.key==="ArrowDown"||k.key==="Enter"||k.key===" "){k.preventDefault(),d=!0,W()?b(0):Y(0,!0);return}k.key==="ArrowUp"&&(k.preventDefault(),d=!0,W()?b(-1):Y(-1,!0))},_=k=>{switch(uL.has(k.key)&&(d=!0),k.key){case"ArrowDown":k.preventDefault(),b(p+1);return;case"ArrowUp":k.preventDefault(),b(p-1);return;case"Home":k.preventDefault(),b(0);return;case"End":k.preventDefault(),b(h().length-1);return;case"Escape":k.preventDefault(),k.stopPropagation(),j(!0);return;case"Tab":j(!0);return;default:}};return r.addEventListener("click",M),r.addEventListener("keydown",T),s.addEventListener("keydown",_),{trigger:o,triggerButton:r,panel:s,setItems:k=>{for(let U of c)k.includes(U)||U.removeAttribute(Bf);if(c=[...k],!W())return;let Q=h();y(Q,Math.min(p,Q.length-1)),f()},isOpen:W,open:()=>Y(0),close:j,setLabel:k=>{k!==t&&(t=k,l())},applyButtonSize:i,destroy:()=>{n=!0,H(),B(),r.removeEventListener("click",M),r.removeEventListener("keydown",T),s.removeEventListener("keydown",_),V?.destroy(),V=null,o.remove(),s.remove(),c=[]}}}var Jo={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},lw="data-persona-composer-action",Df="data-persona-composer-disable-when-streaming",fL="core:overflow",mL=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function hL(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 o=x("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=e,t.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function Nf(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let o=n.getComputedStyle(e),r=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,t-r)}var cw=(e,t)=>{!e||typeof console>"u"||console.warn(t)},yL=(e,t)=>t.includes(":")?t:`${e}:${t}`;function bL(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){cw(t,`[Persona] composer action "${l.id}" is already contributed by ${dw(c)}; the ${dw(l)} copy is ignored.`);return}o.set(l.id,l),n.push(l)};for(let l of e.builtIns)s({id:l.id,placement:l.placement,presentation:"bar",order:l.order,sequence:r++,source:"core",builtIn:l});let i=(l,c,p)=>{let d=p?yL(p,l.id):l.id,g=l.order??Jo.custom;l.placement==="end"&&g>=Jo.send&&(cw(t,`[Persona] composer action "${d}" ordered at ${g} would render after send; clamped to ${Jo.send-1}.`),g=Jo.send-1),s({id:d,placement:l.placement,presentation:l.presentation??"bar",order:g,sequence:r++,source:c,pluginId:p,action:l})};for(let l of e.configActions??[])i(l,"config");for(let l of e.plugins){if(!l.contributeComposerActions)continue;let c;try{c=l.contributeComposerActions(e.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,p);continue}for(let p of c??[])i(p,"plugin",l.id)}return n.sort((l,c)=>l.order===c.order?l.sequence-c.sequence:l.order-c.order)}var dw=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",pw=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,vL=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function CL(e,t){if(!e||e==="always")return!0;let n=vL(t);return e==="when-text"?n:!n}var ys=e=>e.kind==="custom",Ff=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,wL=e=>{let t=Ff(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},SL='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function AL(e){let t="",n=o=>{if(o.nodeType===Node.TEXT_NODE){t+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let r=o;typeof r.matches=="function"&&r.matches(SL)||o.childNodes.forEach(n)};return n(e),t.trim()}var xL=e=>AL(e).length===0;function uw(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(M,T)=>{let _=M.button;if(!_)return;_.setAttribute("role","menuitem"),_.setAttribute("tabindex","-1"),_.className="persona-composer-overflow-menu__item";for(let U of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])_.style[U]="";_.style.lineHeight="1",T.tooltipText?_.setAttribute("title",T.tooltipText):_.removeAttribute("title"),_.replaceChildren();let k=x("span","persona-composer-overflow-menu__icon");if(T.iconName){let U=ue(T.iconName,16,"currentColor",1.5);U&&k.appendChild(U)}let Q=x("span","persona-composer-overflow-menu__label");Q.textContent=T.shortLabel??T.label,_.append(k,Q)},i=(M,T)=>{let _=M.button;if(!_)return;if(_.setAttribute("aria-label",T.label),T.pressed===void 0?_.removeAttribute("aria-pressed"):_.setAttribute("aria-pressed",T.pressed?"true":"false"),_.toggleAttribute(Df,T.disableWhenStreaming===!0),M.mode==="menu"){M.tooltip?.destroy(),M.tooltip=void 0,s(M,T);return}_.removeAttribute("role"),_.removeAttribute("tabindex"),_.removeAttribute("title");let k=r(),Q=!!T.shortLabel;if(_.className=On("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",eo,Ro,Q&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),_.style.width=k&&!Q?k:"",_.style.height=k??"",_.style.minWidth=k&&!Q?k:"",_.style.minHeight=k??"",_.style.fontSize=Q?"":"18px",_.style.lineHeight="1",_.style.color=T.iconColor??"",_.style.backgroundColor=T.backgroundColor??"",_.replaceChildren(),T.iconName){let U=ue(T.iconName,zn,"currentColor",1.5);U&&_.appendChild(U)}if(Q){let U=x("span","persona-composer-action-button__label");U.textContent=T.shortLabel,_.appendChild(U)}else _.firstChild||(_.textContent=T.label);M.tooltip?.destroy(),M.tooltip=yn({anchor:_,trigger:M.element,text:()=>T.tooltipText??T.label,enabled:!!T.tooltipText})},l=(M,T)=>{let _=M.action,k=X("button",{attrs:{type:"button"}}),Q=k;if(T==="bar"){let pe=x("div","persona-send-button-wrapper");pe.appendChild(k),Q=pe}Q.setAttribute(lw,M.id);let U={resolved:M,element:Q,button:k,owned:!0,managed:!0,busy:!1,visible:!0,mode:T},de=pe=>{if(pe.preventDefault(),pe.stopPropagation(),U.busy||k.disabled)return;let ge=U.resolved.action;U.mode==="menu"&&h?.close(!0);let Pe;try{Pe=ge.onSelect(e.actionContext,pe)}catch(Ae){e.reportError(Ae,{actionId:U.resolved.id});return}!Pe||typeof Pe.then!="function"||(U.busy=!0,k.setAttribute("aria-busy","true"),Pe.catch(Ae=>{e.reportError(Ae,{actionId:U.resolved.id})}).finally(()=>{U.busy=!1,k.removeAttribute("aria-busy")}))};return k.addEventListener("click",de),U.detach=()=>k.removeEventListener("click",de),i(U,_),U},c=M=>{let T=M.action,_;try{_=T.render({...e.actionContext,id:M.id,action:T})}catch(k){return e.reportError(k,{actionId:M.id}),null}return _?.element?(_.element.setAttribute(lw,M.id),_.element.toggleAttribute(Df,T.disableWhenStreaming===!0),{resolved:M,element:_.element,owned:!0,managed:!0,destroy:_.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(M,T)=>{if(M.builtIn){let k=M.builtIn.element;return k?{resolved:M,element:k,owned:!1,managed:M.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let _=M.action;return _?ys(_)?c(M):l(M,T):null},d=M=>{if(M.detach?.(),M.tooltip?.destroy(),M.detachMenuSlot?.(),M.detachMenuSlot=void 0,M.menuLabel?.remove(),M.menuLabel=void 0,M.menuSlot?.remove(),M.menuSlot=void 0,M.owned){try{M.destroy?.()}catch(T){e.reportError(T,{actionId:M.resolved.id})}M.element.remove()}},g=(M,T)=>{for(let _=0;_<T.length;_++){let k=T[_];if(!k.managed)continue;let Q=null;for(let U=_+1;U<T.length;U++){let de=T[U];if(!de.managed&&de.element.parentElement===M){Q=de.element;break}}Q?(k.element.parentElement!==M||k.element.nextSibling!==Q)&&M.insertBefore(k.element,Q):M.lastChild!==k.element&&M.appendChild(k.element)}},f=(M,T)=>{if(M.button){M.button.disabled=T;return}if(!M.owned)return;let _=M.element;_.toggleAttribute("data-disabled",T),_.setAttribute("aria-disabled",T?"true":"false");let k=_ instanceof HTMLButtonElement||_ instanceof HTMLSelectElement||_ instanceof HTMLInputElement||_ instanceof HTMLTextAreaElement?_:_.querySelector("button, select, input, textarea");k&&(k.disabled=T)},h=null,y=null,b=null,C=0,A=()=>{let M=e.getOverflow?.();return M?.enabled===!0?M:void 0},L=()=>(h?h.setLabel(e.getOverflowLabel?.()??"More actions"):h=aw({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),I=M=>{y!==M&&(b?.disconnect(),y=M,C=Nf(M),!(typeof ResizeObserver>"u")&&(b=new ResizeObserver(T=>{let k=T[T.length-1]?.contentRect?.width??Nf(M);k!==C&&(C=k,j())}),b.observe(M)))},H=(M,T)=>{let _=hL(M.collapseAutoActionsBelow,T);if(_===null)return!1;let k=C||Nf(T);return k>0&&k<_},B=(M,T,_)=>{if(!T)return"bar";if(M.resolved.builtIn){let Q=mL(M.resolved.id);return Q&&T.includeBuiltIns?.includes(Q)?"menu":"bar"}let k=M.resolved.presentation;return k==="overflow"||k==="auto"&&_?"menu":"bar"},V=M=>{let T=M.menuSlot;if(!T)return;if(!xL(M.element)){M.menuLabel?.remove(),M.menuLabel=void 0;return}let _=wL(M.element);if(!_){M.menuLabel?.remove(),M.menuLabel=void 0;return}M.menuLabel||(M.menuLabel=x("span","persona-composer-overflow-menu__label")),M.menuLabel.textContent!==_&&(M.menuLabel.textContent=_),M.menuLabel.parentElement!==T&&T.appendChild(M.menuLabel)},te=(M,T)=>{if(M.mode===T)return M;let _=M.resolved.action;if(_&&!ys(_)){d(M),t.delete(M.resolved.id);let k=l(M.resolved,T);return t.set(M.resolved.id,k),k}if(T==="menu"){let k=X("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[jg]:""}});k.appendChild(M.element),Iv(Ff(M.element)),M.menuSlot=k;let Q=U=>{let de=Ff(M.element);if(de.disabled)return;let pe=U.target===de||de.contains(U.target);h?.close(!0),pe||de.click()};k.addEventListener("click",Q,!0),M.detachMenuSlot=()=>k.removeEventListener("click",Q,!0),M.managed=!0,V(M)}else M.detachMenuSlot?.(),M.detachMenuSlot=void 0,M.menuLabel?.remove(),M.menuLabel=void 0,M.menuSlot?.remove(),M.menuSlot=void 0;return M.mode=T,M},W=(M,T)=>{let _=T.map(k=>k.menuSlot??k.element);for(_.forEach((k,Q)=>{let U=M.children[Q];U!==k&&(U?M.insertBefore(k,U):M.appendChild(k))});M.children.length>_.length;)M.lastElementChild?.remove()},j=()=>{if(o)return;let M=e.getBindings();if(!M)return;let T=e.getState(),_=T.phase==="streaming",k=A();k&&I(M.footer);let Q=k?H(k,M.footer):!1,U={start:[],end:[]},de=[];for(let pe of n){let ge=t.get(pe.id);if(!ge)continue;let Pe=pe.action,Ae=Pe?pw(Pe.visible,T,!0)&&CL(Pe.visibility,T):!0;if(ge.visible!==Ae&&(ge.visible=Ae,!Ae&&ge.managed&&(ge.menuSlot??ge.element).remove()),!!Ae){if(ge=te(ge,B(ge,k,Q)),Pe){let Le=pw(Pe.disabled,T,!1)||Pe.disableWhenStreaming===!0&&_;f(ge,Le),!ys(Pe)&&Pe.pressed!==void 0&&ge.button?.setAttribute("aria-pressed",Pe.pressed?"true":"false")}ge.mode==="menu"?(V(ge),de.push(ge)):U[pe.placement].push(ge)}}if(de.length>0){let pe=L();W(pe.panel,de),pe.setItems(de.map(Le=>Le.menuSlot??Le.element)),pe.applyButtonSize();let ge=Number.isFinite(k?.order)?k?.order:Jo.overflow,Pe=U.start.findIndex(Le=>Le.resolved.order>ge),Ae={resolved:{id:fL,placement:"start",presentation:"bar",order:ge,sequence:-1,source:"core"},element:pe.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};U.start.splice(Pe<0?U.start.length:Pe,0,Ae)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));g(M.actionsStart,U.start),g(M.actionsEnd,U.end)};return{resolve:()=>{if(o)return;let M=bL(e.collect()),T=new Set(M.map(_=>_.id));for(let[_,k]of t)T.has(_)||(d(k),t.delete(_));for(let _ of M){let k=t.get(_.id);if(!k){let pe=p(_,"bar");pe&&t.set(_.id,pe);continue}let Q=k.resolved.action,U=_.action;if(!!Q!=!!U||Q&&U&&ys(Q)!==ys(U)||Q&&U&&ys(Q)&&ys(U)&&Q.render!==U.render){d(k),t.delete(_.id);let pe=p(_,k.mode);pe&&t.set(_.id,pe);continue}k.resolved=_,_.builtIn?(k.managed=_.builtIn.managed===!0||k.mode==="menu",_.builtIn.element&&k.mode==="bar"&&(k.element=_.builtIn.element)):U&&!ys(U)?i(k,U):U&&k.element.toggleAttribute(Df,U.disableWhenStreaming===!0)}n=M,j()},sync:j,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,b?.disconnect(),b=null,y=null;for(let M of t.values())d(M);t.clear(),h?.destroy(),h=null,n=[]}}}}Qe();Tt();gs();var EL="core:model",ML=700,gw=16,TL=["--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"],fw=()=>{let e=X("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=X("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function mw(e){let t=e.label??"Model",n=e.presentation??"native",o=null,r=c=>{let p=e.getSelectedModelId();return c.find(d=>d.id===p)??c[0]},s=()=>{let c=X("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),p="",d=()=>{let b=e.getModels(),C=b.map(A=>`${A.id}:${A.label}`).join("|");C!==p&&(p=C,c.replaceChildren(...b.map(A=>{let L=X("option",{attrs:{value:A.id}});return L.textContent=A.label,L}))),c.value=r(b)?.id??""};d(),o=d;let g=()=>{c.value&&e.onSelect(c.value)};c.addEventListener("change",g);let f=b=>b.stopPropagation();c.addEventListener("click",f);let{wrapper:h,chevron:y}=fw();return h.append(c,y),{element:h,destroy:()=>{o===d&&(o=null),c.removeEventListener("change",g),c.removeEventListener("click",f)}}},i=()=>{let c=X("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"}}),p=x("span","persona-composer-model-picker-label"),d=x("span","persona-composer-model-picker-suffix");c.append(p,d);let g=X("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),f=new Map,h="",y=null,b=()=>y?.isOpen===!0,C=(T=!1)=>{b()&&(y?.close(),c.setAttribute("aria-expanded","false"),T&&c.focus())},A=T=>{let _=[...f.values()];if(_.length===0)return;let k=(T%_.length+_.length)%_.length;_[k].focus()},L=T=>{if(b())return;y||(y=op({anchor:c,content:g,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),xd(c,g,TL),y.open(),c.setAttribute("aria-expanded","true");let k=[...f.keys()].indexOf(r(e.getModels())?.id??"");A(T??(k>=0?k:0))},I=T=>{C(!0),e.onSelect(T)},H=T=>{T.preventDefault(),T.stopPropagation();let _=T.currentTarget.getAttribute("data-persona-model-option");_&&I(_)},B=T=>{let _=X("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":T.id}});if(T.icon){let pe=ue(T.icon,gw,"currentColor",1.5);if(pe){let ge=x("span","persona-composer-model-option-icon");ge.appendChild(pe),_.appendChild(ge)}}let k=x("span","persona-composer-model-option-body"),Q=x("span","persona-composer-model-option-label");if(Q.textContent=T.label,k.appendChild(Q),T.description){let pe=x("span","persona-composer-model-option-description");pe.textContent=T.description,k.appendChild(pe)}_.appendChild(k);let U=x("span","persona-composer-model-option-check");U.setAttribute("aria-hidden","true");let de=ue("check",gw,"currentColor",2);return de&&U.appendChild(de),_.appendChild(U),_.addEventListener("click",H),_},V=()=>{let T=e.getModels(),_=T.map(U=>`${U.id}:${U.label}:${U.icon??""}:${U.description??""}`).join("|");if(_!==h){h=_;for(let U of f.values())U.removeEventListener("click",H);f.clear(),g.replaceChildren(...T.map(U=>{let de=B(U);return f.set(U.id,de),de}))}let k=r(T);for(let[U,de]of f)de.setAttribute("aria-selected",String(U===k?.id));p.textContent=k?.label??"";let Q=e.getSuffix?.()??"";d.textContent=Q,c.setAttribute("aria-label",[t,[k?.label,Q].filter(Boolean).join(" ")].filter(Boolean).join(": "))};V(),o=V;let te=T=>{T.preventDefault(),T.stopPropagation(),b()?C(!0):L()},W=T=>{if(T.key==="ArrowDown"){T.preventDefault(),b()?A(0):L(0);return}T.key==="ArrowUp"&&(T.preventDefault(),b()?A(-1):L(-1))},j=T=>{let _=[...f.values()],k=_.indexOf(T.target?.closest?.(".persona-composer-model-option"));switch(T.key){case"ArrowDown":T.preventDefault(),A(k+1);return;case"ArrowUp":T.preventDefault(),A(k-1);return;case"Home":T.preventDefault(),A(0);return;case"End":T.preventDefault(),A(_.length-1);return;case"Escape":T.preventDefault(),T.stopPropagation(),C(!0);return;case"Tab":C(!0);return;default:}};c.addEventListener("click",te),c.addEventListener("keydown",W),g.addEventListener("keydown",j);let{wrapper:Y,chevron:M}=fw();return Y.append(c,M),{element:Y,destroy:()=>{o===V&&(o=null),c.removeEventListener("click",te),c.removeEventListener("keydown",W),g.removeEventListener("keydown",j);for(let T of f.values())T.removeEventListener("click",H);f.clear(),y?.destroy(),y=null,g.remove()}}};return{action:{id:EL,kind:"custom",placement:"end",order:ML,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?i():s()},repaint:()=>o?.()}}Qe();Tt();Qe();var $f="[data-persona-composer-chip-row]";function rp(e){e.style.display=e.childElementCount>0?"flex":"none"}function Uf(e){let t=e.querySelector($f);if(t)return t;let n=X("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===e?e.insertBefore(n,o):e.appendChild(n),n}var kL=":scope > [data-persona-composer-mode]";function hw(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=p=>{let d=X("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let y=x("span","persona-mention-chip-icon"),b=ue(p.iconName,12,"currentColor",1.5);b&&y.appendChild(b),d.appendChild(y)}let g=x("span","persona-mention-chip-label");g.textContent=p.shortLabel??p.label,d.appendChild(g);let f=X("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=ue("x",12,"currentColor",2);return h?f.appendChild(h):f.textContent="\xD7",f.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),e.onRemove(p.id)}),d.appendChild(f),d},i=()=>Array.from(t.querySelectorAll(kL)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let d=()=>{p.remove(),rp(t)},g=t.ownerDocument.defaultView,f=typeof g?.getComputedStyle=="function"?g.getComputedStyle(p).animationName:"";if(!f||f==="none"){d();return}p.addEventListener("animationend",d,{once:!0}),p.addEventListener("animationcancel",d,{once:!0})},c=()=>{for(let p of i())p.remove()};return{element:t,render:(p,d)=>{if(o)return;let g=d.filter(b=>p.includes(b.id)),f=g.map(b=>`${b.id}:${b.shortLabel??b.label}`).join("|");if(f===n)return;n=f;let h=new Map;for(let b of i()){let C=b.getAttribute("data-persona-composer-mode");C&&g.some(L=>L.id===C)&&!b.hasAttribute("data-persona-chip-exit")?h.set(C,b):b.hasAttribute("data-persona-chip-exit")||l(b)}let y=t.firstChild;for(let b of g){let C=h.get(b.id);C||(C=s(b),r.has(b.id)||(C.setAttribute("data-persona-chip-enter",""),C.addEventListener("animationend",()=>C?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(b.id),C!==y&&t.insertBefore(C,y),y=C.nextSibling}rp(t)},destroy:()=>{o=!0,c(),rp(t)}}}Qe();Tt();var yw=e=>`core:mode:${e}`;var Vf=e=>Math.min(300+e,499),bw=e=>`core:mode-group:${e}`;function sp(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function PL(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function vw(e,t){return e?.length?e.filter(n=>!sp(n.groupId,t)&&!PL(n.groupId,t)):[]}var LL=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function Cw(e,t,n,o){let r=n.find(l=>l.id===t);if(!r)return[...e];let s=e.includes(t),i=new Set(e);if(s)i.delete(t);else{if(LL(r,o)==="single"){let l=n.filter(c=>c.groupId===r.groupId).map(c=>c.id);i=new Set([...i].filter(c=>!l.includes(c)))}i.add(t)}return n.filter(l=>i.has(l.id)).map(l=>l.id)}function ip(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function ww(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Sw(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var HL=16;function Aw(e){let t=null;return{action:{id:bw(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=X("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,s="",i=p=>{p.preventDefault(),p.stopPropagation();let g=p.currentTarget.getAttribute("data-persona-composer-mode");!g||e.getActiveIds().includes(g)&&e.getGroup()?.selection==="single"||e.onSelect(g)},l=p=>{let d=X("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let f=ue(p.iconName,HL,"currentColor",1.5);f&&d.appendChild(f)}let g=x("span","persona-composer-segmented-label");return g.textContent=p.shortLabel??p.label,d.appendChild(g),d.addEventListener("click",i),d},c=()=>{let p=e.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let d=e.getModes(),g=d.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(g!==s){s=g;for(let y of r.values())y.removeEventListener("click",i);r.clear();let h=d.map(y=>{let b=l(y);return r.set(y.id,b),b});o.replaceChildren(...h)}let f=e.getActiveIds();for(let[h,y]of r)y.setAttribute("aria-pressed",String(f.includes(h)))};return c(),t=c,{element:o,destroy:()=>{t===c&&(t=null);for(let p of r.values())p.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}Qe();Tt();function xw(e){let t=X("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let n="",o=!1,r=s=>{let i=x("span","persona-composer-quote-bar"),l=x("div","persona-composer-quote-content");if(s.sourceLabel){let g=x("div","persona-composer-quote-source");g.textContent=s.sourceLabel,l.appendChild(g)}let c=X("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=Zd(s.text),l.appendChild(c);let p=X("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),d=ue("x",12,"currentColor",2);d?p.appendChild(d):p.textContent="\xD7",p.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,l,p)};return{element:t,render:s=>{if(o)return;let i=s?`${s.sourceLabel??""}\0${s.text}`:"";if(i!==n){if(n=i,!s){t.replaceChildren(),t.style.display="none";return}r(s),t.style.display="flex"}},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}Qe();Tt();function Ew(e){let t=X("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let n,o=!1,r=(i,l,c,p)=>{let d=X("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),g=ue(i,12,"currentColor",2);return g?d.appendChild(g):d.textContent=l,d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),p()}),d},s=i=>{let l=Zd(i.text??"",90);if(l)return l;let c=i.contentParts?.length??0;return c>0?c===1?"1 attachment":`${c} attachments`:(i.mentionRefs?.length??0)>0?i.mentionRefs.map(d=>d.label).join(", "):"Queued message"};return{element:t,render:i=>{if(o||i===n)return;if(n=i,!i){t.replaceChildren(),t.style.display="none";return}let l=x("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let c=X("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});c.textContent=s(i),t.replaceChildren(l,c,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}Qe();function Mw(e){let t=X("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=X("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 o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=x("div","persona-message-edit-actions"),s=(l,c,p,d)=>{let g=X("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[p]:""},text:l});return g.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),d()}),g},i=()=>{let l=n.value.trim();l&&e.onSave(l)};return r.append(s(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),s(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",i)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),e.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),i())}),t.append(n,r),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let l=n.value.length;n.setSelectionRange(l,l),o()},destroy:()=>{t.replaceChildren(),t.remove()}}}function Tw(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 kw(e,t){if(!e||typeof e.text!="string")return;let n=new Set(t.mentionSourceIds),o=(e.mentionRefs??[]).filter(c=>n.has(c.sourceId)),r=o.length===(e.mentionRefs?.length??0)&&o.length>0,s=new Set(t.modes.map(c=>c.id)),i=(e.activeModeIds??[]).filter(c=>s.has(c)),l=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...r?{mentionRefs:o}:{},...r&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...l?{selectedModelId:l}:{},...i.length?{activeModeIds:i}:{},...e.quote?.text?{quote:e.quote}:{}}}function Pw(e){let t=e.delay??500,n=null,o=!1,r=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(r(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{o||n===null||(r(),e.write())},cancel:r,destroy:()=>{o=!0,r()}}}function Lw(e){return e.wrapped||e.text.includes(`
29
+ `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function Hw(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function Iw(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),o=Number.parseFloat(n.lineHeight),r=Number.parseFloat(n.fontSize),s=Number.isFinite(o)&&o>0?o:Number.isFinite(r)&&r>0?r*1.4:0;if(!s)return!1;let i=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-i>s*1.5}function Rw(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}Ad();function jf(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 Ow(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var IL=e=>typeof e?.then=="function";function Ww(e,t){return t===!1?{status:"canceled"}:!t||typeof t!="object"?{status:"proceed"}:(typeof t.text=="string"&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options}),{status:"proceed"})}function _w(e,t,n){let o;try{o=e(jf(t),{signal:n})}catch(r){return{status:"error",error:r}}return IL(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:Ww(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):Ww(t,o)}pf();uf();df();Hr();var ap=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?"circle":"pill"),lp={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"};vo();vo();var dp="16px",pp="transparent",RL=(()=>{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})(),Ll={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:RL,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"}},cp={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"}},to={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:aa,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:dp,canvasBackground:pp,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"}}},WL=Ll.colors.gray,OL={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},Dw={...Ll,colors:{...Ll.colors,gray:WL}},_L={...Ll,colors:{...Ll.colors,gray:OL},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}},BL=Dw,Nw=cp,DL={...cp,colors:{...cp.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...cp.typography,fontSize:"14px",lineHeight:"1.5"}},NL=Nw,up=to,FL={...to,launcher:lp,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:{...to.input,borderRadius:"palette.radius.full"},introCard:{...to.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...to.suggestion.chip,fontWeight:"400"},card:{...to.suggestion.card,fontWeight:"400"},list:{...to.suggestion.list,fontWeight:"400"}},panel:{...to.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...to.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:{...to.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...to.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:{...to.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...to.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)"}},$L=up,UL=e=>us({future:e}),zf=e=>UL(e)==="v5"?{palette:_L,semantic:DL,components:FL}:{palette:Dw,semantic:Nw,components:up};function vn(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?vn(e,o):o}function Kf(e){let t={};function n(o,r){for(let[s,i]of Object.entries(o)){let l=`${r}.${s}`;if(typeof i=="string"){let c=vn(e,i);c!==void 0&&(t[l]={path:l,value:c,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof i=="object"&&i!==null&&n(i,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Fw(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 $w(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=$w(s,r):n[o]=r}return n}function VL(e,t){return t?$w(e,t):e}function gp(e,t={}){let n=zf(t.future),o={palette:n.palette,semantic:n.semantic,components:n.components},r={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:VL(o.components,e?.components)},s=e?.components?.activity;for(let p of["toolBubble","reasoningBubble"])for(let d of["rowHeight","labelSize","iconSize","indent","bodySurface"])s?.[d]!==void 0&&(r.components[p][d]=s[d]);let i=e?.components?.collapsibleWidget?.surface;i!==void 0&&s?.bodySurface===void 0&&(r.components.activity={...r.components.activity,bodySurface:i});let l=e?.components?.header;l?.padding!==void 0&&l.minimalPadding===void 0&&(r.components.header.minimalPadding=r.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(r.components.message.fullscreenGap=r.components.message.gap),t.validate!==!1){let p=Fw(r);if(!p.valid)throw new Error(`Theme validation failed: ${p.errors.map(d=>d.message).join(", ")}`)}if(t.plugins)for(let p of t.plugins)r=p.transform(r);return r}var qf=e=>e.trim()==="0"?"0px":e,Bw="--persona-",jL=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let i=t.slice(1);if(!/^[0-9a-f]+$/.test(i))return;i.length===3||i.length===4?n=[0,1,2].map(l=>parseInt(i[l]+i[l],16)):(i.length===6||i.length===8)&&(n=[0,2,4].map(l=>parseInt(i.slice(l,l+2),16)))}else{let i=t.match(/^rgba?\(([^)]+)\)$/);if(i){let l=i[1].split(/[,/\s]+/).filter(Boolean);l.length>=3&&(n=l.slice(0,3).map(c=>{let p=c.endsWith("%"),d=parseFloat(p?c.slice(0,-1):c);return p?d/100*255:d}))}}if(!n||n.some(i=>!Number.isFinite(i)))return;let[o,r,s]=n.map(i=>{let l=Math.max(0,Math.min(255,i))/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*s},qL=.179,bn=(e,t)=>{for(let[n,...o]of t){let r;for(let s of o)if(r=s.charCodeAt(0)===61?s.slice(1):e[Bw+s],r!==void 0)break;r!==void 0&&(e[Bw+n]=r)}};function Gf(e){let t=Kf(e),n={};for(let[$,We]of Object.entries(t)){let me=$.replace(/\./g,"-");n[`--persona-${me}`]=We.value}bn(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 o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],bn(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"]]),bn(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"]}`,bn(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"]??dp,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??pp,bn(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"]]),bn(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],i=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??n["--persona-divider"],bn(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"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??i??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??i??n["--persona-muted"],bn(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=e.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let c=n["--persona-components-history-railHeader-background"];c&&(n["--persona-history-rail-header-bg"]=c);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let d=n["--persona-components-history-railHeader-minHeight"];d&&(n["--persona-history-rail-header-min-height"]=d);for(let[$,We]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let me=n[`--persona-components-history-overlay-${$}`];me&&(n[`--persona-history-overlay-${We}`]=me)}for(let[$,We]of[["background","bg"],["borderRadius","radius"]]){let me=n[`--persona-components-history-menu-${$}`];me&&(n[`--persona-history-menu-${We}`]=me)}let g=e.components?.history?.motion;if(g){let $=dt=>{if(dt===void 0)return;let Qt=String(dt).trim();return/^\d+(\.\d+)?$/.test(Qt)?`${Qt}ms`:Qt},We=$(g.enterDurationMs);We!==void 0&&(n["--persona-history-enter-ms"]=We);let me=$(g.exitDurationMs);me!==void 0&&(n["--persona-history-exit-ms"]=me),g.enterEasing&&(n["--persona-history-enter-easing"]=g.enterEasing),g.exitEasing&&(n["--persona-history-exit-easing"]=g.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 $ of["scrim","shadow"]){let We=n[`--persona-components-history-confirm-${$}`];We&&(n[`--persona-history-confirm-${$}`]=We)}for(let[$,We]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let me=n[`--persona-components-tooltip-${$}`];me&&(n[`--persona-tooltip-${We}`]=me)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[$,We]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let me=n[`--persona-components-messageActions-${$}`];me&&(n[`--persona-message-action-${We}`]=me)}bn(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],y=n["--persona-components-introCard-shadow"],b=(!h||h==="transparent"||h==="none")&&(!y||y==="none"),C=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=b&&C==="1.5rem"?"1.5rem 0":C,bn(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"]]),bn(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 A=n["--persona-components-markdown-heading-h1-fontSize"];A&&(n["--persona-md-h1-size"]=A);let L=n["--persona-components-markdown-heading-h1-fontWeight"];L&&(n["--persona-md-h1-weight"]=L);let I=n["--persona-components-markdown-heading-h2-fontSize"];I&&(n["--persona-md-h2-size"]=I);let H=n["--persona-components-markdown-heading-h2-fontWeight"];H&&(n["--persona-md-h2-weight"]=H);let B=n["--persona-components-markdown-prose-fontFamily"];B&&B!=="inherit"&&(n["--persona-md-prose-font-family"]=B),bn(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"]]),bn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),bn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),bn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),bn(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"]]);let V=[["container","surface"],["surface","surface"],["border","border"]];for(let[$,We]of V){let me=n[`--persona-components-collapsibleWidget-${$}`]??n[`--persona-${We}`];me!==void 0&&(n[`--persona-cw-${$}`]=me,n[`--cw-${$}`]=me)}bn(n,[["message-border","components-message-border","border"]]),bn(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 te=e.components,W=te?.iconButton;W&&(W.background&&(n["--persona-icon-btn-bg"]=W.background),W.border&&(n["--persona-icon-btn-border"]=W.border),W.color&&(n["--persona-icon-btn-color"]=W.color),W.padding&&(n["--persona-icon-btn-padding"]=W.padding),W.borderRadius&&(n["--persona-icon-btn-radius"]=W.borderRadius),W.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=W.hoverBackground),W.hoverColor&&(n["--persona-icon-btn-hover-color"]=W.hoverColor),W.activeBackground&&(n["--persona-icon-btn-active-bg"]=W.activeBackground),W.activeBorder&&(n["--persona-icon-btn-active-border"]=W.activeBorder));let j=te?.labelButton;j&&(j.background&&(n["--persona-label-btn-bg"]=j.background),j.border&&(n["--persona-label-btn-border"]=j.border),j.color&&(n["--persona-label-btn-color"]=j.color),j.padding&&(n["--persona-label-btn-padding"]=j.padding),j.borderRadius&&(n["--persona-label-btn-radius"]=j.borderRadius),j.hoverBackground&&(n["--persona-label-btn-hover-bg"]=j.hoverBackground),j.fontSize&&(n["--persona-label-btn-font-size"]=j.fontSize),j.gap&&(n["--persona-label-btn-gap"]=j.gap));let Y=te?.toggleGroup;Y&&(Y.gap&&(n["--persona-toggle-group-gap"]=Y.gap),Y.borderRadius&&(n["--persona-toggle-group-radius"]=Y.borderRadius));let M=te?.artifact;if(M?.toolbar){let $=M.toolbar;$.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=$.iconHoverColor),$.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=$.iconHoverBackground),$.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=$.iconPadding),$.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=$.iconBorderRadius),$.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=$.iconBorder),$.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=qf($.toggleGroupGap)),$.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=$.toggleBorderRadius),$.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=qf($.toggleGroupPadding)),$.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=$.toggleGroupBorder),$.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=$.toggleGroupBorderRadius),$.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=vn(e,$.toggleGroupBackground)??$.toggleGroupBackground),$.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=$.copyBackground),$.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=$.copyBorder),$.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=$.copyColor),$.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=qf($.copyBorderRadius)),$.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=$.copyPadding),$.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=$.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??$.copyMenuBackground),$.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=$.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??$.copyMenuBorder),$.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=$.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??$.copyMenuShadow),$.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=$.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??$.copyMenuBorderRadius),$.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=$.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??$.copyMenuItemHoverBackground),$.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=$.iconBackground),$.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=$.toolbarBorder)}if(M?.tab){let $=M.tab;$.background&&(n["--persona-artifact-tab-bg"]=$.background),$.activeBackground&&(n["--persona-artifact-tab-active-bg"]=$.activeBackground),$.activeBorder&&(n["--persona-artifact-tab-active-border"]=$.activeBorder),$.borderRadius&&(n["--persona-artifact-tab-radius"]=$.borderRadius),$.textColor&&(n["--persona-artifact-tab-color"]=$.textColor),$.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=$.hoverBackground),$.listBackground&&(n["--persona-artifact-tab-list-bg"]=$.listBackground),$.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=$.listBorderColor),$.listPadding&&(n["--persona-artifact-tab-list-padding"]=$.listPadding)}if(M?.pane){let $=M.pane;if($.toolbarBackground){let We=vn(e,$.toolbarBackground)??$.toolbarBackground;n["--persona-artifact-toolbar-bg"]=We}}if(M?.card){let $=M.card;$.background&&(n["--persona-artifact-card-bg"]=$.background),$.border&&(n["--persona-artifact-card-border"]=$.border),$.borderRadius&&(n["--persona-artifact-card-radius"]=$.borderRadius),$.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=$.hoverBackground),$.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=$.hoverBorderColor)}if(M?.inline){let $=M.inline;$.background&&(n["--persona-artifact-inline-bg"]=vn(e,$.background)??$.background),$.border&&(n["--persona-artifact-inline-border"]=$.border),$.borderRadius&&(n["--persona-artifact-inline-radius"]=$.borderRadius),$.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=vn(e,$.chromeBackground)??$.chromeBackground),$.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=vn(e,$.chromeBorder)??$.chromeBorder),$.titleColor&&(n["--persona-artifact-inline-title-color"]=vn(e,$.titleColor)??$.titleColor),$.mutedColor&&(n["--persona-artifact-inline-muted-color"]=vn(e,$.mutedColor)??$.mutedColor),$.frameHeight&&(n["--persona-artifact-inline-frame-height"]=$.frameHeight)}let T=te?.code;T&&(T.keywordColor&&(n["--persona-code-keyword-color"]=T.keywordColor),T.stringColor&&(n["--persona-code-string-color"]=T.stringColor),T.commentColor&&(n["--persona-code-comment-color"]=T.commentColor),T.numberColor&&(n["--persona-code-number-color"]=T.numberColor),T.tagColor&&(n["--persona-code-tag-color"]=T.tagColor),T.attrColor&&(n["--persona-code-attr-color"]=T.attrColor),T.propertyColor&&(n["--persona-code-property-color"]=T.propertyColor),T.lineNumberColor&&(n["--persona-code-line-number-color"]=T.lineNumberColor),T.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=T.gutterBorderColor),T.background&&(n["--persona-code-bg"]=vn(e,T.background)??T.background));let _=n["--persona-surface"],k=n["--persona-container"],Q=n["--persona-palette-colors-gray-100"]??"#f3f4f6",U=n["--persona-palette-colors-gray-200"]??"#e5e7eb",de=n["--persona-palette-colors-gray-300"]??"#d1d5db",pe=!k||k===_,ge=jL(_??n["--persona-background"]),Pe=pe&&ge!==void 0&&ge<qL,Ae=Pe?"rgba(255, 255, 255, 0.08)":Q,Le=Pe?"rgba(255, 255, 255, 0.12)":U,mt=Pe?"rgba(255, 255, 255, 0.16)":de,Ve=pe?Ae:k,Re=pe?Le:k;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??Ve,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Re,pe&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??mt),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??Ve,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??Ve,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??Ve,n}var zL={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"};hd();var KL=e=>!!e&&"launcher"in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode==="docked"),Uw=(e,t)=>{if(!t||!KL(t))return e;let n=t.theme?.components?.panel?.width,o=t.darkTheme?.components?.panel?.width;return(ma(t)==="dark"?o??n:n)!=null?e:{...e,components:{...e.components,panel:{...e.components.panel,width:us(t)==="v5"?"400px":"420px"}}}},GL={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"}}},Hl={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)"}}}},Yf=GL,YL={...Yf,colors:{...Yf.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"}}},XL=Hl,QL={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:{...Hl.components,button:{...Hl.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:{...Hl.components?.eventStream,badge:{...Hl.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"}}}}},JL=e=>us({future:e})==="v5"?{palette:YL,components:QL}:{palette:Yf,components:XL},Vw=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},fp=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",ZL=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":fp()},ma=e=>ZL(e),eH=(e,t={})=>gp(e,t),tH=(e,t={})=>{let n=JL(t.future),o=Ho(n.components,e??{})??{};return gp({...o,palette:{...o.palette,colors:us(t)==="v5"?Ho(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})},Zo=e=>{let t=ma(e),n=Vw(e?.theme),o=ap(e)==="circle"?lp:{...up.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=Ho({components:{launcher:o}},n),s=Vw(e?.darkTheme);return Uw(t==="dark"?tH(Ho(r??{},s??{}),{future:e?.future}):eH(r,{future:e?.future}),e)},nH=e=>Gf(e),ha=(e,t)=>{let n=Zo(t),o=nH(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",ma(t)),e.setAttribute("data-persona-defaults",us(t))},Il=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(fp())});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)"),o=()=>e(fp());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};hd();Tt();Er();Qe();import{Activity as yA,Check as bA,Copy as vA}from"lucide";var bs=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var mp="24px",Xf=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",Rl=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},jw=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);sa();gd();Fd();import{Idiomorph as oH}from"idiomorph";var hp=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;oH.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let i=r.textContent??"",l=s.textContent??"";if(i!==l)return}return!1}}}}})};var qw=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Qf={index:-1,draft:""};function zw(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,i=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!i&&!r)return{handled:!1,state:s};if(!i){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!i)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function Kw(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 Gw(){return new Map}function Yw(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Xw(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Qw(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Jw(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function Zw(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function er(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function di(e,t){return er(e)-e.scrollTop<=t}function eS(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:i=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:p=!1}=e,d=n-o;return i||Math.abs(d)<s?{action:"none",delta:d,nextLastScrollTop:n}:!t&&r&&(!p||d>0)?{action:"resume",delta:d,nextLastScrollTop:n}:t&&l&&d<0?{action:"pause",delta:d,nextLastScrollTop:n}:t&&c&&!r?{action:"pause",delta:d,nextLastScrollTop:n}:{action:"none",delta:d,nextLastScrollTop:n}}function tS(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function nS(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Jf(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:n}}function oS(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}Lo();var Wl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},rH=["pre","code","a","script","style"],yp=e=>({type:e?.type??Wl.type,placeholder:e?.placeholder??Wl.placeholder,speed:e?.speed??Wl.speed,duration:e?.duration??Wl.duration,buffer:e?.buffer??Wl.buffer}),sS=[{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"}],Ol=new Map;for(let e of sS)Ol.set(e.name,e);var iS=["wipe","glyph-cycle"],bp=e=>{Ol.set(e.name,e)},sH=e=>{sS.some(t=>t.name===e)||Ol.delete(e)},iH=()=>Array.from(Ol.keys()),_l=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Ol.get(e)??null,vp=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
30
+ `);return s<0?"":e.slice(0,s)}return e},aH=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},lH=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},Zf=/\s/,cH=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},dH=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=0;for(;l<s.length;)if(Zf.test(s[l])){let c=l;for(;c<s.length&&Zf.test(s[c]);)c+=1;i.appendChild(o.createTextNode(s.slice(l,c))),l=c}else{let c=o.createElement("span");c.className="persona-stream-word-group";let p=l;for(;p<s.length&&!Zf.test(s[p]);)c.appendChild(aH(o,s[p],t,n.value)),n.value+=1,p+=1;i.appendChild(c),l=p}r.replaceChild(i,e)},pH=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let c of l)c&&(/^\s+$/.test(c)?i.appendChild(o.createTextNode(c)):(i.appendChild(lH(o,c,t,n.value)),n.value+=1));r.replaceChild(i,e)},Bl=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??rH).map(g=>g.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],c=i.nextNode();for(;c;)cH(c,s)||l.push(c),c=i.nextNode();let p={value:o?.startIndex??0},d=t==="char"?dH:pH;for(let g of l)d(g,n,p);return r.innerHTML},Cp=(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},Dl=(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},rS=new WeakMap,uH=(e,t)=>{if(!e.styles)return;let n=rS.get(t);if(n||(n=new Set,rS.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))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)},em=new WeakMap,gH=(e,t)=>{if(!e.onAttach)return;let n=em.get(t);if(n||(n=new Map,em.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},aS=e=>{let t=em.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Nl=(e,t)=>{uH(e,t),gH(e,t)};ln();var{setLoader:b1,load:fH}=it({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var lS=fH;Lo();function tm(e,t=Tn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),i=s.position==="static"||s.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var Fl=0,vs=null;function nm(e=document){if(Fl++,Fl===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;vs={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Fl=Math.max(0,Fl-1),Fl===0&&vs)){let n=e.body,o=e.defaultView??window;n.style.overflow=vs.originalOverflow,n.style.position=vs.originalPosition,n.style.top=vs.originalTop,n.style.width=vs.originalWidth,o.scrollTo(0,vs.scrollY),vs=null}}}ia();var $l={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ht=e=>(e?.launcher?.mountMode??"floating")==="docked",Cs=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",no=e=>{let t=e?.launcher?.dock,n=kr(e).dockWidth?t?.width:vn(Zo(e),"components.panel.width");return{side:t?.side??$l.side,width:n??$l.width,animate:t?.animate??$l.animate,reveal:t?.reveal??$l.reveal,maxHeight:t?.maxHeight??$l.maxHeight}};Qe();Qe();Tt();Er();import{ArrowRight as mH}from"lucide";var om=e=>e==="followUp"?"follow-up":e,rm=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},cS=new WeakSet,hH=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,yH=e=>{hH()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},sm=e=>{let{item:t,index:n,surface:o,source:r,variant:s,streaming:i,config:l,plugins:c,chipsConfig:p,session:d,getTextarea:g,eventTarget:f,submitPrompt:h}=e,y=o==="followUp",b=t.behavior,C=()=>{if(d.isStreaming())return;let I={suggestion:{...t},surface:o,source:r,behavior:b},H=f.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:I,bubbles:!0,composed:!0,cancelable:!0}));if(y&&f.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!H)return;for(let V of c)if(V.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let B=g();if(b==="fill"){B.value=t.prompt,B.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),B.focus();return}if(h){h(t.prompt);return}B.value="",d.sendMessage(t.prompt)},A=()=>{let I=x("button",`persona-suggestion persona-suggestion--${s}`);if(I.type="button",I.disabled=i,I.dataset.suggestionId=t.id,I.dataset.emphasis=t.emphasis,I.dataset.behavior=b,s==="chip"&&(p?.fontWeight&&(I.style.fontWeight=p.fontWeight),p?.paddingX&&(I.style.paddingLeft=p.paddingX,I.style.paddingRight=p.paddingX),p?.paddingY&&(I.style.paddingTop=p.paddingY,I.style.paddingBottom=p.paddingY)),t.icon){let B=ue(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);B&&(B.classList.add("persona-suggestion__icon"),t.iconColor&&(B.style.color=t.iconColor),I.appendChild(B))}let H=x("span","persona-suggestion__copy");if(H.appendChild(X("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&H.appendChild(X("span",{className:"persona-suggestion__description",text:t.description})),I.appendChild(H),s!=="chip"){let B=Bt(mH,16,"currentColor",1.8);B&&(B.classList.add("persona-suggestion__arrow"),I.appendChild(B))}return I.addEventListener("click",C),I},L=null;for(let I of c)if(I.renderSuggestion&&(L=I.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:i,config:l,defaultRenderer:A,select:C}),L))break;return L??=A(),L.dataset.suggestionId||=t.id,L.dataset.behavior||=b,L.dataset.emphasis||=t.emphasis,L instanceof HTMLButtonElement||L.setAttribute("aria-disabled",i?"true":"false"),L},Ul=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let d=Math.max(0,e.scrollWidth-e.clientWidth);if(d<=1){s();return}let g=getComputedStyle(e).direction==="rtl",f=Math.min(d,Math.max(0,Math.abs(e.scrollLeft))),h=4,y=f<=h,b=f>=d-h,C=g?!b:!y,A=g?!y:!b;e.toggleAttribute("data-scroll-left",C),e.toggleAttribute("data-scroll-right",A)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",l,{passive:!0});let c=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),c?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(d,g,f,h,y,b)=>{e.replaceChildren(),t.length=0,n.length=0;let C=b?.source??"config",A=b?.surface??(C==="config"?"starter":"followUp"),L=A==="followUp",I=b?.variant??"chip",H=b?.behavior??"send",B=b?.overflow??"wrap",V=b?.config??{},te=b?.plugins??[],W=typeof b?.maxItems=="number"?Math.max(0,Math.floor(b.maxItems)):void 0,j=L?"followUps":"starters";!cS.has(V)&&V.debug===!0&&I!=="chip"&&V.suggestions?.[j]?.overflow!==void 0&&(cS.add(V),console.info(`[persona] suggestions.${j}.overflow applies to the "chip" variant only; the "${I}" variant manages its own stacking.`));let Y=U=>U.map(rm).filter(de=>de!==null).map(de=>({...de,behavior:de.behavior??H})),M=Y(d??[]);te.forEach(U=>{U.transformSuggestions&&(M=Y(U.transformSuggestions({suggestions:M.map(de=>({...de})),surface:A,source:C,config:V})))});let T=W===void 0?M:M.slice(0,W);if(!T.length){e.hidden=!0,o=null,s();return}if(!L&&(h??g.getMessages()).some(de=>de.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=om(A),e.dataset.variant=I,e.dataset.overflow=B;let _=document.createDocumentFragment(),k=g.isStreaming();T.forEach((U,de)=>{let pe=sm({item:U,index:de,surface:A,source:C,variant:I,streaming:k,config:V,plugins:te,chipsConfig:y,session:g,getTextarea:()=>f,eventTarget:e,submitPrompt:b?.submitPrompt});_.appendChild(pe),n.push(pe),[...pe instanceof HTMLButtonElement?[pe]:[],...Array.from(pe.querySelectorAll("button"))].forEach(Pe=>{t.includes(Pe)||(Pe.disabled=k,t.push(Pe))})}),e.appendChild(_),i(),l();let Q=JSON.stringify({normalized:T,surface:A,variant:I,source:C});Q!==o&&(o=Q,yH(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:T.map(U=>({...U})),surface:A,source:C,variant:I},bubbles:!0,composed:!0})),L&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:T.map(U=>U.prompt)},bubbles:!0,composed:!0})))}}};var oo={"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"};Lo();Qe();Tt();vo();Qe();Tt();sa();var bH="persona-header-control",vH="persona-header-control--glyph",CH="persona-header-control--sparse",wH=20,SH={x:[1.4,1.05]},dS="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",AH="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",wp=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,i]=SH[t]??[1,1.5],l=!o;e.classList.toggle(vH,l),e.classList.toggle(CH,l&&s!==1);let c=parseFloat(o??"")||wH,p=ue(t,`${Math.round(c*s)}px`,"currentColor",i);p?(p.style.display="block",l||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(p)):r&&(e.textContent=r)},ya=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:i=dS,size:l,iconSize:c,color:p,backgroundColor:d,borderWidth:g,borderColor:f,borderRadius:h,paddingX:y,paddingY:b,hidden:C,extraClassName:A,attrs:L}=e,I=x("div",i),H=!!(g||f),B=X("button",{className:On(bH,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"persona-bg-transparent hover:persona-bg-gray-100",!H&&"persona-border-none",!h&&"persona-rounded-full",A),attrs:{type:"button","aria-label":t,...L},style:{width:l,height:l,minWidth:l,minHeight:l,display:C?"none":void 0,color:p||_n.actionIconColor,backgroundColor:d,border:H?`${g||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:h,paddingLeft:y,paddingRight:y,paddingTop:b,paddingBottom:b}});return r?wp(B,r,{iconSize:c,iconText:s}):s&&(B.textContent=s),I.appendChild(B),yn({anchor:B,trigger:I,text:()=>B.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:B,wrapper:I}},ba=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=dS,buttonSize:r,iconSize:s}=t,i=e?.launcher??{},l=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:p,wrapper:d}=ya({ariaLabel:l,tooltip:c,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??i.closeButtonSize,iconSize:s,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:d}},va=(e,t={})=>{let{wrapperClassName:n=AH,buttonSize:o,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},l=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:p,wrapper:d}=ya({ariaLabel:l,tooltip:c,iconName:i.iconName??"refresh-cw",wrapperClassName:n,size:o??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:p,wrapper:d}};var _n={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)"},im={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)"},xH={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)"},ws=e=>{let{config:t,showClose:n=!0}=e,o=X("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:_n.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)))"}}),r=t?.launcher??{},s=r.headerIconSize??hl,i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,c=r.headerIconName,p=X("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(c){let B=parseFloat(s)||24,V=ue(c,B*.6,"currentColor",1);V?(V.style.width=`calc(${B}px * var(--persona-components-header-iconScale, 0.6))`,V.style.height=`calc(${B}px * var(--persona-components-header-iconScale, 0.6))`,p.replaceChildren(V)):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let B=x("img");B.src=t.launcher.iconUrl,B.alt="",B.className="persona-rounded-xl persona-object-cover",B.style.height=s,B.style.width=s,p.replaceChildren(B)}else p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let d=x("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=X("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:_n.titleColor,...im}}),f=X("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:_n.subtitleColor,...xH}});d.append(g,f),l?o.append(d):o.append(p,d);let h=r.clearChat??{},y=h.enabled??!0,b=h.placement??"inline",C=null,A=null;if(y){let V=va(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});C=V.button,A=V.wrapper,b==="top-right"&&(A.style.right="48px"),b==="inline"&&o.appendChild(A)}let L=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&b==="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",{button:I,wrapper:H}=ba(t,{showClose:n,wrapperClassName:L});return i!=="top-right"&&o.appendChild(H),{header:o,iconHolder:p,headerTitle:g,headerSubtitle:f,closeButton:I,closeButtonWrapper:H,clearChatButton:C,clearChatButtonWrapper:A}},Ca=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};Qe();Qe();Tt();Lo();function wa(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:i}=e,l=x("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(na)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let y of t){if(y.dividerBefore){let A=document.createElement("hr");l.appendChild(A)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",y.id),y.destructive&&b.setAttribute("data-destructive",""),y.icon){let A=ue(y.icon,16,"currentColor",1.5);A&&b.appendChild(A)}let C=document.createElement("span");C.textContent=y.label,b.appendChild(C),b.addEventListener("click",A=>{A.stopPropagation(),g(),n(y.id)}),l.appendChild(b)}let c=null;function p(){if(!s)return;let y=o.getBoundingClientRect();l.style.top=`${y.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-y.right}px`,l.style.left="auto"):(l.style.left=`${y.left}px`,l.style.right="auto")}function d(){let y=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),y&&i?.(!0),requestAnimationFrame(()=>{let b=C=>{!l.contains(C.target)&&!o.contains(C.target)&&g()};document.addEventListener("click",b,!0),c=()=>document.removeEventListener("click",b,!0)})}function g(){let y=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),c?.(),c=null,y&&i?.(!1)}function f(){l.classList.contains("persona-hidden")?d():g()}function h(){g(),l.remove()}return s&&s.appendChild(l),{element:l,show:d,hide:g,toggle:f,destroy:h}}Qe();Tt();function ro(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:i,onClick:l,aria:c}=e,p=x("button",On(!i&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ue(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),l&&p.addEventListener("click",l),c)for(let[g,f]of Object.entries(c))p.setAttribute(g,f);return p}function pS(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:i,onClick:l,aria:c}=e,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,i&&(p+=" "+i);let d=x("button",p);if(d.type="button",d.setAttribute("aria-label",n),t){let f=ue(t,s??14,"currentColor",2);f&&d.appendChild(f)}let g=x("span");if(g.textContent=n,d.appendChild(g),l&&d.addEventListener("click",l),c)for(let[f,h]of Object.entries(c))d.setAttribute(f,h);return d}function Sp(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=x("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let i=n,l=[];function c(){for(let d of l)d.btn.setAttribute("aria-pressed",d.id===i?"true":"false")}for(let d of t){let g;d.icon?g=ro({icon:d.icon,label:d.label,className:d.className,onClick:()=>{i=d.id,c(),o(d.id)}}):(g=x("button","persona-icon-btn"+(d.className?" "+d.className:"")),g.type="button",g.setAttribute("aria-label",d.label),g.title=d.label,g.textContent=d.label,g.addEventListener("click",()=>{i=d.id,c(),o(d.id)})),g.setAttribute("aria-pressed",d.id===i?"true":"false"),l.push({id:d.id,btn:g}),s.appendChild(g)}function p(d){i=d,c()}return{element:s,setSelected:p}}function EH(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:i,onPrimary:l,position:c="bottom-left",portal:p,chevronLabel:d="More options",chevronIconSize:g,className:f,primaryClassName:h,chevronClassName:y}=e,b=x("div","persona-split-btn"+(f?" "+f:"")),C={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:l},A=r&&n?ro({...C,icon:n,size:o??14}):pS({...C,icon:n,iconSize:o??14}),L=ro({icon:"chevron-down",label:d,size:g??14,className:"persona-split-btn-chevron"+(y?" "+y:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});b.append(A,L);let I=null,H=()=>{if(I)return I;let B=(typeof p=="function"?p():p)??void 0;return I=wa({items:s,onSelect:i,anchor:b,position:c,portal:B,onOpenChange:V=>{L.setAttribute("aria-expanded",V?"true":"false")}}),B||b.appendChild(I.element),I};return b.isConnected?H():requestAnimationFrame(()=>{I||H()}),L.addEventListener("click",B=>{B.stopPropagation(),H().toggle()}),{element:b,primaryButton:A,chevronButton:L,openMenu:()=>H().show(),closeMenu:()=>I?.hide(),toggleMenu:()=>H().toggle(),destroy:()=>{I?.destroy(),b.remove()}}}function am(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:c}=e,p=x("div","persona-combo-btn"+(l?" "+l:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",t);let d=x("span","persona-combo-btn-label");d.textContent=t,p.appendChild(d);let g=ue(n,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",p.appendChild(g)),c&&(p.style.borderRadius=c.borderRadius??"10px",p.style.padding=c.padding??"6px 4px 6px 12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=c.background??"",p.style.borderColor=c.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}));let f=wa({items:o,onSelect:y=>{p.setAttribute("aria-expanded","false"),r(y)},anchor:p,position:s,portal:i});i||p.appendChild(f.element);let h=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",y=>{if(y.stopPropagation(),h())return;let b=!f.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",b?"false":"true"),f.toggle()}),p.addEventListener("keydown",y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),p.click())}),{element:p,setLabel:y=>{d.textContent=y,p.setAttribute("aria-label",y)},open:()=>{p.setAttribute("aria-expanded","true"),f.show()},close:()=>{p.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let y=!f.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",y?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),p.remove()}}}Fd();var uS=e=>{let t=ws({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function MH(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=ya({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Nd(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let i=wl(o.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(o.menuItems?.length){let i=wa({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(i.element),r.addEventListener("click",l=>{l.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>n?.(o.id));e.appendChild(s)}}var gS=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,i=t?.launcher??{},l=x("div","persona-flex persona-items-center persona-justify-between");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=_n.minHeight,l.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=r?.titleMenu,p,d;if(c){let H=am({label:i.title??"Chat Assistant",menuItems:c.menuItems,onSelect:B=>{let V=W=>{W===!1&&H.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:B}}))},te=c.onSelect(B);te instanceof Promise?te.then(V,()=>{}):V(te)},hover:c.hover,className:""});p=H.element,p.style.color=_n.titleColor,d=p.querySelector(".persona-combo-btn-label")??p}else{if(p=x("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=x("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=_n.titleColor,Object.assign(d.style,im),d.textContent=i.title??"Chat Assistant",p.appendChild(d),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let B=r.onTitleClick;p.addEventListener("click",V=>{V.target.closest("button")||B()}),p.addEventListener("keydown",V=>{(V.key==="Enter"||V.key===" ")&&(V.preventDefault(),B())})}let H=r?.titleRowHover;H&&(p.style.borderRadius=H.borderRadius??"10px",p.style.padding=H.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=H.background??"",p.style.borderColor=H.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let g="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:f,wrapper:h}=ba(t,{showClose:n,wrapperClassName:g});o&&f.addEventListener("click",o);let y=x("div","persona-flex persona-items-center persona-gap-1");c||MH(y,r?.trailingActions,r?.onAction??s);let b=i.clearChat??{},C=null,A=null;if(b.enabled??!0){let H=b.placement??"inline",B=va(t,{wrapperClassName:H==="top-right"?"persona-absolute persona-top-4 persona-z-50":g});C=B.button,A=B.wrapper,H==="top-right"?A.style.right="48px":y.appendChild(A)}y.appendChild(h),l.appendChild(y);let L=x("div");L.style.display="none";let I=x("span");return I.style.display="none",{header:l,iconHolder:L,headerTitle:d,headerSubtitle:I,closeButton:f,closeButtonWrapper:h,clearChatButton:C,clearChatButtonWrapper:A}},lm={default:uS,minimal:gS},fS=e=>lm[e]??lm.default,Vl=(e,t,n)=>{if(t?.render){let i=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=x("div");l.style.display="none";let c=x("span"),p=x("span"),d=x("button");d.style.display="none";let g=x("div");return g.style.display="none",{header:i,iconHolder:l,headerTitle:c,headerSubtitle:p,closeButton:d,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=fS(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};Qe();gs();var Sa=e=>{let{config:t}=e,n=X("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"}}),o=Pd(),r=X("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:s,attachAutoResize:i}=Ed(t);i();let l=Md(t),c=ca(t),p=Td(t),d=kd(t),g=X("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(g),p&&(p.previewsContainer.style.gap="8px",g.append(p.previewsContainer),r.append(p.input)),r.append(s);let f=X("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=X("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),y=X("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&h.append(p.wrapper),c&&y.append(c.wrapper),y.append(l.wrapper),f.append(h,y),r.append(f),r.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==c?.button&&b.target!==c?.wrapper&&b.target!==p?.button&&b.target!==p?.wrapper&&s.focus()}),t?.statusIndicator?.mode==="transient"?n.append(o,d,r):n.append(o,r,d),{footer:n,suggestions:o,composerForm:r,header:g,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:d,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:f,leftActions:h,rightActions:y,setSendButtonMode:l.setMode}};Qe();Er();gs();Ad();import{ChevronUp as TH,MessageSquare as kH}from"lucide";var mS=()=>{let e=X("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=x("span","persona-pill-peek__icon"),n=Bt(kH,16,"currentColor",1.5);n&&t.appendChild(n);let o=x("span","persona-pill-peek__text"),r=x("span","persona-pill-peek__caret"),s=Bt(TH,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Ap=e=>{let{config:t}=e,n=X("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Pd(),r=kd(t);r.style.display="none";let{textarea:s,attachAutoResize:i}=Ed(t,{defaultMaxLines:5});i();let l=Md(t),c=ca(t),p=Td(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let d=X("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),g=X("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&g.append(p.wrapper);let f=X("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&f.append(c.wrapper),f.append(l.wrapper),d.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==c?.button&&b.target!==c?.wrapper&&b.target!==p?.button&&b.target!==p?.wrapper&&s.focus()}),p&&d.append(p.input),d.append(g,s,f);let h=X("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(h),p&&h.append(p.previewsContainer),n.append(o,d,r);let y=d;return{footer:n,suggestions:o,composerForm:d,header:h,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:y,leftActions:g,rightActions:f,setSendButtonMode:l.setMode}};Qe();Tt();Qe();gf();Tt();Hr();var PH=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}},LH=(e,t)=>{if(!e)return null;let n=PH(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},HH=(e,t)=>{let n=x("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},IH=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},dm=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(":"))},pm=320,CS=320,RH=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),WH=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),OH=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),_H=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),BH=e=>{if(!e||e.length===0)return null;let t=X("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=X("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=x("span","persona-mention-chip-icon"),s=ue(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(X("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},DH=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Cl(o.ref,{readonly:!0,render:t}))}return n},hS="\uE000",yS="\uE001",NH=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=f=>`${hS}${r}:${f}${yS}`,i=t.map((f,h)=>f.kind==="text"?f.text:s(h)).join(""),l=n(i);if(!t.every((f,h)=>f.kind==="text"||l.includes(s(h)))){e.replaceChildren(DH(t,o));return}e.innerHTML=l;let p=new RegExp(`${hS}${r}:(\\d+)${yS}`),d=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),g=[];for(let f=d.nextNode();f;f=d.nextNode())g.push(f);for(let f of g){let h=f;for(let y=p.exec(h.data);y;y=p.exec(h.data)){let b=t[Number(y[1])],C=h.splitText(y.index);C.data=C.data.slice(y[0].length),b?.kind==="mention"&&C.parentNode?.insertBefore(Cl(b.ref,{readonly:!0,render:o}),C),h=C}}},FH=(e,t,n)=>{if(e.length===0)return null;try{let o=x("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,i=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,c)=>{let p=x("img");p.alt=l.alt?.trim()||`Attached image ${c+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${pm}px`,p.style.maxHeight=`${CS}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let d=!1;r+=1,p.addEventListener("error",()=>{d||(d=!0,r=Math.max(0,r-1),p.remove(),r===0&&i())}),p.addEventListener("load",()=>{d=!0}),IH(l.image)?(p.src=l.image,o.appendChild(p)):(d=!0,r=Math.max(0,r-1),p.remove())}),r===0?(i(),null):o}catch{return n?.(),null}},$H=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!dm(o.audio))return;let r=x("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${pm}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},UH=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!dm(o.video))return;let r=x("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${pm}px`,r.style.maxHeight=`${CS}px`,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}},VH=e=>{if(e.length===0)return null;try{let t=x("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!dm(o.data))return;let r=x("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.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}},Aa=()=>{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 o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},wS=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Aa};if(t){let r=t(o);if(r!==null)return r}return Aa()},jH=(e,t)=>{let n=x("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"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=x("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,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},bS=(e,t,n="div")=>{let o=x(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},jl=(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");break}return n},vS={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"}},qH=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=vS[n??"bubble"]??vS.bubble;o.padding&&(e.style.padding=`var(--persona-message-${r}-padding, ${s.padding})`),o.fontSize&&(e.style.fontSize=`var(--persona-message-${r}-font-size, ${s.fontSize})`),o.lineHeight&&(e.style.lineHeight=`var(--persona-message-${r}-line-height, ${s.lineHeight})`),o.fontFamily&&(e.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},xp="custom:",zH=e=>`${xp}${e}`,SS=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),AS=(e,t,n,o)=>{let r=t.showCopy??!0,s=t.showUpvote??!1,i=t.showDownvote??!1,l=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&o?.canRegenerate===!0,p=(t.showEdit??!1)&&o?.canEdit===!0,d=(t.showQuote??!1)&&o?.canQuote!==!1,g=SS(t,e.role);if(!r&&!s&&!i&&!l&&!c&&!p&&!d&&g.length===0){let I=x("div");return I.style.display="none",I.id=`actions-${e.id}`,I.setAttribute("data-actions-for",e.id),I}let f=t.visibility??"hover",h=t.align??"right",y=t.layout??"pill-inside",b={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],C={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[y],A=x("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${b} ${C} ${f==="hover"?"persona-message-actions-hover":""}`);A.id=`actions-${e.id}`,A.setAttribute("data-actions-for",e.id);let L=(I,H,B)=>{let V=ro({icon:I,label:H,size:14,className:"persona-message-action-btn",chromeless:!0});return V.setAttribute("data-action",B),V};r&&A.appendChild(L("copy","Copy message","copy")),l&&A.appendChild(L("volume-2","Read aloud","read-aloud")),s&&A.appendChild(L("thumbs-up","Upvote","upvote")),i&&A.appendChild(L("thumbs-down","Downvote","downvote")),c&&A.appendChild(L("refresh-cw","Regenerate response","regenerate")),p&&A.appendChild(L("pencil","Edit message","edit")),d&&A.appendChild(L("quote","Quote message","quote"));for(let I of g)A.appendChild(L(I.iconName??"ellipsis",I.label,zH(I.id)));return A},ql=(e,t,n,o,r,s)=>{let i=n??{},l=i.layout??"bubble",c=i.avatar,p=i.timestamp,d=c?.show??!1,g=p?.show??!1,f=c?.position??"left",h=p?.position??"below",y=jl(e.role,l),b=x("div",y.join(" "));b.id=`bubble-${e.id}`,b.setAttribute("data-message-id",e.id),b.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let C=zf(s?.widgetConfig?.future).components.message,A=s?.widgetConfig?.theme?.components?.message;qH(b,e.role,l,e.role==="user"?{...C.user,...A?.user,...s?.widgetConfig?.darkTheme?.components?.message?.user}:{...C.assistant,...A?.assistant,...s?.widgetConfig?.darkTheme?.components?.message?.assistant}),l==="flat"?(b.style.backgroundColor="transparent",b.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(b.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",b.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(b.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",b.style.color="var(--persona-message-assistant-text, var(--persona-text))");let L=RH(e),I=e.content?.trim()??"",B=L.length>0&&I===la,V=yp(s?.widgetConfig?.features?.streamAnimation),te=s?.widgetConfig?.features?.streamAnimation?.plugins,W=e.role==="assistant"&&V.type!=="none"?_l(V.type,te):null,j=e.role==="assistant"&&W?.isAnimating?.(e)===!0,Y=e.role==="assistant"&&W!==null&&(!!e.streaming||j);Y&&W?.bubbleClass&&b.classList.add(W.bubbleClass);let M=document.createElement("div");M.classList.add("persona-message-content"),e.streaming&&M.classList.add("persona-content-streaming"),Y&&W&&(W.containerClass&&M.classList.add(W.containerClass),M.style.setProperty("--persona-stream-step",`${V.speed}ms`),M.style.setProperty("--persona-stream-duration",`${V.duration}ms`));let T=Y?vp(e.content??"",V.buffer,W,e,!!e.streaming):e.content??"",_=()=>{let Re=t({text:T,message:e,streaming:!!e.streaming,raw:e.rawContent});return Y&&W?.wrap==="char"?Bl(Re,"char",e.id,{skipTags:W.skipTags}):Y&&W?.wrap==="word"?Bl(Re,"word",e.id,{skipTags:W.skipTags}):Re},k=null;if(B?(k=document.createElement("div"),k.innerHTML=_(),k.style.display="none",M.appendChild(k)):e.contentSegments?.length?NH(M,e.contentSegments,Re=>t({text:Re,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):M.innerHTML=_(),Y&&W?.useCaret&&!B&&I){let Re=Cp(),$=M.querySelectorAll(".persona-stream-char, .persona-stream-word"),We=$[$.length-1];if(We?.parentNode)We.parentNode.insertBefore(Re,We.nextSibling);else{let me=M.lastElementChild;me?me.appendChild(Re):M.appendChild(Re)}}if(g&&h==="inline"&&e.createdAt){let Re=bS(e,p,"span");Re.classList.add("persona-timestamp-inline");let $=M.lastElementChild;$?$.appendChild(Re):M.appendChild(Re)}if(L.length>0){let Re=FH(L,!B&&!!I,()=>{B&&k&&(k.style.display="")});Re?b.appendChild(Re):B&&k&&(k.style.display="")}let Q=WH(e);if(Q.length>0){let Re=$H(Q);Re&&b.appendChild(Re)}let U=OH(e);if(U.length>0){let Re=UH(U);Re&&b.appendChild(Re)}let de=_H(e);if(de.length>0){let Re=VH(de);Re&&b.appendChild(Re)}let pe=e.contentSegments?.length?null:BH(e.contextMentions);if(pe&&b.appendChild(pe),b.appendChild(M),g&&h==="below"&&e.createdAt){let Re=bS(e,p);Re.classList.add("persona-mt-1"),b.appendChild(Re)}let ge=e.role==="assistant"?LH(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Re=!!(T&&T.trim()),$=V.placeholder==="skeleton",We=$&&V.buffer==="line"&&Re;if(Re)We&&b.appendChild(Dl());else if($)b.appendChild(Dl());else{let me=wS("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);me&&b.appendChild(me)}}ge&&e.stopReason&&!e.streaming&&(I||(M.style.display="none"),b.appendChild(HH(e.stopReason,ge)));let Pe=e.role==="assistant"&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&o?.enabled!==!1,Ae=s?.actionEligibility,Le=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Ae?.canEdit===!0||o?.showQuote===!0&&Ae?.canQuote===!0||SS(o,"user").length>0);if((Pe||Le)&&o){let Re=AS(e,Le?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,Ae);b.appendChild(Re)}if(!d||e.role==="system")return b;let mt=x("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ve=jH(c,e.role);return f==="right"||f==="left"&&e.role==="user"?mt.append(b,Ve):mt.append(Ve,b),mt},KH=(e,t,n,o,r,s)=>{let i=n??{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):ql(e,t,n,o,r,s)};var GH=40,YH=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=ue(t.name,GH);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(X("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(X("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},xS=(e,t,n={})=>{let o=X("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=x("p","persona-welcome-kicker");r.hidden=!0;let s=x("h2","persona-welcome-title"),i=x("p","persona-welcome-subtitle"),l=X("div",{className:"persona-welcome-head-text"},r,s),c=X("div",{className:"persona-welcome-title-row"},o,l);return{host:X("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,i,t),iconHolder:o,kicker:r,title:s,subtitle:i,starterSuggestions:t}},xa=(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)},Mp=(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==="",YH(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")},XH="data-persona-welcome-plugin",ES="data-persona-welcome-overlay",Ep="persona-welcome-overlay-active",um=new WeakMap,gm=(e,t,n)=>{n.setAttribute(XH,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(ES,""),e.classList.contains(Ep)||(um.set(e,e.scrollTop),e.classList.add(Ep),e.scrollTop=0)},fm=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(ES),e.classList.contains(Ep)&&(e.classList.remove(Ep),e.scrollTop=um.get(e)??e.scrollTop,um.delete(e))},MS=()=>{let e=X("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Tp=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=X("div",{className:jl("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="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(X("div",{className:"persona-flex"},r)),e.hidden=!1},TS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,kS=(e,t)=>{if(TS()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,i=0;if(o){let y=getComputedStyle(o);r=parseFloat(y.rowGap)||0;let b=e.previousElementSibling,C=e.nextElementSibling,L=o.getBoundingClientRect().top+(parseFloat(y.borderTopWidth)||0)+(parseFloat(y.paddingTop)||0)-o.scrollTop;s=Math.max(0,b?n.top-b.getBoundingClientRect().bottom-r:n.top-L),i=Math.max(0,C?C.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let c=getComputedStyle(e),p=parseFloat(c.paddingTop)||0,d=parseFloat(c.paddingBottom)||0,g=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${d}px`,marginTop:`${s}px`,marginBottom:`${i}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),f=!1,h=()=>{f||(f=!0,e.style.overflow=l,t(g))};return g.finished.then(h).catch(h),g},PS=(e,t,n,o=260)=>{if(t<=1||TS()||typeof e.animate!="function"||!e.isConnected)return null;let r=n==="drop"?-t:t;return e.animate([{transform:`translateY(${r}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var QH="Hello \u{1F44B}",JH="I can answer questions and help you get things done here.",LS=new WeakSet,Bn=(e,t)=>!!e&&e[t]!==void 0,ZH=(e,t)=>{!e||e.debug!==!0||!t.length||LS.has(e)||(LS.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},zl=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!=="docked")=>{let n=e?.welcome,o=e?.copy,r=e?.future?.v5Defaults===!0,s=n?.layout??(r?"centered":"top"),i=Bn(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=i==="hero"&&!r&&n?.layout===void 0?"on-first-message":Bn(n,"dismiss")?n.dismiss:r||i==="hero"?"on-first-message":"never",c=[];Bn(n,"title")&&Bn(o,"welcomeTitle")&&c.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Bn(n,"subtitle")&&Bn(o,"welcomeSubtitle")&&c.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Bn(n,"variant")&&Bn(o,"showWelcomeCard")&&c.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),i==="hero"&&Bn(n,"message")&&c.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!r&&n?.layout===void 0&&i==="hero"&&Bn(n,"dismiss")&&n.dismiss!=="on-first-message"&&c.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let p=n?.anchor??(s==="centered"&&t?"center":"bottom"),d=Rl(n?.anchorComposerTop)!==null;return Bn(n,"anchorComposerTop")&&!d&&c.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&(Bn(n,"anchorComposerTop")||Bn(n,"composerGap"))&&c.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),ZH(e,c),{title:Bn(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":QH),kicker:n?.kicker??"",subtitle:Bn(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":JH),icon:n?.icon,align:n?.align==="start"||n?.align==="center"?n.align:s==="centered"?"center":void 0,iconPlacement:n?.icon&&typeof n.icon!="function"&&n.icon.placement==="inline"?"inline":"above",variant:i,dismiss:l,message:i==="hero"?void 0:n?.message,layout:s,anchor:p,anchorComposerTop:d?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||mp}},HS=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",pi=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");ia();var eI="var(--persona-components-panel-maxWidth)",IS="var(--persona-components-panel-height)",tI="var(--persona-components-panel-maxHeight)",ui=e=>{let t=kr(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0,r=o===0?`max(200px, ${IS})`:`max(200px, calc(${IS} - ${o}px))`;return{width:n??Nv,maxWidth:n??eI,height:r,maxHeight:tI}},RS="16px",hm="10px",ym="14px",WS=e=>{let t=e?.launcher?.enabled??!0,n=Ht(e);if(Cs(e)){let p=e?.launcher?.composerBar??{},d=x("div","persona-widget-wrapper persona-fixed persona-transition");d.setAttribute("data-persona-composer-bar",""),d.dataset.state="collapsed",d.dataset.expandedSize=p.expandedSize??"anchored",d.style.zIndex=String(e?.launcher?.zIndex??Tn);let g=x("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");g.style.width="100%",d.appendChild(g);let f=x("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=p.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Tn),{wrapper:d,panel:g,pillRoot:f}}if(n){let p=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),d=x("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(d),{wrapper:p,panel:d}}if(!t){let p=x("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),d=x("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),g=kr(e),h=g.launcherWidth||g.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?ui(e).width:"100%";return p.style.width=h,d.style.width="100%",p.appendChild(d),{wrapper:p,panel:d}}let r=e?.launcher??{},s=r.position&&oo[r.position]?oo[r.position]:oo["bottom-right"],i=x("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??Tn);let l=x("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=ui(e);return l.style.width=c.width,l.style.maxWidth=c.maxWidth,i.appendChild(l),{wrapper:i,panel:l}},bm=e=>{let t=X("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":om(e)}});return t.hidden=!0,t},OS=(e,t)=>{let n=bm("starter"),o=xS(e,n,{flatShadow:Ht(e)}),r=zl(e);Mp(o,r),xa(t,o.host,pi(r,e?.initialMessages));let s=MS();return Tp(s,r.message,e),{welcome:o,greetingHost:s}},nI=(e,t)=>{let n=x("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:o,wrapper:r}=ba(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:RS,iconSize:hm});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,i=null,l=null;if(s){let te=va(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:RS,iconSize:ym});i=te.button,l=te.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let c=X("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=X("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"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:d,greetingHost:g}=OS(e,p),{host:f,title:h,subtitle:y}=d,b=d.starterSuggestions,C=x("div","persona-widget-messages persona-flex persona-flex-col");C.style.gap="var(--persona-components-message-gap, 12px)";let A=bm("followUp"),L=bs(e,!0);L&&(C.style.maxWidth=L,C.style.marginLeft="auto",C.style.marginRight="auto",C.style.width="100%"),p.append(f,g,C,A);let I=X("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"}}),H=Ap({config:e}),{root:B,textNode:V}=mS();return n.append(c,r,p,I),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:C,starterSuggestions:b,transcriptSuggestions:A,composerOverlay:I,suggestions:H.suggestions,textarea:H.textarea,sendButton:H.sendButton,sendButtonWrapper:H.sendButtonWrapper,micButton:H.micButton,micButtonWrapper:H.micButtonWrapper,composerForm:H.composerForm,statusText:H.statusText,welcomeHost:f,welcomeIconHolder:d.iconHolder,greetingHost:g,introKicker:d.kicker,introTitle:h,introSubtitle:y,closeButton:o,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:l,iconHolder:x("span"),headerTitle:x("span"),headerSubtitle:x("span"),header:c,footer:H.footer,attachmentButton:H.attachmentButton,attachmentButtonWrapper:H.attachmentButtonWrapper,attachmentInput:H.attachmentInput,attachmentPreviewsContainer:H.attachmentPreviewsContainer,actionsRow:H.actionsRow,leftActions:H.leftActions,rightActions:H.rightActions,setSendButtonMode:H.setSendButtonMode,peekBanner:B,peekTextNode:V}},_S=(e,t=!0)=>{if(Cs(e))return nI(e,t);let n=X("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"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?Vl(e,o,{showClose:t}):ws({config:e,showClose:t}),i=X("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"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:c}=OS(e,i),{host:p,title:d,subtitle:g}=l,f=l.starterSuggestions,h=x("div","persona-widget-messages persona-flex persona-flex-col");h.style.gap="var(--persona-components-message-gap, 12px)";let y=bm("followUp"),b=bs(e,!1);b&&(h.style.maxWidth=b,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),i.append(p,c,h,y);let C=Sa({config:e}),A=e?.layout?.showFooter!==!1;r?Ca(n,s,e):(s.header.style.display="none",Ca(n,s,e)),n.append(i);let L=X("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 A||(C.footer.style.display="none"),n.append(C.footer),n.append(L),{container:n,body:i,messagesWrapper:h,starterSuggestions:f,transcriptSuggestions:y,composerOverlay:L,suggestions:C.suggestions,textarea:C.textarea,sendButton:C.sendButton,sendButtonWrapper:C.sendButtonWrapper,micButton:C.micButton,micButtonWrapper:C.micButtonWrapper,composerForm:C.composerForm,statusText:C.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:c,introKicker:l.kicker,introTitle:d,introSubtitle:g,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions,setSendButtonMode:C.setSendButtonMode}};gs();Qe();Tt();Lo();var vm=(e,t)=>{let n=x("button");n.type="button",n.innerHTML=`
31
31
  <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">\u{1F4AC}</span>
32
32
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
33
33
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -35,15 +35,15 @@ _Details: ${n.message}_`:o}var QC=e=>Zs(e)||e===Xo,kl=class e{constructor(t={},n
35
35
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
36
36
  </span>
37
37
  <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">\u2197</span>
38
- `,n.addEventListener("click",t);let o=s=>{let i=s.launcher??{},l=Ht(s),c=sp(s)==="circle";c?(n.dataset.personaLauncherVariant="circle",n.setAttribute("aria-label",i.title??"Open chat")):(n.removeAttribute("data-persona-launcher-variant"),n.removeAttribute("aria-label"));let p=n.querySelector("[data-role='launcher-title']");if(p){let H=i.title??"Chat Assistant";p.textContent=H,p.setAttribute("title",H)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let H=i.subtitle??"Here to help you get answers fast";d.textContent=H,d.setAttribute("title",H)}let g=n.querySelector(".persona-flex-col");g&&(i.textHidden||l||c?g.style.display="none":g.style.display="");let f=n.querySelector("[data-role='launcher-icon']");if(f)if(i.agentIconHidden)f.style.display="none";else{let H=i.agentIconSize??"40px";if(f.style.height=H,f.style.width=H,i.agentIconBackgroundColor?(f.style.backgroundColor=i.agentIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),f.innerHTML="",i.agentIconName){let _=parseFloat(H)||24,V=ue(i.agentIconName,_*.6,"var(--persona-text-inverse, #ffffff)",1.5);V?(f.appendChild(V),f.style.display=""):(f.textContent=i.agentIconText??"\u{1F4AC}",f.style.display="")}else i.iconUrl?f.style.display="none":(f.textContent=i.agentIconText??"\u{1F4AC}",f.style.display="")}let h=n.querySelector("[data-role='launcher-image']");if(h){let H=i.agentIconSize??"40px";h.style.height=H,h.style.width=H,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(h.src=i.iconUrl,h.style.display="block"):h.style.display="none"}let y=n.querySelector("[data-role='launcher-call-to-action-icon']");if(y){let H=i.callToActionIconSize??"32px";y.style.height=H,y.style.width=H,i.callToActionIconBackgroundColor?(y.style.backgroundColor=i.callToActionIconBackgroundColor,y.classList.remove("persona-bg-persona-primary")):(y.style.backgroundColor="",y.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(y.style.color=i.callToActionIconColor,y.classList.remove("persona-text-persona-call-to-action")):(y.style.color="",y.classList.add("persona-text-persona-call-to-action"));let _=0;if(i.callToActionIconPadding?(y.style.boxSizing="border-box",y.style.padding=i.callToActionIconPadding,_=(parseFloat(i.callToActionIconPadding)||0)*2):(y.style.boxSizing="",y.style.padding=""),i.callToActionIconHidden||c)y.style.display="none";else if(y.style.display=l?"none":"",y.innerHTML="",i.callToActionIconName){let V=parseFloat(H)||24,te=Math.max(V-_,8),W=ue(i.callToActionIconName,te,"currentColor",1.5);W?y.appendChild(W):y.textContent=i.callToActionIconText??"\u2197"}else y.textContent=i.callToActionIconText??"\u2197"}let v=i.position&&no[i.position]?no[i.position]:no["bottom-right"],C="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",A="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";n.className=l?A:`${C} ${v}`,l||(n.style.zIndex=String(i.zIndex??Tn));let L="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",I="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=i.border??L,n.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:I,l?(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=i.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}},JH="teaser-dismissed",WS=new Set,RS=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${JH}`},ZH=(e,t)=>{if(WS.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},eI=(e,t)=>{if(WS.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},tI=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,nI=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Ht(e??{})?null:t},OS=(e,t)=>{let n=x("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,i=null,l=null,c=null,p=!1,d=!1,g=!1,f=!1,h=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,y=()=>{c!==null&&(clearTimeout(c),c=null)},v=()=>{!s||!p||(p=!1,s.hidden=!0)},C=Q=>{y(),g=!0,v(),eI(RS(o),Q&&h())},A=Q=>{!r||g||C(Q==="user"&&p)},L=()=>{c=null,!(!s||g||f)&&(d=!0,p=!0,s.hidden=!1,!(tI()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},I=()=>{!r||!s||g||d||f||ZH(RS(o),h())||(y(),c=setTimeout(L,Math.max(0,r.delayMs??0)))},H=()=>{C(h()),t()},_=Q=>{Q.stopPropagation(),C(h())},te=hm(e,()=>{A("user"),t()}),W=()=>{y(),l?.removeEventListener("click",H),i?.removeEventListener("click",_),s?.remove(),s=null,l=null,i=null,p=!1},j=()=>{l=X("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",H),i=X("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",_),s=X("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,i),n.insertBefore(s,te.element)},Y=()=>{let Q=o.launcher?.position??"bottom-right",U=no[Q]??no["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",te.element.style.position="";return}n.className=Wn("persona-launcher-surface",U),n.setAttribute("data-teaser",Q),n.style.zIndex=String(o.launcher?.zIndex??Tn),te.element.style.position="static"},E=Q=>{let U=nI(Q);if(r=U,!U){W();return}s||j(),l.textContent=U.text,i.hidden=U.dismissible===!1,i.setAttribute("aria-label",U.dismissLabel??"Dismiss message"),I()},T=Q=>{o=Q,te.update(Q),E(Q),Y()},B=(Q,U="user")=>{f=Q,Q&&A(U)},P=()=>{W(),te.destroy(),n.remove()};return n.appendChild(te.element),e&&(E(e),Y()),{element:n,launcher:te,get teaser(){return s?{element:s,show:L,dismiss:C}:null},setPanelOpen:B,update:T,destroy:P}};var BS=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=LS(e),s=IS(e,t),i={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,welcomeHost:s.welcomeHost,welcomeIconHolder:s.welcomeIconHolder,greetingHost:s.greetingHost,introTitle:s.introTitle,introSubtitle:s.introSubtitle},c={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},p={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:i,panelElements:s,transcript:l,header:c,composer:p,replaceHeader:f=>(c.element.replaceWith(f.header),c.element=f.header,c.iconHolder=f.iconHolder,c.headerTitle=f.headerTitle,c.headerSubtitle=f.headerSubtitle,c.closeButton=f.closeButton,c.closeButtonWrapper=f.closeButtonWrapper,c.clearChatButton=f.clearChatButton,c.clearChatButtonWrapper=f.clearChatButtonWrapper,f),replaceComposer:f=>{p.footer.replaceWith(f),p.footer=f}}},ym=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>hm(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=OS(e,n);return{instance:r,element:r.element}};var oI=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},rI=(e,t,n)=>`${oI(e)}plugin:${t}:${n}`,_S=e=>{let t=new Map,n=!1,o=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=i=>rI(e(),r,i);return{get:i=>{let l=s(i),c=o();if(c)try{return c.getItem(l)}catch{n=!0}return t.get(l)??null},set:(i,l)=>{let c=s(i),p=o();if(p)try{p.setItem(c,l);return}catch{n=!0}t.set(c,l)},remove:i=>{let l=s(i);t.delete(l);let c=o();if(c)try{c.removeItem(l)}catch{n=!0}}}}};Xe();Tt();bo();ss();Xe();var Ma=(e,t,n)=>{let o=n;for(let r of t){let s=x("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};var sI=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
39
- `):""},bm=(e,t,n)=>{Kd(e,t,{stateSet:n,previewKind:"reasoning",iconColor:"currentColor"})},vm=(e,t,n=new Set)=>{t=Gd(t,"reasoning");let o=e.reasoning,r=Vd("persona-reasoning-bubble",e.id);if(!o)return Rr(r,e,t,"reasoning");let s=t?.features?.reasoningDisplay??{},i=s.expandable??ai.expandable,l=i&&n.has(e.id),c=o.status!=="complete",p=sI(e,s.previewMaxLines??ai.previewMaxLines),d=jd({expandable:i,expanded:l,bubbleType:"reasoning"}),g=x("div","persona-flex persona-flex-col persona-text-left"),f=x("span","persona-text-xs persona-text-persona-primary"),h=fs(t,"reasoning")==="row",y=h&&!c?`Thought for ${xl(o.durationMs??(o.completedAt!==void 0&&o.startedAt!==void 0?o.completedAt-o.startedAt:void 0))}`:"Thinking...",v=t?.reasoning??{},C=String(o.startedAt??Date.now()),A=()=>{let U=x("span","");return U.setAttribute("data-tool-elapsed",C),U.textContent=td(o),U},L=v.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:y,previewText:p,isActive:c,config:t??{},elapsed:td(o),createElapsedElement:A});typeof L=="string"&&L.trim()?(f.textContent=L,g.appendChild(f)):L instanceof HTMLElement?g.appendChild(L):(f.textContent=y,g.appendChild(f));let I=x("span","persona-text-xs persona-text-persona-primary");I.textContent=Hb(o),h||g.appendChild(I);let H=s.loadingAnimation??ai.loadingAnimation,_=v.activeTextTemplate,V=v.completeTextTemplate,te=c?_:V,W=L instanceof HTMLElement,j=(U,de)=>{f.textContent="";let pe=nd(U,""),ge=0;for(let ke of pe){let xe=ke.styles.length>0?(()=>{let Le=x("span",ke.styles.map(mt=>`persona-tool-text-${mt}`).join(" "));return f.appendChild(Le),Le})():f;if(ke.isDuration&&c)xe.appendChild(A());else{let Le=ke.isDuration?td(o):ke.text;de?ge=Ma(xe,Le,ge):xe.appendChild(document.createTextNode(Le))}}};if(!W&&te)if(I.style.display="none",f.style.display="",c&&H!=="none"){let U=v.loadingAnimationDuration??2e3;f.setAttribute("data-preserve-animation","true"),H==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${U}ms`),j(te,!1)):(f.classList.add(`persona-tool-loading-${H}`),f.style.setProperty("--persona-tool-anim-duration",`${U}ms`),H==="shimmer-color"&&(v.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",v.loadingAnimationColor),v.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",v.loadingAnimationSecondaryColor)),j(te,!0))}else j(te,!1);else if(!W&&c&&H!=="none"){f.style.display="";let U=v.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),H==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${U}ms`);else{f.classList.add(`persona-tool-loading-${H}`),f.style.setProperty("--persona-tool-anim-duration",`${U}ms`),H==="shimmer-color"&&(v.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",v.loadingAnimationColor),v.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",v.loadingAnimationSecondaryColor));let de=f.textContent||y;f.textContent="",Ma(f,de,0)}o.status==="complete"&&!h&&(f.style.display="none")}else W||(o.status==="complete"&&!h?f.style.display="none":f.style.display="");if(s.iconName&&!W){let U=x("span","persona-reasoning-header-icon"),de=ue(s.iconName,16,"currentColor",2);de&&(U.appendChild(de),d.appendChild(U))}let Y="currentColor",E=da(d,g,{expandable:i,expanded:l,iconColor:Y,metaGap:!1}),T=qd({bubble:r,previewKind:"reasoning",expanded:l,isActive:c,previewText:p,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:o,defaultPreview:p,isActive:c,config:t??{}})});if(!i)return r.append(d,T),Rr(r,e,t,"reasoning");let B=x("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");B.style.display=l?"":"none";let P=o.chunks.join(""),Q=x("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Q.textContent=P||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),B.appendChild(Q),zd({expanded:l,header:d,toggleIcon:E,content:B,collapsedPreview:T,iconColor:Y}),r.append(d,T,B),Rr(r,e,t,"reasoning")};Xe();ss();Tt();var DS=e=>{if(e==null)return!0;if(typeof e=="string"){if(!e.trim())return!0;try{return DS(JSON.parse(e))}catch{return!1}}return typeof e=="object"&&Object.keys(e).length===0},iI=e=>{if(e!==null&&typeof e=="object")return!0;if(typeof e!="string")return!1;try{let t=JSON.parse(e);return t!==null&&typeof t=="object"}catch{return!1}};function NS(e,t,n){let o=t.toolCall;if(!o)return;let r=n.toolCall??{},s=(l,c)=>{let p=X("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":l.toLowerCase()},style:{backgroundColor:r.codeBlockBackgroundColor,borderColor:r.codeBlockBorderColor,borderWidth:r.codeBlockBorderColor?"1px":void 0}}),d=X("div",{className:"persona-tool-detail-label",text:l,style:{color:r.labelTextColor}}),g=Xi(c),f=X("pre",{className:`persona-tool-detail-value${iI(c)?" persona-tool-detail-code":""}`,text:g,attrs:g.length>420||g.split(`
40
- `).length>7?{tabindex:"0","aria-label":`${l} content`}:{},style:{color:r.codeBlockTextColor??r.contentTextColor}}),h=X("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${l.toLowerCase()}`,title:`Copy ${l.toLowerCase()}`}}),y=ue("copy",14,"currentColor",1.7);y&&h.appendChild(y),p.append(d,f,h),e.appendChild(p)};DS(o.args)||s("Request",o.args);let i=o.status==="complete"&&o.result!==void 0?o.result:o.chunks?.join("");i!==void 0&&(typeof i!="string"||i.trim())&&s("Response",i),o.success===!1&&e.appendChild(X("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var Cm=new WeakMap;async function FS(e){let t=e.closest("[data-persona-tool-detail]"),n=t?.querySelector("pre");if(!n)return;let o=`Copy ${t?.getAttribute("data-persona-tool-detail")}`;clearTimeout(Cm.get(e));try{await navigator.clipboard.writeText(n.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let r=ue("check",14,"currentColor",2);r&&e.replaceChildren(r)}catch{e.setAttribute("aria-label","Copy failed \u2014 try again"),e.title="Copy failed \u2014 try again"}Cm.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",o),e.title=o;let r=ue("copy",14,"currentColor",1.7);r&&e.replaceChildren(r),Cm.delete(e)},1800))}Xe();bo();ss();var $S=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?"currentColor":"var(--persona-primary, #171717)"),aI=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
38
+ `,n.addEventListener("click",t);let o=s=>{let i=s.launcher??{},l=Ht(s),c=ap(s)==="circle";c?(n.dataset.personaLauncherVariant="circle",n.setAttribute("aria-label",i.title??"Open chat")):(n.removeAttribute("data-persona-launcher-variant"),n.removeAttribute("aria-label"));let p=n.querySelector("[data-role='launcher-title']");if(p){let H=i.title??"Chat Assistant";p.textContent=H,p.setAttribute("title",H)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let H=i.subtitle??"Here to help you get answers fast";d.textContent=H,d.setAttribute("title",H)}let g=n.querySelector(".persona-flex-col");g&&(i.textHidden||l||c?g.style.display="none":g.style.display="");let f=n.querySelector("[data-role='launcher-icon']");if(f)if(i.agentIconHidden)f.style.display="none";else{let H=i.agentIconSize??"40px";if(f.style.height=H,f.style.width=H,i.agentIconBackgroundColor?(f.style.backgroundColor=i.agentIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),f.innerHTML="",i.agentIconName){let B=parseFloat(H)||24,V=ue(i.agentIconName,B*.6,"var(--persona-text-inverse, #ffffff)",1.5);V?(f.appendChild(V),f.style.display=""):(f.textContent=i.agentIconText??"\u{1F4AC}",f.style.display="")}else i.iconUrl?f.style.display="none":(f.textContent=i.agentIconText??"\u{1F4AC}",f.style.display="")}let h=n.querySelector("[data-role='launcher-image']");if(h){let H=i.agentIconSize??"40px";h.style.height=H,h.style.width=H,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(h.src=i.iconUrl,h.style.display="block"):h.style.display="none"}let y=n.querySelector("[data-role='launcher-call-to-action-icon']");if(y){let H=i.callToActionIconSize??"32px";y.style.height=H,y.style.width=H,i.callToActionIconBackgroundColor?(y.style.backgroundColor=i.callToActionIconBackgroundColor,y.classList.remove("persona-bg-persona-primary")):(y.style.backgroundColor="",y.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(y.style.color=i.callToActionIconColor,y.classList.remove("persona-text-persona-call-to-action")):(y.style.color="",y.classList.add("persona-text-persona-call-to-action"));let B=0;if(i.callToActionIconPadding?(y.style.boxSizing="border-box",y.style.padding=i.callToActionIconPadding,B=(parseFloat(i.callToActionIconPadding)||0)*2):(y.style.boxSizing="",y.style.padding=""),i.callToActionIconHidden||c)y.style.display="none";else if(y.style.display=l?"none":"",y.innerHTML="",i.callToActionIconName){let V=parseFloat(H)||24,te=Math.max(V-B,8),W=ue(i.callToActionIconName,te,"currentColor",1.5);W?y.appendChild(W):y.textContent=i.callToActionIconText??"\u2197"}else y.textContent=i.callToActionIconText??"\u2197"}let b=i.position&&oo[i.position]?oo[i.position]:oo["bottom-right"],C="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",A="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";n.className=l?A:`${C} ${b}`,l||(n.style.zIndex=String(i.zIndex??Tn));let L="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",I="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=i.border??L,n.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:I,l?(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=i.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}},oI="teaser-dismissed",DS=new Set,BS=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${oI}`},rI=(e,t)=>{if(DS.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},sI=(e,t)=>{if(DS.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},iI=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,aI=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Ht(e??{})?null:t},NS=(e,t)=>{let n=x("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,i=null,l=null,c=null,p=!1,d=!1,g=!1,f=!1,h=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,y=()=>{c!==null&&(clearTimeout(c),c=null)},b=()=>{!s||!p||(p=!1,s.hidden=!0)},C=Q=>{y(),g=!0,b(),sI(BS(o),Q&&h())},A=Q=>{!r||g||C(Q==="user"&&p)},L=()=>{c=null,!(!s||g||f)&&(d=!0,p=!0,s.hidden=!1,!(iI()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},I=()=>{!r||!s||g||d||f||rI(BS(o),h())||(y(),c=setTimeout(L,Math.max(0,r.delayMs??0)))},H=()=>{C(h()),t()},B=Q=>{Q.stopPropagation(),C(h())},te=vm(e,()=>{A("user"),t()}),W=()=>{y(),l?.removeEventListener("click",H),i?.removeEventListener("click",B),s?.remove(),s=null,l=null,i=null,p=!1},j=()=>{l=X("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",H),i=X("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",B),s=X("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,i),n.insertBefore(s,te.element)},Y=()=>{let Q=o.launcher?.position??"bottom-right",U=oo[Q]??oo["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",te.element.style.position="";return}n.className=On("persona-launcher-surface",U),n.setAttribute("data-teaser",Q),n.style.zIndex=String(o.launcher?.zIndex??Tn),te.element.style.position="static"},M=Q=>{let U=aI(Q);if(r=U,!U){W();return}s||j(),l.textContent=U.text,i.hidden=U.dismissible===!1,i.setAttribute("aria-label",U.dismissLabel??"Dismiss message"),I()},T=Q=>{o=Q,te.update(Q),M(Q),Y()},_=(Q,U="user")=>{f=Q,Q&&A(U)},k=()=>{W(),te.destroy(),n.remove()};return n.appendChild(te.element),e&&(M(e),Y()),{element:n,launcher:te,get teaser(){return s?{element:s,show:L,dismiss:C}:null},setPanelOpen:_,update:T,destroy:k}};var FS=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=WS(e),s=_S(e,t),i={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,welcomeHost:s.welcomeHost,welcomeIconHolder:s.welcomeIconHolder,greetingHost:s.greetingHost,introTitle:s.introTitle,introSubtitle:s.introSubtitle},c={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},p={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:i,panelElements:s,transcript:l,header:c,composer:p,replaceHeader:f=>(c.element.replaceWith(f.header),c.element=f.header,c.iconHolder=f.iconHolder,c.headerTitle=f.headerTitle,c.headerSubtitle=f.headerSubtitle,c.closeButton=f.closeButton,c.closeButtonWrapper=f.closeButtonWrapper,c.clearChatButton=f.clearChatButton,c.clearChatButtonWrapper=f.clearChatButtonWrapper,f),replaceComposer:f=>{p.footer.replaceWith(f),p.footer=f}}},Cm=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>vm(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=NS(e,n);return{instance:r,element:r.element}};var lI=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},cI=(e,t,n)=>`${lI(e)}plugin:${t}:${n}`,$S=e=>{let t=new Map,n=!1,o=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=i=>cI(e(),r,i);return{get:i=>{let l=s(i),c=o();if(c)try{return c.getItem(l)}catch{n=!0}return t.get(l)??null},set:(i,l)=>{let c=s(i),p=o();if(p)try{p.setItem(c,l);return}catch{n=!0}t.set(c,l)},remove:i=>{let l=s(i);t.delete(l);let c=o();if(c)try{c.removeItem(l)}catch{n=!0}}}}};Qe();Tt();vo();ss();Qe();var Ea=(e,t,n)=>{let o=n;for(let r of t){let s=x("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};var dI=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
39
+ `):""},wm=(e,t,n)=>{Yd(e,t,{stateSet:n,previewKind:"reasoning",iconColor:"currentColor"})},Sm=(e,t,n=new Set)=>{t=Xd(t,"reasoning");let o=e.reasoning,r=qd("persona-reasoning-bubble",e.id);if(!o)return Rr(r,e,t,"reasoning");let s=t?.features?.reasoningDisplay??{},i=s.expandable??ai.expandable,l=i&&n.has(e.id),c=o.status!=="complete",p=dI(e,s.previewMaxLines??ai.previewMaxLines),d=zd({expandable:i,expanded:l,bubbleType:"reasoning"}),g=x("div","persona-flex persona-flex-col persona-text-left"),f=x("span","persona-text-xs persona-text-persona-primary"),h=fs(t,"reasoning")==="row",y=h&&!c?`Thought for ${xl(o.durationMs??(o.completedAt!==void 0&&o.startedAt!==void 0?o.completedAt-o.startedAt:void 0))}`:"Thinking...",b=t?.reasoning??{},C=String(o.startedAt??Date.now()),A=()=>{let U=x("span","");return U.setAttribute("data-tool-elapsed",C),U.textContent=od(o),U},L=b.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:y,previewText:p,isActive:c,config:t??{},elapsed:od(o),createElapsedElement:A});typeof L=="string"&&L.trim()?(f.textContent=L,g.appendChild(f)):L instanceof HTMLElement?g.appendChild(L):(f.textContent=y,g.appendChild(f));let I=x("span","persona-text-xs persona-text-persona-primary");I.textContent=Ob(o),h||g.appendChild(I);let H=s.loadingAnimation??ai.loadingAnimation,B=b.activeTextTemplate,V=b.completeTextTemplate,te=c?B:V,W=L instanceof HTMLElement,j=(U,de)=>{f.textContent="";let pe=rd(U,""),ge=0;for(let Pe of pe){let Ae=Pe.styles.length>0?(()=>{let Le=x("span",Pe.styles.map(mt=>`persona-tool-text-${mt}`).join(" "));return f.appendChild(Le),Le})():f;if(Pe.isDuration&&c)Ae.appendChild(A());else{let Le=Pe.isDuration?od(o):Pe.text;de?ge=Ea(Ae,Le,ge):Ae.appendChild(document.createTextNode(Le))}}};if(!W&&te)if(I.style.display="none",f.style.display="",c&&H!=="none"){let U=b.loadingAnimationDuration??2e3;f.setAttribute("data-preserve-animation","true"),H==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${U}ms`),j(te,!1)):(f.classList.add(`persona-tool-loading-${H}`),f.style.setProperty("--persona-tool-anim-duration",`${U}ms`),H==="shimmer-color"&&(b.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",b.loadingAnimationColor),b.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",b.loadingAnimationSecondaryColor)),j(te,!0))}else j(te,!1);else if(!W&&c&&H!=="none"){f.style.display="";let U=b.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),H==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${U}ms`);else{f.classList.add(`persona-tool-loading-${H}`),f.style.setProperty("--persona-tool-anim-duration",`${U}ms`),H==="shimmer-color"&&(b.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",b.loadingAnimationColor),b.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",b.loadingAnimationSecondaryColor));let de=f.textContent||y;f.textContent="",Ea(f,de,0)}o.status==="complete"&&!h&&(f.style.display="none")}else W||(o.status==="complete"&&!h?f.style.display="none":f.style.display="");if(s.iconName&&!W){let U=x("span","persona-reasoning-header-icon"),de=ue(s.iconName,16,"currentColor",2);de&&(U.appendChild(de),d.appendChild(U))}let Y="currentColor",M=da(d,g,{expandable:i,expanded:l,iconColor:Y,metaGap:!1}),T=Kd({bubble:r,previewKind:"reasoning",expanded:l,isActive:c,previewText:p,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:o,defaultPreview:p,isActive:c,config:t??{}})});if(!i)return r.append(d,T),Rr(r,e,t,"reasoning");let _=x("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");_.style.display=l?"":"none";let k=o.chunks.join(""),Q=x("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Q.textContent=k||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),_.appendChild(Q),Gd({expanded:l,header:d,toggleIcon:M,content:_,collapsedPreview:T,iconColor:Y}),r.append(d,T,_),Rr(r,e,t,"reasoning")};Qe();ss();Tt();var US=e=>{if(e==null)return!0;if(typeof e=="string"){if(!e.trim())return!0;try{return US(JSON.parse(e))}catch{return!1}}return typeof e=="object"&&Object.keys(e).length===0},pI=e=>{if(e!==null&&typeof e=="object")return!0;if(typeof e!="string")return!1;try{let t=JSON.parse(e);return t!==null&&typeof t=="object"}catch{return!1}};function VS(e,t,n){let o=t.toolCall;if(!o)return;let r=n.toolCall??{},s=(l,c)=>{let p=X("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":l.toLowerCase()},style:{backgroundColor:r.codeBlockBackgroundColor,borderColor:r.codeBlockBorderColor,borderWidth:r.codeBlockBorderColor?"1px":void 0}}),d=X("div",{className:"persona-tool-detail-label",text:l,style:{color:r.labelTextColor}}),g=Xi(c),f=X("pre",{className:`persona-tool-detail-value${pI(c)?" persona-tool-detail-code":""}`,text:g,attrs:g.length>420||g.split(`
40
+ `).length>7?{tabindex:"0","aria-label":`${l} content`}:{},style:{color:r.codeBlockTextColor??r.contentTextColor}}),h=X("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${l.toLowerCase()}`,title:`Copy ${l.toLowerCase()}`}}),y=ue("copy",14,"currentColor",1.7);y&&h.appendChild(y),p.append(d,f,h),e.appendChild(p)};US(o.args)||s("Request",o.args);let i=o.status==="complete"&&o.result!==void 0?o.result:o.chunks?.join("");i!==void 0&&(typeof i!="string"||i.trim())&&s("Response",i),o.success===!1&&e.appendChild(X("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var Am=new WeakMap;async function jS(e){let t=e.closest("[data-persona-tool-detail]"),n=t?.querySelector("pre");if(!n)return;let o=`Copy ${t?.getAttribute("data-persona-tool-detail")}`;clearTimeout(Am.get(e));try{await navigator.clipboard.writeText(n.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let r=ue("check",14,"currentColor",2);r&&e.replaceChildren(r)}catch{e.setAttribute("aria-label","Copy failed \u2014 try again"),e.title="Copy failed \u2014 try again"}Am.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",o),e.title=o;let r=ue("copy",14,"currentColor",1.7);r&&e.replaceChildren(r),Am.delete(e)},1800))}Qe();vo();ss();var qS=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?"currentColor":"var(--persona-primary, #171717)"),uI=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
41
41
  `);let r=Xi(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
42
- `):""},wm=(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)"},lI=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??kr.collapsedMode,s=n?.success===!1?n.error||"Tool failed":aI(e,o?.previewMaxLines??kr.previewMaxLines),i=n?fs(t,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:Rb(n):"";if(!n)return{summary:i,previewText:s,isActive:!1};let l=n.status!=="complete",c=t?.toolCall??{},p=i;return r==="tool-name"?p=n.name?.trim()||i:r==="tool-preview"&&s&&(p=s),l&&c.activeTextTemplate?p=wg(n,c.activeTextTemplate,p):!l&&c.completeTextTemplate&&(p=wg(n,c.completeTextTemplate,p)),n.success===!1?p+=" \xB7 Failed":n.superseded&&(p+=" \xB7 Approved, ran again below"),{summary:p,previewText:s,isActive:l}},Sm=(e,t,n,o)=>{Kd(e,t,{stateSet:n,previewKind:"tool",iconColor:$S(o?.toolCall??{},t.classList.contains("persona-activity-row"))})},Am=(e,t,n=new Set)=>{t=Gd(t,"tool");let o=e.toolCall,r=t?.toolCall??{},s=Vd("persona-tool-bubble",e.id);if(r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),s.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow)",!o)return Rr(s,e,t,"tool");let i=t?.features?.toolCallDisplay??{},l=i.expandable??kr.expandable,c=l&&n.has(e.id),{summary:p,previewText:d,isActive:g}=lI(e,t),f=jd({expandable:l,expanded:c,bubbleType:"tool"});r.headerBackgroundColor&&(f.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(f.style.paddingLeft=r.headerPaddingX,f.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(f.style.paddingTop=r.headerPaddingY,f.style.paddingBottom=r.headerPaddingY);let h=x("div","persona-flex persona-flex-col persona-text-left"),y=x("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(y.style.color=r.headerTextColor);let v=String(o.startedAt??Date.now()),C=()=>{let T=x("span","");return T.setAttribute("data-tool-elapsed",v),T.textContent=cl(o),T},A=r.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:p,previewText:d,collapsedMode:i.collapsedMode??kr.collapsedMode,isActive:g,config:t??{},elapsed:cl(o),createElapsedElement:C});typeof A=="string"&&A.trim()?(y.textContent=A,h.appendChild(y)):A instanceof HTMLElement?h.appendChild(A):(y.textContent=p,h.appendChild(y));let L=i.loadingAnimation??kr.loadingAnimation,I=r.activeTextTemplate,H=r.completeTextTemplate,_=g?I:H,V=A instanceof HTMLElement,te=(T,B)=>{y.textContent="";let P=o.name?.trim()||"tool",Q=nd(T,P),U=0;for(let de of Q){let pe=de.styles.length>0?(()=>{let ge=x("span",de.styles.map(ke=>`persona-tool-text-${ke}`).join(" "));return y.appendChild(ge),ge})():y;if(de.isDuration&&g)pe.appendChild(C());else{let ge=de.isDuration?cl(o):de.text;B?U=Ma(pe,ge,U):pe.appendChild(document.createTextNode(ge))}}};if(!V)if(g&&L!=="none"){let T=r.loadingAnimationDuration??2e3;if(y.setAttribute("data-preserve-animation","true"),L==="pulse")y.classList.add("persona-tool-loading-pulse"),y.style.setProperty("--persona-tool-anim-duration",`${T}ms`),_&&te(_,!1);else if(y.classList.add(`persona-tool-loading-${L}`),y.style.setProperty("--persona-tool-anim-duration",`${T}ms`),L==="shimmer-color"&&(r.loadingAnimationColor&&y.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&y.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),_)te(_,!0);else{let B=y.textContent||p;y.textContent="",Ma(y,B,0)}}else _&&te(_,!1);let W=$S(r,fs(t,"tool")==="row"),j=da(f,h,{expandable:l,expanded:c,iconColor:W,metaGap:!0}),Y=qd({bubble:s,previewKind:"tool",expanded:c,isActive:g,previewText:d,activePreview:i.activePreview,activeMinHeight:i.activeMinHeight,renderPreview:()=>r.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:d,isActive:g,config:t??{}})});if(!l)return s.append(f,Y),Rr(s,e,t,"tool");let E=x("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(E.style.display=c?"":"none",r.contentBackgroundColor&&(E.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(E.style.color=r.contentTextColor),r.contentPaddingX&&(E.style.paddingLeft=r.contentPaddingX,E.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(E.style.paddingTop=r.contentPaddingY,E.style.paddingBottom=r.contentPaddingY),t.future?.v5Defaults===!0)NS(E,e,t);else{if(o.name){let T=x("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?T.style.color=r.contentTextColor:r.headerTextColor&&(T.style.color=r.headerTextColor),T.textContent=o.name,E.appendChild(T)}if(o.args!==void 0){let T=x("div","persona-space-y-1"),B=x("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(B.style.color=r.labelTextColor),B.textContent="Arguments";let P=x("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");P.style.fontSize="0.75rem",P.style.lineHeight="1rem",wm(P,r),P.textContent=Xi(o.args),T.append(B,P),E.appendChild(T)}if(o.chunks&&o.chunks.length){let T=x("div","persona-space-y-1"),B=x("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(B.style.color=r.labelTextColor),B.textContent="Activity";let P=x("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");P.style.fontSize="0.75rem",P.style.lineHeight="1rem",wm(P,r),P.textContent=o.chunks.join(""),T.append(B,P),E.appendChild(T)}if(o.success===!1&&E.appendChild(X("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),o.status==="complete"&&o.result!==void 0){let T=x("div","persona-space-y-1"),B=x("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(B.style.color=r.labelTextColor),B.textContent="Result";let P=x("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");P.style.fontSize="0.75rem",P.style.lineHeight="1rem",wm(P,r),P.textContent=Xi(o.result),T.append(B,P),E.appendChild(T)}if(o.status==="complete"&&typeof o.duration=="number"){let T=x("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(T.style.color=r.contentTextColor),T.textContent=`Duration: ${o.duration}ms`,E.appendChild(T)}}return zd({expanded:c,header:f,toggleIcon:j,content:E,collapsedPreview:Y,iconColor:W}),s.append(f,Y,E),Rr(s,e,t,"tool")};gl();ea();ss();ln();var{setLoader:w$,load:cI,provide:S$,getSync:dI}=it({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")});var US=cI;var VS=dI;ei();ln();var{setLoader:M$,load:pI}=it({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var xm=pI;ln();var Mm=class{constructor(){this.components=new Map;this.#e=new Map}#e;register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.#e.set(t,o):this.#e.delete(t)}unregister(t){this.components.delete(t),this.#e.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.#e.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.#e.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},tr=new Mm;hg();var Em=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:I$,load:uI,provide:R$,getSync:gI}=it({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),Ea=null,Ep=new Set,jS=e=>{if(Ea)return Ea;Ea=e,e.initArtifactsUi({componentRegistry:tr});for(let o of Em)tr.has(o)||tr.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Yo();t?e.__provideMarkdownParsers(t):il(()=>{let o=Yo();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>Gc());let n=[...Ep];Ep.clear();for(let o of n)try{o()}catch{}return e};var Tp=()=>uI().then(jS);var Wr=()=>{if(Ea)return Ea;let e=gI();return e?jS(e):null},Tm=e=>Ea?()=>{}:(Ep.add(e),()=>{Ep.delete(e)});function Dn(e){return e?.features?.artifacts?.enabled===!0}function qS(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"),!Dn(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function fI(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")}var zS=["panel","seamless","detached"];function Pm(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&zS.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function km(e){return!e||!Dn(e)?!1:Pm(e)==="detached"}function Kl(e,t){if(!Dn(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"),fI(e),qS(e,t);return}let n=t.features?.artifacts?.layout,o=Pm(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),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 r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let i=[[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[l,c]of i){let p=l?.trim();p?e.style.setProperty(c,p):e.style.removeProperty(c)}qS(e,t)}function Gl(e,t){for(let l of zS)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Dn(t))return;let n=t.features?.artifacts?.layout,o=Pm(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let i=n?.chatShadow?.trim();i&&e.style.setProperty("--persona-artifact-chat-shadow",i)}function KS(e,t){return!t||!Dn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}Yi();Yi();var mI=new Set(["__proto__","prototype","constructor"]),hI=new Set(["collapsed","card","panel","inline"]),GS=new Set(["markdown","component"]),yI=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,gi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),kp=e=>!mI.has(e),Lm=e=>typeof e=="string"&&hI.has(e),fi=e=>Object.keys(e).length>0;function nr(e,t,n,o){e.push({path:t,code:n,message:o})}var bI="Ignored because this key is not part of the persisted preference schema.",Pp="Ignored an unsupported value.",vI="Expected collapsed, panel, or inline.",CI='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',YS={kind:"mode",message:Pp},Ta={kind:"string",message:"Expected a CSS length string."},Or={kind:"boolean"},wI={paneWidth:Ta,paneMaxWidth:Ta,paneMinWidth:Ta,expandedPanelWidth:Ta,resizableMinWidth:Ta,resizableMaxWidth:Ta,expandLauncherPanelWhenOpen:Or,resizable:Or},SI={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Or,showReasoning:Or,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Pp},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Pp},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Pp},expandable:Or,grouped:Or}},reasoningDisplay:{kind:"object",children:{expandable:Or,activePreview:Or}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:YS,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:YS,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:GS,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:GS}}},filePreview:{kind:"object",children:{enabled:Or}},layout:{kind:"object",children:wI}}}}};function XS(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:nr(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:nr(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:nr(o,n,"invalid_value",t.message);case"mode":return Lm(e)?Qn(e):nr(o,n,"invalid_value",t.message);case"modeMap":{if(!gi(e))return nr(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[i,l]of Object.entries(e)){let c=r?i:ti(i);kp(i)&&(r?r.has(i):yI.test(c))?Lm(l)?s[c]=Qn(l):nr(o,`${n}.${i}`,"invalid_value",vI):nr(o,`${n}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":CI)}return fi(s)?s:void 0}case"object":{if(t.bareMode&&Lm(e))return Qn(e);if(!gi(e))return nr(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!kp(l)||!r.includes(l))&&nr(o,s(l),"unknown_key",bI);let i={};for(let l of r){let c=t.children[l],p=XS(e[l],c,s(l),o);if(c.deprecated&&e[l]!==void 0&&nr(o,s(l),"deprecated_key",c.deprecated),p===void 0)continue;let d=c.alias??l,g=i[d];i[d]=gi(g)&&gi(p)?{...g,...p}:p}return fi(i)?i:void 0}}}function QS(e){let t=[];return{preferences:(e===null?void 0:XS(e,SI,"",t))??{},issues:t}}function Pa(e){if(Array.isArray(e))return e.map(Pa);if(!gi(e))return e;let t={};for(let[n,o]of Object.entries(e))kp(n)&&o!==void 0&&(t[n]=Pa(o));return t}function JS(e,t){let n=Pa(e);for(let[o,r]of Object.entries(t)){if(!kp(o)||r===void 0)continue;let s=n[o];n[o]=gi(s)&&gi(r)?JS(s,r):Pa(r)}return n}function AI(e){let t={},n;for(let r of e){let s=QS(r).preferences;n=ZS(n,s.artifacts?.display),t=JS(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function xI(e,t){if(t===void 0)return e===void 0?void 0:Pa(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...fi(r)?{byMediaType:r}:{}};return fi(s)?s:void 0}function ZS(e,t){if(t===void 0)return e===void 0?void 0:Pa(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=xI(n.files,t.files),i={...o?{default:o}:{},...fi(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return fi(i)?i:void 0}function eA(e={},t){let n=AI(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let i=ZS(r.display,n.artifacts.display);i!==void 0&&(s.display=i)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Lp(e){let t=e.preferences;return!t||!fi(t)?e:{...e,features:eA(e.features??{},[t])}}function MI(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 EI(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 TI(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function PI(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Hm(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function tA(e,t,n,o,r,s,i=200){let l=MI(r,200),c=PI(t,n,o,i);c=Math.max(l,c);let p=EI(s);return p!==null&&(c=Math.min(c,p)),TI(e,l,c)}ln();var{setLoader:F$,load:kI,provide:$$,getSync:LI}=it({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")});var nA=kI;var oA=LI;var Im=class{#e=new Map;register(t){this.#e.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.#e.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.#e.get(t);n&&(n.onUnregister?.(),this.#e.delete(t))}getAll(){return Array.from(this.#e.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,i)=>(i.priority??0)-(s.priority??0))}clear(){this.#e.forEach(t=>t.onUnregister?.()),this.#e.clear()}},Hp=new Im;bo();bo();ia();Gg();var rA=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),HI=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),sA=(e,t,n)=>{if(!rA(e)||!rA(t)||HI.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=sA(e[r],t[r],s)}return o};function Ip(e,t){let n=md(ii),o=Rv(e,t,n),r=zg(Wv(sA(e,t,""),n,o),o);return Xg(yl(r),Bv(e,t))}ia();var iA=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(i=>{try{i(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var II=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},RI=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Rp=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=II(e),n=RI(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Rm=e=>typeof e=="string"?e:e==null?"":String(e),ka={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Rm(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Rm(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Rm(n.text)}}},aA=e=>Array.isArray(e)?e.map(t=>String(t)):[],Wp=e=>{let t=new Set(aA(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(aA(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.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 l=i?e.parsers.reduce((p,d)=>p||d?.({text:i,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let c={action:l,message:s.message};e.emit("action:detected",c);for(let p of e.handlers)if(p)try{let d=()=>{e.emit("action:resubmit",c)},g=p(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:d});if(!g)continue;if(g.handled){let f=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:f,resubmit:g.resubmit}}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:n}};var WI=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},OI=e=>e.map(t=>({...t,streaming:!1})),BI=e=>e.map(t=>({...t,status:"complete"})),Wm=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?WI(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?OI(n.messages):void 0,artifacts:n.artifacts?BI(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var _I=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")},lA=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(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return _I(e)},DI=async(e,t)=>{let n=await lA(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await lA(`${e}\0${t}`)}`}};var cA=(e,t,n)=>{let o="",r="",s="",i=!1,l=!1,c=0,p=null,d=null,g=new Set,f=()=>{if(n||i)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return i=!0,null}},h=()=>{let W=f();if(!W)return p;try{return W.getItem(o)}catch{return i=!0,p}},y=(W,j)=>{if(l||W===p)return;let Y=p;p=W,c+=1;let E={previousToken:Y,token:W,source:j,revision:c};for(let T of g)T(E)},v=W=>{l||W.key!==null&&W.key!==o||y(W.key===null?null:W.newValue??null,"external")},C=(async()=>{let W=await DI(e,t);o=W.storageKey,r=W.leaseKey,s=W.lockName,p=h(),!n&&typeof window<"u"&&window.addEventListener("storage",v)})(),A=W=>new Promise(j=>setTimeout(j,W)),L=()=>{let W=f();if(!W)return null;try{let j=W.getItem(r);if(!j)return null;let Y=JSON.parse(j);return typeof Y?.expiresAt=="number"&&typeof Y?.ownerNonce=="string"?Y:null}catch{return null}},I=W=>{let j=f();if(j)try{L()?.ownerNonce===W&&j.removeItem(r)}catch{}},H=new Set,_=W=>l?Promise.reject(new Error("Visitor store destroyed before its first init could start")):W(),V=W=>new Promise(j=>{let Y=setTimeout(E,W);function E(){clearTimeout(Y),H.delete(E),window.removeEventListener("storage",T),j()}function T(B){(B.key===null||B.key===r)&&E()}H.add(E),window.addEventListener("storage",T)}),te=async W=>{let j=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,Y=Date.now()+15e3;for(;!l&&Date.now()<Y;){let E=f();if(!E)break;let T=Date.now(),B=L();if(B&&B.expiresAt>T&&B.ownerNonce!==j){await V(Math.min(B.expiresAt-T,500));continue}try{E.setItem(r,JSON.stringify({ownerNonce:j,expiresAt:T+1e4}))}catch{i=!0;break}if(await A(20+Math.random()*40),L()?.ownerNonce!==j){await V(500);continue}d=j;try{return await _(W)}finally{d=null,I(j)}}return _(W)};return{ready:C,async get(){return await C,y(h(),"external"),p},async set(W){await C;let j=f();if(j)try{j.setItem(o,W)}catch{i=!0}y(W,"local")},async clear(){await C;let W=f();if(W)try{W.removeItem(o)}catch{i=!0}y(null,"local")},revision(){return c},subscribe(W){return g.add(W),()=>{g.delete(W)}},async withFirstInitLock(W){await C;let j=globalThis.navigator?.locks;return j?.request?j.request(s,()=>_(W)):f()?te(W):_(W)},matches(W,j,Y){return W===e&&j===t&&Y===n},destroy(){l=!0,g.clear(),typeof window<"u"&&window.removeEventListener("storage",v),d&&I(d);for(let W of[...H])W()}}};ln();var{setLoader:Z$,load:NI}=it({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var dA=NI;var FI=null;function pA(){return FI}import{parse as $I,STR as UI,OBJ as VI}from"partial-json";function jI(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function qI(e,t){if(!jI(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 Om(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=$I(n,UI|VI),s=qI(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function zI(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}Xe();function Bm(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=tr.get(e.component);if(!s){if(Em.includes(e.component)){Tp().catch(()=>{});let l=x("div","persona-w-full");return l.setAttribute("data-persona-artifact-pending","true"),l}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let i={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function KI(){let e=Om();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function uA(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 Op(e){let t=uA(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function _m(e){let t=uA(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var GI=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Dm(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:c=!0,ratingLabels:p=GI}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-csat",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Customer satisfaction feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=o,h.appendChild(y);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=r,h.appendChild(v),f.appendChild(h);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-csat",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Satisfaction rating from 1 to 5");let A=[];for(let V=1;V<=5;V++){let te=document.createElement("button");te.type="button",te.className="persona-feedback-rating-btn persona-feedback-star-btn",te.setAttribute("role","radio"),te.setAttribute("aria-checked","false"),te.setAttribute("aria-label",`${V} star${V>1?"s":""}: ${p[V-1]}`),te.title=p[V-1],te.dataset.rating=String(V),te.innerHTML=`
42
+ `):""},xm=(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)"},gI=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??Pr.collapsedMode,s=n?.success===!1?n.error||"Tool failed":uI(e,o?.previewMaxLines??Pr.previewMaxLines),i=n?fs(t,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:Bb(n):"";if(!n)return{summary:i,previewText:s,isActive:!1};let l=n.status!=="complete",c=t?.toolCall??{},p=i;return r==="tool-name"?p=n.name?.trim()||i:r==="tool-preview"&&s&&(p=s),l&&c.activeTextTemplate?p=xg(n,c.activeTextTemplate,p):!l&&c.completeTextTemplate&&(p=xg(n,c.completeTextTemplate,p)),n.success===!1?p+=" \xB7 Failed":n.superseded&&(p+=" \xB7 Approved, ran again below"),{summary:p,previewText:s,isActive:l}},Em=(e,t,n,o)=>{Yd(e,t,{stateSet:n,previewKind:"tool",iconColor:qS(o?.toolCall??{},t.classList.contains("persona-activity-row"))})},Mm=(e,t,n=new Set)=>{t=Xd(t,"tool");let o=e.toolCall,r=t?.toolCall??{},s=qd("persona-tool-bubble",e.id);if(r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),s.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow)",!o)return Rr(s,e,t,"tool");let i=t?.features?.toolCallDisplay??{},l=i.expandable??Pr.expandable,c=l&&n.has(e.id),{summary:p,previewText:d,isActive:g}=gI(e,t),f=zd({expandable:l,expanded:c,bubbleType:"tool"});r.headerBackgroundColor&&(f.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(f.style.paddingLeft=r.headerPaddingX,f.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(f.style.paddingTop=r.headerPaddingY,f.style.paddingBottom=r.headerPaddingY);let h=x("div","persona-flex persona-flex-col persona-text-left"),y=x("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(y.style.color=r.headerTextColor);let b=String(o.startedAt??Date.now()),C=()=>{let T=x("span","");return T.setAttribute("data-tool-elapsed",b),T.textContent=cl(o),T},A=r.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:p,previewText:d,collapsedMode:i.collapsedMode??Pr.collapsedMode,isActive:g,config:t??{},elapsed:cl(o),createElapsedElement:C});typeof A=="string"&&A.trim()?(y.textContent=A,h.appendChild(y)):A instanceof HTMLElement?h.appendChild(A):(y.textContent=p,h.appendChild(y));let L=i.loadingAnimation??Pr.loadingAnimation,I=r.activeTextTemplate,H=r.completeTextTemplate,B=g?I:H,V=A instanceof HTMLElement,te=(T,_)=>{y.textContent="";let k=o.name?.trim()||"tool",Q=rd(T,k),U=0;for(let de of Q){let pe=de.styles.length>0?(()=>{let ge=x("span",de.styles.map(Pe=>`persona-tool-text-${Pe}`).join(" "));return y.appendChild(ge),ge})():y;if(de.isDuration&&g)pe.appendChild(C());else{let ge=de.isDuration?cl(o):de.text;_?U=Ea(pe,ge,U):pe.appendChild(document.createTextNode(ge))}}};if(!V)if(g&&L!=="none"){let T=r.loadingAnimationDuration??2e3;if(y.setAttribute("data-preserve-animation","true"),L==="pulse")y.classList.add("persona-tool-loading-pulse"),y.style.setProperty("--persona-tool-anim-duration",`${T}ms`),B&&te(B,!1);else if(y.classList.add(`persona-tool-loading-${L}`),y.style.setProperty("--persona-tool-anim-duration",`${T}ms`),L==="shimmer-color"&&(r.loadingAnimationColor&&y.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&y.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),B)te(B,!0);else{let _=y.textContent||p;y.textContent="",Ea(y,_,0)}}else B&&te(B,!1);let W=qS(r,fs(t,"tool")==="row"),j=da(f,h,{expandable:l,expanded:c,iconColor:W,metaGap:!0}),Y=Kd({bubble:s,previewKind:"tool",expanded:c,isActive:g,previewText:d,activePreview:i.activePreview,activeMinHeight:i.activeMinHeight,renderPreview:()=>r.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:d,isActive:g,config:t??{}})});if(!l)return s.append(f,Y),Rr(s,e,t,"tool");let M=x("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(M.style.display=c?"":"none",r.contentBackgroundColor&&(M.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(M.style.color=r.contentTextColor),r.contentPaddingX&&(M.style.paddingLeft=r.contentPaddingX,M.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(M.style.paddingTop=r.contentPaddingY,M.style.paddingBottom=r.contentPaddingY),t.future?.v5Defaults===!0)VS(M,e,t);else{if(o.name){let T=x("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?T.style.color=r.contentTextColor:r.headerTextColor&&(T.style.color=r.headerTextColor),T.textContent=o.name,M.appendChild(T)}if(o.args!==void 0){let T=x("div","persona-space-y-1"),_=x("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(_.style.color=r.labelTextColor),_.textContent="Arguments";let k=x("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");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",xm(k,r),k.textContent=Xi(o.args),T.append(_,k),M.appendChild(T)}if(o.chunks&&o.chunks.length){let T=x("div","persona-space-y-1"),_=x("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(_.style.color=r.labelTextColor),_.textContent="Activity";let k=x("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");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",xm(k,r),k.textContent=o.chunks.join(""),T.append(_,k),M.appendChild(T)}if(o.success===!1&&M.appendChild(X("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),o.status==="complete"&&o.result!==void 0){let T=x("div","persona-space-y-1"),_=x("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(_.style.color=r.labelTextColor),_.textContent="Result";let k=x("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");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",xm(k,r),k.textContent=Xi(o.result),T.append(_,k),M.appendChild(T)}if(o.status==="complete"&&typeof o.duration=="number"){let T=x("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(T.style.color=r.contentTextColor),T.textContent=`Duration: ${o.duration}ms`,M.appendChild(T)}}return Gd({expanded:c,header:f,toggleIcon:j,content:M,collapsedPreview:Y,iconColor:W}),s.append(f,Y,M),Rr(s,e,t,"tool")};gl();ea();ss();ln();var{setLoader:P$,load:fI,provide:L$,getSync:mI}=it({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")});var zS=fI;var KS=mI;ei();ln();var{setLoader:R$,load:hI}=it({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var Tm=hI;ln();var km=class{constructor(){this.components=new Map;this.#e=new Map}#e;register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.#e.set(t,o):this.#e.delete(t)}unregister(t){this.components.delete(t),this.#e.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.#e.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.#e.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},tr=new km;vg();var Pm=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:F$,load:yI,provide:$$,getSync:bI}=it({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),Ma=null,kp=new Set,GS=e=>{if(Ma)return Ma;Ma=e,e.initArtifactsUi({componentRegistry:tr});for(let o of Pm)tr.has(o)||tr.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Yo();t?e.__provideMarkdownParsers(t):il(()=>{let o=Yo();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>Xc());let n=[...kp];kp.clear();for(let o of n)try{o()}catch{}return e};var Pp=()=>yI().then(GS);var Wr=()=>{if(Ma)return Ma;let e=bI();return e?GS(e):null},Lm=e=>Ma?()=>{}:(kp.add(e),()=>{kp.delete(e)});function Dn(e){return e?.features?.artifacts?.enabled===!0}function YS(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"),!Dn(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function vI(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")}var XS=["panel","seamless","detached"];function Hm(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&XS.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Im(e){return!e||!Dn(e)?!1:Hm(e)==="detached"}function Kl(e,t){if(!Dn(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"),vI(e),YS(e,t);return}let n=t.features?.artifacts?.layout,o=Hm(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),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 r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let i=[[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[l,c]of i){let p=l?.trim();p?e.style.setProperty(c,p):e.style.removeProperty(c)}YS(e,t)}function Gl(e,t){for(let l of XS)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Dn(t))return;let n=t.features?.artifacts?.layout,o=Hm(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let i=n?.chatShadow?.trim();i&&e.style.setProperty("--persona-artifact-chat-shadow",i)}function QS(e,t){return!t||!Dn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}Yi();Yi();var CI=new Set(["__proto__","prototype","constructor"]),wI=new Set(["collapsed","card","panel","inline"]),JS=new Set(["markdown","component"]),SI=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,gi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Hp=e=>!CI.has(e),Rm=e=>typeof e=="string"&&wI.has(e),fi=e=>Object.keys(e).length>0;function nr(e,t,n,o){e.push({path:t,code:n,message:o})}var AI="Ignored because this key is not part of the persisted preference schema.",Lp="Ignored an unsupported value.",xI="Expected collapsed, panel, or inline.",EI='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',ZS={kind:"mode",message:Lp},Ta={kind:"string",message:"Expected a CSS length string."},Or={kind:"boolean"},MI={paneWidth:Ta,paneMaxWidth:Ta,paneMinWidth:Ta,expandedPanelWidth:Ta,resizableMinWidth:Ta,resizableMaxWidth:Ta,expandLauncherPanelWhenOpen:Or,resizable:Or},TI={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Or,showReasoning:Or,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Lp},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Lp},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Lp},expandable:Or,grouped:Or}},reasoningDisplay:{kind:"object",children:{expandable:Or,activePreview:Or}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:ZS,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:ZS,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:JS,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:JS}}},filePreview:{kind:"object",children:{enabled:Or}},layout:{kind:"object",children:MI}}}}};function eA(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:nr(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:nr(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:nr(o,n,"invalid_value",t.message);case"mode":return Rm(e)?Jn(e):nr(o,n,"invalid_value",t.message);case"modeMap":{if(!gi(e))return nr(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[i,l]of Object.entries(e)){let c=r?i:ti(i);Hp(i)&&(r?r.has(i):SI.test(c))?Rm(l)?s[c]=Jn(l):nr(o,`${n}.${i}`,"invalid_value",xI):nr(o,`${n}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":EI)}return fi(s)?s:void 0}case"object":{if(t.bareMode&&Rm(e))return Jn(e);if(!gi(e))return nr(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!Hp(l)||!r.includes(l))&&nr(o,s(l),"unknown_key",AI);let i={};for(let l of r){let c=t.children[l],p=eA(e[l],c,s(l),o);if(c.deprecated&&e[l]!==void 0&&nr(o,s(l),"deprecated_key",c.deprecated),p===void 0)continue;let d=c.alias??l,g=i[d];i[d]=gi(g)&&gi(p)?{...g,...p}:p}return fi(i)?i:void 0}}}function tA(e){let t=[];return{preferences:(e===null?void 0:eA(e,TI,"",t))??{},issues:t}}function ka(e){if(Array.isArray(e))return e.map(ka);if(!gi(e))return e;let t={};for(let[n,o]of Object.entries(e))Hp(n)&&o!==void 0&&(t[n]=ka(o));return t}function nA(e,t){let n=ka(e);for(let[o,r]of Object.entries(t)){if(!Hp(o)||r===void 0)continue;let s=n[o];n[o]=gi(s)&&gi(r)?nA(s,r):ka(r)}return n}function kI(e){let t={},n;for(let r of e){let s=tA(r).preferences;n=oA(n,s.artifacts?.display),t=nA(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function PI(e,t){if(t===void 0)return e===void 0?void 0:ka(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...fi(r)?{byMediaType:r}:{}};return fi(s)?s:void 0}function oA(e,t){if(t===void 0)return e===void 0?void 0:ka(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=PI(n.files,t.files),i={...o?{default:o}:{},...fi(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return fi(i)?i:void 0}function rA(e={},t){let n=kI(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let i=oA(r.display,n.artifacts.display);i!==void 0&&(s.display=i)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Ip(e){let t=e.preferences;return!t||!fi(t)?e:{...e,features:rA(e.features??{},[t])}}function LI(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 HI(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 II(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function RI(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Wm(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function sA(e,t,n,o,r,s,i=200){let l=LI(r,200),c=RI(t,n,o,i);c=Math.max(l,c);let p=HI(s);return p!==null&&(c=Math.min(c,p)),II(e,l,c)}ln();var{setLoader:G$,load:WI,provide:Y$,getSync:OI}=it({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")});var iA=WI;var aA=OI;var Om=class{#e=new Map;register(t){this.#e.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.#e.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.#e.get(t);n&&(n.onUnregister?.(),this.#e.delete(t))}getAll(){return Array.from(this.#e.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,i)=>(i.priority??0)-(s.priority??0))}clear(){this.#e.forEach(t=>t.onUnregister?.()),this.#e.clear()}},Rp=new Om;vo();vo();ia();Qg();var lA=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_I=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),cA=(e,t,n)=>{if(!lA(e)||!lA(t)||_I.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=cA(e[r],t[r],s)}return o};function Wp(e,t){let n=yd(ii),o=Bv(e,t,n),r=Yg(Dv(cA(e,t,""),n,o),o);return Zg(yl(r),Fv(e,t))}ia();var dA=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(i=>{try{i(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var BI=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},DI=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Op=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=BI(e),n=DI(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},_m=e=>typeof e=="string"?e:e==null?"":String(e),Pa={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:_m(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=_m(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:_m(n.text)}}},pA=e=>Array.isArray(e)?e.map(t=>String(t)):[],_p=e=>{let t=new Set(pA(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(pA(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.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 l=i?e.parsers.reduce((p,d)=>p||d?.({text:i,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let c={action:l,message:s.message};e.emit("action:detected",c);for(let p of e.handlers)if(p)try{let d=()=>{e.emit("action:resubmit",c)},g=p(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:d});if(!g)continue;if(g.handled){let f=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:f,resubmit:g.resubmit}}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:n}};var NI=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},FI=e=>e.map(t=>({...t,streaming:!1})),$I=e=>e.map(t=>({...t,status:"complete"})),Bm=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?NI(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?FI(n.messages):void 0,artifacts:n.artifacts?$I(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var UI=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")},uA=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(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return UI(e)},VI=async(e,t)=>{let n=await uA(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await uA(`${e}\0${t}`)}`}};var gA=(e,t,n)=>{let o="",r="",s="",i=!1,l=!1,c=0,p=null,d=null,g=new Set,f=()=>{if(n||i)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return i=!0,null}},h=()=>{let W=f();if(!W)return p;try{return W.getItem(o)}catch{return i=!0,p}},y=(W,j)=>{if(l||W===p)return;let Y=p;p=W,c+=1;let M={previousToken:Y,token:W,source:j,revision:c};for(let T of g)T(M)},b=W=>{l||W.key!==null&&W.key!==o||y(W.key===null?null:W.newValue??null,"external")},C=(async()=>{let W=await VI(e,t);o=W.storageKey,r=W.leaseKey,s=W.lockName,p=h(),!n&&typeof window<"u"&&window.addEventListener("storage",b)})(),A=W=>new Promise(j=>setTimeout(j,W)),L=()=>{let W=f();if(!W)return null;try{let j=W.getItem(r);if(!j)return null;let Y=JSON.parse(j);return typeof Y?.expiresAt=="number"&&typeof Y?.ownerNonce=="string"?Y:null}catch{return null}},I=W=>{let j=f();if(j)try{L()?.ownerNonce===W&&j.removeItem(r)}catch{}},H=new Set,B=W=>l?Promise.reject(new Error("Visitor store destroyed before its first init could start")):W(),V=W=>new Promise(j=>{let Y=setTimeout(M,W);function M(){clearTimeout(Y),H.delete(M),window.removeEventListener("storage",T),j()}function T(_){(_.key===null||_.key===r)&&M()}H.add(M),window.addEventListener("storage",T)}),te=async W=>{let j=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,Y=Date.now()+15e3;for(;!l&&Date.now()<Y;){let M=f();if(!M)break;let T=Date.now(),_=L();if(_&&_.expiresAt>T&&_.ownerNonce!==j){await V(Math.min(_.expiresAt-T,500));continue}try{M.setItem(r,JSON.stringify({ownerNonce:j,expiresAt:T+1e4}))}catch{i=!0;break}if(await A(20+Math.random()*40),L()?.ownerNonce!==j){await V(500);continue}d=j;try{return await B(W)}finally{d=null,I(j)}}return B(W)};return{ready:C,async get(){return await C,y(h(),"external"),p},async set(W){await C;let j=f();if(j)try{j.setItem(o,W)}catch{i=!0}y(W,"local")},async clear(){await C;let W=f();if(W)try{W.removeItem(o)}catch{i=!0}y(null,"local")},revision(){return c},subscribe(W){return g.add(W),()=>{g.delete(W)}},async withFirstInitLock(W){await C;let j=globalThis.navigator?.locks;return j?.request?j.request(s,()=>B(W)):f()?te(W):B(W)},matches(W,j,Y){return W===e&&j===t&&Y===n},destroy(){l=!0,g.clear(),typeof window<"u"&&window.removeEventListener("storage",b),d&&I(d);for(let W of[...H])W()}}};ln();var{setLoader:aU,load:jI}=it({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var fA=jI;var qI=null;function mA(){return qI}import{parse as zI,STR as KI,OBJ as GI}from"partial-json";function YI(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function XI(e,t){if(!YI(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 Dm(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=zI(n,KI|GI),s=XI(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function QI(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}Qe();function Nm(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=tr.get(e.component);if(!s){if(Pm.includes(e.component)){Pp().catch(()=>{});let l=x("div","persona-w-full");return l.setAttribute("data-persona-artifact-pending","true"),l}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let i={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function JI(){let e=Dm();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function hA(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 Bp(e){let t=hA(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Fm(e){let t=hA(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var ZI=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function $m(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:c=!0,ratingLabels:p=ZI}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-csat",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Customer satisfaction feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=o,h.appendChild(y);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=r,h.appendChild(b),f.appendChild(h);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-csat",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Satisfaction rating from 1 to 5");let A=[];for(let V=1;V<=5;V++){let te=document.createElement("button");te.type="button",te.className="persona-feedback-rating-btn persona-feedback-star-btn",te.setAttribute("role","radio"),te.setAttribute("aria-checked","false"),te.setAttribute("aria-label",`${V} star${V>1?"s":""}: ${p[V-1]}`),te.title=p[V-1],te.dataset.rating=String(V),te.innerHTML=`
43
43
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
44
44
  <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>
45
45
  </svg>
46
- `,te.addEventListener("click",()=>{g=V,A.forEach((W,j)=>{let Y=j<V;W.classList.toggle("selected",Y),W.setAttribute("aria-checked",j===V-1?"true":"false")})}),A.push(te),C.appendChild(te)}f.appendChild(C);let L=null;if(c){let V=document.createElement("div");V.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),V.appendChild(L),f.appendChild(V)}let I=document.createElement("div");I.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=l,H.addEventListener("click",()=>{n?.(),d.remove()});let _=document.createElement("button");return _.type="button",_.className="persona-feedback-btn persona-feedback-btn-submit",_.textContent=i,_.addEventListener("click",async()=>{if(g===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}_.disabled=!0,_.textContent="Submitting...";try{let V=L?.value.trim()||void 0;await t(g,V),d.remove()}catch(V){_.disabled=!1,_.textContent=i,console.error("[CSAT Feedback] Failed to submit:",V)}}),I.appendChild(H),I.appendChild(_),f.appendChild(I),d.appendChild(f),d}function Nm(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:c=!0,lowLabel:p="Not likely",highLabel:d="Very likely"}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let f=null,h=document.createElement("div");h.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,y.appendChild(v);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,y.appendChild(C),h.appendChild(y);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-nps",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let I=document.createElement("span");I.className="persona-feedback-label-low",I.textContent=p;let H=document.createElement("span");H.className="persona-feedback-label-high",H.textContent=d,L.appendChild(I),L.appendChild(H);let _=document.createElement("div");_.className="persona-feedback-numbers";let V=[];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,V.forEach((B,P)=>{B.classList.toggle("selected",P===E),B.setAttribute("aria-checked",P===E?"true":"false")})}),V.push(T),_.appendChild(T)}A.appendChild(L),A.appendChild(_),h.appendChild(A);let te=null;if(c){let E=document.createElement("div");E.className="persona-feedback-comment-container",te=document.createElement("textarea"),te.className="persona-feedback-comment",te.placeholder=s,te.rows=3,te.setAttribute("aria-label","Additional comments"),E.appendChild(te),h.appendChild(E)}let W=document.createElement("div");W.className="persona-feedback-actions";let j=document.createElement("button");j.type="button",j.className="persona-feedback-btn persona-feedback-btn-skip",j.textContent=l,j.addEventListener("click",()=>{n?.(),g.remove()});let Y=document.createElement("button");return Y.type="button",Y.className="persona-feedback-btn persona-feedback-btn-submit",Y.textContent=i,Y.addEventListener("click",async()=>{if(f===null){_.classList.add("persona-feedback-shake"),setTimeout(()=>_.classList.remove("persona-feedback-shake"),500);return}Y.disabled=!0,Y.textContent="Submitting...";try{let E=te?.value.trim()||void 0;await t(f,E),g.remove()}catch(E){Y.disabled=!1,Y.textContent=i,console.error("[NPS Feedback] Failed to submit:",E)}}),W.appendChild(j),W.appendChild(Y),h.appendChild(W),g.appendChild(h),g}var La="persona-chat-history",QI=30*1e3,JI=641,Ha="data-persona-composer-reason",ZI={"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 eR(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let s=ZI[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function Bp(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 tR(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 nR(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Fm=e=>!e||typeof e!="object"?{}:{...e},hA=e=>e.map(t=>({...t,streaming:!1})),yA=(e,t,n)=>{let o=e?.markdown?Xd(e.markdown):null,r=Sf(e?.sanitize);e?.postprocessMessage&&r&&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 s=!1,i=l=>{let c=l.text??"",p=l.message.rawContent??null;if(t){let f=t.process({text:c,raw:p??c,message:l.message,streaming:l.streaming});f!==null&&(c=f.text,f.persist||(l.message.__skipPersist=!0),f.resubmit&&!l.streaming&&n&&n())}let d=Yo()!==null,g;if(e?.postprocessMessage){let f=e.postprocessMessage({...l,text:c,raw:p??l.text??""});g=r?r(f):f}else if(o){let f=l.streaming?TC(c):c,h=o(f);g=r&&d?r(h):h}else g=ms(c);return g};return l=>{try{return i(l)}catch(c){return s||(s=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",c)),ms(l.text??"")}}};function bA(e){let t=x("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",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,i=ue(n,o,r,s);if(i&&t.appendChild(i),e?.label){let l=x("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var oR=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},rR=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:oR(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),$m=(e,t,n)=>{if(e==null)throw new 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 o=yl(t),r=new Set,s=new Set,i=mC((a,u)=>{xn.delete(a);let m=Array.from(Me.querySelectorAll("[data-message-id]")).find(b=>b.dataset.messageId===a);m&&(u==="tool"?Sm(a,m,r,o):bm(a,m,s))}),l=new Map,c=()=>{Tv({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};c();let p=o.features;o=Lp(o);let d=Hp.getForInstance(o.plugins),g=lC(e),f=[],h=!1,y=_S(()=>o),v=null,C=null,A=null,L=!1,I=null,H=a=>{v=a,a.initApprovalUi({webMcpToolTitle:Gi});let u=a.createBuiltInApprovalPlugin(l);C=u.plugin,A=u.teardown},_=()=>{if(v)return v;let a=VS();return a?(H(a),a):(US().then(u=>{L||v||(H(u),I?.())}).catch(()=>{}),null)},V=!1,te=!1,W=null,j=(a,u,m,b)=>{if(!a.querySelector("[data-tv-form]"))return;let w=oA();if(w){w.enhanceWithForms(a,u,m,b);return}nA().then(()=>{V||te||!W||(te=!0,W())}).catch(()=>{})};o.components&&tr.registerAll(o.components);let Y=iA(),T=o.persistState===!1?null:o.storageAdapter??Wm(),B=!!o.clientToken&&typeof o.reconnectStream!="function",P={},Q=null,U,de=new Promise(a=>{U=a}),pe=()=>{},ge=new Promise(a=>{pe=a}),ke,xe=!1,Le=a=>{if(o.onStateLoaded)try{let u=o.onStateLoaded(a);if(u&&typeof u=="object"&&"state"in u){let{state:m,open:b}=u;return b&&(xe=!0),m}return u}catch(u){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return a};if(T?.load)try{let a=T.load();if(a&&typeof a.then=="function")Q=a.then(u=>Le(u??{messages:[],metadata:{}}));else{let m=Le(a??{messages:[],metadata:{}});m.metadata&&(P=Fm(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null}),ke=m.draft}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=Le({messages:[],metadata:{}});a.messages?.length&&(o={...o,initialMessages:a.messages})}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}Q||U();let mt=()=>P,Ve=a=>{P=a({...P})??{},Ii()},Re=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Rp],$=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ka.message,ka.messageAndClick],We=Wp({parsers:Re,handlers:$,getSessionMetadata:mt,updateSessionMetadata:Ve,emit:Y.emit,documentRef:typeof document<"u"?document:null});We.syncFromMetadata();let me=o.launcher?.enabled??!0,dt=o.launcher?.autoExpand??!1,Qt=o.autoFocusInput??!1,St=dt,Se=me,It=o.layout?.header?.layout,yt=!1,Pe=()=>Cs(o),Ke=()=>me||Pe(),D=Pe()?!1:me?dt:!0,S=!1,F=null,z=()=>{S=!0,F&&clearTimeout(F),F=setTimeout(()=>{S&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),S=!1)},1e4)},K=yA(o,We,z),Z=o.features?.showReasoning??!0,ye=o.features?.showToolCalls??!0,be=o.features?.showEventStreamToggle??!1,Ae=o.features?.scrollToBottom??{},tt=o.features?.scrollBehavior??{},bt=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Ge=`${bt()}event-stream`,cn=null,vo=o.features?.eventStream?.maxEvents??2e3,ut=null,ht=null,Dt=null,hi=!1,nn=null,Cn=!1,ro=null,yi=0,bi=(a,u)=>{ut?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(u)})},Ia=(a,u)=>{ht?.processEvent(a,u),ut?bi(a,u):Dt&&(Dt.length>=vo&&Dt.shift(),Dt.push({type:a,payload:u}))},rr=()=>{ut||!be||(Dt??=[],xm().then(a=>{if(hi||ut||!be)return;cn=new a.EventStreamStore(Ge),ut=new a.EventStreamBuffer(vo,cn),ht=ht??new a.ThroughputTracker,cn.open().then(()=>ut?.restore()).catch(m=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",m)});let u=Dt??[];Dt=null;for(let m of u)ht?.processEvent(m.type,m.payload),bi(m.type,m.payload)}).catch(()=>{}))};be&&rr();let dn=!1,Nn=null,sr=()=>{},Fn=()=>{},ir=()=>{},Oo=()=>{},_r=()=>{},Jl=()=>Cn||dn&&Nn==="panel",Kn={onCopy:a=>{Y.emit("message:copy",a),R?.isClientTokenMode()&&R.submitMessageFeedback(a.id,"copy").catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",u)}),o.messageActions?.onCopy?.(a)},onFeedback:a=>{Y.emit("message:feedback",a),R?.isClientTokenMode()&&R.submitMessageFeedback(a.messageId,a.type).catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",u)}),o.messageActions?.onFeedback?.(a)}},nh=o.statusIndicator??{},ar=(a,u=o.statusIndicator??{})=>a==="idle"?u.idleText??Kt.idle:a==="connecting"?u.connectingText??Kt.connecting:a==="connected"?u.connectedText??Kt.connected:a==="error"?u.errorText??Kt.error:a==="paused"?u.pausedText??Kt.paused:a==="resuming"?u.resumingText??Kt.resuming:Kt[a];function As(a,u,m,b){if(!Pe()&&(m.mode==="transient"||a.classList.contains("persona-mb-2"))&&(Ug(a,wn,m),ri(a,m,b)),!a.hasAttribute(Ha))if(b==="idle"&&m.idleLink){a.textContent="";let w=document.createElement("a");w.href=m.idleLink,w.target="_blank",w.rel="noopener noreferrer",w.textContent=u,w.style.color="inherit",w.style.textDecoration="none",a.appendChild(w)}else a.textContent=u}let Pn=BS({config:o,showClose:Ke()}),{wrapper:Ye,panel:we,pillRoot:Gt}=Pn.shell,Qe=Pn.panelElements,{container:ve,body:se,messagesWrapper:Me,starterSuggestions:lr,transcriptSuggestions:Dr,suggestions:so,textarea:ae,sendButton:Ee,composerForm:wn,statusText:nt,welcomeHost:Jt,welcomeIconHolder:Zl,greetingHost:Ln,introKicker:ec,introTitle:Qp,introSubtitle:vi,closeButton:je,iconHolder:Pt,headerTitle:Bo,headerSubtitle:_o,header:gt,footer:qe,actionsRow:Ci}=Qe,Sn=Qe.leftActions,xs=Qe.rightActions,Hn=Qe.sendButtonWrapper,tc=Qe.setSendButtonMode,fe=Qe.micButton,pn=Qe.micButtonWrapper,kt=Qe.attachmentButton,on=Qe.attachmentButtonWrapper,At=Qe.attachmentInput,un=Qe.attachmentPreviewsContainer;ve.classList.add("persona-relative"),se.classList.add("persona-relative");let nc=12,Nr=()=>Ae.label??"",Jp=()=>Ae.iconName??"arrow-down",Zp=()=>Ae.enabled!==!1,An=()=>tt.mode??"anchor-top",Co=()=>An()==="follow"||An()==="anchor-top"&&Va,Ms=()=>tt.anchorTopOffset??16,oc=()=>tt.restorePosition??"bottom",Ra=()=>tt.pauseOnInteraction===!0,Wa=()=>tt.showActivityWhilePinned!==!1,wi=()=>tt.announce===!0,Es=()=>tt.scrollbar??"on-scroll",$t=x("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");$t.type="button",$t.style.display="none",$t.setAttribute("data-persona-scroll-to-bottom","true");let Ts=x("span","persona-flex persona-items-center"),Oa=x("span",""),Zt=x("span","");Zt.setAttribute("data-persona-scroll-to-bottom-count",""),Zt.style.display="none",$t.append(Ts,Oa,Zt),ve.appendChild($t);let Yt=x("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",se.appendChild(Yt);let wo=x("div","persona-sr-only");wo.setAttribute("aria-live","polite"),wo.setAttribute("aria-atomic","true"),wo.setAttribute("role","status"),wo.setAttribute("data-persona-live-region",""),Object.assign(wo.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"}),ve.appendChild(wo);let Fr=null,cr=null,Ps=a=>{!wi()||!a||(cr=a,Fr===null&&(Fr=setTimeout(()=>{Fr=null,cr&&wi()&&(wo.textContent=cr),cr=null},400)))},$n=()=>{let a=e.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&a.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(me||Ht(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!Ht(o)},M=()=>zl(o,$n()),N="empty",ee=0,ce=()=>ee||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,He=()=>{let u=qe.style.display==="none"?0:qe.offsetHeight;$t.style.bottom=`${u+ce()+nc}px`};He();let Nt=()=>{Ti||(qe.style.marginBottom=ee>0?`${ee}px`:"")},Rt=()=>{let a=Kf(o,Pe()),u=M();e.setAttribute("data-persona-welcome-fullscreen",String($n())),e.setAttribute("data-persona-welcome-layout",u.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",u.anchor??"bottom");let b=qe.style.display==="none"?0:qe.offsetHeight,w=u.anchor==="center"&&N==="empty"?Rl(u.anchorComposerTop)??Rl("44%"):null,k=w!==null&&u.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,q=k?getComputedStyle(se):null,ne=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,G=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,re=Math.max(0,(parseFloat(q?.paddingBottom??"")||0)-(a==="overlay"?ne+G:0)),ie=k?se.getBoundingClientRect().top-ve.getBoundingClientRect().top:0,le=!k||Jt.hidden?0:(Jt.querySelector("[data-persona-welcome-plugin]")??Jt).offsetHeight,Te=w===null||Pe()?0:k?Math.max(0,Math.round((ve.clientHeight-ie-le-re-b)/2)):Fw({columnHeight:ve.clientHeight,footerHeight:b,fraction:w});e.style.setProperty("--persona-composer-overlay-height",`${b}px`),e.style.setProperty("--persona-composer-lift",`${a==="overlay"?Te:0}px`),ee=a==="block"?Te:0,Nt(),He()},Wt=()=>{let a=!!Nr();$t.setAttribute("aria-label",Nr()||"Jump to latest"),$t.title=Nr(),$t.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),Ts.innerHTML="";let u=ue(Jp(),"14px","currentColor",2);u?(Ts.appendChild(u),Ts.style.display=""):Ts.style.display="none",Oa.textContent=Nr(),Oa.style.display=a?"":"none"};Wt();let Ue=null,st=null,he=ZC(),Si=a=>{try{ve.dispatchEvent(new CustomEvent("persona:composer:state",{detail:a,bubbles:!0,composed:!0}))}catch{}};he.subscribe(Si);let io=()=>{he.setText(ae?.value??"")},dr=()=>{he.setMentionRefs(st?.getMentionRefs()??[])},rx=a=>({id:a.id,name:a.file.name,mimeType:a.file.type,size:a.file.size,status:a.status,progress:a.progress,error:a.error}),oh=a=>{let u=Object.freeze(a.map(rx));he.setAttachments(u);try{o.attachments?.onChange?.(u)}catch(m){console.error("[AgentWidget] attachments.onChange failed:",m)}Hu()};he.setSelectedModelId(o.composer?.selectedModelId);let Ba=()=>o.composer?.modes??[],Ai=()=>mw(Ba(),o.composer?.modeGroups);{let a=rp(o.composer?.defaultActiveModeIds??[],Ba());a.length&&he.setActiveModeIds(a)}function rh(a){if(he.getState().selectedModelId!==a){he.setSelectedModelId(a),$r?.repaint();try{o.composer?.onModelChange?.(a)}catch(u){console.error("[AgentWidget] composer.onModelChange failed:",u)}}}function rc(a){he.setActiveModeIds(a),pr?.render(a,Ai()),xi.forEach(u=>u.repaint()),So?.resolve(),Hc(),Ao()}function eu(a){rc(hw(he.getState().activeModeIds,a,Ba(),o.composer?.modeGroups))}let $r=null,tu=null,pr=null,xi=new Map,Ur=null;function Do(a){he.setQuote(a),Ur?.render(he.getState().quote),Ao(),Yh()}let sh=!1;function nu(){let a=o.composer?.streamingSubmitBehavior??"block";return a!=="interrupt"?a:o.clientToken?"interrupt":(!sh&&o.debug===!0&&(sh=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Vr=null;function Mi(a){he.setPendingSubmission(a),Vr?.render(he.getState().pendingSubmission),Ao()}let sx=a=>{let u=xi.get(a);if(u)return u;let m=vw({groupId:a,getGroup:()=>o.composer?.modeGroups?.find(b=>b.id===a),getModes:()=>Ba().filter(b=>b.groupId===a),getActiveIds:()=>he.getState().activeModeIds,onSelect:b=>eu(b)});return xi.set(a,m),m},ix=()=>{let a=[],u=he.getState().activeModeIds,m=new Set;if(Ba().forEach((b,w)=>{if(op(b.groupId,o.composer?.modeGroups)){let k=b.groupId;if(m.has(k))return;m.add(k);let q=sx(k);q.action.order=Ff(w),q.action.label=o.composer?.modeGroups?.find(ne=>ne.id===k)?.label??k,a.push(q.action);return}a.push({id:gw(b.id),kind:"button",placement:"start",order:Ff(w),presentation:b.presentation??"auto",label:b.label,shortLabel:b.shortLabel,iconName:b.iconName,pressed:u.includes(b.id),onSelect:()=>eu(b.id)})}),o.composer?.models?.length&&!d.some(b=>b.renderComposer)){let b=o.composer?.modelPicker?.presentation??"native";(!$r||tu!==b)&&(tu=b,$r=pw({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>he.getState().selectedModelId,onSelect:w=>rh(w),presentation:b,getSuffix:()=>o.composer?.modelPicker?.suffix})),a.push($r.action)}return a},ou=null,ih=d.find(a=>a.renderHeader);if(ih?.renderHeader){let a=ih.renderHeader({config:o,defaultRenderer:()=>{let u=ws({config:o,showClose:Ke()});return Ca(ve,u,o),u.header},onClose:()=>xt(!1,"user")});if(a){let u=gt;u&&(u.replaceWith(a),gt=a,Pn.header.element=a)}}let ah=()=>{nn&&(se.style.display="none",qe.parentNode?.insertBefore(nn.element,qe),nn.update())},ru=()=>{if(!ut){rr();return}if(Cn=!0,nn?ah():xm().then(u=>{nn||!Cn||!ut||(nn=u.createEventStreamView({buffer:ut,getFullHistory:()=>ut.getAllFromStore(),onClose:()=>Ei(),config:o,plugins:d,getThroughput:()=>ht?.getMetric()??{status:"idle"},renderIconByName:ue}),ah())}).catch(()=>{Ei()}),ft){ft.style.boxShadow=`inset 0 0 0 1.5px ${Bn.actionIconColor}`;let u=o.features?.eventStream?.classNames?.toggleButtonActive;u&&u.split(/\s+/).forEach(m=>m&&ft.classList.add(m))}let a=()=>{if(!Cn)return;let u=Date.now();u-yi>=200&&(nn?.update(),yi=u),ro=requestAnimationFrame(a)};yi=0,ro=requestAnimationFrame(a),Mn(),Y.emit("eventStream:opened",{timestamp:Date.now()})},Ei=()=>{if(Cn){if(Cn=!1,nn&&nn.element.remove(),se.style.display="",ft){ft.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(u=>u&&ft.classList.remove(u))}ro!==null&&(cancelAnimationFrame(ro),ro=null),Mn(),Y.emit("eventStream:closed",{timestamp:Date.now()})}},ft=null;if(be){let a=o.features?.eventStream?.classNames,u="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"+(a?.toggleButton?" "+a.toggleButton:"");ft=x("button",u),ft.style.width="28px",ft.style.height="28px",ft.style.color=Bn.actionIconColor,ft.type="button",ft.setAttribute("aria-label","Event Stream"),ft.title="Event Stream";let m=_t(gA,"18px","currentColor",1.5);m&&ft.appendChild(m);let b=Qe.clearChatButtonWrapper,w=Qe.closeButtonWrapper,k=b||w;k&&k.parentNode===gt?gt.insertBefore(ft,k):gt.appendChild(ft),ft.addEventListener("click",()=>{Cn?Ei():ru()})}let lh=a=>{let u=o.attachments;if(!u?.enabled)return;let m=a.querySelector("[data-persona-composer-attachment-previews]")??a.querySelector(".persona-attachment-previews");if(!m){m=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let w=a.querySelector("[data-persona-composer-form]");w?.parentNode?w.parentNode.insertBefore(m,w):a.insertBefore(m,a.firstChild)}if(!(a.querySelector("[data-persona-composer-attachment-input]")??a.querySelector('input[type="file"]'))){let w=x("input");w.type="file",w.setAttribute("data-persona-composer-attachment-input",""),w.accept=(u.allowedTypes??Lr).join(","),w.multiple=(u.maxFiles??4)>1,w.style.display="none",w.setAttribute("aria-label",u.buttonTooltipText??"Attach files"),a.appendChild(w)}},Ti=!1,ch=a=>{let u=d.find(w=>w.renderComposer);if(!u?.renderComposer)return null;let m=o.composer,b=h?R.isStreaming():!1;return u.renderComposer({config:o,defaultRenderer:a,requestRender:()=>sb(),storage:y(u.id),onSubmit:w=>{!R||R.isStreaming()||Nc(w.trim(),{consumeDraft:!1})},streaming:b,disabled:b,openAttachmentPicker:()=>{Uo()||At?.click()},models:m?.models,selectedModelId:he.getState().selectedModelId??m?.selectedModelId,onModelChange:w=>rh(w),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{ou?.()}:void 0})},dh=ch(()=>Sa({config:o}).footer);dh&&(Pn.replaceComposer(dh),qe=Pn.composer.footer,Ti=!0);let at=null,ax=a=>{wn=a.form,ae=a.input,Hn=a.sendButton?a.sendButton.parentElement:null,a.sendButton&&(Ee=a.sendButton),a.micButton&&(fe=a.micButton,pn=a.micButton.parentElement),a.found.status&&(nt=a.found.status),a.found.suggestions&&(so=a.found.suggestions),a.attachmentButton&&(kt=a.attachmentButton,on=a.attachmentButton.parentElement),At=a.attachmentInput??null,un=a.attachmentPreviews??null,a.found.actionsRow&&(Ci=a.found.actionsRow),Sn=a.found.actionsStart,xs=a.found.actionsEnd};function su(){let a=ae;if(!a)return;let u=o.composer?.inputAttributes,m=!u?.ariaLabel&&!(a instanceof HTMLTextAreaElement)?a.getAttribute("aria-label"):null;Cd(a,u),m&&a.setAttribute("aria-label",m),vd(a,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:vl(a)}),jv(a,bd(o.composer?.maxLines,Pe()?5:3))}let ph=a=>{at=tw(a,{debug:o.debug===!0}),at&&ax(at),su()};lh(qe),ph(qe),io();let _a=bs(o,Pe());_a&&(Me.style.maxWidth=_a,Me.style.marginLeft="auto",Me.style.marginRight="auto",Me.style.width="100%",Ln.style.maxWidth=_a,Ln.style.marginLeft="auto",Ln.style.marginRight="auto",Ln.style.width="100%",lr.style.maxWidth=_a,Dr.style.maxWidth=_a,Dr.style.marginLeft="auto",Dr.style.marginRight="auto",Dr.style.width="100%");let uh=()=>{let a=bs(o,Pe());if(!(!a||Pe()))for(let u of[wn,so,un,nt])u&&(u.style.maxWidth=a,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%")};uh();let gh=()=>{!o.attachments?.enabled||!At||!un||(Ue?Ue.remountPreviews(un):(Ue=fa.fromConfig(o.attachments,oh),Ue.setPreviewsContainer(un)),at?.addListener(At,"change",a=>{let u=a.target;Ue?.handleFileSelect(u.files),u.value=""}),ve.querySelector(".persona-attachment-drop-overlay")||ve.appendChild(bA(o.attachments.dropOverlay)))};gh();let lx=()=>st?.prefetch(),iu=()=>{if(!o.contextMentions?.enabled||!ae)return;let a=uf();if(!a){let b=ae;Id().then(()=>{st||ae!==b||!b.isConnected||(iu(),So?.resolve())},()=>{});return}let u=at?.header??null,m=u?Nf(u):void 0;if(st=a.createContextMentionOrchestrator({deps:{loadContextMentions:kd,loadContextMentionsInline:Ld,renderLucideIcon:ue,createMentionButton:Pd},config:o,textarea:ae,anchor:wn??ae,getMessages:()=>R.getMessages(),liveRegionHost:ve,chipRow:m}),st&&!m){let b=ae;b.parentElement?.insertBefore(st.contextRow,b)}};iu();let So=null,cx={getState:()=>he.getState(),getValue:()=>ae?.value??"",setValue:a=>{ae&&(ae.value=a,ae.dispatchEvent(new Event("input",{bubbles:!0})),io())},submit:()=>{kw(at?.form??null)},openAttachmentPicker:()=>{Uo()||At?.click()},toggleVoice:()=>{ou?.()},requestRender:()=>So?.resolve()},dx=()=>{let a=[];return(st?.affordanceButtons??[]).forEach((m,b)=>{a.push({id:`core:mention-${b}`,placement:"start",order:Jo.mention+b,element:m,managed:!0})}),on&&a.push({id:"core:attachment",placement:"start",order:Jo.attachment,element:on}),pn&&a.push({id:"core:mic",placement:"end",order:Jo.mic,element:pn}),Hn&&a.push({id:"core:send",placement:"end",order:Jo.send,element:Hn}),a},fh=()=>{So?.destroy(),So=lw({getBindings:()=>at,collect:()=>({builtIns:dx(),configActions:[...ix(),...o.composer?.actions??[]],plugins:d,contributionContext:{config:o,getState:()=>he.getState(),requestRender:()=>So?.resolve()},debug:o.debug===!0}),actionContext:cx,getState:()=>he.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(a,u)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${u.actionId}" failed:`,a)}}),So.resolve()};fh();let au=()=>{if(pr?.destroy(),pr=null,!Ai().length)return;let a=at?.header;a&&(pr=uw({row:Nf(a),onRemove:u=>eu(u),initialIds:he.getState().activeModeIds}),pr.render(he.getState().activeModeIds,Ai()))};au();let mh=()=>{Ur?.destroy(),Ur=null,Vr?.destroy(),Vr=null;let a=at?.header;a&&(Ur=Cw({onDismiss:()=>Do(void 0)}),a.appendChild(Ur.element),Ur.render(he.getState().quote),nu()==="defer-one"&&(Vr=ww({onEdit:()=>iM(),onRemove:()=>Mi(void 0)}),a.appendChild(Vr.element),Vr.render(he.getState().pendingSubmission)))};mh();let lu=Tw(),px=()=>{let a=at?.header?.querySelector(Df);if(a)return a.childElementCount>0;let u=he.getState();return u.mentionRefs.length>0||rp(u.activeModeIds,Ai()).length>0};function Ao(){let a=he.getState(),u=lu.observe(Pw(ae),a.text);qe.toggleAttribute("data-persona-composer-compact",Ew({text:a.text,wrapped:u,hasAttachments:a.attachments.length>0,hasChips:px(),hasQuote:a.quote!==void 0,hasPendingSubmission:a.pendingSubmission!==void 0}))}function hh(){o.composer?.layout==="single-row"&&!Pe()?qe.setAttribute("data-persona-composer-layout","single-row"):qe.removeAttribute("data-persona-composer-layout")}hh(),he.subscribe(()=>{So?.sync(),Hu(),Pc(),Ao(),Yh()}),Pc();let yh=!1,ux=a=>{if(yh||o.debug!==!0)return;let u=["messages","composer"].filter(m=>a[m]);u.length&&(yh=!0,console.warn(`[persona] layout.slots.${u.join(" and layout.slots.")} ${u.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 a=o.layout?.slots??{};ux(a);let u=b=>{switch(b){case"body-top":return se.querySelector("[data-persona-intro-card]");case"messages":return Me;case"footer-top":return so;case"composer":return wn;case"footer-bottom":return nt;default:return null}},m=(b,w)=>{switch(b){case"header-left":case"header-center":case"header-right":if(b==="header-left")gt.insertBefore(w,gt.firstChild);else if(b==="header-right")gt.appendChild(w);else{let k=gt.querySelector(".persona-flex-col");k?k.parentNode?.insertBefore(w,k.nextSibling):gt.appendChild(w)}break;case"body-top":{let k=se.querySelector("[data-persona-intro-card]");k?k.replaceWith(w):se.insertBefore(w,se.firstChild);break}case"body-bottom":se.appendChild(w);break;case"footer-top":so.replaceWith(w);break;case"footer-bottom":nt.replaceWith(w);break;default:break}};for(let[b,w]of Object.entries(a))if(w)try{let k=w({config:o,defaultContent:()=>u(b)});k&&m(b,k)}catch(k){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${b}":`,k)}})(),Me.addEventListener("click",a=>{let u=a.target;if(!(u instanceof Element))return;let m=u.closest("button[data-persona-copy-tool-detail]");m&&(a.preventDefault(),a.stopPropagation(),FS(m))});let cu=a=>{let m=a.target.closest('button[data-expand-header="true"]');if(!m)return;let b=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let w=b.getAttribute("data-message-id");if(!w)return;Gr(),Oi();let k=m.getAttribute("data-bubble-type");if(b.classList.contains("persona-activity-row")){i.manual(w);let q=b.parentElement?.closest("[data-persona-tool-group]");q?.dataset.messageId&&i.manual(q.dataset.messageId)}if(k==="reasoning")s.has(w)?s.delete(w):s.add(w),bm(w,b,s);else if(k==="tool")r.has(w)?r.delete(w):r.add(w),Sm(w,b,r,o);else if(k==="approval"&&v){let ne=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",G=l.get(w)??ne;l.set(w,!G),v.updateApprovalDetailsUI(w,b,o,l)}xn.delete(w)};Me.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),cu(a))}),Me.addEventListener("click",a=>{a.detail===0&&a.target.closest(".persona-activity-row")&&cu(a)}),Me.addEventListener("keydown",a=>{let u=a.target;(a.key==="Enter"||a.key===" ")&&u.closest('button[data-expand-header="true"]')&&(a.preventDefault(),cu(a))}),Me.addEventListener("copy",a=>{let{clipboardData:u}=a;if(!u)return;let m=Me.getRootNode(),b=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let w=b.toString(),k=$w(w);!k||k===w||(u.setData("text/plain",k),a.preventDefault())});let du=new Map,bh=null,vh="idle",gx={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},fx=(a,u)=>{let{icon:m,label:b}=gx[u];a.setAttribute("aria-label",b),a.title=b,a.setAttribute("aria-pressed",u==="idle"?"false":"true"),a.classList.toggle("persona-message-action-active",u!=="idle"),a.classList.toggle("persona-message-action-loading",u==="loading");let w=ue(m,14,"currentColor",2);w&&(a.innerHTML="",a.appendChild(w))},Ch=()=>{Me.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{let b=u.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;fx(u,b&&b===bh?vh:"idle")})};Me.addEventListener("click",a=>{let m=a.target.closest(".persona-message-action-btn[data-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.closest("[data-actions-for]");if(!b)return;let w=b.getAttribute("data-actions-for");if(!w)return;let k=m.getAttribute("data-action");if(k==="copy"){let ne=R.getMessages().find(G=>G.id===w);if(ne&&Kn.onCopy){let G=ne.content||"";navigator.clipboard.writeText(G).then(()=>{m.classList.add("persona-message-action-success");let re=_t(fA,14,"currentColor",2);re&&(m.innerHTML="",m.appendChild(re)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let ie=_t(mA,14,"currentColor",2);ie&&(m.innerHTML="",m.appendChild(ie))},2e3)}).catch(re=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",re)}),Kn.onCopy(ne)}}else if(k==="read-aloud")R.toggleReadAloud(w);else if(k==="upvote"||k==="downvote"){let ne=(du.get(w)??null)===k,G=k==="upvote"?"thumbs-up":"thumbs-down";if(ne){du.delete(w),m.classList.remove("persona-message-action-active");let re=ue(G,14,"currentColor",2);re&&(m.innerHTML="",m.appendChild(re))}else{let re=k==="upvote"?"downvote":"upvote",ie=b.querySelector(`[data-action="${re}"]`);if(ie){ie.classList.remove("persona-message-action-active");let lt=ue(re==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);lt&&(ie.innerHTML="",ie.appendChild(lt))}du.set(w,k),m.classList.add("persona-message-action-active");let le=ue(G,14,"currentColor",2);le&&(le.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(le)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let rt=R.getMessages().find(pt=>pt.id===w);rt&&Kn.onFeedback&&Kn.onFeedback({type:k,messageId:rt.id,message:rt})}}else if(k==="regenerate")sc?.regenerate(w);else if(k==="edit")sc?.edit(w);else if(k==="quote")sc?.quote(w);else if(k?.startsWith(Sp)){let q=k.slice(Sp.length),ne=o.messageActions?.custom?.find(re=>re.id===q),G=R.getMessages().find(re=>re.id===w);if(!ne||!G)return;try{ne.onSelect(G)}catch(re){console.error(`[AgentWidget] messageActions.custom "${q}" onSelect failed:`,re)}}});let sc=null;Me.addEventListener("click",a=>{let m=a.target.closest("button[data-approval-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.closest(".persona-approval-bubble");if(!b)return;let w=b.getAttribute("data-message-id");if(!w)return;let k=m.getAttribute("data-approval-action");if(!k)return;let q=k==="approve"?"approved":"denied",G=R.getMessages().find(ie=>ie.id===w);if(!G?.approval)return;let re=b.querySelector("[data-approval-buttons]");re&&re.querySelectorAll("button").forEach(le=>{le.disabled=!0,le.style.opacity="0.5",le.style.cursor="not-allowed"}),G.approval.toolType==="webmcp"?R.resolveWebMcpApproval(w,q):R.resolveApproval(G.approval,q)});let Je=null,wh=!1,Da=null,ks=()=>{},Na="none",ic=null,ao={artifacts:[],selectedId:null},ur=!1,xo=!1,Fa=!1,Pi=!1,Sh=()=>Pi||ao.artifacts.some(a=>Er(o.features?.artifacts,a)==="panel"),ac=()=>ao.artifacts.length>0&&!ur&&Sh(),lo={current:null},pu=(a,u)=>{let m=R.getArtifactById(u),b=m?.markdown,w=m?.title||"artifact",k=m?.file,q=m?.artifactType??"markdown";if(!b){let re=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(re){let le=R.getMessages().find(Te=>Te.id===re);if(le?.rawContent)try{let Te=JSON.parse(le.rawContent);b=Te?.props?.markdown,w=Te?.props?.title||w,Te?.props?.file&&typeof Te.props.file=="object"&&(k=Te.props.file),!m&&typeof Te?.props?.artifactType=="string"&&(q=Te.props.artifactType)}catch{}}}return{markdown:b,title:w,file:k,artifactType:q}};Me.addEventListener("click",a=>{let m=a.target.closest("[data-download-artifact]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.getAttribute("data-download-artifact");if(!b||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:b})===!0)return;let{markdown:k,title:q,file:ne}=pu(m,b);if(!k)return;let G=Wr();G&&G.triggerArtifactDownload(G.downloadInfoFor({title:q,markdown:k,file:ne}))}),Me.addEventListener("click",a=>{let m=a.target.closest("[data-artifact-custom-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.getAttribute("data-artifact-custom-action");if(!b)return;let w=m.closest("[data-artifact-inline]"),k=w?null:m.closest("[data-open-artifact]"),q=w?w.getAttribute("data-artifact-inline"):k?.getAttribute("data-open-artifact")??null,G=(w?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(pt=>pt.id===b);if(!G)return;let{markdown:re,title:ie,file:le,artifactType:Te}=pu(m,q??""),rt={artifactId:q,title:ie,artifactType:Te,markdown:re,file:le};try{Promise.resolve(G.onClick(rt)).catch(()=>{})}catch{}}),Me.addEventListener("click",a=>{let m=a.target.closest("[data-copy-artifact]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.getAttribute("data-copy-artifact");if(!b)return;let w=R.getArtifactById(b),k=Wr();if(!k)return;let q="";if(w)q=k.artifactCopyText(w);else{let{markdown:ne,file:G,artifactType:re}=pu(m,b);re==="markdown"&&(q=k.artifactCopyText({id:b,artifactType:"markdown",status:"complete",markdown:ne??"",...G?{file:G}:{}}))}q&&navigator.clipboard.writeText(q).then(()=>{let ne=_t(fA,16,"currentColor",2);ne&&(m.replaceChildren(ne),setTimeout(()=>{let G=_t(mA,16,"currentColor",2);G&&m.replaceChildren(G)},1500))}).catch(()=>{})}),Me.addEventListener("click",a=>{let m=a.target.closest("[data-expand-artifact-inline]");if(!m)return;a.preventDefault(),a.stopPropagation();let b=m.getAttribute("data-expand-artifact-inline");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(ur=!1,Pi=!0,xo=!0,Fa=!0,R.selectArtifact(b),Mo())}),Me.addEventListener("click",a=>{let u=a.target;if(u.closest("[data-download-artifact]")||u.closest("[data-artifact-custom-action]"))return;let m=u.closest("[data-open-artifact]");if(!m)return;let b=m.getAttribute("data-open-artifact");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(a.preventDefault(),a.stopPropagation(),ur=!1,Pi=!0,R.selectArtifact(b),Mo())}),Me.addEventListener("keydown",a=>{if(a.key!=="Enter"&&a.key!==" ")return;let u=a.target;!u.hasAttribute("data-open-artifact")&&!u.hasAttribute("data-expand-artifact-inline")||(a.preventDefault(),u.click())});let $a=Qe.composerOverlay,uu=a=>{Id().catch(()=>{}),Lg(a,o,$a)},Ah=null,mx={mount:e,overlay:$a,sessionRef:lo,config:()=>o},lc=!1,xh=a=>u=>{let m=u.target,b=m?.closest?.("[data-persona-ask-sheet-for]");if(!b||!(a==="click"?!!m?.closest("[data-ask-user-action]"):u.key==="Enter"&&!!m?.matches?.('[data-ask-free-text-input="true"]')))return;let k=ne=>{Ah??=ne.createAskUserSheetHandlers(mx),Ah[a](u)},q=uf();if(q){k(q);return}lc||(lc=!0,Id().then(ne=>{lc=!1,b.isConnected&&k(ne)},()=>{lc=!1}))};$a.addEventListener("click",xh("click")),$a.addEventListener("keydown",xh("keydown"));let Mh=a=>{if(!/^[1-9]$/.test(a.key)||a.metaKey||a.ctrlKey||a.altKey)return;let u=a.target;if(u?.tagName==="INPUT"||u?.tagName==="TEXTAREA"||u?.isContentEditable)return;let m=$a.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let b=Number(a.key),k=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];k&&(a.preventDefault(),k.click())};document.addEventListener("keydown",Mh);let gr=null,Ft=null,Ua=null,cc=null,dc=()=>{},Eh=!1,pc="",uc="";function gu(){cc?.(),cc=null}let hx=()=>{let a=Ot?.railShell?Ot.railHost:null,u=a?.isConnected?a:null,m=u?u.getBoundingClientRect().width:0;return m<=0?200:m+360},Th=()=>{if(!gr||!Ft)return;let a=e.classList.contains("persona-artifact-welded-split"),u=e.ownerDocument.defaultView??window,m=u.innerWidth<=640;if(!a||e.classList.contains("persona-artifact-narrow-host")||m){Ft.style.removeProperty("position"),Ft.style.removeProperty("left"),Ft.style.removeProperty("top"),Ft.style.removeProperty("bottom"),Ft.style.removeProperty("width"),Ft.style.removeProperty("z-index");return}let b=gr.firstElementChild;if(!b||b===Ft)return;let w=10;Ft.style.position="absolute",Ft.style.top="0",Ft.style.bottom="0",Ft.style.width=`${w}px`,Ft.style.zIndex="5";let k=Hm(gr,u),q=b.offsetWidth+k/2-w/2;Ft.style.left=`${Math.max(0,q)}px`},gc=()=>{},Ph=()=>{let a=e.ownerDocument.defaultView??window,u=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!u||a.innerWidth>m?!1:me||Ht(o)},fc=()=>!Dn(o)||!ac()||e.classList.contains("persona-artifact-narrow-host")||Ph()||(e.ownerDocument.defaultView??window).innerWidth<JI?"none":km(o)?"detached":"welded",Mo=()=>{if(!Je||!Dn(o))return;Kl(e,o),Gl(e,o),gc();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,u=we.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=a);let m=ac();Je.setVisible(m),Je.update(ao),ur?(Je.setMobileOpen(!1),Je.element.classList.add("persona-hidden"),Je.backdrop?.classList.add("persona-hidden"),xo=!1,Fa=!1):ao.artifacts.length>0&&Sh()?(Je.element.classList.remove("persona-hidden"),Je.setMobileOpen(!0)):(Je.setMobileOpen(!1),Je.element.classList.add("persona-hidden"),Je.backdrop?.classList.add("persona-hidden"),xo=!1,Fa=!1);let b=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Je.setExpandToggleVisible(b),Je.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Je.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),Je.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Je.setTabFade(o.features?.artifacts?.layout?.tabFade),Je.setRenderTabBar(o.features?.artifacts?.renderTabBar),!b&&!Fa&&(xo=!1),xo!==Eh){let k=Je.element;xo?(pc=k.style.width,uc=k.style.maxWidth,k.style.removeProperty("width"),k.style.removeProperty("max-width")):(pc&&(k.style.width=pc),uc&&(k.style.maxWidth=uc),pc="",uc=""),Eh=xo}e.classList.toggle("persona-artifact-expanded",xo),Je.setExpanded(xo);let w=fc();w!==Na&&(Na=w,ks()),dc()};if(Dn(o)){we.style.position="relative";let a=x("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=x("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");a.appendChild(ve),gr=u,u.appendChild(a),we.appendChild(u);let m=w=>{wh||Je||(Je=w.createArtifactPane(o,{onSelect:k=>lo.current?.selectArtifact(k),onDismiss:()=>{ur=!0,Mo()},onToggleExpand:()=>{let k=!xo,q=ao.selectedId??ao.artifacts[ao.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:q,expanded:k})!==!0&&(xo=k,k||(Fa=!1),Mo())}}),Je.element.classList.add("persona-hidden"),u.appendChild(Je.element),Je.backdrop&&we.appendChild(Je.backdrop),dc(),Mo())},b=Wr();b?m(b):(Tm(()=>{let w=Wr();w&&m(w)}),Tp().catch(()=>{})),dc=()=>{if(!gr||!Je)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Ua?.(),Ua=null,gu(),Ft&&(Ft.remove(),Ft=null),Je.element.style.removeProperty("width"),Je.element.style.removeProperty("maxWidth");return}if(!Ft){let k=x("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");k.setAttribute("role","separator"),k.setAttribute("aria-orientation","vertical"),k.setAttribute("aria-label","Resize artifacts panel"),k.tabIndex=0;let q=e.ownerDocument,ne=q.defaultView??window,G=re=>{if(!Je||re.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||ne.innerWidth<=640)return;re.preventDefault(),gu();let ie=re.clientX,le=Je.element.getBoundingClientRect().width,Te=o.features?.artifacts?.layout,rt=lt=>{let Vn=gr.getBoundingClientRect().width,Bt=e.classList.contains("persona-artifact-welded-split"),Ut=Hm(gr,ne),Rn=Bt?0:k.getBoundingClientRect().width||6,qt=le-(lt.clientX-ie),vt=tA(qt,Vn,Ut,Rn,Te?.resizableMinWidth,Te?.resizableMaxWidth,hx());Je.element.style.width=`${vt}px`,Je.element.style.maxWidth="none",Th()},pt=()=>{q.removeEventListener("pointermove",rt),q.removeEventListener("pointerup",pt),q.removeEventListener("pointercancel",pt),cc=null;try{k.releasePointerCapture(re.pointerId)}catch{}};cc=pt,q.addEventListener("pointermove",rt),q.addEventListener("pointerup",pt),q.addEventListener("pointercancel",pt);try{k.setPointerCapture(re.pointerId)}catch{}};k.addEventListener("pointerdown",G),Ft=k,gr.insertBefore(k,Je.element),Ua=()=>{k.removeEventListener("pointerdown",G)}}if(Ft){let k=ac();Ft.classList.toggle("persona-hidden",!k),Th()}},gc=()=>{if(!me||!Je||(o.launcher?.sidebarMode??!1)||Ht(o)&&to(o).reveal==="emerge")return;let k=e.ownerDocument.defaultView??window,q=o.launcher?.mobileFullscreen??!0,ne=o.launcher?.mobileBreakpoint??640;if(q&&k.innerWidth<=ne||!KS(o,me))return;let G=ui(o).width,re=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";ac()?(we.style.width=re,we.style.maxWidth=re):(we.style.width=G,we.style.maxWidth=G)},typeof ResizeObserver<"u"&&(Da=new ResizeObserver(()=>{Mo()}),Da.observe(we))}else we.appendChild(ve);Pe()&&Gt&&(Qe.peekBanner&&Gt.appendChild(Qe.peekBanner),Gt.appendChild(qe)),e.appendChild(Ye),Gt&&e.appendChild(Gt);let fu=()=>{let a=Ph()||Pe()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!Ht(o);if(Me.style.gap=a?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",Me.style.setProperty("--persona-transcript-gap",Me.style.gap),Pe()){we.style.width="100%",we.style.maxWidth="100%";let Oe=o.launcher?.composerBar??{},ze=Ye.dataset.state==="expanded",Fe=Oe.expandedSize??"anchored";if(!(ze&&Fe!=="fullscreen")){ve.style.background="",ve.style.border="",ve.style.borderRadius="",ve.style.overflow="",ve.style.boxShadow="";return}let en=o.theme?.components?.panel,jn=Zo(o),Ar=(xr,Xs)=>xr==null||xr===""?Xs:vn(jn,xr)??xr,ug="1px solid var(--persona-border)",Ys="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",gg="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ve.style.background="var(--persona-surface, #ffffff)",ve.style.border=Ar(en?.border,ug),ve.style.borderRadius=Ar(en?.borderRadius,gg),ve.style.boxShadow=Ar(en?.shadow,Ys),ve.style.overflow="hidden";return}let u=Ht(o),m=o.launcher?.sidebarMode??!1,b=u||m||(o.launcher?.fullHeight??!1),w=o.launcher?.enabled===!1,k=o.launcher?.detachedPanel===!0,q=o.theme?.components?.panel,ne=o.darkTheme?.components?.panel,G=ma(o)==="dark"?Ho(q??{},ne??{}):q,re=Zo(o),ie=(Oe,ze)=>Oe==null||Oe===""?ze:vn(re,Oe)??Oe,le=e.ownerDocument.defaultView??window,Te=o.launcher?.mobileFullscreen??!0,rt=o.launcher?.mobileBreakpoint??640,pt=le.innerWidth<=rt,lt=Te&&pt&&me,Vn=u&&Te&&pt,Bt=o.launcher?.position??"bottom-left",Ut=Bt==="bottom-left"||Bt==="top-left",Rn=o.launcher?.zIndex??Tn,qt=(Oe,ze,Fe)=>`var(--persona-components-panel-modes-${Oe}-${ze}, ${Fe})`,vt=G?.modes?.floating,qo=ie(vt?.border??G?.border,qt("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),zo=ie(vt?.shadow??G?.shadow,qt("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),fo=ie(vt?.borderRadius??G?.borderRadius,qt("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),mo=k&&!lt&&!Vn,ns=lt||Vn?"mobile":mo?"floating":u?"docked":m?"sidebar":w?"inline":"floating",Ko=G?.modes?.[ns];mo?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let To=mo?qo:m||lt?"none":qo,os=mo?zo:lt?"none":m?Ut?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":w?"none":zo;u&&!lt&&!mo&&(os="none",To="none");let sl=mo?fo:m||lt?"0":fo,Gs=ie(Ko?.border??G?.border,qt(ns,"border",To)),O=ie(Ko?.shadow??G?.shadow,qt(ns,"shadow",os)),_e=ie(Ko?.borderRadius??G?.borderRadius,qt(ns,"borderRadius",sl)),De=fc(),oe=De==="detached",Ct=De==="welded";e.classList.toggle("persona-artifact-detached-split",oe),e.classList.toggle("persona-artifact-welded-split",Ct);let Xt="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)))))",Mt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Dn(o)&&km(o)&&w&&!u;e.classList.toggle("persona-artifact-chat-flush",Mt);let zt=oe||Mt?"none":O,sn=oe?qo:Ct?"none":Gs,Ie=oe?fo:_e;Mt&&(sn="none",Ie="0");let Et=Ko?.borderRadius!=null&&Ko.borderRadius!==""||G?.borderRadius!=null&&G.borderRadius!=="",Ne=Mt&&!Et?"0":_e,an=se.scrollTop;e.style.cssText="",Ye.style.cssText="",we.style.cssText="",ve.style.cssText="",se.style.cssText="",Ti||(qe.style.cssText=""),Cn&&(se.style.display="none"),(b||w)&&(e.style.minWidth="0");let ho=()=>{if(an<=0)return;(se.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(se.scrollTop===an)return;let ze=se.scrollHeight-se.clientHeight;ze<=0||(se.scrollTop=Math.min(an,ze))})};if(lt){Ye.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"),Ye.style.cssText=`
46
+ `,te.addEventListener("click",()=>{g=V,A.forEach((W,j)=>{let Y=j<V;W.classList.toggle("selected",Y),W.setAttribute("aria-checked",j===V-1?"true":"false")})}),A.push(te),C.appendChild(te)}f.appendChild(C);let L=null;if(c){let V=document.createElement("div");V.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),V.appendChild(L),f.appendChild(V)}let I=document.createElement("div");I.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=l,H.addEventListener("click",()=>{n?.(),d.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=i,B.addEventListener("click",async()=>{if(g===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let V=L?.value.trim()||void 0;await t(g,V),d.remove()}catch(V){B.disabled=!1,B.textContent=i,console.error("[CSAT Feedback] Failed to submit:",V)}}),I.appendChild(H),I.appendChild(B),f.appendChild(I),d.appendChild(f),d}function Um(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:c=!0,lowLabel:p="Not likely",highLabel:d="Very likely"}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let f=null,h=document.createElement("div");h.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,y.appendChild(b);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,y.appendChild(C),h.appendChild(y);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-nps",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let I=document.createElement("span");I.className="persona-feedback-label-low",I.textContent=p;let H=document.createElement("span");H.className="persona-feedback-label-high",H.textContent=d,L.appendChild(I),L.appendChild(H);let B=document.createElement("div");B.className="persona-feedback-numbers";let V=[];for(let M=0;M<=10;M++){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 ${M} out of 10`),T.textContent=String(M),T.dataset.rating=String(M),M<=6?T.classList.add("persona-feedback-detractor"):M<=8?T.classList.add("persona-feedback-passive"):T.classList.add("persona-feedback-promoter"),T.addEventListener("click",()=>{f=M,V.forEach((_,k)=>{_.classList.toggle("selected",k===M),_.setAttribute("aria-checked",k===M?"true":"false")})}),V.push(T),B.appendChild(T)}A.appendChild(L),A.appendChild(B),h.appendChild(A);let te=null;if(c){let M=document.createElement("div");M.className="persona-feedback-comment-container",te=document.createElement("textarea"),te.className="persona-feedback-comment",te.placeholder=s,te.rows=3,te.setAttribute("aria-label","Additional comments"),M.appendChild(te),h.appendChild(M)}let W=document.createElement("div");W.className="persona-feedback-actions";let j=document.createElement("button");j.type="button",j.className="persona-feedback-btn persona-feedback-btn-skip",j.textContent=l,j.addEventListener("click",()=>{n?.(),g.remove()});let Y=document.createElement("button");return Y.type="button",Y.className="persona-feedback-btn persona-feedback-btn-submit",Y.textContent=i,Y.addEventListener("click",async()=>{if(f===null){B.classList.add("persona-feedback-shake"),setTimeout(()=>B.classList.remove("persona-feedback-shake"),500);return}Y.disabled=!0,Y.textContent="Submitting...";try{let M=te?.value.trim()||void 0;await t(f,M),g.remove()}catch(M){Y.disabled=!1,Y.textContent=i,console.error("[NPS Feedback] Failed to submit:",M)}}),W.appendChild(j),W.appendChild(Y),h.appendChild(W),g.appendChild(h),g}var La="persona-chat-history",nR=30*1e3,oR="Tap the mic to resume your voice call",rR=641,Ha="data-persona-composer-reason",Yl="data-persona-composer-notice",sR={"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 iR(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let s=sR[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function Dp(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 aR(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 lR(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Vm=e=>!e||typeof e!="object"?{}:{...e},CA=e=>e.map(t=>({...t,streaming:!1})),wA=(e,t,n)=>{let o=e?.markdown?Jd(e.markdown):null,r=Ef(e?.sanitize);e?.postprocessMessage&&r&&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 s=!1,i=l=>{let c=l.text??"",p=l.message.rawContent??null;if(t){let f=t.process({text:c,raw:p??c,message:l.message,streaming:l.streaming});f!==null&&(c=f.text,f.persist||(l.message.__skipPersist=!0),f.resubmit&&!l.streaming&&n&&n())}let d=Yo()!==null,g;if(e?.postprocessMessage){let f=e.postprocessMessage({...l,text:c,raw:p??l.text??""});g=r?r(f):f}else if(o){let f=l.streaming?HC(c):c,h=o(f);g=r&&d?r(h):h}else g=ms(c);return g};return l=>{try{return i(l)}catch(c){return s||(s=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",c)),ms(l.text??"")}}};function SA(e){let t=x("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",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,i=ue(n,o,r,s);if(i&&t.appendChild(i),e?.label){let l=x("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var cR=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},dR=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:cR(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),jm=(e,t,n)=>{if(e==null)throw new 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 o=yl(t),r=new Set,s=new Set,i=vC((a,u)=>{xn.delete(a);let m=Array.from(Ee.querySelectorAll("[data-message-id]")).find(v=>v.dataset.messageId===a);m&&(u==="tool"?Em(a,m,r,o):wm(a,m,s))}),l=new Map,c=()=>{Hv({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};c();let p=o.features;o=Ip(o);let d=Rp.getForInstance(o.plugins),g=uC(e),f=[],h=!1,y=$S(()=>o),b=null,C=null,A=null,L=!1,I=null,H=a=>{b=a,a.initApprovalUi({webMcpToolTitle:Gi});let u=a.createBuiltInApprovalPlugin(l);C=u.plugin,A=u.teardown},B=()=>{if(b)return b;let a=KS();return a?(H(a),a):(zS().then(u=>{L||b||(H(u),I?.())}).catch(()=>{}),null)},V=!1,te=!1,W=null,j=(a,u,m,v)=>{if(!a.querySelector("[data-tv-form]"))return;let w=aA();if(w){w.enhanceWithForms(a,u,m,v);return}iA().then(()=>{V||te||!W||(te=!0,W())}).catch(()=>{})};o.components&&tr.registerAll(o.components);let Y=dA(),T=o.persistState===!1?null:o.storageAdapter??Bm(),_=!!o.clientToken&&typeof o.reconnectStream!="function",k={},Q=null,U,de=new Promise(a=>{U=a}),pe=()=>{},ge=new Promise(a=>{pe=a}),Pe,Ae=!1,Le=a=>{if(o.onStateLoaded)try{let u=o.onStateLoaded(a);if(u&&typeof u=="object"&&"state"in u){let{state:m,open:v}=u;return v&&(Ae=!0),m}return u}catch(u){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return a};if(T?.load)try{let a=T.load();if(a&&typeof a.then=="function")Q=a.then(u=>Le(u??{messages:[],metadata:{}}));else{let m=Le(a??{messages:[],metadata:{}});m.metadata&&(k=Vm(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null}),Pe=m.draft}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=Le({messages:[],metadata:{}});a.messages?.length&&(o={...o,initialMessages:a.messages})}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}Q||U();let mt=()=>k,Ve=a=>{k=a({...k})??{},Ii()},Re=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Op],$=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Pa.message,Pa.messageAndClick],We=_p({parsers:Re,handlers:$,getSessionMetadata:mt,updateSessionMetadata:Ve,emit:Y.emit,documentRef:typeof document<"u"?document:null});We.syncFromMetadata();let me=o.launcher?.enabled??!0,dt=o.launcher?.autoExpand??!1,Qt=o.autoFocusInput??!1,St=dt,Se=me,It=o.layout?.header?.layout,yt=!1,ke=()=>Cs(o),Ge=()=>me||ke(),D=ke()?!1:me?dt:!0,S=!1,F=null,q=()=>{S=!0,F&&clearTimeout(F),F=setTimeout(()=>{S&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),S=!1)},1e4)},K=wA(o,We,q),Z=o.features?.showReasoning??!0,ye=o.features?.showToolCalls??!0,xe=o.features?.showEventStreamToggle??!1,be=o.features?.scrollToBottom??{},ot=o.features?.scrollBehavior??{},bt=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Ye=`${bt()}event-stream`,cn=null,Co=o.features?.eventStream?.maxEvents??2e3,ut=null,ht=null,Dt=null,hi=!1,nn=null,Cn=!1,so=null,yi=0,bi=(a,u)=>{ut?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(u)})},Ia=(a,u)=>{ht?.processEvent(a,u),ut?bi(a,u):Dt&&(Dt.length>=Co&&Dt.shift(),Dt.push({type:a,payload:u}))},rr=()=>{ut||!xe||(Dt??=[],Tm().then(a=>{if(hi||ut||!xe)return;cn=new a.EventStreamStore(Ye),ut=new a.EventStreamBuffer(Co,cn),ht=ht??new a.ThroughputTracker,cn.open().then(()=>ut?.restore()).catch(m=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",m)});let u=Dt??[];Dt=null;for(let m of u)ht?.processEvent(m.type,m.payload),bi(m.type,m.payload)}).catch(()=>{}))};xe&&rr();let dn=!1,Nn=null,sr=()=>{},Fn=()=>{},ir=()=>{},Oo=()=>{},Br=()=>{},Zl=()=>Cn||dn&&Nn==="panel",Gn={onCopy:a=>{Y.emit("message:copy",a),R?.isClientTokenMode()&&R.submitMessageFeedback(a.id,"copy").catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",u)}),o.messageActions?.onCopy?.(a)},onFeedback:a=>{Y.emit("message:feedback",a),R?.isClientTokenMode()&&R.submitMessageFeedback(a.messageId,a.type).catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",u)}),o.messageActions?.onFeedback?.(a)}},sh=o.statusIndicator??{},ar=(a,u=o.statusIndicator??{})=>a==="idle"?u.idleText??Kt.idle:a==="connecting"?u.connectingText??Kt.connecting:a==="connected"?u.connectedText??Kt.connected:a==="error"?u.errorText??Kt.error:a==="paused"?u.pausedText??Kt.paused:a==="resuming"?u.resumingText??Kt.resuming:Kt[a];function As(a,u,m,v){if(!ke()&&(m.mode==="transient"||a.classList.contains("persona-mb-2"))&&(qg(a,wn,m),ri(a,m,v)),!(a.hasAttribute(Ha)||a.hasAttribute(Yl)))if(v==="idle"&&m.idleLink){a.textContent="";let w=document.createElement("a");w.href=m.idleLink,w.target="_blank",w.rel="noopener noreferrer",w.textContent=u,w.style.color="inherit",w.style.textDecoration="none",a.appendChild(w)}else a.textContent=u}let kn=FS({config:o,showClose:Ge()}),{wrapper:Xe,panel:we,pillRoot:Gt}=kn.shell,Je=kn.panelElements,{container:ve,body:se,messagesWrapper:Ee,starterSuggestions:lr,transcriptSuggestions:Dr,suggestions:io,textarea:ae,sendButton:Me,composerForm:wn,statusText:Ze,welcomeHost:Jt,welcomeIconHolder:ec,greetingHost:Hn,introKicker:tc,introTitle:eu,introSubtitle:vi,closeButton:je,iconHolder:kt,headerTitle:_o,headerSubtitle:Bo,header:gt,footer:qe,actionsRow:Ci}=Je,Sn=Je.leftActions,xs=Je.rightActions,In=Je.sendButtonWrapper,nc=Je.setSendButtonMode,fe=Je.micButton,pn=Je.micButtonWrapper,Pt=Je.attachmentButton,on=Je.attachmentButtonWrapper,At=Je.attachmentInput,un=Je.attachmentPreviewsContainer;ve.classList.add("persona-relative"),se.classList.add("persona-relative");let oc=12,Nr=()=>be.label??"",tu=()=>be.iconName??"arrow-down",nu=()=>be.enabled!==!1,An=()=>ot.mode??"anchor-top",wo=()=>An()==="follow"||An()==="anchor-top"&&Va,Es=()=>ot.anchorTopOffset??16,rc=()=>ot.restorePosition??"bottom",Ra=()=>ot.pauseOnInteraction===!0,Wa=()=>ot.showActivityWhilePinned!==!1,wi=()=>ot.announce===!0,Ms=()=>ot.scrollbar??"on-scroll",$t=x("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");$t.type="button",$t.style.display="none",$t.setAttribute("data-persona-scroll-to-bottom","true");let Ts=x("span","persona-flex persona-items-center"),Oa=x("span",""),Zt=x("span","");Zt.setAttribute("data-persona-scroll-to-bottom-count",""),Zt.style.display="none",$t.append(Ts,Oa,Zt),ve.appendChild($t);let Yt=x("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",se.appendChild(Yt);let So=x("div","persona-sr-only");So.setAttribute("aria-live","polite"),So.setAttribute("aria-atomic","true"),So.setAttribute("role","status"),So.setAttribute("data-persona-live-region",""),Object.assign(So.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"}),ve.appendChild(So);let Fr=null,cr=null,ks=a=>{!wi()||!a||(cr=a,Fr===null&&(Fr=setTimeout(()=>{Fr=null,cr&&wi()&&(So.textContent=cr),cr=null},400)))},$n=()=>{let a=e.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&a.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(me||Ht(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!Ht(o)},E=()=>zl(o,$n()),N="empty",ee=0,ce=()=>ee||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,He=()=>{let u=qe.style.display==="none"?0:qe.offsetHeight;$t.style.bottom=`${u+ce()+oc}px`};He();let Nt=()=>{Ti||(qe.style.marginBottom=ee>0?`${ee}px`:"")},Rt=()=>{let a=Xf(o,ke()),u=E();e.setAttribute("data-persona-welcome-fullscreen",String($n())),e.setAttribute("data-persona-welcome-layout",u.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",u.anchor??"bottom");let v=qe.style.display==="none"?0:qe.offsetHeight,w=u.anchor==="center"&&N==="empty"?Rl(u.anchorComposerTop)??Rl("44%"):null,P=w!==null&&u.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,z=P?getComputedStyle(se):null,ne=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,G=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,re=Math.max(0,(parseFloat(z?.paddingBottom??"")||0)-(a==="overlay"?ne+G:0)),ie=P?se.getBoundingClientRect().top-ve.getBoundingClientRect().top:0,le=!P||Jt.hidden?0:(Jt.querySelector("[data-persona-welcome-plugin]")??Jt).offsetHeight,Te=w===null||ke()?0:P?Math.max(0,Math.round((ve.clientHeight-ie-le-re-v)/2)):jw({columnHeight:ve.clientHeight,footerHeight:v,fraction:w});e.style.setProperty("--persona-composer-overlay-height",`${v}px`),e.style.setProperty("--persona-composer-lift",`${a==="overlay"?Te:0}px`),ee=a==="block"?Te:0,Nt(),He()},Wt=()=>{let a=!!Nr();$t.setAttribute("aria-label",Nr()||"Jump to latest"),$t.title=Nr(),$t.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),Ts.innerHTML="";let u=ue(tu(),"14px","currentColor",2);u?(Ts.appendChild(u),Ts.style.display=""):Ts.style.display="none",Oa.textContent=Nr(),Oa.style.display=a?"":"none"};Wt();let Ue=null,st=null,he=ow(),Si=a=>{try{ve.dispatchEvent(new CustomEvent("persona:composer:state",{detail:a,bubbles:!0,composed:!0}))}catch{}};he.subscribe(Si);let ao=()=>{he.setText(ae?.value??"")},dr=()=>{he.setMentionRefs(st?.getMentionRefs()??[])},cx=a=>({id:a.id,name:a.file.name,mimeType:a.file.type,size:a.file.size,status:a.status,progress:a.progress,error:a.error}),ih=a=>{let u=Object.freeze(a.map(cx));he.setAttachments(u);try{o.attachments?.onChange?.(u)}catch(m){console.error("[AgentWidget] attachments.onChange failed:",m)}Ou()};he.setSelectedModelId(o.composer?.selectedModelId);let _a=()=>o.composer?.modes??[],Ai=()=>vw(_a(),o.composer?.modeGroups);{let a=ip(o.composer?.defaultActiveModeIds??[],_a());a.length&&he.setActiveModeIds(a)}function ah(a){if(he.getState().selectedModelId!==a){he.setSelectedModelId(a),$r?.repaint();try{o.composer?.onModelChange?.(a)}catch(u){console.error("[AgentWidget] composer.onModelChange failed:",u)}}}function sc(a){he.setActiveModeIds(a),pr?.render(a,Ai()),xi.forEach(u=>u.repaint()),Ao?.resolve(),Ic(),xo()}function ou(a){sc(Cw(he.getState().activeModeIds,a,_a(),o.composer?.modeGroups))}let $r=null,ru=null,pr=null,xi=new Map,Ur=null;function Do(a){he.setQuote(a),Ur?.render(he.getState().quote),xo(),ey()}let lh=!1;function su(){let a=o.composer?.streamingSubmitBehavior??"block";return a!=="interrupt"?a:o.clientToken?"interrupt":(!lh&&o.debug===!0&&(lh=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Vr=null;function Ei(a){he.setPendingSubmission(a),Vr?.render(he.getState().pendingSubmission),xo()}let dx=a=>{let u=xi.get(a);if(u)return u;let m=Aw({groupId:a,getGroup:()=>o.composer?.modeGroups?.find(v=>v.id===a),getModes:()=>_a().filter(v=>v.groupId===a),getActiveIds:()=>he.getState().activeModeIds,onSelect:v=>ou(v)});return xi.set(a,m),m},px=()=>{let a=[],u=he.getState().activeModeIds,m=new Set;if(_a().forEach((v,w)=>{if(sp(v.groupId,o.composer?.modeGroups)){let P=v.groupId;if(m.has(P))return;m.add(P);let z=dx(P);z.action.order=Vf(w),z.action.label=o.composer?.modeGroups?.find(ne=>ne.id===P)?.label??P,a.push(z.action);return}a.push({id:yw(v.id),kind:"button",placement:"start",order:Vf(w),presentation:v.presentation??"auto",label:v.label,shortLabel:v.shortLabel,iconName:v.iconName,pressed:u.includes(v.id),onSelect:()=>ou(v.id)})}),o.composer?.models?.length&&!d.some(v=>v.renderComposer)){let v=o.composer?.modelPicker?.presentation??"native";(!$r||ru!==v)&&(ru=v,$r=mw({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>he.getState().selectedModelId,onSelect:w=>ah(w),presentation:v,getSuffix:()=>o.composer?.modelPicker?.suffix})),a.push($r.action)}return a},iu=null,ch=d.find(a=>a.renderHeader);if(ch?.renderHeader){let a=ch.renderHeader({config:o,defaultRenderer:()=>{let u=ws({config:o,showClose:Ge()});return Ca(ve,u,o),u.header},onClose:()=>xt(!1,"user")});if(a){let u=gt;u&&(u.replaceWith(a),gt=a,kn.header.element=a)}}let dh=()=>{nn&&(se.style.display="none",qe.parentNode?.insertBefore(nn.element,qe),nn.update())},au=()=>{if(!ut){rr();return}if(Cn=!0,nn?dh():Tm().then(u=>{nn||!Cn||!ut||(nn=u.createEventStreamView({buffer:ut,getFullHistory:()=>ut.getAllFromStore(),onClose:()=>Mi(),config:o,plugins:d,getThroughput:()=>ht?.getMetric()??{status:"idle"},renderIconByName:ue}),dh())}).catch(()=>{Mi()}),ft){ft.style.boxShadow=`inset 0 0 0 1.5px ${_n.actionIconColor}`;let u=o.features?.eventStream?.classNames?.toggleButtonActive;u&&u.split(/\s+/).forEach(m=>m&&ft.classList.add(m))}let a=()=>{if(!Cn)return;let u=Date.now();u-yi>=200&&(nn?.update(),yi=u),so=requestAnimationFrame(a)};yi=0,so=requestAnimationFrame(a),En(),Y.emit("eventStream:opened",{timestamp:Date.now()})},Mi=()=>{if(Cn){if(Cn=!1,nn&&nn.element.remove(),se.style.display="",ft){ft.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(u=>u&&ft.classList.remove(u))}so!==null&&(cancelAnimationFrame(so),so=null),En(),Y.emit("eventStream:closed",{timestamp:Date.now()})}},ft=null;if(xe){let a=o.features?.eventStream?.classNames,u="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"+(a?.toggleButton?" "+a.toggleButton:"");ft=x("button",u),ft.style.width="28px",ft.style.height="28px",ft.style.color=_n.actionIconColor,ft.type="button",ft.setAttribute("aria-label","Event Stream"),ft.title="Event Stream";let m=Bt(yA,"18px","currentColor",1.5);m&&ft.appendChild(m);let v=Je.clearChatButtonWrapper,w=Je.closeButtonWrapper,P=v||w;P&&P.parentNode===gt?gt.insertBefore(ft,P):gt.appendChild(ft),ft.addEventListener("click",()=>{Cn?Mi():au()})}let ph=a=>{let u=o.attachments;if(!u?.enabled)return;let m=a.querySelector("[data-persona-composer-attachment-previews]")??a.querySelector(".persona-attachment-previews");if(!m){m=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let w=a.querySelector("[data-persona-composer-form]");w?.parentNode?w.parentNode.insertBefore(m,w):a.insertBefore(m,a.firstChild)}if(!(a.querySelector("[data-persona-composer-attachment-input]")??a.querySelector('input[type="file"]'))){let w=x("input");w.type="file",w.setAttribute("data-persona-composer-attachment-input",""),w.accept=(u.allowedTypes??Lr).join(","),w.multiple=(u.maxFiles??4)>1,w.style.display="none",w.setAttribute("aria-label",u.buttonTooltipText??"Attach files"),a.appendChild(w)}},Ti=!1,uh=a=>{let u=d.find(w=>w.renderComposer);if(!u?.renderComposer)return null;let m=o.composer,v=h?R.isStreaming():!1;return u.renderComposer({config:o,defaultRenderer:a,requestRender:()=>cb(),storage:y(u.id),onSubmit:w=>{!R||R.isStreaming()||$c(w.trim(),{consumeDraft:!1})},streaming:v,disabled:v,openAttachmentPicker:()=>{Uo()||At?.click()},models:m?.models,selectedModelId:he.getState().selectedModelId??m?.selectedModelId,onModelChange:w=>ah(w),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{iu?.()}:void 0})},gh=uh(()=>Sa({config:o}).footer);gh&&(kn.replaceComposer(gh),qe=kn.composer.footer,Ti=!0);let at=null,ux=a=>{wn=a.form,ae=a.input,In=a.sendButton?a.sendButton.parentElement:null,a.sendButton&&(Me=a.sendButton),a.micButton&&(fe=a.micButton,pn=a.micButton.parentElement),a.found.status&&(Ze=a.found.status),a.found.suggestions&&(io=a.found.suggestions),a.attachmentButton&&(Pt=a.attachmentButton,on=a.attachmentButton.parentElement),At=a.attachmentInput??null,un=a.attachmentPreviews??null,a.found.actionsRow&&(Ci=a.found.actionsRow),Sn=a.found.actionsStart,xs=a.found.actionsEnd};function lu(){let a=ae;if(!a)return;let u=o.composer?.inputAttributes,m=!u?.ariaLabel&&!(a instanceof HTMLTextAreaElement)?a.getAttribute("aria-label"):null;Sd(a,u),m&&a.setAttribute("aria-label",m),wd(a,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:vl(a)}),Gv(a,Cd(o.composer?.maxLines,ke()?5:3))}let fh=a=>{at=sw(a,{debug:o.debug===!0}),at&&ux(at),lu()};ph(qe),fh(qe),ao();let Ba=bs(o,ke());Ba&&(Ee.style.maxWidth=Ba,Ee.style.marginLeft="auto",Ee.style.marginRight="auto",Ee.style.width="100%",Hn.style.maxWidth=Ba,Hn.style.marginLeft="auto",Hn.style.marginRight="auto",Hn.style.width="100%",lr.style.maxWidth=Ba,Dr.style.maxWidth=Ba,Dr.style.marginLeft="auto",Dr.style.marginRight="auto",Dr.style.width="100%");let mh=()=>{let a=bs(o,ke());if(!(!a||ke()))for(let u of[wn,io,un,Ze])u&&(u.style.maxWidth=a,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%")};mh();let hh=()=>{!o.attachments?.enabled||!At||!un||(Ue?Ue.remountPreviews(un):(Ue=fa.fromConfig(o.attachments,ih),Ue.setPreviewsContainer(un)),at?.addListener(At,"change",a=>{let u=a.target;Ue?.handleFileSelect(u.files),u.value=""}),ve.querySelector(".persona-attachment-drop-overlay")||ve.appendChild(SA(o.attachments.dropOverlay)))};hh();let gx=()=>st?.prefetch(),cu=()=>{if(!o.contextMentions?.enabled||!ae)return;let a=mf();if(!a){let v=ae;Wd().then(()=>{st||ae!==v||!v.isConnected||(cu(),Ao?.resolve())},()=>{});return}let u=at?.header??null,m=u?Uf(u):void 0;if(st=a.createContextMentionOrchestrator({deps:{loadContextMentions:Hd,loadContextMentionsInline:Id,renderLucideIcon:ue,createMentionButton:Ld},config:o,textarea:ae,anchor:wn??ae,getMessages:()=>R.getMessages(),liveRegionHost:ve,chipRow:m}),st&&!m){let v=ae;v.parentElement?.insertBefore(st.contextRow,v)}};cu();let Ao=null,fx={getState:()=>he.getState(),getValue:()=>ae?.value??"",setValue:a=>{ae&&(ae.value=a,ae.dispatchEvent(new Event("input",{bubbles:!0})),ao())},submit:()=>{Rw(at?.form??null)},openAttachmentPicker:()=>{Uo()||At?.click()},toggleVoice:()=>{iu?.()},requestRender:()=>Ao?.resolve()},mx=()=>{let a=[];return(st?.affordanceButtons??[]).forEach((m,v)=>{a.push({id:`core:mention-${v}`,placement:"start",order:Jo.mention+v,element:m,managed:!0})}),on&&a.push({id:"core:attachment",placement:"start",order:Jo.attachment,element:on}),pn&&a.push({id:"core:mic",placement:"end",order:Jo.mic,element:pn}),In&&a.push({id:"core:send",placement:"end",order:Jo.send,element:In}),a},yh=()=>{Ao?.destroy(),Ao=uw({getBindings:()=>at,collect:()=>({builtIns:mx(),configActions:[...px(),...o.composer?.actions??[]],plugins:d,contributionContext:{config:o,getState:()=>he.getState(),requestRender:()=>Ao?.resolve()},debug:o.debug===!0}),actionContext:fx,getState:()=>he.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(a,u)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${u.actionId}" failed:`,a)}}),Ao.resolve()};yh();let du=()=>{if(pr?.destroy(),pr=null,!Ai().length)return;let a=at?.header;a&&(pr=hw({row:Uf(a),onRemove:u=>ou(u),initialIds:he.getState().activeModeIds}),pr.render(he.getState().activeModeIds,Ai()))};du();let bh=()=>{Ur?.destroy(),Ur=null,Vr?.destroy(),Vr=null;let a=at?.header;a&&(Ur=xw({onDismiss:()=>Do(void 0)}),a.appendChild(Ur.element),Ur.render(he.getState().quote),su()==="defer-one"&&(Vr=Ew({onEdit:()=>pE(),onRemove:()=>Ei(void 0)}),a.appendChild(Vr.element),Vr.render(he.getState().pendingSubmission)))};bh();let pu=Hw(),hx=()=>{let a=at?.header?.querySelector($f);if(a)return a.childElementCount>0;let u=he.getState();return u.mentionRefs.length>0||ip(u.activeModeIds,Ai()).length>0};function xo(){let a=he.getState(),u=pu.observe(Iw(ae),a.text);qe.toggleAttribute("data-persona-composer-compact",Lw({text:a.text,wrapped:u,hasAttachments:a.attachments.length>0,hasChips:hx(),hasQuote:a.quote!==void 0,hasPendingSubmission:a.pendingSubmission!==void 0}))}function vh(){o.composer?.layout==="single-row"&&!ke()?qe.setAttribute("data-persona-composer-layout","single-row"):qe.removeAttribute("data-persona-composer-layout")}vh(),he.subscribe(()=>{Ao?.sync(),Ou(),Pc(),xo(),ey()}),Pc();let Ch=!1,yx=a=>{if(Ch||o.debug!==!0)return;let u=["messages","composer"].filter(m=>a[m]);u.length&&(Ch=!0,console.warn(`[persona] layout.slots.${u.join(" and layout.slots.")} ${u.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 a=o.layout?.slots??{};yx(a);let u=v=>{switch(v){case"body-top":return se.querySelector("[data-persona-intro-card]");case"messages":return Ee;case"footer-top":return io;case"composer":return wn;case"footer-bottom":return Ze;default:return null}},m=(v,w)=>{switch(v){case"header-left":case"header-center":case"header-right":if(v==="header-left")gt.insertBefore(w,gt.firstChild);else if(v==="header-right")gt.appendChild(w);else{let P=gt.querySelector(".persona-flex-col");P?P.parentNode?.insertBefore(w,P.nextSibling):gt.appendChild(w)}break;case"body-top":{let P=se.querySelector("[data-persona-intro-card]");P?P.replaceWith(w):se.insertBefore(w,se.firstChild);break}case"body-bottom":se.appendChild(w);break;case"footer-top":io.replaceWith(w);break;case"footer-bottom":Ze.replaceWith(w);break;default:break}};for(let[v,w]of Object.entries(a))if(w)try{let P=w({config:o,defaultContent:()=>u(v)});P&&m(v,P)}catch(P){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${v}":`,P)}})(),Ee.addEventListener("click",a=>{let u=a.target;if(!(u instanceof Element))return;let m=u.closest("button[data-persona-copy-tool-detail]");m&&(a.preventDefault(),a.stopPropagation(),jS(m))});let uu=a=>{let m=a.target.closest('button[data-expand-header="true"]');if(!m)return;let v=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!v)return;let w=v.getAttribute("data-message-id");if(!w)return;Gr(),Oi();let P=m.getAttribute("data-bubble-type");if(v.classList.contains("persona-activity-row")){i.manual(w);let z=v.parentElement?.closest("[data-persona-tool-group]");z?.dataset.messageId&&i.manual(z.dataset.messageId)}if(P==="reasoning")s.has(w)?s.delete(w):s.add(w),wm(w,v,s);else if(P==="tool")r.has(w)?r.delete(w):r.add(w),Em(w,v,r,o);else if(P==="approval"&&b){let ne=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",G=l.get(w)??ne;l.set(w,!G),b.updateApprovalDetailsUI(w,v,o,l)}xn.delete(w)};Ee.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),uu(a))}),Ee.addEventListener("click",a=>{a.detail===0&&a.target.closest(".persona-activity-row")&&uu(a)}),Ee.addEventListener("keydown",a=>{let u=a.target;(a.key==="Enter"||a.key===" ")&&u.closest('button[data-expand-header="true"]')&&(a.preventDefault(),uu(a))}),Ee.addEventListener("copy",a=>{let{clipboardData:u}=a;if(!u)return;let m=Ee.getRootNode(),v=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let w=v.toString(),P=qw(w);!P||P===w||(u.setData("text/plain",P),a.preventDefault())});let gu=new Map,wh=null,Sh="idle",bx={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},vx=(a,u)=>{let{icon:m,label:v}=bx[u];a.setAttribute("aria-label",v),a.title=v,a.setAttribute("aria-pressed",u==="idle"?"false":"true"),a.classList.toggle("persona-message-action-active",u!=="idle"),a.classList.toggle("persona-message-action-loading",u==="loading");let w=ue(m,14,"currentColor",2);w&&(a.innerHTML="",a.appendChild(w))},Ah=()=>{Ee.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{let v=u.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;vx(u,v&&v===wh?Sh:"idle")})};Ee.addEventListener("click",a=>{let m=a.target.closest(".persona-message-action-btn[data-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let v=m.closest("[data-actions-for]");if(!v)return;let w=v.getAttribute("data-actions-for");if(!w)return;let P=m.getAttribute("data-action");if(P==="copy"){let ne=R.getMessages().find(G=>G.id===w);if(ne&&Gn.onCopy){let G=ne.content||"";navigator.clipboard.writeText(G).then(()=>{m.classList.add("persona-message-action-success");let re=Bt(bA,14,"currentColor",2);re&&(m.innerHTML="",m.appendChild(re)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let ie=Bt(vA,14,"currentColor",2);ie&&(m.innerHTML="",m.appendChild(ie))},2e3)}).catch(re=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",re)}),Gn.onCopy(ne)}}else if(P==="read-aloud")R.toggleReadAloud(w);else if(P==="upvote"||P==="downvote"){let ne=(gu.get(w)??null)===P,G=P==="upvote"?"thumbs-up":"thumbs-down";if(ne){gu.delete(w),m.classList.remove("persona-message-action-active");let re=ue(G,14,"currentColor",2);re&&(m.innerHTML="",m.appendChild(re))}else{let re=P==="upvote"?"downvote":"upvote",ie=v.querySelector(`[data-action="${re}"]`);if(ie){ie.classList.remove("persona-message-action-active");let lt=ue(re==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);lt&&(ie.innerHTML="",ie.appendChild(lt))}gu.set(w,P),m.classList.add("persona-message-action-active");let le=ue(G,14,"currentColor",2);le&&(le.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(le)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let rt=R.getMessages().find(pt=>pt.id===w);rt&&Gn.onFeedback&&Gn.onFeedback({type:P,messageId:rt.id,message:rt})}}else if(P==="regenerate")ic?.regenerate(w);else if(P==="edit")ic?.edit(w);else if(P==="quote")ic?.quote(w);else if(P?.startsWith(xp)){let z=P.slice(xp.length),ne=o.messageActions?.custom?.find(re=>re.id===z),G=R.getMessages().find(re=>re.id===w);if(!ne||!G)return;try{ne.onSelect(G)}catch(re){console.error(`[AgentWidget] messageActions.custom "${z}" onSelect failed:`,re)}}});let ic=null;Ee.addEventListener("click",a=>{let m=a.target.closest("button[data-approval-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let v=m.closest(".persona-approval-bubble");if(!v)return;let w=v.getAttribute("data-message-id");if(!w)return;let P=m.getAttribute("data-approval-action");if(!P)return;let z=P==="approve"?"approved":"denied",G=R.getMessages().find(ie=>ie.id===w);if(!G?.approval)return;let re=v.querySelector("[data-approval-buttons]");re&&re.querySelectorAll("button").forEach(le=>{le.disabled=!0,le.style.opacity="0.5",le.style.cursor="not-allowed"}),G.approval.toolType==="webmcp"?R.resolveWebMcpApproval(w,z):R.resolveApproval(G.approval,z)});let et=null,xh=!1,Da=null,Ps=()=>{},Na="none",ac=null,lo={artifacts:[],selectedId:null},ur=!1,Eo=!1,Fa=!1,ki=!1,Eh=()=>ki||lo.artifacts.some(a=>Mr(o.features?.artifacts,a)==="panel"),lc=()=>lo.artifacts.length>0&&!ur&&Eh(),co={current:null},fu=(a,u)=>{let m=R.getArtifactById(u),v=m?.markdown,w=m?.title||"artifact",P=m?.file,z=m?.artifactType??"markdown";if(!v){let re=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(re){let le=R.getMessages().find(Te=>Te.id===re);if(le?.rawContent)try{let Te=JSON.parse(le.rawContent);v=Te?.props?.markdown,w=Te?.props?.title||w,Te?.props?.file&&typeof Te.props.file=="object"&&(P=Te.props.file),!m&&typeof Te?.props?.artifactType=="string"&&(z=Te.props.artifactType)}catch{}}}return{markdown:v,title:w,file:P,artifactType:z}};Ee.addEventListener("click",a=>{let m=a.target.closest("[data-download-artifact]");if(!m)return;a.preventDefault(),a.stopPropagation();let v=m.getAttribute("data-download-artifact");if(!v||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:v})===!0)return;let{markdown:P,title:z,file:ne}=fu(m,v);if(!P)return;let G=Wr();G&&G.triggerArtifactDownload(G.downloadInfoFor({title:z,markdown:P,file:ne}))}),Ee.addEventListener("click",a=>{let m=a.target.closest("[data-artifact-custom-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let v=m.getAttribute("data-artifact-custom-action");if(!v)return;let w=m.closest("[data-artifact-inline]"),P=w?null:m.closest("[data-open-artifact]"),z=w?w.getAttribute("data-artifact-inline"):P?.getAttribute("data-open-artifact")??null,G=(w?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(pt=>pt.id===v);if(!G)return;let{markdown:re,title:ie,file:le,artifactType:Te}=fu(m,z??""),rt={artifactId:z,title:ie,artifactType:Te,markdown:re,file:le};try{Promise.resolve(G.onClick(rt)).catch(()=>{})}catch{}}),Ee.addEventListener("click",a=>{let m=a.target.closest("[data-copy-artifact]");if(!m)return;a.preventDefault(),a.stopPropagation();let v=m.getAttribute("data-copy-artifact");if(!v)return;let w=R.getArtifactById(v),P=Wr();if(!P)return;let z="";if(w)z=P.artifactCopyText(w);else{let{markdown:ne,file:G,artifactType:re}=fu(m,v);re==="markdown"&&(z=P.artifactCopyText({id:v,artifactType:"markdown",status:"complete",markdown:ne??"",...G?{file:G}:{}}))}z&&navigator.clipboard.writeText(z).then(()=>{let ne=Bt(bA,16,"currentColor",2);ne&&(m.replaceChildren(ne),setTimeout(()=>{let G=Bt(vA,16,"currentColor",2);G&&m.replaceChildren(G)},1500))}).catch(()=>{})}),Ee.addEventListener("click",a=>{let m=a.target.closest("[data-expand-artifact-inline]");if(!m)return;a.preventDefault(),a.stopPropagation();let v=m.getAttribute("data-expand-artifact-inline");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(ur=!1,ki=!0,Eo=!0,Fa=!0,R.selectArtifact(v),Mo())}),Ee.addEventListener("click",a=>{let u=a.target;if(u.closest("[data-download-artifact]")||u.closest("[data-artifact-custom-action]"))return;let m=u.closest("[data-open-artifact]");if(!m)return;let v=m.getAttribute("data-open-artifact");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(a.preventDefault(),a.stopPropagation(),ur=!1,ki=!0,R.selectArtifact(v),Mo())}),Ee.addEventListener("keydown",a=>{if(a.key!=="Enter"&&a.key!==" ")return;let u=a.target;!u.hasAttribute("data-open-artifact")&&!u.hasAttribute("data-expand-artifact-inline")||(a.preventDefault(),u.click())});let $a=Je.composerOverlay,mu=a=>{Wd().catch(()=>{}),Rg(a,o,$a)},Mh=null,Cx={mount:e,overlay:$a,sessionRef:co,config:()=>o},cc=!1,Th=a=>u=>{let m=u.target,v=m?.closest?.("[data-persona-ask-sheet-for]");if(!v||!(a==="click"?!!m?.closest("[data-ask-user-action]"):u.key==="Enter"&&!!m?.matches?.('[data-ask-free-text-input="true"]')))return;let P=ne=>{Mh??=ne.createAskUserSheetHandlers(Cx),Mh[a](u)},z=mf();if(z){P(z);return}cc||(cc=!0,Wd().then(ne=>{cc=!1,v.isConnected&&P(ne)},()=>{cc=!1}))};$a.addEventListener("click",Th("click")),$a.addEventListener("keydown",Th("keydown"));let kh=a=>{if(!/^[1-9]$/.test(a.key)||a.metaKey||a.ctrlKey||a.altKey)return;let u=a.target;if(u?.tagName==="INPUT"||u?.tagName==="TEXTAREA"||u?.isContentEditable)return;let m=$a.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let v=Number(a.key),P=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[v-1];P&&(a.preventDefault(),P.click())};document.addEventListener("keydown",kh);let gr=null,Ft=null,Ua=null,dc=null,pc=()=>{},Ph=!1,uc="",gc="";function hu(){dc?.(),dc=null}let wx=()=>{let a=Ot?.railShell?Ot.railHost:null,u=a?.isConnected?a:null,m=u?u.getBoundingClientRect().width:0;return m<=0?200:m+360},Lh=()=>{if(!gr||!Ft)return;let a=e.classList.contains("persona-artifact-welded-split"),u=e.ownerDocument.defaultView??window,m=u.innerWidth<=640;if(!a||e.classList.contains("persona-artifact-narrow-host")||m){Ft.style.removeProperty("position"),Ft.style.removeProperty("left"),Ft.style.removeProperty("top"),Ft.style.removeProperty("bottom"),Ft.style.removeProperty("width"),Ft.style.removeProperty("z-index");return}let v=gr.firstElementChild;if(!v||v===Ft)return;let w=10;Ft.style.position="absolute",Ft.style.top="0",Ft.style.bottom="0",Ft.style.width=`${w}px`,Ft.style.zIndex="5";let P=Wm(gr,u),z=v.offsetWidth+P/2-w/2;Ft.style.left=`${Math.max(0,z)}px`},fc=()=>{},Hh=()=>{let a=e.ownerDocument.defaultView??window,u=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!u||a.innerWidth>m?!1:me||Ht(o)},mc=()=>!Dn(o)||!lc()||e.classList.contains("persona-artifact-narrow-host")||Hh()||(e.ownerDocument.defaultView??window).innerWidth<rR?"none":Im(o)?"detached":"welded",Mo=()=>{if(!et||!Dn(o))return;Kl(e,o),Gl(e,o),fc();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,u=we.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=a);let m=lc();et.setVisible(m),et.update(lo),ur?(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),et.backdrop?.classList.add("persona-hidden"),Eo=!1,Fa=!1):lo.artifacts.length>0&&Eh()?(et.element.classList.remove("persona-hidden"),et.setMobileOpen(!0)):(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),et.backdrop?.classList.add("persona-hidden"),Eo=!1,Fa=!1);let v=o.features?.artifacts?.layout?.showExpandToggle===!0;if(et.setExpandToggleVisible(v),et.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),et.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),et.setCustomActions(o.features?.artifacts?.toolbarActions??[]),et.setTabFade(o.features?.artifacts?.layout?.tabFade),et.setRenderTabBar(o.features?.artifacts?.renderTabBar),!v&&!Fa&&(Eo=!1),Eo!==Ph){let P=et.element;Eo?(uc=P.style.width,gc=P.style.maxWidth,P.style.removeProperty("width"),P.style.removeProperty("max-width")):(uc&&(P.style.width=uc),gc&&(P.style.maxWidth=gc),uc="",gc=""),Ph=Eo}e.classList.toggle("persona-artifact-expanded",Eo),et.setExpanded(Eo);let w=mc();w!==Na&&(Na=w,Ps()),pc()};if(Dn(o)){we.style.position="relative";let a=x("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=x("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");a.appendChild(ve),gr=u,u.appendChild(a),we.appendChild(u);let m=w=>{xh||et||(et=w.createArtifactPane(o,{onSelect:P=>co.current?.selectArtifact(P),onDismiss:()=>{ur=!0,Mo()},onToggleExpand:()=>{let P=!Eo,z=lo.selectedId??lo.artifacts[lo.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:z,expanded:P})!==!0&&(Eo=P,P||(Fa=!1),Mo())}}),et.element.classList.add("persona-hidden"),u.appendChild(et.element),et.backdrop&&we.appendChild(et.backdrop),pc(),Mo())},v=Wr();v?m(v):(Lm(()=>{let w=Wr();w&&m(w)}),Pp().catch(()=>{})),pc=()=>{if(!gr||!et)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Ua?.(),Ua=null,hu(),Ft&&(Ft.remove(),Ft=null),et.element.style.removeProperty("width"),et.element.style.removeProperty("maxWidth");return}if(!Ft){let P=x("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");P.setAttribute("role","separator"),P.setAttribute("aria-orientation","vertical"),P.setAttribute("aria-label","Resize artifacts panel"),P.tabIndex=0;let z=e.ownerDocument,ne=z.defaultView??window,G=re=>{if(!et||re.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||ne.innerWidth<=640)return;re.preventDefault(),hu();let ie=re.clientX,le=et.element.getBoundingClientRect().width,Te=o.features?.artifacts?.layout,rt=lt=>{let jn=gr.getBoundingClientRect().width,_t=e.classList.contains("persona-artifact-welded-split"),Ut=Wm(gr,ne),Wn=_t?0:P.getBoundingClientRect().width||6,qt=le-(lt.clientX-ie),vt=sA(qt,jn,Ut,Wn,Te?.resizableMinWidth,Te?.resizableMaxWidth,wx());et.element.style.width=`${vt}px`,et.element.style.maxWidth="none",Lh()},pt=()=>{z.removeEventListener("pointermove",rt),z.removeEventListener("pointerup",pt),z.removeEventListener("pointercancel",pt),dc=null;try{P.releasePointerCapture(re.pointerId)}catch{}};dc=pt,z.addEventListener("pointermove",rt),z.addEventListener("pointerup",pt),z.addEventListener("pointercancel",pt);try{P.setPointerCapture(re.pointerId)}catch{}};P.addEventListener("pointerdown",G),Ft=P,gr.insertBefore(P,et.element),Ua=()=>{P.removeEventListener("pointerdown",G)}}if(Ft){let P=lc();Ft.classList.toggle("persona-hidden",!P),Lh()}},fc=()=>{if(!me||!et||(o.launcher?.sidebarMode??!1)||Ht(o)&&no(o).reveal==="emerge")return;let P=e.ownerDocument.defaultView??window,z=o.launcher?.mobileFullscreen??!0,ne=o.launcher?.mobileBreakpoint??640;if(z&&P.innerWidth<=ne||!QS(o,me))return;let G=ui(o).width,re=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";lc()?(we.style.width=re,we.style.maxWidth=re):(we.style.width=G,we.style.maxWidth=G)},typeof ResizeObserver<"u"&&(Da=new ResizeObserver(()=>{Mo()}),Da.observe(we))}else we.appendChild(ve);ke()&&Gt&&(Je.peekBanner&&Gt.appendChild(Je.peekBanner),Gt.appendChild(qe)),e.appendChild(Xe),Gt&&e.appendChild(Gt);let yu=()=>{let a=Hh()||ke()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!Ht(o);if(Ee.style.gap=a?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",Ee.style.setProperty("--persona-transcript-gap",Ee.style.gap),ke()){we.style.width="100%",we.style.maxWidth="100%";let Oe=o.launcher?.composerBar??{},Ke=Xe.dataset.state==="expanded",Fe=Oe.expandedSize??"anchored";if(!(Ke&&Fe!=="fullscreen")){ve.style.background="",ve.style.border="",ve.style.borderRadius="",ve.style.overflow="",ve.style.boxShadow="";return}let en=o.theme?.components?.panel,qn=Zo(o),Ar=(xr,Xs)=>xr==null||xr===""?Xs:vn(qn,xr)??xr,mg="1px solid var(--persona-border)",Ys="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",hg="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ve.style.background="var(--persona-surface, #ffffff)",ve.style.border=Ar(en?.border,mg),ve.style.borderRadius=Ar(en?.borderRadius,hg),ve.style.boxShadow=Ar(en?.shadow,Ys),ve.style.overflow="hidden";return}let u=Ht(o),m=o.launcher?.sidebarMode??!1,v=u||m||(o.launcher?.fullHeight??!1),w=o.launcher?.enabled===!1,P=o.launcher?.detachedPanel===!0,z=o.theme?.components?.panel,ne=o.darkTheme?.components?.panel,G=ma(o)==="dark"?Ho(z??{},ne??{}):z,re=Zo(o),ie=(Oe,Ke)=>Oe==null||Oe===""?Ke:vn(re,Oe)??Oe,le=e.ownerDocument.defaultView??window,Te=o.launcher?.mobileFullscreen??!0,rt=o.launcher?.mobileBreakpoint??640,pt=le.innerWidth<=rt,lt=Te&&pt&&me,jn=u&&Te&&pt,_t=o.launcher?.position??"bottom-left",Ut=_t==="bottom-left"||_t==="top-left",Wn=o.launcher?.zIndex??Tn,qt=(Oe,Ke,Fe)=>`var(--persona-components-panel-modes-${Oe}-${Ke}, ${Fe})`,vt=G?.modes?.floating,qo=ie(vt?.border??G?.border,qt("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),zo=ie(vt?.shadow??G?.shadow,qt("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),mo=ie(vt?.borderRadius??G?.borderRadius,qt("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),ho=P&&!lt&&!jn,ns=lt||jn?"mobile":ho?"floating":u?"docked":m?"sidebar":w?"inline":"floating",Ko=G?.modes?.[ns];ho?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let To=ho?qo:m||lt?"none":qo,os=ho?zo:lt?"none":m?Ut?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":w?"none":zo;u&&!lt&&!ho&&(os="none",To="none");let sl=ho?mo:m||lt?"0":mo,Gs=ie(Ko?.border??G?.border,qt(ns,"border",To)),O=ie(Ko?.shadow??G?.shadow,qt(ns,"shadow",os)),Be=ie(Ko?.borderRadius??G?.borderRadius,qt(ns,"borderRadius",sl)),De=mc(),oe=De==="detached",Ct=De==="welded";e.classList.toggle("persona-artifact-detached-split",oe),e.classList.toggle("persona-artifact-welded-split",Ct);let Xt="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)))))",Et=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Dn(o)&&Im(o)&&w&&!u;e.classList.toggle("persona-artifact-chat-flush",Et);let zt=oe||Et?"none":O,sn=oe?qo:Ct?"none":Gs,Ie=oe?mo:Be;Et&&(sn="none",Ie="0");let Mt=Ko?.borderRadius!=null&&Ko.borderRadius!==""||G?.borderRadius!=null&&G.borderRadius!=="",Ne=Et&&!Mt?"0":Be,an=se.scrollTop;e.style.cssText="",Xe.style.cssText="",we.style.cssText="",ve.style.cssText="",se.style.cssText="",Ti||(qe.style.cssText=""),Cn&&(se.style.display="none"),(v||w)&&(e.style.minWidth="0");let yo=()=>{if(an<=0)return;(se.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(se.scrollTop===an)return;let Ke=se.scrollHeight-se.clientHeight;Ke<=0||(se.scrollTop=Math.min(an,Ke))})};if(lt){Xe.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"),Xe.style.cssText=`
47
47
  position: fixed !important;
48
48
  inset: 0 !important;
49
49
  width: 100% !important;
@@ -53,7 +53,7 @@ _Details: ${n.message}_`:o}var QC=e=>Zs(e)||e===Xo,kl=class e{constructor(t={},n
53
53
  padding: 0 !important;
54
54
  display: flex !important;
55
55
  flex-direction: column !important;
56
- z-index: ${Rn} !important;
56
+ z-index: ${Wn} !important;
57
57
  background-color: var(--persona-surface, #ffffff) !important;
58
58
  `,we.style.cssText=`
59
59
  position: relative !important;
@@ -79,7 +79,7 @@ _Details: ${n.message}_`:o}var QC=e=>Zs(e)||e===Xo,kl=class e{constructor(t={},n
79
79
  overflow: hidden !important;
80
80
  border-radius: 0 !important;
81
81
  border: none !important;
82
- `,se.style.flex="1 1 0%",se.style.minHeight="0",se.style.overflowY="auto",qe.style.flexShrink="0",Nt(),yt=!0,ho();return}let fn=ui(o);if(!m&&!u)w&&b?(we.style.width="100%",we.style.maxWidth="100%"):(we.style.width=fn.width,we.style.maxWidth=fn.maxWidth);else if(u)if(to(o).reveal==="emerge"&&!k){let ze=to(o).width;we.style.width=ze,we.style.maxWidth=ze}else we.style.width="100%",we.style.maxWidth="100%";if(gc(),we.style.boxShadow=zt,we.style.borderRadius=Ne,oe?we.style.border="none":Ct&&(we.style.border=Gs),ve.style.border=sn,ve.style.borderRadius=Ie,ve.style.boxShadow=oe&&!Mt?Xt:"",Mt&&(ve.style.background="transparent",se.style.background="transparent",qe.style.background="transparent",qe.style.borderTop="none"),Ct){let Oe=o.features?.artifacts?.layout;ic=Oe?.unifiedSplitOuterRadius?.trim()||Oe?.paneBorderRadius?.trim()||_e}else ic=null;let wt=Ko?.border!=null||G?.border!=null;if(u&&!lt&&!mo&&!oe&&!Ct&&!wt&&(ve.style.border="none",to(o).side==="right"?ve.style.borderLeft="1px solid var(--persona-border)":ve.style.borderRight="1px solid var(--persona-border)"),u&&!lt&&Ct&&!wt&&(to(o).side==="right"?we.style.borderLeft="1px solid var(--persona-border)":we.style.borderRight="1px solid var(--persona-border)"),b&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",w&&(e.style.width="100%"),Ye.style.display="flex",Ye.style.flexDirection="column",Ye.style.flex="1 1 0%",Ye.style.minHeight="0",Ye.style.maxHeight="100%",Ye.style.height="100%",w&&(Ye.style.overflow="hidden"),we.style.display="flex",we.style.flexDirection="column",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.maxHeight="100%",we.style.height="100%",oe||(we.style.overflow="hidden"),ve.style.display="flex",ve.style.flexDirection="column",ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.maxHeight="100%",ve.style.overflow="hidden",se.style.flex="1 1 0%",se.style.minHeight="0",se.style.overflowY="auto",qe.style.flexShrink="0"),w&&(mo||oe||Mt)&&!u&&(Mt||(Ye.style.padding="var(--persona-panel-inset)"),Ye.style.background="var(--persona-panel-canvas-bg)"),Ye.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"),!m&&!w&&!u&&(no[Bt]??no["bottom-right"]).split(" ").forEach(ze=>Ye.classList.add(ze)),m){let Oe=Pr(o).sidebarWidth?o.launcher?.sidebarWidth??"420px":vn(Zo(o),"components.panel.width")??"420px";k?Ye.style.cssText=`
82
+ `,se.style.flex="1 1 0%",se.style.minHeight="0",se.style.overflowY="auto",qe.style.flexShrink="0",Nt(),yt=!0,yo();return}let fn=ui(o);if(!m&&!u)w&&v?(we.style.width="100%",we.style.maxWidth="100%"):(we.style.width=fn.width,we.style.maxWidth=fn.maxWidth);else if(u)if(no(o).reveal==="emerge"&&!P){let Ke=no(o).width;we.style.width=Ke,we.style.maxWidth=Ke}else we.style.width="100%",we.style.maxWidth="100%";if(fc(),we.style.boxShadow=zt,we.style.borderRadius=Ne,oe?we.style.border="none":Ct&&(we.style.border=Gs),ve.style.border=sn,ve.style.borderRadius=Ie,ve.style.boxShadow=oe&&!Et?Xt:"",Et&&(ve.style.background="transparent",se.style.background="transparent",qe.style.background="transparent",qe.style.borderTop="none"),Ct){let Oe=o.features?.artifacts?.layout;ac=Oe?.unifiedSplitOuterRadius?.trim()||Oe?.paneBorderRadius?.trim()||Be}else ac=null;let wt=Ko?.border!=null||G?.border!=null;if(u&&!lt&&!ho&&!oe&&!Ct&&!wt&&(ve.style.border="none",no(o).side==="right"?ve.style.borderLeft="1px solid var(--persona-border)":ve.style.borderRight="1px solid var(--persona-border)"),u&&!lt&&Ct&&!wt&&(no(o).side==="right"?we.style.borderLeft="1px solid var(--persona-border)":we.style.borderRight="1px solid var(--persona-border)"),v&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",w&&(e.style.width="100%"),Xe.style.display="flex",Xe.style.flexDirection="column",Xe.style.flex="1 1 0%",Xe.style.minHeight="0",Xe.style.maxHeight="100%",Xe.style.height="100%",w&&(Xe.style.overflow="hidden"),we.style.display="flex",we.style.flexDirection="column",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.maxHeight="100%",we.style.height="100%",oe||(we.style.overflow="hidden"),ve.style.display="flex",ve.style.flexDirection="column",ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.maxHeight="100%",ve.style.overflow="hidden",se.style.flex="1 1 0%",se.style.minHeight="0",se.style.overflowY="auto",qe.style.flexShrink="0"),w&&(ho||oe||Et)&&!u&&(Et||(Xe.style.padding="var(--persona-panel-inset)"),Xe.style.background="var(--persona-panel-canvas-bg)"),Xe.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"),!m&&!w&&!u&&(oo[_t]??oo["bottom-right"]).split(" ").forEach(Ke=>Xe.classList.add(Ke)),m){let Oe=kr(o).sidebarWidth?o.launcher?.sidebarWidth??"420px":vn(Zo(o),"components.panel.width")??"420px";P?Xe.style.cssText=`
83
83
  position: fixed !important;
84
84
  top: var(--persona-panel-inset) !important;
85
85
  bottom: var(--persona-panel-inset) !important;
@@ -90,9 +90,9 @@ _Details: ${n.message}_`:o}var QC=e=>Zs(e)||e===Xo,kl=class e{constructor(t={},n
90
90
  padding: 0 !important;
91
91
  display: flex !important;
92
92
  flex-direction: column !important;
93
- z-index: ${Rn} !important;
93
+ z-index: ${Wn} !important;
94
94
  ${Ut?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
95
- `:Ye.style.cssText=`
95
+ `:Xe.style.cssText=`
96
96
  position: fixed !important;
97
97
  top: 0 !important;
98
98
  bottom: 0 !important;
@@ -103,7 +103,7 @@ _Details: ${n.message}_`:o}var QC=e=>Zs(e)||e===Xo,kl=class e{constructor(t={},n
103
103
  padding: 0 !important;
104
104
  display: flex !important;
105
105
  flex-direction: column !important;
106
- z-index: ${Rn} !important;
106
+ z-index: ${Wn} !important;
107
107
  ${Ut?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
108
108
  `,we.style.cssText=`
109
109
  position: relative !important;
@@ -130,30 +130,30 @@ _Details: ${n.message}_`:o}var QC=e=>Zs(e)||e===Xo,kl=class e{constructor(t={},n
130
130
  overflow: hidden !important;
131
131
  border-radius: ${Ie} !important;
132
132
  border: ${sn} !important;
133
- ${oe&&!Mt?`box-shadow: ${Xt} !important;`:""}
134
- ${Mt?"background: transparent !important;":""}
133
+ ${oe&&!Et?`box-shadow: ${Xt} !important;`:""}
134
+ ${Et?"background: transparent !important;":""}
135
135
  `,Ti||(qe.style.cssText=`
136
136
  flex-shrink: 0 !important;
137
137
  border-top: none !important;
138
138
  padding: 8px 16px 12px 16px !important;
139
- ${Mt?"background: transparent !important;":""}
140
- `)}if(!w&&!u){let Oe="max-height: -moz-available !important; max-height: stretch !important;",ze=m?"":"padding-top: 1.25em !important;",Fe=m?"":`z-index: ${o.launcher?.zIndex??Tn} !important;`;Ye.style.cssText+=Oe+ze+Fe}Nt(),ho()},mu=()=>{e.style.setProperty("--persona-content-max-width",bs(o,Pe()))},kh=!1;function Lh(){o.layout?.topFade&&se.scrollTop>1?se.setAttribute("data-persona-top-fade","true"):se.removeAttribute("data-persona-top-fade")}let hu=()=>{Lh();let a=Kf(o,Pe());Pe()&&o.composer?.placement&&o.debug===!0&&!kh&&(kh=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let u=M();e.setAttribute("data-persona-composer-placement",a),e.setAttribute("data-persona-conversation-state",N),e.setAttribute("data-persona-welcome-anchor",u.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",u.composerGap??gp),Rt()},Hh=()=>{if(Pe())return;let a=Ht(o),u=o.launcher?.sidebarMode??!1;if(a||u||(o.launcher?.fullHeight??!1)||!me)return;let b=e.ownerDocument.defaultView??window,w=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640;if(w&&b.innerWidth<=k)return;let q=ui(o);we.style.height=q.height,we.style.maxHeight=q.maxHeight};fu(),ha(e,o),Kl(e,o),Gl(e,o),mu(),hu(),ks=()=>{fu(),Hh(),ha(e,o),Kl(e,o),Gl(e,o),mu(),hu(),ic?e.style.setProperty("--persona-artifact-welded-outer-radius",ic):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Fn(),sr()};let Ce=[];Ce.push(()=>{wh=!0}),Ce.push(()=>{f.forEach(a=>a()),g.destroy()}),Ce.push(()=>{document.removeEventListener("keydown",Mh)}),Ce.push(()=>{Fr!==null&&clearTimeout(Fr)});let No=null,Fo=null;Ce.push(()=>{No?.(),No=null,Fo?.(),Fo=null}),Da&&Ce.push(()=>{Da?.disconnect(),Da=null}),Ce.push(()=>{Ua?.(),Ua=null,gu(),Ft&&(Ft.remove(),Ft=null),Je?.element.style.removeProperty("width"),Je?.element.style.removeProperty("maxWidth"),Je?.destroy()}),be&&Ce.push(()=>{hi=!0,Dt=null,ro!==null&&(cancelAnimationFrame(ro),ro=null),nn?.destroy(),nn=null,ut?.destroy(),ut=null,cn=null});let Ls=null,Ih=()=>{Ls&&(Ls(),Ls=null),o.colorScheme==="auto"&&(Ls=Il(()=>{ha(e,o)}))};Ih(),Ce.push(()=>{Ls&&(Ls(),Ls=null)}),Ce.push(()=>{L=!0,A?.()}),Ce.push(()=>{V=!0});let Rh=!1;Ce.push(()=>{Rh=!0});let yu=(a,u)=>{let m=Bl(a,u);return m||!nS.includes(a)?m:(rS().then(b=>{if(Rh)return;hp(b.wipe),hp(b.glyphCycle);let w=Bl(a,u);w&&Nl(w,e)}).catch(()=>{}),null)},mc=o.features?.streamAnimation;if(mc?.type&&mc.type!=="none"){let a=yu(mc.type,mc.plugins);a&&Nl(a,e),Ce.push(()=>oS(e))}let fr=Ul(so),Wh=Ul(lr),Oh=Ul(Dr),Hs=[fr,Wh,Oh];Ce.push(()=>{Hs.forEach(a=>a.destroy())});let Is=null,R,Rs=null,Bh=!1,_h=0,Dh=null,Nh=a=>a.reduce((u,m)=>m.role==="user"?u+1:u,0),Fh=a=>{for(let u=a.length-1;u>=0;u--)if(Zi(a[u]))return a[u].id??null;return null},$h=!1,yx=()=>{$h||o.debug!==!0||($h=!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".'))},Uh=!1,Vh=!1,jh=(a,u)=>{Uh||o.debug!==!0||!u.enabled||u.expose||Bh||Vh&&(R.isStreaming()||a.some(Zi)||(Uh=!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.")))},Ws=a=>{if(!R)return;let u=a??R.getMessages(),m=le=>{le.render([],R,ae,u)},b=le=>{Hs.forEach(Te=>{Te!==le&&m(Te)})};Rs&&(Nh(u)>_h||Fh(u)!==Dh)&&(Rs=null);let w=ps(o);jh(u,w);let k=w.enabled?Rg(u):null,q=Rs??k,ne=Rs?"host":"agent";if(q){let le=o.suggestions?.followUps,Te=le?.placement??(le?"auto":"composer"),pt=(Te==="auto"?Pe()?"composer":"after-message":Te)==="after-message"?Oh:fr;b(pt),pt.render(q,R,ae,u,o.suggestionChipsConfig,{source:ne,surface:"followUp",variant:le?.variant??"chip",behavior:le?.behavior??"send",overflow:le?.overflow??"wrap",maxItems:le?.maxItems??4,config:o,plugins:d,submitPrompt:Dc});return}if(u.some(le=>le.role==="user")){Hs.forEach(m);return}let G=o.future?.v5Defaults===!0,re=$n(),ie=o.suggestions?.starters??(G?{}:void 0);if(ie){let le=pi(M(),u),Te=ie.placement??"auto",rt=Te==="auto"?le?"welcome":"composer":Te;if(rt==="welcome"&&!le){yx(),Hs.forEach(m);return}let pt=rt==="welcome"?Wh:fr;b(pt),pt.render(ie.items??o.suggestionChips,R,ae,u,o.suggestionChipsConfig,{surface:"starter",variant:ie.variant??(G&&!re?"chip":"card"),behavior:ie.behavior??"send",overflow:ie.overflow??"wrap",maxItems:ie.maxItems??(G&&!re?3:4),config:o,plugins:d,submitPrompt:Dc});return}b(fr),fr.render(o.suggestionChips,R,ae,u,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:d,submitPrompt:Dc})},qh=()=>{Rs&&(Rs=null,Ws())},bx=a=>{let u=Array.isArray(a)?[...a]:[];if(!u.length){qh();return}let m=R?R.getMessages():[];Rs=u,Bh=!0,_h=Nh(m),Dh=Fh(m),Ws(m)},Gn=!1,xn=jw(),ki=new Map,Os=new Map,jr=new Map,Bs=null,qr=null;function _s(){if(!Bs)return;let a=Bs;Bs=null,qr?.destroy(),qr=null,xn.delete(a),ve.querySelector(`#wrapper-${a}`)?.removeAttribute("data-preserve-runtime"),R&&co(Me,R.getMessages(),K)}let Ds=0,vx=Yo()!==null,Yn=Yw(),Xn=0,zr=null,Un=!1,hc=!1,Kr=0,rn=null,Ns=null,bu=!1,Li=!1,Fs=null,Va=!0,yc=!1,Hi=null,bc=!1,Gr=()=>{bc=!0,Ax()},vu=null,Cx=4,mr=24,wx=80,Sx=1e3,hr=null,zh=()=>{e.setAttribute("data-persona-scrollbar",Es()),Es()!=="on-scroll"&&(hr!==null&&clearTimeout(hr),hr=null,se.removeAttribute("data-persona-scrollbar-visible"))},Ax=()=>{Es()==="on-scroll"&&(se.setAttribute("data-persona-scrollbar-visible",""),hr!==null&&clearTimeout(hr),hr=setTimeout(()=>{hr=null,di(se,mr)&&se.removeAttribute("data-persona-scrollbar-visible")},Sx))};zh(),Ce.push(()=>{hr!==null&&clearTimeout(hr)});let Cu=new Map,wu=!1,vc=null,ot={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Ao();let Kh=o.voiceRecognition?.autoResume??!1,yr=a=>{Y.emit("voice:state",{active:ot.active,source:a,timestamp:Date.now()})},Eo=()=>{Ve(a=>({...a,voiceState:{active:ot.active,timestamp:Date.now(),manuallyDeactivated:ot.manuallyDeactivated}}))},xx=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=Fm(P.voiceState),u=!!a.active,m=Number(a.timestamp??0);ot.manuallyDeactivated=!!a.manuallyDeactivated,u&&Date.now()-m<QI&&setTimeout(()=>{ot.active||(ot.manuallyDeactivated=!1,On(o.voiceRecognition?.provider)?R.toggleVoice().then(()=>{ot.active=R.isVoiceActive(),yr("restore"),R.isVoiceActive()&&ji()}):Uc("restore"))},1e3)},Mx=()=>R?hA(R.getMessages()).filter(a=>!a.__skipPersist):[],Cc=null,Gh=(a,u)=>{typeof console<"u"&&console.error(a,u)},wc=(a,u)=>{let m=()=>{try{let q=a();return!q||typeof q.then!="function"?null:Promise.resolve(q).catch(ne=>{Gh(u,ne)})}catch(q){return Gh(u,q),null}},b=Cc,w=b?b.then(()=>m()??void 0):m();if(!w)return;let k=w.finally(()=>{Cc===k&&(Cc=null)});Cc=k};function Ii(a){if(!T?.save)return;let u=a?hA(a):R?Mx():[],m=B&&R?.getResumableHandle();m&&(P={...P,durableResume:{executionId:m.executionId,after:m.lastEventId}});let b={messages:u,metadata:P,artifacts:ao.artifacts,selectedArtifactId:ao.selectedId,...$s?{draft:$s}:{}};wc(()=>T.save(b),"[AgentWidget] Failed to persist state:")}let $s,Sc=()=>!T?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,ja=Mw({write:()=>{if(!Sc())return;let a=he.getState(),u=Aw({text:a.text,mentionRefs:a.mentionRefs,contentSegments:Ju(),selectedModelId:a.selectedModelId,activeModeIds:a.activeModeIds,quote:a.quote});JSON.stringify(u)!==JSON.stringify($s)&&($s=u,Ii())}});function Yh(){Sc()&&ja.schedule()}function Su(){ja.flush()}function Xh(a){if(!Sc())return;let u=xw(a,{mentionSourceIds:(o.contextMentions?.sources??[]).map(m=>m.id),modelIds:(o.composer?.models??[]).map(m=>m.id),modes:o.composer?.modes??[]});u&&($s=a,ae&&!ae.value&&(ae.value=u.text,ae.dispatchEvent(new Event("input",{bubbles:!0})),io()),u.selectedModelId&&(he.setSelectedModelId(u.selectedModelId),$r?.repaint()),rc(u.activeModeIds??[]),u.quote&&Do(u.quote),ja.cancel())}function Ac(){ja.cancel(),$s&&($s=void 0,Sc()&&Ii())}let Ri=null,Qh=()=>Ye.querySelector("#persona-scroll-container")||se,Wi=()=>{Ri!==null&&(cancelAnimationFrame(Ri),Ri=null),Un=!1},Jh=()=>{zr!==null&&(cancelAnimationFrame(zr),zr=null),hc=!1,Wi()},Ex=()=>Gn&&xu()&&(An()!=="anchor-top"||Wa()),Au=()=>{let a=Nr()||"Jump to latest",u=Ex();$t.toggleAttribute("data-persona-scroll-to-bottom-streaming",u),Kr>0?(Zt.textContent=String(Kr),Zt.style.display="",$t.setAttribute("aria-label",`${a} (${Kr} new)`)):(Zt.textContent="",Zt.style.display="none",$t.setAttribute("aria-label",u?`${a} (response streaming below)`:a))},Zh=()=>{Kr!==0&&(Kr=0,Au())},Tx=()=>{let a=rn?.spacerHeight??0;return a<=0?di(se,mr):Ec(a)-se.scrollTop-se.clientHeight<=mr},xu=()=>Co()?!Yn.isFollowing():!Tx(),Mu=()=>!!R&&R.getMessages().length>0,Mn=()=>{if(!Zp()||Jl()){$t.parentNode&&$t.remove(),$t.style.display="none";return}$t.parentNode!==ve&&ve.appendChild($t),He();let u=er(se)>0&&xu()&&Mu();u?Au():Zh(),$t.style.display=u?"":"none"},Oi=()=>{Yn.pause()&&(Jh(),Mn())},$o=()=>{Yn.resume(),Zh(),Mn()},Yr=(a=!1)=>{Co()&&Mu()&&Yn.isFollowing()&&(!a&&!Gn||(zr!==null&&(cancelAnimationFrame(zr),zr=null),hc=!0,zr=requestAnimationFrame(()=>{zr=null,hc=!1,Yn.isFollowing()&&Px(Qh(),a?220:140)})))},ey=(a,u,m,b=()=>!0)=>{let w=a.scrollTop,k=u(),q=k-w;if(Wi(),Math.abs(q)<1){Un=!0,a.scrollTop=k,Xn=a.scrollTop,Un=!1;return}let ne=performance.now();Un=!0;let G=ie=>1-Math.pow(1-ie,3),re=ie=>{if(!b()){Wi();return}let le=u();le!==k&&(k=le,q=k-w);let Te=ie-ne,rt=Math.min(Te/m,1),pt=G(rt),lt=w+q*pt;a.scrollTop=lt,Xn=a.scrollTop,rt<1?Ri=requestAnimationFrame(re):(a.scrollTop=k,Xn=a.scrollTop,Ri=null,Un=!1)};Ri=requestAnimationFrame(re)},Px=(a,u=500)=>{let m=er(a)-a.scrollTop;if(Math.abs(m)<1){Xn=a.scrollTop;return}if(Math.abs(m)>=wx){Wi(),Un=!0,a.scrollTop=er(a),Xn=a.scrollTop,Un=!1;return}ey(a,()=>er(a),u,()=>Yn.isFollowing())},Eu=()=>{if(!Mu()){Mn();return}let a=Qh();Un=!0,a.scrollTop=er(a),Xn=a.scrollTop,Un=!1,Mn()},Us=a=>{let u=0,m=a;for(;m&&m!==se;)u+=m.offsetTop,m=m.offsetParent;return u},kx=()=>{let a=se.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??se.ownerDocument.getSelection()},xc=()=>Jw(kx(),se),Tu=()=>{if(oc()!=="last-user-turn")return!1;let a=R?.getMessages()??[];if(a.length<2)return!1;let u=[...a].reverse().find(k=>k.role==="user");if(!u)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(u.id):u.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=se.querySelector(`[data-message-id="${m}"]`);if(!b)return!1;let w=Math.min(Math.max(0,Us(b)-Ms()),er(se));return Un=!0,se.scrollTop=w,Xn=se.scrollTop,Un=!1,An()==="follow"&&!di(se,mr)&&Yn.pause(),Mn(),!0},Mc=a=>{let u=Math.max(0,Math.round(a));Yt.style.height=`${u}px`,Yt.style.display=u>0?"":"none",rn&&(rn.spacerHeight=Math.max(0,a))},Ec=a=>{let u=parseFloat(getComputedStyle(se).paddingBottom)||0,m=0;for(let w of Array.from(se.children)){if(w===Yt||w.offsetHeight===0)continue;let k=Us(w)+w.offsetHeight;k>m&&(m=k)}let b=se.scrollHeight-a;return m>0?Math.min(m+u,b):b},Lx=()=>{if(!rn||rn.spacerHeight<=0)return;let a=Ec(rn.spacerHeight),u=Math.max(0,Math.round(se.scrollTop)+se.clientHeight-a+mr);u<rn.spacerHeight&&(Mc(u),Mn())},Vs=()=>{Ns!==null&&(cancelAnimationFrame(Ns),Ns=null),Wi(),rn=null,Yt.style.height="0px",Yt.style.display="none"},ty=a=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Pu=a=>se.querySelector(`[data-message-id="${ty(a)}"]`),ny=a=>{Ns!==null&&cancelAnimationFrame(Ns),Ns=requestAnimationFrame(()=>{Ns=null;let u=ty(a),m=se.querySelector(`[data-message-id="${u}"]`);if(!m)return;let b=Us(m),w=rn?.spacerHeight??0,k=Ec(w),{targetScrollTop:q,spacerHeight:ne}=Yf({anchorOffsetTop:b,topOffset:Ms(),viewportHeight:se.clientHeight,contentHeight:k,slack:mr});rn={initialSpacerHeight:ne,contentHeightAtAnchor:k,spacerHeight:ne},Mc(ne),ey(se,()=>m.isConnected?Math.max(0,Us(m)-Ms()):q,220)})},Bi=()=>{if(An()!=="anchor-top"||!rn||!Hi)return;let a=Pu(Hi);if(!a)return;Wi();let u=rn.spacerHeight,m=Ec(u),{targetScrollTop:b,spacerHeight:w}=Yf({anchorOffsetTop:Us(a),topOffset:Ms(),viewportHeight:se.clientHeight,contentHeight:m,slack:mr});rn={initialSpacerHeight:w,contentHeightAtAnchor:m,spacerHeight:w},Mc(w),Un=!0,se.scrollTop=b,Xn=se.scrollTop,Un=!1,Mn()},Hx=()=>{if(Co()){if(!Yn.isFollowing()||di(se,1))return;Yr(!Gn);return}if(rn&&rn.initialSpacerHeight>0){let a=se.scrollHeight-rn.spacerHeight,u=Zw({initialSpacerHeight:rn.initialSpacerHeight,contentHeightAtAnchor:rn.contentHeightAtAnchor,currentContentHeight:a});u!==rn.spacerHeight&&Mc(u)}Mn()},Ix=a=>{let u=An();u==="follow"?($o(),Yr(!0)):u==="anchor-top"&&(Va=!1,yc=!0,bc=!1,Hi=a,ny(a))},Rx=()=>{if(An()==="anchor-top"){if(yc){Va=!1;return}Va=!0,Vs(),$o(),Yr(!0)}},Wx=96,Ox=a=>{if(Fs===null)return!0;let u=Pu(Fs),m=Pu(a);if(!u||!m)return!0;let b=Us(m)-Us(u);return Ms()+b>se.clientHeight-Wx},Bx=a=>{if(An()!=="anchor-top"||!yc||bc||xc())return;let u=Fs===null;for(let m of a){if(!u){m.id===Fs&&(u=!0);continue}if(Gw(m)){if(m.id===Hi||!Ox(m.id))return;Hi=m.id,ny(m.id);return}}},_x=a=>{let u=new Map;a.forEach(m=>{let b=Cu.get(m.id);u.set(m.id,{streaming:m.streaming,role:m.role}),!b&&m.role==="assistant"&&(Y.emit("assistant:message",m),!Li&&(An()!=="anchor-top"||Wa())&&xu()&&(Kr+=1,Au(),Mn(),Ps(Kr===1?"1 new message below.":`${Kr} new messages below.`))),m.role==="assistant"&&b?.streaming&&m.streaming===!1&&Y.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(b?m.approval.status!=="pending"&&Y.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):Y.emit("approval:requested",{approval:m.approval,message:m}))}),Cu.clear(),u.forEach((m,b)=>{Cu.set(b,m)})},qa=(a,u)=>{let m=u==="user"?"user":"assistant",b=o.layout?.messages?.[m],w=b?.width??"content",k=b?.maxWidth??(w==="full"?`var(--persona-message-${m}-max-width, 100%)`:void 0);a.classList.add("persona-message-row"),a.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),a.classList.add(`persona-message-row-${u}`,`persona-message-width-${w}`),a.classList.toggle("persona-justify-end",u==="user"),a.setAttribute("data-message-role",u),a.setAttribute("data-message-width",w),k?a.style.setProperty("--persona-message-row-max-width",k):a.style.removeProperty("--persona-message-row-max-width")},br=(a,u)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${a}`,m.setAttribute("data-wrapper-id",a),qa(m,u),m},Dx=(a,u,m)=>{let b=new Set;for(let O of u){let _e=O.variant==="tool"?"tool":O.variant==="reasoning"?"reasoning":null;if(!_e||fs(o,_e)!=="row")continue;let De=_e==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;De?.expandable!==!1&&(b.add(O.id),i.observe(O,_e,_e==="tool"?r:s,De))}let w=document.createElement("div"),q=(()=>{let O=d.find(_e=>_e.renderLoadingIndicator);if(O?.renderLoadingIndicator)return O.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),ne=(O,_e)=>_e==null?!1:typeof _e=="string"?(O.textContent=_e,!0):(O.appendChild(_e),!0),G=new Set,re=new Map,ie=new Set,le=d.some(O=>O.renderAskUserQuestion),Te=[],rt=[],pt=o.enableComponentStreaming!==!1,lt=o.approval!==!1,Vn=[],Bt=o.messageActions,Ut=Bt?.showRegenerate===!0&&Bt.enabled!==!1&&lo.current?.isStreaming()!==!0?UC(u):null,Rn=Bt?.showEdit===!0&&Bt.enabled!==!1,qt=Bt?.showQuote===!0&&Bt.enabled!==!1,vt=null,qo=o.features?.reasoningDisplay?.completedVisibility,zo=O=>qo==="removed"?!0:qo==="removed-when-short"?Ib(O,o.features?.reasoningDisplay?.shortThinkThreshold):!1,fo=o.features?.toolCallDisplay?.completedVisibility==="removed",mo=O=>O.variant==="reasoning"&&O.reasoning?.status==="complete"?zo(O.reasoning):fo&&O.variant==="tool"&&O.toolCall?.status==="complete";if(u.forEach(O=>{if(mo(O))return;if(G.add(O.id),re.set(O.id,O.role),Bs===O.id&&qr){let Ne=br(O.id,O.role);Ne.setAttribute("data-persona-message-edit-stub","true"),Ne.setAttribute("data-preserve-runtime","true"),w.appendChild(Ne),vt={messageId:O.id,element:qr.element};return}let _e=le&&is(O),De=lt&&O.variant==="approval"&&!!O.approval,oe=!_e&&O.role==="assistant"&&!O.variant&&pt&&Op(O);!De&&jr.has(O.id)&&(a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),jr.delete(O.id)),!oe&&Os.has(O.id)&&(a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),Os.delete(O.id));let Ct=is(O)?`:${O.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${O.agentMetadata?.askUserQuestionAnswers?Object.keys(O.agentMetadata.askUserQuestionAnswers).length:0}`:"",Xt={canRegenerate:Ut===O.id,canEdit:Rn&&Pf(O),canQuote:qt&&!O.variant&&(O.content?.trim().length??0)>0},kn=`${Xt.canRegenerate?"r":""}${Xt.canEdit?"e":""}${Xt.canQuote?"q":""}`,gn=Vw(O,Ds)+Ct+`:${kn}`,Mt=_e||De||oe?null:qw(xn,O.id,gn);if(Mt){w.appendChild(Mt.cloneNode(!0)),is(O)&&O.toolCall?.id&&O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(ie.add(O.toolCall.id),uu(O));return}let zt=null,sn=d.find(Ne=>!!(O.variant==="reasoning"&&Ne.renderReasoning||O.variant==="tool"&&Ne.renderToolCall||!O.variant&&Ne.renderMessage)),Ie=o.layout?.messages;if(is(O)&&O.agentMetadata?.askUserQuestionAnswered===!0){ki.delete(O.id),a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime");return}if(Zi(O)&&ps(o).enabled)return;if(is(O)&&o.features?.askUserQuestion?.enabled!==!1){let Ne=d.find(an=>typeof an.renderAskUserQuestion=="function");if(Ne&&lo.current){let an=ki.get(O.id),ho=an!==gn,fn=null;if(ho){let{payload:ze,complete:Fe}=as(O),rs=O.id,en=()=>lo.current?.getMessages().find(jn=>jn.id===rs);fn=Ne.renderAskUserQuestion({message:O,payload:ze,complete:Fe,resolve:jn=>{let Ar=en();Ar&&lo.current?.resolveAskUserQuestion(Ar,jn)},dismiss:()=>{let jn=en();jn?.agentMetadata?.awaitingLocalTool&&(lo.current?.markAskUserQuestionResolved(jn),lo.current?.resolveAskUserQuestion(jn,"(dismissed)"))},config:o})}let wt=an!=null;if(ho&&fn===null&&!wt){O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(ie.add(O.toolCall.id),uu(O));return}let Oe=br(O.id,O.role);Oe.setAttribute("data-ask-plugin-stub","true"),Oe.setAttribute("data-preserve-runtime","true"),w.appendChild(Oe),Te.push({messageId:O.id,fingerprint:gn,bubble:fn});return}else{O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(ie.add(O.toolCall.id),uu(O));return}}else if(De){let Ne=_();if(!Ne){w.appendChild(br(O.id,O.role));return}let an=d.find(Oe=>typeof Oe.renderApproval=="function")??C,fn=jr.get(O.id)!==gn,wt=null;if(fn&&an?.renderApproval){let Oe=O.id,ze=(Fe,rs)=>{let en=lo.current?.getMessages().find(jn=>jn.id===Oe);en?.approval&&(en.approval.toolType==="webmcp"?lo.current?.resolveWebMcpApproval(en.id,Fe):lo.current?.resolveApproval(en.approval,Fe,rs))};wt=an.renderApproval({message:O,defaultRenderer:()=>Ne.createApprovalBubble(O,o,l),config:o,approve:Fe=>ze("approved",Fe),deny:Fe=>ze("denied",Fe)})}if(fn&&wt===null)a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),jr.delete(O.id),zt=Ne.createApprovalBubble(O,o,l);else{let Oe=br(O.id,O.role);Oe.setAttribute("data-approval-plugin-stub","true"),Oe.setAttribute("data-preserve-runtime","true"),w.appendChild(Oe),Vn.push({messageId:O.id,fingerprint:gn,bubble:wt});return}}else if(sn)if(O.variant==="reasoning"&&O.reasoning&&sn.renderReasoning){if(!Z)return;zt=sn.renderReasoning({message:O,defaultRenderer:()=>vm(O,o,s),config:o})}else if(O.variant==="tool"&&O.toolCall&&sn.renderToolCall){if(!ye)return;zt=sn.renderToolCall({message:O,defaultRenderer:()=>Am(O,o,r),config:o})}else sn.renderMessage&&(zt=sn.renderMessage({message:O,defaultRenderer:()=>{let Ne=ql(O,m,Ie,o.messageActions,Kn,{loadingIndicatorRenderer:q,widgetConfig:o,actionEligibility:Xt});return O.role!=="user"&&j(Ne,O,o,R),Ne},config:o}));if(!zt&&oe){let Ne=_m(O);if(Ne){let an=Os.get(O.id),ho=an!==gn,fn=o.wrapComponentDirectiveInBubble!==!1&&tr.getOptions(Ne.component)?.bubbleChrome!==!1,wt=null;if(ho){let Oe=Bm(Ne,{config:o,message:O,transform:m});if(Oe&&Ne.component==="PersonaArtifactInline"){let ze=Oe.hasAttribute("data-artifact-inline")?Oe:Oe.querySelector("[data-artifact-inline]"),Fe=ze?.getAttribute("data-artifact-inline")??"",rs=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Fe):Fe,en=Fe?a.querySelector(`#wrapper-${O.id}`)?.querySelector(`[data-artifact-inline="${rs}"]`)??null:null;ze&&en&&en!==ze&&Wr()?.hasLiveInlineArtifactBlock(en)&&(ze===Oe?Oe=en:ze.replaceWith(en))}if(Oe)if(fn){let ze=document.createElement("div");if(ze.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),ze.id=`bubble-${O.id}`,ze.setAttribute("data-message-id",O.id),O.content&&O.content.trim()){let Fe=document.createElement("div");Fe.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Fe.innerHTML=m({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),ze.appendChild(Fe)}ze.appendChild(Oe),wt=ze}else{let ze=document.createElement("div");if(ze.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",ze.id=`bubble-${O.id}`,ze.setAttribute("data-message-id",O.id),ze.setAttribute("data-persona-component-directive","true"),O.content&&O.content.trim()){let Fe=document.createElement("div");Fe.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Fe.innerHTML=m({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),ze.appendChild(Fe)}ze.appendChild(Oe),wt=ze}}if(wt||an!=null){let Oe=br(O.id,O.role);Oe.setAttribute("data-component-directive-stub","true"),Oe.setAttribute("data-preserve-runtime","true"),w.appendChild(Oe),rt.push({messageId:O.id,fingerprint:gn,bubble:wt});return}}}if(!zt)if(O.variant==="reasoning"&&O.reasoning){if(!Z)return;zt=vm(O,o,s)}else if(O.variant==="tool"&&O.toolCall){if(!ye)return;zt=Am(O,o,r)}else if(O.variant==="approval"&&O.approval){if(o.approval===!1)return;let Ne=_();if(!Ne)return;zt=Ne.createApprovalBubble(O,o,l)}else{let Ne=o.layout?.messages;Ne?.renderUserMessage&&O.role==="user"?zt=Ne.renderUserMessage({message:O,config:o,streaming:!!O.streaming}):Ne?.renderAssistantMessage&&O.role==="assistant"?zt=Ne.renderAssistantMessage({message:O,config:o,streaming:!!O.streaming}):zt=ql(O,m,Ne,o.messageActions,Kn,{loadingIndicatorRenderer:q,widgetConfig:o,actionEligibility:Xt}),O.role!=="user"&&zt&&j(zt,O,o,R)}let Et=br(O.id,O.role);Et.appendChild(zt),zw(xn,O.id,gn,Et),w.appendChild(Et)}),Qe.composerOverlay&&Qe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(_e=>{let De=_e.getAttribute("data-persona-ask-sheet-for");De&&!ie.has(De)&&cs(Qe.composerOverlay,De)}),o.features?.toolCallDisplay?.grouped){let O=[],_e=[],De=o.features.toolCallDisplay.groupedMode==="summary";u.forEach(oe=>{if(oe.variant==="tool"&&oe.toolCall&&ye){if(fo&&oe.toolCall.status==="complete")return;_e.push(oe);return}oe.variant==="reasoning"&&(!Z||oe.reasoning?.status==="complete"&&zo(oe.reasoning))||((_e.length>1||De&&_e.length>0)&&O.push(_e),_e=[])}),(_e.length>1||De&&_e.length>0)&&O.push(_e),O.forEach(oe=>{let Ct=oe.map(Ie=>Array.from(w.children).find(Et=>Et instanceof HTMLElement&&Et.getAttribute("data-wrapper-id")===Ie.id)).filter(Ie=>!!Ie);if(Ct.length<(De?1:2))return;let Xt=br(`tool-group-${oe[0].id}`,"assistant");if(Xt.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let Ie=`tool-group-${oe[0].id}`,Et=oe.some(wt=>wt.toolCall?.status!=="complete"),Ne={...oe[0],id:Ie,toolCall:{id:Ie,name:`${oe.length} tools`,status:Et?"running":"complete",chunks:oe.flatMap(wt=>wt.toolCall?.chunks??[]),success:!oe.some(wt=>wt.toolCall?.success===!1)}};b.add(Ie),i.observe(Ne,"tool",r,o.features.toolCallDisplay);let an=`${Et?"Using":"Used"} ${oe.length} tools`,ho=o.toolCall?.renderGroupedSummary?.({messages:oe,toolCalls:oe.map(wt=>wt.toolCall),defaultSummary:an,config:o}),fn=hC(Ne,o,r.has(Ie),ho??an);fn.bubble.classList.add("persona-tool-group"),fn.body.dataset.personaToolGroupStack="true",Ct[0].before(Xt),Xt.appendChild(fn.bubble),Ct.forEach((wt,Oe)=>{wt.style.setProperty("--persona-message-row-max-width","100%"),wt.style.setProperty("--persona-activity-stagger",`${Oe*40}ms`),wt.classList.add("persona-activity-group-child"),fn.body.appendChild(wt)});return}let kn=document.createElement("div");kn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",kn.setAttribute("data-persona-tool-group","true");let gn=document.createElement("div");gn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",gn.id=`tool-group-summary-${oe[0].id}`;let Mt=`Called ${oe.length} ${oe.length===1?"tool":"tools"}`,zt=o.toolCall?.renderGroupedSummary?.({messages:oe,toolCalls:oe.map(Ie=>Ie.toolCall).filter(Ie=>!!Ie),defaultSummary:Mt,config:o});ne(gn,zt)||(gn.textContent=Mt);let sn=document.createElement("div");sn.className="persona-tool-group-stack persona-flex persona-flex-col",sn.id=`tool-group-stack-${oe[0].id}`,sn.setAttribute("data-persona-tool-group-stack","true"),kn.appendChild(gn),De||kn.appendChild(sn),Xt.appendChild(kn),Ct[0].before(Xt),Ct.forEach((Ie,Et)=>{if(De){Ie.remove();return}Ie.style.setProperty("--persona-message-row-max-width","100%");let Ne=document.createElement("div");Ne.className="persona-tool-group-item persona-relative",Ne.setAttribute("data-persona-tool-group-item","true"),Et<Ct.length-1&&Ne.setAttribute("data-persona-tool-group-connector","true"),Ne.appendChild(Ie),sn.appendChild(Ne)})})}i.prune(b),Kw(xn,G);let ns=O=>O.variant==="tool"&&!ye||O.variant==="reasoning"&&!Z||mo(O),Ko=u.some(O=>O.role==="assistant"&&O.streaming&&!ns(O)),To=u.length-1;for(;To>=0&&ns(u[To]);)To--;let os=To>=0?u[To]:void 0,sl=To<u.length-1,Gs=os?.role==="assistant"&&!os.streaming&&os.variant!=="approval"&&!sl;if(Gn&&u.some(O=>O.role==="user")&&!Ko&&!Gs){let O={config:o,streaming:!0,location:"standalone",defaultRenderer:Aa},_e=d.find(oe=>oe.renderLoadingIndicator),De=null;if(_e?.renderLoadingIndicator&&(De=_e.renderLoadingIndicator(O)),De===null&&o.loadingIndicator?.render&&(De=o.loadingIndicator.render(O)),De===null&&(De=Aa()),De){let oe=document.createElement("div"),Ct=o.loadingIndicator?.showBubble!==!1,Xt=o.layout?.messages?.layout??"bubble";oe.className=Ct?jl("assistant",Xt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),oe.setAttribute("data-typing-indicator","true"),Ct&&(oe.style.color="var(--persona-message-assistant-text, var(--persona-text))",Xt!=="flat"&&(oe.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",oe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),oe.appendChild(De);let kn=br("typing-indicator","assistant");kn.appendChild(oe),w.appendChild(kn)}}if(!Gn&&u.length>0){let O=u[u.length-1],_e={config:o,lastMessage:O,messageCount:u.length},De=d.find(Ct=>Ct.renderIdleIndicator),oe=null;if(De?.renderIdleIndicator&&(oe=De.renderIdleIndicator(_e)),oe===null&&o.loadingIndicator?.renderIdle&&(oe=o.loadingIndicator.renderIdle(_e)),oe){let Ct=document.createElement("div"),Xt=o.loadingIndicator?.showBubble!==!1;Ct.className=Xt?["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(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ct.setAttribute("data-idle-indicator","true"),Ct.appendChild(oe);let kn=br("idle-indicator","assistant");kn.appendChild(Ct),w.appendChild(kn)}}if(HC(w),fp(a,w),Af(a),vt){let{messageId:O,element:_e}=vt,De=a.querySelector(`#wrapper-${O}`);De&&_e.parentElement!==De&&(qa(De,re.get(O)??"user"),De.replaceChildren(_e))}if(Te.length>0)for(let{messageId:O,fingerprint:_e,bubble:De}of Te){let oe=a.querySelector(`#wrapper-${O}`);oe&&(qa(oe,re.get(O)??"assistant"),De!==null&&(oe.replaceChildren(De),oe.setAttribute("data-bubble-fp",_e),ki.set(O,_e)))}if(ki.size>0)for(let O of ki.keys())G.has(O)||ki.delete(O);if(rt.length>0)for(let{messageId:O,fingerprint:_e,bubble:De}of rt){let oe=a.querySelector(`#wrapper-${O}`);oe&&(qa(oe,re.get(O)??"assistant"),De!==null&&(oe.replaceChildren(De),oe.setAttribute("data-bubble-fp",_e),Os.set(O,_e)))}if(Os.size>0)for(let O of Os.keys())G.has(O)||Os.delete(O);if(Vn.length>0)for(let{messageId:O,fingerprint:_e,bubble:De}of Vn){let oe=a.querySelector(`#wrapper-${O}`);oe&&(qa(oe,re.get(O)??"assistant"),De!==null&&(oe.replaceChildren(De),oe.setAttribute("data-bubble-fp",_e),jr.set(O,_e)))}if(jr.size>0)for(let O of jr.keys())G.has(O)||jr.delete(O)},ku=!1,Tc=()=>{ku||(ku=!0,oi().catch(()=>{}),mg().catch(()=>{ku=!1}))},co=(a,u,m)=>{u.length>0&&Tc(),Dx(a,u,m),Ch()},za=null,Nx=()=>{if(za)return;let a=m=>{let b=m.composedPath();b.includes(Ye)||Gt&&b.includes(Gt)||xt(!1,"user")};za=a,(e.ownerDocument??document).addEventListener("pointerdown",a,!0)},oy=()=>{if(!za)return;(e.ownerDocument??document).removeEventListener("pointerdown",za,!0),za=null};Ce.push(()=>oy());let Ka=null,Fx=()=>{if(Ka)return;let a=m=>{m.key==="Escape"&&(m.isComposing||xt(!1,"user"))};Ka=a,(e.ownerDocument??document).addEventListener("keydown",a,!0)},ry=()=>{if(!Ka)return;(e.ownerDocument??document).removeEventListener("keydown",Ka,!0),Ka=null};Ce.push(()=>ry());let Ga=!1,sy=new Set,$x=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},_i=()=>{if(!Pe())return;let a=Qe.peekBanner,u=Qe.peekTextNode;if(!a||!u)return;if(D){a.classList.remove("persona-pill-peek--visible");return}let m=R?.getMessages()??[],b;for(let Bt=m.length-1;Bt>=0;Bt--){let Ut=m[Bt];if(Ut.role==="assistant"&&Ut.content){b=Ut;break}}if(!b){a.classList.remove("persona-pill-peek--visible");return}let w=b.content,k=!!b.streaming,q=$x(),ne=mp(q),G=ne.type!=="none"?yu(ne.type,q?.plugins):null,re=G?.isAnimating?.(b)===!0,ie=G!==null&&(k||re);ie&&G&&!sy.has(G.name)&&(Nl(G,e),sy.add(G.name));let le=ie&&G?.containerClass?G.containerClass:null,Te=u.dataset.personaPeekStreamClass??null;Te&&Te!==le&&(u.classList.remove(Te),delete u.dataset.personaPeekStreamClass),le&&Te!==le&&(u.classList.add(le),u.dataset.personaPeekStreamClass=le),ie?(u.style.setProperty("--persona-stream-step",`${ne.speed}ms`),u.style.setProperty("--persona-stream-duration",`${ne.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let rt=ie?yp(w,ne.buffer,G,b,k):w;if(ie&&ne.placeholder==="skeleton"&&k&&(!rt||!rt.trim())){let Bt=document.createElement("div"),Ut=Dl();Ut.classList.add("persona-pill-peek__skeleton"),Bt.appendChild(Ut),fp(u,Bt)}else{let Bt=Math.max(0,rt.length-100),Ut=rt.length>100?rt.slice(-100):rt,Rn=ms(Ut);if(!ie||!G){let qt=rt.length>100?`\u2026${Ut}`:Ut;u.textContent!==qt&&(u.textContent=qt)}else{let qt=Rn;(G.wrap==="char"||G.wrap==="word")&&(qt=_l(Rn,G.wrap,`peek-${b.id}`,{skipTags:G.skipTags,startIndex:Bt}));let vt=document.createElement("div");if(vt.innerHTML=qt,G.useCaret&&Ut.length>0){let qo=bp(),zo=vt.querySelectorAll(".persona-stream-char, .persona-stream-word"),fo=zo[zo.length-1];fo?.parentNode?fo.parentNode.insertBefore(qo,fo.nextSibling):vt.appendChild(qo)}fp(u,vt),G.onAfterRender?.({container:u,bubble:a,messageId:b.id,message:b,speed:ne.speed,duration:ne.duration})}}let Vn=Gn||Ga;a.classList.toggle("persona-pill-peek--visible",Vn)};if(Pe()){let a=Qe.peekBanner;if(a){let b=w=>{w.preventDefault(),w.stopPropagation(),xt(!0,"user")};a.addEventListener("pointerdown",b),Ce.push(()=>{a.removeEventListener("pointerdown",b)})}let u=()=>{Ga||(Ga=!0,_i())},m=()=>{Ga&&(Ga=!1,_i())};we.addEventListener("pointerenter",u),we.addEventListener("pointerleave",m),Ce.push(()=>{we.removeEventListener("pointerenter",u),we.removeEventListener("pointerleave",m)}),Gt&&(Gt.addEventListener("pointerenter",u),Gt.addEventListener("pointerleave",m),Ce.push(()=>{Gt.removeEventListener("pointerenter",u),Gt.removeEventListener("pointerleave",m)}))}let Ux=a=>{let u=o.launcher?.composerBar??{},m=u.expandedSize??"anchored",b=u.bottomOffset??"16px",w=u.collapsedMaxWidth,k=u.expandedMaxWidth??"880px",q=u.expandedTopOffset??"5vh",ne=u.modalMaxWidth??"880px",G=u.modalMaxHeight??"min(90vh, 800px)",re="calc(100vw - 32px)",ie="var(--persona-pill-area-height, 80px)",le=Ye.style;if(le.left="",le.right="",le.top="",le.bottom="",le.transform="",le.width="",le.maxWidth="",le.height="",le.maxHeight="",Gt){let Te=Gt.style;Te.bottom=b,Te.width=w??""}if(a&&m!=="fullscreen"){if(m==="modal"){le.top="50%",le.left="50%",le.transform="translate(-50%, -50%)",le.bottom="auto",le.right="auto",le.width=ne,le.maxWidth=re,le.maxHeight=G,le.height=G;return}le.left="50%",le.transform="translateX(-50%)",le.bottom=`calc(${b} + ${ie})`,le.top=q,le.width=k,le.maxWidth=re}},Ya=()=>{if(D&&Tc(),!Ke())return;if(Pe()){let re=(o.launcher?.composerBar??{}).expandedSize??"anchored",ie=D?"expanded":"collapsed";Ye.dataset.state=ie,Ye.dataset.expandedSize=re,Gt&&(Gt.dataset.state=ie,Gt.dataset.expandedSize=re),Ye.style.removeProperty("display"),Ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ux(D),ve.style.display=D?"flex":"none",ks(),D?(Nx(),Fx()):(oy(),ry()),_i();return}let a=Ht(o),u=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,b=o.launcher?.mobileFullscreen??!0,w=u.innerWidth<=m,k=b&&w&&me,q=to(o).reveal;D?(Ye.style.removeProperty("display"),Ye.style.display=a?"flex":"",Ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0"),we.classList.add("persona-scale-100","persona-opacity-100"),Vt?(Vt.setPanelOpen(!0),Vt.element.style.display="none"):In&&(In.style.display="none")):(a?a&&(q==="overlay"||q==="push")&&!k?(Ye.style.removeProperty("display"),Ye.style.display="flex",Ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ye.style.setProperty("display","none","important"),Ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ye.style.display="",Ye.classList.add("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100"),we.classList.add("persona-scale-95","persona-opacity-0")),Vt?(Vt.setPanelOpen(!1),Vt.element.style.display=a?"none":""):In&&(In.style.display=a?"none":""))},xt=(a,u="user")=>{if(!Ke()||D===a)return;let m=D;D=a,Ya();let b=(()=>{let k=o.launcher?.sidebarMode??!1,q=e.ownerDocument.defaultView??window,ne=o.launcher?.mobileFullscreen??!0,G=o.launcher?.mobileBreakpoint??640,re=q.innerWidth<=G,ie=Ht(o)&&ne&&re,le=Pe()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return k||ne&&re&&me||ie||le})();if(D&&b){if(!No){let k=e.getRootNode(),q=k instanceof ShadowRoot?k.host:e.closest(".persona-host");q&&(No=Jf(q,o.launcher?.zIndex??Tn))}Fo||(Fo=Zf(e.ownerDocument))}else D||(No?.(),No=null,Fo?.(),Fo=null);D&&(nl(),Tu()||(An()==="follow"?Yr(!0):Eu()));let w={open:D,source:u,timestamp:Date.now()};D&&!m?Y.emit("widget:opened",w):!D&&m&&Y.emit("widget:closed",w),Y.emit("widget:state",{open:D,launcherEnabled:me,voiceActive:ot.active,streaming:R.isStreaming()})},Xr={inputDisabled:!1,sendDisabled:!1},Uo=()=>Xr.inputDisabled,Lu=()=>On(o.voiceRecognition?.provider)&&!!R&&(R.isBargeInActive()||["listening","processing","speaking"].includes(R.getVoiceStatus())),js=()=>Xr.inputDisabled||Xr.sendDisabled,Vx=()=>(Xr.inputDisabled?Xr.inputReason:void 0)??(Xr.sendDisabled?Xr.sendReason:void 0);function Hu(){if(!Ee)return;if(he.getState().phase==="streaming"){Ee.disabled=!1;return}let a=Ue?!Ue.isReady():!1;Ee.disabled=js()||a}function Pc(){if(!Hn)return;let a=he.getState(),u=o.sendButton?.visibility==="when-text"&&a.phase!=="streaming"&&a.text.trim().length===0&&a.attachments.length===0;Hn.toggleAttribute("data-persona-send-hidden",u)}function jx(){let a=Vx();if(Pe()){let u=wn??qe;a?u.setAttribute("title",a):u.removeAttribute("title"),qe.toggleAttribute(Ha,!!a);return}if(a){nt.setAttribute("role","status"),nt.setAttribute("aria-live","polite"),nt.setAttribute(Ha,""),nt.textContent=a,ri(nt,o.statusIndicator??{},"idle");return}if(nt.hasAttribute(Ha)&&(nt.removeAttribute("role"),nt.removeAttribute("aria-live"),nt.removeAttribute(Ha),h)){let u=R.getStatus();As(nt,ar(u),o.statusIndicator??{},u)}}function Iu(){let a=nf(o.composer?.inputDisabled),u=nf(o.composer?.sendDisabled);Xr={inputDisabled:a.disabled,inputReason:a.reason,sendDisabled:u.disabled,sendReason:u.reason},he.setInputDisabled(a.disabled),he.setSendDisabled(u.disabled);let m=he.getState().phase==="streaming",b=a.disabled,w=m||b;ae&&(ae instanceof HTMLTextAreaElement?ae.disabled=b:ae.setAttribute("contenteditable",b?"false":"true"),ae.setAttribute("aria-disabled",b?"true":"false")),kt&&(kt.disabled=b),At&&(At.disabled=b);for(let k of st?.affordanceButtons??[])k.querySelectorAll("button").forEach(q=>{q.disabled=b});fe&&(fe.disabled=b||m&&!Lu()),Hs.forEach(k=>{k.elements.forEach(q=>{q.toggleAttribute("data-disabled",w),q instanceof HTMLButtonElement||q.setAttribute("aria-disabled",w?"true":"false")}),k.buttons.forEach(q=>{q.disabled=w})}),Du.forEach(k=>{k.toggleAttribute("data-disabled",w),k instanceof HTMLButtonElement?k.disabled=w:k.setAttribute("aria-disabled",w?"true":"false"),k.querySelectorAll("button").forEach(q=>{q.disabled=w})}),qe.dataset.personaComposerStreaming=m?"true":"false",qe.dataset.personaComposerInputDisabled=b?"true":"false",qe.dataset.personaComposerSendDisabled=js()?"true":"false",qe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(k=>{(k instanceof HTMLButtonElement||k instanceof HTMLInputElement||k instanceof HTMLTextAreaElement||k instanceof HTMLSelectElement)&&(k.disabled=m)}),Hu(),jx()}let Xa=a=>{he.setStreaming(a),tc(a?"stop":"send"),Iu()},kc=()=>{ot.active||ae&&ae.focus()};Y.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>kc(),200)});let iy=null,Ru=!1,Wu=!Jt.hidden,Qr=null,Ou=!Q,Lc=null;Ce.push(()=>{Lc?.cancel(),Lc=null});let qx=a=>{let u=TS(a);if(u===N)return;N=u,e.setAttribute("data-persona-conversation-state",u);let m=ce();Rt(),Ou&&(Lc?.cancel(),Lc=MS(qe,u==="active"?m:ce(),u==="active"?"drop":"rise",M().layout==="centered"?320:260)),Bi()},ay=null,ly,cy=null,Di=null,Bu=!1,Qa=a=>{let u=M(),m=`${u.variant}|${u.layout}|${u.dismiss}|${u.anchor??"bottom"}|${u.align??""}|${u.iconPlacement}|${u.kicker??""}|${u.title}|${u.subtitle}`;(m!==ay||u.icon!==ly)&&(ay=m,ly=u.icon,xp({host:Jt,iconHolder:Zl,kicker:ec,title:Qp,subtitle:vi,starterSuggestions:lr},u));let b=u.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${u.message}`;b!==cy&&(cy=b,Mp(Ln,u.message,o));let w=a??(R?R.getMessages():o.initialMessages);qx(w);let k=Ru,q=!k&&pi(u,w),ne=q!==Wu;if(Wu=q,Di){Qr?.cancel(),Qr=null,k!==Bu&&(Bu=k,k?pm(se,Jt,null):dm(se,Jt,Di)),xa(se,Jt,!k);return}if(ne&&!q&&!k&&u.dismiss==="on-first-message"&&Ou){Qr=xS(Jt,re=>{Qr===re&&(Qr=null),!Wu&&!Di&&(xa(se,Jt,!1),Bi()),re?.cancel()});return}if(Qr){if(!q&&!k)return;Qr.cancel(),Qr=null}let G=!Jt.hidden;xa(se,Jt,q),!q&&G&&Bi()},_u=[],Du=[],Nu=!1,dy=null,py,uy=()=>{Du.length=0;let a=_u.splice(0,_u.length);for(let u of a)try{u()}catch(m){console.warn("[persona] renderWelcome cleanup threw",m)}};Ce.push(uy);let zx=(a,u)=>{let m=tm(a,u);if(!m)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),x("span");let b=o.suggestions?.starters,w=nm({item:{...m,behavior:m.behavior??b?.behavior??"send"},index:u,surface:"starter",source:"config",variant:b?.variant??"card",streaming:h?R.isStreaming():!1,config:o,plugins:d,chipsConfig:o.suggestionChipsConfig,session:R,getTextarea:()=>ae,eventTarget:Jt,submitPrompt:Dc});return Du.push(w),w},Fu=()=>{if(Nu)return;Nu=!0;let a=M();dy=`${a.variant}|${a.layout}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`,py=a.icon;try{uy(),pm(se,Jt,Di),Di=null,Bu=!1;let u=R?R.getMessages():o.initialMessages,m=pi(a,u),b=0,w=null;for(let k of d)if(k.renderWelcome&&(w=k.renderWelcome({config:a,variant:a.variant,visible:m,defaultRenderer:()=>Jt,sendMessage:q=>{if(!R||R.isStreaming())return;let ne=q.trim();ne&&R.sendMessage(ne)},requestRender:()=>Fu(),renderStarter:q=>zx(q,b++),storage:y(k.id),onCleanup:q=>{_u.push(q)}}),w))break;w&&w!==Jt&&(Di=w,dm(se,Jt,w))}finally{Nu=!1}Qa()},Kx=()=>{let a=M();`${a.variant}|${a.layout}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`===dy&&a.icon===py||Fu()},Hc=()=>{Qa(),Ti||(ae.placeholder=bw(he.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!R?.isStreaming()&&(Ee.textContent=o.copy?.sendButtonLabel??"Send")),ae.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ae.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},Gx=!!o.setStoredConversationId,Ni=a=>Ve(u=>{let m={...u};return delete m[a],m}),Ic=a=>{let u=P[a];return typeof u=="string"?u:null},gy=()=>{let a=P.durableResume;if(!a||typeof a!="object")return null;let u=a;return typeof u.executionId=="string"&&u.executionId.length>0&&typeof u.after=="string"&&u.after.length>0?{executionId:u.executionId,after:u.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Ic("sessionId"),setStoredSessionId:a=>{Ve(u=>({...u,sessionId:a}))},clearStoredSessionId:o.clearStoredSessionId??(()=>Ni("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Ic("conversationId")),setStoredConversationId:o.setStoredConversationId??(a=>{Ve(u=>({...u,conversationId:a}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>Ni("conversationId"))});let fy=()=>o.clientToken??null,my=a=>cA(a,bt(),o.persistState===!1),hy=fy(),po=hy?my(hy):null,Yx=()=>{let a=P.pendingDisplayProjections;if(!a||typeof a!="object")return null;let u=a;return typeof u.conversationId!="string"||!Array.isArray(u.messageIds)?null:{conversationId:u.conversationId,messageIds:u.messageIds.filter(m=>typeof m=="string")}},Jr={...po?{visitorStore:po}:{},historyBootstrapReady:o.features?.history?.enabled===!0&&!Ud()?Promise.all([de,ge]).then(()=>{}):de,getStoredMessageCursor:()=>Ic("historyMessageCursor"),setStoredMessageCursor:a=>{if(a===null){Ni("historyMessageCursor");return}Ve(u=>({...u,historyMessageCursor:a}))},getPendingDisplayProjections:Yx,setPendingDisplayProjections:a=>{if(!a){Ni("pendingDisplayProjections");return}Ve(u=>({...u,pendingDisplayProjections:a}))},getStoredResumableHandle:gy,setStoredResumableHandle:a=>{if(!a){Ni("durableResume");return}Ve(u=>({...u,durableResume:a}))},shouldResumeDurableConversation:()=>B&&gy()!==null,...Gx?{}:{getStoredConversationRevision:()=>Ic("conversationRevision"),setStoredConversationRevision:a=>{if(a===null){Ni("conversationRevision");return}Ve(u=>({...u,conversationRevision:a}))}}};if(B){let a=o.onExecutionState,u=e.ownerDocument.defaultView,m=!1,b=()=>m=!0,w=()=>m=!1;u?.addEventListener("pagehide",b),u?.addEventListener("pageshow",w),Ce.push(()=>{u?.removeEventListener("pagehide",b),u?.removeEventListener("pageshow",w)}),o={...o,reconnectStream:o.reconnectStream??(k=>R.getClient().reconnectClientTokenStream(k)),onExecutionState:k=>{(k||!m)&&Jr.setStoredResumableHandle?.(k?{executionId:k.executionId,after:k.lastEventId}:null),a?.(k)}}}let Xx=()=>{let a=fy();if(a&&po?.matches(a,bt(),o.persistState===!1)||!a&&!po)return;po?.destroy(),po=a?my(a):null;let u={...Jr};po?u.visitorStore=po:delete u.visitorStore,Jr=u,R.setHistoryInternals(Jr)},qs=null,Qx=()=>{qs==null&&(qs=setInterval(()=>{let a=Me.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(qs),qs=null;return}let u=Date.now();a.forEach(m=>{let b=Number(m.getAttribute("data-tool-elapsed"));b&&(m.textContent=m.closest(".persona-activity-row")?xl(u-b):ed(u-b))})},100))},$u=(a,u)=>{if(Object.is(a,u))return!0;if(a===null||u===null||typeof a!="object"||typeof u!="object")return!1;if(Array.isArray(a)||Array.isArray(u))return!Array.isArray(a)||!Array.isArray(u)||a.length!==u.length?!1:a.every((q,ne)=>$u(q,u[ne]));let m=a,b=u,w=Object.keys(m),k=Object.keys(b);return w.length===k.length&&w.every(q=>Object.prototype.hasOwnProperty.call(b,q)&&$u(m[q],b[q]))},yy=a=>{let{content:u,rawContent:m,llmContent:b,...w}=a;return w},Uu=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!Op(a),Jx=(a,u,m)=>{if(a.length!==u.length)return!1;let b=a[m.index],w=u[m.index];return!b||!w||b.id!==m.id||w.id!==m.id?!1:(!Object.is(b.content,w.content)||!Object.is(b.rawContent,w.rawContent)||!Object.is(b.llmContent,w.llmContent))&&Uu(b)&&Uu(w)&&$u(yy(b),yy(w))},Rc=null,Fi=null,zs=null,vr=null,Vu=null,Zx=a=>{if(!B)return Ii(a);Vu=a,queueMicrotask(()=>{Vu===a&&(Vu=null,Ii(a))})},Wc=a=>{Rc=a;let u,m;Fi=null;for(let w=a.length-1;w>=0;w-=1){let k=a[w];if(!u&&k.role==="user"&&(u=k),!m&&k.role==="assistant"&&(m=k),!Fi&&Uu(k)&&(Fi={index:w,id:k.id}),u&&m&&Fi)break}co(Me,a,K),Wr()?.updateInlineArtifactBlocks(Me,ao.artifacts,{suppressTransition:Gn}),Qx(),Qa(a),Ws(a),Yr(!Gn),_x(a),a.length===0&&(Vs(),Va=!0,yc=!1,Hi=null,bc=!1),!bu||Li?(bu=!0,Fs=u?.id??null,vu=m?.id??null):u&&u.id!==Fs?(Fs=u.id,Ix(u.id)):m&&m.id!==vu&&Rx(),m&&(vu=m.id),Bx(a);let b=ot.lastUserMessageId;u&&u.id!==b&&(ot.lastUserMessageId=u.id,Y.emit("user:message",u)),ot.lastUserMessageWasVoice=!!u?.viaVoice,Zx(a),_i()},ju=()=>{vr!==null&&(cancelAnimationFrame(vr),vr=null);let a=zs;zs=null,a&&Wc(a)},by=()=>{vr!==null&&cancelAnimationFrame(vr),vr=null,zs=null},eM=a=>{let u=zs??Rc;if(Gn&&u&&Fi&&Jx(u,a,Fi)){zs=a,vr===null&&(vr=requestAnimationFrame(()=>{vr=null;let m=zs;zs=null,m&&Wc(m)}));return}if(a.length===0){by(),Wc(a);return}ju(),Wc(a)};R=new kl(o,{onMessagesChanged(a){eM(a)},onStatusChanged(a){let u=o.statusIndicator??{};As(nt,(b=>b==="idle"?u.idleText??Kt.idle:b==="connecting"?u.connectingText??Kt.connecting:b==="connected"?u.connectedText??Kt.connected:b==="error"?u.errorText??Kt.error:b==="paused"?u.pausedText??Kt.paused:b==="resuming"?u.resumingText??Kt.resuming:Kt[b])(a),u,a),_r()},onStreamingChanged(a){a||(R?.getMessages().length===0?by():ju()),Gn=a,Xa(a),_r(),R&&co(Me,R.getMessages(),K),a||(Yr(!0),Lx(),Vh=!0,R&&jh(R.getMessages(),ps(o))),Mn(),Ps(a?"Responding\u2026":"Response complete."),_i()},onVoiceStatusChanged(a){if(Y.emit("voice:status",{status:a,timestamp:Date.now()}),!(a!=="disconnected"&&!On(o.voiceRecognition?.provider)))switch(a){case"listening":if(!wu){let u=R.getVoiceDisclosure();u&&(wu=!0,Pe()?(vc=ae.placeholder,ae.placeholder=u,Ps(u)):ky(u,1e4))}Sr(),ji();break;case"processing":Sr(),AM();break;case"speaking":Sr(),xM();break;default:a==="idle"&&R.isBargeInActive()?(Sr(),ji(),fe?.setAttribute("aria-label","End voice session")):(ot.active=!1,wu=!1,vc!==null&&(ae.placeholder=vc,vc=null),Sr(),yr("system"),Eo());break}},onArtifactsState(a){ao=a,a.artifacts.length===0&&(Pi=!1),Wr()?.updateInlineArtifactBlocks(Me,a.artifacts,{suppressTransition:Gn}),Mo(),Ii()},onHistoryStateChanged(a){ir(a)},onHistoryNotice(a){Oo(a)},onReconnect(a){let{executionId:u,lastEventId:m}=a.handle;a.phase==="paused"?Y.emit("stream:paused",{executionId:u,after:m}):a.phase==="resuming"?Y.emit("stream:resuming",{executionId:u,after:m,attempt:a.attempt??1}):Y.emit("stream:resumed",{executionId:u,after:m})}},Jr),lo.current=R,Ce.push(()=>R.cancel()),Ce.push(()=>{R.destroy(),po?.destroy(),po=null});let qu=null;if(R.onReadAloudChange((a,u)=>{bh=a,vh=u,Ch();let m=a??qu;a&&(qu=a);let b=m?R.getMessages().find(w=>w.id===m)??null:null;Y.emit("message:read-aloud",{messageId:m,message:b,state:u,timestamp:Date.now()}),u==="idle"&&(qu=null)}),h=!0,bu=!0,o.voiceRecognition?.enabled===!0&&On(o.voiceRecognition.provider))try{R.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}let Ot=null,zu=null,vy=!1,Cy=R.getHistoryState(),Ja=()=>o.features?.history?.enabled===!0,wy=a=>{a&&(wo.textContent="",wo.textContent=a)},Ku=()=>{f.forEach(m=>m()),f=[];let a=Ot,u=a?.railCollapseShortcut();a&&u&&f.push(g.register({id:"history-rail-collapse",combo:u.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>dn&&Nn==="rail"&&a.railCollapsible()||a.railTriggerApplies(),run:()=>a.railOverlayMode()?a.toggleRailPinned():a.toggleRailCollapsed()}));for(let m of o.layout?.header?.trailingActions??[])m.shortcut&&f.push(g.register({id:`header-action-${m.id}`,combo:m.shortcut,run:()=>{let b=e.querySelector(`[data-persona-header-action="${m.id}"]`);b?b.click():o.layout?.header?.onAction?.(m.id)}}));for(let m of d)for(let b of m.shortcuts??[])f.push(g.register({...b,id:`${m.id}:${b.id}`}))};Ku();let Oc=null,Sy=!1,Za=()=>{if(!Bo)return;let a=o.layout?.header?.titleSource==="conversation",u=a&&Oc?.trim()||null;Bo.textContent=u??o.launcher?.title??"Chat Assistant";let m=Bo.closest(".persona-combo-btn");if(!m)return;let b=!a||R.getActiveConversationId()!==null;m.setAttribute("data-persona-menu-locked",b?"false":"true"),m.setAttribute("aria-haspopup",b?"true":"false"),b||m.setAttribute("aria-expanded","false"),m.style.cursor=b?"pointer":"default";let w=m.querySelector("svg");w&&(w.style.display=b?"":"none")},tM=a=>{a!==Oc&&(Oc=a,Za())},nM=a=>{Sy=a?.starred===!0,tM(a&&a.title.trim()||null),Za()};Za(),ve.addEventListener("persona:title-menu-builtin",a=>{let u=a.detail?.actionId,m=R.getActiveConversationId();m&&(u==="delete"?Vo(b=>b.requestDeleteConversation(m)):u==="star"&&R.canUpdateConversations()&&Vo(b=>b.updateHistoryConversation(m,{starred:!Sy})).catch(()=>{}))}),ir=a=>{Cy=a,Ot?.historySurface?.view.setNewConversationRequired(a.recovery==="new_conversation_required"),Xa(a.sendBlocked||Gn),Ot?.syncEarlierMessagesPill()},Oo=a=>{(a.code==="history_continuity_reset"||a.code==="conversation_deleted_recovered")&&(xn.clear(),Vs(),$o()),wy(a.message),Ot?.historySurface?.view.refresh()};let oM={get actionManager(){return We},get activeConversationTitle(){return Oc},announceHistory:wy,get applyRailChrome(){return Fn},set applyRailChrome(a){Fn=a},get artifactSplitRoot(){return gr},get body(){return se},get config(){return o},get container(){return ve},get conversationOpenPendingEl(){return iy},set conversationOpenPendingEl(a){iy=a},get conversationOpenTakeover(){return Ru},set conversationOpenTakeover(a){Ru=a},currentKeyPrefix:bt,destroyCallbacks:Ce,eventBus:Y,get footer(){return qe},get header(){return gt},get historyChromeSync(){return _r},set historyChromeSync(a){_r=a},historyFeatureEnabled:Ja,get historyInternals(){return Jr},set historyInternals(a){Jr=a},get historyPresentation(){return Nn},set historyPresentation(a){Nn=a},get historySessionState(){return Cy},get historyVisible(){return dn},set historyVisible(a){dn=a},get isStreaming(){return Gn},jumpToBottomInstant:Eu,get lastAppliedMessages(){return Rc},set lastAppliedMessages(a){Rc=a},get launcherEnabled(){return me},get launcherSurfaceInstance(){return Vt},maybeFocusInput:kc,messageCache:xn,get messagesWrapper(){return Me},mount:e,get open(){return D},panel:we,panelElements:Qe,get persistentMetadata(){return P},set persistentMetadata(a){P=a},plugins:d,get reapplyHistoryHostChrome(){return sr},set reapplyHistoryHostChrome(a){sr=a},repinAnchoredMessage:Bi,resetAnchorState:Vs,restoreScrollPosition:Tu,resumeAutoScroll:$o,runStorageMutation:wc,get session(){return R},setActiveConversationSummary:nM,storageAdapter:T,get suppressScrollSend(){return Li},set suppressScrollSend(a){Li=a},syncScrollToBottomButton:Mn,updateWelcome:Qa,getHistoryProviderFactory:pA,historyErrors:{HistoryClientError:tn,HistoryProviderError:hs},isDockedMountMode:Ht,renderLucideIcon:ue,loadHistoryView:dA,createHeaderIconButton:ya,attachTooltip:yn},Gu=a=>(!Ot&&!vy&&(Ot=a.createHistoryShell(oM),Ot.railCollapseShortcut()&&Ku()),Ot),Yu=()=>{if(Ot)return Promise.resolve(Ot);let a=Ud();return a?Promise.resolve(Gu(a)):(zu??=gC().then(Gu,u=>{throw zu=null,u}),zu)},Vo=a=>{let u=Ud(),m=Ot??(u?Gu(u):null);return m?a(m):Yu().then(b=>{if(!b)throw new Error("[AgentWidget] The widget was destroyed");return a(b)})},Bc=()=>{Ot?.syncHistoryPresentation()};Ce.push(()=>{vy=!0}),Ja()&&Yu().catch(()=>{}).finally(pe),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&R.initClientSession().then(()=>{let a=Ot;if(a?.historyAvailable())return R.reconcileBootConversation({scope:a.historyScope()})}).then(()=>{Ot?.syncEarlierMessagesPill()}).catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)});let Xu=()=>R.warmClientSession(),Ay=a=>{let u=o.sessionInit??"input",m=at?.input??ae,b=a.target;m&&(a.type==="input"?(u==="input"||u==="focus")&&b===m&&a.inputType&&m.value.trim():u==="focus"&&(a.type==="keyup"?b===m&&a.key==="Tab":(at?.form??wn)?.contains(b)))&&Xu()},xy=["input","pointerdown","keyup"];xy.forEach(a=>e.addEventListener(a,Ay));let My,Qu,Ey=()=>{let a=Qu;Qu=void 0;try{typeof a=="function"&&a()}catch{}},Ty=()=>{let a=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(a!==My){Ey(),My=a;try{Qu=a?.({warm:Xu,mount:e})}catch{}}};Ty(),Ce.push(()=>{xy.forEach(a=>e.removeEventListener(a,Ay)),Ey()}),(be||o.onSSEEvent)&&R.setSSEEventCallback((a,u)=>{o.onSSEEvent?.(a,u),Ia(a,u)});let Py=()=>{let a=o.resume??(B?Jr.getStoredResumableHandle?.():null);a&&typeof o.reconnectStream=="function"&&R.resumeFromHandle(a)};Q?Q.then(a=>{if(a){if(a.metadata&&(P=Fm(a.metadata),We.syncFromMetadata()),a.messages?.length){Li=!0;try{R.hydrateMessages(a.messages)}finally{Li=!1}Tc()}a.artifacts?.length&&R.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null),Xh(a.draft)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>{Ou=!0,U(),Py()}):(Xh(ke),Py());let rM=()=>{!Pe()||D||!(o.launcher?.composerBar?.expandOnSubmit??!0)||xt(!0,"auto")},sM=(a,u)=>a?u?{refs:[...a.refs,...u.refs],finalize:async()=>{let[m,b]=await Promise.allSettled([a.finalize(),u.finalize()]),w=[];return m.status==="fulfilled"?w.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),b.status==="fulfilled"?w.push(b.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",b.reason),rR(w)}}:a:u,Ju=()=>{let u=ae.getInlineMessageFields?.();return u&&u.contentSegments.some(b=>b.kind==="mention")?u.contentSegments:void 0},Cr=!1,Ks=null,_c=()=>{ae.value="",ae.style.height="auto",io(),tl()},Zu="data-persona-composer-notice",$i=null;function ky(a,u=4e3){Ps(a),!(Pe()||!nt)&&(nt.hasAttribute(Ha)||(nt.setAttribute(Zu,""),nt.setAttribute("role","status"),nt.setAttribute("aria-live","polite"),nt.textContent=a,ri(nt,o.statusIndicator??{},"idle"),$i&&clearTimeout($i),$i=setTimeout(()=>{if($i=null,!!nt?.hasAttribute(Zu)&&(nt.removeAttribute(Zu),nt.removeAttribute("role"),nt.removeAttribute("aria-live"),h)){let m=R.getStatus();As(nt,ar(m),o.statusIndicator??{},m)}},u)))}function iM(){let a=he.getState().pendingSubmission;a&&(Mi(void 0),ae&&(ae.value=a.text,ae.dispatchEvent(new Event("input",{bubbles:!0})),io()),a.options.selectedModelId&&(he.setSelectedModelId(a.options.selectedModelId),$r?.repaint()),a.options.activeModeIds?.length&&rc(a.options.activeModeIds),a.options.quote&&Do(a.options.quote),ae?.focus())}let aM=a=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",a)},Ly=(a={})=>{let u=(a.overrideText??ae?.value??"").trim();return a.resolveInlineCommand&&u?(st?.takeInlineCommand(u)??Promise.resolve(null)).then(m=>Hy(a,u,m)):Hy(a,u,null)},Hy=(a,u,m)=>{if(m?.kind==="action"){_c(),st?.clear(),dr();return}let b=m?.kind==="server"?m.mentions:null,w=m?.kind==="prompt"?m.sendText:u,k=a.pending?.contentParts,q=(Ue?.hasAttachments()??!1)||(k?.length??0)>0;if(!Hw({text:w,hasAttachments:q,attachmentsReady:Ue?.isReady()??!0,hasMentions:st?.hasMentions()??!1,hasServerMentions:!!b,inputDisabled:Uo(),sendDisabled:js()}))return;let ne=R.isStreaming()?nu():"block";if(ne==="defer-one"&&!a.pending){if(he.getState().pendingSubmission){ky("One message is already queued. Edit or remove it first.");return}lM({intent:a,sendText:w,serverMentions:b});return}let G={text:w,mentionRefs:[...st?.getMentionRefs()??[],...b?.refs??[]],contentSegments:m?.kind==="prompt"?void 0:Ju(),options:{...he.getState().selectedModelId&&{selectedModelId:he.getState().selectedModelId},...he.getState().activeModeIds.length>0&&{activeModeIds:[...he.getState().activeModeIds]},...he.getState().quote&&{quote:{...he.getState().quote}}},viaVoice:a.viaVoice};a.pending&&(G.options={...a.pending.options},G.contentSegments=a.pending.contentSegments,G.mentionRefs=[...a.pending.mentionRefs],G.viaVoice=a.pending.viaVoice);let re=()=>{if(k?.length)return[...k];if(!Ue?.hasAttachments())return;let lt=[...Ue.getContentParts()];return G.text&&lt.push(Io(G.text)),lt};G.contentParts=re();let ie=()=>{_s(),rM();let lt=st?.collectForSubmit()??null,Vn=sM(lt,b),Bt=re();a.consumeDraft!==!1&&_c();let Ut={selectedModelId:G.options.selectedModelId,activeModeIds:G.options.activeModeIds},Rn=ne==="interrupt";Rn&&R.cancel(),R.sendMessage(G.text,{contentParts:Bt,mentions:Vn??void 0,contentSegments:G.contentSegments,viaVoice:G.viaVoice,composerOptions:Ut,...G.options.quote&&{quote:G.options.quote},...Rn&&{interrupt:!0}}),Ue?.hasAttachments()&&Ue.clearAttachments(),lt&&st?.clear(),dr();let qt=he.getState().activeModeIds,vt=yw(qt,o.composer?.modes);vt.length!==qt.length&&rc(vt),he.getState().quote&&Do(void 0),Ac(),lu.release(),Ao()},le=o.composer?.onBeforeSend;if(!le){ie();return}let Te=new AbortController;Ks=Te;let rt=lt=>{if(Ks=null,lt.status==="error"){aM(lt.error);return}lt.status==="proceed"&&ie()},pt=Iw(le,G,Te.signal);if(!(pt instanceof Promise)){rt(pt);return}return he.setPreparing(!0),pt.then(rt).finally(()=>he.setPreparing(!1))};function lM(a){let u=he.getState(),m=Ue?.hasAttachments()??!1,b=m?[...Ue.getContentParts()]:[];m&&a.sendText&&b.push(Io(a.sendText));let w=$f({text:a.sendText,contentParts:b.length?b:void 0,mentionRefs:[...st?.getMentionRefs()??[],...a.serverMentions?.refs??[]],contentSegments:Ju(),options:{...u.selectedModelId&&{selectedModelId:u.selectedModelId},...u.activeModeIds.length>0&&{activeModeIds:[...u.activeModeIds]},...u.quote&&{quote:{...u.quote}}},viaVoice:a.intent.viaVoice});Mi(w),a.intent.consumeDraft!==!1&&_c(),m&&Ue.clearAttachments(),st?.clear(),dr(),u.quote&&Do(void 0),Ac(),lu.release(),Ao(),Ps("Message queued. It sends when the response finishes.")}function cM(){let a=he.getState().pendingSubmission;a&&(Mi(void 0),Nc(a.text,{consumeDraft:!1,pending:a}))}function dM(a){if(o.messageActions?.showEdit!==!0)return;let u=R.getMessages().find(m=>m.id===a);!u||!Pf(u)||Bs!==a&&(_s(),Bs=a,qr=Sw({messageId:a,initialText:u.content,onSave:m=>pM(a,m),onCancel:()=>_s()}),xn.delete(a),co(Me,R.getMessages(),K),qr.focus())}function pM(a,u){let m=qr;if(Bs=null,qr=null,m?.destroy(),xn.delete(a),!R.resubmitFrom(a,{reason:"edit",replacement:{text:u,mentionRefs:[],options:{}}})){co(Me,R.getMessages(),K);return}Bi()}function uM(a){if(R.isStreaming())return;let u=Tf(R.getMessages(),a);u&&(_s(),R.resubmitFrom(u,{reason:"retry"})&&Bi())}sc={regenerate:uM,edit:dM,quote:a=>{let m=R.getMessages().find(b=>b.id===a)?.content?.trim();m&&(Do({text:m,messageId:a}),ae?.focus())}};let el=async a=>{if(!Cr){Cr=!0;try{await Ly({resolveInlineCommand:!0,...a})}finally{Cr=!1}}};function Dc(a){js()||(_c(),Nc(a,{consumeDraft:!1}))}let Nc=(a,u)=>{if(Cr)return;Cr=!0;let m=()=>{Cr=!1};try{let b=Ly({...u,overrideText:a});b instanceof Promise?b.finally(m):m()}catch(b){throw m(),b}},gM=a=>{if(a.preventDefault(),R.isStreaming()){R.cancel(),ht?.reset(),nn?.update();return}Cr||el()},fM=()=>o.features?.composerHistory!==!1,eg={...Gf},tg=!1,tl=()=>{eg={...Gf}},mM=()=>R.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),hM=a=>{if(!ae)return;tg=!0,ae.value=a,ae.dispatchEvent(new Event("input",{bubbles:!0})),tg=!1;let u=ae.value.length;ae.setSelectionRange(u,u)},yM=a=>{tg||(a.isComposing||st?.handleInput(a.inputType??void 0),tl())},bM=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:vl(ae)}),vM=a=>{if(ae&&!Uo()&&!(!a.isComposing&&st?.handleKeydown(a))){if(fM()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let u=ae.selectionStart===0&&ae.selectionEnd===0,m=Uw({direction:a.key==="ArrowUp"?"up":"down",history:mM(),currentValue:ae.value,atStart:u,state:eg});if(eg=m.state,m.handled){a.preventDefault(),m.value!==void 0&&hM(m.value);return}}if(zv(a,bM())){if(R.isStreaming()){if(a.preventDefault(),nu()==="block"||Cr||js())return;tl(),el();return}if(Cr){a.preventDefault();return}if(js()){a.preventDefault();return}tl(),a.preventDefault(),Ee.click()}}},Iy=a=>{if(!(a.key!=="Escape"||a.isComposing)&&a.composedPath().includes(ve)){if(Ks){Ks.abort(),Ks=null,a.preventDefault(),a.stopImmediatePropagation();return}R.isStreaming()&&(R.cancel(),ht?.reset(),nn?.update(),tl(),a.preventDefault(),a.stopImmediatePropagation())}},CM=async a=>{if(o.attachments?.enabled!==!0||!Ue||Uo())return;let u=eR(a.clipboardData);u.length!==0&&(a.preventDefault(),await Ue.handleFiles(u))},uo=null,jo=!1,Ui=null,wr=null,ng=()=>o.voiceRecognition?.completionBehavior==="review";function Fc(a){fe?.setAttribute("data-state",a),a==="recording"?SM():ig()}let Ry="--persona-voice-level",og=.5,Vi=null,rg=-1,$c=0,Wy=()=>{let a=[],u=pn??fe?.parentElement??null;return u&&a.push(u),qe&&a.push(qe),a},sg=a=>{let u=Math.round(Math.max(0,Math.min(1,a))*100)/100;if(u!==rg){rg=u;for(let m of Wy())m.style.setProperty(Ry,String(u))}},wM=()=>{rg=-1,$c=0;for(let a of Wy())a.style.removeProperty(Ry)};function SM(){if(Vi!==null)return;if(typeof requestAnimationFrame!="function"){sg(h?R.getVoiceLevel()??og:og);return}let a=()=>{Vi=requestAnimationFrame(a);let u=h?R.getVoiceLevel():null;if(u===null){sg(og);return}$c+=(u-$c)*.3,sg($c)};Vi=requestAnimationFrame(a)}function ig(){Vi!==null&&(cancelAnimationFrame(Vi),Vi=null),wM()}let Oy=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Uc=(a="user")=>{if(jo||R.isStreaming())return;let u=Oy();if(!u)return;uo=new u;let m=o.voiceRecognition??{},b=m.pauseDuration??2e3;uo.continuous=m.provider?.browser?.continuous??!0,uo.interimResults=!0,uo.lang=m.provider?.browser?.language??"en-US";let w=ae.value;uo.onresult=k=>{let q="",ne="";for(let re=0;re<k.results.length;re++){let ie=k.results[re],le=ie[0].transcript;ie.isFinal?q+=le+" ":ne=le}let G=w+q+ne;ae.value=G,io(),Ui&&clearTimeout(Ui),(q||ne)&&(Ui=window.setTimeout(()=>{if(ae.value.trim()&&uo&&jo){if(Zr(),ng())return;el({viaVoice:!0})}},b))},uo.onerror=k=>{k.error!=="no-speech"&&Zr()},uo.onend=()=>{if(jo){let k=ae.value.trim();!ng()&&k&&k!==w.trim()&&el({viaVoice:!0}),Zr()}};try{if(uo.start(),jo=!0,ot.active=!0,a!=="system"&&(ot.manuallyDeactivated=!1),yr(a),Eo(),Ao(),fe){let k=o.voiceRecognition??{};wr={backgroundColor:fe.style.backgroundColor,color:fe.style.color,borderColor:fe.style.borderColor,iconName:k.iconName??"mic",iconSize:parseFloat(k.iconSize??"")||qn};let q=k.recordingBackgroundColor,ne=k.recordingIconColor,G=k.recordingBorderColor;if(fe.classList.add("persona-voice-recording"),Fc("recording"),fe.style.backgroundColor=q??"var(--persona-voice-recording-bg, #ef4444)",fe.style.color=ne??"var(--persona-voice-recording-indicator, #ffffff)",ne){let re=fe.querySelector("svg");re&&re.setAttribute("stroke",ne)}G&&(fe.style.borderColor=G),fe.setAttribute("aria-label","Stop voice recognition")}}catch{Zr("system")}},Zr=(a="user")=>{if(jo){if(jo=!1,Ui&&(clearTimeout(Ui),Ui=null),uo){try{uo.stop()}catch{}uo=null}if(ot.active=!1,yr(a),Eo(),Ao(),fe){if(fe.classList.remove("persona-voice-recording"),Fc("idle"),wr){fe.style.backgroundColor=wr.backgroundColor,fe.style.color=wr.color,fe.style.borderColor=wr.borderColor;let u=fe.querySelector("svg");u&&u.setAttribute("stroke",wr.color||"currentColor"),wr=null}fe.setAttribute("aria-label","Start voice recognition")}}},By=null,Vc=a=>{let u=b=>{By??=b.createMicStateStyles({mic:()=>fe,config:()=>o,session:()=>R,get original(){return wr},set original(w){wr=w},setMicState:Fc,renderIcon:ue,iconFallbackPx:qn}),a(By)},m=VC();m?u(m):Pl().then(u,()=>{})},ji=()=>Vc(a=>a.recording()),AM=()=>Vc(a=>a.processing()),xM=()=>Vc(a=>a.speaking()),Sr=()=>Vc(a=>a.reset()),ag=()=>{if(!Uo()){if(On(o.voiceRecognition?.provider)){let a=R.getVoiceStatus(),u=R.getVoiceInterruptionMode();if(u==="none"&&(a==="processing"||a==="speaking"))return;if(u==="cancel"&&(a==="processing"||a==="speaking")){R.stopVoicePlayback();return}if(R.isBargeInActive()){R.stopVoicePlayback(),R.deactivateBargeIn().then(()=>{ot.active=!1,ot.manuallyDeactivated=!0,Eo(),yr("user"),Sr()});return}R.toggleVoice().then(()=>{ot.active=R.isVoiceActive(),ot.manuallyDeactivated=!R.isVoiceActive(),Eo(),yr("user"),R.isVoiceActive()?ji():Sr()});return}if(jo){let a=ae.value.trim();ot.manuallyDeactivated=!0,Eo(),Zr("user"),a&&!ng()&&el()}else ot.manuallyDeactivated=!1,Eo(),Uc("user")}};ou=ag;let _y=()=>R.prewarmVoice(),Dy=()=>{let a=o.voiceRecognition;return a?.enabled!==!0?!1:a.prewarm??(o.clientToken?"hover":!1)},Ny=a=>{Dy()==="hover"&&fe?.contains(a.target)&&_y()},Fy=["pointerover","pointerdown","focusin"];Fy.forEach(a=>e.addEventListener(a,Ny));let $y,Uy=null,lg,Vy=()=>{let a=lg;lg=void 0;try{typeof a=="function"&&a()}catch{}},cg=()=>{let a=Dy(),u=typeof a=="function"&&fe?a:void 0,m=u?fe:null;if(!(u===$y&&m===Uy)&&(Vy(),$y=u,Uy=m,!(!u||!m)))try{lg=u({warm:_y,micButton:m,mount:e})}catch{}};cg(),Ce.push(()=>{Fy.forEach(a=>e.removeEventListener(a,Ny)),Vy()}),fe&&Ce.push(()=>{On(o.voiceRecognition?.provider)?(R.isVoiceActive()&&R.toggleVoice(),Sr()):Zr("system")});let MM=Y.on("assistant:complete",()=>{he.getState().pendingSubmission&&setTimeout(()=>{R.isStreaming()||cM()},0)});Ce.push(MM);let EM=Y.on("assistant:complete",()=>{Kh&&(ot.active||ot.manuallyDeactivated||Kh==="assistant"&&!ot.lastUserMessageWasVoice||setTimeout(()=>{!ot.active&&!ot.manuallyDeactivated&&(On(o.voiceRecognition?.provider)?R.toggleVoice().then(()=>{ot.active=R.isVoiceActive(),yr("auto"),R.isVoiceActive()&&ji()}):Uc("auto"))},600))});Ce.push(EM);let TM=Y.on("action:resubmit",()=>{setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)});Ce.push(TM);let jy=()=>{xt(!D,"user")},Vt=null,In=null;if(me&&!Pe()){let{instance:a,element:u}=ym({config:o,plugins:d,onToggle:jy});Vt=a,a||(In=u)}Vt?e.appendChild(Vt.element):In&&e.appendChild(In),Ya(),Ws(),Hc(),Fu(),Xa(R.isStreaming()),Tu()||(An()==="follow"?Yr(!0):Eu()),xx(),Qt&&(!me||Pe()?setTimeout(()=>kc(),0):D&&setTimeout(()=>kc(),200));let es=null,qy=()=>{es&&(es.disconnect(),es.observe(qe),es.observe(ve),es.observe(Jt))},zy=$n(),nl=()=>{if(Pe()){He(),Ya();return}let a=Ht(o),u=o.launcher?.sidebarMode??!1,m=e.ownerDocument.defaultView??window,b=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640,k=m.innerWidth<=w,q=b&&k&&me;try{if(q){ks(),Na=fc();return}let ne=!1;yt&&(yt=!1,ks(),ne=!0);let G=fc();if(!ne&&G!==Na&&(ks(),ne=!0),Na=G,ne&&dc(),!me&&!a){we.style.height="",we.style.width="";return}if(!u&&!a){let re=ui(o);we.style.width=re.width,we.style.maxWidth=re.maxWidth}gc(),Hh()}finally{He(),Rt();let ne=$n();if(ne!==zy&&(zy=ne,Qa(),Ws()),Ya(),D&&me){let re=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ie=o.launcher?.sidebarMode??!1,le=o.launcher?.mobileFullscreen??!0,Te=Ht(o)&&le&&re,rt=ie||le&&re&&me||Te;if(rt&&!Fo){let pt=e.getRootNode(),lt=pt instanceof ShadowRoot?pt.host:e.closest(".persona-host");lt&&!No&&(No=Jf(lt,o.launcher?.zIndex??Tn)),Fo=Zf(e.ownerDocument)}else rt||(No?.(),No=null,Fo?.(),Fo=null)}}};nl();let jc=e.ownerDocument.defaultView??window;if(jc.addEventListener("resize",nl),Ce.push(()=>jc.removeEventListener("resize",nl)),typeof ResizeObserver<"u"){es=new ResizeObserver(()=>{Rt()}),qy(),Ce.push(()=>{es?.disconnect(),es=null});let a=new ResizeObserver(()=>{Bc()});a.observe(ve),Ce.push(()=>a.disconnect())}jc.addEventListener("resize",Bc),Ce.push(()=>jc.removeEventListener("resize",Bc)),Xn=se.scrollTop;let Ky=er(se),Gy=()=>{Lh();let a=se.scrollTop,u=er(se),m=u<Ky;if(Ky=u,!Co()){Xn=a,Mn();return}let{action:b,nextLastScrollTop:w}=Xw({following:Yn.isFollowing(),currentScrollTop:a,lastScrollTop:Xn,nearBottom:di(se,mr),userScrollThreshold:Cx,isAutoScrolling:Un||hc||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Xn=w,b==="resume"){xc()||$o();return}b==="pause"&&Oi()};if(se.addEventListener("scroll",Gy,{passive:!0}),Ce.push(()=>se.removeEventListener("scroll",Gy)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{Hx(),Af(Me)});a.observe(Me),a.observe(se),Ce.push(()=>a.disconnect())}let Yy=()=>{Co()&&Yn.isFollowing()&&xc()&&Oi()},Xy=se.ownerDocument;Xy.addEventListener("selectionchange",Yy),Ce.push(()=>{Xy.removeEventListener("selectionchange",Yy)});let PM=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Qy=a=>{PM.has(a.key)&&(Gr(),Ra()&&Co()&&Yn.isFollowing()&&Oi())},Jy=a=>{a.target?.closest("a, button, [tabindex], input, textarea, select")&&(Gr(),Ra()&&Co()&&Yn.isFollowing()&&Oi())};se.addEventListener("keydown",Qy),se.addEventListener("focusin",Jy),Ce.push(()=>{se.removeEventListener("keydown",Qy),se.removeEventListener("focusin",Jy)});let Zy=a=>{if(a.deltaY!==0&&Gr(),!Co())return;let u=Qw({following:Yn.isFollowing(),deltaY:a.deltaY,nearBottom:di(se,mr),resumeWhenNearBottom:!0});u==="pause"?Oi():u==="resume"&&!xc()&&$o()};se.addEventListener("wheel",Zy,{passive:!0}),se.addEventListener("touchmove",Gr,{passive:!0}),se.addEventListener("pointerdown",Gr,{passive:!0}),Ce.push(()=>{se.removeEventListener("touchmove",Gr),se.removeEventListener("pointerdown",Gr)}),Ce.push(()=>se.removeEventListener("wheel",Zy)),$t.addEventListener("click",()=>{Vs(),se.scrollTop=se.scrollHeight,Xn=se.scrollTop,$o(),Yr(!0),Mn()}),Ce.push(()=>$t.remove()),Ce.push(()=>{Jh(),Vs()});let eb=()=>{je&&(Is&&(je.removeEventListener("click",Is),Is=null),Ke()?(je.style.display="",Is=()=>{xt(!1,"user")},je.addEventListener("click",Is)):je.style.display="none")};eb(),(()=>{let{clearChatButton:a}=Qe;a&&a.addEventListener("click",()=>{let u=Ot;if(u?.historyAvailable()){u.startNewConversation({focusComposer:!0}).catch(b=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",b)});return}R.clearMessages(),o.layout?.topFade&&(se.scrollTop=0),se.removeAttribute("data-persona-top-fade"),xn.clear(),$o(),cs(Qe.composerOverlay);try{localStorage.removeItem(La),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${La}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==La)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(m),T?.clear&&wc(()=>T.clear(),"[AgentWidget] Failed to clear storage adapter:"),P={},We.syncFromMetadata(),Ue?.clearAttachments(),Ac(),Mi(void 0),Do(void 0),_s(),ut?.clear(),ht?.reset(),nn?.update()})})();let tb=[["keydown",vM],["input",yM],["input",io],["input",dr],["keyup",dr],["paste",CM],["focus",lx]],nb=a=>{if(a)for(let[u,m]of tb)at?.addListener(a,u,m)},kM=a=>{if(a)for(let[u,m]of tb)at?.removeListener(a,u,m)},ob=()=>{at&&(at.addListener(at.form,"submit",gM),at.addListener(at.footer,"click",dr),nb(ae),fe&&at.addListener(fe,"click",ag),cg())};ob();let rb=()=>{st?.onComposerSwap((a,u)=>{kM(u),ae=a,at&&(at.input=a),nb(a),su(),Iu(),io()})};rb();let dg=!1;function sb(){if(!dg){dg=!0;try{let a=ae?.value??"",u=qe.ownerDocument??document,m=ae?u.activeElement===ae:!1;ig(),at?.destroy(),at=null,st?.destroy(),st=null;let b=null,w=()=>(b=Pe()?wp({config:o}):Sa({config:o}),b.footer),k=ch(w)??w();Pn.replaceComposer(k),qe=Pn.composer.footer;let q=b!==null&&k===b.footer;Ti=!q,tc=q?b.setSendButtonMode:()=>{},lh(qe),ph(qe),uh(),gh(),iu(),rb(),fh(),au(),mh(),ob();let ne=Hs.indexOf(fr);if(fr.destroy(),fr=Ul(so),ne>=0&&(Hs[ne]=fr),ae&&(ae.value=a),io(),dr(),Hc(),Ws(),Xa(R.isStreaming()),o.statusIndicator?.mode==="transient"&&!Pe()){let G=R.getStatus();As(nt,ar(G),o.statusIndicator,G)}ot.active&&Fc("recording"),ks(),qy(),He(),Ao(),Pc(),m&&ae?.focus()}finally{dg=!1}}}let ol=e.ownerDocument??document;ol.addEventListener("keydown",Iy,!0);let ib=()=>{Su()},ab=()=>{ol.visibilityState==="hidden"&&Su()};typeof window<"u"&&(window.addEventListener("pagehide",ib),ol.addEventListener("visibilitychange",ab),Ce.push(()=>{window.removeEventListener("pagehide",ib),ol.removeEventListener("visibilitychange",ab)}));let lb="persona-attachment-drop-active",rl=0,pg=()=>{rl=0,ve.classList.remove(lb)},qi=()=>o.attachments?.enabled===!0&&Ue!==null&&!Uo(),cb=a=>{!Bp(a.dataTransfer)||!qi()||(rl++,rl===1&&ve.classList.add(lb))},db=a=>{!Bp(a.dataTransfer)||!qi()||(rl--,rl<=0&&pg())},pb=a=>{!Bp(a.dataTransfer)||!qi()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},ub=a=>{if(!Bp(a.dataTransfer)||!qi())return;a.preventDefault(),a.stopPropagation(),pg();let u=Array.from(a.dataTransfer.files??[]);u.length!==0&&Ue.handleFiles(u)},ts=!0;ve.addEventListener("dragenter",cb,ts),ve.addEventListener("dragleave",db,ts),e.addEventListener("dragover",pb,ts),e.addEventListener("drop",ub,ts);let qc=e.ownerDocument,gb=a=>{qi()&&a.preventDefault()},fb=a=>{qi()&&a.preventDefault()};qc.addEventListener("dragover",gb),qc.addEventListener("drop",fb),Ce.push(()=>{at?.destroy(),at=null,ig(),So?.destroy(),So=null,pr?.destroy(),pr=null,Ur?.destroy(),Ur=null,Vr?.destroy(),Vr=null,$r=null,tu=null,Su(),ja.destroy(),$i&&clearTimeout($i),_s(),Ks?.abort(),Ks=null,Ue?.destroy(),Ue=null,he.destroy(),ol.removeEventListener("keydown",Iy,!0),st?.destroy()}),Ce.push(()=>{ve.removeEventListener("dragenter",cb,ts),ve.removeEventListener("dragleave",db,ts),e.removeEventListener("dragover",pb,ts),e.removeEventListener("drop",ub,ts),qc.removeEventListener("dragover",gb),qc.removeEventListener("drop",fb),pg()}),Ce.push(()=>{R.cancel()}),Vt?Ce.push(()=>{Vt?.destroy()}):In&&Ce.push(()=>{In?.remove()});let jt={update(a){let u=o.future?.v5Defaults===!0,m=o.toolCall,b=o.messageActions,w=o.layout?.messages,k=o.colorScheme,q=o.loadingIndicator,ne=o.iterationDisplay,G=o.features?.showReasoning,re=o.features?.showToolCalls,ie=o.features?.toolCallDisplay,le=o.features?.reasoningDisplay,Te=o.features?.streamAnimation?.type,rt=o.features?.history?.enabled===!0,pt=o.features?.history?.provider,lt=o.getIdentityProof,Vn=o.clientToken,Bt=o.contextMentions;o=Ip({...o,features:p},a),p=o.features,o=Lp(o),c(),fu(),ha(e,o),Kl(e,o),Gl(e,o),Fn(),Mo(),o.colorScheme!==k&&Ih();let Ut=Hp.getForInstance(o.plugins);d.length=0,d.push(...Ut),Ku(),me=o.launcher?.enabled??!0,dt=o.launcher?.autoExpand??!1,Z=o.features?.showReasoning??!0,ye=o.features?.showToolCalls??!0,Ae=o.features?.scrollToBottom??{};let Rn=An();tt=o.features?.scrollBehavior??{},Rn!==An()&&(Vs(),$o()),zh(),Wt(),Mn();let qt=be;if(be=o.features?.showEventStreamToggle??!1,be&&!qt){if(ut||(rr(),R.setSSEEventCallback((J,Ze)=>{o.onSSEEvent?.(J,Ze),Ia(J,Ze)})),!ft&&gt){let J=o.features?.eventStream?.classNames,Ze="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"+(J?.toggleButton?" "+J.toggleButton:"");ft=x("button",Ze),ft.style.width="28px",ft.style.height="28px",ft.style.color=Bn.actionIconColor,ft.type="button",ft.setAttribute("aria-label","Event Stream"),ft.title="Event Stream";let et=_t(gA,"18px","currentColor",1.5);et&&ft.appendChild(et);let ct=Qe.clearChatButtonWrapper,Lt=Qe.closeButtonWrapper,En=ct||Lt;En&&En.parentNode===gt?gt.insertBefore(ft,En):gt.appendChild(ft),ft.addEventListener("click",()=>{Cn?Ei():ru()})}}else!be&&qt&&(Ei(),ft&&(ft.remove(),ft=null),ut?.clear(),cn?.destroy(),ut=null,cn=null,ht?.reset(),ht=null,Dt=null);if(o.launcher?.enabled===!1&&Vt&&(Vt.destroy(),Vt=null),o.launcher?.enabled===!1&&In&&(In.remove(),In=null),o.launcher?.enabled!==!1&&!Vt&&!In){let{instance:J,element:Ze}=ym({config:o,plugins:d,onToggle:jy});Vt=J,J||(In=Ze),e.appendChild(Ze)}Vt&&Vt.update(o),Za(),_o&&o.launcher?.subtitle!==void 0&&(_o.textContent=o.launcher.subtitle);let vt=o.layout?.header;if(vt?.layout!==It&&gt){let J=vt?Vl(o,vt,{showClose:Ke(),onClose:()=>xt(!1,"user")}):ws({config:o,showClose:Ke(),onClose:()=>xt(!1,"user")});Pn.replaceHeader(J),gt=Pn.header.element,Pt=Pn.header.iconHolder,Bo=Pn.header.headerTitle,_o=Pn.header.headerSubtitle,je=Pn.header.closeButton,It=vt?.layout,Za()}else if(vt){if(Pt&&(Pt.style.display=vt.showIcon===!1?"none":""),Bo&&(Bo.style.display=vt.showTitle===!1?"none":""),_o&&(_o.style.display=vt.showSubtitle===!1?"none":""),je){let J=Ke()&&vt.showCloseButton!==!1;je.style.display=J?"":"none"}if(Qe.clearChatButtonWrapper){let J=vt.showClearChat;if(J!==void 0){Qe.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:Ze}=Qe;Ze&&!Ze.classList.contains("persona-absolute")&&(J?Ze.classList.remove("persona-ml-auto"):Ze.classList.add("persona-ml-auto"))}}}let zo=o.layout?.showHeader!==!1;gt&&(gt.style.display=zo?"":"none");let fo=o.layout?.showFooter!==!1;qe&&(qe.style.display=fo?"":"none"),He(),Mn(),me!==Se?me?xt(dt,"auto"):(D=!0,Ya()):dt!==St&&xt(dt,"auto"),St=dt,Se=me,nl(),eb();let Ko=JSON.stringify(o.toolCall)!==JSON.stringify(m),To=JSON.stringify(o.messageActions)!==JSON.stringify(b),os=JSON.stringify(o.layout?.messages)!==JSON.stringify(w),sl=o.loadingIndicator?.render!==q?.render||o.loadingIndicator?.renderIdle!==q?.renderIdle||o.loadingIndicator?.showBubble!==q?.showBubble,Gs=o.iterationDisplay!==ne,O=(o.features?.showReasoning??!0)!==(G??!0)||(o.features?.showToolCalls??!0)!==(re??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ie)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(le);(o.future?.v5Defaults===!0!==u||Ko||To||os||sl||Gs||O)&&R&&(Ds++,co(Me,R.getMessages(),K));let De=o.features?.streamAnimation?.type;if(De!==Te&&De&&De!=="none"){let J=yu(De,o.features?.streamAnimation?.plugins);J&&Nl(J,e)}let oe=o.launcher??{},Ct=oe.headerIconHidden??!1,Xt=o.layout?.header?.showIcon,kn=Ct||Xt===!1,gn=oe.headerIconName,Mt=oe.headerIconSize??hl;if(Pt){let J=gt,Ze=J?.querySelector(".persona-flex-col");if(kn)Pt.style.display="none",J&&Ze&&!J.contains(Ze)&&J.insertBefore(Ze,J.firstChild);else{if(Pt.style.display="",Pt.style.height=Mt,Pt.style.width=Mt,J&&Ze&&(J.contains(Pt)?Pt.nextSibling!==Ze&&(Pt.remove(),J.insertBefore(Pt,Ze)):J.insertBefore(Pt,Ze)),gn){let ct=parseFloat(Mt)||24,Lt=ue(gn,ct*.6,"currentColor",1);Lt?(Lt.style.width=`calc(${ct}px * var(--persona-components-header-iconScale, 0.6))`,Lt.style.height=`calc(${ct}px * var(--persona-components-header-iconScale, 0.6))`,Pt.replaceChildren(Lt)):Pt.textContent=oe.agentIconText??"\u{1F4AC}"}else if(oe.iconUrl){let ct=Pt.querySelector("img");if(ct)ct.src=oe.iconUrl,ct.style.height=Mt,ct.style.width=Mt;else{let Lt=document.createElement("img");Lt.src=oe.iconUrl,Lt.alt="",Lt.className="persona-rounded-xl persona-object-cover",Lt.style.height=Mt,Lt.style.width=Mt,Pt.replaceChildren(Lt)}}else{let ct=Pt.querySelector("svg"),Lt=Pt.querySelector("img");(ct||Lt)&&Pt.replaceChildren(),Pt.textContent=oe.agentIconText??"\u{1F4AC}"}let et=Pt.querySelector("img");et&&(et.style.height=Mt,et.style.width=Mt)}}let zt=o.layout?.header?.showTitle,sn=o.layout?.header?.showSubtitle;if(Bo&&(Bo.style.display=zt===!1?"none":""),_o&&(_o.style.display=sn===!1?"none":""),je){let J=Ke()&&o.layout?.header?.showCloseButton!==!1;if(je.style.display=J?"":"none",!Pe()){let mn=oe.closeButtonSize??"";je.style.height=mn,je.style.width=mn,je.style.minWidth=mn,je.style.minHeight=mn}let Ze=oe.closeButtonPlacement??"inline",{closeButtonWrapper:et}=Qe,ct=Ze==="top-right",Lt=et?.classList.contains("persona-absolute");if(et&&ct!==Lt)if(et.remove(),ct){et.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let mn=Ot?.railColumn??ve;mn.style.position="relative",mn.appendChild(et)}else{let mn=oe.clearChat?.placement??"inline",hn=oe.clearChat?.enabled??!0;et.className=hn&&mn==="inline"?"":"persona-ml-auto",gt&&gt.appendChild(et)}if(je.style.color=oe.closeButtonColor||Bn.actionIconColor,oe.closeButtonBackgroundColor?(je.style.backgroundColor=oe.closeButtonBackgroundColor,je.classList.remove("hover:persona-bg-gray-100")):(je.style.backgroundColor="",je.classList.add("hover:persona-bg-gray-100")),oe.closeButtonBorderWidth||oe.closeButtonBorderColor){let mn=oe.closeButtonBorderWidth||"0px",hn=oe.closeButtonBorderColor||"transparent";je.style.border=`${mn} solid ${hn}`,je.classList.remove("persona-border-none")}else je.style.border="",je.classList.add("persona-border-none");oe.closeButtonBorderRadius?(je.style.borderRadius=oe.closeButtonBorderRadius,je.classList.remove("persona-rounded-full")):(je.style.borderRadius="",je.classList.add("persona-rounded-full")),oe.closeButtonPaddingX?(je.style.paddingLeft=oe.closeButtonPaddingX,je.style.paddingRight=oe.closeButtonPaddingX):(je.style.paddingLeft="",je.style.paddingRight=""),oe.closeButtonPaddingY?(je.style.paddingTop=oe.closeButtonPaddingY,je.style.paddingBottom=oe.closeButtonPaddingY):(je.style.paddingTop="",je.style.paddingBottom=""),vp(je,oe.closeButtonIconName??"x",{iconSize:Pe()?gm:void 0,iconText:oe.closeButtonIconText??"\xD7"});let En=oe.closeButtonTooltipText??"Close chat",ko=oe.closeButtonShowTooltip??!0;je.setAttribute("aria-label",En),et&&yn({anchor:je,trigger:et,text:()=>je?.getAttribute("aria-label")??En,enabled:ko})}let{clearChatButton:Ie,clearChatButtonWrapper:Et}=Qe;if(Ie){let J=oe.clearChat??{},Ze=J.enabled??!0,et=o.layout?.header?.showClearChat,ct=et!==void 0?et:Ze,Lt=J.placement??"inline";if(Et){Et.style.display=ct?"":"none";let{closeButtonWrapper:En}=Qe;!Pe()&&En&&!En.classList.contains("persona-absolute")&&(ct?En.classList.remove("persona-ml-auto"):En.classList.add("persona-ml-auto"));let ko=Lt==="top-right",mn=Et.classList.contains("persona-absolute");if(!Pe()&&ko!==mn&&ct){if(Et.remove(),ko){Et.className="persona-absolute persona-top-4 persona-z-50",Et.style.right="48px";let Go=Ot?.railColumn??ve;Go.style.position="relative",Go.appendChild(Et)}else{Et.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Et.style.right="";let Go=Qe.closeButtonWrapper;gt&&Go&&Go.parentElement===gt?gt.insertBefore(Et,Go):gt&&gt.appendChild(Et)}let hn=Qe.closeButtonWrapper;hn&&!hn.classList.contains("persona-absolute")&&(ko?hn.classList.add("persona-ml-auto"):hn.classList.remove("persona-ml-auto"))}}if(ct){if(!Pe()){let hn=J.size??"";Ie.style.height=hn,Ie.style.width=hn,Ie.style.minWidth=hn,Ie.style.minHeight=hn}let En=J.iconColor??"";if(Ie.style.color=En||Bn.actionIconColor,vp(Ie,J.iconName??"refresh-cw",{iconSize:Pe()?fm:void 0}),J.backgroundColor?(Ie.style.backgroundColor=J.backgroundColor,Ie.classList.remove("hover:persona-bg-gray-100")):(Ie.style.backgroundColor="",Ie.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let hn=J.borderWidth||"0px",Go=J.borderColor||"transparent";Ie.style.border=`${hn} solid ${Go}`,Ie.classList.remove("persona-border-none")}else Ie.style.border="",Ie.classList.add("persona-border-none");J.borderRadius?(Ie.style.borderRadius=J.borderRadius,Ie.classList.remove("persona-rounded-full")):(Ie.style.borderRadius="",Ie.classList.add("persona-rounded-full")),J.paddingX?(Ie.style.paddingLeft=J.paddingX,Ie.style.paddingRight=J.paddingX):(Ie.style.paddingLeft="",Ie.style.paddingRight=""),J.paddingY?(Ie.style.paddingTop=J.paddingY,Ie.style.paddingBottom=J.paddingY):(Ie.style.paddingTop="",Ie.style.paddingBottom="");let ko=J.tooltipText??"Clear chat",mn=J.showTooltip??!0;Ie.setAttribute("aria-label",ko),Et&&yn({anchor:Ie,trigger:Et,text:()=>Ie?.getAttribute("aria-label")??ko,enabled:mn})}}let Ne=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Rp],an=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ka.message,ka.messageAndClick];We=Wp({parsers:Ne,handlers:an,getSessionMetadata:mt,updateSessionMetadata:Ve,emit:Y.emit,documentRef:typeof document<"u"?document:null}),K=yA(o,We,z),Xx(),R.updateConfig(o),Ty(),(o.features?.history?.enabled===!0!==rt||o.features?.history?.provider!==pt||o.getIdentityProof!==lt||o.clientToken!==Vn)&&(Ot?.closeHistory({restoreFocus:!1}),Ot?.installHistoryProvider()),Ot?.syncHistoryChromeImpl(),Bc(),Ja()&&!Ot&&Yu().catch(()=>{}),co(Me,R.getMessages(),K),Ws(),Hc(),Kx(),Xa(R.isStreaming()),Bt!==o.contextMentions&&sb();let ho=o.voiceRecognition?.enabled===!0,fn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),wt=On(o.voiceRecognition?.provider);if(ho&&(fn||wt))if(!fe||!pn){let J=ca(o);if(J){fe=J.button,pn=J.wrapper;let Ze=Hn&&Hn.parentElement===xs?Hn:null;xs?xs.insertBefore(pn,Ze):wn?.appendChild(pn),at&&(at.micButton=fe),at?.addListener(fe,"click",ag),fe.disabled=Uo()||R.isStreaming()&&!Lu()}}else{let J=o.voiceRecognition??{},Ze=o.sendButton??{},et=J.iconName??"mic",ct=J.iconSize,Lt=parseFloat(ct??"")||qn;fe.classList.add(Zn),fe.classList.toggle(Ro,!ct),fe.style.width=ct??"",fe.style.height=ct??"",fe.style.minWidth=ct??"",fe.style.minHeight=ct??"";let En=J.iconColor??Ze.textColor;fe.innerHTML="";let ko=ue(et,Lt,En||"currentColor",1.5);ko?fe.appendChild(ko):fe.textContent="\u{1F3A4}";let mn=J.backgroundColor??Ze.backgroundColor;mn?fe.style.backgroundColor=mn:fe.style.backgroundColor="",En?fe.style.color=En:fe.style.color="var(--persona-text, #111827)",J.borderWidth?(fe.style.borderWidth=J.borderWidth,fe.style.borderStyle="solid"):(fe.style.borderWidth="",fe.style.borderStyle=""),J.borderColor?fe.style.borderColor=J.borderColor:fe.style.borderColor="",J.paddingX?(fe.style.paddingLeft=J.paddingX,fe.style.paddingRight=J.paddingX):(fe.style.paddingLeft="",fe.style.paddingRight=""),J.paddingY?(fe.style.paddingTop=J.paddingY,fe.style.paddingBottom=J.paddingY):(fe.style.paddingTop="",fe.style.paddingBottom="");let hn=J.tooltipText??"Start voice recognition",Go=J.showTooltip??!1;fe.setAttribute("aria-label",hn),pn&&yn({anchor:fe,trigger:pn,text:()=>fe?.getAttribute("aria-label")??hn,enabled:Go}),pn.style.display="",fe.disabled=Uo()||R.isStreaming()&&!Lu()}else fe&&pn&&(pn.style.display="none",On(o.voiceRecognition?.provider)?R.isVoiceActive()&&R.toggleVoice():jo&&Zr());if(cg(),o.attachments?.enabled===!0){if(!on||!kt){let J=o.attachments??{};un||(un=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),un.style.display="none",(ae.parentElement??wn).insertBefore(un,ae)),At||(At=document.createElement("input"),At.type="file",At.accept=(J.allowedTypes??Lr).join(","),At.multiple=(J.maxFiles??4)>1,At.style.display="none",At.setAttribute("aria-label","Attach files"),(ae.parentElement??wn).insertBefore(At,ae)),on=x("div","persona-send-button-wrapper"),kt=x("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Zn} ${Ro}`),kt.type="button",kt.setAttribute("aria-label",J.buttonTooltipText??"Attach file");let Ze=J.buttonIconName??"paperclip";kt.style.fontSize="18px",kt.style.lineHeight="1";let et=ue(Ze,qn,"currentColor",1.5);et?kt.appendChild(et):kt.textContent="\u{1F4CE}",kt.addEventListener("click",Lt=>{Lt.preventDefault(),At?.click()}),on.appendChild(kt);let ct=J.buttonTooltipText??"Attach file";yn({anchor:kt,trigger:on,text:()=>kt?.getAttribute("aria-label")??ct}),Sn?Sn.append(on):wn.appendChild(on),at&&(at.attachmentButton=kt,at.attachmentInput=At??void 0,at.attachmentPreviews=un??void 0),!Ue&&At&&un&&(Ue=fa.fromConfig(J,oh),Ue.setPreviewsContainer(un),at?.addListener(At,"change",async()=>{Ue&&At?.files&&(await Ue.handleFileSelect(At.files),At.value="")}))}else{on.style.display="";let J=o.attachments??{};At&&(At.accept=(J.allowedTypes??Lr).join(","),At.multiple=(J.maxFiles??4)>1),Ue&&Ue.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles,adapter:J.adapter})}if(ve.querySelector(".persona-attachment-drop-overlay")?.remove(),ve.appendChild(bA(o.attachments?.dropOverlay)),kt){let J=o.attachments??{},Ze=J.buttonTooltipText??"Attach file";kt.setAttribute("aria-label",Ze),kt.textContent="";let et=ue(J.buttonIconName??"paperclip",qn,"currentColor",1.5);et?kt.appendChild(et):kt.textContent="\u{1F4CE}",on&&yn({anchor:kt,trigger:on,text:()=>kt?.getAttribute("aria-label")??Ze})}}else on&&(on.style.display="none"),Ue&&Ue.clearAttachments(),ve.querySelector(".persona-attachment-drop-overlay")?.remove();let Fe=o.sendButton??{},rs=Fe.useIcon??!1,en=Fe.iconText??"\u2191",jn=Fe.iconName,Ar=Fe.tooltipText??"Send message",ug=Fe.showTooltip??!1,Ys=Fe.size,gg=parseFloat(Ys??"")||rf,xr=Fe.backgroundColor,Xs=Fe.textColor;if(rs){if(Ee.style.width=Ys??"",Ee.style.height=Ys??"",Ee.style.minWidth=Ys??"",Ee.style.minHeight=Ys??"",Ee.style.fontSize="18px",Ee.style.lineHeight="1",Xs?Ee.style.color=Xs:Ee.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!R.isStreaming())if(Ee.innerHTML="",jn){let J=parseFloat(Fe.iconSize??"")||Math.round(gg*.5),Ze=Xs?.trim()||"currentColor",et=Fe.iconStrokeWidth??2,ct=ue(jn,J,Ze,et),Lt=ue(Fe.stopIconName??"square",J,Ze,et);ct&&Lt?Ee.appendChild(sf(ct,Lt)):ct?Ee.appendChild(ct):Ee.textContent=en}else Ee.textContent=en;Ee.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Zn}`,xr?(Ee.style.backgroundColor=xr,Ee.classList.remove("persona-bg-persona-primary")):(Ee.style.backgroundColor="",Ee.classList.add("persona-bg-persona-primary"))}else Ee.textContent=o.copy?.sendButtonLabel??"Send",Ee.style.width="",Ee.style.height="",Ee.style.minWidth="",Ee.style.minHeight="",Ee.style.fontSize="",Ee.style.lineHeight="",Ee.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",xr?(Ee.style.backgroundColor=xr,Ee.classList.remove("persona-bg-persona-accent")):Ee.classList.add("persona-bg-persona-accent"),Xs?Ee.style.color=Xs:Ee.classList.add("persona-text-white");Fe.borderWidth?(Ee.style.borderWidth=Fe.borderWidth,Ee.style.borderStyle="solid"):(Ee.style.borderWidth="",Ee.style.borderStyle=""),Fe.borderColor?Ee.style.borderColor=Fe.borderColor:Ee.style.borderColor="",Fe.paddingX?(Ee.style.paddingLeft=Fe.paddingX,Ee.style.paddingRight=Fe.paddingX):(Ee.style.paddingLeft="",Ee.style.paddingRight=""),Fe.paddingY?(Ee.style.paddingTop=Fe.paddingY,Ee.style.paddingBottom=Fe.paddingY):(Ee.style.paddingTop="",Ee.style.paddingBottom=""),R.isStreaming()||Ee.setAttribute("aria-label",Ar),Pc(),Hn&&yn({anchor:Ee,trigger:Hn,text:()=>Ee.getAttribute("aria-label")??Ar,enabled:ug}),hh(),hu();let mb=rp(he.getState().activeModeIds,o.composer?.modes);he.setActiveModeIds(mb),Ai().length>0!==!!pr&&au(),pr?.render(mb,Ai());for(let J of[...xi.keys()])op(J,o.composer?.modeGroups)||xi.delete(J);xi.forEach(J=>J.repaint()),$r?.repaint(),So?.resolve();let zc=bs(o,Pe());if(mu(),zc){Me.style.maxWidth=zc,Me.style.marginLeft="auto",Me.style.marginRight="auto",Me.style.width="100%",Ln.style.maxWidth=zc,Ln.style.marginLeft="auto",Ln.style.marginRight="auto",Ln.style.width="100%";for(let J of[wn,so,un,nt])J&&(J.style.maxWidth=zc,J.style.marginLeft="auto",J.style.marginRight="auto",J.style.width="100%")}else{Me.style.maxWidth="",Me.style.marginLeft="",Me.style.marginRight="",Me.style.width="",Ln.style.maxWidth="",Ln.style.marginLeft="",Ln.style.marginRight="",Ln.style.width="";for(let J of[wn,so,un,nt])J&&(J.style.maxWidth="",J.style.marginLeft="",J.style.marginRight="",J.style.width="")}let Po=o.statusIndicator??{};if(Ug(nt,wn,Po),ri(nt,Po,R?.getStatus()??"idle"),R){let J=R.getStatus();As(nt,(et=>et==="idle"?Po.idleText??Kt.idle:et==="connecting"?Po.connectingText??Kt.connecting:et==="connected"?Po.connectedText??Kt.connected:et==="error"?Po.errorText??Kt.error:et==="paused"?Po.pausedText??Kt.paused:et==="resuming"?Po.resumingText??Kt.resuming:Kt[et])(J),Po,J)}nt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let IM=Po.align==="left"?"persona-text-left":Po.align==="center"?"persona-text-center":"persona-text-right";nt.classList.add(IM),su(),Iu(),Ao(),sr()},open(){Ke()&&xt(!0,"api")},close(){Ke()&&xt(!1,"api")},toggle(){Ke()&&xt(!D,"api")},reconnect(){R.reconnectNow()},clearChat(){ur=!1,i.clear(),r.clear(),s.clear(),l.clear(),R.clearMessages(),o.layout?.topFade&&(se.scrollTop=0),se.removeAttribute("data-persona-top-fade"),xn.clear(),$o();try{localStorage.removeItem(La),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${La}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==La)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),T?.clear&&wc(()=>T.clear(),"[AgentWidget] Failed to clear storage adapter:"),P={},We.syncFromMetadata(),Ue?.clearAttachments(),Ac(),Mi(void 0),Do(void 0),_s(),ut?.clear(),ht?.reset(),nn?.update()},setMessage(a){return!ae||R.isStreaming()||Uo()?!1:(!D&&Ke()&&xt(!0,"system"),ae.value=a,ae.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(R.isStreaming()||js())return!1;let u=a?.trim()||ae.value.trim();return u?(!D&&Ke()&&xt(!0,"system"),ae.value="",ae.style.height="auto",io(),Nc(u,{consumeDraft:!1}),!0):!1},getComposerState(){return he.getState()},setQuote(a){let u=a?.text?.trim();u&&Do({...a,text:u})},clearQuote(){Do(void 0)},startVoiceRecognition(){return R.isStreaming()?!1:On(o.voiceRecognition?.provider)?(R.isVoiceActive()||R.isBargeInActive()||(!D&&Ke()&&xt(!0,"system"),ot.manuallyDeactivated=!1,Eo(),R.toggleVoice().then(()=>{ot.active=R.isVoiceActive(),yr("user"),R.isVoiceActive()&&ji()})),!0):jo?!0:Oy()?(!D&&Ke()&&xt(!0,"system"),ot.manuallyDeactivated=!1,Eo(),Uc("user"),!0):!1},stopVoiceRecognition(){return On(o.voiceRecognition?.provider)?!R.isVoiceActive()&&!R.isBargeInActive()?!1:((R.isBargeInActive()?R.deactivateBargeIn():R.toggleVoice()).then(()=>{ot.active=!1,ot.manuallyDeactivated=!0,Eo(),yr("user"),Sr()}),!0):jo?(ot.manuallyDeactivated=!0,Eo(),Zr("user"),!0):!1},injectMessage(a){return!D&&Ke()&&xt(!0,"system"),R.injectMessage(a)},injectAssistantMessage(a){!D&&Ke()&&xt(!0,"system");let u=R.injectAssistantMessage(a);return S&&(S=!1,F&&(clearTimeout(F),F=null),setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)),u},injectUserMessage(a){return!D&&Ke()&&xt(!0,"system"),R.injectUserMessage(a)},injectSystemMessage(a){return!D&&Ke()&&xt(!0,"system"),R.injectSystemMessage(a)},injectMessageBatch(a){return!D&&Ke()&&xt(!0,"system"),R.injectMessageBatch(a)},injectComponentDirective(a){return!D&&Ke()&&xt(!0,"system"),R.injectComponentDirective(a)},injectTestMessage(a){!D&&Ke()&&xt(!0,"system"),R.injectTestEvent(a)},async connectStream(a,u){return R.connectStream(a,u)},__pushEventStreamEvent(a){be&&(rr(),Ia(a.type,a.payload))},showEventStream(){be&&ru()},hideEventStream(){Cn&&Ei()},isEventStreamVisible(){return Cn},listConversations(a){return R.listConversations(a)},getActiveConversationId(){return R.getActiveConversationId()},openConversation(a,u){return Vo(m=>m.openHistoryConversation(a,{focusComposer:u?.focus===!0}))},startNewConversation(a){return Vo(u=>u.startNewConversation({focusComposer:a?.focus===!0}))},warmSession(){Xu()},deleteConversation(a){return Vo(u=>u.deleteHistoryConversation(a))},renameConversation(a,u){return Vo(m=>m.updateHistoryConversation(a,{title:u}))},setConversationStarred(a,u){return Vo(m=>m.updateHistoryConversation(a,{starred:u}))},clearConversationHistory(a){return Vo(u=>u.clearConversationHistory(a))},resetHistoryIdentity(){return Vo(a=>a.resetHistoryIdentity())},async getVisitorToken(){let a=po;if(!a)return null;let u=await a.get();return a===po?u:null},getHistoryIdentityStatus(){let a=Ot?.historyProvider;return a?a.getIdentityStatus():Ja()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(a){return Ja()?Vo(u=>u.openHistory({...a?.returnSurface?{returnSurface:a.returnSurface}:{},...a?.focus!==void 0?{focus:a.focus}:{}})):Promise.resolve()},hideHistory(a){Ot?.closeHistory(a?.restoreFocus!==void 0?{restoreFocus:a.restoreFocus}:void 0)},isHistoryVisible(){return dn},showArtifacts(){Dn(o)&&(ur=!1,Pi=!0,Mo(),Je?.setMobileOpen(!0))},hideArtifacts(){Dn(o)&&(ur=!0,Mo())},upsertArtifact(a){return Dn(o)?(Er(o.features?.artifacts,{artifactType:a.artifactType,...a.artifactType==="markdown"&&a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{}})==="panel"&&(ur=!1,Pi=!0),R.upsertArtifact(a)):null},selectArtifact(a){Dn(o)&&R.selectArtifact(a)},clearArtifacts(){Dn(o)&&R.clearArtifacts()},getArtifacts(){return R?.getArtifacts()??[]},getSelectedArtifactId(){return R?.getSelectedArtifactId()??null},focusInput(){return me&&!D&&!Pe()||!ae?!1:(ae.focus(),!0)},async resolveApproval(a,u,m){let w=R.getMessages().find(k=>k.variant==="approval"&&k.approval?.id===a);if(!w?.approval)throw new Error(`Approval not found: ${a}`);if(w.approval.toolType==="webmcp"){R.resolveWebMcpApproval(w.id,u);return}return R.resolveApproval(w.approval,u,m)},setFollowUpSuggestions(a){bx(a)},clearFollowUpSuggestions(){qh()},getMessages(){return R.getMessages()},getStatus(){return R.getStatus()},getPersistentMetadata(){return{...P}},updatePersistentMetadata(a){Ve(a)},on(a,u){return Y.on(a,u)},off(a,u){Y.off(a,u)},isOpen(){return Ke()&&D},isVoiceActive(){return ot.active},toggleReadAloud(a){R.toggleReadAloud(a)},stopReadAloud(){R.stopSpeaking()},getReadAloudState(a){return R.getReadAloudState(a)},onReadAloudChange(a){return R.onReadAloudChange(a)},getState(){return{open:Ke()&&D,launcherEnabled:me,voiceActive:ot.active,streaming:R.isStreaming()}},showCSATFeedback(a){!D&&Ke()&&xt(!0,"system");let u=Me.querySelector(".persona-feedback-container");u&&u.remove();let m=Dm({onSubmit:async(b,w)=>{R.isClientTokenMode()&&await R.submitCSATFeedback(b,w),a?.onSubmit?.(b,w)},onDismiss:a?.onDismiss,...a});Me.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!D&&Ke()&&xt(!0,"system");let u=Me.querySelector(".persona-feedback-container");u&&u.remove();let m=Nm({onSubmit:async(b,w)=>{R.isClientTokenMode()&&await R.submitNPSFeedback(b,w),a?.onSubmit?.(b,w)},onDismiss:a?.onDismiss,...a});Me.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,u){return R.submitCSATFeedback(a,u)},async submitNPSFeedback(a,u){return R.submitNPSFeedback(a,u)},destroy(){ju(),qs!=null&&(clearInterval(qs),qs=null),i.clear(),r.clear(),s.clear(),l.clear(),Ce.forEach(a=>a()),Ye.remove(),Gt?.remove(),Vt?.destroy(),In?.remove(),Is&&je.removeEventListener("click",Is)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,u={controller:jt,getMessages:jt.getMessages,getStatus:jt.getStatus,getMetadata:jt.getPersistentMetadata,updateMetadata:jt.updatePersistentMetadata,clearHistory:()=>jt.clearChat(),setVoiceActive:m=>m?jt.startVoiceRecognition():jt.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Ce.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=a)})}if(typeof window<"u"){let a=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=re=>{let ie=re.detail;(!ie?.instanceId||ie.instanceId===a)&&jt.focusInput()};if(window.addEventListener("persona:focusInput",u),Ce.push(()=>{window.removeEventListener("persona:focusInput",u)}),be){let re=le=>{let Te=le.detail;(!Te?.instanceId||Te.instanceId===a)&&jt.showEventStream()},ie=le=>{let Te=le.detail;(!Te?.instanceId||Te.instanceId===a)&&jt.hideEventStream()};window.addEventListener("persona:showEventStream",re),window.addEventListener("persona:hideEventStream",ie),Ce.push(()=>{window.removeEventListener("persona:showEventStream",re),window.removeEventListener("persona:hideEventStream",ie)})}let m=re=>{let ie=re.detail;(!ie?.instanceId||ie.instanceId===a)&&jt.showHistory()},b=re=>{let ie=re.detail;(!ie?.instanceId||ie.instanceId===a)&&jt.hideHistory()};window.addEventListener("persona:showHistory",m),window.addEventListener("persona:hideHistory",b),Ce.push(()=>{window.removeEventListener("persona:showHistory",m),window.removeEventListener("persona:hideHistory",b)});let w=re=>{let ie=re.detail;(!ie?.instanceId||ie.instanceId===a)&&jt.showArtifacts()},k=re=>{let ie=re.detail;(!ie?.instanceId||ie.instanceId===a)&&jt.hideArtifacts()},q=re=>{let ie=re.detail;ie?.instanceId&&ie.instanceId!==a||ie?.artifact&&jt.upsertArtifact(ie.artifact)},ne=re=>{let ie=re.detail;ie?.instanceId&&ie.instanceId!==a||typeof ie?.id=="string"&&jt.selectArtifact(ie.id)},G=re=>{let ie=re.detail;(!ie?.instanceId||ie.instanceId===a)&&jt.clearArtifacts()};window.addEventListener("persona:showArtifacts",w),window.addEventListener("persona:hideArtifacts",k),window.addEventListener("persona:upsertArtifact",q),window.addEventListener("persona:selectArtifact",ne),window.addEventListener("persona:clearArtifacts",G),Ce.push(()=>{window.removeEventListener("persona:showArtifacts",w),window.removeEventListener("persona:hideArtifacts",k),window.removeEventListener("persona:upsertArtifact",q),window.removeEventListener("persona:selectArtifact",ne),window.removeEventListener("persona:clearArtifacts",G)})}let go=tR(o.persistState);if(go&&Ke()){let a=nR(go.storage),u=`${go.keyPrefix}widget-open`,m=`${go.keyPrefix}widget-voice`,b=`${go.keyPrefix}widget-voice-mode`;if(a){let w=go.persist?.openState&&a.getItem(u)==="true",k=go.persist?.voiceState&&a.getItem(m)==="true",q=go.persist?.voiceState&&a.getItem(b)==="true";if(w&&(Vt?.setPanelOpen(!0,"auto"),setTimeout(()=>{jt.open(),setTimeout(()=>{if(k||q)jt.startVoiceRecognition();else if(go.persist?.focusInput){let ne=e.querySelector("textarea");ne&&ne.focus()}},100)},0)),go.persist?.openState&&(Y.on("widget:opened",()=>{a.setItem(u,"true")}),Y.on("widget:closed",()=>{a.setItem(u,"false")})),go.persist?.voiceState&&(Y.on("voice:state",ne=>{a.setItem(m,ne.active?"true":"false")}),Y.on("user:message",ne=>{a.setItem(b,ne.viaVoice?"true":"false")})),go.clearOnChatClear){let ne=()=>{a.removeItem(u),a.removeItem(m),a.removeItem(b)},G=()=>ne();window.addEventListener("persona:clear-chat",G),Ce.push(()=>{window.removeEventListener("persona:clear-chat",G)})}}}if(xe&&Ke()&&(Vt?.setPanelOpen(!0,"auto"),setTimeout(()=>{jt.open()},0)),_i(),!vx){let a=il(()=>{R&&(Ds++,xn.clear(),co(Me,R.getMessages(),K))});Ce.push(a)}I=()=>{R&&(Ds++,xn.clear(),co(Me,R.getMessages(),K))},R.getMessages().length>0&&Tc(),W=()=>{R&&(Ds++,xn.clear(),co(Me,R.getMessages(),K))};let LM=wb(()=>{R&&(Ds++,xn.clear(),co(Me,R.getMessages(),K))});Ce.push(LM);let HM=Tm(()=>{R&&(Ds++,xn.clear(),co(Me,R.getMessages(),K),Wr()?.updateInlineArtifactBlocks(Me,ao.artifacts,{suppressTransition:!0}),Mo())});return Ce.push(HM),jt};Lo();var vA=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},sR=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},iR=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},aR=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&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.")},CA=(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"},qm=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=""},wA=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",qm(e)},Um=e=>{e.style.transition=""},Vm=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=""},jm=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},_p=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},lR=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},cR=(e,t,n,o,r,s)=>{let i=s?t:e;r==="left"?i.firstElementChild!==o&&i.replaceChildren(o,n):i.lastElementChild!==o&&i.replaceChildren(n,o)},dR=e=>{let t=Zo(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:vn(t,r)??r;return{inset:o(n?.inset,lp),canvasBackground:o(n?.canvasBackground,cp)}},SA=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},pR=(e,t,n,o,r,s,i,l)=>{let c=to(s),p=c.reveal==="push",d=l!=null,g=l?.inset??"",f=l?.canvasBackground??"";lR(e,t,n,o,p),cR(e,t,n,o,c.side,p),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=i?"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",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let h=e.ownerDocument.defaultView,y=s?.launcher?.mobileFullscreen??!0,v=s?.launcher?.mobileBreakpoint??640,C=h!=null?h.innerWidth<=v:!1;if(y&&C&&i){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Vm(t),Um(o),wA(o),jm(n),_p(r,o),SA(o,!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",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Tn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(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");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),wA(o),sR(o,c.maxHeight),SA(o,d&&i,g,f),c.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Vm(t),Um(o),jm(n),_p(r,o);let L=c.animate?"transform 180ms ease":"none",I=c.side==="right"?"translateX(100%)":"translateX(-100%)",H=i?"translateX(0)":I;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=c.width,o.style.maxWidth=c.width,o.style.minWidth=c.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=L,o.style.transform=H,o.style.pointerEvents=i?"auto":"none",o.style.zIndex="2",c.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.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",Um(o),qm(o),_p(r,o);let L=vA(c.width,e.clientWidth),I=Math.max(0,e.clientWidth),H=c.animate?"margin-left 180ms ease":"none",_=c.side==="right"?i?-L:0:i?0:-L;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=`${I+L}px`,t.style.transition=H,t.style.marginLeft=`${_}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${I}px`,n.style.maxWidth=`${I}px`,n.style.minWidth=`${I}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=c.width,o.style.minWidth=c.width,o.style.maxWidth=c.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=i?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Vm(t),qm(o),jm(n),_p(r,o);let L=c.reveal==="emerge";L?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=i?c.width:"0px",H=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${d?", padding 180ms ease":""}`:"none",_=!i;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${I}`,o.style.width=I,o.style.maxWidth=I,o.style.minWidth=I,o.style.minHeight="0",iR(o,c.maxHeight),o.style.overflow=L||_?"hidden":"visible",o.style.transition=H,L){o.style.alignItems=c.side==="right"?"flex-start":"flex-end";let V=d?`calc(${vA(c.width,e.clientWidth)}px - (2 * ${g}))`:c.width;r.style.width=V,r.style.minWidth=V,r.style.maxWidth=V,r.style.boxSizing="border-box"}}},uR=(e,t)=>{let n=e.ownerDocument.createElement("div");return CA(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){CA(n,o)},destroy(){n.remove()}}},gR=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,i=n.createElement("div"),l=n.createElement("div"),c=n.createElement("div"),p=n.createElement("aside"),d=n.createElement("div"),g=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",d.dataset.personaDockRole="host",p.appendChild(d),o.insertBefore(i,e),c.appendChild(e);let f=null,h=()=>{f?.disconnect(),f=null},y=null,v=()=>{y=t?.launcher?.detachedPanel===!0?dR(t):null};v();let C=()=>{pR(i,l,c,p,d,t,g,y)},A=null,L=()=>{A?.(),A=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(A=Il(()=>{v(),C()}))},I=()=>{h(),to(t).reveal==="push"&&(typeof ResizeObserver>"u"||(f=new ResizeObserver(()=>{C()}),f.observe(i)))},H=!1,_=()=>{C(),I(),g&&!H&&i.dataset.personaDockMobileFullscreen!=="true"&&(H=!0,aR(i,to(t)))},V=i.ownerDocument.defaultView,te=()=>{_()};return V?.addEventListener("resize",te),to(t).reveal==="push"?(l.appendChild(c),l.appendChild(p),i.appendChild(l)):(i.appendChild(c),i.appendChild(p)),_(),L(),{mode:"docked",host:d,shell:i,syncWidgetState(W){let j=W.launcherEnabled?W.open:!0;g!==j&&(g=j,_())},updateConfig(W){t=W,(t?.launcher?.enabled??!0)===!1&&(g=!0),v(),_(),L()},destroy(){V?.removeEventListener("resize",te),A?.(),A=null,h(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),i.remove()}}},Dp=(e,t)=>Ht(t)?gR(e,t):uR(e,t);var fR=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},AA=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},Np=[],mR=()=>[...Np],xA=e=>{let t=fR(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=Dp(t,r),i,l=[],c=(C,A)=>{let I=!(A?.launcher?.enabled??!0)||Ht(A),H=o.createElement("div");if(H.setAttribute("data-persona-root","true"),I&&(H.style.height="100%",H.style.display="flex",H.style.flexDirection="column",H.style.flex="1",H.style.minHeight="0",H.style.minWidth="0"),n){let _=C.attachShadow({mode:"open"});_.appendChild(H),AA(_,o)}else C.appendChild(H),AA(C,o);return t.id&&H.setAttribute("data-persona-instance",t.id),H},p=()=>{s.syncWidgetState(i.getState())},d=()=>{l.forEach(C=>C()),l=[i.on("widget:opened",p),i.on("widget:closed",p)],p()},g=()=>{let C=c(s.host,r);i=$m(C,r,{debugTools:e.debugTools}),d()},f=()=>{l.forEach(C=>C()),l=[],i.destroy()};g(),e.onChatReady?.();let h=C=>{f(),s.destroy(),s=Dp(t,C),r=C,g()},y={update(C){let A=Ip(r??{},C),L=Ht(r),I=Ht(A),H=Cs(r),_=Cs(A);if(L!==I||H!==_){h(A);return}r=A,s.updateConfig(r),i.update(C),p()},destroy(){f(),s.destroy();let C=Np.indexOf(v);C!==-1&&Np.splice(C,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},v=new Proxy(y,{get(C,A,L){if(A==="host")return s.host;if(A in C)return Reflect.get(C,A,L);let I=i[A];return typeof I=="function"?I.bind(i):I}});return Np.push(v),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=v),v};Yi();gl();ad();ea();ei();ss();Hr();var kA=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),hR=new Set(["button","a","input","select","textarea","details","summary"]),yR=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),zm=/\b(product|card|item|listing|result)\b/i,Gm=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,bR=3e3,vR=100;function LA(e){let t=typeof e.className=="string"?e.className:"";if(zm.test(t)||e.id&&zm.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&zm.test(o.value))return!0}return!1}function HA(e){return Gm.test((e.textContent??"").trim())}function IA(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function CR(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function MA(e){let t=e.match(Gm);return t?t[0]:null}function EA(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 o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o: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 wR(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var SR="commerce-card",AR="result-card";function TA(e){return!LA(e)||!HA(e)||!IA(e)&&!CR(e)?0:5200}function PA(e){return!LA(e)||HA(e)||!IA(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var RA=[{id:SR,scoreElement(e){return TA(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||Gm.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(TA(e)===0)return null;let{title:n,href:o}=EA(e),r=MA((e.textContent??"").trim())??MA(t.text)??"",s=wR(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
141
- `)}},{id:AR,scoreElement(e){return PA(e)},formatSummary(e,t){if(PA(e)===0)return null;let{title:n,href:o}=EA(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
142
- `)}}];function xR(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function MR(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,s=t.visibleOnly??e.visibleOnly??!0,i=t.root??e.root,l=t.mode??"structured",c=t.maxCandidates??Math.max(500,n*10),p=e.rules??RA;return l==="simple"&&e.rules&&e.rules.length>0?(xR(),p=[]):l==="simple"&&(p=[]),{mode:l,maxElements:n,maxCandidates:c,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:i,rules:p}}function Km(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var ER=["data-testid","data-product","data-action","data-id","data-name","data-type"];function TR(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"||hR.has(t)||n&&yR.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function WA(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 PR(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let s=e.getAttribute("type");s&&(t.type=s);let i=e.getAttribute("value");i&&(t.value=i);let l=e.getAttribute("name");l&&(t.name=l);let c=e.getAttribute("role");c&&(t.role=c);for(let p=0;p<e.attributes.length;p++){let d=e.attributes[p];d.name.startsWith("data-")&&(t[d.name]=d.value)}return t}function OA(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${Km(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of ER){let s=e.getAttribute(r);if(s){let i=`${t}[${r}="${Km(s)}"]`;try{if(e.ownerDocument.querySelectorAll(i).length===1)return i}catch{}}}let n=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(n.length>0){let r=`${t}.${n.map(i=>Km(i)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let s=e.parentElement;if(s){let l=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(l>=0){let c=`${r}:nth-of-type(${l+1})`;try{if(e.ownerDocument.querySelectorAll(c).length===1)return c}catch{}}}}let o=e.parentElement;if(o){let s=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function kR(e){return e==="static"?vR:bR}function BA(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:OA(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:TR(e),attributes:PR(e)}}function LR(e,t,n,o){let r=kR(t.interactivity),s=null;for(let i of n){let l=i.scoreElement(e,t,o);l>0&&(r+=l,i.formatSummary&&!s&&(s=i))}return{score:r,formattingRule:s}}function HR(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 IR(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],s=0,i=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),l=i.currentNode;for(;l&&r.length<e.maxCandidates;){if(l.nodeType===Node.ELEMENT_NODE){let p=l,d=p.tagName.toLowerCase();if(kA.has(d)){l=i.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){l=i.nextNode();continue}}catch{}if(e.visibleOnly&&!WA(p)){l=i.nextNode();continue}let g=BA(p,e.maxTextLength),f=g.text.length>0,h=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(C=>C==="role");if(!f&&!h){l=i.nextNode();continue}if(o.has(g.selector)){l=i.nextNode();continue}o.add(g.selector);let{score:y,formattingRule:v}=LR(p,g,e.rules,n);r.push({el:p,domIndex:s,enriched:g,score:y,formattingRule:v}),s+=1}l=i.nextNode()}r.sort((p,d)=>{let g=p.enriched.interactivity==="static"?1:0,f=d.enriched.interactivity==="static"?1:0;return g!==f?g-f:d.score!==p.score?d.score-p.score:p.domIndex-d.domIndex});let c=[];for(let p of r){if(c.length>=e.maxElements)break;HR(c,p)||c.push(p)}return c.sort((p,d)=>{let g=p.enriched.interactivity==="static"?1:0,f=d.enriched.interactivity==="static"?1:0;return g!==f?g-f:g===1&&d.score!==p.score?d.score-p.score:p.domIndex-d.domIndex}),c.map(p=>{let d;if(p.formattingRule?.formatSummary){let f=p.formattingRule.formatSummary(p.el,p.enriched,n);f&&(d=f)}let g={...p.enriched};return d&&(g.formattedSummary=d),g})}function RR(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=r.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let c=s,p=c.tagName.toLowerCase();if(kA.has(p)){s=r.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!WA(c)){s=r.nextNode();continue}let d=BA(c,e.maxTextLength),g=d.text.length>0,f=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(h=>h==="role");if(!g&&!f){s=r.nextNode();continue}o.has(d.selector)||(o.add(d.selector),n.push(d))}s=r.nextNode()}let i=[],l=[];for(let c of n)c.interactivity!=="static"?i.push(c):l.push(c);return[...i,...l].slice(0,e.maxElements)}function WR(e={}){let t=MR(e),n=t.root??document.body;return n?t.mode==="simple"?RR(t,n):IR(t,n):[]}var Fp=100;function OR(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let s=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);s.length>0&&o.push(`Structured summaries:
139
+ ${Et?"background: transparent !important;":""}
140
+ `)}if(!w&&!u){let Oe="max-height: -moz-available !important; max-height: stretch !important;",Ke=m?"":"padding-top: 1.25em !important;",Fe=m?"":`z-index: ${o.launcher?.zIndex??Tn} !important;`;Xe.style.cssText+=Oe+Ke+Fe}Nt(),yo()},bu=()=>{e.style.setProperty("--persona-content-max-width",bs(o,ke()))},Ih=!1;function Rh(){o.layout?.topFade&&se.scrollTop>1?se.setAttribute("data-persona-top-fade","true"):se.removeAttribute("data-persona-top-fade")}let vu=()=>{Rh();let a=Xf(o,ke());ke()&&o.composer?.placement&&o.debug===!0&&!Ih&&(Ih=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let u=E();e.setAttribute("data-persona-composer-placement",a),e.setAttribute("data-persona-conversation-state",N),e.setAttribute("data-persona-welcome-anchor",u.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",u.composerGap??mp),Rt()},Wh=()=>{if(ke())return;let a=Ht(o),u=o.launcher?.sidebarMode??!1;if(a||u||(o.launcher?.fullHeight??!1)||!me)return;let v=e.ownerDocument.defaultView??window,w=o.launcher?.mobileFullscreen??!0,P=o.launcher?.mobileBreakpoint??640;if(w&&v.innerWidth<=P)return;let z=ui(o);we.style.height=z.height,we.style.maxHeight=z.maxHeight};yu(),ha(e,o),Kl(e,o),Gl(e,o),bu(),vu(),Ps=()=>{yu(),Wh(),ha(e,o),Kl(e,o),Gl(e,o),bu(),vu(),ac?e.style.setProperty("--persona-artifact-welded-outer-radius",ac):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Fn(),sr()};let Ce=[];Ce.push(()=>{xh=!0}),Ce.push(()=>{f.forEach(a=>a()),g.destroy()}),Ce.push(()=>{document.removeEventListener("keydown",kh)}),Ce.push(()=>{Fr!==null&&clearTimeout(Fr)});let No=null,Fo=null;Ce.push(()=>{No?.(),No=null,Fo?.(),Fo=null}),Da&&Ce.push(()=>{Da?.disconnect(),Da=null}),Ce.push(()=>{Ua?.(),Ua=null,hu(),Ft&&(Ft.remove(),Ft=null),et?.element.style.removeProperty("width"),et?.element.style.removeProperty("maxWidth"),et?.destroy()}),xe&&Ce.push(()=>{hi=!0,Dt=null,so!==null&&(cancelAnimationFrame(so),so=null),nn?.destroy(),nn=null,ut?.destroy(),ut=null,cn=null});let Ls=null,Oh=()=>{Ls&&(Ls(),Ls=null),o.colorScheme==="auto"&&(Ls=Il(()=>{ha(e,o)}))};Oh(),Ce.push(()=>{Ls&&(Ls(),Ls=null)}),Ce.push(()=>{L=!0,A?.()}),Ce.push(()=>{V=!0});let _h=!1;Ce.push(()=>{_h=!0});let Cu=(a,u)=>{let m=_l(a,u);return m||!iS.includes(a)?m:(lS().then(v=>{if(_h)return;bp(v.wipe),bp(v.glyphCycle);let w=_l(a,u);w&&Nl(w,e)}).catch(()=>{}),null)},hc=o.features?.streamAnimation;if(hc?.type&&hc.type!=="none"){let a=Cu(hc.type,hc.plugins);a&&Nl(a,e),Ce.push(()=>aS(e))}let fr=Ul(io),Bh=Ul(lr),Dh=Ul(Dr),Hs=[fr,Bh,Dh];Ce.push(()=>{Hs.forEach(a=>a.destroy())});let Is=null,R,Rs=null,Nh=!1,Fh=0,$h=null,Uh=a=>a.reduce((u,m)=>m.role==="user"?u+1:u,0),Vh=a=>{for(let u=a.length-1;u>=0;u--)if(Zi(a[u]))return a[u].id??null;return null},jh=!1,Sx=()=>{jh||o.debug!==!0||(jh=!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".'))},qh=!1,zh=!1,Kh=(a,u)=>{qh||o.debug!==!0||!u.enabled||u.expose||Nh||zh&&(R.isStreaming()||a.some(Zi)||(qh=!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.")))},Ws=a=>{if(!R)return;let u=a??R.getMessages(),m=le=>{le.render([],R,ae,u)},v=le=>{Hs.forEach(Te=>{Te!==le&&m(Te)})};Rs&&(Uh(u)>Fh||Vh(u)!==$h)&&(Rs=null);let w=ps(o);Kh(u,w);let P=w.enabled?_g(u):null,z=Rs??P,ne=Rs?"host":"agent";if(z){let le=o.suggestions?.followUps,Te=le?.placement??(le?"auto":"composer"),pt=(Te==="auto"?ke()?"composer":"after-message":Te)==="after-message"?Dh:fr;v(pt),pt.render(z,R,ae,u,o.suggestionChipsConfig,{source:ne,surface:"followUp",variant:le?.variant??"chip",behavior:le?.behavior??"send",overflow:le?.overflow??"wrap",maxItems:le?.maxItems??4,config:o,plugins:d,submitPrompt:Fc});return}if(u.some(le=>le.role==="user")){Hs.forEach(m);return}let G=o.future?.v5Defaults===!0,re=$n(),ie=o.suggestions?.starters??(G?{}:void 0);if(ie){let le=pi(E(),u),Te=ie.placement??"auto",rt=Te==="auto"?le?"welcome":"composer":Te;if(rt==="welcome"&&!le){Sx(),Hs.forEach(m);return}let pt=rt==="welcome"?Bh:fr;v(pt),pt.render(ie.items??o.suggestionChips,R,ae,u,o.suggestionChipsConfig,{surface:"starter",variant:ie.variant??(G&&!re?"chip":"card"),behavior:ie.behavior??"send",overflow:ie.overflow??"wrap",maxItems:ie.maxItems??(G&&!re?3:4),config:o,plugins:d,submitPrompt:Fc});return}v(fr),fr.render(o.suggestionChips,R,ae,u,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:d,submitPrompt:Fc})},Gh=()=>{Rs&&(Rs=null,Ws())},Ax=a=>{let u=Array.isArray(a)?[...a]:[];if(!u.length){Gh();return}let m=R?R.getMessages():[];Rs=u,Nh=!0,Fh=Uh(m),$h=Vh(m),Ws(m)},Yn=!1,xn=Gw(),Pi=new Map,Os=new Map,jr=new Map,_s=null,qr=null;function Bs(){if(!_s)return;let a=_s;_s=null,qr?.destroy(),qr=null,xn.delete(a),ve.querySelector(`#wrapper-${a}`)?.removeAttribute("data-preserve-runtime"),R&&po(Ee,R.getMessages(),K)}let Ds=0,xx=Yo()!==null,Xn=Zw(),Qn=0,zr=null,Un=!1,yc=!1,Kr=0,rn=null,Ns=null,wu=!1,Li=!1,Fs=null,Va=!0,bc=!1,Hi=null,vc=!1,Gr=()=>{vc=!0,kx()},Su=null,Ex=4,mr=24,Mx=80,Tx=1e3,hr=null,Yh=()=>{e.setAttribute("data-persona-scrollbar",Ms()),Ms()!=="on-scroll"&&(hr!==null&&clearTimeout(hr),hr=null,se.removeAttribute("data-persona-scrollbar-visible"))},kx=()=>{Ms()==="on-scroll"&&(se.setAttribute("data-persona-scrollbar-visible",""),hr!==null&&clearTimeout(hr),hr=setTimeout(()=>{hr=null,di(se,mr)&&se.removeAttribute("data-persona-scrollbar-visible")},Tx))};Yh(),Ce.push(()=>{hr!==null&&clearTimeout(hr)});let Au=new Map,xu=!1,Cc=null,ze={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};xo();let Xh=o.voiceRecognition?.autoResume??!1,Eu=()=>R.isVoiceActive()||R.isBargeInActive(),Qh=!1,yr=a=>{Y.emit("voice:state",{active:ze.active,source:a,timestamp:Date.now()})},Vn=()=>{Ve(a=>({...a,voiceState:{active:ze.active,timestamp:Date.now(),manuallyDeactivated:ze.manuallyDeactivated}}))},Px=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=Vm(k.voiceState),u=!!a.active,m=Number(a.timestamp??0);ze.manuallyDeactivated=!!a.manuallyDeactivated,u&&Date.now()-m<nR&&setTimeout(()=>{ze.active||(ze.manuallyDeactivated=!1,Ln(o.voiceRecognition?.provider)?R.toggleVoice().then(()=>{ze.active=Eu(),yr("restore"),ze.active?ji():(Vn(),Nc(oR,1e4))}):jc("restore"))},Ln(o.voiceRecognition?.provider)?0:1e3)},Jh=a=>{Qh=!a.persisted,ze.active&&Vn()};typeof window<"u"&&(window.addEventListener("pagehide",Jh),Ce.push(()=>window.removeEventListener("pagehide",Jh)));let Lx=()=>R?CA(R.getMessages()).filter(a=>!a.__skipPersist):[],wc=null,Zh=(a,u)=>{typeof console<"u"&&console.error(a,u)},Sc=(a,u)=>{let m=()=>{try{let z=a();return!z||typeof z.then!="function"?null:Promise.resolve(z).catch(ne=>{Zh(u,ne)})}catch(z){return Zh(u,z),null}},v=wc,w=v?v.then(()=>m()??void 0):m();if(!w)return;let P=w.finally(()=>{wc===P&&(wc=null)});wc=P};function Ii(a){if(!T?.save)return;let u=a?CA(a):R?Lx():[],m=_&&R?.getResumableHandle();m&&(k={...k,durableResume:{executionId:m.executionId,after:m.lastEventId}});let v={messages:u,metadata:k,artifacts:lo.artifacts,selectedArtifactId:lo.selectedId,...$s?{draft:$s}:{}};Sc(()=>T.save(v),"[AgentWidget] Failed to persist state:")}let $s,Ac=()=>!T?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,ja=Pw({write:()=>{if(!Ac())return;let a=he.getState(),u=Tw({text:a.text,mentionRefs:a.mentionRefs,contentSegments:ng(),selectedModelId:a.selectedModelId,activeModeIds:a.activeModeIds,quote:a.quote});JSON.stringify(u)!==JSON.stringify($s)&&($s=u,Ii())}});function ey(){Ac()&&ja.schedule()}function Mu(){ja.flush()}function ty(a){if(!Ac())return;let u=kw(a,{mentionSourceIds:(o.contextMentions?.sources??[]).map(m=>m.id),modelIds:(o.composer?.models??[]).map(m=>m.id),modes:o.composer?.modes??[]});u&&($s=a,ae&&!ae.value&&(ae.value=u.text,ae.dispatchEvent(new Event("input",{bubbles:!0})),ao()),u.selectedModelId&&(he.setSelectedModelId(u.selectedModelId),$r?.repaint()),sc(u.activeModeIds??[]),u.quote&&Do(u.quote),ja.cancel())}function xc(){ja.cancel(),$s&&($s=void 0,Ac()&&Ii())}let Ri=null,ny=()=>Xe.querySelector("#persona-scroll-container")||se,Wi=()=>{Ri!==null&&(cancelAnimationFrame(Ri),Ri=null),Un=!1},oy=()=>{zr!==null&&(cancelAnimationFrame(zr),zr=null),yc=!1,Wi()},Hx=()=>Yn&&ku()&&(An()!=="anchor-top"||Wa()),Tu=()=>{let a=Nr()||"Jump to latest",u=Hx();$t.toggleAttribute("data-persona-scroll-to-bottom-streaming",u),Kr>0?(Zt.textContent=String(Kr),Zt.style.display="",$t.setAttribute("aria-label",`${a} (${Kr} new)`)):(Zt.textContent="",Zt.style.display="none",$t.setAttribute("aria-label",u?`${a} (response streaming below)`:a))},ry=()=>{Kr!==0&&(Kr=0,Tu())},Ix=()=>{let a=rn?.spacerHeight??0;return a<=0?di(se,mr):Tc(a)-se.scrollTop-se.clientHeight<=mr},ku=()=>wo()?!Xn.isFollowing():!Ix(),Pu=()=>!!R&&R.getMessages().length>0,En=()=>{if(!nu()||Zl()){$t.parentNode&&$t.remove(),$t.style.display="none";return}$t.parentNode!==ve&&ve.appendChild($t),He();let u=er(se)>0&&ku()&&Pu();u?Tu():ry(),$t.style.display=u?"":"none"},Oi=()=>{Xn.pause()&&(oy(),En())},$o=()=>{Xn.resume(),ry(),En()},Yr=(a=!1)=>{wo()&&Pu()&&Xn.isFollowing()&&(!a&&!Yn||(zr!==null&&(cancelAnimationFrame(zr),zr=null),yc=!0,zr=requestAnimationFrame(()=>{zr=null,yc=!1,Xn.isFollowing()&&Rx(ny(),a?220:140)})))},sy=(a,u,m,v=()=>!0)=>{let w=a.scrollTop,P=u(),z=P-w;if(Wi(),Math.abs(z)<1){Un=!0,a.scrollTop=P,Qn=a.scrollTop,Un=!1;return}let ne=performance.now();Un=!0;let G=ie=>1-Math.pow(1-ie,3),re=ie=>{if(!v()){Wi();return}let le=u();le!==P&&(P=le,z=P-w);let Te=ie-ne,rt=Math.min(Te/m,1),pt=G(rt),lt=w+z*pt;a.scrollTop=lt,Qn=a.scrollTop,rt<1?Ri=requestAnimationFrame(re):(a.scrollTop=P,Qn=a.scrollTop,Ri=null,Un=!1)};Ri=requestAnimationFrame(re)},Rx=(a,u=500)=>{let m=er(a)-a.scrollTop;if(Math.abs(m)<1){Qn=a.scrollTop;return}if(Math.abs(m)>=Mx){Wi(),Un=!0,a.scrollTop=er(a),Qn=a.scrollTop,Un=!1;return}sy(a,()=>er(a),u,()=>Xn.isFollowing())},Lu=()=>{if(!Pu()){En();return}let a=ny();Un=!0,a.scrollTop=er(a),Qn=a.scrollTop,Un=!1,En()},Us=a=>{let u=0,m=a;for(;m&&m!==se;)u+=m.offsetTop,m=m.offsetParent;return u},Wx=()=>{let a=se.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??se.ownerDocument.getSelection()},Ec=()=>nS(Wx(),se),Hu=()=>{if(rc()!=="last-user-turn")return!1;let a=R?.getMessages()??[];if(a.length<2)return!1;let u=[...a].reverse().find(P=>P.role==="user");if(!u)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(u.id):u.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),v=se.querySelector(`[data-message-id="${m}"]`);if(!v)return!1;let w=Math.min(Math.max(0,Us(v)-Es()),er(se));return Un=!0,se.scrollTop=w,Qn=se.scrollTop,Un=!1,An()==="follow"&&!di(se,mr)&&Xn.pause(),En(),!0},Mc=a=>{let u=Math.max(0,Math.round(a));Yt.style.height=`${u}px`,Yt.style.display=u>0?"":"none",rn&&(rn.spacerHeight=Math.max(0,a))},Tc=a=>{let u=parseFloat(getComputedStyle(se).paddingBottom)||0,m=0;for(let w of Array.from(se.children)){if(w===Yt||w.offsetHeight===0)continue;let P=Us(w)+w.offsetHeight;P>m&&(m=P)}let v=se.scrollHeight-a;return m>0?Math.min(m+u,v):v},Ox=()=>{if(!rn||rn.spacerHeight<=0)return;let a=Tc(rn.spacerHeight),u=Math.max(0,Math.round(se.scrollTop)+se.clientHeight-a+mr);u<rn.spacerHeight&&(Mc(u),En())},Vs=()=>{Ns!==null&&(cancelAnimationFrame(Ns),Ns=null),Wi(),rn=null,Yt.style.height="0px",Yt.style.display="none"},iy=a=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Iu=a=>se.querySelector(`[data-message-id="${iy(a)}"]`),ay=a=>{Ns!==null&&cancelAnimationFrame(Ns),Ns=requestAnimationFrame(()=>{Ns=null;let u=iy(a),m=se.querySelector(`[data-message-id="${u}"]`);if(!m)return;let v=Us(m),w=rn?.spacerHeight??0,P=Tc(w),{targetScrollTop:z,spacerHeight:ne}=Jf({anchorOffsetTop:v,topOffset:Es(),viewportHeight:se.clientHeight,contentHeight:P,slack:mr});rn={initialSpacerHeight:ne,contentHeightAtAnchor:P,spacerHeight:ne},Mc(ne),sy(se,()=>m.isConnected?Math.max(0,Us(m)-Es()):z,220)})},_i=()=>{if(An()!=="anchor-top"||!rn||!Hi)return;let a=Iu(Hi);if(!a)return;Wi();let u=rn.spacerHeight,m=Tc(u),{targetScrollTop:v,spacerHeight:w}=Jf({anchorOffsetTop:Us(a),topOffset:Es(),viewportHeight:se.clientHeight,contentHeight:m,slack:mr});rn={initialSpacerHeight:w,contentHeightAtAnchor:m,spacerHeight:w},Mc(w),Un=!0,se.scrollTop=v,Qn=se.scrollTop,Un=!1,En()},_x=()=>{if(wo()){if(!Xn.isFollowing()||di(se,1))return;Yr(!Yn);return}if(rn&&rn.initialSpacerHeight>0){let a=se.scrollHeight-rn.spacerHeight,u=oS({initialSpacerHeight:rn.initialSpacerHeight,contentHeightAtAnchor:rn.contentHeightAtAnchor,currentContentHeight:a});u!==rn.spacerHeight&&Mc(u)}En()},Bx=a=>{let u=An();u==="follow"?($o(),Yr(!0)):u==="anchor-top"&&(Va=!1,bc=!0,vc=!1,Hi=a,ay(a))},Dx=()=>{if(An()==="anchor-top"){if(bc){Va=!1;return}Va=!0,Vs(),$o(),Yr(!0)}},Nx=96,Fx=a=>{if(Fs===null)return!0;let u=Iu(Fs),m=Iu(a);if(!u||!m)return!0;let v=Us(m)-Us(u);return Es()+v>se.clientHeight-Nx},$x=a=>{if(An()!=="anchor-top"||!bc||vc||Ec())return;let u=Fs===null;for(let m of a){if(!u){m.id===Fs&&(u=!0);continue}if(Jw(m)){if(m.id===Hi||!Fx(m.id))return;Hi=m.id,ay(m.id);return}}},Ux=a=>{let u=new Map;a.forEach(m=>{let v=Au.get(m.id);u.set(m.id,{streaming:m.streaming,role:m.role}),!v&&m.role==="assistant"&&(Y.emit("assistant:message",m),!Li&&(An()!=="anchor-top"||Wa())&&ku()&&(Kr+=1,Tu(),En(),ks(Kr===1?"1 new message below.":`${Kr} new messages below.`))),m.role==="assistant"&&v?.streaming&&m.streaming===!1&&Y.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(v?m.approval.status!=="pending"&&Y.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):Y.emit("approval:requested",{approval:m.approval,message:m}))}),Au.clear(),u.forEach((m,v)=>{Au.set(v,m)})},qa=(a,u)=>{let m=u==="user"?"user":"assistant",v=o.layout?.messages?.[m],w=v?.width??"content",P=v?.maxWidth??(w==="full"?`var(--persona-message-${m}-max-width, 100%)`:void 0);a.classList.add("persona-message-row"),a.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),a.classList.add(`persona-message-row-${u}`,`persona-message-width-${w}`),a.classList.toggle("persona-justify-end",u==="user"),a.setAttribute("data-message-role",u),a.setAttribute("data-message-width",w),P?a.style.setProperty("--persona-message-row-max-width",P):a.style.removeProperty("--persona-message-row-max-width")},br=(a,u)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${a}`,m.setAttribute("data-wrapper-id",a),qa(m,u),m},Vx=(a,u,m)=>{let v=new Set;for(let O of u){let Be=O.variant==="tool"?"tool":O.variant==="reasoning"?"reasoning":null;if(!Be||fs(o,Be)!=="row")continue;let De=Be==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;De?.expandable!==!1&&(v.add(O.id),i.observe(O,Be,Be==="tool"?r:s,De))}let w=document.createElement("div"),z=(()=>{let O=d.find(Be=>Be.renderLoadingIndicator);if(O?.renderLoadingIndicator)return O.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),ne=(O,Be)=>Be==null?!1:typeof Be=="string"?(O.textContent=Be,!0):(O.appendChild(Be),!0),G=new Set,re=new Map,ie=new Set,le=d.some(O=>O.renderAskUserQuestion),Te=[],rt=[],pt=o.enableComponentStreaming!==!1,lt=o.approval!==!1,jn=[],_t=o.messageActions,Ut=_t?.showRegenerate===!0&&_t.enabled!==!1&&co.current?.isStreaming()!==!0?zC(u):null,Wn=_t?.showEdit===!0&&_t.enabled!==!1,qt=_t?.showQuote===!0&&_t.enabled!==!1,vt=null,qo=o.features?.reasoningDisplay?.completedVisibility,zo=O=>qo==="removed"?!0:qo==="removed-when-short"?_b(O,o.features?.reasoningDisplay?.shortThinkThreshold):!1,mo=o.features?.toolCallDisplay?.completedVisibility==="removed",ho=O=>O.variant==="reasoning"&&O.reasoning?.status==="complete"?zo(O.reasoning):mo&&O.variant==="tool"&&O.toolCall?.status==="complete";if(u.forEach(O=>{if(ho(O))return;if(G.add(O.id),re.set(O.id,O.role),_s===O.id&&qr){let Ne=br(O.id,O.role);Ne.setAttribute("data-persona-message-edit-stub","true"),Ne.setAttribute("data-preserve-runtime","true"),w.appendChild(Ne),vt={messageId:O.id,element:qr.element};return}let Be=le&&is(O),De=lt&&O.variant==="approval"&&!!O.approval,oe=!Be&&O.role==="assistant"&&!O.variant&&pt&&Bp(O);!De&&jr.has(O.id)&&(a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),jr.delete(O.id)),!oe&&Os.has(O.id)&&(a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),Os.delete(O.id));let Ct=is(O)?`:${O.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${O.agentMetadata?.askUserQuestionAnswers?Object.keys(O.agentMetadata.askUserQuestionAnswers).length:0}`:"",Xt={canRegenerate:Ut===O.id,canEdit:Wn&&Hf(O),canQuote:qt&&!O.variant&&(O.content?.trim().length??0)>0},Pn=`${Xt.canRegenerate?"r":""}${Xt.canEdit?"e":""}${Xt.canQuote?"q":""}`,gn=Kw(O,Ds)+Ct+`:${Pn}`,Et=Be||De||oe?null:Yw(xn,O.id,gn);if(Et){w.appendChild(Et.cloneNode(!0)),is(O)&&O.toolCall?.id&&O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(ie.add(O.toolCall.id),mu(O));return}let zt=null,sn=d.find(Ne=>!!(O.variant==="reasoning"&&Ne.renderReasoning||O.variant==="tool"&&Ne.renderToolCall||!O.variant&&Ne.renderMessage)),Ie=o.layout?.messages;if(is(O)&&O.agentMetadata?.askUserQuestionAnswered===!0){Pi.delete(O.id),a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime");return}if(Zi(O)&&ps(o).enabled)return;if(is(O)&&o.features?.askUserQuestion?.enabled!==!1){let Ne=d.find(an=>typeof an.renderAskUserQuestion=="function");if(Ne&&co.current){let an=Pi.get(O.id),yo=an!==gn,fn=null;if(yo){let{payload:Ke,complete:Fe}=as(O),rs=O.id,en=()=>co.current?.getMessages().find(qn=>qn.id===rs);fn=Ne.renderAskUserQuestion({message:O,payload:Ke,complete:Fe,resolve:qn=>{let Ar=en();Ar&&co.current?.resolveAskUserQuestion(Ar,qn)},dismiss:()=>{let qn=en();qn?.agentMetadata?.awaitingLocalTool&&(co.current?.markAskUserQuestionResolved(qn),co.current?.resolveAskUserQuestion(qn,"(dismissed)"))},config:o})}let wt=an!=null;if(yo&&fn===null&&!wt){O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(ie.add(O.toolCall.id),mu(O));return}let Oe=br(O.id,O.role);Oe.setAttribute("data-ask-plugin-stub","true"),Oe.setAttribute("data-preserve-runtime","true"),w.appendChild(Oe),Te.push({messageId:O.id,fingerprint:gn,bubble:fn});return}else{O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(ie.add(O.toolCall.id),mu(O));return}}else if(De){let Ne=B();if(!Ne){w.appendChild(br(O.id,O.role));return}let an=d.find(Oe=>typeof Oe.renderApproval=="function")??C,fn=jr.get(O.id)!==gn,wt=null;if(fn&&an?.renderApproval){let Oe=O.id,Ke=(Fe,rs)=>{let en=co.current?.getMessages().find(qn=>qn.id===Oe);en?.approval&&(en.approval.toolType==="webmcp"?co.current?.resolveWebMcpApproval(en.id,Fe):co.current?.resolveApproval(en.approval,Fe,rs))};wt=an.renderApproval({message:O,defaultRenderer:()=>Ne.createApprovalBubble(O,o,l),config:o,approve:Fe=>Ke("approved",Fe),deny:Fe=>Ke("denied",Fe)})}if(fn&&wt===null)a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),jr.delete(O.id),zt=Ne.createApprovalBubble(O,o,l);else{let Oe=br(O.id,O.role);Oe.setAttribute("data-approval-plugin-stub","true"),Oe.setAttribute("data-preserve-runtime","true"),w.appendChild(Oe),jn.push({messageId:O.id,fingerprint:gn,bubble:wt});return}}else if(sn)if(O.variant==="reasoning"&&O.reasoning&&sn.renderReasoning){if(!Z)return;zt=sn.renderReasoning({message:O,defaultRenderer:()=>Sm(O,o,s),config:o})}else if(O.variant==="tool"&&O.toolCall&&sn.renderToolCall){if(!ye)return;zt=sn.renderToolCall({message:O,defaultRenderer:()=>Mm(O,o,r),config:o})}else sn.renderMessage&&(zt=sn.renderMessage({message:O,defaultRenderer:()=>{let Ne=ql(O,m,Ie,o.messageActions,Gn,{loadingIndicatorRenderer:z,widgetConfig:o,actionEligibility:Xt});return O.role!=="user"&&j(Ne,O,o,R),Ne},config:o}));if(!zt&&oe){let Ne=Fm(O);if(Ne){let an=Os.get(O.id),yo=an!==gn,fn=o.wrapComponentDirectiveInBubble!==!1&&tr.getOptions(Ne.component)?.bubbleChrome!==!1,wt=null;if(yo){let Oe=Nm(Ne,{config:o,message:O,transform:m});if(Oe&&Ne.component==="PersonaArtifactInline"){let Ke=Oe.hasAttribute("data-artifact-inline")?Oe:Oe.querySelector("[data-artifact-inline]"),Fe=Ke?.getAttribute("data-artifact-inline")??"",rs=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Fe):Fe,en=Fe?a.querySelector(`#wrapper-${O.id}`)?.querySelector(`[data-artifact-inline="${rs}"]`)??null:null;Ke&&en&&en!==Ke&&Wr()?.hasLiveInlineArtifactBlock(en)&&(Ke===Oe?Oe=en:Ke.replaceWith(en))}if(Oe)if(fn){let Ke=document.createElement("div");if(Ke.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ke.id=`bubble-${O.id}`,Ke.setAttribute("data-message-id",O.id),O.content&&O.content.trim()){let Fe=document.createElement("div");Fe.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Fe.innerHTML=m({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),Ke.appendChild(Fe)}Ke.appendChild(Oe),wt=Ke}else{let Ke=document.createElement("div");if(Ke.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ke.id=`bubble-${O.id}`,Ke.setAttribute("data-message-id",O.id),Ke.setAttribute("data-persona-component-directive","true"),O.content&&O.content.trim()){let Fe=document.createElement("div");Fe.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Fe.innerHTML=m({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),Ke.appendChild(Fe)}Ke.appendChild(Oe),wt=Ke}}if(wt||an!=null){let Oe=br(O.id,O.role);Oe.setAttribute("data-component-directive-stub","true"),Oe.setAttribute("data-preserve-runtime","true"),w.appendChild(Oe),rt.push({messageId:O.id,fingerprint:gn,bubble:wt});return}}}if(!zt)if(O.variant==="reasoning"&&O.reasoning){if(!Z)return;zt=Sm(O,o,s)}else if(O.variant==="tool"&&O.toolCall){if(!ye)return;zt=Mm(O,o,r)}else if(O.variant==="approval"&&O.approval){if(o.approval===!1)return;let Ne=B();if(!Ne)return;zt=Ne.createApprovalBubble(O,o,l)}else{let Ne=o.layout?.messages;Ne?.renderUserMessage&&O.role==="user"?zt=Ne.renderUserMessage({message:O,config:o,streaming:!!O.streaming}):Ne?.renderAssistantMessage&&O.role==="assistant"?zt=Ne.renderAssistantMessage({message:O,config:o,streaming:!!O.streaming}):zt=ql(O,m,Ne,o.messageActions,Gn,{loadingIndicatorRenderer:z,widgetConfig:o,actionEligibility:Xt}),O.role!=="user"&&zt&&j(zt,O,o,R)}let Mt=br(O.id,O.role);Mt.appendChild(zt),Xw(xn,O.id,gn,Mt),w.appendChild(Mt)}),Je.composerOverlay&&Je.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let De=Be.getAttribute("data-persona-ask-sheet-for");De&&!ie.has(De)&&cs(Je.composerOverlay,De)}),o.features?.toolCallDisplay?.grouped){let O=[],Be=[],De=o.features.toolCallDisplay.groupedMode==="summary";u.forEach(oe=>{if(oe.variant==="tool"&&oe.toolCall&&ye){if(mo&&oe.toolCall.status==="complete")return;Be.push(oe);return}oe.variant==="reasoning"&&(!Z||oe.reasoning?.status==="complete"&&zo(oe.reasoning))||((Be.length>1||De&&Be.length>0)&&O.push(Be),Be=[])}),(Be.length>1||De&&Be.length>0)&&O.push(Be),O.forEach(oe=>{let Ct=oe.map(Ie=>Array.from(w.children).find(Mt=>Mt instanceof HTMLElement&&Mt.getAttribute("data-wrapper-id")===Ie.id)).filter(Ie=>!!Ie);if(Ct.length<(De?1:2))return;let Xt=br(`tool-group-${oe[0].id}`,"assistant");if(Xt.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let Ie=`tool-group-${oe[0].id}`,Mt=oe.some(wt=>wt.toolCall?.status!=="complete"),Ne={...oe[0],id:Ie,toolCall:{id:Ie,name:`${oe.length} tools`,status:Mt?"running":"complete",chunks:oe.flatMap(wt=>wt.toolCall?.chunks??[]),success:!oe.some(wt=>wt.toolCall?.success===!1)}};v.add(Ie),i.observe(Ne,"tool",r,o.features.toolCallDisplay);let an=`${Mt?"Using":"Used"} ${oe.length} tools`,yo=o.toolCall?.renderGroupedSummary?.({messages:oe,toolCalls:oe.map(wt=>wt.toolCall),defaultSummary:an,config:o}),fn=CC(Ne,o,r.has(Ie),yo??an);fn.bubble.classList.add("persona-tool-group"),fn.body.dataset.personaToolGroupStack="true",Ct[0].before(Xt),Xt.appendChild(fn.bubble),Ct.forEach((wt,Oe)=>{wt.style.setProperty("--persona-message-row-max-width","100%"),wt.style.setProperty("--persona-activity-stagger",`${Oe*40}ms`),wt.classList.add("persona-activity-group-child"),fn.body.appendChild(wt)});return}let Pn=document.createElement("div");Pn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Pn.setAttribute("data-persona-tool-group","true");let gn=document.createElement("div");gn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",gn.id=`tool-group-summary-${oe[0].id}`;let Et=`Called ${oe.length} ${oe.length===1?"tool":"tools"}`,zt=o.toolCall?.renderGroupedSummary?.({messages:oe,toolCalls:oe.map(Ie=>Ie.toolCall).filter(Ie=>!!Ie),defaultSummary:Et,config:o});ne(gn,zt)||(gn.textContent=Et);let sn=document.createElement("div");sn.className="persona-tool-group-stack persona-flex persona-flex-col",sn.id=`tool-group-stack-${oe[0].id}`,sn.setAttribute("data-persona-tool-group-stack","true"),Pn.appendChild(gn),De||Pn.appendChild(sn),Xt.appendChild(Pn),Ct[0].before(Xt),Ct.forEach((Ie,Mt)=>{if(De){Ie.remove();return}Ie.style.setProperty("--persona-message-row-max-width","100%");let Ne=document.createElement("div");Ne.className="persona-tool-group-item persona-relative",Ne.setAttribute("data-persona-tool-group-item","true"),Mt<Ct.length-1&&Ne.setAttribute("data-persona-tool-group-connector","true"),Ne.appendChild(Ie),sn.appendChild(Ne)})})}i.prune(v),Qw(xn,G);let ns=O=>O.variant==="tool"&&!ye||O.variant==="reasoning"&&!Z||ho(O),Ko=u.some(O=>O.role==="assistant"&&O.streaming&&!ns(O)),To=u.length-1;for(;To>=0&&ns(u[To]);)To--;let os=To>=0?u[To]:void 0,sl=To<u.length-1,Gs=os?.role==="assistant"&&!os.streaming&&os.variant!=="approval"&&!sl;if(Yn&&u.some(O=>O.role==="user")&&!Ko&&!Gs){let O={config:o,streaming:!0,location:"standalone",defaultRenderer:Aa},Be=d.find(oe=>oe.renderLoadingIndicator),De=null;if(Be?.renderLoadingIndicator&&(De=Be.renderLoadingIndicator(O)),De===null&&o.loadingIndicator?.render&&(De=o.loadingIndicator.render(O)),De===null&&(De=Aa()),De){let oe=document.createElement("div"),Ct=o.loadingIndicator?.showBubble!==!1,Xt=o.layout?.messages?.layout??"bubble";oe.className=Ct?jl("assistant",Xt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),oe.setAttribute("data-typing-indicator","true"),Ct&&(oe.style.color="var(--persona-message-assistant-text, var(--persona-text))",Xt!=="flat"&&(oe.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",oe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),oe.appendChild(De);let Pn=br("typing-indicator","assistant");Pn.appendChild(oe),w.appendChild(Pn)}}if(!Yn&&u.length>0){let O=u[u.length-1],Be={config:o,lastMessage:O,messageCount:u.length},De=d.find(Ct=>Ct.renderIdleIndicator),oe=null;if(De?.renderIdleIndicator&&(oe=De.renderIdleIndicator(Be)),oe===null&&o.loadingIndicator?.renderIdle&&(oe=o.loadingIndicator.renderIdle(Be)),oe){let Ct=document.createElement("div"),Xt=o.loadingIndicator?.showBubble!==!1;Ct.className=Xt?["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(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ct.setAttribute("data-idle-indicator","true"),Ct.appendChild(oe);let Pn=br("idle-indicator","assistant");Pn.appendChild(Ct),w.appendChild(Pn)}}if(OC(w),hp(a,w),Mf(a),vt){let{messageId:O,element:Be}=vt,De=a.querySelector(`#wrapper-${O}`);De&&Be.parentElement!==De&&(qa(De,re.get(O)??"user"),De.replaceChildren(Be))}if(Te.length>0)for(let{messageId:O,fingerprint:Be,bubble:De}of Te){let oe=a.querySelector(`#wrapper-${O}`);oe&&(qa(oe,re.get(O)??"assistant"),De!==null&&(oe.replaceChildren(De),oe.setAttribute("data-bubble-fp",Be),Pi.set(O,Be)))}if(Pi.size>0)for(let O of Pi.keys())G.has(O)||Pi.delete(O);if(rt.length>0)for(let{messageId:O,fingerprint:Be,bubble:De}of rt){let oe=a.querySelector(`#wrapper-${O}`);oe&&(qa(oe,re.get(O)??"assistant"),De!==null&&(oe.replaceChildren(De),oe.setAttribute("data-bubble-fp",Be),Os.set(O,Be)))}if(Os.size>0)for(let O of Os.keys())G.has(O)||Os.delete(O);if(jn.length>0)for(let{messageId:O,fingerprint:Be,bubble:De}of jn){let oe=a.querySelector(`#wrapper-${O}`);oe&&(qa(oe,re.get(O)??"assistant"),De!==null&&(oe.replaceChildren(De),oe.setAttribute("data-bubble-fp",Be),jr.set(O,Be)))}if(jr.size>0)for(let O of jr.keys())G.has(O)||jr.delete(O)},Ru=!1,kc=()=>{Ru||(Ru=!0,oi().catch(()=>{}),bg().catch(()=>{Ru=!1}))},po=(a,u,m)=>{u.length>0&&kc(),Vx(a,u,m),Ah()},za=null,jx=()=>{if(za)return;let a=m=>{let v=m.composedPath();v.includes(Xe)||Gt&&v.includes(Gt)||xt(!1,"user")};za=a,(e.ownerDocument??document).addEventListener("pointerdown",a,!0)},ly=()=>{if(!za)return;(e.ownerDocument??document).removeEventListener("pointerdown",za,!0),za=null};Ce.push(()=>ly());let Ka=null,qx=()=>{if(Ka)return;let a=m=>{m.key==="Escape"&&(m.isComposing||xt(!1,"user"))};Ka=a,(e.ownerDocument??document).addEventListener("keydown",a,!0)},cy=()=>{if(!Ka)return;(e.ownerDocument??document).removeEventListener("keydown",Ka,!0),Ka=null};Ce.push(()=>cy());let Ga=!1,dy=new Set,zx=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},Bi=()=>{if(!ke())return;let a=Je.peekBanner,u=Je.peekTextNode;if(!a||!u)return;if(D){a.classList.remove("persona-pill-peek--visible");return}let m=R?.getMessages()??[],v;for(let _t=m.length-1;_t>=0;_t--){let Ut=m[_t];if(Ut.role==="assistant"&&Ut.content){v=Ut;break}}if(!v){a.classList.remove("persona-pill-peek--visible");return}let w=v.content,P=!!v.streaming,z=zx(),ne=yp(z),G=ne.type!=="none"?Cu(ne.type,z?.plugins):null,re=G?.isAnimating?.(v)===!0,ie=G!==null&&(P||re);ie&&G&&!dy.has(G.name)&&(Nl(G,e),dy.add(G.name));let le=ie&&G?.containerClass?G.containerClass:null,Te=u.dataset.personaPeekStreamClass??null;Te&&Te!==le&&(u.classList.remove(Te),delete u.dataset.personaPeekStreamClass),le&&Te!==le&&(u.classList.add(le),u.dataset.personaPeekStreamClass=le),ie?(u.style.setProperty("--persona-stream-step",`${ne.speed}ms`),u.style.setProperty("--persona-stream-duration",`${ne.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let rt=ie?vp(w,ne.buffer,G,v,P):w;if(ie&&ne.placeholder==="skeleton"&&P&&(!rt||!rt.trim())){let _t=document.createElement("div"),Ut=Dl();Ut.classList.add("persona-pill-peek__skeleton"),_t.appendChild(Ut),hp(u,_t)}else{let _t=Math.max(0,rt.length-100),Ut=rt.length>100?rt.slice(-100):rt,Wn=ms(Ut);if(!ie||!G){let qt=rt.length>100?`\u2026${Ut}`:Ut;u.textContent!==qt&&(u.textContent=qt)}else{let qt=Wn;(G.wrap==="char"||G.wrap==="word")&&(qt=Bl(Wn,G.wrap,`peek-${v.id}`,{skipTags:G.skipTags,startIndex:_t}));let vt=document.createElement("div");if(vt.innerHTML=qt,G.useCaret&&Ut.length>0){let qo=Cp(),zo=vt.querySelectorAll(".persona-stream-char, .persona-stream-word"),mo=zo[zo.length-1];mo?.parentNode?mo.parentNode.insertBefore(qo,mo.nextSibling):vt.appendChild(qo)}hp(u,vt),G.onAfterRender?.({container:u,bubble:a,messageId:v.id,message:v,speed:ne.speed,duration:ne.duration})}}let jn=Yn||Ga;a.classList.toggle("persona-pill-peek--visible",jn)};if(ke()){let a=Je.peekBanner;if(a){let v=w=>{w.preventDefault(),w.stopPropagation(),xt(!0,"user")};a.addEventListener("pointerdown",v),Ce.push(()=>{a.removeEventListener("pointerdown",v)})}let u=()=>{Ga||(Ga=!0,Bi())},m=()=>{Ga&&(Ga=!1,Bi())};we.addEventListener("pointerenter",u),we.addEventListener("pointerleave",m),Ce.push(()=>{we.removeEventListener("pointerenter",u),we.removeEventListener("pointerleave",m)}),Gt&&(Gt.addEventListener("pointerenter",u),Gt.addEventListener("pointerleave",m),Ce.push(()=>{Gt.removeEventListener("pointerenter",u),Gt.removeEventListener("pointerleave",m)}))}let Kx=a=>{let u=o.launcher?.composerBar??{},m=u.expandedSize??"anchored",v=u.bottomOffset??"16px",w=u.collapsedMaxWidth,P=u.expandedMaxWidth??"880px",z=u.expandedTopOffset??"5vh",ne=u.modalMaxWidth??"880px",G=u.modalMaxHeight??"min(90vh, 800px)",re="calc(100vw - 32px)",ie="var(--persona-pill-area-height, 80px)",le=Xe.style;if(le.left="",le.right="",le.top="",le.bottom="",le.transform="",le.width="",le.maxWidth="",le.height="",le.maxHeight="",Gt){let Te=Gt.style;Te.bottom=v,Te.width=w??""}if(a&&m!=="fullscreen"){if(m==="modal"){le.top="50%",le.left="50%",le.transform="translate(-50%, -50%)",le.bottom="auto",le.right="auto",le.width=ne,le.maxWidth=re,le.maxHeight=G,le.height=G;return}le.left="50%",le.transform="translateX(-50%)",le.bottom=`calc(${v} + ${ie})`,le.top=z,le.width=P,le.maxWidth=re}},Ya=()=>{if(D&&kc(),!Ge())return;if(ke()){let re=(o.launcher?.composerBar??{}).expandedSize??"anchored",ie=D?"expanded":"collapsed";Xe.dataset.state=ie,Xe.dataset.expandedSize=re,Gt&&(Gt.dataset.state=ie,Gt.dataset.expandedSize=re),Xe.style.removeProperty("display"),Xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Kx(D),ve.style.display=D?"flex":"none",Ps(),D?(jx(),qx()):(ly(),cy()),Bi();return}let a=Ht(o),u=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,v=o.launcher?.mobileFullscreen??!0,w=u.innerWidth<=m,P=v&&w&&me,z=no(o).reveal;D?(Xe.style.removeProperty("display"),Xe.style.display=a?"flex":"",Xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0"),we.classList.add("persona-scale-100","persona-opacity-100"),Vt?(Vt.setPanelOpen(!0),Vt.element.style.display="none"):Rn&&(Rn.style.display="none")):(a?a&&(z==="overlay"||z==="push")&&!P?(Xe.style.removeProperty("display"),Xe.style.display="flex",Xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Xe.style.setProperty("display","none","important"),Xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Xe.style.display="",Xe.classList.add("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100"),we.classList.add("persona-scale-95","persona-opacity-0")),Vt?(Vt.setPanelOpen(!1),Vt.element.style.display=a?"none":""):Rn&&(Rn.style.display=a?"none":""))},xt=(a,u="user")=>{if(!Ge()||D===a)return;let m=D;D=a,Ya();let v=(()=>{let P=o.launcher?.sidebarMode??!1,z=e.ownerDocument.defaultView??window,ne=o.launcher?.mobileFullscreen??!0,G=o.launcher?.mobileBreakpoint??640,re=z.innerWidth<=G,ie=Ht(o)&&ne&&re,le=ke()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return P||ne&&re&&me||ie||le})();if(D&&v){if(!No){let P=e.getRootNode(),z=P instanceof ShadowRoot?P.host:e.closest(".persona-host");z&&(No=tm(z,o.launcher?.zIndex??Tn))}Fo||(Fo=nm(e.ownerDocument))}else D||(No?.(),No=null,Fo?.(),Fo=null);D&&(nl(),Hu()||(An()==="follow"?Yr(!0):Lu()));let w={open:D,source:u,timestamp:Date.now()};D&&!m?Y.emit("widget:opened",w):!D&&m&&Y.emit("widget:closed",w),Y.emit("widget:state",{open:D,launcherEnabled:me,voiceActive:ze.active,streaming:R.isStreaming()})},Xr={inputDisabled:!1,sendDisabled:!1},Uo=()=>Xr.inputDisabled,Wu=()=>Ln(o.voiceRecognition?.provider)&&!!R&&(R.isBargeInActive()||["listening","processing","speaking"].includes(R.getVoiceStatus())),js=()=>Xr.inputDisabled||Xr.sendDisabled,Gx=()=>(Xr.inputDisabled?Xr.inputReason:void 0)??(Xr.sendDisabled?Xr.sendReason:void 0);function Ou(){if(!Me)return;if(he.getState().phase==="streaming"){Me.disabled=!1;return}let a=Ue?!Ue.isReady():!1;Me.disabled=js()||a}function Pc(){if(!In)return;let a=he.getState(),u=o.sendButton?.visibility==="when-text"&&a.phase!=="streaming"&&a.text.trim().length===0&&a.attachments.length===0;In.toggleAttribute("data-persona-send-hidden",u)}function Yx(){let a=Gx();if(ke()){let u=wn??qe;a?u.setAttribute("title",a):u.removeAttribute("title"),qe.toggleAttribute(Ha,!!a);return}if(a){Ze.setAttribute("role","status"),Ze.setAttribute("aria-live","polite"),Ze.setAttribute(Ha,""),Ze.removeAttribute(Yl),Ze.textContent=a,ri(Ze,o.statusIndicator??{},"idle");return}if(Ze.hasAttribute(Ha)&&(Ze.removeAttribute("role"),Ze.removeAttribute("aria-live"),Ze.removeAttribute(Ha),h)){let u=R.getStatus();As(Ze,ar(u),o.statusIndicator??{},u)}}function _u(){let a=sf(o.composer?.inputDisabled),u=sf(o.composer?.sendDisabled);Xr={inputDisabled:a.disabled,inputReason:a.reason,sendDisabled:u.disabled,sendReason:u.reason},he.setInputDisabled(a.disabled),he.setSendDisabled(u.disabled);let m=he.getState().phase==="streaming",v=a.disabled,w=m||v;ae&&(ae instanceof HTMLTextAreaElement?ae.disabled=v:ae.setAttribute("contenteditable",v?"false":"true"),ae.setAttribute("aria-disabled",v?"true":"false")),Pt&&(Pt.disabled=v),At&&(At.disabled=v);for(let P of st?.affordanceButtons??[])P.querySelectorAll("button").forEach(z=>{z.disabled=v});fe&&(fe.disabled=v||m&&!Wu()),Hs.forEach(P=>{P.elements.forEach(z=>{z.toggleAttribute("data-disabled",w),z instanceof HTMLButtonElement||z.setAttribute("aria-disabled",w?"true":"false")}),P.buttons.forEach(z=>{z.disabled=w})}),Uu.forEach(P=>{P.toggleAttribute("data-disabled",w),P instanceof HTMLButtonElement?P.disabled=w:P.setAttribute("aria-disabled",w?"true":"false"),P.querySelectorAll("button").forEach(z=>{z.disabled=w})}),qe.dataset.personaComposerStreaming=m?"true":"false",qe.dataset.personaComposerInputDisabled=v?"true":"false",qe.dataset.personaComposerSendDisabled=js()?"true":"false",qe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(P=>{(P instanceof HTMLButtonElement||P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement||P instanceof HTMLSelectElement)&&(P.disabled=m)}),Ou(),Yx()}let Xa=a=>{he.setStreaming(a),nc(a?"stop":"send"),_u()},Lc=()=>{ze.active||ae&&ae.focus()};Y.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Lc(),200)});let py=null,Bu=!1,Du=!Jt.hidden,Qr=null,Nu=!Q,Hc=null;Ce.push(()=>{Hc?.cancel(),Hc=null});let Xx=a=>{let u=HS(a);if(u===N)return;N=u,e.setAttribute("data-persona-conversation-state",u);let m=ce();Rt(),Nu&&(Hc?.cancel(),Hc=PS(qe,u==="active"?m:ce(),u==="active"?"drop":"rise",E().layout==="centered"?320:260)),_i()},uy=null,gy,fy=null,Di=null,Fu=!1,Qa=a=>{let u=E(),m=`${u.variant}|${u.layout}|${u.dismiss}|${u.anchor??"bottom"}|${u.align??""}|${u.iconPlacement}|${u.kicker??""}|${u.title}|${u.subtitle}`;(m!==uy||u.icon!==gy)&&(uy=m,gy=u.icon,Mp({host:Jt,iconHolder:ec,kicker:tc,title:eu,subtitle:vi,starterSuggestions:lr},u));let v=u.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${u.message}`;v!==fy&&(fy=v,Tp(Hn,u.message,o));let w=a??(R?R.getMessages():o.initialMessages);Xx(w);let P=Bu,z=!P&&pi(u,w),ne=z!==Du;if(Du=z,Di){Qr?.cancel(),Qr=null,P!==Fu&&(Fu=P,P?fm(se,Jt,null):gm(se,Jt,Di)),xa(se,Jt,!P);return}if(ne&&!z&&!P&&u.dismiss==="on-first-message"&&Nu){Qr=kS(Jt,re=>{Qr===re&&(Qr=null),!Du&&!Di&&(xa(se,Jt,!1),_i()),re?.cancel()});return}if(Qr){if(!z&&!P)return;Qr.cancel(),Qr=null}let G=!Jt.hidden;xa(se,Jt,z),!z&&G&&_i()},$u=[],Uu=[],Vu=!1,my=null,hy,yy=()=>{Uu.length=0;let a=$u.splice(0,$u.length);for(let u of a)try{u()}catch(m){console.warn("[persona] renderWelcome cleanup threw",m)}};Ce.push(yy);let Qx=(a,u)=>{let m=rm(a,u);if(!m)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),x("span");let v=o.suggestions?.starters,w=sm({item:{...m,behavior:m.behavior??v?.behavior??"send"},index:u,surface:"starter",source:"config",variant:v?.variant??"card",streaming:h?R.isStreaming():!1,config:o,plugins:d,chipsConfig:o.suggestionChipsConfig,session:R,getTextarea:()=>ae,eventTarget:Jt,submitPrompt:Fc});return Uu.push(w),w},ju=()=>{if(Vu)return;Vu=!0;let a=E();my=`${a.variant}|${a.layout}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`,hy=a.icon;try{yy(),fm(se,Jt,Di),Di=null,Fu=!1;let u=R?R.getMessages():o.initialMessages,m=pi(a,u),v=0,w=null;for(let P of d)if(P.renderWelcome&&(w=P.renderWelcome({config:a,variant:a.variant,visible:m,defaultRenderer:()=>Jt,sendMessage:z=>{if(!R||R.isStreaming())return;let ne=z.trim();ne&&R.sendMessage(ne)},requestRender:()=>ju(),renderStarter:z=>Qx(z,v++),storage:y(P.id),onCleanup:z=>{$u.push(z)}}),w))break;w&&w!==Jt&&(Di=w,gm(se,Jt,w))}finally{Vu=!1}Qa()},Jx=()=>{let a=E();`${a.variant}|${a.layout}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`===my&&a.icon===hy||ju()},Ic=()=>{Qa(),Ti||(ae.placeholder=Sw(he.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!R?.isStreaming()&&(Me.textContent=o.copy?.sendButtonLabel??"Send")),ae.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ae.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},Zx=!!o.setStoredConversationId,Ni=a=>Ve(u=>{let m={...u};return delete m[a],m}),Rc=a=>{let u=k[a];return typeof u=="string"?u:null},by=()=>{let a=k.durableResume;if(!a||typeof a!="object")return null;let u=a;return typeof u.executionId=="string"&&u.executionId.length>0&&typeof u.after=="string"&&u.after.length>0?{executionId:u.executionId,after:u.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Rc("sessionId"),setStoredSessionId:a=>{Ve(u=>({...u,sessionId:a}))},clearStoredSessionId:o.clearStoredSessionId??(()=>Ni("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Rc("conversationId")),setStoredConversationId:o.setStoredConversationId??(a=>{Ve(u=>({...u,conversationId:a}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>Ni("conversationId"))});let vy=()=>o.clientToken??null,Cy=a=>gA(a,bt(),o.persistState===!1),wy=vy(),uo=wy?Cy(wy):null,eE=()=>{let a=k.pendingDisplayProjections;if(!a||typeof a!="object")return null;let u=a;return typeof u.conversationId!="string"||!Array.isArray(u.messageIds)?null:{conversationId:u.conversationId,messageIds:u.messageIds.filter(m=>typeof m=="string")}},Jr={...uo?{visitorStore:uo}:{},historyBootstrapReady:o.features?.history?.enabled===!0&&!jd()?Promise.all([de,ge]).then(()=>{}):de,getStoredMessageCursor:()=>Rc("historyMessageCursor"),setStoredMessageCursor:a=>{if(a===null){Ni("historyMessageCursor");return}Ve(u=>({...u,historyMessageCursor:a}))},getPendingDisplayProjections:eE,setPendingDisplayProjections:a=>{if(!a){Ni("pendingDisplayProjections");return}Ve(u=>({...u,pendingDisplayProjections:a}))},getStoredResumableHandle:by,setStoredResumableHandle:a=>{if(!a){Ni("durableResume");return}Ve(u=>({...u,durableResume:a}))},shouldResumeDurableConversation:()=>_&&by()!==null,...Zx?{}:{getStoredConversationRevision:()=>Rc("conversationRevision"),setStoredConversationRevision:a=>{if(a===null){Ni("conversationRevision");return}Ve(u=>({...u,conversationRevision:a}))}}};if(_){let a=o.onExecutionState,u=e.ownerDocument.defaultView,m=!1,v=()=>m=!0,w=()=>m=!1;u?.addEventListener("pagehide",v),u?.addEventListener("pageshow",w),Ce.push(()=>{u?.removeEventListener("pagehide",v),u?.removeEventListener("pageshow",w)}),o={...o,reconnectStream:o.reconnectStream??(P=>R.getClient().reconnectClientTokenStream(P)),onExecutionState:P=>{(P||!m)&&Jr.setStoredResumableHandle?.(P?{executionId:P.executionId,after:P.lastEventId}:null),a?.(P)}}}let tE=()=>{let a=vy();if(a&&uo?.matches(a,bt(),o.persistState===!1)||!a&&!uo)return;uo?.destroy(),uo=a?Cy(a):null;let u={...Jr};uo?u.visitorStore=uo:delete u.visitorStore,Jr=u,R.setHistoryInternals(Jr)},qs=null,nE=()=>{qs==null&&(qs=setInterval(()=>{let a=Ee.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(qs),qs=null;return}let u=Date.now();a.forEach(m=>{let v=Number(m.getAttribute("data-tool-elapsed"));v&&(m.textContent=m.closest(".persona-activity-row")?xl(u-v):nd(u-v))})},100))},qu=(a,u)=>{if(Object.is(a,u))return!0;if(a===null||u===null||typeof a!="object"||typeof u!="object")return!1;if(Array.isArray(a)||Array.isArray(u))return!Array.isArray(a)||!Array.isArray(u)||a.length!==u.length?!1:a.every((z,ne)=>qu(z,u[ne]));let m=a,v=u,w=Object.keys(m),P=Object.keys(v);return w.length===P.length&&w.every(z=>Object.prototype.hasOwnProperty.call(v,z)&&qu(m[z],v[z]))},Sy=a=>{let{content:u,rawContent:m,llmContent:v,...w}=a;return w},zu=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!Bp(a),oE=(a,u,m)=>{if(a.length!==u.length)return!1;let v=a[m.index],w=u[m.index];return!v||!w||v.id!==m.id||w.id!==m.id?!1:(!Object.is(v.content,w.content)||!Object.is(v.rawContent,w.rawContent)||!Object.is(v.llmContent,w.llmContent))&&zu(v)&&zu(w)&&qu(Sy(v),Sy(w))},Wc=null,Fi=null,zs=null,vr=null,Ku=null,rE=a=>{if(!_)return Ii(a);Ku=a,queueMicrotask(()=>{Ku===a&&(Ku=null,Ii(a))})},Oc=a=>{Wc=a;let u,m;Fi=null;for(let w=a.length-1;w>=0;w-=1){let P=a[w];if(!u&&P.role==="user"&&(u=P),!m&&P.role==="assistant"&&(m=P),!Fi&&zu(P)&&(Fi={index:w,id:P.id}),u&&m&&Fi)break}po(Ee,a,K),Wr()?.updateInlineArtifactBlocks(Ee,lo.artifacts,{suppressTransition:Yn}),nE(),Qa(a),Ws(a),Yr(!Yn),Ux(a),a.length===0&&(Vs(),Va=!0,bc=!1,Hi=null,vc=!1),!wu||Li?(wu=!0,Fs=u?.id??null,Su=m?.id??null):u&&u.id!==Fs?(Fs=u.id,Bx(u.id)):m&&m.id!==Su&&Dx(),m&&(Su=m.id),$x(a);let v=ze.lastUserMessageId;u&&u.id!==v&&(ze.lastUserMessageId=u.id,Y.emit("user:message",u)),ze.lastUserMessageWasVoice=!!u?.viaVoice,rE(a),Bi()},Gu=()=>{vr!==null&&(cancelAnimationFrame(vr),vr=null);let a=zs;zs=null,a&&Oc(a)},Ay=()=>{vr!==null&&cancelAnimationFrame(vr),vr=null,zs=null},sE=a=>{let u=zs??Wc;if(Yn&&u&&Fi&&oE(u,a,Fi)){zs=a,vr===null&&(vr=requestAnimationFrame(()=>{vr=null;let m=zs;zs=null,m&&Oc(m)}));return}if(a.length===0){Ay(),Oc(a);return}Gu(),Oc(a)};R=new Pl(o,{onMessagesChanged(a){sE(a)},onStatusChanged(a){let u=o.statusIndicator??{};As(Ze,(v=>v==="idle"?u.idleText??Kt.idle:v==="connecting"?u.connectingText??Kt.connecting:v==="connected"?u.connectedText??Kt.connected:v==="error"?u.errorText??Kt.error:v==="paused"?u.pausedText??Kt.paused:v==="resuming"?u.resumingText??Kt.resuming:Kt[v])(a),u,a),Br()},onStreamingChanged(a){a||(R?.getMessages().length===0?Ay():Gu()),Yn=a,Xa(a),Br(),R&&po(Ee,R.getMessages(),K),a||(Yr(!0),Ox(),zh=!0,R&&Kh(R.getMessages(),ps(o))),En(),ks(a?"Responding\u2026":"Response complete."),Bi()},onVoiceStatusChanged(a){if(Y.emit("voice:status",{status:a,timestamp:Date.now()}),a!=="disconnected"&&!Ln(o.voiceRecognition?.provider))return;let u=R.getVoiceNotice();switch(u&&Nc(u,1e4),a){case"listening":if(!xu){let m=R.getVoiceDisclosure();m&&(xu=!0,ke()?(Cc=ae.placeholder,ae.placeholder=m,ks(m)):Nc(m,1e4))}Sr(),ji();break;case"processing":Sr(),kE();break;case"speaking":Sr(),PE();break;default:a==="idle"&&R.isBargeInActive()?(Sr(),ji(),fe?.setAttribute("aria-label","End voice session")):(ze.active=!1,xu=!1,Cc!==null&&(ae.placeholder=Cc,Cc=null),Sr(),yr("system"),Qh||Vn());break}},onArtifactsState(a){lo=a,a.artifacts.length===0&&(ki=!1),Wr()?.updateInlineArtifactBlocks(Ee,a.artifacts,{suppressTransition:Yn}),Mo(),Ii()},onHistoryStateChanged(a){ir(a)},onHistoryNotice(a){Oo(a)},onReconnect(a){let{executionId:u,lastEventId:m}=a.handle;a.phase==="paused"?Y.emit("stream:paused",{executionId:u,after:m}):a.phase==="resuming"?Y.emit("stream:resuming",{executionId:u,after:m,attempt:a.attempt??1}):Y.emit("stream:resumed",{executionId:u,after:m})}},Jr),co.current=R,Ce.push(()=>R.cancel()),Ce.push(()=>{R.destroy(),uo?.destroy(),uo=null});let Yu=null;if(R.onReadAloudChange((a,u)=>{wh=a,Sh=u,Ah();let m=a??Yu;a&&(Yu=a);let v=m?R.getMessages().find(w=>w.id===m)??null:null;Y.emit("message:read-aloud",{messageId:m,message:v,state:u,timestamp:Date.now()}),u==="idle"&&(Yu=null)}),h=!0,wu=!0,o.voiceRecognition?.enabled===!0&&Ln(o.voiceRecognition.provider))try{R.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}let Ot=null,Xu=null,xy=!1,Ey=R.getHistoryState(),Ja=()=>o.features?.history?.enabled===!0,My=a=>{a&&(So.textContent="",So.textContent=a)},Qu=()=>{f.forEach(m=>m()),f=[];let a=Ot,u=a?.railCollapseShortcut();a&&u&&f.push(g.register({id:"history-rail-collapse",combo:u.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>dn&&Nn==="rail"&&a.railCollapsible()||a.railTriggerApplies(),run:()=>a.railOverlayMode()?a.toggleRailPinned():a.toggleRailCollapsed()}));for(let m of o.layout?.header?.trailingActions??[])m.shortcut&&f.push(g.register({id:`header-action-${m.id}`,combo:m.shortcut,run:()=>{let v=e.querySelector(`[data-persona-header-action="${m.id}"]`);v?v.click():o.layout?.header?.onAction?.(m.id)}}));for(let m of d)for(let v of m.shortcuts??[])f.push(g.register({...v,id:`${m.id}:${v.id}`}))};Qu();let _c=null,Ty=!1,Za=()=>{if(!_o)return;let a=o.layout?.header?.titleSource==="conversation",u=a&&_c?.trim()||null;_o.textContent=u??o.launcher?.title??"Chat Assistant";let m=_o.closest(".persona-combo-btn");if(!m)return;let v=!a||R.getActiveConversationId()!==null;m.setAttribute("data-persona-menu-locked",v?"false":"true"),m.setAttribute("aria-haspopup",v?"true":"false"),v||m.setAttribute("aria-expanded","false"),m.style.cursor=v?"pointer":"default";let w=m.querySelector("svg");w&&(w.style.display=v?"":"none")},iE=a=>{a!==_c&&(_c=a,Za())},aE=a=>{Ty=a?.starred===!0,iE(a&&a.title.trim()||null),Za()};Za(),ve.addEventListener("persona:title-menu-builtin",a=>{let u=a.detail?.actionId,m=R.getActiveConversationId();m&&(u==="delete"?Vo(v=>v.requestDeleteConversation(m)):u==="star"&&R.canUpdateConversations()&&Vo(v=>v.updateHistoryConversation(m,{starred:!Ty})).catch(()=>{}))}),ir=a=>{Ey=a,Ot?.historySurface?.view.setNewConversationRequired(a.recovery==="new_conversation_required"),Xa(a.sendBlocked||Yn),Ot?.syncEarlierMessagesPill()},Oo=a=>{(a.code==="history_continuity_reset"||a.code==="conversation_deleted_recovered")&&(xn.clear(),Vs(),$o()),My(a.message),Ot?.historySurface?.view.refresh()};let lE={get actionManager(){return We},get activeConversationTitle(){return _c},announceHistory:My,get applyRailChrome(){return Fn},set applyRailChrome(a){Fn=a},get artifactSplitRoot(){return gr},get body(){return se},get config(){return o},get container(){return ve},get conversationOpenPendingEl(){return py},set conversationOpenPendingEl(a){py=a},get conversationOpenTakeover(){return Bu},set conversationOpenTakeover(a){Bu=a},currentKeyPrefix:bt,destroyCallbacks:Ce,eventBus:Y,get footer(){return qe},get header(){return gt},get historyChromeSync(){return Br},set historyChromeSync(a){Br=a},historyFeatureEnabled:Ja,get historyInternals(){return Jr},set historyInternals(a){Jr=a},get historyPresentation(){return Nn},set historyPresentation(a){Nn=a},get historySessionState(){return Ey},get historyVisible(){return dn},set historyVisible(a){dn=a},get isStreaming(){return Yn},jumpToBottomInstant:Lu,get lastAppliedMessages(){return Wc},set lastAppliedMessages(a){Wc=a},get launcherEnabled(){return me},get launcherSurfaceInstance(){return Vt},maybeFocusInput:Lc,messageCache:xn,get messagesWrapper(){return Ee},mount:e,get open(){return D},panel:we,panelElements:Je,get persistentMetadata(){return k},set persistentMetadata(a){k=a},plugins:d,get reapplyHistoryHostChrome(){return sr},set reapplyHistoryHostChrome(a){sr=a},repinAnchoredMessage:_i,resetAnchorState:Vs,restoreScrollPosition:Hu,resumeAutoScroll:$o,runStorageMutation:Sc,get session(){return R},setActiveConversationSummary:aE,storageAdapter:T,get suppressScrollSend(){return Li},set suppressScrollSend(a){Li=a},syncScrollToBottomButton:En,updateWelcome:Qa,getHistoryProviderFactory:mA,historyErrors:{HistoryClientError:tn,HistoryProviderError:hs},isDockedMountMode:Ht,renderLucideIcon:ue,loadHistoryView:fA,createHeaderIconButton:ya,attachTooltip:yn},Ju=a=>(!Ot&&!xy&&(Ot=a.createHistoryShell(lE),Ot.railCollapseShortcut()&&Qu()),Ot),Zu=()=>{if(Ot)return Promise.resolve(Ot);let a=jd();return a?Promise.resolve(Ju(a)):(Xu??=yC().then(Ju,u=>{throw Xu=null,u}),Xu)},Vo=a=>{let u=jd(),m=Ot??(u?Ju(u):null);return m?a(m):Zu().then(v=>{if(!v)throw new Error("[AgentWidget] The widget was destroyed");return a(v)})},Bc=()=>{Ot?.syncHistoryPresentation()};Ce.push(()=>{xy=!0}),Ja()&&Zu().catch(()=>{}).finally(pe),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&R.initClientSession().then(()=>{let a=Ot;if(a?.historyAvailable())return R.reconcileBootConversation({scope:a.historyScope()})}).then(()=>{Ot?.syncEarlierMessagesPill()}).catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)});let eg=()=>R.warmClientSession(),ky=a=>{let u=o.sessionInit??"input",m=at?.input??ae,v=a.target;m&&(a.type==="input"?(u==="input"||u==="focus")&&v===m&&a.inputType&&m.value.trim():u==="focus"&&(a.type==="keyup"?v===m&&a.key==="Tab":(at?.form??wn)?.contains(v)))&&eg()},Py=["input","pointerdown","keyup"];Py.forEach(a=>e.addEventListener(a,ky));let Ly,tg,Hy=()=>{let a=tg;tg=void 0;try{typeof a=="function"&&a()}catch{}},Iy=()=>{let a=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(a!==Ly){Hy(),Ly=a;try{tg=a?.({warm:eg,mount:e})}catch{}}};Iy(),Ce.push(()=>{Py.forEach(a=>e.removeEventListener(a,ky)),Hy()}),(xe||o.onSSEEvent)&&R.setSSEEventCallback((a,u)=>{o.onSSEEvent?.(a,u),Ia(a,u)});let Ry=()=>{let a=o.resume??(_?Jr.getStoredResumableHandle?.():null);a&&typeof o.reconnectStream=="function"&&R.resumeFromHandle(a)};Q?Q.then(a=>{if(a){if(a.metadata&&(k=Vm(a.metadata),We.syncFromMetadata()),a.messages?.length){Li=!0;try{R.hydrateMessages(a.messages)}finally{Li=!1}kc()}a.artifacts?.length&&R.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null),ty(a.draft)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>{Nu=!0,U(),Ry()}):(ty(Pe),Ry());let cE=()=>{!ke()||D||!(o.launcher?.composerBar?.expandOnSubmit??!0)||xt(!0,"auto")},dE=(a,u)=>a?u?{refs:[...a.refs,...u.refs],finalize:async()=>{let[m,v]=await Promise.allSettled([a.finalize(),u.finalize()]),w=[];return m.status==="fulfilled"?w.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),v.status==="fulfilled"?w.push(v.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",v.reason),dR(w)}}:a:u,ng=()=>{let u=ae.getInlineMessageFields?.();return u&&u.contentSegments.some(v=>v.kind==="mention")?u.contentSegments:void 0},Cr=!1,Ks=null,Dc=()=>{ae.value="",ae.style.height="auto",ao(),tl()},$i=null;function Nc(a,u=4e3){ks(a),!(ke()||!Ze)&&(Ze.hasAttribute(Ha)||(Ze.setAttribute(Yl,""),Ze.setAttribute("role","status"),Ze.setAttribute("aria-live","polite"),Ze.textContent=a,ri(Ze,o.statusIndicator??{},"idle"),$i&&clearTimeout($i),$i=setTimeout(()=>{if($i=null,!!Ze?.hasAttribute(Yl)&&(Ze.removeAttribute(Yl),Ze.removeAttribute("role"),Ze.removeAttribute("aria-live"),h)){let m=R.getStatus();As(Ze,ar(m),o.statusIndicator??{},m)}},u)))}function pE(){let a=he.getState().pendingSubmission;a&&(Ei(void 0),ae&&(ae.value=a.text,ae.dispatchEvent(new Event("input",{bubbles:!0})),ao()),a.options.selectedModelId&&(he.setSelectedModelId(a.options.selectedModelId),$r?.repaint()),a.options.activeModeIds?.length&&sc(a.options.activeModeIds),a.options.quote&&Do(a.options.quote),ae?.focus())}let uE=a=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",a)},Wy=(a={})=>{let u=(a.overrideText??ae?.value??"").trim();return a.resolveInlineCommand&&u?(st?.takeInlineCommand(u)??Promise.resolve(null)).then(m=>Oy(a,u,m)):Oy(a,u,null)},Oy=(a,u,m)=>{if(m?.kind==="action"){Dc(),st?.clear(),dr();return}let v=m?.kind==="server"?m.mentions:null,w=m?.kind==="prompt"?m.sendText:u,P=a.pending?.contentParts,z=(Ue?.hasAttachments()??!1)||(P?.length??0)>0;if(!Ow({text:w,hasAttachments:z,attachmentsReady:Ue?.isReady()??!0,hasMentions:st?.hasMentions()??!1,hasServerMentions:!!v,inputDisabled:Uo(),sendDisabled:js()}))return;let ne=R.isStreaming()?su():"block";if(ne==="defer-one"&&!a.pending){if(he.getState().pendingSubmission){Nc("One message is already queued. Edit or remove it first.");return}gE({intent:a,sendText:w,serverMentions:v});return}let G={text:w,mentionRefs:[...st?.getMentionRefs()??[],...v?.refs??[]],contentSegments:m?.kind==="prompt"?void 0:ng(),options:{...he.getState().selectedModelId&&{selectedModelId:he.getState().selectedModelId},...he.getState().activeModeIds.length>0&&{activeModeIds:[...he.getState().activeModeIds]},...he.getState().quote&&{quote:{...he.getState().quote}}},viaVoice:a.viaVoice};a.pending&&(G.options={...a.pending.options},G.contentSegments=a.pending.contentSegments,G.mentionRefs=[...a.pending.mentionRefs],G.viaVoice=a.pending.viaVoice);let re=()=>{if(P?.length)return[...P];if(!Ue?.hasAttachments())return;let lt=[...Ue.getContentParts()];return G.text&&lt.push(Io(G.text)),lt};G.contentParts=re();let ie=()=>{Bs(),cE();let lt=st?.collectForSubmit()??null,jn=dE(lt,v),_t=re();a.consumeDraft!==!1&&Dc();let Ut={selectedModelId:G.options.selectedModelId,activeModeIds:G.options.activeModeIds},Wn=ne==="interrupt";Wn&&R.cancel(),R.sendMessage(G.text,{contentParts:_t,mentions:jn??void 0,contentSegments:G.contentSegments,viaVoice:G.viaVoice,composerOptions:Ut,...G.options.quote&&{quote:G.options.quote},...Wn&&{interrupt:!0}}),Ue?.hasAttachments()&&Ue.clearAttachments(),lt&&st?.clear(),dr();let qt=he.getState().activeModeIds,vt=ww(qt,o.composer?.modes);vt.length!==qt.length&&sc(vt),he.getState().quote&&Do(void 0),xc(),pu.release(),xo()},le=o.composer?.onBeforeSend;if(!le){ie();return}let Te=new AbortController;Ks=Te;let rt=lt=>{if(Ks=null,lt.status==="error"){uE(lt.error);return}lt.status==="proceed"&&ie()},pt=_w(le,G,Te.signal);if(!(pt instanceof Promise)){rt(pt);return}return he.setPreparing(!0),pt.then(rt).finally(()=>he.setPreparing(!1))};function gE(a){let u=he.getState(),m=Ue?.hasAttachments()??!1,v=m?[...Ue.getContentParts()]:[];m&&a.sendText&&v.push(Io(a.sendText));let w=jf({text:a.sendText,contentParts:v.length?v:void 0,mentionRefs:[...st?.getMentionRefs()??[],...a.serverMentions?.refs??[]],contentSegments:ng(),options:{...u.selectedModelId&&{selectedModelId:u.selectedModelId},...u.activeModeIds.length>0&&{activeModeIds:[...u.activeModeIds]},...u.quote&&{quote:{...u.quote}}},viaVoice:a.intent.viaVoice});Ei(w),a.intent.consumeDraft!==!1&&Dc(),m&&Ue.clearAttachments(),st?.clear(),dr(),u.quote&&Do(void 0),xc(),pu.release(),xo(),ks("Message queued. It sends when the response finishes.")}function fE(){let a=he.getState().pendingSubmission;a&&(Ei(void 0),$c(a.text,{consumeDraft:!1,pending:a}))}function mE(a){if(o.messageActions?.showEdit!==!0)return;let u=R.getMessages().find(m=>m.id===a);!u||!Hf(u)||_s!==a&&(Bs(),_s=a,qr=Mw({messageId:a,initialText:u.content,onSave:m=>hE(a,m),onCancel:()=>Bs()}),xn.delete(a),po(Ee,R.getMessages(),K),qr.focus())}function hE(a,u){let m=qr;if(_s=null,qr=null,m?.destroy(),xn.delete(a),!R.resubmitFrom(a,{reason:"edit",replacement:{text:u,mentionRefs:[],options:{}}})){po(Ee,R.getMessages(),K);return}_i()}function yE(a){if(R.isStreaming())return;let u=Lf(R.getMessages(),a);u&&(Bs(),R.resubmitFrom(u,{reason:"retry"})&&_i())}ic={regenerate:yE,edit:mE,quote:a=>{let m=R.getMessages().find(v=>v.id===a)?.content?.trim();m&&(Do({text:m,messageId:a}),ae?.focus())}};let el=async a=>{if(!Cr){Cr=!0;try{await Wy({resolveInlineCommand:!0,...a})}finally{Cr=!1}}};function Fc(a){js()||(Dc(),$c(a,{consumeDraft:!1}))}let $c=(a,u)=>{if(Cr)return;Cr=!0;let m=()=>{Cr=!1};try{let v=Wy({...u,overrideText:a});v instanceof Promise?v.finally(m):m()}catch(v){throw m(),v}},bE=a=>{if(a.preventDefault(),R.isStreaming()){R.cancel(),ht?.reset(),nn?.update();return}Cr||el()},vE=()=>o.features?.composerHistory!==!1,og={...Qf},rg=!1,tl=()=>{og={...Qf}},CE=()=>R.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),wE=a=>{if(!ae)return;rg=!0,ae.value=a,ae.dispatchEvent(new Event("input",{bubbles:!0})),rg=!1;let u=ae.value.length;ae.setSelectionRange(u,u)},SE=a=>{rg||(a.isComposing||st?.handleInput(a.inputType??void 0),tl())},AE=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:vl(ae)}),xE=a=>{if(ae&&!Uo()&&!(!a.isComposing&&st?.handleKeydown(a))){if(vE()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let u=ae.selectionStart===0&&ae.selectionEnd===0,m=zw({direction:a.key==="ArrowUp"?"up":"down",history:CE(),currentValue:ae.value,atStart:u,state:og});if(og=m.state,m.handled){a.preventDefault(),m.value!==void 0&&wE(m.value);return}}if(Xv(a,AE())){if(R.isStreaming()){if(a.preventDefault(),su()==="block"||Cr||js())return;tl(),el();return}if(Cr){a.preventDefault();return}if(js()){a.preventDefault();return}tl(),a.preventDefault(),Me.click()}}},_y=a=>{if(!(a.key!=="Escape"||a.isComposing)&&a.composedPath().includes(ve)){if(Ks){Ks.abort(),Ks=null,a.preventDefault(),a.stopImmediatePropagation();return}R.isStreaming()&&(R.cancel(),ht?.reset(),nn?.update(),tl(),a.preventDefault(),a.stopImmediatePropagation())}},EE=async a=>{if(o.attachments?.enabled!==!0||!Ue||Uo())return;let u=iR(a.clipboardData);u.length!==0&&(a.preventDefault(),await Ue.handleFiles(u))},go=null,jo=!1,Ui=null,wr=null,sg=()=>o.voiceRecognition?.completionBehavior==="review";function Uc(a){fe?.setAttribute("data-state",a),a==="recording"?TE():cg()}let By="--persona-voice-level",ig=.5,Vi=null,ag=-1,Vc=0,Dy=()=>{let a=[],u=pn??fe?.parentElement??null;return u&&a.push(u),qe&&a.push(qe),a},lg=a=>{let u=Math.round(Math.max(0,Math.min(1,a))*100)/100;if(u!==ag){ag=u;for(let m of Dy())m.style.setProperty(By,String(u))}},ME=()=>{ag=-1,Vc=0;for(let a of Dy())a.style.removeProperty(By)};function TE(){if(Vi!==null)return;if(typeof requestAnimationFrame!="function"){lg(h?R.getVoiceLevel()??ig:ig);return}let a=()=>{Vi=requestAnimationFrame(a);let u=h?R.getVoiceLevel():null;if(u===null){lg(ig);return}Vc+=(u-Vc)*.3,lg(Vc)};Vi=requestAnimationFrame(a)}function cg(){Vi!==null&&(cancelAnimationFrame(Vi),Vi=null),ME()}let Ny=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,jc=(a="user")=>{if(jo||R.isStreaming())return;let u=Ny();if(!u)return;go=new u;let m=o.voiceRecognition??{},v=m.pauseDuration??2e3;go.continuous=m.provider?.browser?.continuous??!0,go.interimResults=!0,go.lang=m.provider?.browser?.language??"en-US";let w=ae.value;go.onresult=P=>{let z="",ne="";for(let re=0;re<P.results.length;re++){let ie=P.results[re],le=ie[0].transcript;ie.isFinal?z+=le+" ":ne=le}let G=w+z+ne;ae.value=G,ao(),Ui&&clearTimeout(Ui),(z||ne)&&(Ui=window.setTimeout(()=>{if(ae.value.trim()&&go&&jo){if(Zr(),sg())return;el({viaVoice:!0})}},v))},go.onerror=P=>{P.error!=="no-speech"&&Zr()},go.onend=()=>{if(jo){let P=ae.value.trim();!sg()&&P&&P!==w.trim()&&el({viaVoice:!0}),Zr()}};try{if(go.start(),jo=!0,ze.active=!0,a!=="system"&&(ze.manuallyDeactivated=!1),yr(a),Vn(),xo(),fe){let P=o.voiceRecognition??{};wr={backgroundColor:fe.style.backgroundColor,color:fe.style.color,borderColor:fe.style.borderColor,iconName:P.iconName??"mic",iconSize:parseFloat(P.iconSize??"")||zn};let z=P.recordingBackgroundColor,ne=P.recordingIconColor,G=P.recordingBorderColor;if(fe.classList.add("persona-voice-recording"),Uc("recording"),fe.style.backgroundColor=z??"var(--persona-voice-recording-bg, #ef4444)",fe.style.color=ne??"var(--persona-voice-recording-indicator, #ffffff)",ne){let re=fe.querySelector("svg");re&&re.setAttribute("stroke",ne)}G&&(fe.style.borderColor=G),fe.setAttribute("aria-label","Stop voice recognition")}}catch{Zr("system")}},Zr=(a="user")=>{if(jo){if(jo=!1,Ui&&(clearTimeout(Ui),Ui=null),go){try{go.stop()}catch{}go=null}if(ze.active=!1,yr(a),Vn(),xo(),fe){if(fe.classList.remove("persona-voice-recording"),Uc("idle"),wr){fe.style.backgroundColor=wr.backgroundColor,fe.style.color=wr.color,fe.style.borderColor=wr.borderColor;let u=fe.querySelector("svg");u&&u.setAttribute("stroke",wr.color||"currentColor"),wr=null}fe.setAttribute("aria-label","Start voice recognition")}}},Fy=null,qc=a=>{let u=v=>{Fy??=v.createMicStateStyles({mic:()=>fe,config:()=>o,session:()=>R,get original(){return wr},set original(w){wr=w},setMicState:Uc,renderIcon:ue,iconFallbackPx:zn}),a(Fy)},m=KC();m?u(m):kl().then(u,()=>{})},ji=()=>qc(a=>a.recording()),kE=()=>qc(a=>a.processing()),PE=()=>qc(a=>a.speaking()),Sr=()=>qc(a=>a.reset()),dg=()=>{if(!Uo()){if(Ln(o.voiceRecognition?.provider)){let a=R.getVoiceStatus(),u=R.getVoiceInterruptionMode();if(u==="none"&&(a==="processing"||a==="speaking"))return;if(u==="cancel"&&(a==="processing"||a==="speaking")){R.stopVoicePlayback();return}if(R.isBargeInActive()){R.stopVoicePlayback(),R.deactivateBargeIn().then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,Vn(),yr("user"),Sr()});return}R.toggleVoice().then(()=>{ze.active=Eu(),ze.manuallyDeactivated=!ze.active,Vn(),yr("user"),ze.active?ji():Sr()});return}if(jo){let a=ae.value.trim();ze.manuallyDeactivated=!0,Vn(),Zr("user"),a&&!sg()&&el()}else ze.manuallyDeactivated=!1,Vn(),jc("user")}};iu=dg;let $y=()=>R.prewarmVoice(),Uy=()=>{let a=o.voiceRecognition;return a?.enabled!==!0?!1:a.prewarm??(o.clientToken?"hover":!1)},Vy=a=>{Uy()==="hover"&&fe?.contains(a.target)&&$y()},jy=["pointerover","pointerdown","focusin"];jy.forEach(a=>e.addEventListener(a,Vy));let qy,zy=null,pg,Ky=()=>{let a=pg;pg=void 0;try{typeof a=="function"&&a()}catch{}},ug=()=>{let a=Uy(),u=typeof a=="function"&&fe?a:void 0,m=u?fe:null;if(!(u===qy&&m===zy)&&(Ky(),qy=u,zy=m,!(!u||!m)))try{pg=u({warm:$y,micButton:m,mount:e})}catch{}};ug(),Ce.push(()=>{jy.forEach(a=>e.removeEventListener(a,Vy)),Ky()}),fe&&Ce.push(()=>{Ln(o.voiceRecognition?.provider)?(R.isVoiceActive()&&R.toggleVoice(),Sr()):Zr("system")});let LE=Y.on("assistant:complete",()=>{he.getState().pendingSubmission&&setTimeout(()=>{R.isStreaming()||fE()},0)});Ce.push(LE);let HE=Y.on("assistant:complete",()=>{Xh&&(ze.active||ze.manuallyDeactivated||Xh==="assistant"&&!ze.lastUserMessageWasVoice||setTimeout(()=>{!ze.active&&!ze.manuallyDeactivated&&(Ln(o.voiceRecognition?.provider)?R.toggleVoice().then(()=>{ze.active=R.isVoiceActive(),yr("auto"),R.isVoiceActive()&&ji()}):jc("auto"))},600))});Ce.push(HE);let IE=Y.on("action:resubmit",()=>{setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)});Ce.push(IE);let Gy=()=>{xt(!D,"user")},Vt=null,Rn=null;if(me&&!ke()){let{instance:a,element:u}=Cm({config:o,plugins:d,onToggle:Gy});Vt=a,a||(Rn=u)}Vt?e.appendChild(Vt.element):Rn&&e.appendChild(Rn),Ya(),Ws(),Ic(),ju(),Xa(R.isStreaming()),Hu()||(An()==="follow"?Yr(!0):Lu()),Px(),Qt&&(!me||ke()?setTimeout(()=>Lc(),0):D&&setTimeout(()=>Lc(),200));let es=null,Yy=()=>{es&&(es.disconnect(),es.observe(qe),es.observe(ve),es.observe(Jt))},Xy=$n(),nl=()=>{if(ke()){He(),Ya();return}let a=Ht(o),u=o.launcher?.sidebarMode??!1,m=e.ownerDocument.defaultView??window,v=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640,P=m.innerWidth<=w,z=v&&P&&me;try{if(z){Ps(),Na=mc();return}let ne=!1;yt&&(yt=!1,Ps(),ne=!0);let G=mc();if(!ne&&G!==Na&&(Ps(),ne=!0),Na=G,ne&&pc(),!me&&!a){we.style.height="",we.style.width="";return}if(!u&&!a){let re=ui(o);we.style.width=re.width,we.style.maxWidth=re.maxWidth}fc(),Wh()}finally{He(),Rt();let ne=$n();if(ne!==Xy&&(Xy=ne,Qa(),Ws()),Ya(),D&&me){let re=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ie=o.launcher?.sidebarMode??!1,le=o.launcher?.mobileFullscreen??!0,Te=Ht(o)&&le&&re,rt=ie||le&&re&&me||Te;if(rt&&!Fo){let pt=e.getRootNode(),lt=pt instanceof ShadowRoot?pt.host:e.closest(".persona-host");lt&&!No&&(No=tm(lt,o.launcher?.zIndex??Tn)),Fo=nm(e.ownerDocument)}else rt||(No?.(),No=null,Fo?.(),Fo=null)}}};nl();let zc=e.ownerDocument.defaultView??window;if(zc.addEventListener("resize",nl),Ce.push(()=>zc.removeEventListener("resize",nl)),typeof ResizeObserver<"u"){es=new ResizeObserver(()=>{Rt()}),Yy(),Ce.push(()=>{es?.disconnect(),es=null});let a=new ResizeObserver(()=>{Bc()});a.observe(ve),Ce.push(()=>a.disconnect())}zc.addEventListener("resize",Bc),Ce.push(()=>zc.removeEventListener("resize",Bc)),Qn=se.scrollTop;let Qy=er(se),Jy=()=>{Rh();let a=se.scrollTop,u=er(se),m=u<Qy;if(Qy=u,!wo()){Qn=a,En();return}let{action:v,nextLastScrollTop:w}=eS({following:Xn.isFollowing(),currentScrollTop:a,lastScrollTop:Qn,nearBottom:di(se,mr),userScrollThreshold:Ex,isAutoScrolling:Un||yc||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Qn=w,v==="resume"){Ec()||$o();return}v==="pause"&&Oi()};if(se.addEventListener("scroll",Jy,{passive:!0}),Ce.push(()=>se.removeEventListener("scroll",Jy)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{_x(),Mf(Ee)});a.observe(Ee),a.observe(se),Ce.push(()=>a.disconnect())}let Zy=()=>{wo()&&Xn.isFollowing()&&Ec()&&Oi()},eb=se.ownerDocument;eb.addEventListener("selectionchange",Zy),Ce.push(()=>{eb.removeEventListener("selectionchange",Zy)});let RE=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),tb=a=>{RE.has(a.key)&&(Gr(),Ra()&&wo()&&Xn.isFollowing()&&Oi())},nb=a=>{a.target?.closest("a, button, [tabindex], input, textarea, select")&&(Gr(),Ra()&&wo()&&Xn.isFollowing()&&Oi())};se.addEventListener("keydown",tb),se.addEventListener("focusin",nb),Ce.push(()=>{se.removeEventListener("keydown",tb),se.removeEventListener("focusin",nb)});let ob=a=>{if(a.deltaY!==0&&Gr(),!wo())return;let u=tS({following:Xn.isFollowing(),deltaY:a.deltaY,nearBottom:di(se,mr),resumeWhenNearBottom:!0});u==="pause"?Oi():u==="resume"&&!Ec()&&$o()};se.addEventListener("wheel",ob,{passive:!0}),se.addEventListener("touchmove",Gr,{passive:!0}),se.addEventListener("pointerdown",Gr,{passive:!0}),Ce.push(()=>{se.removeEventListener("touchmove",Gr),se.removeEventListener("pointerdown",Gr)}),Ce.push(()=>se.removeEventListener("wheel",ob)),$t.addEventListener("click",()=>{Vs(),se.scrollTop=se.scrollHeight,Qn=se.scrollTop,$o(),Yr(!0),En()}),Ce.push(()=>$t.remove()),Ce.push(()=>{oy(),Vs()});let rb=()=>{je&&(Is&&(je.removeEventListener("click",Is),Is=null),Ge()?(je.style.display="",Is=()=>{xt(!1,"user")},je.addEventListener("click",Is)):je.style.display="none")};rb(),(()=>{let{clearChatButton:a}=Je;a&&a.addEventListener("click",()=>{let u=Ot;if(u?.historyAvailable()){u.startNewConversation({focusComposer:!0}).catch(v=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",v)});return}R.clearMessages(),o.layout?.topFade&&(se.scrollTop=0),se.removeAttribute("data-persona-top-fade"),xn.clear(),$o(),cs(Je.composerOverlay);try{localStorage.removeItem(La),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${La}`)}catch(v){console.error("[AgentWidget] Failed to clear default localStorage:",v)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==La)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(v){console.error("[AgentWidget] Failed to clear custom localStorage:",v)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(m),T?.clear&&Sc(()=>T.clear(),"[AgentWidget] Failed to clear storage adapter:"),k={},We.syncFromMetadata(),Ue?.clearAttachments(),xc(),Ei(void 0),Do(void 0),Bs(),ut?.clear(),ht?.reset(),nn?.update()})})();let sb=[["keydown",xE],["input",SE],["input",ao],["input",dr],["keyup",dr],["paste",EE],["focus",gx]],ib=a=>{if(a)for(let[u,m]of sb)at?.addListener(a,u,m)},WE=a=>{if(a)for(let[u,m]of sb)at?.removeListener(a,u,m)},ab=()=>{at&&(at.addListener(at.form,"submit",bE),at.addListener(at.footer,"click",dr),ib(ae),fe&&at.addListener(fe,"click",dg),ug())};ab();let lb=()=>{st?.onComposerSwap((a,u)=>{WE(u),ae=a,at&&(at.input=a),ib(a),lu(),_u(),ao()})};lb();let gg=!1;function cb(){if(!gg){gg=!0;try{let a=ae?.value??"",u=qe.ownerDocument??document,m=ae?u.activeElement===ae:!1;cg(),at?.destroy(),at=null,st?.destroy(),st=null;let v=null,w=()=>(v=ke()?Ap({config:o}):Sa({config:o}),v.footer),P=uh(w)??w();kn.replaceComposer(P),qe=kn.composer.footer;let z=v!==null&&P===v.footer;Ti=!z,nc=z?v.setSendButtonMode:()=>{},ph(qe),fh(qe),mh(),hh(),cu(),lb(),yh(),du(),bh(),ab();let ne=Hs.indexOf(fr);if(fr.destroy(),fr=Ul(io),ne>=0&&(Hs[ne]=fr),ae&&(ae.value=a),ao(),dr(),Ic(),Ws(),Xa(R.isStreaming()),o.statusIndicator?.mode==="transient"&&!ke()){let G=R.getStatus();As(Ze,ar(G),o.statusIndicator,G)}ze.active&&Uc("recording"),Ps(),Yy(),He(),xo(),Pc(),m&&ae?.focus()}finally{gg=!1}}}let ol=e.ownerDocument??document;ol.addEventListener("keydown",_y,!0);let db=()=>{Mu()},pb=()=>{ol.visibilityState==="hidden"&&Mu()};typeof window<"u"&&(window.addEventListener("pagehide",db),ol.addEventListener("visibilitychange",pb),Ce.push(()=>{window.removeEventListener("pagehide",db),ol.removeEventListener("visibilitychange",pb)}));let ub="persona-attachment-drop-active",rl=0,fg=()=>{rl=0,ve.classList.remove(ub)},qi=()=>o.attachments?.enabled===!0&&Ue!==null&&!Uo(),gb=a=>{!Dp(a.dataTransfer)||!qi()||(rl++,rl===1&&ve.classList.add(ub))},fb=a=>{!Dp(a.dataTransfer)||!qi()||(rl--,rl<=0&&fg())},mb=a=>{!Dp(a.dataTransfer)||!qi()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},hb=a=>{if(!Dp(a.dataTransfer)||!qi())return;a.preventDefault(),a.stopPropagation(),fg();let u=Array.from(a.dataTransfer.files??[]);u.length!==0&&Ue.handleFiles(u)},ts=!0;ve.addEventListener("dragenter",gb,ts),ve.addEventListener("dragleave",fb,ts),e.addEventListener("dragover",mb,ts),e.addEventListener("drop",hb,ts);let Kc=e.ownerDocument,yb=a=>{qi()&&a.preventDefault()},bb=a=>{qi()&&a.preventDefault()};Kc.addEventListener("dragover",yb),Kc.addEventListener("drop",bb),Ce.push(()=>{at?.destroy(),at=null,cg(),Ao?.destroy(),Ao=null,pr?.destroy(),pr=null,Ur?.destroy(),Ur=null,Vr?.destroy(),Vr=null,$r=null,ru=null,Mu(),ja.destroy(),$i&&clearTimeout($i),Bs(),Ks?.abort(),Ks=null,Ue?.destroy(),Ue=null,he.destroy(),ol.removeEventListener("keydown",_y,!0),st?.destroy()}),Ce.push(()=>{ve.removeEventListener("dragenter",gb,ts),ve.removeEventListener("dragleave",fb,ts),e.removeEventListener("dragover",mb,ts),e.removeEventListener("drop",hb,ts),Kc.removeEventListener("dragover",yb),Kc.removeEventListener("drop",bb),fg()}),Ce.push(()=>{R.cancel()}),Vt?Ce.push(()=>{Vt?.destroy()}):Rn&&Ce.push(()=>{Rn?.remove()});let jt={update(a){let u=o.future?.v5Defaults===!0,m=o.toolCall,v=o.messageActions,w=o.layout?.messages,P=o.colorScheme,z=o.loadingIndicator,ne=o.iterationDisplay,G=o.features?.showReasoning,re=o.features?.showToolCalls,ie=o.features?.toolCallDisplay,le=o.features?.reasoningDisplay,Te=o.features?.streamAnimation?.type,rt=o.features?.history?.enabled===!0,pt=o.features?.history?.provider,lt=o.getIdentityProof,jn=o.clientToken,_t=o.contextMentions;o=Wp({...o,features:p},a),p=o.features,o=Ip(o),c(),yu(),ha(e,o),Kl(e,o),Gl(e,o),Fn(),Mo(),o.colorScheme!==P&&Oh();let Ut=Rp.getForInstance(o.plugins);d.length=0,d.push(...Ut),Qu(),me=o.launcher?.enabled??!0,dt=o.launcher?.autoExpand??!1,Z=o.features?.showReasoning??!0,ye=o.features?.showToolCalls??!0,be=o.features?.scrollToBottom??{};let Wn=An();ot=o.features?.scrollBehavior??{},Wn!==An()&&(Vs(),$o()),Yh(),Wt(),En();let qt=xe;if(xe=o.features?.showEventStreamToggle??!1,xe&&!qt){if(ut||(rr(),R.setSSEEventCallback((J,tt)=>{o.onSSEEvent?.(J,tt),Ia(J,tt)})),!ft&&gt){let J=o.features?.eventStream?.classNames,tt="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"+(J?.toggleButton?" "+J.toggleButton:"");ft=x("button",tt),ft.style.width="28px",ft.style.height="28px",ft.style.color=_n.actionIconColor,ft.type="button",ft.setAttribute("aria-label","Event Stream"),ft.title="Event Stream";let nt=Bt(yA,"18px","currentColor",1.5);nt&&ft.appendChild(nt);let ct=Je.clearChatButtonWrapper,Lt=Je.closeButtonWrapper,Mn=ct||Lt;Mn&&Mn.parentNode===gt?gt.insertBefore(ft,Mn):gt.appendChild(ft),ft.addEventListener("click",()=>{Cn?Mi():au()})}}else!xe&&qt&&(Mi(),ft&&(ft.remove(),ft=null),ut?.clear(),cn?.destroy(),ut=null,cn=null,ht?.reset(),ht=null,Dt=null);if(o.launcher?.enabled===!1&&Vt&&(Vt.destroy(),Vt=null),o.launcher?.enabled===!1&&Rn&&(Rn.remove(),Rn=null),o.launcher?.enabled!==!1&&!Vt&&!Rn){let{instance:J,element:tt}=Cm({config:o,plugins:d,onToggle:Gy});Vt=J,J||(Rn=tt),e.appendChild(tt)}Vt&&Vt.update(o),Za(),Bo&&o.launcher?.subtitle!==void 0&&(Bo.textContent=o.launcher.subtitle);let vt=o.layout?.header;if(vt?.layout!==It&&gt){let J=vt?Vl(o,vt,{showClose:Ge(),onClose:()=>xt(!1,"user")}):ws({config:o,showClose:Ge(),onClose:()=>xt(!1,"user")});kn.replaceHeader(J),gt=kn.header.element,kt=kn.header.iconHolder,_o=kn.header.headerTitle,Bo=kn.header.headerSubtitle,je=kn.header.closeButton,It=vt?.layout,Za()}else if(vt){if(kt&&(kt.style.display=vt.showIcon===!1?"none":""),_o&&(_o.style.display=vt.showTitle===!1?"none":""),Bo&&(Bo.style.display=vt.showSubtitle===!1?"none":""),je){let J=Ge()&&vt.showCloseButton!==!1;je.style.display=J?"":"none"}if(Je.clearChatButtonWrapper){let J=vt.showClearChat;if(J!==void 0){Je.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:tt}=Je;tt&&!tt.classList.contains("persona-absolute")&&(J?tt.classList.remove("persona-ml-auto"):tt.classList.add("persona-ml-auto"))}}}let zo=o.layout?.showHeader!==!1;gt&&(gt.style.display=zo?"":"none");let mo=o.layout?.showFooter!==!1;qe&&(qe.style.display=mo?"":"none"),He(),En(),me!==Se?me?xt(dt,"auto"):(D=!0,Ya()):dt!==St&&xt(dt,"auto"),St=dt,Se=me,nl(),rb();let Ko=JSON.stringify(o.toolCall)!==JSON.stringify(m),To=JSON.stringify(o.messageActions)!==JSON.stringify(v),os=JSON.stringify(o.layout?.messages)!==JSON.stringify(w),sl=o.loadingIndicator?.render!==z?.render||o.loadingIndicator?.renderIdle!==z?.renderIdle||o.loadingIndicator?.showBubble!==z?.showBubble,Gs=o.iterationDisplay!==ne,O=(o.features?.showReasoning??!0)!==(G??!0)||(o.features?.showToolCalls??!0)!==(re??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ie)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(le);(o.future?.v5Defaults===!0!==u||Ko||To||os||sl||Gs||O)&&R&&(Ds++,po(Ee,R.getMessages(),K));let De=o.features?.streamAnimation?.type;if(De!==Te&&De&&De!=="none"){let J=Cu(De,o.features?.streamAnimation?.plugins);J&&Nl(J,e)}let oe=o.launcher??{},Ct=oe.headerIconHidden??!1,Xt=o.layout?.header?.showIcon,Pn=Ct||Xt===!1,gn=oe.headerIconName,Et=oe.headerIconSize??hl;if(kt){let J=gt,tt=J?.querySelector(".persona-flex-col");if(Pn)kt.style.display="none",J&&tt&&!J.contains(tt)&&J.insertBefore(tt,J.firstChild);else{if(kt.style.display="",kt.style.height=Et,kt.style.width=Et,J&&tt&&(J.contains(kt)?kt.nextSibling!==tt&&(kt.remove(),J.insertBefore(kt,tt)):J.insertBefore(kt,tt)),gn){let ct=parseFloat(Et)||24,Lt=ue(gn,ct*.6,"currentColor",1);Lt?(Lt.style.width=`calc(${ct}px * var(--persona-components-header-iconScale, 0.6))`,Lt.style.height=`calc(${ct}px * var(--persona-components-header-iconScale, 0.6))`,kt.replaceChildren(Lt)):kt.textContent=oe.agentIconText??"\u{1F4AC}"}else if(oe.iconUrl){let ct=kt.querySelector("img");if(ct)ct.src=oe.iconUrl,ct.style.height=Et,ct.style.width=Et;else{let Lt=document.createElement("img");Lt.src=oe.iconUrl,Lt.alt="",Lt.className="persona-rounded-xl persona-object-cover",Lt.style.height=Et,Lt.style.width=Et,kt.replaceChildren(Lt)}}else{let ct=kt.querySelector("svg"),Lt=kt.querySelector("img");(ct||Lt)&&kt.replaceChildren(),kt.textContent=oe.agentIconText??"\u{1F4AC}"}let nt=kt.querySelector("img");nt&&(nt.style.height=Et,nt.style.width=Et)}}let zt=o.layout?.header?.showTitle,sn=o.layout?.header?.showSubtitle;if(_o&&(_o.style.display=zt===!1?"none":""),Bo&&(Bo.style.display=sn===!1?"none":""),je){let J=Ge()&&o.layout?.header?.showCloseButton!==!1;if(je.style.display=J?"":"none",!ke()){let mn=oe.closeButtonSize??"";je.style.height=mn,je.style.width=mn,je.style.minWidth=mn,je.style.minHeight=mn}let tt=oe.closeButtonPlacement??"inline",{closeButtonWrapper:nt}=Je,ct=tt==="top-right",Lt=nt?.classList.contains("persona-absolute");if(nt&&ct!==Lt)if(nt.remove(),ct){nt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let mn=Ot?.railColumn??ve;mn.style.position="relative",mn.appendChild(nt)}else{let mn=oe.clearChat?.placement??"inline",hn=oe.clearChat?.enabled??!0;nt.className=hn&&mn==="inline"?"":"persona-ml-auto",gt&&gt.appendChild(nt)}if(je.style.color=oe.closeButtonColor||_n.actionIconColor,oe.closeButtonBackgroundColor?(je.style.backgroundColor=oe.closeButtonBackgroundColor,je.classList.remove("hover:persona-bg-gray-100")):(je.style.backgroundColor="",je.classList.add("hover:persona-bg-gray-100")),oe.closeButtonBorderWidth||oe.closeButtonBorderColor){let mn=oe.closeButtonBorderWidth||"0px",hn=oe.closeButtonBorderColor||"transparent";je.style.border=`${mn} solid ${hn}`,je.classList.remove("persona-border-none")}else je.style.border="",je.classList.add("persona-border-none");oe.closeButtonBorderRadius?(je.style.borderRadius=oe.closeButtonBorderRadius,je.classList.remove("persona-rounded-full")):(je.style.borderRadius="",je.classList.add("persona-rounded-full")),oe.closeButtonPaddingX?(je.style.paddingLeft=oe.closeButtonPaddingX,je.style.paddingRight=oe.closeButtonPaddingX):(je.style.paddingLeft="",je.style.paddingRight=""),oe.closeButtonPaddingY?(je.style.paddingTop=oe.closeButtonPaddingY,je.style.paddingBottom=oe.closeButtonPaddingY):(je.style.paddingTop="",je.style.paddingBottom=""),wp(je,oe.closeButtonIconName??"x",{iconSize:ke()?hm:void 0,iconText:oe.closeButtonIconText??"\xD7"});let Mn=oe.closeButtonTooltipText??"Close chat",Po=oe.closeButtonShowTooltip??!0;je.setAttribute("aria-label",Mn),nt&&yn({anchor:je,trigger:nt,text:()=>je?.getAttribute("aria-label")??Mn,enabled:Po})}let{clearChatButton:Ie,clearChatButtonWrapper:Mt}=Je;if(Ie){let J=oe.clearChat??{},tt=J.enabled??!0,nt=o.layout?.header?.showClearChat,ct=nt!==void 0?nt:tt,Lt=J.placement??"inline";if(Mt){Mt.style.display=ct?"":"none";let{closeButtonWrapper:Mn}=Je;!ke()&&Mn&&!Mn.classList.contains("persona-absolute")&&(ct?Mn.classList.remove("persona-ml-auto"):Mn.classList.add("persona-ml-auto"));let Po=Lt==="top-right",mn=Mt.classList.contains("persona-absolute");if(!ke()&&Po!==mn&&ct){if(Mt.remove(),Po){Mt.className="persona-absolute persona-top-4 persona-z-50",Mt.style.right="48px";let Go=Ot?.railColumn??ve;Go.style.position="relative",Go.appendChild(Mt)}else{Mt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Mt.style.right="";let Go=Je.closeButtonWrapper;gt&&Go&&Go.parentElement===gt?gt.insertBefore(Mt,Go):gt&&gt.appendChild(Mt)}let hn=Je.closeButtonWrapper;hn&&!hn.classList.contains("persona-absolute")&&(Po?hn.classList.add("persona-ml-auto"):hn.classList.remove("persona-ml-auto"))}}if(ct){if(!ke()){let hn=J.size??"";Ie.style.height=hn,Ie.style.width=hn,Ie.style.minWidth=hn,Ie.style.minHeight=hn}let Mn=J.iconColor??"";if(Ie.style.color=Mn||_n.actionIconColor,wp(Ie,J.iconName??"refresh-cw",{iconSize:ke()?ym:void 0}),J.backgroundColor?(Ie.style.backgroundColor=J.backgroundColor,Ie.classList.remove("hover:persona-bg-gray-100")):(Ie.style.backgroundColor="",Ie.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let hn=J.borderWidth||"0px",Go=J.borderColor||"transparent";Ie.style.border=`${hn} solid ${Go}`,Ie.classList.remove("persona-border-none")}else Ie.style.border="",Ie.classList.add("persona-border-none");J.borderRadius?(Ie.style.borderRadius=J.borderRadius,Ie.classList.remove("persona-rounded-full")):(Ie.style.borderRadius="",Ie.classList.add("persona-rounded-full")),J.paddingX?(Ie.style.paddingLeft=J.paddingX,Ie.style.paddingRight=J.paddingX):(Ie.style.paddingLeft="",Ie.style.paddingRight=""),J.paddingY?(Ie.style.paddingTop=J.paddingY,Ie.style.paddingBottom=J.paddingY):(Ie.style.paddingTop="",Ie.style.paddingBottom="");let Po=J.tooltipText??"Clear chat",mn=J.showTooltip??!0;Ie.setAttribute("aria-label",Po),Mt&&yn({anchor:Ie,trigger:Mt,text:()=>Ie?.getAttribute("aria-label")??Po,enabled:mn})}}let Ne=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Op],an=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Pa.message,Pa.messageAndClick];We=_p({parsers:Ne,handlers:an,getSessionMetadata:mt,updateSessionMetadata:Ve,emit:Y.emit,documentRef:typeof document<"u"?document:null}),K=wA(o,We,q),tE(),R.updateConfig(o),Iy(),(o.features?.history?.enabled===!0!==rt||o.features?.history?.provider!==pt||o.getIdentityProof!==lt||o.clientToken!==jn)&&(Ot?.closeHistory({restoreFocus:!1}),Ot?.installHistoryProvider()),Ot?.syncHistoryChromeImpl(),Bc(),Ja()&&!Ot&&Zu().catch(()=>{}),po(Ee,R.getMessages(),K),Ws(),Ic(),Jx(),Xa(R.isStreaming()),_t!==o.contextMentions&&cb();let yo=o.voiceRecognition?.enabled===!0,fn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),wt=Ln(o.voiceRecognition?.provider);if(yo&&(fn||wt))if(!fe||!pn){let J=ca(o);if(J){fe=J.button,pn=J.wrapper;let tt=In&&In.parentElement===xs?In:null;xs?xs.insertBefore(pn,tt):wn?.appendChild(pn),at&&(at.micButton=fe),at?.addListener(fe,"click",dg),fe.disabled=Uo()||R.isStreaming()&&!Wu()}}else{let J=o.voiceRecognition??{},tt=o.sendButton??{},nt=J.iconName??"mic",ct=J.iconSize,Lt=parseFloat(ct??"")||zn;fe.classList.add(eo),fe.classList.toggle(Ro,!ct),fe.style.width=ct??"",fe.style.height=ct??"",fe.style.minWidth=ct??"",fe.style.minHeight=ct??"";let Mn=J.iconColor??tt.textColor;fe.innerHTML="";let Po=ue(nt,Lt,Mn||"currentColor",1.5);Po?fe.appendChild(Po):fe.textContent="\u{1F3A4}";let mn=J.backgroundColor??tt.backgroundColor;mn?fe.style.backgroundColor=mn:fe.style.backgroundColor="",Mn?fe.style.color=Mn:fe.style.color="var(--persona-text, #111827)",J.borderWidth?(fe.style.borderWidth=J.borderWidth,fe.style.borderStyle="solid"):(fe.style.borderWidth="",fe.style.borderStyle=""),J.borderColor?fe.style.borderColor=J.borderColor:fe.style.borderColor="",J.paddingX?(fe.style.paddingLeft=J.paddingX,fe.style.paddingRight=J.paddingX):(fe.style.paddingLeft="",fe.style.paddingRight=""),J.paddingY?(fe.style.paddingTop=J.paddingY,fe.style.paddingBottom=J.paddingY):(fe.style.paddingTop="",fe.style.paddingBottom="");let hn=J.tooltipText??"Start voice recognition",Go=J.showTooltip??!1;fe.setAttribute("aria-label",hn),pn&&yn({anchor:fe,trigger:pn,text:()=>fe?.getAttribute("aria-label")??hn,enabled:Go}),pn.style.display="",fe.disabled=Uo()||R.isStreaming()&&!Wu()}else fe&&pn&&(pn.style.display="none",Ln(o.voiceRecognition?.provider)?R.isVoiceActive()&&R.toggleVoice():jo&&Zr());if(ug(),o.attachments?.enabled===!0){if(!on||!Pt){let J=o.attachments??{};un||(un=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),un.style.display="none",(ae.parentElement??wn).insertBefore(un,ae)),At||(At=document.createElement("input"),At.type="file",At.accept=(J.allowedTypes??Lr).join(","),At.multiple=(J.maxFiles??4)>1,At.style.display="none",At.setAttribute("aria-label","Attach files"),(ae.parentElement??wn).insertBefore(At,ae)),on=x("div","persona-send-button-wrapper"),Pt=x("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${eo} ${Ro}`),Pt.type="button",Pt.setAttribute("aria-label",J.buttonTooltipText??"Attach file");let tt=J.buttonIconName??"paperclip";Pt.style.fontSize="18px",Pt.style.lineHeight="1";let nt=ue(tt,zn,"currentColor",1.5);nt?Pt.appendChild(nt):Pt.textContent="\u{1F4CE}",Pt.addEventListener("click",Lt=>{Lt.preventDefault(),At?.click()}),on.appendChild(Pt);let ct=J.buttonTooltipText??"Attach file";yn({anchor:Pt,trigger:on,text:()=>Pt?.getAttribute("aria-label")??ct}),Sn?Sn.append(on):wn.appendChild(on),at&&(at.attachmentButton=Pt,at.attachmentInput=At??void 0,at.attachmentPreviews=un??void 0),!Ue&&At&&un&&(Ue=fa.fromConfig(J,ih),Ue.setPreviewsContainer(un),at?.addListener(At,"change",async()=>{Ue&&At?.files&&(await Ue.handleFileSelect(At.files),At.value="")}))}else{on.style.display="";let J=o.attachments??{};At&&(At.accept=(J.allowedTypes??Lr).join(","),At.multiple=(J.maxFiles??4)>1),Ue&&Ue.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles,adapter:J.adapter})}if(ve.querySelector(".persona-attachment-drop-overlay")?.remove(),ve.appendChild(SA(o.attachments?.dropOverlay)),Pt){let J=o.attachments??{},tt=J.buttonTooltipText??"Attach file";Pt.setAttribute("aria-label",tt),Pt.textContent="";let nt=ue(J.buttonIconName??"paperclip",zn,"currentColor",1.5);nt?Pt.appendChild(nt):Pt.textContent="\u{1F4CE}",on&&yn({anchor:Pt,trigger:on,text:()=>Pt?.getAttribute("aria-label")??tt})}}else on&&(on.style.display="none"),Ue&&Ue.clearAttachments(),ve.querySelector(".persona-attachment-drop-overlay")?.remove();let Fe=o.sendButton??{},rs=Fe.useIcon??!1,en=Fe.iconText??"\u2191",qn=Fe.iconName,Ar=Fe.tooltipText??"Send message",mg=Fe.showTooltip??!1,Ys=Fe.size,hg=parseFloat(Ys??"")||lf,xr=Fe.backgroundColor,Xs=Fe.textColor;if(rs){if(Me.style.width=Ys??"",Me.style.height=Ys??"",Me.style.minWidth=Ys??"",Me.style.minHeight=Ys??"",Me.style.fontSize="18px",Me.style.lineHeight="1",Xs?Me.style.color=Xs:Me.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!R.isStreaming())if(Me.innerHTML="",qn){let J=parseFloat(Fe.iconSize??"")||Math.round(hg*.5),tt=Xs?.trim()||"currentColor",nt=Fe.iconStrokeWidth??2,ct=ue(qn,J,tt,nt),Lt=ue(Fe.stopIconName??"square",J,tt,nt);ct&&Lt?Me.appendChild(cf(ct,Lt)):ct?Me.appendChild(ct):Me.textContent=en}else Me.textContent=en;Me.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${eo}`,xr?(Me.style.backgroundColor=xr,Me.classList.remove("persona-bg-persona-primary")):(Me.style.backgroundColor="",Me.classList.add("persona-bg-persona-primary"))}else Me.textContent=o.copy?.sendButtonLabel??"Send",Me.style.width="",Me.style.height="",Me.style.minWidth="",Me.style.minHeight="",Me.style.fontSize="",Me.style.lineHeight="",Me.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",xr?(Me.style.backgroundColor=xr,Me.classList.remove("persona-bg-persona-accent")):Me.classList.add("persona-bg-persona-accent"),Xs?Me.style.color=Xs:Me.classList.add("persona-text-white");Fe.borderWidth?(Me.style.borderWidth=Fe.borderWidth,Me.style.borderStyle="solid"):(Me.style.borderWidth="",Me.style.borderStyle=""),Fe.borderColor?Me.style.borderColor=Fe.borderColor:Me.style.borderColor="",Fe.paddingX?(Me.style.paddingLeft=Fe.paddingX,Me.style.paddingRight=Fe.paddingX):(Me.style.paddingLeft="",Me.style.paddingRight=""),Fe.paddingY?(Me.style.paddingTop=Fe.paddingY,Me.style.paddingBottom=Fe.paddingY):(Me.style.paddingTop="",Me.style.paddingBottom=""),R.isStreaming()||Me.setAttribute("aria-label",Ar),Pc(),In&&yn({anchor:Me,trigger:In,text:()=>Me.getAttribute("aria-label")??Ar,enabled:mg}),vh(),vu();let vb=ip(he.getState().activeModeIds,o.composer?.modes);he.setActiveModeIds(vb),Ai().length>0!==!!pr&&du(),pr?.render(vb,Ai());for(let J of[...xi.keys()])sp(J,o.composer?.modeGroups)||xi.delete(J);xi.forEach(J=>J.repaint()),$r?.repaint(),Ao?.resolve();let Gc=bs(o,ke());if(bu(),Gc){Ee.style.maxWidth=Gc,Ee.style.marginLeft="auto",Ee.style.marginRight="auto",Ee.style.width="100%",Hn.style.maxWidth=Gc,Hn.style.marginLeft="auto",Hn.style.marginRight="auto",Hn.style.width="100%";for(let J of[wn,io,un,Ze])J&&(J.style.maxWidth=Gc,J.style.marginLeft="auto",J.style.marginRight="auto",J.style.width="100%")}else{Ee.style.maxWidth="",Ee.style.marginLeft="",Ee.style.marginRight="",Ee.style.width="",Hn.style.maxWidth="",Hn.style.marginLeft="",Hn.style.marginRight="",Hn.style.width="";for(let J of[wn,io,un,Ze])J&&(J.style.maxWidth="",J.style.marginLeft="",J.style.marginRight="",J.style.width="")}let ko=o.statusIndicator??{};if(qg(Ze,wn,ko),ri(Ze,ko,R?.getStatus()??"idle"),R){let J=R.getStatus();As(Ze,(nt=>nt==="idle"?ko.idleText??Kt.idle:nt==="connecting"?ko.connectingText??Kt.connecting:nt==="connected"?ko.connectedText??Kt.connected:nt==="error"?ko.errorText??Kt.error:nt==="paused"?ko.pausedText??Kt.paused:nt==="resuming"?ko.resumingText??Kt.resuming:Kt[nt])(J),ko,J)}Ze.classList.remove("persona-text-left","persona-text-center","persona-text-right");let BE=ko.align==="left"?"persona-text-left":ko.align==="center"?"persona-text-center":"persona-text-right";Ze.classList.add(BE),lu(),_u(),xo(),sr()},open(){Ge()&&xt(!0,"api")},close(){Ge()&&xt(!1,"api")},toggle(){Ge()&&xt(!D,"api")},reconnect(){R.reconnectNow()},clearChat(){ur=!1,i.clear(),r.clear(),s.clear(),l.clear(),R.clearMessages(),o.layout?.topFade&&(se.scrollTop=0),se.removeAttribute("data-persona-top-fade"),xn.clear(),$o();try{localStorage.removeItem(La),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${La}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==La)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),T?.clear&&Sc(()=>T.clear(),"[AgentWidget] Failed to clear storage adapter:"),k={},We.syncFromMetadata(),Ue?.clearAttachments(),xc(),Ei(void 0),Do(void 0),Bs(),ut?.clear(),ht?.reset(),nn?.update()},setMessage(a){return!ae||R.isStreaming()||Uo()?!1:(!D&&Ge()&&xt(!0,"system"),ae.value=a,ae.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(R.isStreaming()||js())return!1;let u=a?.trim()||ae.value.trim();return u?(!D&&Ge()&&xt(!0,"system"),ae.value="",ae.style.height="auto",ao(),$c(u,{consumeDraft:!1}),!0):!1},getComposerState(){return he.getState()},setQuote(a){let u=a?.text?.trim();u&&Do({...a,text:u})},clearQuote(){Do(void 0)},startVoiceRecognition(){return R.isStreaming()?!1:Ln(o.voiceRecognition?.provider)?(R.isVoiceActive()||R.isBargeInActive()||(!D&&Ge()&&xt(!0,"system"),ze.manuallyDeactivated=!1,Vn(),R.toggleVoice().then(()=>{ze.active=Eu(),Vn(),yr("user"),ze.active&&ji()})),!0):jo?!0:Ny()?(!D&&Ge()&&xt(!0,"system"),ze.manuallyDeactivated=!1,Vn(),jc("user"),!0):!1},stopVoiceRecognition(){return Ln(o.voiceRecognition?.provider)?!R.isVoiceActive()&&!R.isBargeInActive()?!1:((R.isBargeInActive()?R.deactivateBargeIn():R.toggleVoice()).then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,Vn(),yr("user"),Sr()}),!0):jo?(ze.manuallyDeactivated=!0,Vn(),Zr("user"),!0):!1},injectMessage(a){return!D&&Ge()&&xt(!0,"system"),R.injectMessage(a)},injectAssistantMessage(a){!D&&Ge()&&xt(!0,"system");let u=R.injectAssistantMessage(a);return S&&(S=!1,F&&(clearTimeout(F),F=null),setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)),u},injectUserMessage(a){return!D&&Ge()&&xt(!0,"system"),R.injectUserMessage(a)},injectSystemMessage(a){return!D&&Ge()&&xt(!0,"system"),R.injectSystemMessage(a)},injectMessageBatch(a){return!D&&Ge()&&xt(!0,"system"),R.injectMessageBatch(a)},injectComponentDirective(a){return!D&&Ge()&&xt(!0,"system"),R.injectComponentDirective(a)},injectTestMessage(a){!D&&Ge()&&xt(!0,"system"),R.injectTestEvent(a)},async connectStream(a,u){return R.connectStream(a,u)},__pushEventStreamEvent(a){xe&&(rr(),Ia(a.type,a.payload))},showEventStream(){xe&&au()},hideEventStream(){Cn&&Mi()},isEventStreamVisible(){return Cn},listConversations(a){return R.listConversations(a)},getActiveConversationId(){return R.getActiveConversationId()},openConversation(a,u){return Vo(m=>m.openHistoryConversation(a,{focusComposer:u?.focus===!0}))},startNewConversation(a){return Vo(u=>u.startNewConversation({focusComposer:a?.focus===!0}))},warmSession(){eg()},deleteConversation(a){return Vo(u=>u.deleteHistoryConversation(a))},renameConversation(a,u){return Vo(m=>m.updateHistoryConversation(a,{title:u}))},setConversationStarred(a,u){return Vo(m=>m.updateHistoryConversation(a,{starred:u}))},clearConversationHistory(a){return Vo(u=>u.clearConversationHistory(a))},resetHistoryIdentity(){return Vo(a=>a.resetHistoryIdentity())},async getVisitorToken(){let a=uo;if(!a)return null;let u=await a.get();return a===uo?u:null},getHistoryIdentityStatus(){let a=Ot?.historyProvider;return a?a.getIdentityStatus():Ja()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(a){return Ja()?Vo(u=>u.openHistory({...a?.returnSurface?{returnSurface:a.returnSurface}:{},...a?.focus!==void 0?{focus:a.focus}:{}})):Promise.resolve()},hideHistory(a){Ot?.closeHistory(a?.restoreFocus!==void 0?{restoreFocus:a.restoreFocus}:void 0)},isHistoryVisible(){return dn},showArtifacts(){Dn(o)&&(ur=!1,ki=!0,Mo(),et?.setMobileOpen(!0))},hideArtifacts(){Dn(o)&&(ur=!0,Mo())},upsertArtifact(a){return Dn(o)?(Mr(o.features?.artifacts,{artifactType:a.artifactType,...a.artifactType==="markdown"&&a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{}})==="panel"&&(ur=!1,ki=!0),R.upsertArtifact(a)):null},selectArtifact(a){Dn(o)&&R.selectArtifact(a)},clearArtifacts(){Dn(o)&&R.clearArtifacts()},getArtifacts(){return R?.getArtifacts()??[]},getSelectedArtifactId(){return R?.getSelectedArtifactId()??null},focusInput(){return me&&!D&&!ke()||!ae?!1:(ae.focus(),!0)},async resolveApproval(a,u,m){let w=R.getMessages().find(P=>P.variant==="approval"&&P.approval?.id===a);if(!w?.approval)throw new Error(`Approval not found: ${a}`);if(w.approval.toolType==="webmcp"){R.resolveWebMcpApproval(w.id,u);return}return R.resolveApproval(w.approval,u,m)},setFollowUpSuggestions(a){Ax(a)},clearFollowUpSuggestions(){Gh()},getMessages(){return R.getMessages()},getStatus(){return R.getStatus()},getPersistentMetadata(){return{...k}},updatePersistentMetadata(a){Ve(a)},on(a,u){return Y.on(a,u)},off(a,u){Y.off(a,u)},isOpen(){return Ge()&&D},isVoiceActive(){return ze.active},toggleReadAloud(a){R.toggleReadAloud(a)},stopReadAloud(){R.stopSpeaking()},getReadAloudState(a){return R.getReadAloudState(a)},onReadAloudChange(a){return R.onReadAloudChange(a)},getState(){return{open:Ge()&&D,launcherEnabled:me,voiceActive:ze.active,streaming:R.isStreaming()}},showCSATFeedback(a){!D&&Ge()&&xt(!0,"system");let u=Ee.querySelector(".persona-feedback-container");u&&u.remove();let m=$m({onSubmit:async(v,w)=>{R.isClientTokenMode()&&await R.submitCSATFeedback(v,w),a?.onSubmit?.(v,w)},onDismiss:a?.onDismiss,...a});Ee.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!D&&Ge()&&xt(!0,"system");let u=Ee.querySelector(".persona-feedback-container");u&&u.remove();let m=Um({onSubmit:async(v,w)=>{R.isClientTokenMode()&&await R.submitNPSFeedback(v,w),a?.onSubmit?.(v,w)},onDismiss:a?.onDismiss,...a});Ee.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,u){return R.submitCSATFeedback(a,u)},async submitNPSFeedback(a,u){return R.submitNPSFeedback(a,u)},destroy(){Gu(),qs!=null&&(clearInterval(qs),qs=null),i.clear(),r.clear(),s.clear(),l.clear(),Ce.forEach(a=>a()),Xe.remove(),Gt?.remove(),Vt?.destroy(),Rn?.remove(),Is&&je.removeEventListener("click",Is)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,u={controller:jt,getMessages:jt.getMessages,getStatus:jt.getStatus,getMetadata:jt.getPersistentMetadata,updateMetadata:jt.updatePersistentMetadata,clearHistory:()=>jt.clearChat(),setVoiceActive:m=>m?jt.startVoiceRecognition():jt.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Ce.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=a)})}if(typeof window<"u"){let a=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=re=>{let ie=re.detail;(!ie?.instanceId||ie.instanceId===a)&&jt.focusInput()};if(window.addEventListener("persona:focusInput",u),Ce.push(()=>{window.removeEventListener("persona:focusInput",u)}),xe){let re=le=>{let Te=le.detail;(!Te?.instanceId||Te.instanceId===a)&&jt.showEventStream()},ie=le=>{let Te=le.detail;(!Te?.instanceId||Te.instanceId===a)&&jt.hideEventStream()};window.addEventListener("persona:showEventStream",re),window.addEventListener("persona:hideEventStream",ie),Ce.push(()=>{window.removeEventListener("persona:showEventStream",re),window.removeEventListener("persona:hideEventStream",ie)})}let m=re=>{let ie=re.detail;(!ie?.instanceId||ie.instanceId===a)&&jt.showHistory()},v=re=>{let ie=re.detail;(!ie?.instanceId||ie.instanceId===a)&&jt.hideHistory()};window.addEventListener("persona:showHistory",m),window.addEventListener("persona:hideHistory",v),Ce.push(()=>{window.removeEventListener("persona:showHistory",m),window.removeEventListener("persona:hideHistory",v)});let w=re=>{let ie=re.detail;(!ie?.instanceId||ie.instanceId===a)&&jt.showArtifacts()},P=re=>{let ie=re.detail;(!ie?.instanceId||ie.instanceId===a)&&jt.hideArtifacts()},z=re=>{let ie=re.detail;ie?.instanceId&&ie.instanceId!==a||ie?.artifact&&jt.upsertArtifact(ie.artifact)},ne=re=>{let ie=re.detail;ie?.instanceId&&ie.instanceId!==a||typeof ie?.id=="string"&&jt.selectArtifact(ie.id)},G=re=>{let ie=re.detail;(!ie?.instanceId||ie.instanceId===a)&&jt.clearArtifacts()};window.addEventListener("persona:showArtifacts",w),window.addEventListener("persona:hideArtifacts",P),window.addEventListener("persona:upsertArtifact",z),window.addEventListener("persona:selectArtifact",ne),window.addEventListener("persona:clearArtifacts",G),Ce.push(()=>{window.removeEventListener("persona:showArtifacts",w),window.removeEventListener("persona:hideArtifacts",P),window.removeEventListener("persona:upsertArtifact",z),window.removeEventListener("persona:selectArtifact",ne),window.removeEventListener("persona:clearArtifacts",G)})}let fo=aR(o.persistState);if(fo&&Ge()){let a=lR(fo.storage),u=`${fo.keyPrefix}widget-open`,m=`${fo.keyPrefix}widget-voice`,v=`${fo.keyPrefix}widget-voice-mode`;if(a){let w=fo.persist?.openState&&a.getItem(u)==="true",P=fo.persist?.voiceState&&a.getItem(m)==="true",z=fo.persist?.voiceState&&a.getItem(v)==="true";if(w&&(Vt?.setPanelOpen(!0,"auto"),setTimeout(()=>{jt.open(),setTimeout(()=>{if(P||z)jt.startVoiceRecognition();else if(fo.persist?.focusInput){let ne=e.querySelector("textarea");ne&&ne.focus()}},100)},0)),fo.persist?.openState&&(Y.on("widget:opened",()=>{a.setItem(u,"true")}),Y.on("widget:closed",()=>{a.setItem(u,"false")})),fo.persist?.voiceState&&(Y.on("voice:state",ne=>{a.setItem(m,ne.active?"true":"false")}),Y.on("user:message",ne=>{a.setItem(v,ne.viaVoice?"true":"false")})),fo.clearOnChatClear){let ne=()=>{a.removeItem(u),a.removeItem(m),a.removeItem(v)},G=()=>ne();window.addEventListener("persona:clear-chat",G),Ce.push(()=>{window.removeEventListener("persona:clear-chat",G)})}}}if(Ae&&Ge()&&(Vt?.setPanelOpen(!0,"auto"),setTimeout(()=>{jt.open()},0)),Bi(),!xx){let a=il(()=>{R&&(Ds++,xn.clear(),po(Ee,R.getMessages(),K))});Ce.push(a)}I=()=>{R&&(Ds++,xn.clear(),po(Ee,R.getMessages(),K))},R.getMessages().length>0&&kc(),W=()=>{R&&(Ds++,xn.clear(),po(Ee,R.getMessages(),K))};let OE=Eb(()=>{R&&(Ds++,xn.clear(),po(Ee,R.getMessages(),K))});Ce.push(OE);let _E=Lm(()=>{R&&(Ds++,xn.clear(),po(Ee,R.getMessages(),K),Wr()?.updateInlineArtifactBlocks(Ee,lo.artifacts,{suppressTransition:!0}),Mo())});return Ce.push(_E),jt};Lo();var AA=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},pR=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},uR=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},gR=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&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.")},xA=(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"},Gm=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=""},EA=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Gm(e)},qm=e=>{e.style.transition=""},zm=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=""},Km=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Np=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},fR=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},mR=(e,t,n,o,r,s)=>{let i=s?t:e;r==="left"?i.firstElementChild!==o&&i.replaceChildren(o,n):i.lastElementChild!==o&&i.replaceChildren(n,o)},hR=e=>{let t=Zo(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:vn(t,r)??r;return{inset:o(n?.inset,dp),canvasBackground:o(n?.canvasBackground,pp)}},MA=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},yR=(e,t,n,o,r,s,i,l)=>{let c=no(s),p=c.reveal==="push",d=l!=null,g=l?.inset??"",f=l?.canvasBackground??"";fR(e,t,n,o,p),mR(e,t,n,o,c.side,p),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=i?"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",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let h=e.ownerDocument.defaultView,y=s?.launcher?.mobileFullscreen??!0,b=s?.launcher?.mobileBreakpoint??640,C=h!=null?h.innerWidth<=b:!1;if(y&&C&&i){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),zm(t),qm(o),EA(o),Km(n),Np(r,o),MA(o,!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",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Tn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(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");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),EA(o),pR(o,c.maxHeight),MA(o,d&&i,g,f),c.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",zm(t),qm(o),Km(n),Np(r,o);let L=c.animate?"transform 180ms ease":"none",I=c.side==="right"?"translateX(100%)":"translateX(-100%)",H=i?"translateX(0)":I;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=c.width,o.style.maxWidth=c.width,o.style.minWidth=c.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=L,o.style.transform=H,o.style.pointerEvents=i?"auto":"none",o.style.zIndex="2",c.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.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",qm(o),Gm(o),Np(r,o);let L=AA(c.width,e.clientWidth),I=Math.max(0,e.clientWidth),H=c.animate?"margin-left 180ms ease":"none",B=c.side==="right"?i?-L:0:i?0:-L;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=`${I+L}px`,t.style.transition=H,t.style.marginLeft=`${B}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${I}px`,n.style.maxWidth=`${I}px`,n.style.minWidth=`${I}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=c.width,o.style.minWidth=c.width,o.style.maxWidth=c.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=i?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",zm(t),Gm(o),Km(n),Np(r,o);let L=c.reveal==="emerge";L?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=i?c.width:"0px",H=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${d?", padding 180ms ease":""}`:"none",B=!i;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${I}`,o.style.width=I,o.style.maxWidth=I,o.style.minWidth=I,o.style.minHeight="0",uR(o,c.maxHeight),o.style.overflow=L||B?"hidden":"visible",o.style.transition=H,L){o.style.alignItems=c.side==="right"?"flex-start":"flex-end";let V=d?`calc(${AA(c.width,e.clientWidth)}px - (2 * ${g}))`:c.width;r.style.width=V,r.style.minWidth=V,r.style.maxWidth=V,r.style.boxSizing="border-box"}}},bR=(e,t)=>{let n=e.ownerDocument.createElement("div");return xA(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){xA(n,o)},destroy(){n.remove()}}},vR=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,i=n.createElement("div"),l=n.createElement("div"),c=n.createElement("div"),p=n.createElement("aside"),d=n.createElement("div"),g=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",c.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",d.dataset.personaDockRole="host",p.appendChild(d),o.insertBefore(i,e),c.appendChild(e);let f=null,h=()=>{f?.disconnect(),f=null},y=null,b=()=>{y=t?.launcher?.detachedPanel===!0?hR(t):null};b();let C=()=>{yR(i,l,c,p,d,t,g,y)},A=null,L=()=>{A?.(),A=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(A=Il(()=>{b(),C()}))},I=()=>{h(),no(t).reveal==="push"&&(typeof ResizeObserver>"u"||(f=new ResizeObserver(()=>{C()}),f.observe(i)))},H=!1,B=()=>{C(),I(),g&&!H&&i.dataset.personaDockMobileFullscreen!=="true"&&(H=!0,gR(i,no(t)))},V=i.ownerDocument.defaultView,te=()=>{B()};return V?.addEventListener("resize",te),no(t).reveal==="push"?(l.appendChild(c),l.appendChild(p),i.appendChild(l)):(i.appendChild(c),i.appendChild(p)),B(),L(),{mode:"docked",host:d,shell:i,syncWidgetState(W){let j=W.launcherEnabled?W.open:!0;g!==j&&(g=j,B())},updateConfig(W){t=W,(t?.launcher?.enabled??!0)===!1&&(g=!0),b(),B(),L()},destroy(){V?.removeEventListener("resize",te),A?.(),A=null,h(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),i.remove()}}},Fp=(e,t)=>Ht(t)?vR(e,t):bR(e,t);var CR=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},TA=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},$p=[],wR=()=>[...$p],kA=e=>{let t=CR(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=Fp(t,r),i,l=[],c=(C,A)=>{let I=!(A?.launcher?.enabled??!0)||Ht(A),H=o.createElement("div");if(H.setAttribute("data-persona-root","true"),I&&(H.style.height="100%",H.style.display="flex",H.style.flexDirection="column",H.style.flex="1",H.style.minHeight="0",H.style.minWidth="0"),n){let B=C.attachShadow({mode:"open"});B.appendChild(H),TA(B,o)}else C.appendChild(H),TA(C,o);return t.id&&H.setAttribute("data-persona-instance",t.id),H},p=()=>{s.syncWidgetState(i.getState())},d=()=>{l.forEach(C=>C()),l=[i.on("widget:opened",p),i.on("widget:closed",p)],p()},g=()=>{let C=c(s.host,r);i=jm(C,r,{debugTools:e.debugTools}),d()},f=()=>{l.forEach(C=>C()),l=[],i.destroy()};g(),e.onChatReady?.();let h=C=>{f(),s.destroy(),s=Fp(t,C),r=C,g()},y={update(C){let A=Wp(r??{},C),L=Ht(r),I=Ht(A),H=Cs(r),B=Cs(A);if(L!==I||H!==B){h(A);return}r=A,s.updateConfig(r),i.update(C),p()},destroy(){f(),s.destroy();let C=$p.indexOf(b);C!==-1&&$p.splice(C,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},b=new Proxy(y,{get(C,A,L){if(A==="host")return s.host;if(A in C)return Reflect.get(C,A,L);let I=i[A];return typeof I=="function"?I.bind(i):I}});return $p.push(b),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=b),b};Yi();gl();cd();ea();ei();ss();Hr();var RA=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),SR=new Set(["button","a","input","select","textarea","details","summary"]),AR=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ym=/\b(product|card|item|listing|result)\b/i,Qm=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,xR=3e3,ER=100;function WA(e){let t=typeof e.className=="string"?e.className:"";if(Ym.test(t)||e.id&&Ym.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Ym.test(o.value))return!0}return!1}function OA(e){return Qm.test((e.textContent??"").trim())}function _A(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function MR(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function PA(e){let t=e.match(Qm);return t?t[0]:null}function LA(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 o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o: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 TR(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var kR="commerce-card",PR="result-card";function HA(e){return!WA(e)||!OA(e)||!_A(e)&&!MR(e)?0:5200}function IA(e){return!WA(e)||OA(e)||!_A(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var BA=[{id:kR,scoreElement(e){return HA(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||Qm.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(HA(e)===0)return null;let{title:n,href:o}=LA(e),r=PA((e.textContent??"").trim())??PA(t.text)??"",s=TR(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
141
+ `)}},{id:PR,scoreElement(e){return IA(e)},formatSummary(e,t){if(IA(e)===0)return null;let{title:n,href:o}=LA(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
142
+ `)}}];function LR(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function HR(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,s=t.visibleOnly??e.visibleOnly??!0,i=t.root??e.root,l=t.mode??"structured",c=t.maxCandidates??Math.max(500,n*10),p=e.rules??BA;return l==="simple"&&e.rules&&e.rules.length>0?(LR(),p=[]):l==="simple"&&(p=[]),{mode:l,maxElements:n,maxCandidates:c,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:i,rules:p}}function Xm(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var IR=["data-testid","data-product","data-action","data-id","data-name","data-type"];function RR(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"||SR.has(t)||n&&AR.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function DA(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 WR(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let s=e.getAttribute("type");s&&(t.type=s);let i=e.getAttribute("value");i&&(t.value=i);let l=e.getAttribute("name");l&&(t.name=l);let c=e.getAttribute("role");c&&(t.role=c);for(let p=0;p<e.attributes.length;p++){let d=e.attributes[p];d.name.startsWith("data-")&&(t[d.name]=d.value)}return t}function NA(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${Xm(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of IR){let s=e.getAttribute(r);if(s){let i=`${t}[${r}="${Xm(s)}"]`;try{if(e.ownerDocument.querySelectorAll(i).length===1)return i}catch{}}}let n=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(n.length>0){let r=`${t}.${n.map(i=>Xm(i)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let s=e.parentElement;if(s){let l=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(l>=0){let c=`${r}:nth-of-type(${l+1})`;try{if(e.ownerDocument.querySelectorAll(c).length===1)return c}catch{}}}}let o=e.parentElement;if(o){let s=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function OR(e){return e==="static"?ER:xR}function FA(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:NA(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:RR(e),attributes:WR(e)}}function _R(e,t,n,o){let r=OR(t.interactivity),s=null;for(let i of n){let l=i.scoreElement(e,t,o);l>0&&(r+=l,i.formatSummary&&!s&&(s=i))}return{score:r,formattingRule:s}}function BR(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 DR(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],s=0,i=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),l=i.currentNode;for(;l&&r.length<e.maxCandidates;){if(l.nodeType===Node.ELEMENT_NODE){let p=l,d=p.tagName.toLowerCase();if(RA.has(d)){l=i.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){l=i.nextNode();continue}}catch{}if(e.visibleOnly&&!DA(p)){l=i.nextNode();continue}let g=FA(p,e.maxTextLength),f=g.text.length>0,h=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(C=>C==="role");if(!f&&!h){l=i.nextNode();continue}if(o.has(g.selector)){l=i.nextNode();continue}o.add(g.selector);let{score:y,formattingRule:b}=_R(p,g,e.rules,n);r.push({el:p,domIndex:s,enriched:g,score:y,formattingRule:b}),s+=1}l=i.nextNode()}r.sort((p,d)=>{let g=p.enriched.interactivity==="static"?1:0,f=d.enriched.interactivity==="static"?1:0;return g!==f?g-f:d.score!==p.score?d.score-p.score:p.domIndex-d.domIndex});let c=[];for(let p of r){if(c.length>=e.maxElements)break;BR(c,p)||c.push(p)}return c.sort((p,d)=>{let g=p.enriched.interactivity==="static"?1:0,f=d.enriched.interactivity==="static"?1:0;return g!==f?g-f:g===1&&d.score!==p.score?d.score-p.score:p.domIndex-d.domIndex}),c.map(p=>{let d;if(p.formattingRule?.formatSummary){let f=p.formattingRule.formatSummary(p.el,p.enriched,n);f&&(d=f)}let g={...p.enriched};return d&&(g.formattedSummary=d),g})}function NR(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=r.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let c=s,p=c.tagName.toLowerCase();if(RA.has(p)){s=r.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!DA(c)){s=r.nextNode();continue}let d=FA(c,e.maxTextLength),g=d.text.length>0,f=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(h=>h==="role");if(!g&&!f){s=r.nextNode();continue}o.has(d.selector)||(o.add(d.selector),n.push(d))}s=r.nextNode()}let i=[],l=[];for(let c of n)c.interactivity!=="static"?i.push(c):l.push(c);return[...i,...l].slice(0,e.maxElements)}function FR(e={}){let t=HR(e),n=t.root??document.body;return n?t.mode==="simple"?NR(t,n):DR(t,n):[]}var Up=100;function $R(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let s=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);s.length>0&&o.push(`Structured summaries:
143
143
  ${s.map(i=>`- ${i.split(`
144
144
  `).join(`
145
145
  `)}`).join(`
146
- `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let s of e)n==="structured"&&s.formattedSummary||r[s.interactivity].push(s);if(r.clickable.length>0){let s=r.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Fp)}" (clickable)`);o.push(`Interactive elements:
146
+ `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let s of e)n==="structured"&&s.formattedSummary||r[s.interactivity].push(s);if(r.clickable.length>0){let s=r.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Up)}" (clickable)`);o.push(`Interactive elements:
147
147
  ${s.join(`
148
- `)}`)}if(r.navigable.length>0){let s=r.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Fp)}" (navigable)`);o.push(`Navigation links:
148
+ `)}`)}if(r.navigable.length>0){let s=r.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Up)}" (navigable)`);o.push(`Navigation links:
149
149
  ${s.join(`
150
- `)}`)}if(r.input.length>0){let s=r.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Fp)}" (input)`);o.push(`Form inputs:
150
+ `)}`)}if(r.input.length>0){let s=r.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Up)}" (input)`);o.push(`Form inputs:
151
151
  ${s.join(`
152
- `)}`)}if(r.static.length>0){let s=r.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Fp)}"`);o.push(`Content:
152
+ `)}`)}if(r.static.length>0){let s=r.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Up)}"`);o.push(`Content:
153
153
  ${s.join(`
154
154
  `)}`)}return o.join(`
155
155
 
156
- `)}oa();Tt();bo();bo();var BR={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"}}},_A={components:{panel:{borderRadius:"0",shadow:"none"}}},DA={id:"shop",label:"Shopping Assistant",config:{theme:BR,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:aa},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"]}},NA={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:_A}},FA={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:_A}},$A={shop:DA,minimal:NA,fullscreen:FA};function _R(e){return $A[e]}var DR=xA;function NR(){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 FR(){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 $R(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:or(e.colors.primary,.95),100:or(e.colors.primary,.9),200:or(e.colors.primary,.8),300:or(e.colors.primary,.7),400:or(e.colors.primary,.6),500:e.colors.primary,600:or(e.colors.primary,.8),700:or(e.colors.primary,.7),800:or(e.colors.primary,.6),900:or(e.colors.primary,.5),950:or(e.colors.primary,.45)}}),{...t,palette:n}}}}function UR(){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 VR(){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 or(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),i=Math.round(o+(255-o)*(1-t)),l=Math.round(r+(255-r)*(1-t));return`#${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}`}function jR(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}oa();function Ym(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,n=>`%${n.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Jn}/dist`}function Br(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function qR(e){if(e)return{getHeaders:Br(e.getHeaders),onFeedback:Br(e.onFeedback),onCopy:Br(e.onCopy),requestMiddleware:Br(e.requestMiddleware),actionHandlers:Br(e.actionHandlers),actionParsers:Br(e.actionParsers),postprocessMessage:Br(e.postprocessMessage),contextProviders:Br(e.contextProviders),streamParser:Br(e.streamParser)}}var UA=`({ text, message }: any) => {
156
+ `)}oa();Tt();vo();vo();var UR={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"}}},$A={components:{panel:{borderRadius:"0",shadow:"none"}}},UA={id:"shop",label:"Shopping Assistant",config:{theme:UR,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:aa},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"]}},VA={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:$A}},jA={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:$A}},qA={shop:UA,minimal:VA,fullscreen:jA};function VR(e){return qA[e]}var jR=kA;function qR(){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 zR(){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 KR(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:or(e.colors.primary,.95),100:or(e.colors.primary,.9),200:or(e.colors.primary,.8),300:or(e.colors.primary,.7),400:or(e.colors.primary,.6),500:e.colors.primary,600:or(e.colors.primary,.8),700:or(e.colors.primary,.7),800:or(e.colors.primary,.6),900:or(e.colors.primary,.5),950:or(e.colors.primary,.45)}}),{...t,palette:n}}}}function GR(){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 YR(){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 or(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),i=Math.round(o+(255-o)*(1-t)),l=Math.round(r+(255-r)*(1-t));return`#${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}`}function XR(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}oa();function Jm(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,n=>`%${n.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Zn}/dist`}function _r(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function QR(e){if(e)return{getHeaders:_r(e.getHeaders),onFeedback:_r(e.onFeedback),onCopy:_r(e.onCopy),requestMiddleware:_r(e.requestMiddleware),actionHandlers:_r(e.actionHandlers),actionParsers:_r(e.actionParsers),postprocessMessage:_r(e.postprocessMessage),contextProviders:_r(e.contextProviders),streamParser:_r(e.streamParser)}}var zA=`({ text, message }: any) => {
157
157
  const jsonSource = (message as any).rawContent || text || message.content;
158
158
  if (!jsonSource || typeof jsonSource !== 'string') return null;
159
159
  let cleanJson = jsonSource
@@ -166,7 +166,7 @@ ${s.join(`
166
166
  if (parsed.action) return { type: parsed.action, payload: parsed };
167
167
  } catch (e) { return null; }
168
168
  return null;
169
- }`,VA=`function(ctx) {
169
+ }`,KA=`function(ctx) {
170
170
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
171
171
  if (!jsonSource || typeof jsonSource !== 'string') return null;
172
172
  var cleanJson = jsonSource
@@ -179,7 +179,7 @@ ${s.join(`
179
179
  if (parsed.action) return { type: parsed.action, payload: parsed };
180
180
  } catch (e) { return null; }
181
181
  return null;
182
- }`,jA=`(action: any, context: any) => {
182
+ }`,GA=`(action: any, context: any) => {
183
183
  if (action.type !== 'nav_then_click') return;
184
184
  const payload = action.payload || action.raw || {};
185
185
  const url = payload?.page;
@@ -196,7 +196,7 @@ ${s.join(`
196
196
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
197
197
  window.location.href = targetUrl;
198
198
  return { handled: true, displayText: text };
199
- }`,qA=`function(action, context) {
199
+ }`,YA=`function(action, context) {
200
200
  if (action.type !== 'nav_then_click') return;
201
201
  var payload = action.payload || action.raw || {};
202
202
  var url = payload.page;
@@ -213,27 +213,27 @@ ${s.join(`
213
213
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
214
214
  window.location.href = targetUrl;
215
215
  return { handled: true, displayText: text };
216
- }`,zR=`(parsed: any) => {
216
+ }`,JR=`(parsed: any) => {
217
217
  if (!parsed || typeof parsed !== 'object') return null;
218
218
  if (parsed.action === 'nav_then_click') return 'Navigating...';
219
219
  if (parsed.action === 'message') return parsed.text || '';
220
220
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
221
221
  return parsed.text || null;
222
- }`,KR=`function(parsed) {
222
+ }`,ZR=`function(parsed) {
223
223
  if (!parsed || typeof parsed !== 'object') return null;
224
224
  if (parsed.action === 'nav_then_click') return 'Navigating...';
225
225
  if (parsed.action === 'message') return parsed.text || '';
226
226
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
227
227
  return parsed.text || null;
228
- }`;function GR(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 $p(e){return e.parserType??GR(e.streamParser)??"plain"}function Up(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([o,r])=>{typeof r=="string"&&n.push(`${t} ${o}: "${r}",`)}),n.push(`${t}},`)),n}function Vp(e,t,n){let o=[],r=e.messageActions&&Object.entries(e.messageActions).some(([i,l])=>i!=="onFeedback"&&i!=="onCopy"&&l!==void 0),s=n?.onFeedback||n?.onCopy;return(r||s)&&(o.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,l])=>{i==="onFeedback"||i==="onCopy"||(typeof l=="string"?o.push(`${t} ${i}: "${l}",`):typeof l=="boolean"&&o.push(`${t} ${i}: ${l},`))}),n?.onFeedback&&o.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&o.push(`${t} onCopy: ${n.onCopy},`),o.push(`${t}},`)),o}function jp(e,t){let n=[];if(e.markdown){let o=e.markdown.options&&Object.keys(e.markdown.options).length>0,r=e.markdown.disableDefaultStyles!==void 0;(o||r)&&(n.push(`${t}markdown: {`),o&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,i])=>{typeof i=="string"?n.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&n.push(`${t} ${s}: ${i},`)}),n.push(`${t} },`)),r&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function qp(e,t){if(!e.suggestions)return[];let n=JSON.stringify(e.suggestions,null,2).split(`
229
- `);return n.map((o,r)=>{let s=r===0?`${t}suggestions: `:t,i=r===n.length-1?",":"";return`${s}${o}${i}`})}function zp(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(o||r)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?n.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&n.push(`${t} ${s}: ${i},`))}),n.push(`${t} },`)),r&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(n.push(`${t} avatar: {`),Object.entries(i).forEach(([l,c])=>{typeof c=="string"?n.push(`${t} ${l}: "${c}",`):typeof c=="boolean"&&n.push(`${t} ${l}: ${c},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([c])=>c!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(i).forEach(([c,p])=>{c!=="format"&&(typeof p=="string"?n.push(`${t} ${c}: "${p}",`):typeof p=="boolean"&&n.push(`${t} ${c}: ${p},`))}),n.push(`${t} },`)):typeof i=="string"?n.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&n.push(`${t} ${s}: ${i},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Xm(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 zA(e,t,n){Object.entries(t).forEach(([o,r])=>{if(!(r===void 0||typeof r=="function")){if(Array.isArray(r)){e.push(`${n}${o}: ${JSON.stringify(r)},`);return}if(r&&typeof r=="object"){e.push(`${n}${o}: {`),zA(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function Ss(e,t,n,o){n&&(e.push(`${o}${t}: {`),zA(e,n,`${o} `),e.push(`${o}},`))}function Kp(e,t,n){t.future?.v5Defaults!==void 0&&e.push(`${n}future: { v5Defaults: ${t.future.v5Defaults===!0} },`)}function Yl(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function YR(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:qR(n.hooks)}:void 0;return t==="esm"?XR(o,r):t==="script-installer"?ZR(o,r):t==="script-advanced"?tW(o,r):t==="react-component"?QR(o,r):t==="react-advanced"?JR(o,r):eW(o,r)}function XR(e,t){let n=t?.hooks,o=$p(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Yl(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),Kp(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ss(s,"theme",e.theme," "),e.launcher&&Ss(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,l])=>{s.push(` ${i}: "${l}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"?s.push(` ${i}: ${l},`):typeof l=="number"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,l])=>{s.push(` ${i}: ${l},`)}),s.push(" },")),s.push(...qp(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Up(e," ")),s.push(...Vp(e," ",n)),s.push(...jp(e," ")),s.push(...zp(e," ")),s.push(...Xm(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
230
- `)}function QR(e,t){let n=t?.hooks,o=$p(e),r=o!=="plain",s=["// 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: '${Yl(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),Kp(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ss(s,"theme",e.theme," "),e.launcher&&Ss(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,l])=>{s.push(` ${i}: "${l}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"?s.push(` ${i}: ${l},`):typeof l=="number"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,l])=>{s.push(` ${i}: ${l},`)}),s.push(" },")),s.push(...qp(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Up(e," ")),s.push(...Vp(e," ",n)),s.push(...jp(e," ")),s.push(...zp(e," ")),s.push(...Xm(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
231
- `)}function JR(e,t){let n=t?.hooks,o=["// 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: '${Yl(t)}',`," 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}",`),Kp(o,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ss(o,"theme",e.theme," "),e.launcher&&Ss(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{o.push(` ${r}: "${s}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"?o.push(` ${r}: ${s},`):typeof s=="number"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{o.push(` ${r}: ${s},`)}),o.push(" },")),o.push(...qp(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{o.push(` "${r}",`)}),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(...Up(e," ")),o.push(...Vp(e," ",n)),o.push(...jp(e," ")),o.push(...zp(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${zR}),`)),n?.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),o.push(" // Built-in parser for markdown-wrapped JSON"),o.push(` ${UA}`),o.push(" ],")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" actionParsers: ["),o.push(" defaultJsonActionParser,"),o.push(" // Parser for markdown-wrapped JSON"),o.push(` ${UA}`),o.push(" ],")),n?.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` actionHandlers: [...(${n.actionHandlers}),`),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Built-in handler for nav_then_click action"),o.push(` ${jA}`),o.push(" ],")):(o.push(" // Action handlers for navigation and other actions"),o.push(" actionHandlers: ["),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Handler for nav_then_click action"),o.push(` ${jA}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
232
- `)}function KA(e){let t=$p(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.future?.v5Defaults!==void 0&&(o.future={v5Defaults:e.future.v5Defaults===!0}),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestions&&(o.suggestions=e.suggestions),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let r={};Object.entries(e.toolCall).forEach(([s,i])=>{typeof i=="string"&&(r[s]=i)}),Object.keys(r).length>0&&(o.toolCall=r)}if(e.messageActions){let r={};Object.entries(e.messageActions).forEach(([s,i])=>{s!=="onFeedback"&&s!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(r[s]=i)}),Object.keys(r).length>0&&(o.messageActions=r)}if(e.markdown){let r={};e.markdown.options&&(r.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(r.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(r).length>0&&(o.markdown=r)}if(e.layout){let r={};if(e.layout.header){let s={};Object.entries(e.layout.header).forEach(([i,l])=>{i!=="render"&&(typeof l=="string"||typeof l=="boolean")&&(s[i]=l)}),Object.keys(s).length>0&&(r.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([i,l])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof l=="object"&&l!==null)s.avatar=l;else if(i==="timestamp"&&typeof l=="object"&&l!==null){let c={};Object.entries(l).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"||typeof d=="boolean")&&(c[p]=d)}),Object.keys(c).length>0&&(s.timestamp=c)}else(typeof l=="string"||typeof l=="boolean")&&(s[i]=l)}),Object.keys(s).length>0&&(r.messages=s)}Object.keys(r).length>0&&(o.layout=r)}return o}function ZR(e,t){let n=KA(e),r=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="${Ym(t)}/install.global.js" data-config='${s}'></script>`}function eW(e,t){let n=t?.hooks,o=$p(e),r=o!=="plain",s=Ym(t),i=["<!-- Load CSS -->",`<link rel="stylesheet" href="${s}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${s}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Yl(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&i.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&i.push(` clientToken: "${e.clientToken}",`),e.agentId&&i.push(` agentId: "${e.agentId}",`),e.target&&i.push(` target: "${e.target}",`),e.flowId&&i.push(` flowId: "${e.flowId}",`),r&&i.push(` parserType: "${o}",`),Kp(i,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ss(i,"theme",e.theme," "),e.launcher&&Ss(i,"launcher",e.launcher," "),e.copy&&(i.push(" copy: {"),Object.entries(e.copy).forEach(([l,c])=>{i.push(` ${l}: "${c}",`)}),i.push(" },")),e.sendButton&&(i.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([l,c])=>{typeof c=="string"?i.push(` ${l}: "${c}",`):typeof c=="boolean"&&i.push(` ${l}: ${c},`)}),i.push(" },")),e.voiceRecognition&&(i.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([l,c])=>{typeof c=="string"?i.push(` ${l}: "${c}",`):typeof c=="boolean"?i.push(` ${l}: ${c},`):typeof c=="number"&&i.push(` ${l}: ${c},`)}),i.push(" },")),e.statusIndicator&&(i.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([l,c])=>{typeof c=="string"?i.push(` ${l}: "${c}",`):typeof c=="boolean"&&i.push(` ${l}: ${c},`)}),i.push(" },")),e.features&&(i.push(" features: {"),Object.entries(e.features).forEach(([l,c])=>{i.push(` ${l}: ${c},`)}),i.push(" },")),i.push(...qp(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(i.push(" suggestionChips: ["),e.suggestionChips.forEach(l=>{i.push(` "${l}",`)}),i.push(" ],")),e.suggestionChipsConfig&&(i.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&i.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&i.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&i.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&i.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),i.push(" },")),i.push(...Up(e," ")),i.push(...Vp(e," ",n)),i.push(...jp(e," ")),i.push(...zp(e," ")),i.push(...Xm(n," ")),e.debug&&i.push(` debug: ${e.debug},`),n?.postprocessMessage?i.push(` postprocessMessage: ${n.postprocessMessage}`):i.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),i.push(" }"),i.push(" });"),i.push("</script>"),i.join(`
233
- `)}function tW(e,t){let n=t?.hooks,o=KA(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
228
+ }`;function eW(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 Vp(e){return e.parserType??eW(e.streamParser)??"plain"}function jp(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([o,r])=>{typeof r=="string"&&n.push(`${t} ${o}: "${r}",`)}),n.push(`${t}},`)),n}function qp(e,t,n){let o=[],r=e.messageActions&&Object.entries(e.messageActions).some(([i,l])=>i!=="onFeedback"&&i!=="onCopy"&&l!==void 0),s=n?.onFeedback||n?.onCopy;return(r||s)&&(o.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,l])=>{i==="onFeedback"||i==="onCopy"||(typeof l=="string"?o.push(`${t} ${i}: "${l}",`):typeof l=="boolean"&&o.push(`${t} ${i}: ${l},`))}),n?.onFeedback&&o.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&o.push(`${t} onCopy: ${n.onCopy},`),o.push(`${t}},`)),o}function zp(e,t){let n=[];if(e.markdown){let o=e.markdown.options&&Object.keys(e.markdown.options).length>0,r=e.markdown.disableDefaultStyles!==void 0;(o||r)&&(n.push(`${t}markdown: {`),o&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,i])=>{typeof i=="string"?n.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&n.push(`${t} ${s}: ${i},`)}),n.push(`${t} },`)),r&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Kp(e,t){if(!e.suggestions)return[];let n=JSON.stringify(e.suggestions,null,2).split(`
229
+ `);return n.map((o,r)=>{let s=r===0?`${t}suggestions: `:t,i=r===n.length-1?",":"";return`${s}${o}${i}`})}function Gp(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(o||r)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?n.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&n.push(`${t} ${s}: ${i},`))}),n.push(`${t} },`)),r&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(n.push(`${t} avatar: {`),Object.entries(i).forEach(([l,c])=>{typeof c=="string"?n.push(`${t} ${l}: "${c}",`):typeof c=="boolean"&&n.push(`${t} ${l}: ${c},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([c])=>c!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(i).forEach(([c,p])=>{c!=="format"&&(typeof p=="string"?n.push(`${t} ${c}: "${p}",`):typeof p=="boolean"&&n.push(`${t} ${c}: ${p},`))}),n.push(`${t} },`)):typeof i=="string"?n.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&n.push(`${t} ${s}: ${i},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Zm(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 XA(e,t,n){Object.entries(t).forEach(([o,r])=>{if(!(r===void 0||typeof r=="function")){if(Array.isArray(r)){e.push(`${n}${o}: ${JSON.stringify(r)},`);return}if(r&&typeof r=="object"){e.push(`${n}${o}: {`),XA(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function Ss(e,t,n,o){n&&(e.push(`${o}${t}: {`),XA(e,n,`${o} `),e.push(`${o}},`))}function Yp(e,t,n){t.future?.v5Defaults!==void 0&&e.push(`${n}future: { v5Defaults: ${t.future.v5Defaults===!0} },`)}function Xl(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function tW(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:QR(n.hooks)}:void 0;return t==="esm"?nW(o,r):t==="script-installer"?sW(o,r):t==="script-advanced"?aW(o,r):t==="react-component"?oW(o,r):t==="react-advanced"?rW(o,r):iW(o,r)}function nW(e,t){let n=t?.hooks,o=Vp(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Xl(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),Yp(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ss(s,"theme",e.theme," "),e.launcher&&Ss(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,l])=>{s.push(` ${i}: "${l}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"?s.push(` ${i}: ${l},`):typeof l=="number"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,l])=>{s.push(` ${i}: ${l},`)}),s.push(" },")),s.push(...Kp(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...jp(e," ")),s.push(...qp(e," ",n)),s.push(...zp(e," ")),s.push(...Gp(e," ")),s.push(...Zm(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
230
+ `)}function oW(e,t){let n=t?.hooks,o=Vp(e),r=o!=="plain",s=["// 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: '${Xl(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),Yp(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ss(s,"theme",e.theme," "),e.launcher&&Ss(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,l])=>{s.push(` ${i}: "${l}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"?s.push(` ${i}: ${l},`):typeof l=="number"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,l])=>{s.push(` ${i}: ${l},`)}),s.push(" },")),s.push(...Kp(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...jp(e," ")),s.push(...qp(e," ",n)),s.push(...zp(e," ")),s.push(...Gp(e," ")),s.push(...Zm(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
231
+ `)}function rW(e,t){let n=t?.hooks,o=["// 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: '${Xl(t)}',`," 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}",`),Yp(o,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ss(o,"theme",e.theme," "),e.launcher&&Ss(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{o.push(` ${r}: "${s}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"?o.push(` ${r}: ${s},`):typeof s=="number"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{o.push(` ${r}: ${s},`)}),o.push(" },")),o.push(...Kp(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{o.push(` "${r}",`)}),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(...jp(e," ")),o.push(...qp(e," ",n)),o.push(...zp(e," ")),o.push(...Gp(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${JR}),`)),n?.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),o.push(" // Built-in parser for markdown-wrapped JSON"),o.push(` ${zA}`),o.push(" ],")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" actionParsers: ["),o.push(" defaultJsonActionParser,"),o.push(" // Parser for markdown-wrapped JSON"),o.push(` ${zA}`),o.push(" ],")),n?.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` actionHandlers: [...(${n.actionHandlers}),`),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Built-in handler for nav_then_click action"),o.push(` ${GA}`),o.push(" ],")):(o.push(" // Action handlers for navigation and other actions"),o.push(" actionHandlers: ["),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Handler for nav_then_click action"),o.push(` ${GA}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
232
+ `)}function QA(e){let t=Vp(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.future?.v5Defaults!==void 0&&(o.future={v5Defaults:e.future.v5Defaults===!0}),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestions&&(o.suggestions=e.suggestions),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let r={};Object.entries(e.toolCall).forEach(([s,i])=>{typeof i=="string"&&(r[s]=i)}),Object.keys(r).length>0&&(o.toolCall=r)}if(e.messageActions){let r={};Object.entries(e.messageActions).forEach(([s,i])=>{s!=="onFeedback"&&s!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(r[s]=i)}),Object.keys(r).length>0&&(o.messageActions=r)}if(e.markdown){let r={};e.markdown.options&&(r.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(r.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(r).length>0&&(o.markdown=r)}if(e.layout){let r={};if(e.layout.header){let s={};Object.entries(e.layout.header).forEach(([i,l])=>{i!=="render"&&(typeof l=="string"||typeof l=="boolean")&&(s[i]=l)}),Object.keys(s).length>0&&(r.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([i,l])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof l=="object"&&l!==null)s.avatar=l;else if(i==="timestamp"&&typeof l=="object"&&l!==null){let c={};Object.entries(l).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"||typeof d=="boolean")&&(c[p]=d)}),Object.keys(c).length>0&&(s.timestamp=c)}else(typeof l=="string"||typeof l=="boolean")&&(s[i]=l)}),Object.keys(s).length>0&&(r.messages=s)}Object.keys(r).length>0&&(o.layout=r)}return o}function sW(e,t){let n=QA(e),r=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="${Jm(t)}/install.global.js" data-config='${s}'></script>`}function iW(e,t){let n=t?.hooks,o=Vp(e),r=o!=="plain",s=Jm(t),i=["<!-- Load CSS -->",`<link rel="stylesheet" href="${s}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${s}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Xl(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&i.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&i.push(` clientToken: "${e.clientToken}",`),e.agentId&&i.push(` agentId: "${e.agentId}",`),e.target&&i.push(` target: "${e.target}",`),e.flowId&&i.push(` flowId: "${e.flowId}",`),r&&i.push(` parserType: "${o}",`),Yp(i,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ss(i,"theme",e.theme," "),e.launcher&&Ss(i,"launcher",e.launcher," "),e.copy&&(i.push(" copy: {"),Object.entries(e.copy).forEach(([l,c])=>{i.push(` ${l}: "${c}",`)}),i.push(" },")),e.sendButton&&(i.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([l,c])=>{typeof c=="string"?i.push(` ${l}: "${c}",`):typeof c=="boolean"&&i.push(` ${l}: ${c},`)}),i.push(" },")),e.voiceRecognition&&(i.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([l,c])=>{typeof c=="string"?i.push(` ${l}: "${c}",`):typeof c=="boolean"?i.push(` ${l}: ${c},`):typeof c=="number"&&i.push(` ${l}: ${c},`)}),i.push(" },")),e.statusIndicator&&(i.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([l,c])=>{typeof c=="string"?i.push(` ${l}: "${c}",`):typeof c=="boolean"&&i.push(` ${l}: ${c},`)}),i.push(" },")),e.features&&(i.push(" features: {"),Object.entries(e.features).forEach(([l,c])=>{i.push(` ${l}: ${c},`)}),i.push(" },")),i.push(...Kp(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(i.push(" suggestionChips: ["),e.suggestionChips.forEach(l=>{i.push(` "${l}",`)}),i.push(" ],")),e.suggestionChipsConfig&&(i.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&i.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&i.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&i.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&i.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),i.push(" },")),i.push(...jp(e," ")),i.push(...qp(e," ",n)),i.push(...zp(e," ")),i.push(...Gp(e," ")),i.push(...Zm(n," ")),e.debug&&i.push(` debug: ${e.debug},`),n?.postprocessMessage?i.push(` postprocessMessage: ${n.postprocessMessage}`):i.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),i.push(" }"),i.push(" });"),i.push("</script>"),i.join(`
233
+ `)}function aW(e,t){let n=t?.hooks,o=QA(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
234
234
  `).map((i,l)=>l===0?i:" "+i).join(`
235
- `)};`,""," // Constants",` var CDN_BASE = '${Ym(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&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n?.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n?.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${KR});`),s.push(" };")),s.push(""),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${VA}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${VA}`),s.push(" ];")),s.push(""),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${qA}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${qA}`),s.push(" ];")),s.push(""),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n?.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n?.onFeedback||n?.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.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: '${Yl(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>"),s.join(`
236
- `)}Xe();Mr();import{ChevronDown as nW}from"lucide";var GA={desktop:{w:1280,h:800},mobile:{w:390,h:844}},YA=.1,XA=.15,QA=1.5,Qm=24,JA=40,oW=`
235
+ `)};`,""," // Constants",` var CDN_BASE = '${Jm(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&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n?.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n?.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${ZR});`),s.push(" };")),s.push(""),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${KA}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${KA}`),s.push(" ];")),s.push(""),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${YA}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${YA}`),s.push(" ];")),s.push(""),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n?.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n?.onFeedback||n?.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.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: '${Xl(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>"),s.join(`
236
+ `)}Qe();Er();import{ChevronDown as lW}from"lucide";var JA={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ZA=.1,ex=.15,tx=1.5,eh=24,nx=40,cW=`
237
237
  /* \u2500\u2500 Root \u2500\u2500 */
238
238
  .persona-dc-root {
239
239
  display: flex;
@@ -384,7 +384,7 @@ ${s.join(`
384
384
  .persona-dc-stage {
385
385
  height: 550px;
386
386
  min-height: 400px;
387
- padding: ${Qm}px;
387
+ padding: ${eh}px;
388
388
  overflow: auto;
389
389
  background: #f0f1f3;
390
390
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -474,14 +474,14 @@ ${s.join(`
474
474
  min-height: 300px;
475
475
  }
476
476
  }
477
- `;function rW(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=oW,document.head.appendChild(e)}function sW(e,t){let n=e.clientWidth-Qm*2-JA,o=e.clientHeight-Qm*2-JA;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function iW(e,t,n,o,r){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=r==="mobile"?`${32*o}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${o})`}function aW(e,t){let{items:n,initialIndex:o=0,initialDevice:r="desktop",initialColorScheme:s="light",showZoomControls:i=!0,showDeviceToggle:l=!0,showColorSchemeToggle:c=!0,onChange:p}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");rW();let d=Math.max(0,Math.min(o,n.length-1)),g=r,f=s,h=null,y=1,v=!1,C=x("div","persona-dc-root"),A=x("div","persona-dc-toolbar"),L=x("div","persona-dc-toolbar-lead"),I=x("div","persona-dc-toolbar-trail"),H=oo({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>We(-1)}),_=x("div");_.style.position="relative";let V=x("button","persona-dc-title-btn");V.type="button",V.setAttribute("aria-expanded","false"),V.setAttribute("aria-haspopup","listbox");let te=x("span","persona-dc-title-text"),W=x("span","persona-dc-title-chevron"),j=_t(nW,12,"currentColor",2);j&&W.appendChild(j),V.append(te,W);let Y=x("div","persona-dc-dropdown");Y.setAttribute("role","listbox"),Y.style.display="none";let E=!1;function T(){Y.innerHTML="";for(let Se=0;Se<n.length;Se++){let It=n[Se],yt=x("button","persona-dc-dropdown-item");yt.type="button",yt.setAttribute("role","option"),yt.setAttribute("aria-current",Se===d?"true":"false");let Pe=x("span");if(Pe.textContent=It.title,yt.appendChild(Pe),It.description){let Ke=x("span","persona-dc-dropdown-desc");Ke.textContent=It.description,yt.appendChild(Ke)}yt.addEventListener("click",()=>{P(),me(Se)}),Y.appendChild(yt)}}function B(){E=!E,Y.style.display=E?"":"none",V.setAttribute("aria-expanded",E?"true":"false"),E&&T()}function P(){E&&(E=!1,Y.style.display="none",V.setAttribute("aria-expanded","false"))}V.addEventListener("click",Se=>{Se.stopPropagation(),B()});let Q=()=>P();document.addEventListener("click",Q),_.append(V,Y);let U=oo({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>We(1)}),de=x("span","persona-dc-counter");L.append(H,_,U,de);let pe=null;l&&(pe=Cp({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:g,onSelect:Se=>{g=Se,mt.dataset.device=g,h=null,dt()}}),I.appendChild(pe.element));let ge=null;if(i){let Se=x("div","persona-dc-zoom-controls"),It=oo({icon:"minus",label:"Zoom out",size:14,onClick:()=>{h=Math.max(XA,(h??y)-YA),dt()}});ge=x("span","persona-dc-zoom-level"),ge.title="Reset to 100%",ge.style.cursor="pointer",ge.addEventListener("click",()=>{h=1,dt()});let yt=oo({icon:"plus",label:"Zoom in",size:14,onClick:()=>{h=Math.min(QA,(h??y)+YA),dt()}}),Pe=oo({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{h=null,dt()}});Se.append(It,ge,yt,Pe),I.appendChild(Se)}if(c){let Se=x("div","persona-dc-separator");I.appendChild(Se);let It=Cp({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:yt=>{f=yt,mt.dataset.colorScheme=f,Re()}});I.appendChild(It.element)}let ke=x("div","persona-dc-separator");I.appendChild(ke);let xe=oo({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[d].url,"_blank")}});I.appendChild(xe),A.append(L,I);let Le=x("div","persona-dc-stage"),mt=x("div","persona-dc-iframe-wrapper");mt.dataset.device=g,mt.dataset.colorScheme=f;let Ve=x("iframe","persona-dc-iframe");Ve.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),Ve.setAttribute("loading","lazy"),Ve.title=n[d].title,mt.appendChild(Ve),Le.appendChild(mt),C.append(A,Le),e.appendChild(C);function Re(){try{let Se=Ve.contentDocument?.body;if(!Se)return;f==="dark"?Se.classList.add("theme-dark"):Se.classList.remove("theme-dark")}catch{}}Ve.addEventListener("load",()=>Re());function $(){let Se=n[d];te.textContent=Se.title,de.textContent=`${d+1} / ${n.length}`,Ve.title=Se.title}function We(Se){let It=((d+Se)%n.length+n.length)%n.length;me(It)}function me(Se){Se<0||Se>=n.length||(d=Se,Ve.src=n[d].url,$(),p?.(d,n[d]))}function dt(){if(v)return;let Se=GA[g]??GA.desktop;y=sW(Le,Se);let It=Math.max(XA,Math.min(QA,h??y));iW(mt,Ve,Se,It,g),ge&&(ge.textContent=`${Math.round(It*100)}%`)}let Qt=new ResizeObserver(()=>dt());Qt.observe(Le),$(),Ve.src=n[d].url,requestAnimationFrame(()=>dt());function St(){v||(v=!0,Qt.disconnect(),document.removeEventListener("click",Q),C.remove())}return{element:C,goTo:me,next:()=>We(1),prev:()=>We(-1),getIndex:()=>d,setDevice(Se){g=Se,mt.dataset.device=Se,pe?.setSelected(Se),h=null,dt()},setColorScheme(Se){f=Se,mt.dataset.colorScheme=Se},setZoom(Se){h=Se,dt()},destroy:St}}Lf();oa();var Jm=16e3,lW=24e3,cW=4096,dW=Jm*2*8,pW=4,uW=1380533830,gW=3e4,fW=5e3,mW=3e4,hW=3e4,yW=6e5,bW="full-duplex-v1",vW=300,CW=2e3,wW=2e3,SW="runtype-browser-v1",AW=54e4,xW="You're talking to an AI assistant. Voice is processed by OpenAI.",MW=8e3,EW=4e3,TW=12,ZA=2e3;function PW(e,t){let n="Conversation so far:",o=t.slice(0,EW).trim(),r=MW-(o?o.length+2:0)-n.length,s=[];for(let l of e.slice(-TW).reverse()){let c=l.content.replace(/\s+/g," ").trim();if(!c)continue;c.length>ZA&&(c=`${c.slice(0,ZA-1)}\u2026`);let p=`${l.role==="user"?"User":"Assistant"}: ${c}`;if(p.length+1>r)break;r-=p.length+1,s.unshift(p)}let i=s.length>0?[`${n}
477
+ `;function dW(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=cW,document.head.appendChild(e)}function pW(e,t){let n=e.clientWidth-eh*2-nx,o=e.clientHeight-eh*2-nx;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function uW(e,t,n,o,r){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=r==="mobile"?`${32*o}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${o})`}function gW(e,t){let{items:n,initialIndex:o=0,initialDevice:r="desktop",initialColorScheme:s="light",showZoomControls:i=!0,showDeviceToggle:l=!0,showColorSchemeToggle:c=!0,onChange:p}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");dW();let d=Math.max(0,Math.min(o,n.length-1)),g=r,f=s,h=null,y=1,b=!1,C=x("div","persona-dc-root"),A=x("div","persona-dc-toolbar"),L=x("div","persona-dc-toolbar-lead"),I=x("div","persona-dc-toolbar-trail"),H=ro({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>We(-1)}),B=x("div");B.style.position="relative";let V=x("button","persona-dc-title-btn");V.type="button",V.setAttribute("aria-expanded","false"),V.setAttribute("aria-haspopup","listbox");let te=x("span","persona-dc-title-text"),W=x("span","persona-dc-title-chevron"),j=Bt(lW,12,"currentColor",2);j&&W.appendChild(j),V.append(te,W);let Y=x("div","persona-dc-dropdown");Y.setAttribute("role","listbox"),Y.style.display="none";let M=!1;function T(){Y.innerHTML="";for(let Se=0;Se<n.length;Se++){let It=n[Se],yt=x("button","persona-dc-dropdown-item");yt.type="button",yt.setAttribute("role","option"),yt.setAttribute("aria-current",Se===d?"true":"false");let ke=x("span");if(ke.textContent=It.title,yt.appendChild(ke),It.description){let Ge=x("span","persona-dc-dropdown-desc");Ge.textContent=It.description,yt.appendChild(Ge)}yt.addEventListener("click",()=>{k(),me(Se)}),Y.appendChild(yt)}}function _(){M=!M,Y.style.display=M?"":"none",V.setAttribute("aria-expanded",M?"true":"false"),M&&T()}function k(){M&&(M=!1,Y.style.display="none",V.setAttribute("aria-expanded","false"))}V.addEventListener("click",Se=>{Se.stopPropagation(),_()});let Q=()=>k();document.addEventListener("click",Q),B.append(V,Y);let U=ro({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>We(1)}),de=x("span","persona-dc-counter");L.append(H,B,U,de);let pe=null;l&&(pe=Sp({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:g,onSelect:Se=>{g=Se,mt.dataset.device=g,h=null,dt()}}),I.appendChild(pe.element));let ge=null;if(i){let Se=x("div","persona-dc-zoom-controls"),It=ro({icon:"minus",label:"Zoom out",size:14,onClick:()=>{h=Math.max(ex,(h??y)-ZA),dt()}});ge=x("span","persona-dc-zoom-level"),ge.title="Reset to 100%",ge.style.cursor="pointer",ge.addEventListener("click",()=>{h=1,dt()});let yt=ro({icon:"plus",label:"Zoom in",size:14,onClick:()=>{h=Math.min(tx,(h??y)+ZA),dt()}}),ke=ro({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{h=null,dt()}});Se.append(It,ge,yt,ke),I.appendChild(Se)}if(c){let Se=x("div","persona-dc-separator");I.appendChild(Se);let It=Sp({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:yt=>{f=yt,mt.dataset.colorScheme=f,Re()}});I.appendChild(It.element)}let Pe=x("div","persona-dc-separator");I.appendChild(Pe);let Ae=ro({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[d].url,"_blank")}});I.appendChild(Ae),A.append(L,I);let Le=x("div","persona-dc-stage"),mt=x("div","persona-dc-iframe-wrapper");mt.dataset.device=g,mt.dataset.colorScheme=f;let Ve=x("iframe","persona-dc-iframe");Ve.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),Ve.setAttribute("loading","lazy"),Ve.title=n[d].title,mt.appendChild(Ve),Le.appendChild(mt),C.append(A,Le),e.appendChild(C);function Re(){try{let Se=Ve.contentDocument?.body;if(!Se)return;f==="dark"?Se.classList.add("theme-dark"):Se.classList.remove("theme-dark")}catch{}}Ve.addEventListener("load",()=>Re());function $(){let Se=n[d];te.textContent=Se.title,de.textContent=`${d+1} / ${n.length}`,Ve.title=Se.title}function We(Se){let It=((d+Se)%n.length+n.length)%n.length;me(It)}function me(Se){Se<0||Se>=n.length||(d=Se,Ve.src=n[d].url,$(),p?.(d,n[d]))}function dt(){if(b)return;let Se=JA[g]??JA.desktop;y=pW(Le,Se);let It=Math.max(ex,Math.min(tx,h??y));uW(mt,Ve,Se,It,g),ge&&(ge.textContent=`${Math.round(It*100)}%`)}let Qt=new ResizeObserver(()=>dt());Qt.observe(Le),$(),Ve.src=n[d].url,requestAnimationFrame(()=>dt());function St(){b||(b=!0,Qt.disconnect(),document.removeEventListener("click",Q),C.remove())}return{element:C,goTo:me,next:()=>We(1),prev:()=>We(-1),getIndex:()=>d,setDevice(Se){g=Se,mt.dataset.device=Se,pe?.setSelected(Se),h=null,dt()},setColorScheme(Se){f=Se,mt.dataset.colorScheme=Se},setZoom(Se){h=Se,dt()},destroy:St}}Rf();oa();var th=16e3,fW=24e3,mW=4096,hW=th*2*8,yW=4,bW=1380533830,vW=3e4,CW=1e3,wW=5e3,SW=3e4,AW=3e4,xW=6e5,EW="full-duplex-v1",MW=300,TW=2e3,kW=2e3,PW="runtype-browser-v1",LW=54e4,HW="You're talking to an AI assistant. Voice is processed by OpenAI.",IW=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."]]),ox=["provider_error","server_restart"],Xp="Voice connection lost.",RW=8e3,WW=4e3,OW=12,rx=2e3;function _W(e,t){let n="Conversation so far:",o=t.slice(0,WW).trim(),r=RW-(o?o.length+2:0)-n.length,s=[];for(let l of e.slice(-OW).reverse()){let c=l.content.replace(/\s+/g," ").trim();if(!c)continue;c.length>rx&&(c=`${c.slice(0,rx-1)}\u2026`);let p=`${l.role==="user"?"User":"Assistant"}: ${c}`;if(p.length+1>r)break;r-=p.length+1,s.unshift(p)}let i=s.length>0?[`${n}
478
478
  ${s.join(`
479
479
  `)}`]:[];return o&&i.push(o),i.join(`
480
480
 
481
- `)}function kW(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===uW?new Uint8Array(e,44):new Uint8Array(e)}function ex(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 LW(e){return ex(e).replace(/^ws/i,"http")}function HW(e){return typeof e!="number"||!Number.isFinite(e)?mW:Math.min(yW,Math.max(hW,Math.round(e)))}var Xl=class{constructor(t){this.config=t;this.type="runtype";this.#e=null;this.#n=null;this.#o=[];this.#t=null;this.#s=null;this.#r=null;this.#p=[];this.#f=0;this.#i=null;this.#g=!1;this.#l=!1;this.#c=0;this.#a=!1;this.#E=Number.NEGATIVE_INFINITY;this.#h=null;this.#S=!1;this.#v=!1;this.#A=0;this.#d=0;this.#m=!1;this.bridge=null;this.#C=!1;this.#x=new Set;this.#y=new Map;this.#b=new Set;this.#k=!1;this.#M=null;this.#I=null;this.#Y=Promise.resolve();this.#j=new Set;this.#B=!1;this.#T=new Set;this.#K=new Set;this.#_=[];this.#F=[];this.#ee=[];this.#te=[];this.#D=[]}#e;#n;#o;#t;#s;#r;#p;#f;#i;#g;#l;#c;#a;#E;#h;#S;#v;#A;#d;#u;#m;#C;#x;#y;#b;#H;#k;#M;#I;#Y;#j;#B;#T;#K;#_;#F;#ee;#te;#D;async connect(){}setSessionBridge(t){this.bridge=t}prewarm(){if(this.#g||this.#h)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t||!n||!o)return;let r=Date.now();if(!(r-this.#E<gW)){this.#E=r;try{this.config?.prewarmMode==="attach"?this.#Z(o,t,n):this.#X(o,t,n)}catch{}}}#X(t,n,o){if(typeof fetch!="function")return;let r=`${LW(t)}/v1/client/agents/${encodeURIComponent(n)}/voice/prewarm`;fetch(r,{method:"POST",headers:{Authorization:`Bearer ${o}`},keepalive:!0}).catch(()=>{})}#Z(t,n,o){let r=new URLSearchParams,s=this.config?.attachIdleMs,i=HW(s);s!==void 0&&r.set("attachIdleMs",String(i));let l=new WebSocket(this.#de(t,n,r),["runtype.bearer","runtype.attach",o]);l.binaryType="arraybuffer";let c=()=>{},p=new Promise(g=>{c=g}),d={ws:l,state:"connecting",ready:p,settle:c,openedAt:0,idleTimer:void 0};this.#h=d,l.onopen=()=>{this.#h===d&&(d.state=l.protocol==="runtype.attach"?"attached":"live",d.openedAt=Date.now(),this.#ne(d,i),d.state==="attached"&&l.send('{"type":"ping"}'),d.settle())},l.onmessage=g=>{if(this.#h!==d||typeof g.data!="string")return;let f;try{f=JSON.parse(g.data)}catch{return}f.type==="attached"&&typeof f.idleMs=="number"&&this.#ne(d,f.idleMs-(Date.now()-d.openedAt))},l.onerror=()=>{},l.onclose=()=>{this.#h===d&&this.#$()}}#ne(t,n){clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{this.#h===t&&this.#$()},Math.max(0,n))}#$(){let t=this.#h;if(!t)return;this.#h=null,clearTimeout(t.idleTimer);let{ws:n}=t;if(n.onopen=null,n.onmessage=null,n.onerror=null,n.onclose=null,t.settle(),n.readyState===WebSocket.CONNECTING||n.readyState===WebSocket.OPEN)try{n.close(1e3,"prewarm released")}catch{}}async#U(){let t=this.#h;if(!t)return null;if(t.state==="connecting"){let n;await Promise.race([t.ready,new Promise(o=>{n=setTimeout(o,fW)})]),clearTimeout(n)}return this.#h!==t?null:t.state==="connecting"||t.ws.readyState!==WebSocket.OPEN?(this.#$(),null):(this.#h=null,clearTimeout(t.idleTimer),{ws:t.ws,live:t.state==="live"})}#de(t,n,o){let r=["partial_transcript","context"];this.bridge&&this.config?.clientDelegation!==!1&&r.push("client_delegation","delegation_update","delegation_read_back"),o&&r.unshift("attach");let s=new URLSearchParams({voiceProtocol:SW,clientVersion:`persona/${Jn}`,voiceCapabilities:bW,clientCapabilities:r.join(",")});return o?.forEach((i,l)=>s.set(l,i)),`${ex(t)}/ws/agents/${encodeURIComponent(n)}/voice?${s}`}async startListening(){if(this.#g)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.#c;this.#a=!1,this.#g=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Jm,channelCount:1,echoCancellation:!0}});if(r!==this.#c){s.getTracks().forEach(g=>g.stop());return}this.#t=s;let i=window.AudioContext||window.webkitAudioContext,l=new i({sampleRate:Jm});l.state==="suspended"&&await l.resume().catch(()=>{}),this.#n=l;let c=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new ga(lW);if(r!==this.#c){c.destroy(),s.getTracks().forEach(g=>g.stop()),l.close().catch(()=>{});return}this.#i=c,this.#G(),this.#be(l,s,r);let p=await this.#U();if(r!==this.#c){p?.ws.close(1e3,"client ended call");return}if(p){let{ws:g}=p;this.#e=g,this.#W(g,r),p.live||g.send('{"type":"start"}'),this.#oe(g),this.#w("listening");return}let d=new WebSocket(this.#de(o,t),["runtype.bearer",n]);d.binaryType="arraybuffer",this.#e=d,d.onopen=()=>{r===this.#c&&(this.#oe(d),this.#w("listening"))},this.#W(d,r)}catch(s){throw this.#Q(),this.#ie(s),this.#w("error"),s}}#W(t,n){t.onmessage=o=>this.#pe(o,n),t.onerror=()=>{n===this.#c&&(this.#ie(new Error("Voice connection failed")),this.#w("error"),this.#Q())},t.onclose=o=>{if(this.#a){this.#a=!1;return}if(n===this.#c){if(o.code!==1e3){let r=o.code?` (code ${o.code})`:"";this.#ie(new Error(`Voice connection closed${r}`)),this.#w("error")}else this.#w("idle");this.#Q()}}}getDisclosure(){let t=this.config?.disclosureText;return this.#g&&this.#S&&t!==!1?t||xW:null}async stopListening(){this.#Q(),this.#w("idle")}async disconnect(){this.#Q(),this.#w("disconnected"),this.#_=[],this.#F=[],this.#ee=[],this.#te=[],this.#D=[]}stopPlayback(){this.#ve();let t=this.#e;t&&t.readyState===WebSocket.OPEN&&(this.#S&&(this.#A=Date.now()+CW,t.send('{"type":"cancel"}')),this.#w("listening"))}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.#g}onLevel(t){this.#o.push(t)}async deactivateBargeIn(){this.#Q(),this.#w("idle")}#be(t,n,o){let r=t.createMediaStreamSource(n);this.#s=r;let s=t.createScriptProcessor(cW,1,1);this.#r=s,s.onaudioprocess=i=>{if(o!==this.#c)return;let l=this.#e,c=l?.readyState===WebSocket.OPEN;if(l&&!c&&l.readyState!==WebSocket.CONNECTING)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length),g=0;for(let f=0;f<p.length;f++){let h=Math.max(-1,Math.min(1,p[f]));g+=h*h,d[f]=h<0?h*32768:h*32767}if(l&&c)this.#oe(l),l.send(d.buffer);else for(this.#p.push(d.buffer),this.#f+=d.byteLength;this.#f>dW;)this.#f-=this.#p.shift().byteLength;if(this.#o.length>0){let f=Math.sqrt(g/p.length),h=Math.max(0,Math.min(1,f*pW));for(let y of this.#o)y(h)}},r.connect(s),s.connect(t.destination)}#oe(t){for(let n of this.#p)t.send(n);this.#p=[],this.#f=0}#pe(t,n){if(n!==this.#c)return;if(t.data instanceof ArrayBuffer){this.#L(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"session_config":o.speechMode&&(this.#S=o.speechMode==="speech_to_speech",this.#i?.setContinuousMode?.(this.#S)),Array.isArray(o.capabilities)&&(this.#x=new Set(o.capabilities)),typeof o.callId=="string"&&(this.#H=o.callId),this.#C=this.#S&&this.#x.has("client_delegation")&&!!this.bridge,this.#S&&!this.#l&&this.#w("listening"),this.#x.has("context")&&!this.#k&&(this.#k=!0,this.#M=this.#re());break;case"transcript_update":{let r=o.role==="assistant"?"assistant":"user",s=o.utteranceId??o.turnId;if(!s||r==="assistant"&&this.#N())break;let i=String(s);if(r==="user")o.final===!0&&this.#se(n),this.#B=!1;else{if(this.#x.has("delegation_read_back")){let l=o.delegationId;typeof l=="string"&&this.#j.has(l)&&!this.#T.has(i)&&this.#K.add(i)}else this.#B&&!this.#T.has(i)&&(this.#K.add(i),this.#B=!1);if(this.#T.add(i),this.#K.has(i))break}this.#ae(r,o.text??"",o.final===!0,{turnId:i,...typeof o.startMs=="number"&&{startMs:o.startMs},...typeof o.endMs=="number"&&{endMs:o.endMs},...this.#C&&{caption:!0}});break}case"delegation_started":case"delegation_completed":{let r=String(o.delegationId??o.turnId);if(o.type==="delegation_started"){this.#se(n);let s=o.input;this.#C&&s&&this.#O(r,{delegationId:r,userText:String(s.text??""),userUtteranceIds:Array.isArray(s.userUtteranceIds)?s.userUtteranceIds.filter(i=>typeof i=="string"):[],messages:Array.isArray(s.messages)?s.messages:[]},n)}else o.speak!==!1&&this.#j.has(r)&&(this.#B=!0);this.#v=o.type==="delegation_started",!this.#l&&!this.#N()&&this.#w(this.#v?"processing":"listening");break}case"delegation_cancelled":this.#R(String(o.delegationId),o.reason!=="session_ending"&&o.reason!=="provider_cancelled");break;case"warning":console.warn(`[Persona voice] ${o.code}: ${o.message??""}`,this.#H??""),o.delegationId&&(o.code==="UNKNOWN_DELEGATION"||o.code==="LATE_RESULT_LIMIT")&&this.#R(String(o.delegationId));break;case"audio_clear":this.#ve(),this.#A=0,this.#w("listening");break;case"transcript_interim":this.#w("listening"),this.#ae("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.#w(r==="user"?"processing":"speaking"),this.#ae(r,o.text??"",!0);break}case"audio_end":this.#i?this.#i.markStreamEnd():(this.#l=!1,this.#w("listening"));break;case"metrics":this.#we({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.#ie(new Error(o.error||"Voice error")),this.#w("error");break}}async#re(){let t=this.bridge?.getHistory()??[],n="";try{let o=this.config?.callContext;n=String((typeof o=="function"?await o():o)??"")}catch{}return PW(t,n)}#se(t){let n=this.#M;if(!n)return;this.#M=null;let o=!1,r=n.then(s=>{let i=this.#e;o||!s||t!==this.#c||i?.readyState!==WebSocket.OPEN||i.send(JSON.stringify({type:"context",text:s}))});this.#I={done:r,drop:()=>o=!0}}async#q(){let t=this.#I;if(!t)return;let n,o=await Promise.race([t.done.then(()=>!1),new Promise(r=>{n=setTimeout(()=>r(!0),wW)})]);clearTimeout(n),o&&t.drop()}#R(t,n=!1){this.#b.add(t),this.bridge?.dropDelegation?.(t,n),this.#y.get(t)?.abort()}#O(t,n,o){let r=this.bridge,s=(i,l,c)=>{let p=this.#e;return o!==this.#c||p?.readyState!==WebSocket.OPEN||this.#b.has(t)?!1:(p.send(JSON.stringify({type:i,delegationId:t,status:l,text:c})),!0)};this.#Y=this.#Y.then(async()=>{if(o!==this.#c||this.#b.has(t))return;let i=await r.runDelegatedTurn(n).catch(()=>({status:"failed",text:""}));await this.#q();let l=!!i.followUp,c=l&&this.#x.has("delegation_update");if(!s(c?"delegation_update":"delegation_result",l&&!c?"completed":i.status,i.text)||(i.status!=="failed"&&i.inChat!==!1&&this.#j.add(t),!i.followUp))return;let d=new AbortController;this.#y.set(t,d),i.followUp({signal:d.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,AW),readBack:c,onUpdate:g=>s("delegation_update","pending_approval",g)}).then(g=>{this.#y.delete(t),c&&g&&!d.signal.aborted&&s("delegation_result",g.status,g.text)})})}#L(t,n){if(n!==this.#c||!this.#i||this.#N())return;let o=kW(t);o.length!==0&&(this.#l||(this.#l=!0,this.#w("speaking")),this.#G(),this.#i.enqueue(o),this.#S&&this.#xe(o.length))}#N(){return Date.now()<this.#A}#G(){if(this.#m||!this.#i)return;this.#m=!0;let t=this.#c;this.#i.onFinished(()=>{t===this.#c&&(this.#m=!1,this.#ue())})}#xe(t){let n=Date.now();this.#d=Math.max(n,this.#d)+t/48,clearTimeout(this.#u),this.#u=setTimeout(()=>this.#ue(),this.#d-n+vW)}#ue(){this.#l=!1,this.#d=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#w(this.#v?"processing":"listening")}#ve(){this.#i?.flush(),this.#m=!1,this.#G(),this.#l=!1,this.#d=0,clearTimeout(this.#u)}#Q(){this.#c+=1,this.#g=!1,this.#l=!1,this.#$(),this.#S=!1,this.#v=!1,this.#C=!1,this.#x=new Set;for(let t of this.#y.values())t.abort();if(this.#y.clear(),this.#b.clear(),this.#H=void 0,this.#k=!1,this.#M=null,this.#I=null,this.#Y=Promise.resolve(),this.#j.clear(),this.#B=!1,this.#T.clear(),this.#K.clear(),this.#m=!1,this.#A=0,this.#d=0,clearTimeout(this.#u),this.#p=[],this.#f=0,this.#r&&(this.#r.onaudioprocess=null,this.#r.disconnect(),this.#r=null),this.#s&&(this.#s.disconnect(),this.#s=null),this.#t&&(this.#t.getTracks().forEach(t=>t.stop()),this.#t=null),this.#n&&(this.#n.close().catch(()=>{}),this.#n=null),this.#i&&(this.#i.destroy(),this.#i=null),this.#e){this.#a=!0;try{this.#e.close(1e3,"client ended call")}catch{}this.#e=null}}onResult(t){this.#_.push(t)}onError(t){this.#F.push(t)}onStatusChange(t){this.#ee.push(t)}onTranscript(t){this.#te.push(t)}onMetrics(t){this.#D.push(t)}#w(t){this.#ee.forEach(n=>n(t))}#ie(t){this.#F.forEach(n=>n(t))}#ae(t,n,o,r){this.#te.forEach(s=>s(t,n,o,r))}#we(t){this.#D.forEach(n=>n(t))}};var mi=class{constructor(t={}){this.config=t;this.type="browser";this.#e=null;this.#n=[];this.#o=[];this.#t=[];this.#s=!1;this.#r=typeof window<"u"?window:void 0}#e;#n;#o;#t;#s;#r;async connect(){this.#t.forEach(t=>t("connected"))}async startListening(){try{if(this.#s)throw new Error("Already listening");if(!this.#r)throw new Error("Window object not available");let t=this.#r.SpeechRecognition||this.#r.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.#e=new t,this.#e.lang=this.config?.language||"en-US",this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.#n.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=n=>{this.#o.forEach(o=>o(new Error(n.error))),this.#t.forEach(o=>o("error"))},this.#e.onstart=()=>{this.#s=!0,this.#t.forEach(n=>n("listening"))},this.#e.onend=()=>{this.#s=!1,this.#t.forEach(n=>n("idle"))},this.#e.start()}catch(t){throw this.#o.forEach(n=>n(t)),this.#t.forEach(n=>n("error")),t}}async stopListening(){this.#e&&(this.#e.stop(),this.#e=null),this.#s=!1,this.#t.forEach(t=>t("idle"))}onResult(t){this.#n.push(t)}onError(t){this.#o.push(t)}onStatusChange(t){this.#t.push(t)}async disconnect(){await this.stopListening(),this.#t.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Ql(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Xl(e.runtype);case"browser":if(!mi.isSupported())throw new Error("Browser speech recognition not supported");return new mi(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new 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 new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Zm(e){if(e?.type==="custom"&&e.custom)return Ql({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Ql({type:"runtype",runtype:e.runtype});if(mi.isSupported())return Ql({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function tx(e){try{return Zm(e),!0}catch{return!1}}var nx="webmcp:",IW=e=>e.startsWith(nx)?e.slice(nx.length):e,Gp={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Xp=class{constructor(t,n){this.config=t;this.#r=n,this.#e=t.onConfirm??null,this.#n=3e4}#e;#n;#o=!1;#t=null;#s=!1;#r;setConfirmHandler(t){this.#e=t}isOperational(){return this.config.enabled!==!0||!this.#o?!1:this.#i()!==null}async snapshotForDispatch(){if(await this.#p(),this.config.enabled!==!0)return[];let t=this.#i();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return Gp.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.#r.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.#l(r.name)).map(r=>{let s=WW(r.annotations);return{name:r.name,description:r.description,parametersSchema:OW(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(t,n,o){if(await this.#p(),this.config.enabled!==!0)return Wo("WebMCP is not enabled on this widget.");let r=this.#i();if(!r){let y=typeof document<"u"&&!!document.modelContext;return Wo(y?"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 s=IW(t),i;try{i=await r.getTools()}catch(y){let v=y instanceof Error?y.message:String(y);return Wo(`Failed to read WebMCP registry: ${v}`)}this.#r.recordToolDisplayTitles(i);let l=i.find(y=>y.name===s);if(!l)return Wo(`WebMCP tool not registered on this page: ${s}`);if(!this.#l(s))return Wo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Wo("Aborted by cancel()");let c=this.#r.getToolDisplayTitle(s),p={toolName:s,args:n,description:l.description,...c?{title:c}:{},reason:"gate"};if(!await this.#g(p))return Wo("User declined the tool call.");if(o?.aborted)return Wo("Aborted by cancel()");let d=new AbortController,g=!1,f=setTimeout(()=>{g=!0,d.abort()},this.#n),h=()=>d.abort();o&&(o.aborted?d.abort():o.addEventListener("abort",h,{once:!0}));try{let y=await r.executeTool(l,NW(n),{signal:d.signal});return BW(y)}catch(y){if(g)return Wo(`WebMCP tool '${s}' timed out after ${this.#n}ms`);if(o?.aborted)return Wo("Aborted by cancel()");let v=y instanceof Error?y.message:String(y);return Wo(v)}finally{clearTimeout(f),o&&o.removeEventListener("abort",h)}}#p(){return this.config.enabled!==!0?Promise.resolve():(this.#t||(this.#t=this.#f()),this.#t)}async#f(){try{if(this.#i()){this.#o=!0;return}(await this.#r.loadPolyfill()).initializeWebMCPPolyfill(),this.#o=!0}catch(t){Gp.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.#o=!1}}#i(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.#s||(this.#s=!0,Gp.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):t}async#g(t){let n=this.#e??_W;try{return await n(t)}catch(o){return Gp.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}#l(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>RW(t,o))}},RW=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Yp={type:"object",properties:{}},WW=e=>{if(!e||typeof e!="object")return;let t={...typeof e.readOnlyHint=="boolean"?{readOnlyHint:e.readOnlyHint}:{},...typeof e.untrustedContentHint=="boolean"?{untrustedContentHint:e.untrustedContentHint}:{}};return Object.keys(t).length>0?t:void 0},OW=e=>{if(e===void 0||e==="")return{...Yp};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...Yp};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...Yp}}catch{return{...Yp}}},BW=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:FW(t)}]}},Wo=e=>({isError:!0,content:[{type:"text",text:e}]}),_W=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=DW(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
481
+ `)}function BW(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===bW?new Uint8Array(e,44):new Uint8Array(e)}function sx(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 DW(e){return sx(e).replace(/^ws/i,"http")}function NW(e){return typeof e!="number"||!Number.isFinite(e)?SW:Math.min(xW,Math.max(AW,Math.round(e)))}var Ql=class{constructor(t){this.config=t;this.type="runtype";this.#e=null;this.#n=null;this.#o=[];this.#t=null;this.#s=null;this.#r=null;this.#p=[];this.#f=0;this.#i=null;this.#u=!1;this.#c=!1;this.#l=0;this.#a=!1;this.#M=Number.NEGATIVE_INFINITY;this.#h=null;this.#x=!1;this.#S=!1;this.#E=0;this.#d=0;this.#m=!1;this.bridge=null;this.#A=!1;this.#C=new Set;this.#b=new Map;this.#y=new Set;this.#T=null;this.#w=null;this.#Q=!1;this.#G=!1;this.#q=!1;this.#k=null;this.#J=null;this.#B=Promise.resolve();this.#R=new Set;this.#Z=new Set;this.#re=null;this.#P=!1;this.#F=new Set;this.#U=new Set;this.#se=[];this.#z=[];this.#D=[];this.#ie=[];this.#W=[]}#e;#n;#o;#t;#s;#r;#p;#f;#i;#u;#c;#l;#a;#M;#h;#x;#S;#E;#d;#g;#m;#A;#C;#b;#y;#I;#T;#w;#_;#Q;#G;#q;#k;#J;#B;#R;#Z;#re;#P;#F;#U;#se;#z;#D;#ie;#W;async connect(){}setSessionBridge(t){this.bridge=t}prewarm(){if(this.#u||this.#h)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t||!n||!o)return;let r=Date.now();if(!(r-this.#M<vW)){this.#M=r;try{this.config?.prewarmMode==="attach"?this.#ve(o,t,n):this.#be(o,t,n)}catch{}}}#be(t,n,o){if(typeof fetch!="function")return;let r=`${DW(t)}/v1/client/agents/${encodeURIComponent(n)}/voice/prewarm`;fetch(r,{method:"POST",headers:{Authorization:`Bearer ${o}`},keepalive:!0}).catch(()=>{})}#ve(t,n,o){let r=new URLSearchParams,s=this.config?.attachIdleMs,i=NW(s);s!==void 0&&r.set("attachIdleMs",String(i));let l=new WebSocket(this.#V(t,n,r),["runtype.bearer","runtype.attach",o]);l.binaryType="arraybuffer";let c=()=>{},p=new Promise(g=>{c=g}),d={ws:l,state:"connecting",ready:p,settle:c,openedAt:0,idleTimer:void 0};this.#h=d,l.onopen=()=>{this.#h===d&&(d.state=l.protocol==="runtype.attach"?"attached":"live",d.openedAt=Date.now(),this.#ae(d,i),d.state==="attached"&&l.send('{"type":"ping"}'),d.settle())},l.onmessage=g=>{if(this.#h!==d||typeof g.data!="string")return;let f;try{f=JSON.parse(g.data)}catch{return}f.type==="attached"&&typeof f.idleMs=="number"&&this.#ae(d,f.idleMs-(Date.now()-d.openedAt))},l.onerror=()=>{},l.onclose=()=>{this.#h===d&&this.#Y()}}#ae(t,n){clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{this.#h===t&&this.#Y()},Math.max(0,n))}#Y(){let t=this.#h;if(!t)return;this.#h=null,clearTimeout(t.idleTimer);let{ws:n}=t;if(n.onopen=null,n.onmessage=null,n.onerror=null,n.onclose=null,t.settle(),n.readyState===WebSocket.CONNECTING||n.readyState===WebSocket.OPEN)try{n.close(1e3,"prewarm released")}catch{}}async#ue(){let t=this.#h;if(!t)return null;if(t.state==="connecting"){let n;await Promise.race([t.ready,new Promise(o=>{n=setTimeout(o,wW)})]),clearTimeout(n)}return this.#h!==t?null:t.state==="connecting"||t.ws.readyState!==WebSocket.OPEN?(this.#Y(),null):(this.#h=null,clearTimeout(t.idleTimer),{ws:t.ws,live:t.state==="live"})}#V(t,n,o){let r=["partial_transcript","context"];this.bridge&&this.config?.clientDelegation!==!1&&r.push("client_delegation","delegation_update","delegation_read_back","delegation_stream"),o&&r.unshift("attach");let s=new URLSearchParams({voiceProtocol:PW,clientVersion:`persona/${Zn}`,voiceCapabilities:EW,clientCapabilities:r.join(",")});return o?.forEach((i,l)=>s.set(l,i)),`${sx(t)}/ws/agents/${encodeURIComponent(n)}/voice?${s}`}async startListening(){if(this.#u)return;let t=this.#G;t||(this.#Q=!1,this.#w=null),this.#G=!1;let n=this.config?.agentId,o=this.config?.clientToken,r=this.config?.host;if(!n)throw new Error("Runtype voice requires an agentId");if(!o)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let s=++this.#l;this.#a=!1,this.#u=!0;try{let i=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:th,channelCount:1,echoCancellation:!0}});if(s!==this.#l){i.getTracks().forEach(f=>f.stop());return}this.#t=i;let l=window.AudioContext||window.webkitAudioContext,c=new l({sampleRate:th});if(this.#n=c,c.state==="suspended"){if(await Promise.race([c.resume().catch(()=>{}),new Promise(f=>setTimeout(f,t?500:CW))]),s!==this.#l)return;if(c.state!=="running")throw t?new Error(this.#w=`${Xp} Tap the mic to reconnect.`):new Error("Audio blocked until a tap")}let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new ga(fW);if(s!==this.#l){p.destroy(),i.getTracks().forEach(f=>f.stop()),c.close().catch(()=>{});return}this.#i=p,this.#X(),this.#H(c,i,s);let d=await this.#ue();if(s!==this.#l){d?.ws.close(1e3,"client ended call");return}if(d){let{ws:f}=d;this.#e=f,this.#O(f,s),d.live||f.send('{"type":"start"}'),this.#$(f),this.#v("listening");return}let g=new WebSocket(this.#V(r,n),["runtype.bearer",o]);g.binaryType="arraybuffer",this.#e=g,g.onopen=()=>{s===this.#l&&(this.#$(g),this.#v("listening"))},this.#O(g,s)}catch(i){throw this.#ee(),this.#le(i),this.#v("error"),i}}#O(t,n){t.onmessage=o=>this.#ne(o,n),t.onerror=()=>{n!==this.#l||this.#T||(this.#le(new Error("Voice connection failed")),this.#v("error"),this.#ee())},t.onclose=o=>{if(this.#a){this.#a=!1;return}if(n!==this.#l)return;let r=this.#T??(o.code===4408?{reason:"idle_timeout"}:null);if(!r){if(o.code!==1e3){let s=o.code?` (code ${o.code})`:"";this.#le(new Error(`Voice connection closed${s}`)),this.#v("error")}else this.#v("idle");this.#ee();return}this.#N(r.reason,r.message)}}#N(t,n){let o=ox.includes(t)&&!this.#Q;if(this.#ee(),o){this.#Q=!0,this.#u=!0,this.#w=t==="provider_error"?`${Xp} Reconnecting\u2026`:"Reconnecting\u2026",this.#_=setTimeout(()=>{this.#u=!1,this.#G=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#v("idle");return}if(ox.includes(t))return this.#w=Xp,this.#le(new Error(Xp)),this.#v("error");if(t==="error")return this.#v("error");this.#w=t==="quota"&&n||IW.get(t)||null,this.#v("idle")}takeNotice(){let t=this.#w;return this.#w=null,t}getDisclosure(){let t=this.config?.disclosureText;return this.#u&&this.#x&&t!==!1?t||HW:null}async stopListening(){this.#ee(),this.#v("idle")}async disconnect(){this.#ee(),this.#v("disconnected"),this.#se=[],this.#z=[],this.#D=[],this.#ie=[],this.#W=[]}stopPlayback(){this.#Te();let t=this.#e;t&&t.readyState===WebSocket.OPEN&&(this.#x&&(this.#E=Date.now()+TW,t.send('{"type":"cancel"}')),this.#v("listening"))}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.#u}onLevel(t){this.#o.push(t)}async deactivateBargeIn(){this.#ee(),this.#v("idle")}#H(t,n,o){let r=t.createMediaStreamSource(n);this.#s=r;let s=t.createScriptProcessor(mW,1,1);this.#r=s,s.onaudioprocess=i=>{if(o!==this.#l)return;let l=this.#e,c=l?.readyState===WebSocket.OPEN;if(l&&!c&&l.readyState!==WebSocket.CONNECTING)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length),g=0;for(let f=0;f<p.length;f++){let h=Math.max(-1,Math.min(1,p[f]));g+=h*h,d[f]=h<0?h*32768:h*32767}if(l&&c)this.#$(l),l.send(d.buffer);else for(this.#p.push(d.buffer),this.#f+=d.byteLength;this.#f>hW;)this.#f-=this.#p.shift().byteLength;if(this.#o.length>0){let f=Math.sqrt(g/p.length),h=Math.max(0,Math.min(1,f*yW));for(let y of this.#o)y(h)}},r.connect(s),s.connect(t.destination)}#$(t){for(let n of this.#p)t.send(n);this.#p=[],this.#f=0}#ne(t,n){if(n!==this.#l)return;if(t.data instanceof ArrayBuffer){this.#Se(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"session_config":o.speechMode&&(this.#x=o.speechMode==="speech_to_speech",this.#i?.setContinuousMode?.(this.#x)),Array.isArray(o.capabilities)&&(this.#C=new Set(o.capabilities)),typeof o.callId=="string"&&(this.#I=o.callId),this.#A=this.#x&&this.#C.has("client_delegation")&&!!this.bridge,this.#x&&!this.#c&&this.#v("listening"),this.#C.has("context")&&!this.#q&&(this.#q=!0,this.#k=this.#Le());break;case"transcript_update":{let r=o.role==="assistant"?"assistant":"user",s=o.utteranceId??o.turnId;if(!s||r==="assistant"&&this.#fe())break;let i=String(s);if(r==="user")o.final===!0&&this.#ge(n),this.#P=!1;else{if(this.#C.has("delegation_read_back")){let l=o.delegationId;typeof l=="string"&&this.#R.has(l)&&!this.#F.has(i)?(this.#U.add(i),this.#P=!1):this.#P&&!this.#F.has(i)&&(this.#U.add(i),this.#P=!1)}else this.#P&&!this.#F.has(i)&&(this.#U.add(i),this.#P=!1);if(this.#F.add(i),this.#U.has(i))break}this.#ce(r,o.text??"",o.final===!0,{turnId:i,...typeof o.startMs=="number"&&{startMs:o.startMs},...typeof o.endMs=="number"&&{endMs:o.endMs},...this.#A&&{caption:!0}});break}case"delegation_started":case"delegation_completed":{let r=String(o.delegationId??o.turnId);if(o.type==="delegation_started"){this.#ge(n);let s=o.input;this.#A&&s&&this.#Me(r,{delegationId:r,userText:String(s.text??""),userUtteranceIds:Array.isArray(s.userUtteranceIds)?s.userUtteranceIds.filter(i=>typeof i=="string"):[],messages:Array.isArray(s.messages)?s.messages:[]},n)}else o.speak!==!1&&this.#R.has(r)&&!this.#Z.delete(r)&&!this.#C.has("delegation_read_back")&&this.#we(r);this.#S=o.type==="delegation_started",!this.#c&&!this.#fe()&&this.#v(this.#S?"processing":"listening");break}case"delegation_progress":{let r=String(o.delegationId);this.#R.has(r)&&!this.#Z.has(r)&&!this.#y.has(r)&&(this.#Z.add(r),this.#we(r));break}case"delegation_cancelled":this.#Ee(String(o.delegationId),o.reason!=="session_ending"&&o.reason!=="provider_cancelled");break;case"warning":console.warn(`[Persona voice] ${o.code}: ${o.message??""}`,this.#I??""),o.delegationId&&(o.code==="UNKNOWN_DELEGATION"||o.code==="LATE_RESULT_LIMIT")&&this.#Ee(String(o.delegationId));break;case"audio_clear":this.#Te(),this.#E=0,this.#v("listening");break;case"transcript_interim":this.#v("listening"),this.#ce("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.#v(r==="user"?"processing":"speaking"),this.#ce(r,o.text??"",!0);break}case"audio_end":this.#i?this.#i.markStreamEnd():(this.#c=!1,this.#v("listening"));break;case"metrics":this.#oe({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.#le(new Error(o.error||"Voice error")),this.#v("error");break;case"session_end":this.#T={reason:String(o.reason),...typeof o.message=="string"&&{message:o.message}};break}}async#Le(){let t=this.bridge?.getHistory()??[],n="";try{let o=this.config?.callContext;n=String((typeof o=="function"?await o():o)??"")}catch{}return _W(t,n)}#ge(t){let n=this.#k;if(!n)return;this.#k=null;let o=!1,r=n.then(s=>{let i=this.#e;o||!s||t!==this.#l||i?.readyState!==WebSocket.OPEN||i.send(JSON.stringify({type:"context",text:s}))});this.#J={done:r,drop:()=>o=!0}}async#Ce(){let t=this.#J;if(!t)return;let n,o=await Promise.race([t.done.then(()=>!1),new Promise(r=>{n=setTimeout(()=>r(!0),kW)})]);clearTimeout(n),o&&t.drop()}#we(t){this.#P=!0,this.#re=t}#Ee(t,n=!1){this.#y.add(t),this.#re===t&&(this.#P=!1),this.#Z.delete(t),this.bridge?.dropDelegation?.(t,n),this.#b.get(t)?.abort()}#Me(t,n,o){let r=this.bridge,s=({type:l,...c})=>{let p=this.#e;return o!==this.#l||p?.readyState!==WebSocket.OPEN||this.#y.has(t)?!1:(p.send(JSON.stringify({type:l,delegationId:t,...c})),!0)},i=(l,c,p,d=0)=>s({type:l,status:c,text:p,...d>0&&{streamedChars:d}});this.#B=this.#B.then(async()=>{if(o!==this.#l||this.#y.has(t))return;let l=null,c=this.#C.has("delegation_stream")&&this.#C.has("delegation_read_back"),p=C=>{l=(l??this.#Ce()).then(()=>{s({type:"delegation_delta",text:C})&&this.#R.add(t)})},d=await r.runDelegatedTurn(c?{...n,stream:p}:n).catch(()=>({status:"failed",text:""}));await this.#Ce(),await l;let g=c?d.streamedChars??0:0,f=!!d.followUp,h=f&&this.#C.has("delegation_update");if(!i(h?"delegation_update":"delegation_result",f&&!h?"completed":d.status,d.text,g)||(d.status!=="failed"&&d.inChat!==!1&&this.#R.add(t),!d.followUp))return;let b=new AbortController;this.#b.set(t,b),d.followUp({signal:b.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,LW),readBack:h,onUpdate:C=>i("delegation_update","pending_approval",C)}).then(C=>{this.#b.delete(t),h&&C&&!b.signal.aborted&&i("delegation_result",C.status,C.text)})})}#Se(t,n){if(n!==this.#l||!this.#i||this.#fe())return;let o=BW(t);o.length!==0&&(this.#c||(this.#c=!0,this.#v("speaking")),this.#X(),this.#i.enqueue(o),this.#x&&this.#He(o.length))}#fe(){return Date.now()<this.#E}#X(){if(this.#m||!this.#i)return;this.#m=!0;let t=this.#l;this.#i.onFinished(()=>{t===this.#l&&(this.#m=!1,this.#Ae())})}#He(t){let n=Date.now();this.#d=Math.max(n,this.#d)+t/48,clearTimeout(this.#g),this.#g=setTimeout(()=>this.#Ae(),this.#d-n+MW)}#Ae(){this.#c=!1,this.#d=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#v(this.#S?"processing":"listening")}#Te(){this.#i?.flush(),this.#m=!1,this.#X(),this.#c=!1,this.#d=0,clearTimeout(this.#g)}#ee(){this.#l+=1,this.#u=!1,this.#c=!1,this.#Y(),this.#x=!1,this.#S=!1,this.#A=!1,this.#C=new Set;for(let t of this.#b.values())t.abort();if(this.#b.clear(),this.#y.clear(),this.#I=void 0,this.#T=null,clearTimeout(this.#_),this.#q=!1,this.#k=null,this.#J=null,this.#B=Promise.resolve(),this.#R.clear(),this.#Z.clear(),this.#re=null,this.#P=!1,this.#F.clear(),this.#U.clear(),this.#m=!1,this.#E=0,this.#d=0,clearTimeout(this.#g),this.#p=[],this.#f=0,this.#r&&(this.#r.onaudioprocess=null,this.#r.disconnect(),this.#r=null),this.#s&&(this.#s.disconnect(),this.#s=null),this.#t&&(this.#t.getTracks().forEach(t=>t.stop()),this.#t=null),this.#n&&(this.#n.close().catch(()=>{}),this.#n=null),this.#i&&(this.#i.destroy(),this.#i=null),this.#e){this.#a=!0;try{this.#e.close(1e3,"client ended call")}catch{}this.#e=null}}onResult(t){this.#se.push(t)}onError(t){this.#z.push(t)}onStatusChange(t){this.#D.push(t)}onTranscript(t){this.#ie.push(t)}onMetrics(t){this.#W.push(t)}#v(t){this.#D.forEach(n=>n(t))}#le(t){this.#z.forEach(n=>n(t))}#ce(t,n,o,r){this.#ie.forEach(s=>s(t,n,o,r))}#oe(t){this.#W.forEach(n=>n(t))}};var mi=class{constructor(t={}){this.config=t;this.type="browser";this.#e=null;this.#n=[];this.#o=[];this.#t=[];this.#s=!1;this.#r=typeof window<"u"?window:void 0}#e;#n;#o;#t;#s;#r;async connect(){this.#t.forEach(t=>t("connected"))}async startListening(){try{if(this.#s)throw new Error("Already listening");if(!this.#r)throw new Error("Window object not available");let t=this.#r.SpeechRecognition||this.#r.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.#e=new t,this.#e.lang=this.config?.language||"en-US",this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.#n.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=n=>{this.#o.forEach(o=>o(new Error(n.error))),this.#t.forEach(o=>o("error"))},this.#e.onstart=()=>{this.#s=!0,this.#t.forEach(n=>n("listening"))},this.#e.onend=()=>{this.#s=!1,this.#t.forEach(n=>n("idle"))},this.#e.start()}catch(t){throw this.#o.forEach(n=>n(t)),this.#t.forEach(n=>n("error")),t}}async stopListening(){this.#e&&(this.#e.stop(),this.#e=null),this.#s=!1,this.#t.forEach(t=>t("idle"))}onResult(t){this.#n.push(t)}onError(t){this.#o.push(t)}onStatusChange(t){this.#t.push(t)}async disconnect(){await this.stopListening(),this.#t.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Jl(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ql(e.runtype);case"browser":if(!mi.isSupported())throw new Error("Browser speech recognition not supported");return new mi(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new 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 new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function nh(e){if(e?.type==="custom"&&e.custom)return Jl({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Jl({type:"runtype",runtype:e.runtype});if(mi.isSupported())return Jl({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function ix(e){try{return nh(e),!0}catch{return!1}}var ax="webmcp:",FW=e=>e.startsWith(ax)?e.slice(ax.length):e,Qp={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Zp=class{constructor(t,n){this.config=t;this.#r=n,this.#e=t.onConfirm??null,this.#n=3e4}#e;#n;#o=!1;#t=null;#s=!1;#r;setConfirmHandler(t){this.#e=t}isOperational(){return this.config.enabled!==!0||!this.#o?!1:this.#i()!==null}async snapshotForDispatch(){if(await this.#p(),this.config.enabled!==!0)return[];let t=this.#i();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return Qp.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.#r.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.#c(r.name)).map(r=>{let s=UW(r.annotations);return{name:r.name,description:r.description,parametersSchema:VW(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(t,n,o){if(await this.#p(),this.config.enabled!==!0)return Wo("WebMCP is not enabled on this widget.");let r=this.#i();if(!r){let y=typeof document<"u"&&!!document.modelContext;return Wo(y?"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 s=FW(t),i;try{i=await r.getTools()}catch(y){let b=y instanceof Error?y.message:String(y);return Wo(`Failed to read WebMCP registry: ${b}`)}this.#r.recordToolDisplayTitles(i);let l=i.find(y=>y.name===s);if(!l)return Wo(`WebMCP tool not registered on this page: ${s}`);if(!this.#c(s))return Wo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Wo("Aborted by cancel()");let c=this.#r.getToolDisplayTitle(s),p={toolName:s,args:n,description:l.description,...c?{title:c}:{},reason:"gate"};if(!await this.#u(p))return Wo("User declined the tool call.");if(o?.aborted)return Wo("Aborted by cancel()");let d=new AbortController,g=!1,f=setTimeout(()=>{g=!0,d.abort()},this.#n),h=()=>d.abort();o&&(o.aborted?d.abort():o.addEventListener("abort",h,{once:!0}));try{let y=await r.executeTool(l,KW(n),{signal:d.signal});return jW(y)}catch(y){if(g)return Wo(`WebMCP tool '${s}' timed out after ${this.#n}ms`);if(o?.aborted)return Wo("Aborted by cancel()");let b=y instanceof Error?y.message:String(y);return Wo(b)}finally{clearTimeout(f),o&&o.removeEventListener("abort",h)}}#p(){return this.config.enabled!==!0?Promise.resolve():(this.#t||(this.#t=this.#f()),this.#t)}async#f(){try{if(this.#i()){this.#o=!0;return}(await this.#r.loadPolyfill()).initializeWebMCPPolyfill(),this.#o=!0}catch(t){Qp.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.#o=!1}}#i(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.#s||(this.#s=!0,Qp.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):t}async#u(t){let n=this.#e??qW;try{return await n(t)}catch(o){return Qp.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}#c(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>$W(t,o))}},$W=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Jp={type:"object",properties:{}},UW=e=>{if(!e||typeof e!="object")return;let t={...typeof e.readOnlyHint=="boolean"?{readOnlyHint:e.readOnlyHint}:{},...typeof e.untrustedContentHint=="boolean"?{untrustedContentHint:e.untrustedContentHint}:{}};return Object.keys(t).length>0?t:void 0},VW=e=>{if(e===void 0||e==="")return{...Jp};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...Jp};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...Jp}}catch{return{...Jp}}},jW=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:GW(t)}]}},Wo=e=>({isError:!0,content:[{type:"text",text:e}]}),qW=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=zW(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
482
482
 
483
483
  Arguments:
484
484
  ${t}`:"")+(e.description?`
485
485
 
486
- ${e.description}`:"");return window.confirm(n)},DW=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},NW=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},FW=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};ei();var eh=class extends Xp{constructor(t){super(t,{recordToolDisplayTitles:Qc,getToolDisplayTitle:Gi,loadPolyfill:Jc})}};function $W(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function UW(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(s=>s.toLowerCase().startsWith(o))?1:$W(o,n)?2:3}function ox(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function th(e,t){let n=t.trim();if(!n)return[...e].sort(ox);let o=[];for(let r of e){let s=UW(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:ox(r.item,s.item)),o.map(r=>r.item)}function VW(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 jW(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>th(e.items,t),resolve:e.resolve}}function qW(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>th(t,VW(r).name),resolve:(r,s)=>{let i=n.get(r.id);return i?i.kind==="server"?{context:(typeof i.data=="function"?i.data(s.args):i.data)??{}}:{insertText:typeof i.prompt=="function"?i.prompt(s.args):i.prompt??""}:{}}}}function zW(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],i=!1,l=g=>{typeof g.scrollIntoView=="function"&&g.scrollIntoView({block:"nearest",inline:"nearest"})},c=g=>{let f=g;return s.findIndex(h=>h===f||h.contains(f))},p=g=>{let f=c(g.target);if(f<0)return;let h=f;if(g.key===r)h=Math.min(f+1,s.length-1);else if(g.key===o)h=Math.max(f-1,0);else if(g.key==="Home")h=0;else if(g.key==="End")h=s.length-1;else return;g.preventDefault(),h!==f&&t.onSelect(h)},d=g=>{let f=c(g.target);f>=0&&l(s[f])};return e.addEventListener("keydown",p),e.addEventListener("focusin",d),{beforeRender(){i=typeof document<"u"&&e.contains(document.activeElement)},render(g,f){if(s=g,g.forEach((h,y)=>{h.setAttribute("role","tab");let v=y===f;h.setAttribute("aria-selected",v?"true":"false"),h.tabIndex=v||f<0&&y===0?0:-1}),i){let h=(f>=0?g[f]:void 0)??g[0];h&&typeof h.focus=="function"&&(l(h),h.focus())}},destroy(){e.removeEventListener("keydown",p),e.removeEventListener("focusin",d)}}}export{Qb as ASK_USER_QUESTION_CLIENT_TOOL,Xb as ASK_USER_QUESTION_PARAMETERS_SCHEMA,od as ASK_USER_QUESTION_TOOL_NAME,pa as AgentWidgetClient,kl as AgentWidgetSession,fa as AttachmentManager,ci as BrowserSpeechEngine,BL as DEFAULT_COMPONENTS,mk as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,aa as DEFAULT_FLOATING_LAUNCHER_WIDTH,IL as DEFAULT_PALETTE,WL as DEFAULT_SEMANTIC,Ck as DEFAULT_WIDGET_CONFIG,hs as HistoryProviderError,$A as PRESETS,FA as PRESET_FULLSCREEN,NA as PRESET_MINIMAL,DA as PRESET_SHOP,ua as ReadAloudController,Ig as SUGGEST_REPLIES_CLIENT_TOOL,Kb as SUGGEST_REPLIES_PARAMETERS_SCHEMA,Xo as SUGGEST_REPLIES_TOOL_NAME,$L as THEME_ZONES,Jn as VERSION,Xc as WEBMCP_TOOL_PREFIX,eh as WebMcpBridge,NR as accessibilityPlugin,FR as animationsPlugin,eA as applyFeaturePreferences,ha as applyThemeVariables,Ca as attachHeaderToContainer,$R as brandPlugin,Sa as buildComposer,lS as buildDefaultHeader,ws as buildHeader,Vl as buildHeaderWithLayout,cS as buildMinimalHeader,ta as builtInClientToolsForDispatch,Qn as canonicalArtifactDisplayMode,WR as collectEnrichedPageContext,tr as componentRegistry,Wp as createActionManager,$m as createAgentExperience,BP as createAskUserQuestionBubble,Zm as createBestAvailableVoiceProvider,UH as createBubbleWithLayout,Dm as createCSATFeedback,rm as createComboButton,KI as createComponentMiddleware,Om as createComponentStreamParser,AC as createDefaultSanitizer,aW as createDemoCarousel,C0 as createDirectivePostprocessor,wa as createDropdownMenu,dP as createFlexibleJsonStreamParser,oo as createIconButton,ef as createImagePart,xg as createJsonStreamParser,aS as createLabelButton,Wm as createLocalStorageAdapter,Yd as createMarkdownProcessor,Xd as createMarkdownProcessorFromConfig,vS as createMessageActions,Nm as createNPSFeedback,Sg as createPlainTextParser,jR as createPlugin,Ag as createRegexJsonParser,zW as createRovingTablist,qW as createSlashCommandsSource,CH as createSplitButton,ql as createStandardBubble,jW as createStaticMentionSource,Io as createTextPart,pp as createTheme,Il as createThemeObserver,Cp as createToggleGroup,Aa as createTypingIndicator,Ql as createVoiceProvider,Dp as createWidgetHostLayout,Mg as createXmlParser,DR as default,ka as defaultActionHandlers,Rp as defaultJsonActionParser,th as defaultMentionFilter,RA as defaultParseRules,up as detectColorScheme,w0 as directivePostprocessor,Lg as ensureAskUserQuestionSheet,ms as escapeHtml,_m as extractComponentDirectiveFromMessage,Ak as fileToImagePart,OR as formatEnrichedContext,li as generateAssistantMessageId,YR as generateCodeSnippet,L0 as generateMessageId,OA as generateStableSelector,Ml as generateUserMessageId,Zo as getActiveTheme,mR as getAgentWidgetHandles,ma as getColorScheme,Zg as getDisplayText,dS as getHeaderLayout,Sk as getImageParts,_R as getPreset,Op as hasComponentDirective,bl as hasImages,sm as headerLayouts,VR as highContrastPlugin,xA as initAgentWidget,is as isAskUserQuestionMessage,zI as isComponentDirectiveType,Ht as isDockedMountMode,_0 as isHistoryProviderError,Zi as isSuggestRepliesMessage,tx as isVoiceSupported,Zs as isWebMcpToolName,pi as isWelcomeVisible,Rg as latestAgentSuggestions,tH as listRegisteredStreamAnimations,mg as loadMarkdownParsers,CC as markdownPostprocessor,yl as mergeWithDefaults,wk as normalizeContent,ti as normalizeMediaType,il as onMarkdownParsersReady,as as parseAskUserQuestionPayload,Yb as parseSuggestRepliesPayload,QS as parseWidgetPreferenceSlice,El as pickBestVoice,Hp as pluginRegistry,UR as reducedMotionPlugin,eP as registerIcons,hp as registerStreamAnimationPlugin,cs as removeAskUserQuestionSheet,Bm as renderComponentDirective,yS as renderLoadingIndicatorWithFallback,ue as renderLucideIcon,Tb as resolveArtifactDisplay,Er as resolveArtifactDisplayMode,Lp as resolveConfigPreferences,to as resolveDockConfig,Sf as resolveSanitizer,jf as resolveTokens,zl as resolveWelcomeConfig,Eb as stripWebMcpPrefix,qf as themeToCssVariables,eH as unregisterStreamAnimationPlugin,xk as validateImageFile,Bw as validateTheme};
486
+ ${e.description}`:"");return window.confirm(n)},zW=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},KW=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},GW=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};ei();var oh=class extends Zp{constructor(t){super(t,{recordToolDisplayTitles:Zc,getToolDisplayTitle:Gi,loadPolyfill:ed})}};function YW(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function XW(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(s=>s.toLowerCase().startsWith(o))?1:YW(o,n)?2:3}function lx(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function rh(e,t){let n=t.trim();if(!n)return[...e].sort(lx);let o=[];for(let r of e){let s=XW(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:lx(r.item,s.item)),o.map(r=>r.item)}function QW(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 JW(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>rh(e.items,t),resolve:e.resolve}}function ZW(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>rh(t,QW(r).name),resolve:(r,s)=>{let i=n.get(r.id);return i?i.kind==="server"?{context:(typeof i.data=="function"?i.data(s.args):i.data)??{}}:{insertText:typeof i.prompt=="function"?i.prompt(s.args):i.prompt??""}:{}}}}function eO(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],i=!1,l=g=>{typeof g.scrollIntoView=="function"&&g.scrollIntoView({block:"nearest",inline:"nearest"})},c=g=>{let f=g;return s.findIndex(h=>h===f||h.contains(f))},p=g=>{let f=c(g.target);if(f<0)return;let h=f;if(g.key===r)h=Math.min(f+1,s.length-1);else if(g.key===o)h=Math.max(f-1,0);else if(g.key==="Home")h=0;else if(g.key==="End")h=s.length-1;else return;g.preventDefault(),h!==f&&t.onSelect(h)},d=g=>{let f=c(g.target);f>=0&&l(s[f])};return e.addEventListener("keydown",p),e.addEventListener("focusin",d),{beforeRender(){i=typeof document<"u"&&e.contains(document.activeElement)},render(g,f){if(s=g,g.forEach((h,y)=>{h.setAttribute("role","tab");let b=y===f;h.setAttribute("aria-selected",b?"true":"false"),h.tabIndex=b||f<0&&y===0?0:-1}),i){let h=(f>=0?g[f]:void 0)??g[0];h&&typeof h.focus=="function"&&(l(h),h.focus())}},destroy(){e.removeEventListener("keydown",p),e.removeEventListener("focusin",d)}}}export{tv as ASK_USER_QUESTION_CLIENT_TOOL,ev as ASK_USER_QUESTION_PARAMETERS_SCHEMA,sd as ASK_USER_QUESTION_TOOL_NAME,pa as AgentWidgetClient,Pl as AgentWidgetSession,fa as AttachmentManager,ci as BrowserSpeechEngine,$L as DEFAULT_COMPONENTS,CP as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,aa as DEFAULT_FLOATING_LAUNCHER_WIDTH,BL as DEFAULT_PALETTE,NL as DEFAULT_SEMANTIC,EP as DEFAULT_WIDGET_CONFIG,hs as HistoryProviderError,qA as PRESETS,jA as PRESET_FULLSCREEN,VA as PRESET_MINIMAL,UA as PRESET_SHOP,ua as ReadAloudController,Og as SUGGEST_REPLIES_CLIENT_TOOL,Qb as SUGGEST_REPLIES_PARAMETERS_SCHEMA,Xo as SUGGEST_REPLIES_TOOL_NAME,zL as THEME_ZONES,Zn as VERSION,Jc as WEBMCP_TOOL_PREFIX,oh as WebMcpBridge,qR as accessibilityPlugin,zR as animationsPlugin,rA as applyFeaturePreferences,ha as applyThemeVariables,Ca as attachHeaderToContainer,KR as brandPlugin,Sa as buildComposer,uS as buildDefaultHeader,ws as buildHeader,Vl as buildHeaderWithLayout,gS as buildMinimalHeader,ta as builtInClientToolsForDispatch,Jn as canonicalArtifactDisplayMode,FR as collectEnrichedPageContext,tr as componentRegistry,_p as createActionManager,jm as createAgentExperience,$k as createAskUserQuestionBubble,nh as createBestAvailableVoiceProvider,KH as createBubbleWithLayout,$m as createCSATFeedback,am as createComboButton,JI as createComponentMiddleware,Dm as createComponentStreamParser,TC as createDefaultSanitizer,gW as createDemoCarousel,E0 as createDirectivePostprocessor,wa as createDropdownMenu,mk as createFlexibleJsonStreamParser,ro as createIconButton,of as createImagePart,Tg as createJsonStreamParser,pS as createLabelButton,Bm as createLocalStorageAdapter,Qd as createMarkdownProcessor,Jd as createMarkdownProcessorFromConfig,AS as createMessageActions,Um as createNPSFeedback,Eg as createPlainTextParser,XR as createPlugin,Mg as createRegexJsonParser,eO as createRovingTablist,ZW as createSlashCommandsSource,EH as createSplitButton,ql as createStandardBubble,JW as createStaticMentionSource,Io as createTextPart,gp as createTheme,Il as createThemeObserver,Sp as createToggleGroup,Aa as createTypingIndicator,Jl as createVoiceProvider,Fp as createWidgetHostLayout,kg as createXmlParser,jR as default,Pa as defaultActionHandlers,Op as defaultJsonActionParser,rh as defaultMentionFilter,BA as defaultParseRules,fp as detectColorScheme,M0 as directivePostprocessor,Rg as ensureAskUserQuestionSheet,ms as escapeHtml,Fm as extractComponentDirectiveFromMessage,kP as fileToImagePart,$R as formatEnrichedContext,li as generateAssistantMessageId,tW as generateCodeSnippet,O0 as generateMessageId,NA as generateStableSelector,El as generateUserMessageId,Zo as getActiveTheme,wR as getAgentWidgetHandles,ma as getColorScheme,nf as getDisplayText,fS as getHeaderLayout,TP as getImageParts,VR as getPreset,Bp as hasComponentDirective,bl as hasImages,lm as headerLayouts,YR as highContrastPlugin,kA as initAgentWidget,is as isAskUserQuestionMessage,QI as isComponentDirectiveType,Ht as isDockedMountMode,U0 as isHistoryProviderError,Zi as isSuggestRepliesMessage,ix as isVoiceSupported,Zs as isWebMcpToolName,pi as isWelcomeVisible,_g as latestAgentSuggestions,iH as listRegisteredStreamAnimations,bg as loadMarkdownParsers,xC as markdownPostprocessor,yl as mergeWithDefaults,MP as normalizeContent,ti as normalizeMediaType,il as onMarkdownParsersReady,as as parseAskUserQuestionPayload,Zb as parseSuggestRepliesPayload,tA as parseWidgetPreferenceSlice,Ml as pickBestVoice,Rp as pluginRegistry,GR as reducedMotionPlugin,sk as registerIcons,bp as registerStreamAnimationPlugin,cs as removeAskUserQuestionSheet,Nm as renderComponentDirective,wS as renderLoadingIndicatorWithFallback,ue as renderLucideIcon,Hb as resolveArtifactDisplay,Mr as resolveArtifactDisplayMode,Ip as resolveConfigPreferences,no as resolveDockConfig,Ef as resolveSanitizer,Kf as resolveTokens,zl as resolveWelcomeConfig,Lb as stripWebMcpPrefix,Gf as themeToCssVariables,sH as unregisterStreamAnimationPlugin,PP as validateImageFile,Fw as validateTheme};
487
487
  //# sourceMappingURL=index.js.map