@runtypelabs/persona 4.28.0 → 4.28.1

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 (62) hide show
  1. package/README.md +25 -0
  2. package/dist/{approval-ui-QAKWNFNM.js → approval-ui-OBBI62ES.js} +1 -1
  3. package/dist/approval-ui.cjs +2 -2
  4. package/dist/approval-ui.d.cts +7 -5
  5. package/dist/approval-ui.d.ts +7 -5
  6. package/dist/approval-ui.js +2 -2
  7. package/dist/artifacts-ui.d.cts +7 -5
  8. package/dist/artifacts-ui.d.ts +7 -5
  9. package/dist/{chunk-NQLDCJAP.js → chunk-D4TDKCT5.js} +2 -2
  10. package/dist/chunk-FNXK3VTC.js +1 -0
  11. package/dist/{client-history-LV3KHEFA.js → client-history-QGAFMCBE.js} +1 -1
  12. package/dist/client-history.js +1 -1
  13. package/dist/{client-stream-N22JHTLE.js → client-stream-WXD2FL23.js} +1 -1
  14. package/dist/client-stream.js +3 -3
  15. package/dist/codegen.cjs +4 -4
  16. package/dist/codegen.js +5 -5
  17. package/dist/context-mentions.d.cts +7 -5
  18. package/dist/context-mentions.d.ts +7 -5
  19. package/dist/event-stream-view.d.cts +7 -5
  20. package/dist/event-stream-view.d.ts +7 -5
  21. package/dist/forms-ui.d.cts +7 -5
  22. package/dist/forms-ui.d.ts +7 -5
  23. package/dist/index.cjs +40 -40
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +32 -30
  26. package/dist/index.d.ts +32 -30
  27. package/dist/index.global.js +1 -1
  28. package/dist/index.global.js.map +1 -1
  29. package/dist/index.js +41 -41
  30. package/dist/index.js.map +1 -1
  31. package/dist/session-reconnect.d.cts +7 -5
  32. package/dist/session-reconnect.d.ts +7 -5
  33. package/dist/smart-dom-reader.d.cts +7 -5
  34. package/dist/smart-dom-reader.d.ts +7 -5
  35. package/dist/theme-editor-preview.cjs +51 -51
  36. package/dist/theme-editor-preview.d.cts +7 -5
  37. package/dist/theme-editor-preview.d.ts +7 -5
  38. package/dist/theme-editor-preview.js +4 -4
  39. package/dist/theme-editor.d.cts +8 -6
  40. package/dist/theme-editor.d.ts +8 -6
  41. package/dist/{voice-runtime-LVUMPUDS.js → voice-runtime-TWFJ4UUS.js} +1 -1
  42. package/dist/voice-runtime.cjs +1 -1
  43. package/dist/voice-runtime.d.cts +7 -5
  44. package/dist/voice-runtime.d.ts +7 -5
  45. package/dist/voice-runtime.js +1 -1
  46. package/dist/webmcp-runtime-5Q3IHAHP.js +6 -0
  47. package/dist/webmcp-runtime.cjs +2 -2
  48. package/dist/webmcp-runtime.d.cts +22 -26
  49. package/dist/webmcp-runtime.d.ts +22 -26
  50. package/dist/webmcp-runtime.js +2 -2
  51. package/package.json +5 -2
  52. package/src/generated/runtype-openapi-contract.ts +3 -0
  53. package/src/theme-editor/webmcp/types.ts +1 -1
  54. package/src/types.ts +7 -5
  55. package/src/webmcp-bridge.test.ts +87 -21
  56. package/src/webmcp-bridge.ts +21 -26
  57. package/src/webmcp-polyfill.integration.test.ts +339 -0
  58. package/src/webmcp-polyfill.ts +7 -4
  59. package/src/webmcp-runtime-bundle.test.ts +1 -1
  60. package/src/webmcp-runtime-entry.ts +34 -19
  61. package/dist/chunk-AALCT54S.js +0 -1
  62. package/dist/webmcp-runtime-V6ZWW3PI.js +0 -6
package/dist/index.cjs CHANGED
@@ -1,33 +1,33 @@
1
- "use strict";var _M=Object.create;var yd=Object.defineProperty;var BM=Object.getOwnPropertyDescriptor;var DM=Object.getOwnPropertyNames;var NM=Object.getPrototypeOf,FM=Object.prototype.hasOwnProperty;var Ve=(e,t)=>()=>(e&&(t=e(e=0)),t);var ys=(e,t)=>{for(var n in t)yd(e,n,{get:t[n],enumerable:!0})},nv=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of DM(t))!FM.call(e,r)&&r!==n&&yd(e,r,{get:()=>t[r],enumerable:!(o=BM(t,r))||o.enumerable});return e};var Bn=(e,t,n)=>(n=e!=null?_M(NM(e)):{},nv(t||!e||!e.__esModule?yd(n,"default",{value:e,enumerable:!0}):n,e)),$M=e=>nv(yd({},"__esModule",{value:!0}),e);var lt,dn=Ve(()=>{"use strict";lt=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 sv={};ys(sv,{DOMPurify:()=>rv.default,Marked:()=>ov.Marked});var ov,rv,iv=Ve(()=>{"use strict";ov=require("marked"),rv=Bn(require("dompurify"),1)});var Nt,Lr=Ve(()=>{"use strict";Nt=(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 JI,jM,Cd,tf=Ve(()=>{"use strict";dn();({setLoader:JI,load:jM}=lt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")})),Cd=jM});var ee,qM,zM,di,ga,fa,wd,of,uv,rf,gv,fv,nf,KM,GM,ge,Pt=Ve(()=>{"use strict";Lr();tf();ee=require("lucide"),qM={activity:ee.Activity,"arrow-down":ee.ArrowDown,"arrow-up":ee.ArrowUp,"arrow-up-right":ee.ArrowUpRight,bot:ee.Bot,"chevron-down":ee.ChevronDown,"chevron-up":ee.ChevronUp,"chevron-right":ee.ChevronRight,"chevron-left":ee.ChevronLeft,check:ee.Check,clipboard:ee.Clipboard,"clipboard-copy":ee.ClipboardCopy,"code-xml":ee.CodeXml,copy:ee.Copy,file:ee.File,"file-code":ee.FileCode,"file-spreadsheet":ee.FileSpreadsheet,"file-text":ee.FileText,"image-plus":ee.ImagePlus,loader:ee.Loader,"loader-circle":ee.LoaderCircle,mic:ee.Mic,paperclip:ee.Paperclip,quote:ee.Quote,"refresh-cw":ee.RefreshCw,search:ee.Search,send:ee.Send,"shield-alert":ee.ShieldAlert,"shield-check":ee.ShieldCheck,"shield-x":ee.ShieldX,square:ee.Square,"thumbs-down":ee.ThumbsDown,"thumbs-up":ee.ThumbsUp,upload:ee.Upload,"volume-2":ee.Volume2,x:ee.X,"at-sign":ee.AtSign,"arrow-left":ee.ArrowLeft,"arrow-right":ee.ArrowRight,"external-link":ee.ExternalLink,ellipsis:ee.Ellipsis,"ellipsis-vertical":ee.EllipsisVertical,menu:ee.Menu,"panel-left":ee.PanelLeft,plus:ee.Plus,minus:ee.Minus,pencil:ee.Pencil,trash:ee.Trash,"trash-2":ee.Trash2,download:ee.Download,maximize:ee.Maximize,minimize:ee.Minimize,"message-square":ee.MessageSquare,star:ee.Star,eye:ee.Eye,history:ee.History},zM=["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"],di=new Map(Object.entries(qM)),ga=new Set,fa=!1,wd=new Set,of=e=>{let t=[...wd];e&&wd.clear();for(let n of t)try{n()}catch{}},uv=e=>fa?()=>{}:(wd.add(e),()=>{wd.delete(e)}),rf=()=>{let e=0;for(let t of[...ga]){let n=di.get(t.name);if(!n)continue;ga.delete(t),e++;let o=Nt(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},gv=e=>{for(let[t,n]of Object.entries(e))di.set(t,n);rf()>0&&!fa&&of(!1)},fv=e=>{if(!fa){for(let[t,n]of Object.entries(e))di.has(t)||di.set(t,n);fa=!0,rf(),of(!0)}},nf=!1,KM=()=>{Cd().then(e=>{if(!fa){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))di.has(t)||di.set(t,n);fa=!0,rf(),of(!0)}}).catch(e=>{nf=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},GM=(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},ge=(e,t=24,n="currentColor",o=2)=>{let r=di.get(e);if(r)return Nt(r,t,n,o);if(zM.includes(e)){nf&&(nf=!1);let s=GM(t,n,o);if(ga.size>=500){let i=ga.values().next().value;i&&ga.delete(i)}return ga.add({el:s,name:e,size:t,color:n,strokeWidth:o}),KM(),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 yv(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}:${YM(t.join(""))}`}function hv(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 YM(e){let t=hv(e,0).toString(36),n=hv(e,2654435761).toString(36);return`${t}.${n}`}var El,sf,Sd,ma,mv,af,bs,Ad,pi=Ve(()=>{"use strict";El="webmcp:",sf=new Map,Sd=e=>{sf.clear();for(let t of e){let n=t.title?.trim();n&&sf.set(t.name,n)}},ma=e=>sf.get(af(e)),mv=null;af=e=>e.startsWith(El)?e.slice(El.length):e,bs=e=>e.startsWith(El),Ad=()=>mv?mv():import("@mcp-b/webmcp-polyfill")});function Yn(e){return e==="card"?"collapsed":e}function vs(e){return e.split(";",1)[0].trim().toLowerCase()}function XM(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(vs(r)===t)return{mode:Yn(s),selector:vs(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(vs(r)===o)return{mode:Yn(s),selector:o}}function lf(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:Yn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?vs(t.file.mimeType):void 0,c=l?XM(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:Yn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:Yn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:Yn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:Yn(i),matchedBy:{type:"preferredMode"}}:o.default?{mode:Yn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function or(e,t){return lf(e,t).mode}function Ml(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 ha=Ve(()=>{"use strict"});var Hr,xd,ya,QM,bv,JM,ZM,vv,eT,Cv,Ed,kl,Md,cf,Td,Tl,tT,Pl,kd,Pd,Ld,wv,Hd,Cs=Ve(()=>{"use strict";Hr=require("partial-json"),xd=e=>e.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ya=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)}},QM=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`},bv=e=>e.status==="complete"?QM(e):e.status==="pending"?"Waiting":"",JM=15e3,ZM=1200,vv=(e,t)=>{let n=t?.durationMs??JM,o=t?.chars??ZM;return typeof e.durationMs=="number"?e.durationMs<n:(e.chunks??[]).join("").length<o},eT=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`},Cv=e=>e.status==="complete"?eT(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`},kl=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)},Md=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)},cf=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=kl(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Td=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=r.exec(n))!==null;)i.index>s&&Tl(o,n.slice(s,i.index),[]),i[1]!==void 0?Tl(o,i[1],["bold"]):i[2]!==void 0?Tl(o,i[2],["italic"]):i[3]!==void 0&&Tl(o,i[3],["dim"]),s=i.index+i[0].length;return s<n.length&&Tl(o,n.slice(s),[]),o},Tl=(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})},tT=()=>{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
+ "use strict";var BM=Object.create;var yd=Object.defineProperty;var DM=Object.getOwnPropertyDescriptor;var NM=Object.getOwnPropertyNames;var FM=Object.getPrototypeOf,$M=Object.prototype.hasOwnProperty;var Ve=(e,t)=>()=>(e&&(t=e(e=0)),t);var ys=(e,t)=>{for(var n in t)yd(e,n,{get:t[n],enumerable:!0})},nv=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of NM(t))!$M.call(e,r)&&r!==n&&yd(e,r,{get:()=>t[r],enumerable:!(o=DM(t,r))||o.enumerable});return e};var Bn=(e,t,n)=>(n=e!=null?BM(FM(e)):{},nv(t||!e||!e.__esModule?yd(n,"default",{value:e,enumerable:!0}):n,e)),UM=e=>nv(yd({},"__esModule",{value:!0}),e);var lt,dn=Ve(()=>{"use strict";lt=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 sv={};ys(sv,{DOMPurify:()=>rv.default,Marked:()=>ov.Marked});var ov,rv,iv=Ve(()=>{"use strict";ov=require("marked"),rv=Bn(require("dompurify"),1)});var Nt,Lr=Ve(()=>{"use strict";Nt=(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 ZI,qM,Cd,tf=Ve(()=>{"use strict";dn();({setLoader:ZI,load:qM}=lt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")})),Cd=qM});var ee,zM,KM,di,ga,fa,wd,of,uv,rf,gv,fv,nf,GM,YM,ge,kt=Ve(()=>{"use strict";Lr();tf();ee=require("lucide"),zM={activity:ee.Activity,"arrow-down":ee.ArrowDown,"arrow-up":ee.ArrowUp,"arrow-up-right":ee.ArrowUpRight,bot:ee.Bot,"chevron-down":ee.ChevronDown,"chevron-up":ee.ChevronUp,"chevron-right":ee.ChevronRight,"chevron-left":ee.ChevronLeft,check:ee.Check,clipboard:ee.Clipboard,"clipboard-copy":ee.ClipboardCopy,"code-xml":ee.CodeXml,copy:ee.Copy,file:ee.File,"file-code":ee.FileCode,"file-spreadsheet":ee.FileSpreadsheet,"file-text":ee.FileText,"image-plus":ee.ImagePlus,loader:ee.Loader,"loader-circle":ee.LoaderCircle,mic:ee.Mic,paperclip:ee.Paperclip,quote:ee.Quote,"refresh-cw":ee.RefreshCw,search:ee.Search,send:ee.Send,"shield-alert":ee.ShieldAlert,"shield-check":ee.ShieldCheck,"shield-x":ee.ShieldX,square:ee.Square,"thumbs-down":ee.ThumbsDown,"thumbs-up":ee.ThumbsUp,upload:ee.Upload,"volume-2":ee.Volume2,x:ee.X,"at-sign":ee.AtSign,"arrow-left":ee.ArrowLeft,"arrow-right":ee.ArrowRight,"external-link":ee.ExternalLink,ellipsis:ee.Ellipsis,"ellipsis-vertical":ee.EllipsisVertical,menu:ee.Menu,"panel-left":ee.PanelLeft,plus:ee.Plus,minus:ee.Minus,pencil:ee.Pencil,trash:ee.Trash,"trash-2":ee.Trash2,download:ee.Download,maximize:ee.Maximize,minimize:ee.Minimize,"message-square":ee.MessageSquare,star:ee.Star,eye:ee.Eye,history:ee.History},KM=["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"],di=new Map(Object.entries(zM)),ga=new Set,fa=!1,wd=new Set,of=e=>{let t=[...wd];e&&wd.clear();for(let n of t)try{n()}catch{}},uv=e=>fa?()=>{}:(wd.add(e),()=>{wd.delete(e)}),rf=()=>{let e=0;for(let t of[...ga]){let n=di.get(t.name);if(!n)continue;ga.delete(t),e++;let o=Nt(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},gv=e=>{for(let[t,n]of Object.entries(e))di.set(t,n);rf()>0&&!fa&&of(!1)},fv=e=>{if(!fa){for(let[t,n]of Object.entries(e))di.has(t)||di.set(t,n);fa=!0,rf(),of(!0)}},nf=!1,GM=()=>{Cd().then(e=>{if(!fa){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))di.has(t)||di.set(t,n);fa=!0,rf(),of(!0)}}).catch(e=>{nf=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},YM=(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},ge=(e,t=24,n="currentColor",o=2)=>{let r=di.get(e);if(r)return Nt(r,t,n,o);if(KM.includes(e)){nf&&(nf=!1);let s=YM(t,n,o);if(ga.size>=500){let i=ga.values().next().value;i&&ga.delete(i)}return ga.add({el:s,name:e,size:t,color:n,strokeWidth:o}),GM(),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 yv(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}:${XM(t.join(""))}`}function hv(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 XM(e){let t=hv(e,0).toString(36),n=hv(e,2654435761).toString(36);return`${t}.${n}`}var El,sf,Sd,ma,mv,af,bs,Ad,pi=Ve(()=>{"use strict";El="webmcp:",sf=new Map,Sd=e=>{sf.clear();for(let t of e){let n=t.title?.trim();n&&sf.set(t.name,n)}},ma=e=>sf.get(af(e)),mv=null;af=e=>e.startsWith(El)?e.slice(El.length):e,bs=e=>e.startsWith(El),Ad=()=>mv?mv():import("@mcp-b/webmcp-polyfill")});function Yn(e){return e==="card"?"collapsed":e}function vs(e){return e.split(";",1)[0].trim().toLowerCase()}function QM(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(vs(r)===t)return{mode:Yn(s),selector:vs(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(vs(r)===o)return{mode:Yn(s),selector:o}}function lf(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:Yn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?vs(t.file.mimeType):void 0,c=l?QM(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:Yn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:Yn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:Yn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:Yn(i),matchedBy:{type:"preferredMode"}}:o.default?{mode:Yn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function or(e,t){return lf(e,t).mode}function Ml(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 ha=Ve(()=>{"use strict"});var Hr,xd,ya,JM,bv,ZM,eT,vv,tT,Cv,Ed,Pl,Md,cf,Td,Tl,nT,kl,Pd,kd,Ld,wv,Hd,Cs=Ve(()=>{"use strict";Hr=require("partial-json"),xd=e=>e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ya=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)}},JM=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`},bv=e=>e.status==="complete"?JM(e):e.status==="pending"?"Waiting":"",ZM=15e3,eT=1200,vv=(e,t)=>{let n=t?.durationMs??ZM,o=t?.chars??eT;return typeof e.durationMs=="number"?e.durationMs<n:(e.chunks??[]).join("").length<o},tT=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`},Cv=e=>e.status==="complete"?tT(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`},Pl=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)},Md=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)},cf=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Pl(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Td=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=r.exec(n))!==null;)i.index>s&&Tl(o,n.slice(s,i.index),[]),i[1]!==void 0?Tl(o,i[1],["bold"]):i[2]!==void 0?Tl(o,i[2],["italic"]):i[3]!==void 0&&Tl(o,i[3],["dim"]),s=i.index+i[0].length;return s<n.length&&Tl(o,n.slice(s),[]),o},Tl=(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})},nT=()=>{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()=>{}}},Pl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},kd=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Pd=()=>{let e=tT();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)}},Ld=()=>{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=(0,Hr.parse)(n,Hr.STR|Hr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?xd(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=xd(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},wv=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?xd(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?xd(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=(0,Hr.parse)(s,Hr.STR|Hr.OBJ),c=r(l);c!==null&&(t=c)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Hd=()=>{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,Q,Dn,Ze=Ve(()=>{"use strict";x=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Q=(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},Dn=(...e)=>e.filter(Boolean).join(" ")});var ws,Hl,Ll,ba,nT,oT,Av,xv,rT,sT,iT,aT,lT,df,pf,Ev,uf,Mv,cT,dT,Sv,Tv,Ir,Id,Rr,Il,pT,uT,kv,Pv,gT,fT,mT,Lv,hT,yT,ui,Hv,wo,bT,va,Ss,vT,CT,Rd,Iv,Rv,gf,wT,ST,Wv,Wd,Wr,ff,As,Od,Rl=Ve(()=>{"use strict";ws=require("partial-json");Ze();Hl="ask_user_question",Ll=8,ba="data-persona-ask-sheet-for",nT="Other",oT="Other\u2026",Av="Type your own answer here",xv="Send",rT="Next",sT="Back",iT="Submit all",aT="Skip",lT=3,df="data-ask-current-index",pf="data-ask-question-count",Ev="data-ask-answers",uf="data-ask-grouped",Mv="data-ask-layout",cT=e=>e.layout==="pills"?"pills":"rows",dT=e=>e.getAttribute(Mv)==="pills"?"pills":"rows",Sv=!1,Tv=e=>e.replace(/["\\]/g,"\\$&"),Ir=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Hl,Id=e=>e?.features?.askUserQuestion??{},Rr=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=(0,ws.parse)(r,ws.STR|ws.OBJ|ws.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Il=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ll&&!Sv&&(Sv=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ll}.`)),t.slice(0,Ll)},pT=e=>Il(e)[0]??null,uT=(e,t)=>Il(e)[t]??null,kv=(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))},Pv=(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},gT=(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=Pv(n,o,t);c&&s.appendChild(c)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},fT=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},mT=(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<lT;d++)s.appendChild(fT(o));return s}if(c.forEach((d,g)=>{s.appendChild(gT(d,g,o,i))}),e?.allowFreeText!==!1){let d=o==="rows"?nT:oT;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??Av,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",t.freeTextLabel??d),f.appendChild(h),g.appendChild(f);let y=Pv(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},Lv=(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??Av,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??xv,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},hT=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??xv,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},yT=(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??sT,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??aT,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??iT:n.nextLabel??rT,l.setAttribute("data-ask-user-action",c?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},ui=e=>{let t=e.getAttribute(Ev);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Hv=(e,t)=>{e.setAttribute(Ev,JSON.stringify(t))},wo=e=>{let t=Number(e.getAttribute(df)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},bT=(e,t)=>{e.setAttribute(df,String(Math.max(0,Math.floor(t))))},va=e=>{let t=Number(e.getAttribute(pf)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Ss=e=>e.getAttribute(uf)==="true",vT=(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},CT=(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)))},Rd=(e,t)=>{let{payload:n}=Rr(t),o=Il(n),r=ui(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},Iv=e=>{let t=ui(e),n=wo(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="")},Rv=e=>{if(!Ss(e))return;let t=ui(e),n=wo(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}},gf=(e,t,n)=>{let o=Id(n),r=dT(e),{payload:s,complete:i}=Rr(t),l=Ss(e),c=wo(e),p=va(e),d=l?uT(s,c):pT(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=mT(d,o,i,r);b.replaceWith(L)}if(r!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Lv(o,r))}let C=e.querySelector('[data-ask-multi-actions="true"]');!l&&g&&!C?e.appendChild(hT(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=yT(c,p,o);A?A.replaceWith(L):e.appendChild(L)}else A&&A.remove();Iv(e),Rv(e)},wT=(e,t,n)=>{let o=Id(t),r=cT(o),s=e.toolCall.id,i=Il(n),l=Math.max(1,i.length),c=l>1,p=vT(e,i),d=c?CT(e,l):0,g=x("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(ba,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(pf,String(l)),g.setAttribute(df,String(d)),g.setAttribute(uf,c?"true":"false"),g.setAttribute(Mv,r),Hv(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`),kv(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(Lv(o,r)),gf(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},ST=(e,t,n)=>{let{payload:o}=Rr(t),r=Math.max(1,Il(o).length);r>va(e)&&(e.setAttribute(pf,String(r)),r>1&&!Ss(e)&&e.setAttribute(uf,"true")),gf(e,t,n)},Wv=(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);kv(n,o);let r=x("span","persona-ask-stub-label"),{complete:s}=Rr(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Wd=(e,t,n)=>{if(!n||!Ir(e)||Id(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${ba}]`).forEach(p=>{p.getAttribute(ba)!==r&&p.remove()});let i=n.querySelector(`[${ba}="${Tv(r)}"]`);if(i){ST(i,e,t);return}let{payload:l}=Rr(e),c=wT(e,t,l);n.appendChild(c)},Wr=(e,t)=>{if(!e)return;let n=t?`[${ba}="${Tv(t)}"]`:`[${ba}]`;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)})},ff=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),As=(e,t)=>{let n=ui(e),o=wo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Hv(e,n),Iv(e),Rv(e)},Od=(e,t,n,o)=>{let r=va(e),s=Math.max(0,Math.min(r-1,o));bT(e,s),gf(e,t,n)}});var Oo,mf,_d,_v,gi,hf,Bd,Ov,AT,xs,Ca=Ve(()=>{"use strict";Oo="suggest_replies",mf={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},_d={name:Oo,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:mf,origin:"sdk",annotations:{readOnlyHint:!0}},_v=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),gi=e=>e.variant==="tool"&&e.toolCall?.name===Oo,hf=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},Bd=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!gi(n))continue;let o=hf(n.toolCall?.args);return o.length>0?o:null}return null},Ov=new Set,AT=(e,t,n)=>{let o=`${e}:${t}:${n}`;Ov.has(o)||(Ov.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},xs=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&&AT(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 yf,bf,fi,Dd=Ve(()=>{"use strict";Rl();Ca();yf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ll,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},bf={name:Hl,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:yf,origin:"sdk",annotations:{readOnlyHint:!0}},fi=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(bf),xs(e).expose&&t.push(_d),t}});var Yt,Pn,wa,Nd,_o=Ve(()=>{"use strict";Yt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Pn=1e5,wa=Pn+1,Nd="https://api.runtype.com"});async function Bv(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 Dv(e,t,n,o){let r=e.isClientTokenMode(),s=r?e.getClientApiUrl("resume"):`${e.config.apiUrl?.replace(/\/+$/,"")||Nd}/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=[...fi(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 Nv=Ve(()=>{"use strict";Dd();_o()});var Fd={};ys(Fd,{preferFinalStructuredContent:()=>$v,resolveApproval:()=>Bv,resumeFlow:()=>Dv,streamResponse:()=>MT});function xT(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 $v(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=Fv(n);if(!Fv(o))return e;if(!r||o===n||o.startsWith(n))return t;let i=Pl(e);return Pl(t)!==null&&i===null?t:e}async function ET(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 MT(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,oe=new Map,W=new Map,j=o,X=!1,M=()=>{if(y)return y;let D,S="",F=L;return!X&&j?(D=j,X=!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=oe.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 oe.set(D,F),h(F),F},_=new Set,k=new Map,J=new Set,U=new Map,ue=D=>{if(!D)return!1;let S=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return S==="emit_artifact_markdown"||S==="emit_artifact_component"},fe=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},me=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()},He=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},Ee=new Map,Ie=new Map,yt=(D,S)=>{let F=He(S),q=Ie.get(D.id),K=$v(q,F);D.rawContent=K;let te=Ee.get(D.id),ve=De=>{let Qe=D.content??"";De.trim()!==""&&(Qe.trim().length===0||De.startsWith(Qe)||De.trimStart().startsWith(Qe.trim()))&&(D.content=De)},Me=()=>{if(te){let De=te.close?.();De instanceof Promise&&De.catch(()=>{})}Ee.delete(D.id),Ie.delete(D.id),D.streaming=!1,h(D)};if(!te){ve(F),Me();return}let Ce=Pl(K);if(Ce!==null&&Ce.trim()!==""){ve(Ce),Me();return}let st=De=>{let Qe=typeof De=="string"?De:De?.text??null;if(Qe!==null&&Qe.trim()!=="")return Qe;let pn=te.getExtractedText();return pn!==null&&pn.trim()!==""?pn:F},Ct;try{Ct=te.processChunk(K)}catch{ve(F),Me();return}if(Ct instanceof Promise){Ct.then(De=>{ve(st(De)),Me()}).catch(()=>{ve(F),Me()});return}ve(st(Ct)),Me()},qe=null,Oe=(D,S,F,q)=>{D.rawContent=S,Ee.has(D.id)||Ee.set(D.id,e.createStreamParser());let K=Ee.get(D.id),te=S.trim().startsWith("{")||S.trim().startsWith("[");if(te&&Ie.set(D.id,S),K.__isPlainTextParser===!0){D.content=q!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D);return}let Me=K.processChunk(S);if(Me instanceof Promise)Me.then(Ce=>{let st=typeof Ce=="string"?Ce:Ce?.text??null;st!==null&&st.trim()!==""?(D.content=st,h(D)):!te&&!S.trim().startsWith("<")&&(D.content=q!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D))}).catch(()=>{D.content=q!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D)});else{let Ce=typeof Me=="string"?Me:Me?.text??null;Ce!==null&&Ce.trim()!==""?(D.content=Ce,h(D)):!te&&!S.trim().startsWith("<")&&(D.content=q!==void 0?S:D.content+F,Ie.delete(D.id),Ee.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=Ie.get(D.id)??He(F);D.rawContent=K;let te=Ee.get(D.id),ve=null,Me=!1;if(te&&(ve=te.getExtractedText(),ve===null&&(ve=Pl(K)),ve===null)){let Ce=te.processChunk(K);Ce instanceof Promise?(Me=!0,Ce.then(st=>{let Ct=typeof st=="string"?st:st?.text??null;Ct!==null&&(D.content=Ct,D.streaming=!1,Ee.delete(D.id),Ie.delete(D.id),h(D))}).catch(()=>{})):ve=typeof Ce=="string"?Ce:Ce?.text??null}if(!Me){ve!==null&&ve.trim()!==""?D.content=ve:Ie.has(D.id)||(D.content=He(F));let Ce=Ee.get(D.id);if(Ce){let st=Ce.close?.();st instanceof Promise&&st.catch(()=>{}),Ee.delete(D.id)}Ie.delete(D.id),D.streaming=!1,h(D)}},_e=(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},ye=[],ut,Zt=new Map,xt=0,xe="agent",Wt=!1,vt=null,Le=null,Xe=e.config().iterationDisplay??"separate";for(ut=()=>{for(let D=0;D<ye.length;D++){let S=ye[D];if(!Wt&&xe!=="flow"&&typeof S.stepType=="string"&&(xe="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),_e(F,q,"reasoning");continue}let K=S.id,te=T(K);te.reasoning=te.reasoning??{id:K,status:"streaming",chunks:[]},te.reasoning.startedAt=te.reasoning.startedAt??Date.now(),te.reasoning.completedAt=void 0,te.reasoning.durationMs=void 0,(S.scope==="loop"||S.scope==="turn")&&(te.reasoning.scope=S.scope),te.streaming=!0,te.reasoning.status="streaming",h(te)}else if(S.type==="reasoning_delta"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)&&B.has(F)){let te=B.get(F),ve=S.delta;ve&&te.reasoning&&(te.reasoning.chunks.push(String(ve)),h(te));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 ve=B.get(F);if(ve.reasoning){let Me=typeof S.text=="string"?S.text:"";Me&&ve.reasoning.chunks.length===0&&ve.reasoning.chunks.push(Me),ve.reasoning.status="complete",ve.streaming=!1,h(ve)}H.delete(F),B.delete(F);continue}let q=S.id,K=typeof S.text=="string"?S.text:"";!oe.get(q)&&(K||S.scope==="loop")&&T(q);let te=oe.get(q);if(te?.reasoning){(S.scope==="loop"||S.scope==="turn")&&(te.reasoning.scope=S.scope),K&&te.reasoning.chunks.length===0&&te.reasoning.chunks.push(K),te.reasoning.status="complete",te.reasoning.completedAt=Date.now();let ve=te.reasoning.startedAt??Date.now();te.reasoning.durationMs=Math.max(0,(te.reasoning.completedAt??Date.now())-ve),te.streaming=!1,h(te)}}else if(S.type==="tool_start"){y&&(y.streaming=!1,h(y),y=null),typeof S.iteration=="number"&&(xt=S.iteration);let F=S.toolCallId,q=S.toolName;if(ue(q)){_.add(F);continue}let K=fe(F),te=K.toolCall??{id:F,status:"pending"};te.name=q??te.name,te.status="running",te.success=void 0,te.error=void 0,te.duration=void 0,S.parameters!==void 0&&(te.args=S.parameters),te.startedAt=te.startedAt??me(S.startedAt),te.completedAt=void 0,te.durationMs=void 0,K.toolCall=te,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=fe(F),K=q.toolCall??{id:F,status:"running"};K.startedAt=K.startedAt??Date.now();let te=S.delta;te&&(K.chunks=K.chunks??[],K.chunks.push(String(te))),K.status="running",q.toolCall=K,q.streaming=!0,S.executionId&&(q.agentMetadata=q.agentMetadata??{executionId:S.executionId,iteration:xt}),h(q)}else if(S.type==="tool_complete"){let F=S.toolCallId;if(_.has(F)){_.delete(F);continue}let q=fe(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 te=S.executionTime;if(typeof te=="number")K.durationMs=te,K.duration=te;else{let ve=K.startedAt??Date.now();K.durationMs=Math.max(0,(K.completedAt??Date.now())-ve)}q.toolCall=K,q.streaming=!1,S.executionId&&(q.agentMetadata=q.agentMetadata??{executionId:S.executionId,iteration:S.iteration??xt}),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=fe(q),te=S.toolName,ve=S.origin==="webmcp"&&!bs(te)?`webmcp:${te}`:te,Me=bs(ve),Ce=K.toolCall??{id:q,status:"pending"};Ce.name=ve,Ce.args=S.parameters,Ce.status=Me?"running":"complete",Ce.chunks=Ce.chunks??[],Ce.startedAt=Ce.startedAt??me(S.awaitedAt),Me?(Ce.completedAt=void 0,Ce.duration=void 0,Ce.durationMs=void 0):Ce.completedAt=Ce.completedAt??Ce.startedAt,K.toolCall=Ce,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&&(xe==="flow"?($(K),qe=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 ve=typeof S.delta=="string"?S.delta:"",Me=(V.get(F)??"")+ve;if(V.set(F,Me),Me.trim()==="")continue;let Ce=_e(F,q);Ce.agentMetadata={...Ce.agentMetadata,executionId:S.executionId,parentToolId:q},Oe(Ce,Me,ve,void 0);continue}if(L=typeof S.id=="string"?S.id:L,xe==="flow"){let ve=typeof S.delta=="string"?S.delta:"";if(I+=ve,I.trim()==="")continue;let Me=M();Me.agentMetadata={executionId:S.executionId,iteration:xt},Oe(Me,I,ve,void 0),b=Me;continue}let K=typeof S.delta=="string"?S.delta:"";I+=K;let te=M();te.agentMetadata={executionId:S.executionId,iteration:xt,turnId:vt??void 0,agentName:Le?.agentName},Oe(te,I,K,void 0),b=te}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&&(xe==="flow"?($(q),qe=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=qe;qe=null;let q=S.stopReason,te=(S.result&&typeof S.result=="object"?S.result:null)?.response;if(F)q&&(F.stopReason=q),te!=null?yt(F,te):F.streaming!==!1&&(Ee.delete(F.id),Ie.delete(F.id),F.streaming=!1,h(F));else{let ve=te!=null&&te!=="";if(ve||!!q&&q!=="end_turn"&&q!=="unknown"){let Ce=M();q&&(Ce.stopReason=q),ve?$(Ce,te):(Ce.streaming=!1,h(Ce))}}continue}}else if(S.type==="execution_start")xe=S.kind==="flow"?"flow":"agent",Wt=!0,xe==="agent"&&(Le={executionId:S.executionId,agentId:S.agentId??"virtual",agentName:S.agentName??""});else if(S.type==="turn_start"){let F=typeof S.iteration=="number"?S.iteration:xt;if(F!==xt){if(Xe==="separate"&&F>1){let q=y;q&&(q.streaming=!1,h(q),y=null)}xt=F}vt=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=fe(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))}vt===S.id&&(vt=null)}else if(S.type==="media_start"){let F=String(S.id);Zt.set(F,{mediaType:typeof S.mediaType=="string"?S.mediaType:void 0,toolCallId:S.toolCallId,parts:[]})}else if(S.type==="media_delta"){let F=Zt.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=Zt.get(F);Zt.delete(F);let K=(typeof S.mediaType=="string"?S.mediaType:void 0)??q?.mediaType??"application/octet-stream",te=typeof S.data=="string"?S.data:void 0,ve=typeof S.url=="string"?S.url:q&&q.parts.length>0?q.parts.join(""):void 0,Me=null;if(te)Me={type:"media",data:te,mediaType:K};else if(ve){let De=K.toLowerCase();Me={type:De==="image"||De.startsWith("image/")?"image-url":"file-url",url:ve,mediaType:K}}let Ce=S.toolCallId??q?.toolCallId,st=Me?[Me]:[],Ct=[];for(let De of st){if(!De||typeof De!="object")continue;let Qe=De,pn=typeof Qe.type=="string"?Qe.type:void 0,Eo=typeof Qe.mediaType=="string"?Qe.mediaType.toLowerCase():"",ft=null,bt="";if(pn==="media"){let Ft=typeof Qe.data=="string"?Qe.data:void 0;if(!Ft)continue;bt=Eo.length>0?Eo:"application/octet-stream",ft=`data:${bt};base64,${Ft}`}else if(pn==="image-url"){let Ft=typeof Qe.url=="string"?Qe.url:void 0;if(!Ft)continue;bt=Eo,ft=Ft}else if(pn==="file-url"){let Ft=typeof Qe.url=="string"?Qe.url:void 0;if(!Ft)continue;bt=Eo,ft=Ft}else continue;if(ft)if(pn==="image-url"||bt.startsWith("image/"))Ct.push({type:"image",image:ft,...bt.includes("/")?{mimeType:bt}:{}});else if(bt.startsWith("audio/"))Ct.push({type:"audio",audio:ft,mimeType:bt});else if(bt.startsWith("video/"))Ct.push({type:"video",video:ft,mimeType:bt});else{let Ft=bt||"application/octet-stream";Ct.push({type:"file",data:ft,mimeType:Ft,filename:xT(Ft)})}}if(Ct.length>0){let De=d(),Qe=Ce,Eo={id:`agent-media-${typeof Qe=="string"&&Qe.length>0?`${Qe}-${De}`:String(De)}`,role:"assistant",content:"",contentParts:Ct,createdAt:new Date().toISOString(),streaming:!1,sequence:De,agentMetadata:{executionId:S.executionId,iteration:xt}};h(Eo);let ft=y;ft&&(ft.streaming=!1,h(ft)),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="",qe=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:Le?.agentId??"virtual",executionId:S.executionId??Le?.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:Le?.agentId??"virtual",executionId:S.executionId??Le?.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,te=S.file,ve;if(te&&typeof te=="object"&&!Array.isArray(te)&&typeof te.path=="string"&&typeof te.mimeType=="string"&&(ve={path:te.path,mimeType:te.mimeType,...typeof te.language=="string"?{language:te.language}:{}}),n({type:"artifact_start",id:q,artifactType:F,title:K,component:typeof S.component=="string"?S.component:void 0,...ve?{file:ve}:{}}),U.set(q,{markdown:"",title:K,file:ve}),!J.has(q)){J.add(q);let Me=or(e.config().features?.artifacts,{artifactType:F,...ve?{file:ve}:{}}),Ce=typeof S.component=="string"?S.component:void 0,st={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:Ml(Me,{artifactId:q,title:K,artifactType:F,status:"streaming",...ve?{file:ve}:{},...Ce?{component:Ce}:{}})};k.set(q,st),h(st)}}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 te=U.get(F);te?.markdown&&(K.props.markdown=te.markdown),te?.file&&(K.props.file=te.file),K.component==="PersonaArtifactInline"&&te?.props&&Object.keys(te.props).length>0&&(K.props.componentProps=te.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"})}}}ye.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()=>{}}},kl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Pd=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},kd=()=>{let e=nT();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)}},Ld=()=>{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=(0,Hr.parse)(n,Hr.STR|Hr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?xd(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=xd(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},wv=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?xd(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?xd(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=(0,Hr.parse)(s,Hr.STR|Hr.OBJ),c=r(l);c!==null&&(t=c)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Hd=()=>{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,Q,Dn,Ze=Ve(()=>{"use strict";x=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Q=(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},Dn=(...e)=>e.filter(Boolean).join(" ")});var ws,Hl,Ll,ba,oT,rT,Av,xv,sT,iT,aT,lT,cT,df,pf,Ev,uf,Mv,dT,pT,Sv,Tv,Ir,Id,Rr,Il,uT,gT,Pv,kv,fT,mT,hT,Lv,yT,bT,ui,Hv,wo,vT,va,Ss,CT,wT,Rd,Iv,Rv,gf,ST,AT,Wv,Wd,Wr,ff,As,Od,Rl=Ve(()=>{"use strict";ws=require("partial-json");Ze();Hl="ask_user_question",Ll=8,ba="data-persona-ask-sheet-for",oT="Other",rT="Other\u2026",Av="Type your own answer here",xv="Send",sT="Next",iT="Back",aT="Submit all",lT="Skip",cT=3,df="data-ask-current-index",pf="data-ask-question-count",Ev="data-ask-answers",uf="data-ask-grouped",Mv="data-ask-layout",dT=e=>e.layout==="pills"?"pills":"rows",pT=e=>e.getAttribute(Mv)==="pills"?"pills":"rows",Sv=!1,Tv=e=>e.replace(/["\\]/g,"\\$&"),Ir=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Hl,Id=e=>e?.features?.askUserQuestion??{},Rr=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=(0,ws.parse)(r,ws.STR|ws.OBJ|ws.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Il=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ll&&!Sv&&(Sv=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ll}.`)),t.slice(0,Ll)},uT=e=>Il(e)[0]??null,gT=(e,t)=>Il(e)[t]??null,Pv=(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))},kv=(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},fT=(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=kv(n,o,t);c&&s.appendChild(c)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},mT=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},hT=(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<cT;d++)s.appendChild(mT(o));return s}if(c.forEach((d,g)=>{s.appendChild(fT(d,g,o,i))}),e?.allowFreeText!==!1){let d=o==="rows"?oT:rT;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??Av,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",t.freeTextLabel??d),f.appendChild(h),g.appendChild(f);let y=kv(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},Lv=(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??Av,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??xv,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},yT=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??xv,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},bT=(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??iT,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??lT,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??aT:n.nextLabel??sT,l.setAttribute("data-ask-user-action",c?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},ui=e=>{let t=e.getAttribute(Ev);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Hv=(e,t)=>{e.setAttribute(Ev,JSON.stringify(t))},wo=e=>{let t=Number(e.getAttribute(df)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},vT=(e,t)=>{e.setAttribute(df,String(Math.max(0,Math.floor(t))))},va=e=>{let t=Number(e.getAttribute(pf)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Ss=e=>e.getAttribute(uf)==="true",CT=(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},wT=(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)))},Rd=(e,t)=>{let{payload:n}=Rr(t),o=Il(n),r=ui(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},Iv=e=>{let t=ui(e),n=wo(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="")},Rv=e=>{if(!Ss(e))return;let t=ui(e),n=wo(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}},gf=(e,t,n)=>{let o=Id(n),r=pT(e),{payload:s,complete:i}=Rr(t),l=Ss(e),c=wo(e),p=va(e),d=l?gT(s,c):uT(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=hT(d,o,i,r);b.replaceWith(L)}if(r!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Lv(o,r))}let C=e.querySelector('[data-ask-multi-actions="true"]');!l&&g&&!C?e.appendChild(yT(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=bT(c,p,o);A?A.replaceWith(L):e.appendChild(L)}else A&&A.remove();Iv(e),Rv(e)},ST=(e,t,n)=>{let o=Id(t),r=dT(o),s=e.toolCall.id,i=Il(n),l=Math.max(1,i.length),c=l>1,p=CT(e,i),d=c?wT(e,l):0,g=x("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(ba,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(pf,String(l)),g.setAttribute(df,String(d)),g.setAttribute(uf,c?"true":"false"),g.setAttribute(Mv,r),Hv(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`),Pv(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(Lv(o,r)),gf(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},AT=(e,t,n)=>{let{payload:o}=Rr(t),r=Math.max(1,Il(o).length);r>va(e)&&(e.setAttribute(pf,String(r)),r>1&&!Ss(e)&&e.setAttribute(uf,"true")),gf(e,t,n)},Wv=(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);Pv(n,o);let r=x("span","persona-ask-stub-label"),{complete:s}=Rr(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Wd=(e,t,n)=>{if(!n||!Ir(e)||Id(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${ba}]`).forEach(p=>{p.getAttribute(ba)!==r&&p.remove()});let i=n.querySelector(`[${ba}="${Tv(r)}"]`);if(i){AT(i,e,t);return}let{payload:l}=Rr(e),c=ST(e,t,l);n.appendChild(c)},Wr=(e,t)=>{if(!e)return;let n=t?`[${ba}="${Tv(t)}"]`:`[${ba}]`;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)})},ff=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),As=(e,t)=>{let n=ui(e),o=wo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Hv(e,n),Iv(e),Rv(e)},Od=(e,t,n,o)=>{let r=va(e),s=Math.max(0,Math.min(r-1,o));vT(e,s),gf(e,t,n)}});var Oo,mf,_d,_v,gi,hf,Bd,Ov,xT,xs,Ca=Ve(()=>{"use strict";Oo="suggest_replies",mf={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},_d={name:Oo,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:mf,origin:"sdk",annotations:{readOnlyHint:!0}},_v=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),gi=e=>e.variant==="tool"&&e.toolCall?.name===Oo,hf=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},Bd=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!gi(n))continue;let o=hf(n.toolCall?.args);return o.length>0?o:null}return null},Ov=new Set,xT=(e,t,n)=>{let o=`${e}:${t}:${n}`;Ov.has(o)||(Ov.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},xs=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&&xT(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 yf,bf,fi,Dd=Ve(()=>{"use strict";Rl();Ca();yf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ll,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},bf={name:Hl,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:yf,origin:"sdk",annotations:{readOnlyHint:!0}},fi=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(bf),xs(e).expose&&t.push(_d),t}});var Yt,kn,wa,Nd,_o=Ve(()=>{"use strict";Yt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},kn=1e5,wa=kn+1,Nd="https://api.runtype.com"});async function Bv(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 Dv(e,t,n,o){let r=e.isClientTokenMode(),s=r?e.getClientApiUrl("resume"):`${e.config.apiUrl?.replace(/\/+$/,"")||Nd}/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=[...fi(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 Nv=Ve(()=>{"use strict";Dd();_o()});var Fd={};ys(Fd,{preferFinalStructuredContent:()=>$v,resolveApproval:()=>Bv,resumeFlow:()=>Dv,streamResponse:()=>TT});function ET(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 $v(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=Fv(n);if(!Fv(o))return e;if(!r||o===n||o.startsWith(n))return t;let i=kl(e);return kl(t)!==null&&i===null?t:e}async function MT(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 TT(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,oe=new Map,W=new Map,j=o,X=!1,M=()=>{if(y)return y;let D,S="",F=L;return!X&&j?(D=j,X=!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=oe.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 oe.set(D,F),h(F),F},_=new Set,P=new Map,J=new Set,U=new Map,ue=D=>{if(!D)return!1;let S=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return S==="emit_artifact_markdown"||S==="emit_artifact_component"},fe=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},me=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()},He=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},Ee=new Map,Ie=new Map,yt=(D,S)=>{let F=He(S),q=Ie.get(D.id),K=$v(q,F);D.rawContent=K;let te=Ee.get(D.id),ve=De=>{let Qe=D.content??"";De.trim()!==""&&(Qe.trim().length===0||De.startsWith(Qe)||De.trimStart().startsWith(Qe.trim()))&&(D.content=De)},Me=()=>{if(te){let De=te.close?.();De instanceof Promise&&De.catch(()=>{})}Ee.delete(D.id),Ie.delete(D.id),D.streaming=!1,h(D)};if(!te){ve(F),Me();return}let Ce=kl(K);if(Ce!==null&&Ce.trim()!==""){ve(Ce),Me();return}let st=De=>{let Qe=typeof De=="string"?De:De?.text??null;if(Qe!==null&&Qe.trim()!=="")return Qe;let pn=te.getExtractedText();return pn!==null&&pn.trim()!==""?pn:F},Ct;try{Ct=te.processChunk(K)}catch{ve(F),Me();return}if(Ct instanceof Promise){Ct.then(De=>{ve(st(De)),Me()}).catch(()=>{ve(F),Me()});return}ve(st(Ct)),Me()},qe=null,Oe=(D,S,F,q)=>{D.rawContent=S,Ee.has(D.id)||Ee.set(D.id,e.createStreamParser());let K=Ee.get(D.id),te=S.trim().startsWith("{")||S.trim().startsWith("[");if(te&&Ie.set(D.id,S),K.__isPlainTextParser===!0){D.content=q!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D);return}let Me=K.processChunk(S);if(Me instanceof Promise)Me.then(Ce=>{let st=typeof Ce=="string"?Ce:Ce?.text??null;st!==null&&st.trim()!==""?(D.content=st,h(D)):!te&&!S.trim().startsWith("<")&&(D.content=q!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D))}).catch(()=>{D.content=q!==void 0?S:D.content+F,Ie.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D)});else{let Ce=typeof Me=="string"?Me:Me?.text??null;Ce!==null&&Ce.trim()!==""?(D.content=Ce,h(D)):!te&&!S.trim().startsWith("<")&&(D.content=q!==void 0?S:D.content+F,Ie.delete(D.id),Ee.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=Ie.get(D.id)??He(F);D.rawContent=K;let te=Ee.get(D.id),ve=null,Me=!1;if(te&&(ve=te.getExtractedText(),ve===null&&(ve=kl(K)),ve===null)){let Ce=te.processChunk(K);Ce instanceof Promise?(Me=!0,Ce.then(st=>{let Ct=typeof st=="string"?st:st?.text??null;Ct!==null&&(D.content=Ct,D.streaming=!1,Ee.delete(D.id),Ie.delete(D.id),h(D))}).catch(()=>{})):ve=typeof Ce=="string"?Ce:Ce?.text??null}if(!Me){ve!==null&&ve.trim()!==""?D.content=ve:Ie.has(D.id)||(D.content=He(F));let Ce=Ee.get(D.id);if(Ce){let st=Ce.close?.();st instanceof Promise&&st.catch(()=>{}),Ee.delete(D.id)}Ie.delete(D.id),D.streaming=!1,h(D)}},_e=(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},ye=[],ut,Zt=new Map,xt=0,xe="agent",Wt=!1,vt=null,Le=null,Xe=e.config().iterationDisplay??"separate";for(ut=()=>{for(let D=0;D<ye.length;D++){let S=ye[D];if(!Wt&&xe!=="flow"&&typeof S.stepType=="string"&&(xe="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),_e(F,q,"reasoning");continue}let K=S.id,te=T(K);te.reasoning=te.reasoning??{id:K,status:"streaming",chunks:[]},te.reasoning.startedAt=te.reasoning.startedAt??Date.now(),te.reasoning.completedAt=void 0,te.reasoning.durationMs=void 0,(S.scope==="loop"||S.scope==="turn")&&(te.reasoning.scope=S.scope),te.streaming=!0,te.reasoning.status="streaming",h(te)}else if(S.type==="reasoning_delta"){let F=typeof S.id=="string"?S.id:null;if(F&&H.has(F)&&B.has(F)){let te=B.get(F),ve=S.delta;ve&&te.reasoning&&(te.reasoning.chunks.push(String(ve)),h(te));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 ve=B.get(F);if(ve.reasoning){let Me=typeof S.text=="string"?S.text:"";Me&&ve.reasoning.chunks.length===0&&ve.reasoning.chunks.push(Me),ve.reasoning.status="complete",ve.streaming=!1,h(ve)}H.delete(F),B.delete(F);continue}let q=S.id,K=typeof S.text=="string"?S.text:"";!oe.get(q)&&(K||S.scope==="loop")&&T(q);let te=oe.get(q);if(te?.reasoning){(S.scope==="loop"||S.scope==="turn")&&(te.reasoning.scope=S.scope),K&&te.reasoning.chunks.length===0&&te.reasoning.chunks.push(K),te.reasoning.status="complete",te.reasoning.completedAt=Date.now();let ve=te.reasoning.startedAt??Date.now();te.reasoning.durationMs=Math.max(0,(te.reasoning.completedAt??Date.now())-ve),te.streaming=!1,h(te)}}else if(S.type==="tool_start"){y&&(y.streaming=!1,h(y),y=null),typeof S.iteration=="number"&&(xt=S.iteration);let F=S.toolCallId,q=S.toolName;if(ue(q)){_.add(F);continue}let K=fe(F),te=K.toolCall??{id:F,status:"pending"};te.name=q??te.name,te.status="running",te.success=void 0,te.error=void 0,te.duration=void 0,S.parameters!==void 0&&(te.args=S.parameters),te.startedAt=te.startedAt??me(S.startedAt),te.completedAt=void 0,te.durationMs=void 0,K.toolCall=te,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=fe(F),K=q.toolCall??{id:F,status:"running"};K.startedAt=K.startedAt??Date.now();let te=S.delta;te&&(K.chunks=K.chunks??[],K.chunks.push(String(te))),K.status="running",q.toolCall=K,q.streaming=!0,S.executionId&&(q.agentMetadata=q.agentMetadata??{executionId:S.executionId,iteration:xt}),h(q)}else if(S.type==="tool_complete"){let F=S.toolCallId;if(_.has(F)){_.delete(F);continue}let q=fe(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 te=S.executionTime;if(typeof te=="number")K.durationMs=te,K.duration=te;else{let ve=K.startedAt??Date.now();K.durationMs=Math.max(0,(K.completedAt??Date.now())-ve)}q.toolCall=K,q.streaming=!1,S.executionId&&(q.agentMetadata=q.agentMetadata??{executionId:S.executionId,iteration:S.iteration??xt}),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=fe(q),te=S.toolName,ve=S.origin==="webmcp"&&!bs(te)?`webmcp:${te}`:te,Me=bs(ve),Ce=K.toolCall??{id:q,status:"pending"};Ce.name=ve,Ce.args=S.parameters,Ce.status=Me?"running":"complete",Ce.chunks=Ce.chunks??[],Ce.startedAt=Ce.startedAt??me(S.awaitedAt),Me?(Ce.completedAt=void 0,Ce.duration=void 0,Ce.durationMs=void 0):Ce.completedAt=Ce.completedAt??Ce.startedAt,K.toolCall=Ce,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&&(xe==="flow"?($(K),qe=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 ve=typeof S.delta=="string"?S.delta:"",Me=(V.get(F)??"")+ve;if(V.set(F,Me),Me.trim()==="")continue;let Ce=_e(F,q);Ce.agentMetadata={...Ce.agentMetadata,executionId:S.executionId,parentToolId:q},Oe(Ce,Me,ve,void 0);continue}if(L=typeof S.id=="string"?S.id:L,xe==="flow"){let ve=typeof S.delta=="string"?S.delta:"";if(I+=ve,I.trim()==="")continue;let Me=M();Me.agentMetadata={executionId:S.executionId,iteration:xt},Oe(Me,I,ve,void 0),b=Me;continue}let K=typeof S.delta=="string"?S.delta:"";I+=K;let te=M();te.agentMetadata={executionId:S.executionId,iteration:xt,turnId:vt??void 0,agentName:Le?.agentName},Oe(te,I,K,void 0),b=te}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&&(xe==="flow"?($(q),qe=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=qe;qe=null;let q=S.stopReason,te=(S.result&&typeof S.result=="object"?S.result:null)?.response;if(F)q&&(F.stopReason=q),te!=null?yt(F,te):F.streaming!==!1&&(Ee.delete(F.id),Ie.delete(F.id),F.streaming=!1,h(F));else{let ve=te!=null&&te!=="";if(ve||!!q&&q!=="end_turn"&&q!=="unknown"){let Ce=M();q&&(Ce.stopReason=q),ve?$(Ce,te):(Ce.streaming=!1,h(Ce))}}continue}}else if(S.type==="execution_start")xe=S.kind==="flow"?"flow":"agent",Wt=!0,xe==="agent"&&(Le={executionId:S.executionId,agentId:S.agentId??"virtual",agentName:S.agentName??""});else if(S.type==="turn_start"){let F=typeof S.iteration=="number"?S.iteration:xt;if(F!==xt){if(Xe==="separate"&&F>1){let q=y;q&&(q.streaming=!1,h(q),y=null)}xt=F}vt=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=fe(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))}vt===S.id&&(vt=null)}else if(S.type==="media_start"){let F=String(S.id);Zt.set(F,{mediaType:typeof S.mediaType=="string"?S.mediaType:void 0,toolCallId:S.toolCallId,parts:[]})}else if(S.type==="media_delta"){let F=Zt.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=Zt.get(F);Zt.delete(F);let K=(typeof S.mediaType=="string"?S.mediaType:void 0)??q?.mediaType??"application/octet-stream",te=typeof S.data=="string"?S.data:void 0,ve=typeof S.url=="string"?S.url:q&&q.parts.length>0?q.parts.join(""):void 0,Me=null;if(te)Me={type:"media",data:te,mediaType:K};else if(ve){let De=K.toLowerCase();Me={type:De==="image"||De.startsWith("image/")?"image-url":"file-url",url:ve,mediaType:K}}let Ce=S.toolCallId??q?.toolCallId,st=Me?[Me]:[],Ct=[];for(let De of st){if(!De||typeof De!="object")continue;let Qe=De,pn=typeof Qe.type=="string"?Qe.type:void 0,Eo=typeof Qe.mediaType=="string"?Qe.mediaType.toLowerCase():"",ft=null,bt="";if(pn==="media"){let Ft=typeof Qe.data=="string"?Qe.data:void 0;if(!Ft)continue;bt=Eo.length>0?Eo:"application/octet-stream",ft=`data:${bt};base64,${Ft}`}else if(pn==="image-url"){let Ft=typeof Qe.url=="string"?Qe.url:void 0;if(!Ft)continue;bt=Eo,ft=Ft}else if(pn==="file-url"){let Ft=typeof Qe.url=="string"?Qe.url:void 0;if(!Ft)continue;bt=Eo,ft=Ft}else continue;if(ft)if(pn==="image-url"||bt.startsWith("image/"))Ct.push({type:"image",image:ft,...bt.includes("/")?{mimeType:bt}:{}});else if(bt.startsWith("audio/"))Ct.push({type:"audio",audio:ft,mimeType:bt});else if(bt.startsWith("video/"))Ct.push({type:"video",video:ft,mimeType:bt});else{let Ft=bt||"application/octet-stream";Ct.push({type:"file",data:ft,mimeType:Ft,filename:ET(Ft)})}}if(Ct.length>0){let De=d(),Qe=Ce,Eo={id:`agent-media-${typeof Qe=="string"&&Qe.length>0?`${Qe}-${De}`:String(De)}`,role:"assistant",content:"",contentParts:Ct,createdAt:new Date().toISOString(),streaming:!1,sequence:De,agentMetadata:{executionId:S.executionId,iteration:xt}};h(Eo);let ft=y;ft&&(ft.streaming=!1,h(ft)),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="",qe=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:Le?.agentId??"virtual",executionId:S.executionId??Le?.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:Le?.agentId??"virtual",executionId:S.executionId??Le?.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,te=S.file,ve;if(te&&typeof te=="object"&&!Array.isArray(te)&&typeof te.path=="string"&&typeof te.mimeType=="string"&&(ve={path:te.path,mimeType:te.mimeType,...typeof te.language=="string"?{language:te.language}:{}}),n({type:"artifact_start",id:q,artifactType:F,title:K,component:typeof S.component=="string"?S.component:void 0,...ve?{file:ve}:{}}),U.set(q,{markdown:"",title:K,file:ve}),!J.has(q)){J.add(q);let Me=or(e.config().features?.artifacts,{artifactType:F,...ve?{file:ve}:{}}),Ce=typeof S.component=="string"?S.component:void 0,st={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:Ml(Me,{artifactId:q,title:K,artifactType:F,status:"streaming",...ve?{file:ve}:{},...Ce?{component:Ce}:{}})};P.set(q,st),h(st)}}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=P.get(F);if(q){q.streaming=!1;try{let K=JSON.parse(q.rawContent??"{}");if(K.props){K.props.status="complete";let te=U.get(F);te?.markdown&&(K.props.markdown=te.markdown),te?.file&&(K.props.file=te.file),K.component==="PersonaArtifactInline"&&te?.props&&Object.keys(te.props).length>0&&(K.props.componentProps=te.props)}q.rawContent=JSON.stringify(K)}catch{}U.delete(F),h(q),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 q=y;q&&q.streaming&&(q.streaming=!1,h(q)),n({type:"status",status:"idle"})}}}ye.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
6
  `);l=F.pop()??"";for(let q of F){let K=q.split(`
7
- `),te="message",ve="",Me=null;for(let Qe of K)Qe.startsWith("event:")?te=Qe.replace("event:","").trim():Qe.startsWith("data:")?ve+=Qe.replace("data:","").trim():Qe.startsWith("id:")&&(Me=Qe.slice(3).trim());let Ce=()=>{Me!==null&&Me!==""&&n({type:"cursor",id:Me})};if(!ve){Ce();continue}let st;try{st=JSON.parse(ve)}catch(Qe){n({type:"error",error:Qe instanceof Error?Qe:new Error("Failed to parse chat stream payload")});continue}let Ct=st!==null&&typeof st=="object"&&!Array.isArray(st)?st:null,De=te!=="message"?te:typeof Ct?.type=="string"?Ct.type:"message";if(e.onSSEEvent?.(De,st),e.parseSSEEvent){C.current=y;let Qe=await ET(e,st,n,C,h,d,A);if(C.current&&C.current!==y&&(y=C.current),Qe){Ce();continue}}Ct&&(ye.push({...Ct,type:De}),ut()),Ce()}}ut()}var Fv,vf=Ve(()=>{"use strict";pi();ha();Cs();Nv();Fv=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<")});var qv,jv=Ve(()=>{qv="4.28.0"});var Xn,Sa=Ve(()=>{"use strict";jv();Xn=qv});var $d={};ys($d,{deleteAllConversations:()=>FT,deleteConversation:()=>NT,finalizeDisplayProjections:()=>DT,getConversation:()=>BT,historyErrorFor:()=>Zv,listConversations:()=>_T,readErrorCode:()=>wf,recoverFromUnauthorized:()=>Jv,resetVisitor:()=>$T});function HT(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 IT(e,t){if(t)return t;let n=e.config.features?.history?.scope;return n||(e.config.getIdentityProof?"verified-user":"browser")}async function RT(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 WT(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 wf(e,t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async function Jv(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",Yv);if(r.includes("visitor token required"))throw new e.HistoryClientError("visitor_token_missing",Xv);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",Qv);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 Zv(e,t,n){let o=await wf(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",Yv)):r.includes("visitor token required")?new e.HistoryClientError("visitor_token_missing",Xv):r.includes("visitor_identity_mismatch")?new e.HistoryClientError("visitor_identity_mismatch",Qv):new e.HistoryClientError("unauthorized",o||"History request was not authorized")}return new e.HistoryClientError("request_failed",o||`History request failed (${t.status})`)}function OT(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 Aa(e,t,n){Sf(e);let o=n.trackIdentity!==!1,r=await e.initSession(),s=null;IT(e,n.scope)==="verified-user"&&(s=await RT(e,r,o),s&&(r=await WT(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(HT(e,t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Xn,...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 Jv(e,await wf(e,d),s,o);continue}if(!d.ok)throw await Zv(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 OT(e,g,s!==null,o),f}}function Sf(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 _T(e,t){let n=await Aa(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(Kv),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async function BT(e,t,n){let o=await Aa(e,`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Kv(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 DT(e,t,n){Sf(e);let o=0;for(let c of n){let p=c.displayContent.length;if(p>zv)throw new e.HistoryClientError("payload_too_large",`displayContent exceeds the ${zv} character limit`);o+=p}if(o>Cf)throw new e.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${Cf} character limit`);await e.initSession();let r=e.historyInternals.visitorStore,s=r?.revision()??0,i=await Aa(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=Cf,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 NT(e,t,n){let o=await Aa(e,`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async function FT(e,t){let n=await Aa(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 $T(e){Sf(e),e.setHistoryIdentityStatus({state:"resetting"});try{await Aa(e,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var zv,Cf,Kv,Gv,Yv,Xv,Qv,Af=Ve(()=>{"use strict";Sa();zv=32768,Cf=49152,Kv=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",Yv="The identity proof was rejected",Xv="The request carried no visitor credential",Qv="The stored visitor belongs to a different signed-in user"});var tC,nC=Ve(()=>{"use strict";Rl();tC=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})),Wr(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:Rd(d,h),currentIndex:wo(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=wo(d),f=va(d);if(g>=f-1)return;let h=o.current?.getMessages().find(y=>y.toolCall?.id===d.getAttribute("data-tool-call-id"));h&&(Od(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})),Wr(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=Ss(h);if(A&&C){let L=ui(h)[wo(h)],I=new Set(Array.isArray(L)?L:[]);I.has(b)?I.delete(b):I.add(b),As(h,Array.from(I)),s(h);return}if(A){As(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=ff(h).length===0);return}r(h,b,{source:"pick",values:[b]});return}if(y==="submit-multi"){let b=ff(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(Ss(h)){As(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=ui(h)[wo(h)];(typeof B!="string"||B!==L)&&As(h,L)}let I=y==="next"?1:-1,H=wo(h)+I;Od(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&&As(h,L);let I=Rd(h,C);o.current.persistAskUserQuestionProgress(C,{answers:I,currentIndex:wo(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=Ss(h),L=wo(h),I=va(h),H=L>=I-1;if(!A){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:b},bubbles:!0,composed:!0})),Wr(n,b),C.agentMetadata?.awaitingLocalTool&&(o.current.markAskUserQuestionResolved(C),o.current.resolveAskUserQuestion(C,"(dismissed)"));return}As(h,"");let B=h.querySelector('[data-ask-free-text-input="true"]');if(B&&(B.value=""),H){let V=Rd(h,C),oe=i(V);r(h,oe||"(skipped)",{source:"submit-all",structured:V});return}Od(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(Ss(h)){As(h,y.trim()),s(h),l(h);return}r(h,y,{source:"free-text"})}}}}});function jT(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===""||oC.test(o)}function qT(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 jT(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(i===`
9
- `||i==="\uFFFC"||!r&&oC.test(i))return null;s--}return null}function rC(e,t,n){for(let o of n){let r=qT(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function sC(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}var oC,iC=Ve(()=>{"use strict";oC=/\s/});function aC(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 lC=Ve(()=>{"use strict"});var Ud=Ve(()=>{"use strict"});function uC(e){e.delayMs!==void 0&&(cC=jd(e.delayMs)),e.skipDelayMs!==void 0&&(dC=jd(e.skipDelayMs))}function gC(e){Vd.get(e)?.hide()}function vn(e){Vd.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:i=zT,viewportPadding:l=KT}=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=()=>jd(e.delayMs??cC),B=()=>jd(e.skipDelayMs??dC),V=()=>{y!==void 0&&(p().clearTimeout(y),y=void 0)},oe=()=>{V();let me=d!==null;h?.(),h=null,d?.remove(),d=null,g=null,f=null,me&&YT(B())},W=()=>{if(!d)return;let me=c(),He=p(),Ee=t.getBoundingClientRect(),Ie=d.getBoundingClientRect(),yt=me.documentElement.clientWidth||He.innerWidth,qe=me.documentElement.clientHeight||He.innerHeight,Oe=yt-l-Ie.width,$=Ee.left+Ee.width/2-Ie.width/2,_e=Ef($,l,Oe),ye=Ee.top-l,ut=qe-l-Ee.bottom,Zt=Ie.height+i,xt=ye>=Zt||ye>=ut?"top":"bottom",xe=xt==="top"?Ee.top-i-Ie.height:Ee.bottom+i,Wt=qe-l-Ie.height,vt=Ef(xe,l,Wt),Le=Ee.left+Ee.width/2,Xe=Math.max(xf,Ie.width-xf),D=Ef(Le-_e,xf,Xe);d.dataset.placement=xt,d.style.left=`${_e}px`,d.style.top=`${vt}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${D}px`)},j=()=>{if(A||!s||d||!t.isConnected||XT(t))return;let me=L(),He=QT(t);if(!me||!He)return;let Ee=c(),Ie=p();d=Ee.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(wa);let yt=Ie.getComputedStyle?.(t);if(yt){for(let Zt of JT){let xt=yt.getPropertyValue(Zt).trim();xt&&d.style.setProperty(Zt,xt)}yt.fontFamily&&(d.style.fontFamily=yt.fontFamily)}g=Ee.createElement("span"),g.className="persona-control-tooltip__label",g.textContent=me,d.appendChild(g);let qe=I();qe&&(f=Ee.createElement("span"),f.className="persona-control-tooltip__hint",f.textContent=qe,d.appendChild(f));let Oe=Ee.createElement("span");Oe.className="persona-control-tooltip__arrow",d.appendChild(Oe),He.appendChild(d),W(),d.dataset.state="open";let $=()=>{if(!t.isConnected){oe();return}g&&(g.textContent=L()),f&&(f.textContent=I()),W()};Ie.addEventListener("scroll",$,!0),Ie.addEventListener("resize",$);let _e=t.getRootNode(),ye=fC(_e)?_e:Ee.documentElement,ut=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||oe()});ut?.observe(ye,{childList:!0,subtree:!0}),h=()=>{Ie.removeEventListener("scroll",$,!0),Ie.removeEventListener("resize",$),ut?.disconnect()}},X=me=>{if(!(A||d)){if(V(),me||H()<=0||GT()){j();return}y=p().setTimeout(()=>{y=void 0,j()},H())}},M=()=>{b||C?X(C):oe()},T=()=>{let me=p();(!me.matchMedia||!me.matchMedia("(hover: none)").matches)&&(b=!0,M())},_=()=>{b=!1,M()},k=()=>{try{C=t.matches(":focus-visible")}catch{C=!0}M()},J=()=>{C=!1,M()},U=()=>{b=!1,C=!1,oe()},ue=me=>{me.key==="Escape"&&U()};n.addEventListener("mouseenter",T),n.addEventListener("mouseleave",_),t.addEventListener("focus",k),t.addEventListener("blur",J),t.addEventListener("keydown",ue),t.addEventListener("click",U);let fe={get isOpen(){return d!==null},show:j,hide:oe,reposition:W,destroy:()=>{A||(A=!0,oe(),n.removeEventListener("mouseenter",T),n.removeEventListener("mouseleave",_),t.removeEventListener("focus",k),t.removeEventListener("blur",J),t.removeEventListener("keydown",ue),t.removeEventListener("click",U),Vd.delete(t))}};return Vd.set(t,fe),fe}var zT,KT,xf,cC,dC,pC,jd,GT,YT,Vd,Mf,XT,fC,QT,Ef,JT,xa=Ve(()=>{"use strict";_o();Ud();zT=8,KT=8,xf=10,cC=200,dC=300,pC=0,jd=e=>Math.max(0,e);GT=()=>Date.now()<pC,YT=e=>{pC=e>0?Date.now()+e:0},Vd=new WeakMap,Mf="data-persona-tooltip-suppressed",XT=e=>typeof e.closest=="function"&&e.closest(`[${Mf}]`)!==null;fC=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,QT=e=>{let t=e.getRootNode?.();return fC(t)?t:e.ownerDocument.body},Ef=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),JT=[...["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 ZT,hi,Tf,kf=Ve(()=>{"use strict";ZT=(e,t)=>e.visible!==!1&&(e.mode!=="transient"||t==="connecting"||t==="paused"||t==="resuming"||t==="error"),hi=(e,t,n)=>{let o=t.mode==="transient",r=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=ZT(t,n)||o&&r&&t.visible!==!1?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},Tf=(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 Bo(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];mC(s)&&mC(r)?n[o]=Bo(s,r):n[o]=r}return n}var mC,qd=Ve(()=>{"use strict";mC=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function zd(e,t=""){return Object.entries(e).flatMap(([n,o])=>{let r=t?`${t}.${n}`:n;return Lf(o)?zd(o,r):[r]})}function hC(e,t){for(let n of t.split(".")){if(!Lf(e)||!Object.prototype.hasOwnProperty.call(e,n))return"absent";if(e=e[n],e===void 0)return"clear"}return"explicit"}function yC(e,t){return e?.[Pf]??t.filter(n=>hC(e,n)==="explicit")}function Hf(e,t){return Object.defineProperty(e,Pf,{value:t,enumerable:!0,configurable:!0}),e}function If(e,t,n){return Hf(e,yC(t,zd(n)))}function bC(e,t,n){let o=t[Pf];if(o)return o;let r=new Set(yC(e,n));for(let s of n){let i=hC(t,s);i==="clear"&&r.delete(s),i==="explicit"&&r.add(s)}return[...r]}function vC(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(!Lf(c)){i=void 0;break}i[l]={...c},i=i[l]}i&&delete i[s[s.length-1]]}return o}var Pf,Lf,Rf=Ve(()=>{"use strict";Pf=Symbol("persona.defaultsProvenance"),Lf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var CC,Wf,yi,Kd,ek,_r,Of,_f,wC,Ea=Ve(()=>{"use strict";CC="var(--persona-components-panel-width)",Wf=Symbol("persona.panelAliasProvenance"),yi=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),Kd=(e,t)=>yi(e,t)&&e[t]!==void 0,ek=e=>({launcherWidth:Kd(e?.launcher,"width"),legacyLauncherWidth:Kd(e,"launcherWidth"),sidebarWidth:Kd(e?.launcher,"sidebarWidth"),dockWidth:Kd(e?.launcher?.dock,"width")}),_r=e=>{let t=e?.[Wf];return t?{...t}:ek(e)},Of=(e,t)=>(Object.defineProperty(e,Wf,{value:t,enumerable:!0,configurable:!0}),e),_f=(e,t)=>Of(e,_r(t)),wC=(e,t)=>{let n=t[Wf];if(n)return{...n};let o=_r(e);return yi(t,"launcherWidth")&&(o.legacyLauncherWidth=t.launcherWidth!==void 0),yi(t,"launcher")&&t.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(yi(t.launcher,"width")&&(o.launcherWidth=t.launcher?.width!==void 0),yi(t.launcher,"sidebarWidth")&&(o.sidebarWidth=t.launcher?.sidebarWidth!==void 0),yi(t.launcher,"dock")&&t.launcher?.dock===void 0?o.dockWidth=!1:yi(t.launcher?.dock,"width")&&(o.dockWidth=t.launcher?.dock?.width!==void 0),o)}});function Es(e){return e?.future?.v5Defaults===!0?"v5":"v4"}function xC(e){let t=Es(e)==="v5"?bi:ok;return Bo(nk,t)}function SC(e,t){if(!(!e&&!t))return e?t?Bo(e,t):e:t}function Ma(e){let t=xC(e);return e?If(_f({...t,...e,theme:SC(t.theme,e.theme),darkTheme:SC(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,bi):If(_f(t),void 0,bi)}var vi,AC,_l,Bf,Br,Ci,tk,nk,ok,rk,bi,EC,So=Ve(()=>{"use strict";qd();Rf();Ea();Ud();vi="min(440px, calc(100vw - 24px))",AC="440px",_l="40px",Bf="How can I help...",Br={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},Ci={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},tk={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:vi,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:_l,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)"},nk={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:tk,copy:{inputPlaceholder:Bf,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:Br,reasoningDisplay:Ci,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},ok={},rk={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},bi={launcher:rk,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"}}}};EC=xC()});function MC(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Gd(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function ka(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function TC(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ao(e){return{type:"text",text:e}}function Yd(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function kC(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 PC(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 ik(e){return LC.includes(e)||e.startsWith("image/")}function Xd(e){return ik(e.type)}function HC(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function IC(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Xd(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 RC(e,t=Dr,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 ak(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function WC(e,t){let n=ak(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 Ta,LC,sk,Dr,Nr=Ve(()=>{"use strict";Ta="[Image]";LC=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],sk=["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"],Dr=[...LC,...sk]});function Df(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 Qd(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function OC(e,t){e.style.maxHeight=`${t*Df(e)}px`,e.style.overflowY="auto"}function Bl(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 _C(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function BC(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||!_C(t)}function lk(e){return(e.submitKey??"enter")!=="enter"||_C(e)?"enter":"send"}function Jd(e,t){e.setAttribute("enterkeyhint",lk(t))}function Zd(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 ep=Ve(()=>{"use strict"});var so,Do,$f,Qn,tp,np,dk,Uf,op,Pa,rp,sp,ip,Ms=Ve(()=>{"use strict";kf();Ze();Pt();So();Nr();xa();ep();so="persona-composer-control",Do="persona-composer-control--glyph",$f=40,Qn=24,tp=(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)}},np=(e,t)=>{let n=x("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??Bf,n.dir="auto",Jd(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Bl(n)}),Zd(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=Qd(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*Df(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}},dk="[data-persona-glyph-stack]",Uf=(e,t,n="send")=>{let o=Q("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},op=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??"")||$f,h=t.backgroundColor,y=t.textColor,b=x("div","persona-send-button-wrapper"),C=Q("button",{className:Dn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${so}`:"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),oe=t.iconStrokeWidth??2,W=y?.trim()||"currentColor";if(r&&(A=ge(r,V,W,oe)),L=ge(s,V,W,oe),!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=Uf(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),vn({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 oe=V==="stop"?l:i;C.setAttribute("aria-label",oe),C.setAttribute("data-persona-send-mode",V),n?(C.querySelector(dk)??I)?.setAttribute("data-mode",V):C.textContent=V==="stop"?p:c},glyphStack:I}},Pa=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=Q("button",{className:Dn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",so,!c&&Do),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=ge(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 vn({anchor:h,trigger:f,text:()=>h.getAttribute("aria-label")??C,enabled:A}),{button:h,wrapper:f}},rp=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??Dr).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=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${so} ${Do}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=ge(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 vn({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:s,input:o,previewsContainer:n}},sp=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",""),hi(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},ip=()=>Q("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}})});function ap(e){let{config:t,onOpen:n}=e,o=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",s=x("div","persona-send-button-wrapper"),i=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${so} ${Do}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=ge(o,Qn,"currentColor",1.5);return l?i.appendChild(l):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),n()}),s.appendChild(i),vn({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:s}}var Vf=Ve(()=>{"use strict";Ze();Pt();xa();Ms()});var fW,pk,lp,jf=Ve(()=>{"use strict";dn();({setLoader:fW,load:pk}=lt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")})),lp=pk});var yW,uk,cp,qf=Ve(()=>{"use strict";dn();({setLoader:yW,load:uk}=lt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0})),cp=uk});function Dl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Q("span",{className:Dn("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=ge(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(Q("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}var zf=Ve(()=>{"use strict";Ze();Pt()});function DC(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:o,createMentionButton:r}=e.deps??gk,s=e.config.contextMentions;if(!s?.enabled)return null;let i=aC(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(`
7
+ `),te="message",ve="",Me=null;for(let Qe of K)Qe.startsWith("event:")?te=Qe.replace("event:","").trim():Qe.startsWith("data:")?ve+=Qe.replace("data:","").trim():Qe.startsWith("id:")&&(Me=Qe.slice(3).trim());let Ce=()=>{Me!==null&&Me!==""&&n({type:"cursor",id:Me})};if(!ve){Ce();continue}let st;try{st=JSON.parse(ve)}catch(Qe){n({type:"error",error:Qe instanceof Error?Qe:new Error("Failed to parse chat stream payload")});continue}let Ct=st!==null&&typeof st=="object"&&!Array.isArray(st)?st:null,De=te!=="message"?te:typeof Ct?.type=="string"?Ct.type:"message";if(e.onSSEEvent?.(De,st),e.parseSSEEvent){C.current=y;let Qe=await MT(e,st,n,C,h,d,A);if(C.current&&C.current!==y&&(y=C.current),Qe){Ce();continue}}Ct&&(ye.push({...Ct,type:De}),ut()),Ce()}}ut()}var Fv,vf=Ve(()=>{"use strict";pi();ha();Cs();Nv();Fv=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<")});var qv,jv=Ve(()=>{qv="4.28.1"});var Xn,Sa=Ve(()=>{"use strict";jv();Xn=qv});var $d={};ys($d,{deleteAllConversations:()=>$T,deleteConversation:()=>FT,finalizeDisplayProjections:()=>NT,getConversation:()=>DT,historyErrorFor:()=>Zv,listConversations:()=>BT,readErrorCode:()=>wf,recoverFromUnauthorized:()=>Jv,resetVisitor:()=>UT});function IT(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 RT(e,t){if(t)return t;let n=e.config.features?.history?.scope;return n||(e.config.getIdentityProof?"verified-user":"browser")}async function WT(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 OT(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 wf(e,t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async function Jv(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",Yv);if(r.includes("visitor token required"))throw new e.HistoryClientError("visitor_token_missing",Xv);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",Qv);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 Zv(e,t,n){let o=await wf(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",Yv)):r.includes("visitor token required")?new e.HistoryClientError("visitor_token_missing",Xv):r.includes("visitor_identity_mismatch")?new e.HistoryClientError("visitor_identity_mismatch",Qv):new e.HistoryClientError("unauthorized",o||"History request was not authorized")}return new e.HistoryClientError("request_failed",o||`History request failed (${t.status})`)}function _T(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 Aa(e,t,n){Sf(e);let o=n.trackIdentity!==!1,r=await e.initSession(),s=null;RT(e,n.scope)==="verified-user"&&(s=await WT(e,r,o),s&&(r=await OT(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(IT(e,t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Xn,...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 Jv(e,await wf(e,d),s,o);continue}if(!d.ok)throw await Zv(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 _T(e,g,s!==null,o),f}}function Sf(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 BT(e,t){let n=await Aa(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(Kv),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async function DT(e,t,n){let o=await Aa(e,`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Kv(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 NT(e,t,n){Sf(e);let o=0;for(let c of n){let p=c.displayContent.length;if(p>zv)throw new e.HistoryClientError("payload_too_large",`displayContent exceeds the ${zv} character limit`);o+=p}if(o>Cf)throw new e.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${Cf} character limit`);await e.initSession();let r=e.historyInternals.visitorStore,s=r?.revision()??0,i=await Aa(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=Cf,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 FT(e,t,n){let o=await Aa(e,`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async function $T(e,t){let n=await Aa(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 UT(e){Sf(e),e.setHistoryIdentityStatus({state:"resetting"});try{await Aa(e,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var zv,Cf,Kv,Gv,Yv,Xv,Qv,Af=Ve(()=>{"use strict";Sa();zv=32768,Cf=49152,Kv=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",Yv="The identity proof was rejected",Xv="The request carried no visitor credential",Qv="The stored visitor belongs to a different signed-in user"});var tC,nC=Ve(()=>{"use strict";Rl();tC=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})),Wr(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:Rd(d,h),currentIndex:wo(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=wo(d),f=va(d);if(g>=f-1)return;let h=o.current?.getMessages().find(y=>y.toolCall?.id===d.getAttribute("data-tool-call-id"));h&&(Od(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})),Wr(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=Ss(h);if(A&&C){let L=ui(h)[wo(h)],I=new Set(Array.isArray(L)?L:[]);I.has(b)?I.delete(b):I.add(b),As(h,Array.from(I)),s(h);return}if(A){As(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=ff(h).length===0);return}r(h,b,{source:"pick",values:[b]});return}if(y==="submit-multi"){let b=ff(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(Ss(h)){As(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=ui(h)[wo(h)];(typeof B!="string"||B!==L)&&As(h,L)}let I=y==="next"?1:-1,H=wo(h)+I;Od(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&&As(h,L);let I=Rd(h,C);o.current.persistAskUserQuestionProgress(C,{answers:I,currentIndex:wo(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=Ss(h),L=wo(h),I=va(h),H=L>=I-1;if(!A){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:b},bubbles:!0,composed:!0})),Wr(n,b),C.agentMetadata?.awaitingLocalTool&&(o.current.markAskUserQuestionResolved(C),o.current.resolveAskUserQuestion(C,"(dismissed)"));return}As(h,"");let B=h.querySelector('[data-ask-free-text-input="true"]');if(B&&(B.value=""),H){let V=Rd(h,C),oe=i(V);r(h,oe||"(skipped)",{source:"submit-all",structured:V});return}Od(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(Ss(h)){As(h,y.trim()),s(h),l(h);return}r(h,y,{source:"free-text"})}}}}});function qT(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===""||oC.test(o)}function zT(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 qT(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(i===`
9
+ `||i==="\uFFFC"||!r&&oC.test(i))return null;s--}return null}function rC(e,t,n){for(let o of n){let r=zT(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function sC(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}var oC,iC=Ve(()=>{"use strict";oC=/\s/});function aC(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 lC=Ve(()=>{"use strict"});var Ud=Ve(()=>{"use strict"});function uC(e){e.delayMs!==void 0&&(cC=jd(e.delayMs)),e.skipDelayMs!==void 0&&(dC=jd(e.skipDelayMs))}function gC(e){Vd.get(e)?.hide()}function vn(e){Vd.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:i=KT,viewportPadding:l=GT}=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=()=>jd(e.delayMs??cC),B=()=>jd(e.skipDelayMs??dC),V=()=>{y!==void 0&&(p().clearTimeout(y),y=void 0)},oe=()=>{V();let me=d!==null;h?.(),h=null,d?.remove(),d=null,g=null,f=null,me&&XT(B())},W=()=>{if(!d)return;let me=c(),He=p(),Ee=t.getBoundingClientRect(),Ie=d.getBoundingClientRect(),yt=me.documentElement.clientWidth||He.innerWidth,qe=me.documentElement.clientHeight||He.innerHeight,Oe=yt-l-Ie.width,$=Ee.left+Ee.width/2-Ie.width/2,_e=Ef($,l,Oe),ye=Ee.top-l,ut=qe-l-Ee.bottom,Zt=Ie.height+i,xt=ye>=Zt||ye>=ut?"top":"bottom",xe=xt==="top"?Ee.top-i-Ie.height:Ee.bottom+i,Wt=qe-l-Ie.height,vt=Ef(xe,l,Wt),Le=Ee.left+Ee.width/2,Xe=Math.max(xf,Ie.width-xf),D=Ef(Le-_e,xf,Xe);d.dataset.placement=xt,d.style.left=`${_e}px`,d.style.top=`${vt}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${D}px`)},j=()=>{if(A||!s||d||!t.isConnected||QT(t))return;let me=L(),He=JT(t);if(!me||!He)return;let Ee=c(),Ie=p();d=Ee.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(wa);let yt=Ie.getComputedStyle?.(t);if(yt){for(let Zt of ZT){let xt=yt.getPropertyValue(Zt).trim();xt&&d.style.setProperty(Zt,xt)}yt.fontFamily&&(d.style.fontFamily=yt.fontFamily)}g=Ee.createElement("span"),g.className="persona-control-tooltip__label",g.textContent=me,d.appendChild(g);let qe=I();qe&&(f=Ee.createElement("span"),f.className="persona-control-tooltip__hint",f.textContent=qe,d.appendChild(f));let Oe=Ee.createElement("span");Oe.className="persona-control-tooltip__arrow",d.appendChild(Oe),He.appendChild(d),W(),d.dataset.state="open";let $=()=>{if(!t.isConnected){oe();return}g&&(g.textContent=L()),f&&(f.textContent=I()),W()};Ie.addEventListener("scroll",$,!0),Ie.addEventListener("resize",$);let _e=t.getRootNode(),ye=fC(_e)?_e:Ee.documentElement,ut=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||oe()});ut?.observe(ye,{childList:!0,subtree:!0}),h=()=>{Ie.removeEventListener("scroll",$,!0),Ie.removeEventListener("resize",$),ut?.disconnect()}},X=me=>{if(!(A||d)){if(V(),me||H()<=0||YT()){j();return}y=p().setTimeout(()=>{y=void 0,j()},H())}},M=()=>{b||C?X(C):oe()},T=()=>{let me=p();(!me.matchMedia||!me.matchMedia("(hover: none)").matches)&&(b=!0,M())},_=()=>{b=!1,M()},P=()=>{try{C=t.matches(":focus-visible")}catch{C=!0}M()},J=()=>{C=!1,M()},U=()=>{b=!1,C=!1,oe()},ue=me=>{me.key==="Escape"&&U()};n.addEventListener("mouseenter",T),n.addEventListener("mouseleave",_),t.addEventListener("focus",P),t.addEventListener("blur",J),t.addEventListener("keydown",ue),t.addEventListener("click",U);let fe={get isOpen(){return d!==null},show:j,hide:oe,reposition:W,destroy:()=>{A||(A=!0,oe(),n.removeEventListener("mouseenter",T),n.removeEventListener("mouseleave",_),t.removeEventListener("focus",P),t.removeEventListener("blur",J),t.removeEventListener("keydown",ue),t.removeEventListener("click",U),Vd.delete(t))}};return Vd.set(t,fe),fe}var KT,GT,xf,cC,dC,pC,jd,YT,XT,Vd,Mf,QT,fC,JT,Ef,ZT,xa=Ve(()=>{"use strict";_o();Ud();KT=8,GT=8,xf=10,cC=200,dC=300,pC=0,jd=e=>Math.max(0,e);YT=()=>Date.now()<pC,XT=e=>{pC=e>0?Date.now()+e:0},Vd=new WeakMap,Mf="data-persona-tooltip-suppressed",QT=e=>typeof e.closest=="function"&&e.closest(`[${Mf}]`)!==null;fC=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,JT=e=>{let t=e.getRootNode?.();return fC(t)?t:e.ownerDocument.body},Ef=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),ZT=[...["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 eP,hi,Tf,Pf=Ve(()=>{"use strict";eP=(e,t)=>e.visible!==!1&&(e.mode!=="transient"||t==="connecting"||t==="paused"||t==="resuming"||t==="error"),hi=(e,t,n)=>{let o=t.mode==="transient",r=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=eP(t,n)||o&&r&&t.visible!==!1?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},Tf=(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 Bo(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];mC(s)&&mC(r)?n[o]=Bo(s,r):n[o]=r}return n}var mC,qd=Ve(()=>{"use strict";mC=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});function zd(e,t=""){return Object.entries(e).flatMap(([n,o])=>{let r=t?`${t}.${n}`:n;return Lf(o)?zd(o,r):[r]})}function hC(e,t){for(let n of t.split(".")){if(!Lf(e)||!Object.prototype.hasOwnProperty.call(e,n))return"absent";if(e=e[n],e===void 0)return"clear"}return"explicit"}function yC(e,t){return e?.[kf]??t.filter(n=>hC(e,n)==="explicit")}function Hf(e,t){return Object.defineProperty(e,kf,{value:t,enumerable:!0,configurable:!0}),e}function If(e,t,n){return Hf(e,yC(t,zd(n)))}function bC(e,t,n){let o=t[kf];if(o)return o;let r=new Set(yC(e,n));for(let s of n){let i=hC(t,s);i==="clear"&&r.delete(s),i==="explicit"&&r.add(s)}return[...r]}function vC(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(!Lf(c)){i=void 0;break}i[l]={...c},i=i[l]}i&&delete i[s[s.length-1]]}return o}var kf,Lf,Rf=Ve(()=>{"use strict";kf=Symbol("persona.defaultsProvenance"),Lf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)});var CC,Wf,yi,Kd,tP,_r,Of,_f,wC,Ea=Ve(()=>{"use strict";CC="var(--persona-components-panel-width)",Wf=Symbol("persona.panelAliasProvenance"),yi=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),Kd=(e,t)=>yi(e,t)&&e[t]!==void 0,tP=e=>({launcherWidth:Kd(e?.launcher,"width"),legacyLauncherWidth:Kd(e,"launcherWidth"),sidebarWidth:Kd(e?.launcher,"sidebarWidth"),dockWidth:Kd(e?.launcher?.dock,"width")}),_r=e=>{let t=e?.[Wf];return t?{...t}:tP(e)},Of=(e,t)=>(Object.defineProperty(e,Wf,{value:t,enumerable:!0,configurable:!0}),e),_f=(e,t)=>Of(e,_r(t)),wC=(e,t)=>{let n=t[Wf];if(n)return{...n};let o=_r(e);return yi(t,"launcherWidth")&&(o.legacyLauncherWidth=t.launcherWidth!==void 0),yi(t,"launcher")&&t.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(yi(t.launcher,"width")&&(o.launcherWidth=t.launcher?.width!==void 0),yi(t.launcher,"sidebarWidth")&&(o.sidebarWidth=t.launcher?.sidebarWidth!==void 0),yi(t.launcher,"dock")&&t.launcher?.dock===void 0?o.dockWidth=!1:yi(t.launcher?.dock,"width")&&(o.dockWidth=t.launcher?.dock?.width!==void 0),o)}});function Es(e){return e?.future?.v5Defaults===!0?"v5":"v4"}function xC(e){let t=Es(e)==="v5"?bi:rP;return Bo(oP,t)}function SC(e,t){if(!(!e&&!t))return e?t?Bo(e,t):e:t}function Ma(e){let t=xC(e);return e?If(_f({...t,...e,theme:SC(t.theme,e.theme),darkTheme:SC(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,bi):If(_f(t),void 0,bi)}var vi,AC,_l,Bf,Br,Ci,nP,oP,rP,sP,bi,EC,So=Ve(()=>{"use strict";qd();Rf();Ea();Ud();vi="min(440px, calc(100vw - 24px))",AC="440px",_l="40px",Bf="How can I help...",Br={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},Ci={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},nP={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:vi,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:_l,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)"},oP={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:nP,copy:{inputPlaceholder:Bf,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:Br,reasoningDisplay:Ci,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},rP={},sP={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},bi={launcher:sP,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"}}}};EC=xC()});function MC(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Gd(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Pa(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function TC(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ao(e){return{type:"text",text:e}}function Yd(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function PC(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 kC(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 aP(e){return LC.includes(e)||e.startsWith("image/")}function Xd(e){return aP(e.type)}function HC(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function IC(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Xd(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 RC(e,t=Dr,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 lP(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function WC(e,t){let n=lP(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 Ta,LC,iP,Dr,Nr=Ve(()=>{"use strict";Ta="[Image]";LC=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],iP=["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"],Dr=[...LC,...iP]});function Df(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 Qd(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function OC(e,t){e.style.maxHeight=`${t*Df(e)}px`,e.style.overflowY="auto"}function Bl(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 _C(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function BC(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||!_C(t)}function cP(e){return(e.submitKey??"enter")!=="enter"||_C(e)?"enter":"send"}function Jd(e,t){e.setAttribute("enterkeyhint",cP(t))}function Zd(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 ep=Ve(()=>{"use strict"});var so,Do,$f,Qn,tp,np,pP,Uf,op,ka,rp,sp,ip,Ms=Ve(()=>{"use strict";Pf();Ze();kt();So();Nr();xa();ep();so="persona-composer-control",Do="persona-composer-control--glyph",$f=40,Qn=24,tp=(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)}},np=(e,t)=>{let n=x("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??Bf,n.dir="auto",Jd(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Bl(n)}),Zd(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=Qd(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*Df(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}},pP="[data-persona-glyph-stack]",Uf=(e,t,n="send")=>{let o=Q("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},op=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??"")||$f,h=t.backgroundColor,y=t.textColor,b=x("div","persona-send-button-wrapper"),C=Q("button",{className:Dn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${so}`:"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),oe=t.iconStrokeWidth??2,W=y?.trim()||"currentColor";if(r&&(A=ge(r,V,W,oe)),L=ge(s,V,W,oe),!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=Uf(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),vn({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 oe=V==="stop"?l:i;C.setAttribute("aria-label",oe),C.setAttribute("data-persona-send-mode",V),n?(C.querySelector(pP)??I)?.setAttribute("data-mode",V):C.textContent=V==="stop"?p:c},glyphStack:I}},ka=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=Q("button",{className:Dn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",so,!c&&Do),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=ge(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 vn({anchor:h,trigger:f,text:()=>h.getAttribute("aria-label")??C,enabled:A}),{button:h,wrapper:f}},rp=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??Dr).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=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${so} ${Do}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=ge(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 vn({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??c}),{button:i,wrapper:s,input:o,previewsContainer:n}},sp=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",""),hi(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},ip=()=>Q("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}})});function ap(e){let{config:t,onOpen:n}=e,o=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",s=x("div","persona-send-button-wrapper"),i=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${so} ${Do}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=ge(o,Qn,"currentColor",1.5);return l?i.appendChild(l):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),n()}),s.appendChild(i),vn({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:s}}var Vf=Ve(()=>{"use strict";Ze();kt();xa();Ms()});var mW,uP,lp,jf=Ve(()=>{"use strict";dn();({setLoader:mW,load:uP}=lt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")})),lp=uP});var bW,gP,cp,qf=Ve(()=>{"use strict";dn();({setLoader:bW,load:gP}=lt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0})),cp=gP});function Dl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Q("span",{className:Dn("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=ge(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(Q("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}var zf=Ve(()=>{"use strict";Ze();kt()});function DC(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:o,createMentionButton:r}=e.deps??fP,s=e.config.contextMentions;if(!s?.enabled)return null;let i=aC(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
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??Q("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:oe,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=>Dl(M,{render:s.renderMentionToken}),onMentionRemoved:M=>f?.untrackMention(M)});b=j.input,C=j.destroy;let X=y;X.replaceWith(j.element),y=j.element,L={next:j.element,prev:X},A?.(j.element,X),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(X=>X?.openMenu(W.trigger))}});B.push(j),V.set(W.trigger,j.button)}let oe=(W,j,X)=>{let M=V.get(j);M&&(M.setAttribute("aria-expanded",W?"true":"false"),W?M.setAttribute("aria-controls",X):M.removeAttribute("aria-controls"))};return{affordanceButtons:B.map(W=>W.wrapper),contextRow:g,handleInput:W=>{if(f){f.handleInput();return}if(!sC(W))return;let j=y,X=j.selectionStart??0;rC(j.value,X,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,X=j.selectionStart===0&&j.selectionEnd===0;if((j.value.length===0||X)&&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 gk,NC=Ve(()=>{"use strict";Ze();iC();lC();Vf();jf();Pt();qf();zf();gk={loadContextMentions:()=>lp(),loadContextMentionsInline:()=>cp(),renderLucideIcon:(...e)=>ge(...e),createMentionButton:(...e)=>ap(...e)}});var dp={};ys(dp,{createAskUserSheetHandlers:()=>tC,createContextMentionOrchestrator:()=>DC});var Kf=Ve(()=>{"use strict";nC();NC()});var gp={};ys(gp,{resolveApproval:()=>bk,resolveAskUserQuestion:()=>vk,resolveWebMcpToolCall:()=>Sk,resolveWebMcpToolCallBatch:()=>UC});async function bk(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 vk(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 Ck(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 $C(e,t){return t.toolCall?.name!==Oo?!1:(e.s.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function wk(e,t){let n=Ck(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 up(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 UC(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)||$C(e,c))return null;e.s.webMcpInflightKeys.add(g),o.push(g);let f=wk(e,c),h=c.agentMetadata?.webMcpToolCallId??p;if(p===Oo)return{dedupeKey:g,resumeKey:h,output:_v(),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))),up(e,c,Yf(A?"Aborted by cancel()":yk(C)),f),e.s.webMcpInflightKeys.delete(g),null}return r.signal.aborted?(up(e,c,Yf("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;up(e,g.toolMessage,g.output,g.startedAt,g.completedAt,{...f===Oo?{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)up(e,d.toolMessage,Yf("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 Sk(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 Ak(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)||$C(e,t)))return UC(e,n,[t])}async function Ak(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 Yf,yk,Xf=Ve(()=>{"use strict";Ca();Yf=e=>({isError:!0,content:[{type:"text",text:e}]}),yk=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t});function Jf(e){if(!e)return qC;let t={...qC};for(let n of Tk){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var Tk,qC,zC=Ve(()=>{"use strict";Tk=["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"],qC={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 YC(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){Zf("renderHistoryView cleanup",B)}},d=(H,B)=>{for(let V of t){let oe=V[H];if(oe)try{let W=oe(B);if(W)return W}catch(W){Zf(H,W)}}return null},g=()=>({presentation:e.getPresentation(),config:n}),f={header:H=>i?d("renderHistoryHeader",Object.freeze({...g(),returnSurface:e.getReturnSurface(),identityStatus:Fr(H.identityStatus),pendingAction:GC(H.pendingAction),copy:Fr(H.copy),actions:Object.freeze({close:b.close,startNewConversation:b.startNewConversation}),defaultRenderer:H.defaultRenderer})):null,conversation:H=>i?d("renderHistoryConversation",Object.freeze({...g(),conversation:KC(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:Fr(H.state),identityStatus:Fr(H.identityStatus),copy:Fr(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(KC)),activeConversationId:H.activeConversationId,state:Fr(H.state),pendingAction:GC(H.pendingAction),identityStatus:Fr(H.identityStatus),nextCursor:H.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:Fr(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(oe){Zf("renderHistoryView",oe),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 Zf,Fr,KC,GC,XC=Ve(()=>{"use strict";Zf=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},Fr=e=>Object.freeze({...e}),KC=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),GC=e=>e?Fr(e):null});var QC,em,kk,fp,mp,Pk,JC,hp,Nl,Lk,Hk,ZC,yp=Ve(()=>{"use strict";QC=null,em=()=>{if(QC!==null)return QC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},kk="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",fp=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},mp=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 fp("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(fp("unsupported",e),null):(n==="space"&&(o.key=" "),o)},Pk=e=>kk.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),JC=(e,t)=>{let n=mp(e);if(!n)return"";let o=em(),r=Pk(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("+")},hp=e=>JC(e,!1),Nl=e=>JC(e,!0),Lk=(e,t)=>t.key?.toLowerCase()===e.key&&(em()?t.metaKey:t.ctrlKey)===e.mod&&!(em()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Hk=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},ZC=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(Lk(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&Hk(i))){s.preventDefault();try{l.run(s)}catch(c){fp(`${l.id} threw on`,l.combo),console.warn(c)}return}};return n?.addEventListener("keydown",r),{register(s){let i=mp(s.combo);if(!i)return()=>{};let l=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(l);return c?(fp(`${c.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:i}),s.element?.setAttribute("aria-keyshortcuts",Nl(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}}});function ew(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function bp(e){return typeof e=="string"?e:void 0}function Wk(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?Ao(t.text):null;case"image":return typeof t.image=="string"?Yd(t.image,{mimeType:bp(t.mimeType),alt:bp(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?HC(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...bp(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...bp(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function Ok(e,t){let n=ew(t),o=e.map(i=>ew(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:Rk+f;s=l+1}return r.map(i=>new Date(i).toISOString())}function tw(e,t){let n=Ok(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!Ik.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(Wk).filter(d=>d!==null),p=Gd(c);o.push({id:r.id,role:i,content:p||(ka(c)?Ta:""),createdAt:l,...c.length>0&&{contentParts:c}});return}o.push({id:r.id,role:i,content:"",createdAt:l})}),o}function Fl(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 $l(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 Ik,Rk,vp=Ve(()=>{"use strict";Nr();Ik=["user","assistant","system"],Rk=0});function Dk(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let o=_k.get(e.code)??"unavailable";return new n(o,tm(o),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new n("unavailable",tm("unavailable"))}function nw(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",tm("unsupported_scope"))},i=async(c,p)=>{s(c);try{return await p()}catch(d){throw Dk(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=tw(d.messages,{...p.beforeCreatedAt?{beforeCreatedAt:p.beforeCreatedAt}:{}});return{summary:d.summary,messages:$l([],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 _k,Bk,tm,ow=Ve(()=>{"use strict";vp();_k=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"]]),Bk=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."]]),tm=e=>Bk.get(e)??"Conversation history is unavailable right now."});var Cp={};ys(Cp,{createHistoryShell:()=>Nk});var Nk,nm=Ve(()=>{"use strict";zC();XC();Ze();yp();_o();ow();Nk=e=>{let o=Jf(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",ne=r?.capabilities.scopes;return!ne||ne.includes(N)?N:ne[0]??N},B=()=>l?.scope??H(),V=()=>e.session.getClientSession()?.targetId??null,oe=E=>`${E.state}:${"reason"in E?E.reason:""}`,W=E=>{let N=oe(E);N!==f&&(f=N,e.eventBus.emit("history:identityStatusChanged",{status:E,timestamp:Date.now()}))},j=null,X=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,X=N()),X):e.session.isClientTokenMode()?nw({errors:e.historyErrors,client:e.session.getClient(),getIdentityProofConfigured:()=>typeof e.config.getIdentityProof=="function",onActivationCommitted:ne=>e.session.bindActivatedSession(ne),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||xn({restoreFocus:!1}),jn()})??null,C=r.subscribeIdentityStatus(N=>W(N)),f=oe(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"))},J="data-persona-history-suppressed",U=null,ue=null,fe=null,me=null,He=null,Ee="",Ie=()=>e.header===He?Ee:e.config.layout?.showHeader===!1?"none":"",yt=()=>e.historyPresentation==="panel"&&!!fe&&me===fe.element&&e.config.layout?.showHeader!==!1&&Ie()!=="none",qe=()=>{for(let E of Array.from(e.header.children))E!==U&&E.setAttribute(J,"")},Oe=()=>{for(let E of Array.from(e.container.querySelectorAll(`[${J}]`)))E.removeAttribute(J)},$=()=>{let E=fe;if(!E)return;if(Array.from(e.header.children).some(pe=>pe!==U&&!pe.hasAttribute(J))){ue&&ue!==e.header&&(ue.style.removeProperty("min-height"),ue=null);let pe=e.header.offsetHeight;pe>0&&(e.header.style.minHeight=`${pe}px`,ue=e.header)}U||(U=x("div","persona-history-header-host")),E.setHeaderPlacement("external");let ne=E.getHeaderElement();ne.parentNode!==U&&U.replaceChildren(ne),U.parentNode!==e.header&&e.header.appendChild(U),qe()},_e=()=>{ue&&(ue.style.removeProperty("min-height"),ue=null),U&&(fe?.setHeaderPlacement("inline"),U.remove(),U=null,Oe())},ye=null,ut=()=>{if(ye){if(e.body.style.display="none",k(e.body,!0),e.footer.hidden=!0,k(e.footer,!0),yt()){$(),e.header.style.display=Ie(),k(e.header,!1);return}_e(),e.header.style.display="none",k(e.header,!0)}};e.reapplyHistoryHostChrome=ut;let Zt=E=>{let N=e.body.style.display,ne=e.footer.hidden,pe=e.footer,Re=e.header,$t=e.header.style.display;He=Re,Ee=$t,ye=()=>{ye=null,_e(),He=null,e.body.style.display=N,k(e.body,!1),pe.hidden=ne,k(pe,!1),e.footer!==pe&&(e.footer.hidden=!1,k(e.footer,!1)),Re.style.display=$t,k(Re,!1),e.header!==Re&&(e.header.style.display=e.config.layout?.showHeader===!1?"none":"",k(e.header,!1))},e.footer.parentNode?.insertBefore(E,e.footer),ut()},xt=null,xe=null,Wt=null,vt=null,Le=()=>[e.header,e.panelElements.closeButtonWrapper,e.panelElements.clearChatButtonWrapper,e.body,e.footer],Xe=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))),te=()=>e.config.features?.history?.rail?.resizable===!0,ve,Me=()=>{if(ve===void 0&&(ve=null,e.config.persistState!==!1))try{let E=Number(window.localStorage.getItem(`${e.currentKeyPrefix()}rail-width`));E&&(ve=E)}catch{}return ve},Ce=()=>K(Me()??e.config.features?.history?.rail?.width??260),st=E=>{if(ve=E,e.config.persistState!==!1)try{window.localStorage.setItem(`${e.currentKeyPrefix()}rail-width`,String(E))}catch{}},Ct=()=>D()&&e.config.features?.history?.rail?.collapsedBehavior==="overlay",De=!1,Qe=E=>{let N=x("img");return N.src=E,N.alt="",N.setAttribute("aria-hidden","true"),N},pn=()=>{let E=e.config.features?.history?.rail?.brand;if(!E)return;let N=!1,ne;return pe=>{if(E.render)try{return E.render({collapsed:pe})??null}catch(Re){return N||(N=!0,console.warn("[persona] history rail brand threw",Re)),null}return ne===void 0&&(E.iconUrl?ne=Qe(E.iconUrl):ne=E.icon?e.renderLucideIcon(E.icon,20):null),ne?ne.cloneNode(!0):null}},Eo=()=>e.config.features?.history?.rail?.sections?.map(E=>{let N=!1,ne=pe=>{N||(N=!0,console.warn("[persona] history rail section threw",E.id,pe))};return{id:E.id,title:E.title,placement:E.placement??"above-conversations",items:E.items.map(pe=>{let Re;return{id:pe.id,label:pe.label,badge:pe.badge,iconNode:()=>{if(Re!==void 0)return Re;try{pe.renderIcon?Re=pe.renderIcon()??null:pe.iconUrl?Re=Qe(pe.iconUrl):Re=pe.icon?e.renderLucideIcon(pe.icon,20):null}catch($t){ne($t),Re=null}return Re},onSelect:()=>{try{pe.onSelect()}catch($t){ne($t)}}}})}})??[],ft=E=>{let N=Eo();for(let ne of E)N.some(pe=>pe.id===ne.id)?console.warn("[persona] duplicate history rail section id",ne.id):N.push(ne);return N.length?N:void 0},bt=null,Ft=()=>`${e.currentKeyPrefix()}rail-collapsed`,_i=()=>{if(bt===null&&(bt=e.config.features?.history?.rail?.defaultCollapsed===!0,e.config.persistState!==!1))try{let E=window.localStorage.getItem(Ft());E&&(bt=E==="1")}catch{}return bt},rn=E=>{if(bt=E,e.config.persistState!==!1)try{window.localStorage.setItem(Ft(),E?"1":"0")}catch{}},Sn=()=>e.historyPresentation==="rail"&&D()&&!Ct()&&_i(),lo=()=>{},Bi=()=>{if(Ct()){lo();return}rn(!_i()),i?.view.setCollapsed(Sn()),e.applyRailChrome(),e.repinAnchoredMessage()},Di=()=>{let E=e.config.features?.history?.rail?.collapseShortcut;return!E||!mp(E)?null:{combo:E,hint:hp(E),aria:Nl(E)}},Qa=300,cr="var(--persona-history-overlay-margin,8px)",un=null,Un=null,dr=0,Vn=null,pr=null,Uo=!1,Yr=0,wc=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,to=()=>L()&&Ct()&&(e.historyPresentation??_())==="rail",$h=()=>e.historyVisible&&!De,ur=()=>{pr!==null&&clearTimeout(pr),pr=null},_s=()=>{e.loadHistoryView().catch(()=>{})},Ln=()=>{ur(),De&&(pr=setTimeout(()=>{pr=null,!(Uo||!De)&&(Vn?.contains(document.activeElement)||xn({restoreFocus:!1}))},Qa))},Je=(E,N)=>{let ne=Vn?.getBoundingClientRect();if(!ne)return!1;let pe=un?.getBoundingClientRect(),Re=pe?Math.min(pe.top,ne.top):ne.top;return E>=ne.left&&E<=ne.right&&N>=Re&&N<=ne.bottom||!!pe&&E>=pe.left&&E<=pe.right&&N>=pe.top&&N<=pe.bottom},Ae=E=>{De&&(Uo=Je(E.clientX,E.clientY),Uo?ur():pr===null&&Ln())},Xt=E=>{e.historyVisible||!to()||(De=!0,Ke({invoker:un,keyboard:E?.keyboard===!0}).then(()=>{e.historyVisible?!Uo&&document.activeElement!==un&&xn():De=!1}))},et=()=>{let E=me?.querySelector('[data-persona-history-focus="collapse"]');E&&(E.setAttribute("aria-label",De?o.expandLabel:o.collapseLabel),E.setAttribute("aria-expanded",De?"false":"true"))},we=()=>{rn(!1);let E=i;if(!De||!E){Ke({invoker:un});return}let N=document.activeElement===un;De=!1,Ni(),E.element.remove(),Ht(E.element),et(),N&&mt(),e.repinAnchoredMessage(),jn()},ae=()=>{rn(!0),xn()};lo=()=>{!e.historyVisible||De?we():ae()};let Te=()=>{let E=Di(),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}:{}}}),ne=N.button;ne.addEventListener("mouseenter",()=>{Uo=!0,ur(),!(wc()||Date.now()<Yr)&&Xt()}),ne.addEventListener("mouseleave",()=>{Uo=!1,Yr=0,Ln()}),ne.addEventListener("focus",()=>{e.historyVisible||_s()}),ne.addEventListener("click",pe=>{L()&&(pe.detail!==0&&wc()&&!e.historyVisible?Xt():we())}),un=ne,Un=N.wrapper},gr=()=>{if(Un&&!Un.isConnected&&(Un=null,un=null),!to()){Un?.remove(),Un=null,un=null;return}un||Te();let E=Un,N=un;if(!E||!N)return;let ne=S()!=="right"?e.header.firstChild:null;(ne??e.header.lastChild)!==E&&e.header.insertBefore(E,ne),E.style.display=$h()||dr>0?"none":"",N.setAttribute("aria-label",o.expandLabel),N.setAttribute("aria-expanded",e.historyVisible?"true":"false"),Vn&&e.applyRailChrome()},Xr=E=>{if(!De)return;let N=E.target;N instanceof Node&&(Vn?.contains(N)||Un?.contains(N)||N instanceof Element&&N.closest('.persona-dropdown-menu,[role="alertdialog"]')||xn({restoreFocus:!1}))};document.addEventListener("pointerdown",Xr,!0),e.destroyCallbacks.push(()=>{document.removeEventListener("pointerdown",Xr,!0),document.removeEventListener("pointermove",Ae),ce?.(),ur()});let co=null,ce=null,ke=16,An=E=>{st(K(E)),e.applyRailChrome(),e.repinAnchoredMessage()},tt=()=>{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 ne=xe;if(!ne||N.button!==0)return;N.preventDefault(),ce?.();let pe=N.clientX,Re=ne.getBoundingClientRect().width||Ce(),$t=S()==="right"?-1:1,Ot=Re,_t=e.mount.ownerDocument;ne.style.transition="none";let je=be=>{Ot=K(Re+$t*(be.clientX-pe)),ne.style.flex=`0 0 ${Ot}px`,E.setAttribute("aria-valuenow",String(Ot))},at=()=>{ce=null,_t.removeEventListener("pointermove",je),_t.removeEventListener("pointerup",at),_t.removeEventListener("pointercancel",at),ne.style.removeProperty("transition");try{E.releasePointerCapture(N.pointerId)}catch{}An(Ot)};ce=at,_t.addEventListener("pointermove",je),_t.addEventListener("pointerup",at),_t.addEventListener("pointercancel",at);try{E.setPointerCapture(N.pointerId)}catch{}}),E.addEventListener("keydown",N=>{let ne=S()==="right"?-ke:ke,pe=Ce(),Re=N.key==="ArrowRight"?pe+ne:N.key==="ArrowLeft"?pe-ne:N.key==="Home"?F:N.key==="End"?q:null;Re!==null&&(N.preventDefault(),An(Re))}),E},en=(E,N)=>{if(!te()||Sn()){ce?.(),co?.remove();return}let ne=co??tt();co=ne,ne.setAttribute("aria-label",o.resizeLabel),ne.setAttribute("aria-valuenow",String(Ce())),ne.nextElementSibling!==N&&E.insertBefore(ne,N)};e.applyRailChrome=()=>{i?.view.setRailSide(S());let E=S()==="right",N=Vn;if(N){let _t=un?un.getBoundingClientRect().bottom-e.container.getBoundingClientRect().top:0;N.style.top=`calc(${Math.max(0,Math.round(_t))}px + ${cr})`,N.style.width=`${Ce()}px`,N.style.left=E?"":cr,N.style.right=E?cr:""}let ne=xe,pe=xt,Re=Wt;if(!ne||!pe||!Re)return;ne.style.flex=`0 0 ${Sn()?Xe:Ce()}px`;let $t="1px solid var(--persona-divider,#e5e7eb)";ne.style.borderRight=E?"":$t,ne.style.borderLeft=E?$t:"";let Ot=E?Re:ne;pe.firstElementChild!==Ot&&pe.append(Ot,E?ne:Re),en(pe,E?ne:Re)};let Sc=E=>{if(vt&&xe){vt.replaceWith(E),vt=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 ne=x("div","persona-history-rail-conversation");ne.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let pe=x("div","persona-history-rail-host");pe.style.cssText="display:flex;min-height:0;overflow:hidden",e.container.insertBefore(N,e.header.parentNode===e.container?e.header:e.body);for(let Re of Le())Re?.parentNode===e.container&&ne.appendChild(Re);N.append(pe,ne),pe.appendChild(E),xt=N,xe=pe,Wt=ne,e.applyRailChrome()},Rn=()=>{if(xt)return;let E=x("div","persona-history-rail-placeholder");E.style.cssText="flex:1 1 auto;min-height:0",vt=E,Sc(E),e.repinAnchoredMessage()},Ac=()=>{vt&&(Ni(),e.repinAnchoredMessage())},Bu=E=>{let N=x("div","persona-history-rail-overlay");N.style.cssText=`position:absolute;bottom:${cr};display:flex;overflow:hidden;z-index:${wa-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",Ae),Vn=N,e.applyRailChrome(),et()},Ni=()=>{ye?.(),Vn&&(Uo&&(Yr=Date.now()+150),document.removeEventListener("pointermove",Ae),Vn.remove(),Vn=null);let E=xt;if(E){ce?.();for(let N of Le())N&&E.contains(N)&&e.container.insertBefore(N,E);E.remove(),xt=null,xe=null,Wt=null,vt=null}},ze=E=>{me=E,E.id=A,E.style.flex="1 1 auto",E.style.minHeight="0"},Ht=E=>{ze(E),(e.historyPresentation!=="rail"||De)&&Ac(),e.historyPresentation!=="rail"?Zt(E):De?Bu(E):Sc(E)},Vo=()=>{if(gr(),Jr(),!e.historyVisible||!i)return;let E=_();if(E===e.historyPresentation)return;let N=document.activeElement,ne=N instanceof HTMLElement&&(i.element.contains(N)||U?.contains(N)===!0)?N:null;Ni(),i.element.remove(),i.view.setHeaderPlacement("inline"),e.historyPresentation=E,i.view.setPresentation(E),i.view.setCollapsed(Sn()),i.requestRender(),i.element.isConnected||Ht(i.element),ne?.isConnected?ne.focus():mt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),jn()},jo=(E,N)=>U?.querySelector(N)??E.querySelector(N),mt=()=>{let E=i?.element??me;if(!E)return;let N=jo(E,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(N){N.focus();return}let ne=jo(E,".persona-history-title")??E;ne.tabIndex=-1,ne.focus()},Ke=async E=>{if(!L()||e.historyVisible)return;let N=r;if(!N)return;if(!De&&to()&&_i()){gr();return}Fi();let ne=++h;c=E?.returnSurface??"conversation",p=E?.invoker??d;let pe=to()&&!De;pe&&(dr+=1,gr(),Rn());let Re;try{Re=await e.loadHistoryView()}catch{e.announceHistory(o.openHistoryLabel),pe&&(dr-=1,ne===h&&(Ac(),gr()));return}if(pe&&(dr-=1),ne!==h||e.historyVisible)return;l={scope:H()},e.historyPresentation=_(),e.historyVisible=!0;let $t=e.historyPresentation==="panel"&&e.config.layout?.showHeader!==!1&&e.header.style.display!=="none"?"external":"inline",Ot=e.config.features?.history?.rowAvatar,_t=Di(),je=_t?{hint:_t.hint,aria:_t.aria}:null,at={provider:N,context:l,targetId:V(),presentation:e.historyPresentation,collapsible:D(),collapsed:Sn(),railSide:S(),renderRailHeader:e.config.features?.history?.rail?.renderHeader,railBrand:pn(),onToggleCollapse:Bi,...je?{collapseShortcut:je}:{},headerPlacement:$t,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:Ot===!1?!1:typeof Ot=="string"?Ot: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:be=>En(be,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:be=>e.setActiveConversationSummary(be),attachTooltip:e.attachTooltip,onStartNew:()=>Mo({focusComposer:!0}),onClose:()=>xn(),onRequestDeleteConversation:be=>Vt(be),onRequestClearHistory:()=>Fs(),...N.resetDevice?{onRequestResetIdentity:()=>el()}:{}};i=YC({plugins:e.plugins,config:e.config,getPresentation:()=>e.historyPresentation??"panel",getReturnSurface:()=>c,close:()=>xn(),createView:({slots:be,renderDom:Ui,onModelChange:po,railSections:mr})=>(fe=Re.createHistoryView({...at,railSections:ft(mr),slots:be,renderDom:Ui,onModelChange:po,onAnnounce:e.announceHistory}),fe),onElementChanged:(be,Ui)=>{if(!Ui?.isConnected)return Ht(be);ze(be),Ui.replaceWith(be),ut()}}),i.view.setNewConversationRequired(e.historySessionState.recovery==="new_conversation_required"),E?.focus!==!1&&(e.historyPresentation!=="rail"||E?.keyboard===!0)&&mt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),jn(),e.eventBus.emit("history:opened",{presentation:e.historyPresentation,returnSurface:c,timestamp:Date.now()})},Fi=()=>{},xn=E=>{if(!e.historyVisible)return;h+=1;let N=c,ne=p,pe=i,Re=E?.restoreFocus!==!1;e.historyVisible=!1;let $t=!1,Ot=null,_t=()=>{if(!$t){if($t=!0,Fi=()=>{},Ot!==null&&clearTimeout(Ot),De=!1,ur(),Ni(),pe?.dispose(),pe?.view.destroy(),pe?.element.remove(),i===pe&&(i=null,fe=null,me=null,e.historyPresentation=null,l=null,p=null),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),jn(),Re){let at=ne??d;at?.isConnected?at.focus():e.maybeFocusInput()}e.eventBus.emit("history:closed",{returnSurface:N,timestamp:Date.now()})}},je=pe&&pe.element===pe.view.element?pe.view.playExit():null;if(!je){_t();return}Fi=_t,Ot=setTimeout(_t,250),je.then(_t)},Bs=E=>{if(!(E.key!=="Escape"||!e.historyVisible||!i)){if(e.historyPresentation==="rail"){let N=E.target;if(!(N instanceof Node)||!(i.element.contains(N)||De&&Un?.contains(N)===!0))return}E.preventDefault(),E.stopPropagation(),xn()}};e.container.addEventListener("keydown",Bs),e.destroyCallbacks.push(()=>e.container.removeEventListener("keydown",Bs));let Wn=0,xc=250,he=null,gn=()=>{he&&clearTimeout(he),he=null};e.destroyCallbacks.push(gn);let It=()=>{gn();let E=e.conversationOpenPendingEl;E&&(e.conversationOpenTakeover=!0,E.hidden=!1,e.messagesWrapper.style.display="none",e.updateWelcome())},sn=()=>{Wn+=1,gn(),e.conversationOpenPendingEl&&(e.conversationOpenPendingEl.remove(),e.conversationOpenPendingEl=null,e.conversationOpenTakeover=!1,e.messagesWrapper.style.removeProperty("display"),k(e.footer,!1),e.updateWelcome())},Et=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;e.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},fn=(E,N)=>Q("div",{className:Dn("persona-conversation-loading-bubble",N&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:E}}),Ec=()=>Q("div",{className:"persona-conversation-loading-body"},fn("58%",!1),fn("72%",!0),fn("44%",!1)),Qr=E=>{e.conversationOpenPendingEl?.remove(),e.conversationOpenPendingEl=E,E.hidden=!e.conversationOpenTakeover,e.body.insertBefore(E,e.messagesWrapper),gn(),e.conversationOpenTakeover||(he=setTimeout(It,xc)),k(e.footer,!0)},Du=()=>{let E={config:e.config,streaming:!1,location:"conversation-open",defaultRenderer:Ec},N=null,ne=e.plugins.find(pe=>pe.renderLoadingIndicator);ne?.renderLoadingIndicator&&(N=ne.renderLoadingIndicator(E)),N===null&&e.config.loadingIndicator?.render&&(N=e.config.loadingIndicator.render(E)),Qr(Q("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":o.openConversationLoadingLabel}},N??Ec()))},Nu=E=>{let N=()=>{En(E,{focusComposer:!0}).catch(()=>{})},ne=L()?()=>{sn(),Ke()}:void 0,pe=(_t,je)=>{let at=Q("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:_t});return at.addEventListener("click",je),at},Re=()=>Q("div",{className:"persona-conversation-loading-error-body"},Q("p",{className:"persona-conversation-loading-error-title",text:o.openConversationErrorTitle}),Q("div",{className:"persona-conversation-loading-error-actions"},pe(o.openConversationRetryLabel,N),ne?pe(o.openConversationBackLabel,ne):null)),$t=Object.freeze({conversationId:E,config:e.config,copy:Object.freeze({title:o.openConversationErrorTitle,retryLabel:o.openConversationRetryLabel,backLabel:o.openConversationBackLabel}),retry:N,...ne?{back:ne}:{},defaultRenderer:Re}),Ot=null;for(let _t of e.plugins)if(_t.renderHistoryOpenError){try{Ot=_t.renderHistoryOpenError($t)}catch(je){console.warn("[persona] renderHistoryOpenError threw",je),Ot=null}if(Ot)break}Qr(Q("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},Ot??Re())),It()};e.eventBus.on("history:closed",()=>{e.conversationOpenPendingEl&&k(e.footer,!0)});let En=async(E,{focusComposer:N=!1}={})=>{let ne=B(),pe=!!i;i?.view.setActiveConversationId(E),sn();let Re=Wn;Du(),e.historyVisible&&(e.historyPresentation==="panel"||De)&&xn({restoreFocus:!1}),e.suppressScrollSend=!0;try{await e.session.openConversation(E,{scope:ne})}catch($t){throw Re===Wn&&Nu(E),$t}finally{e.suppressScrollSend=!1}Re===Wn&&(sn(),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.restoreScrollPosition()||e.jumpToBottomInstant(),Et(),Qt(),pe||e.setActiveConversationSummary(null),e.eventBus.emit("history:conversationOpened",{conversationId:E,title:e.activeConversationTitle,scope:ne,timestamp:Date.now()}),N&&e.maybeFocusInput())},Mo=async({focusComposer:E=!1}={})=>{sn(),await e.session.startNewConversation({scope:B()}),e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.jumpToBottomInstant(),Qt();let N=e.session.getActiveConversationId();i?.view.setActiveConversationId(N),e.eventBus.emit("history:conversationStarted",{conversationId:N,timestamp:Date.now()}),e.historyVisible&&(e.historyPresentation==="panel"||De)&&xn({restoreFocus:!1}),E&&e.maybeFocusInput()},Ds=async(E,N)=>{let ne=await e.session.updateConversation(E,{...N,...N.title!==void 0?{title:N.title.trim()}:{}});return i?.view.applyConversationSummary(ne),!i&&E===e.session.getActiveConversationId()&&e.setActiveConversationSummary(ne),ne},Mc=async E=>{let N=B(),ne=e.session.getActiveConversationId()===E;await e.session.deleteConversation(E,{scope:N}),i?.view.removeConversationSummary(E),ne&&(e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Qt()),e.eventBus.emit("history:conversationDeleted",{conversationId:E,scope:N,wasActive:ne,timestamp:Date.now()})},Ja=async E=>{let N=E?.scope??B(),ne=E?.allTargets?null:E?.targetId??V(),pe=await e.session.clearConversationHistory({...ne?{targetId:ne}:{},scope:N});return e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Qt(),e.eventBus.emit("history:cleared",{deleted:pe.deleted,scope:N,targetId:ne,timestamp:Date.now()}),pe},Za=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(),Qt(),xn({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}},$i=()=>e.artifactSplitRoot?e.panel:e.container,Ns=async E=>{let N=await e.loadHistoryView().catch(()=>null);return typeof N?.showHistoryConfirm=="function"?N.showHistoryConfirm(E):window.confirm(`${E.title}
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??Q("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:oe,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=>Dl(M,{render:s.renderMentionToken}),onMentionRemoved:M=>f?.untrackMention(M)});b=j.input,C=j.destroy;let X=y;X.replaceWith(j.element),y=j.element,L={next:j.element,prev:X},A?.(j.element,X),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(X=>X?.openMenu(W.trigger))}});B.push(j),V.set(W.trigger,j.button)}let oe=(W,j,X)=>{let M=V.get(j);M&&(M.setAttribute("aria-expanded",W?"true":"false"),W?M.setAttribute("aria-controls",X):M.removeAttribute("aria-controls"))};return{affordanceButtons:B.map(W=>W.wrapper),contextRow:g,handleInput:W=>{if(f){f.handleInput();return}if(!sC(W))return;let j=y,X=j.selectionStart??0;rC(j.value,X,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,X=j.selectionStart===0&&j.selectionEnd===0;if((j.value.length===0||X)&&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 fP,NC=Ve(()=>{"use strict";Ze();iC();lC();Vf();jf();kt();qf();zf();fP={loadContextMentions:()=>lp(),loadContextMentionsInline:()=>cp(),renderLucideIcon:(...e)=>ge(...e),createMentionButton:(...e)=>ap(...e)}});var dp={};ys(dp,{createAskUserSheetHandlers:()=>tC,createContextMentionOrchestrator:()=>DC});var Kf=Ve(()=>{"use strict";nC();NC()});var gp={};ys(gp,{resolveApproval:()=>vP,resolveAskUserQuestion:()=>CP,resolveWebMcpToolCall:()=>AP,resolveWebMcpToolCallBatch:()=>UC});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 CP(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 wP(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 $C(e,t){return t.toolCall?.name!==Oo?!1:(e.s.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function SP(e,t){let n=wP(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 up(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 UC(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)||$C(e,c))return null;e.s.webMcpInflightKeys.add(g),o.push(g);let f=SP(e,c),h=c.agentMetadata?.webMcpToolCallId??p;if(p===Oo)return{dedupeKey:g,resumeKey:h,output:_v(),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))),up(e,c,Yf(A?"Aborted by cancel()":bP(C)),f),e.s.webMcpInflightKeys.delete(g),null}return r.signal.aborted?(up(e,c,Yf("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;up(e,g.toolMessage,g.output,g.startedAt,g.completedAt,{...f===Oo?{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)up(e,d.toolMessage,Yf("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 AP(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 xP(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)||$C(e,t)))return UC(e,n,[t])}async function xP(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 Yf,bP,Xf=Ve(()=>{"use strict";Ca();Yf=e=>({isError:!0,content:[{type:"text",text:e}]}),bP=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t});function Jf(e){if(!e)return qC;let t={...qC};for(let n of PP){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var PP,qC,zC=Ve(()=>{"use strict";PP=["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"],qC={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 YC(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){Zf("renderHistoryView cleanup",B)}},d=(H,B)=>{for(let V of t){let oe=V[H];if(oe)try{let W=oe(B);if(W)return W}catch(W){Zf(H,W)}}return null},g=()=>({presentation:e.getPresentation(),config:n}),f={header:H=>i?d("renderHistoryHeader",Object.freeze({...g(),returnSurface:e.getReturnSurface(),identityStatus:Fr(H.identityStatus),pendingAction:GC(H.pendingAction),copy:Fr(H.copy),actions:Object.freeze({close:b.close,startNewConversation:b.startNewConversation}),defaultRenderer:H.defaultRenderer})):null,conversation:H=>i?d("renderHistoryConversation",Object.freeze({...g(),conversation:KC(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:Fr(H.state),identityStatus:Fr(H.identityStatus),copy:Fr(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(KC)),activeConversationId:H.activeConversationId,state:Fr(H.state),pendingAction:GC(H.pendingAction),identityStatus:Fr(H.identityStatus),nextCursor:H.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:Fr(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(oe){Zf("renderHistoryView",oe),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 Zf,Fr,KC,GC,XC=Ve(()=>{"use strict";Zf=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},Fr=e=>Object.freeze({...e}),KC=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),GC=e=>e?Fr(e):null});var QC,em,kP,fp,mp,LP,JC,hp,Nl,HP,IP,ZC,yp=Ve(()=>{"use strict";QC=null,em=()=>{if(QC!==null)return QC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},kP="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",fp=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},mp=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 fp("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(fp("unsupported",e),null):(n==="space"&&(o.key=" "),o)},LP=e=>kP.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),JC=(e,t)=>{let n=mp(e);if(!n)return"";let o=em(),r=LP(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("+")},hp=e=>JC(e,!1),Nl=e=>JC(e,!0),HP=(e,t)=>t.key?.toLowerCase()===e.key&&(em()?t.metaKey:t.ctrlKey)===e.mod&&!(em()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,IP=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},ZC=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(HP(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&IP(i))){s.preventDefault();try{l.run(s)}catch(c){fp(`${l.id} threw on`,l.combo),console.warn(c)}return}};return n?.addEventListener("keydown",r),{register(s){let i=mp(s.combo);if(!i)return()=>{};let l=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(l);return c?(fp(`${c.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:i}),s.element?.setAttribute("aria-keyshortcuts",Nl(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}}});function ew(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function bp(e){return typeof e=="string"?e:void 0}function OP(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?Ao(t.text):null;case"image":return typeof t.image=="string"?Yd(t.image,{mimeType:bp(t.mimeType),alt:bp(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?HC(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...bp(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...bp(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function _P(e,t){let n=ew(t),o=e.map(i=>ew(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:WP+f;s=l+1}return r.map(i=>new Date(i).toISOString())}function tw(e,t){let n=_P(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!RP.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(OP).filter(d=>d!==null),p=Gd(c);o.push({id:r.id,role:i,content:p||(Pa(c)?Ta:""),createdAt:l,...c.length>0&&{contentParts:c}});return}o.push({id:r.id,role:i,content:"",createdAt:l})}),o}function Fl(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 $l(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 RP,WP,vp=Ve(()=>{"use strict";Nr();RP=["user","assistant","system"],WP=0});function NP(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let o=BP.get(e.code)??"unavailable";return new n(o,tm(o),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new n("unavailable",tm("unavailable"))}function nw(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",tm("unsupported_scope"))},i=async(c,p)=>{s(c);try{return await p()}catch(d){throw NP(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=tw(d.messages,{...p.beforeCreatedAt?{beforeCreatedAt:p.beforeCreatedAt}:{}});return{summary:d.summary,messages:$l([],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 BP,DP,tm,ow=Ve(()=>{"use strict";vp();BP=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"]]),DP=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."]]),tm=e=>DP.get(e)??"Conversation history is unavailable right now."});var Cp={};ys(Cp,{createHistoryShell:()=>FP});var FP,nm=Ve(()=>{"use strict";zC();XC();Ze();yp();_o();ow();FP=e=>{let o=Jf(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",ne=r?.capabilities.scopes;return!ne||ne.includes(N)?N:ne[0]??N},B=()=>l?.scope??H(),V=()=>e.session.getClientSession()?.targetId??null,oe=E=>`${E.state}:${"reason"in E?E.reason:""}`,W=E=>{let N=oe(E);N!==f&&(f=N,e.eventBus.emit("history:identityStatusChanged",{status:E,timestamp:Date.now()}))},j=null,X=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,X=N()),X):e.session.isClientTokenMode()?nw({errors:e.historyErrors,client:e.session.getClient(),getIdentityProofConfigured:()=>typeof e.config.getIdentityProof=="function",onActivationCommitted:ne=>e.session.bindActivatedSession(ne),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||xn({restoreFocus:!1}),jn()})??null,C=r.subscribeIdentityStatus(N=>W(N)),f=oe(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"},P=(E,N)=>{N?(E.setAttribute("aria-hidden","true"),E.setAttribute("inert","")):(E.removeAttribute("aria-hidden"),E.removeAttribute("inert"))},J="data-persona-history-suppressed",U=null,ue=null,fe=null,me=null,He=null,Ee="",Ie=()=>e.header===He?Ee:e.config.layout?.showHeader===!1?"none":"",yt=()=>e.historyPresentation==="panel"&&!!fe&&me===fe.element&&e.config.layout?.showHeader!==!1&&Ie()!=="none",qe=()=>{for(let E of Array.from(e.header.children))E!==U&&E.setAttribute(J,"")},Oe=()=>{for(let E of Array.from(e.container.querySelectorAll(`[${J}]`)))E.removeAttribute(J)},$=()=>{let E=fe;if(!E)return;if(Array.from(e.header.children).some(pe=>pe!==U&&!pe.hasAttribute(J))){ue&&ue!==e.header&&(ue.style.removeProperty("min-height"),ue=null);let pe=e.header.offsetHeight;pe>0&&(e.header.style.minHeight=`${pe}px`,ue=e.header)}U||(U=x("div","persona-history-header-host")),E.setHeaderPlacement("external");let ne=E.getHeaderElement();ne.parentNode!==U&&U.replaceChildren(ne),U.parentNode!==e.header&&e.header.appendChild(U),qe()},_e=()=>{ue&&(ue.style.removeProperty("min-height"),ue=null),U&&(fe?.setHeaderPlacement("inline"),U.remove(),U=null,Oe())},ye=null,ut=()=>{if(ye){if(e.body.style.display="none",P(e.body,!0),e.footer.hidden=!0,P(e.footer,!0),yt()){$(),e.header.style.display=Ie(),P(e.header,!1);return}_e(),e.header.style.display="none",P(e.header,!0)}};e.reapplyHistoryHostChrome=ut;let Zt=E=>{let N=e.body.style.display,ne=e.footer.hidden,pe=e.footer,Re=e.header,$t=e.header.style.display;He=Re,Ee=$t,ye=()=>{ye=null,_e(),He=null,e.body.style.display=N,P(e.body,!1),pe.hidden=ne,P(pe,!1),e.footer!==pe&&(e.footer.hidden=!1,P(e.footer,!1)),Re.style.display=$t,P(Re,!1),e.header!==Re&&(e.header.style.display=e.config.layout?.showHeader===!1?"none":"",P(e.header,!1))},e.footer.parentNode?.insertBefore(E,e.footer),ut()},xt=null,xe=null,Wt=null,vt=null,Le=()=>[e.header,e.panelElements.closeButtonWrapper,e.panelElements.clearChatButtonWrapper,e.body,e.footer],Xe=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))),te=()=>e.config.features?.history?.rail?.resizable===!0,ve,Me=()=>{if(ve===void 0&&(ve=null,e.config.persistState!==!1))try{let E=Number(window.localStorage.getItem(`${e.currentKeyPrefix()}rail-width`));E&&(ve=E)}catch{}return ve},Ce=()=>K(Me()??e.config.features?.history?.rail?.width??260),st=E=>{if(ve=E,e.config.persistState!==!1)try{window.localStorage.setItem(`${e.currentKeyPrefix()}rail-width`,String(E))}catch{}},Ct=()=>D()&&e.config.features?.history?.rail?.collapsedBehavior==="overlay",De=!1,Qe=E=>{let N=x("img");return N.src=E,N.alt="",N.setAttribute("aria-hidden","true"),N},pn=()=>{let E=e.config.features?.history?.rail?.brand;if(!E)return;let N=!1,ne;return pe=>{if(E.render)try{return E.render({collapsed:pe})??null}catch(Re){return N||(N=!0,console.warn("[persona] history rail brand threw",Re)),null}return ne===void 0&&(E.iconUrl?ne=Qe(E.iconUrl):ne=E.icon?e.renderLucideIcon(E.icon,20):null),ne?ne.cloneNode(!0):null}},Eo=()=>e.config.features?.history?.rail?.sections?.map(E=>{let N=!1,ne=pe=>{N||(N=!0,console.warn("[persona] history rail section threw",E.id,pe))};return{id:E.id,title:E.title,placement:E.placement??"above-conversations",items:E.items.map(pe=>{let Re;return{id:pe.id,label:pe.label,badge:pe.badge,iconNode:()=>{if(Re!==void 0)return Re;try{pe.renderIcon?Re=pe.renderIcon()??null:pe.iconUrl?Re=Qe(pe.iconUrl):Re=pe.icon?e.renderLucideIcon(pe.icon,20):null}catch($t){ne($t),Re=null}return Re},onSelect:()=>{try{pe.onSelect()}catch($t){ne($t)}}}})}})??[],ft=E=>{let N=Eo();for(let ne of E)N.some(pe=>pe.id===ne.id)?console.warn("[persona] duplicate history rail section id",ne.id):N.push(ne);return N.length?N:void 0},bt=null,Ft=()=>`${e.currentKeyPrefix()}rail-collapsed`,_i=()=>{if(bt===null&&(bt=e.config.features?.history?.rail?.defaultCollapsed===!0,e.config.persistState!==!1))try{let E=window.localStorage.getItem(Ft());E&&(bt=E==="1")}catch{}return bt},rn=E=>{if(bt=E,e.config.persistState!==!1)try{window.localStorage.setItem(Ft(),E?"1":"0")}catch{}},Sn=()=>e.historyPresentation==="rail"&&D()&&!Ct()&&_i(),lo=()=>{},Bi=()=>{if(Ct()){lo();return}rn(!_i()),i?.view.setCollapsed(Sn()),e.applyRailChrome(),e.repinAnchoredMessage()},Di=()=>{let E=e.config.features?.history?.rail?.collapseShortcut;return!E||!mp(E)?null:{combo:E,hint:hp(E),aria:Nl(E)}},Qa=300,cr="var(--persona-history-overlay-margin,8px)",un=null,Un=null,dr=0,Vn=null,pr=null,Uo=!1,Yr=0,wc=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,to=()=>L()&&Ct()&&(e.historyPresentation??_())==="rail",$h=()=>e.historyVisible&&!De,ur=()=>{pr!==null&&clearTimeout(pr),pr=null},_s=()=>{e.loadHistoryView().catch(()=>{})},Ln=()=>{ur(),De&&(pr=setTimeout(()=>{pr=null,!(Uo||!De)&&(Vn?.contains(document.activeElement)||xn({restoreFocus:!1}))},Qa))},Je=(E,N)=>{let ne=Vn?.getBoundingClientRect();if(!ne)return!1;let pe=un?.getBoundingClientRect(),Re=pe?Math.min(pe.top,ne.top):ne.top;return E>=ne.left&&E<=ne.right&&N>=Re&&N<=ne.bottom||!!pe&&E>=pe.left&&E<=pe.right&&N>=pe.top&&N<=pe.bottom},Ae=E=>{De&&(Uo=Je(E.clientX,E.clientY),Uo?ur():pr===null&&Ln())},Xt=E=>{e.historyVisible||!to()||(De=!0,Ke({invoker:un,keyboard:E?.keyboard===!0}).then(()=>{e.historyVisible?!Uo&&document.activeElement!==un&&xn():De=!1}))},et=()=>{let E=me?.querySelector('[data-persona-history-focus="collapse"]');E&&(E.setAttribute("aria-label",De?o.expandLabel:o.collapseLabel),E.setAttribute("aria-expanded",De?"false":"true"))},we=()=>{rn(!1);let E=i;if(!De||!E){Ke({invoker:un});return}let N=document.activeElement===un;De=!1,Ni(),E.element.remove(),Ht(E.element),et(),N&&mt(),e.repinAnchoredMessage(),jn()},ae=()=>{rn(!0),xn()};lo=()=>{!e.historyVisible||De?we():ae()};let Te=()=>{let E=Di(),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}:{}}}),ne=N.button;ne.addEventListener("mouseenter",()=>{Uo=!0,ur(),!(wc()||Date.now()<Yr)&&Xt()}),ne.addEventListener("mouseleave",()=>{Uo=!1,Yr=0,Ln()}),ne.addEventListener("focus",()=>{e.historyVisible||_s()}),ne.addEventListener("click",pe=>{L()&&(pe.detail!==0&&wc()&&!e.historyVisible?Xt():we())}),un=ne,Un=N.wrapper},gr=()=>{if(Un&&!Un.isConnected&&(Un=null,un=null),!to()){Un?.remove(),Un=null,un=null;return}un||Te();let E=Un,N=un;if(!E||!N)return;let ne=S()!=="right"?e.header.firstChild:null;(ne??e.header.lastChild)!==E&&e.header.insertBefore(E,ne),E.style.display=$h()||dr>0?"none":"",N.setAttribute("aria-label",o.expandLabel),N.setAttribute("aria-expanded",e.historyVisible?"true":"false"),Vn&&e.applyRailChrome()},Xr=E=>{if(!De)return;let N=E.target;N instanceof Node&&(Vn?.contains(N)||Un?.contains(N)||N instanceof Element&&N.closest('.persona-dropdown-menu,[role="alertdialog"]')||xn({restoreFocus:!1}))};document.addEventListener("pointerdown",Xr,!0),e.destroyCallbacks.push(()=>{document.removeEventListener("pointerdown",Xr,!0),document.removeEventListener("pointermove",Ae),ce?.(),ur()});let co=null,ce=null,Pe=16,An=E=>{st(K(E)),e.applyRailChrome(),e.repinAnchoredMessage()},tt=()=>{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 ne=xe;if(!ne||N.button!==0)return;N.preventDefault(),ce?.();let pe=N.clientX,Re=ne.getBoundingClientRect().width||Ce(),$t=S()==="right"?-1:1,Ot=Re,_t=e.mount.ownerDocument;ne.style.transition="none";let je=be=>{Ot=K(Re+$t*(be.clientX-pe)),ne.style.flex=`0 0 ${Ot}px`,E.setAttribute("aria-valuenow",String(Ot))},at=()=>{ce=null,_t.removeEventListener("pointermove",je),_t.removeEventListener("pointerup",at),_t.removeEventListener("pointercancel",at),ne.style.removeProperty("transition");try{E.releasePointerCapture(N.pointerId)}catch{}An(Ot)};ce=at,_t.addEventListener("pointermove",je),_t.addEventListener("pointerup",at),_t.addEventListener("pointercancel",at);try{E.setPointerCapture(N.pointerId)}catch{}}),E.addEventListener("keydown",N=>{let ne=S()==="right"?-Pe:Pe,pe=Ce(),Re=N.key==="ArrowRight"?pe+ne:N.key==="ArrowLeft"?pe-ne:N.key==="Home"?F:N.key==="End"?q:null;Re!==null&&(N.preventDefault(),An(Re))}),E},en=(E,N)=>{if(!te()||Sn()){ce?.(),co?.remove();return}let ne=co??tt();co=ne,ne.setAttribute("aria-label",o.resizeLabel),ne.setAttribute("aria-valuenow",String(Ce())),ne.nextElementSibling!==N&&E.insertBefore(ne,N)};e.applyRailChrome=()=>{i?.view.setRailSide(S());let E=S()==="right",N=Vn;if(N){let _t=un?un.getBoundingClientRect().bottom-e.container.getBoundingClientRect().top:0;N.style.top=`calc(${Math.max(0,Math.round(_t))}px + ${cr})`,N.style.width=`${Ce()}px`,N.style.left=E?"":cr,N.style.right=E?cr:""}let ne=xe,pe=xt,Re=Wt;if(!ne||!pe||!Re)return;ne.style.flex=`0 0 ${Sn()?Xe:Ce()}px`;let $t="1px solid var(--persona-divider,#e5e7eb)";ne.style.borderRight=E?"":$t,ne.style.borderLeft=E?$t:"";let Ot=E?Re:ne;pe.firstElementChild!==Ot&&pe.append(Ot,E?ne:Re),en(pe,E?ne:Re)};let Sc=E=>{if(vt&&xe){vt.replaceWith(E),vt=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 ne=x("div","persona-history-rail-conversation");ne.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let pe=x("div","persona-history-rail-host");pe.style.cssText="display:flex;min-height:0;overflow:hidden",e.container.insertBefore(N,e.header.parentNode===e.container?e.header:e.body);for(let Re of Le())Re?.parentNode===e.container&&ne.appendChild(Re);N.append(pe,ne),pe.appendChild(E),xt=N,xe=pe,Wt=ne,e.applyRailChrome()},Rn=()=>{if(xt)return;let E=x("div","persona-history-rail-placeholder");E.style.cssText="flex:1 1 auto;min-height:0",vt=E,Sc(E),e.repinAnchoredMessage()},Ac=()=>{vt&&(Ni(),e.repinAnchoredMessage())},Bu=E=>{let N=x("div","persona-history-rail-overlay");N.style.cssText=`position:absolute;bottom:${cr};display:flex;overflow:hidden;z-index:${wa-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",Ae),Vn=N,e.applyRailChrome(),et()},Ni=()=>{ye?.(),Vn&&(Uo&&(Yr=Date.now()+150),document.removeEventListener("pointermove",Ae),Vn.remove(),Vn=null);let E=xt;if(E){ce?.();for(let N of Le())N&&E.contains(N)&&e.container.insertBefore(N,E);E.remove(),xt=null,xe=null,Wt=null,vt=null}},ze=E=>{me=E,E.id=A,E.style.flex="1 1 auto",E.style.minHeight="0"},Ht=E=>{ze(E),(e.historyPresentation!=="rail"||De)&&Ac(),e.historyPresentation!=="rail"?Zt(E):De?Bu(E):Sc(E)},Vo=()=>{if(gr(),Jr(),!e.historyVisible||!i)return;let E=_();if(E===e.historyPresentation)return;let N=document.activeElement,ne=N instanceof HTMLElement&&(i.element.contains(N)||U?.contains(N)===!0)?N:null;Ni(),i.element.remove(),i.view.setHeaderPlacement("inline"),e.historyPresentation=E,i.view.setPresentation(E),i.view.setCollapsed(Sn()),i.requestRender(),i.element.isConnected||Ht(i.element),ne?.isConnected?ne.focus():mt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),jn()},jo=(E,N)=>U?.querySelector(N)??E.querySelector(N),mt=()=>{let E=i?.element??me;if(!E)return;let N=jo(E,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(N){N.focus();return}let ne=jo(E,".persona-history-title")??E;ne.tabIndex=-1,ne.focus()},Ke=async E=>{if(!L()||e.historyVisible)return;let N=r;if(!N)return;if(!De&&to()&&_i()){gr();return}Fi();let ne=++h;c=E?.returnSurface??"conversation",p=E?.invoker??d;let pe=to()&&!De;pe&&(dr+=1,gr(),Rn());let Re;try{Re=await e.loadHistoryView()}catch{e.announceHistory(o.openHistoryLabel),pe&&(dr-=1,ne===h&&(Ac(),gr()));return}if(pe&&(dr-=1),ne!==h||e.historyVisible)return;l={scope:H()},e.historyPresentation=_(),e.historyVisible=!0;let $t=e.historyPresentation==="panel"&&e.config.layout?.showHeader!==!1&&e.header.style.display!=="none"?"external":"inline",Ot=e.config.features?.history?.rowAvatar,_t=Di(),je=_t?{hint:_t.hint,aria:_t.aria}:null,at={provider:N,context:l,targetId:V(),presentation:e.historyPresentation,collapsible:D(),collapsed:Sn(),railSide:S(),renderRailHeader:e.config.features?.history?.rail?.renderHeader,railBrand:pn(),onToggleCollapse:Bi,...je?{collapseShortcut:je}:{},headerPlacement:$t,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:Ot===!1?!1:typeof Ot=="string"?Ot: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:be=>En(be,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:be=>e.setActiveConversationSummary(be),attachTooltip:e.attachTooltip,onStartNew:()=>Mo({focusComposer:!0}),onClose:()=>xn(),onRequestDeleteConversation:be=>Vt(be),onRequestClearHistory:()=>Fs(),...N.resetDevice?{onRequestResetIdentity:()=>el()}:{}};i=YC({plugins:e.plugins,config:e.config,getPresentation:()=>e.historyPresentation??"panel",getReturnSurface:()=>c,close:()=>xn(),createView:({slots:be,renderDom:Ui,onModelChange:po,railSections:mr})=>(fe=Re.createHistoryView({...at,railSections:ft(mr),slots:be,renderDom:Ui,onModelChange:po,onAnnounce:e.announceHistory}),fe),onElementChanged:(be,Ui)=>{if(!Ui?.isConnected)return Ht(be);ze(be),Ui.replaceWith(be),ut()}}),i.view.setNewConversationRequired(e.historySessionState.recovery==="new_conversation_required"),E?.focus!==!1&&(e.historyPresentation!=="rail"||E?.keyboard===!0)&&mt(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),jn(),e.eventBus.emit("history:opened",{presentation:e.historyPresentation,returnSurface:c,timestamp:Date.now()})},Fi=()=>{},xn=E=>{if(!e.historyVisible)return;h+=1;let N=c,ne=p,pe=i,Re=E?.restoreFocus!==!1;e.historyVisible=!1;let $t=!1,Ot=null,_t=()=>{if(!$t){if($t=!0,Fi=()=>{},Ot!==null&&clearTimeout(Ot),De=!1,ur(),Ni(),pe?.dispose(),pe?.view.destroy(),pe?.element.remove(),i===pe&&(i=null,fe=null,me=null,e.historyPresentation=null,l=null,p=null),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),jn(),Re){let at=ne??d;at?.isConnected?at.focus():e.maybeFocusInput()}e.eventBus.emit("history:closed",{returnSurface:N,timestamp:Date.now()})}},je=pe&&pe.element===pe.view.element?pe.view.playExit():null;if(!je){_t();return}Fi=_t,Ot=setTimeout(_t,250),je.then(_t)},Bs=E=>{if(!(E.key!=="Escape"||!e.historyVisible||!i)){if(e.historyPresentation==="rail"){let N=E.target;if(!(N instanceof Node)||!(i.element.contains(N)||De&&Un?.contains(N)===!0))return}E.preventDefault(),E.stopPropagation(),xn()}};e.container.addEventListener("keydown",Bs),e.destroyCallbacks.push(()=>e.container.removeEventListener("keydown",Bs));let Wn=0,xc=250,he=null,gn=()=>{he&&clearTimeout(he),he=null};e.destroyCallbacks.push(gn);let It=()=>{gn();let E=e.conversationOpenPendingEl;E&&(e.conversationOpenTakeover=!0,E.hidden=!1,e.messagesWrapper.style.display="none",e.updateWelcome())},sn=()=>{Wn+=1,gn(),e.conversationOpenPendingEl&&(e.conversationOpenPendingEl.remove(),e.conversationOpenPendingEl=null,e.conversationOpenTakeover=!1,e.messagesWrapper.style.removeProperty("display"),P(e.footer,!1),e.updateWelcome())},Et=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;e.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},fn=(E,N)=>Q("div",{className:Dn("persona-conversation-loading-bubble",N&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:E}}),Ec=()=>Q("div",{className:"persona-conversation-loading-body"},fn("58%",!1),fn("72%",!0),fn("44%",!1)),Qr=E=>{e.conversationOpenPendingEl?.remove(),e.conversationOpenPendingEl=E,E.hidden=!e.conversationOpenTakeover,e.body.insertBefore(E,e.messagesWrapper),gn(),e.conversationOpenTakeover||(he=setTimeout(It,xc)),P(e.footer,!0)},Du=()=>{let E={config:e.config,streaming:!1,location:"conversation-open",defaultRenderer:Ec},N=null,ne=e.plugins.find(pe=>pe.renderLoadingIndicator);ne?.renderLoadingIndicator&&(N=ne.renderLoadingIndicator(E)),N===null&&e.config.loadingIndicator?.render&&(N=e.config.loadingIndicator.render(E)),Qr(Q("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":o.openConversationLoadingLabel}},N??Ec()))},Nu=E=>{let N=()=>{En(E,{focusComposer:!0}).catch(()=>{})},ne=L()?()=>{sn(),Ke()}:void 0,pe=(_t,je)=>{let at=Q("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:_t});return at.addEventListener("click",je),at},Re=()=>Q("div",{className:"persona-conversation-loading-error-body"},Q("p",{className:"persona-conversation-loading-error-title",text:o.openConversationErrorTitle}),Q("div",{className:"persona-conversation-loading-error-actions"},pe(o.openConversationRetryLabel,N),ne?pe(o.openConversationBackLabel,ne):null)),$t=Object.freeze({conversationId:E,config:e.config,copy:Object.freeze({title:o.openConversationErrorTitle,retryLabel:o.openConversationRetryLabel,backLabel:o.openConversationBackLabel}),retry:N,...ne?{back:ne}:{},defaultRenderer:Re}),Ot=null;for(let _t of e.plugins)if(_t.renderHistoryOpenError){try{Ot=_t.renderHistoryOpenError($t)}catch(je){console.warn("[persona] renderHistoryOpenError threw",je),Ot=null}if(Ot)break}Qr(Q("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},Ot??Re())),It()};e.eventBus.on("history:closed",()=>{e.conversationOpenPendingEl&&P(e.footer,!0)});let En=async(E,{focusComposer:N=!1}={})=>{let ne=B(),pe=!!i;i?.view.setActiveConversationId(E),sn();let Re=Wn;Du(),e.historyVisible&&(e.historyPresentation==="panel"||De)&&xn({restoreFocus:!1}),e.suppressScrollSend=!0;try{await e.session.openConversation(E,{scope:ne})}catch($t){throw Re===Wn&&Nu(E),$t}finally{e.suppressScrollSend=!1}Re===Wn&&(sn(),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.restoreScrollPosition()||e.jumpToBottomInstant(),Et(),Qt(),pe||e.setActiveConversationSummary(null),e.eventBus.emit("history:conversationOpened",{conversationId:E,title:e.activeConversationTitle,scope:ne,timestamp:Date.now()}),N&&e.maybeFocusInput())},Mo=async({focusComposer:E=!1}={})=>{sn(),await e.session.startNewConversation({scope:B()}),e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.jumpToBottomInstant(),Qt();let N=e.session.getActiveConversationId();i?.view.setActiveConversationId(N),e.eventBus.emit("history:conversationStarted",{conversationId:N,timestamp:Date.now()}),e.historyVisible&&(e.historyPresentation==="panel"||De)&&xn({restoreFocus:!1}),E&&e.maybeFocusInput()},Ds=async(E,N)=>{let ne=await e.session.updateConversation(E,{...N,...N.title!==void 0?{title:N.title.trim()}:{}});return i?.view.applyConversationSummary(ne),!i&&E===e.session.getActiveConversationId()&&e.setActiveConversationSummary(ne),ne},Mc=async E=>{let N=B(),ne=e.session.getActiveConversationId()===E;await e.session.deleteConversation(E,{scope:N}),i?.view.removeConversationSummary(E),ne&&(e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Qt()),e.eventBus.emit("history:conversationDeleted",{conversationId:E,scope:N,wasActive:ne,timestamp:Date.now()})},Ja=async E=>{let N=E?.scope??B(),ne=E?.allTargets?null:E?.targetId??V(),pe=await e.session.clearConversationHistory({...ne?{targetId:ne}:{},scope:N});return e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Qt(),e.eventBus.emit("history:cleared",{deleted:pe.deleted,scope:N,targetId:ne,timestamp:Date.now()}),pe},Za=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(),Qt(),xn({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}},$i=()=>e.artifactSplitRoot?e.panel:e.container,Ns=async E=>{let N=await e.loadHistoryView().catch(()=>null);return typeof N?.showHistoryConfirm=="function"?N.showHistoryConfirm(E):window.confirm(`${E.title}
12
12
 
13
- ${E.description}`)},Vt=async E=>await Ns({host:$i(),title:o.deleteConversationConfirmTitle,description:o.deleteConversationConfirm,confirmLabel:o.deleteConversationConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Mc(E),"deleted"):"cancelled",Fs=async()=>{let E=B()==="verified-user";return await Ns({host:$i(),title:o.clearHistoryConfirmTitle,description:E?o.clearHistoryVerifiedConfirm:o.clearHistoryConfirm,confirmLabel:o.clearHistoryConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Ja(),"cleared"):"cancelled"},el=async()=>{if(!await Ns({host:$i(),title:o.resetIdentityConfirmTitle,description:o.resetIdentityConfirm,confirmLabel:o.resetIdentityConfirmLabel,cancelLabel:o.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:N}=await Za();return{outcome:"reset",remoteRevocationConfirmed:N}},tn=x("button","persona-history-earlier");tn.type="button",tn.textContent=o.showEarlierMessagesLabel,tn.setAttribute("data-persona-history-earlier",""),Object.assign(tn.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 Qt=()=>{if(!(L()&&!!e.historySessionState.nextMessageCursor&&!!e.session.getActiveConversationId())){tn.remove();return}tn.textContent=o.showEarlierMessagesLabel,tn.parentNode!==e.body&&e.body.insertBefore(tn,e.body.firstChild)};tn.addEventListener("click",()=>{let E=e.session.getActiveConversationId(),N=e.historySessionState.nextMessageCursor;if(!E||!N||tn.disabled)return;tn.disabled=!0;let ne=e.body.scrollHeight,pe=e.body.scrollTop;e.session.loadOlderMessages(E,N,{scope:B()}).then(()=>{e.body.scrollTop=pe+(e.body.scrollHeight-ne),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{tn.disabled=!1,Qt()})});let To=()=>{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){xn();return}Ke({invoker:E.button,keyboard:N.detail===0})}}),E},Jr=()=>{if(!L()){g?.remove(),d=null,g=null;return}if(g&&!g.isConnected&&(d=null,g=null),!d&&e.header){let pe=To();d=pe.button,g=pe.wrapper;let Re=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;Re?.parentNode&&e.header.contains(Re)?Re.parentNode.insertBefore(g,Re):e.header.appendChild(g)}if(!d||!g)return;let E=to()||e.historyVisible&&e.historyPresentation==="rail";if(g.style.display=E?"none":"",E){document.activeElement===d&&mt();return}let N=I();d.disabled=N,d.setAttribute("aria-disabled",N?"true":"false");let ne=N?o.openHistoryBusyLabel:o.openHistoryLabel;d.setAttribute("aria-label",ne),(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))},fr=!1,$s=()=>{let E=e.panelElements.clearChatButton;if(E){if(L()){fr||(y=E.getAttribute("aria-label")??"",fr=!0),E.setAttribute("aria-label",o.newConversationLabel),E.removeAttribute("title");return}fr&&(fr=!1,y&&E.setAttribute("aria-label",y))}},jn=()=>{o=Jf(e.config.features?.history?.copy),Jr(),gr(),$s(),Qt()};return e.historyChromeSync=jn,T(),jn(),e.destroyCallbacks.push(()=>{b?.(),C?.(),h+=1,Fi(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:L,historyScope:H,installHistoryProvider:T,syncHistoryChromeImpl:jn,syncHistoryPresentation:Vo,syncEarlierMessagesPill:Qt,openHistory:Ke,closeHistory:xn,openHistoryConversation:En,startNewConversation:Mo,updateHistoryConversation:Ds,deleteHistoryConversation:Mc,requestDeleteConversation:Vt,clearConversationHistory:Ja,resetHistoryIdentity:Za,railCollapseShortcut:Di,railCollapsible:D,railTriggerApplies:to,railOverlayMode:Ct,toggleRailCollapsed:Bi,toggleRailPinned:()=>lo(),get historyProvider(){return r},get historySurface(){return i},get railShell(){return xt},get railHost(){return xe},get railColumn(){return Wt}}}});var Ra,gm=Ve(()=>{"use strict";Ra=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 hP(e){return e.replace(/\/+$/,"")}async function yP(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 Ip,Dw=Ve(()=>{"use strict";gm();Ip=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 Ra(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=`${hP(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 yP(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 Rp,Nw=Ve(()=>{"use strict";Rp=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 Fw={};ys(Fw,{FallbackSpeechEngine:()=>Rp,RuntypeSpeechEngine:()=>Ip});var $w=Ve(()=>{"use strict";Dw();Nw()});var DI={};ys(DI,{ASK_USER_QUESTION_CLIENT_TOOL:()=>bf,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>yf,ASK_USER_QUESTION_TOOL_NAME:()=>Hl,AgentWidgetClient:()=>wi,AgentWidgetSession:()=>Wa,AttachmentManager:()=>Ai,BrowserSpeechEngine:()=>Ps,DEFAULT_COMPONENTS:()=>HS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>AC,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>vi,DEFAULT_PALETTE:()=>kS,DEFAULT_SEMANTIC:()=>LS,DEFAULT_WIDGET_CONFIG:()=>EC,HistoryProviderError:()=>Vr,PRESETS:()=>Oh,PRESET_FULLSCREEN:()=>Wh,PRESET_MINIMAL:()=>Rh,PRESET_SHOP:()=>Ih,ReadAloudController:()=>Si,SUGGEST_REPLIES_CLIENT_TOOL:()=>_d,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>mf,SUGGEST_REPLIES_TOOL_NAME:()=>Oo,THEME_ZONES:()=>RS,VERSION:()=>Xn,WEBMCP_TOOL_PREFIX:()=>El,WebMcpBridge:()=>Ou,accessibilityPlugin:()=>Rx,animationsPlugin:()=>Wx,applyFeaturePreferences:()=>yh,applyThemeVariables:()=>Ei,attachHeaderToContainer:()=>Ti,brandPlugin:()=>Ox,buildComposer:()=>Pi,buildDefaultHeader:()=>Fm,buildHeader:()=>jr,buildHeaderWithLayout:()=>Na,buildMinimalHeader:()=>$m,builtInClientToolsForDispatch:()=>fi,canonicalArtifactDisplayMode:()=>Yn,collectEnrichedPageContext:()=>kx,componentRegistry:()=>Fo,createActionManager:()=>mc,createAgentExperience:()=>vu,createAskUserQuestionBubble:()=>Wv,createBestAvailableVoiceProvider:()=>Hu,createBubbleWithLayout:()=>mA,createCSATFeedback:()=>hu,createComboButton:()=>Zp,createComponentMiddleware:()=>ax,createComponentStreamParser:()=>gu,createDefaultSanitizer:()=>sm,createDemoCarousel:()=>Jx,createDirectivePostprocessor:()=>gw,createDropdownMenu:()=>ki,createFlexibleJsonStreamParser:()=>wv,createIconButton:()=>eo,createImagePart:()=>Yd,createJsonStreamParser:()=>Ld,createLabelButton:()=>Nm,createLocalStorageAdapter:()=>uu,createMarkdownProcessor:()=>Vl,createMarkdownProcessorFromConfig:()=>jl,createMessageActions:()=>Km,createNPSFeedback:()=>yu,createPlainTextParser:()=>kd,createPlugin:()=>Dx,createRegexJsonParser:()=>Pd,createRovingTablist:()=>iE,createSlashCommandsSource:()=>sE,createSplitButton:()=>aA,createStandardBubble:()=>Fa,createStaticMentionSource:()=>rE,createTextPart:()=>Ao,createTheme:()=>Gl,createThemeObserver:()=>Oa,createToggleGroup:()=>lc,createTypingIndicator:()=>Li,createVoiceProvider:()=>Xa,createWidgetHostLayout:()=>bc,createXmlParser:()=>Hd,default:()=>Ix,defaultActionHandlers:()=>Wi,defaultJsonActionParser:()=>fc,defaultMentionFilter:()=>_u,defaultParseRules:()=>Lh,detectColorScheme:()=>Xl,directivePostprocessor:()=>fw,ensureAskUserQuestionSheet:()=>Wd,escapeHtml:()=>Ur,extractComponentDirectiveFromMessage:()=>mu,fileToImagePart:()=>kC,formatEnrichedContext:()=>Px,generateAssistantMessageId:()=>ks,generateCodeSnippet:()=>jx,generateMessageId:()=>Mw,generateStableSelector:()=>Hh,generateUserMessageId:()=>Ha,getActiveTheme:()=>No,getAgentWidgetHandles:()=>yx,getColorScheme:()=>xi,getDisplayText:()=>Gd,getHeaderLayout:()=>Um,getImageParts:()=>TC,getPreset:()=>Hx,hasComponentDirective:()=>hc,hasImages:()=>ka,headerLayouts:()=>eu,highContrastPlugin:()=>Bx,initAgentWidget:()=>Mh,isAskUserQuestionMessage:()=>Ir,isComponentDirectiveType:()=>ix,isDockedMountMode:()=>Lt,isHistoryProviderError:()=>Hw,isSuggestRepliesMessage:()=>gi,isVoiceSupported:()=>Fh,isWebMcpToolName:()=>bs,isWelcomeVisible:()=>Ws,latestAgentSuggestions:()=>Bd,listRegisteredStreamAnimations:()=>tA,loadMarkdownParsers:()=>vd,markdownPostprocessor:()=>rm,mergeWithDefaults:()=>Ma,normalizeContent:()=>MC,normalizeMediaType:()=>vs,onMarkdownParsersReady:()=>ua,parseAskUserQuestionPayload:()=>Rr,parseSuggestRepliesPayload:()=>hf,parseWidgetPreferenceSlice:()=>hh,pickBestVoice:()=>Ia,pluginRegistry:()=>gc,reducedMotionPlugin:()=>_x,registerIcons:()=>gv,registerStreamAnimationPlugin:()=>ec,removeAskUserQuestionSheet:()=>Wr,renderComponentDirective:()=>fu,renderLoadingIndicatorWithFallback:()=>zm,renderLucideIcon:()=>ge,resolveArtifactDisplay:()=>lf,resolveArtifactDisplayMode:()=>or,resolveConfigPreferences:()=>uc,resolveDockConfig:()=>Zn,resolveSanitizer:()=>Lp,resolveTokens:()=>qp,resolveWelcomeConfig:()=>Ua,stripWebMcpPrefix:()=>af,themeToCssVariables:()=>zp,unregisterStreamAnimationPlugin:()=>eA,validateImageFile:()=>PC,validateTheme:()=>Mm});module.exports=$M(DI);var cv=require("marked"),dv=Bn(require("dompurify"),1);dn();var{setLoader:zI,load:UM,provide:VM,getSync:ef}=lt({fallbackImport:()=>Promise.resolve().then(()=>(iv(),sv))}),bd=new Set,av=()=>{let e=[...bd];bd.clear();for(let t of e)try{t()}catch{}};var vd=()=>{let e=ef();return e?Promise.resolve(e):UM().then(t=>(av(),t))},ua=e=>ef()?()=>{}:(bd.add(e),()=>{bd.delete(e)}),lv=e=>{VM(e),av()},nr=ef;lv({Marked:cv.Marked,DOMPurify:dv.default});var G=require("lucide"),pv={user:G.User,mail:G.Mail,phone:G.Phone,calendar:G.Calendar,clock:G.Clock,building:G.Building,"map-pin":G.MapPin,lock:G.Lock,key:G.Key,"credit-card":G.CreditCard,hash:G.Hash,globe:G.Globe,link:G.Link,"circle-check":G.CircleCheck,"circle-x":G.CircleX,"triangle-alert":G.TriangleAlert,info:G.Info,ban:G.Ban,shield:G.Shield,house:G.House,"pen-line":G.PenLine,save:G.Save,share:G.Share,funnel:G.Funnel,settings:G.Settings,"rotate-cw":G.RotateCw,"shopping-cart":G.ShoppingCart,"shopping-bag":G.ShoppingBag,package:G.Package,truck:G.Truck,tag:G.Tag,gift:G.Gift,receipt:G.Receipt,wallet:G.Wallet,store:G.Store,"dollar-sign":G.DollarSign,percent:G.Percent,play:G.Play,pause:G.Pause,"volume-x":G.VolumeX,camera:G.Camera,image:G.Image,film:G.Film,headphones:G.Headphones,"message-circle":G.MessageCircle,bell:G.Bell,heart:G.Heart,"eye-off":G.EyeOff,bookmark:G.Bookmark,"calendar-days":G.CalendarDays,timer:G.Timer,folder:G.Folder,"folder-open":G.FolderOpen,files:G.Files,"chart-column":G.ChartColumn,sparkles:G.Sparkles,zap:G.Zap,sun:G.Sun,moon:G.Moon,flag:G.Flag,lightbulb:G.Lightbulb,monitor:G.Monitor,smartphone:G.Smartphone};Pt();fv(pv);vf();dn();var{setLoader:xR,load:TT,provide:kT,getSync:PT}=lt({fallbackImport:()=>Promise.resolve().then(()=>(vf(),Fd))});var mi=TT,Uv=kT,Vv=PT;Uv(Fd);Af();dn();var{setLoader:IR,load:UT,provide:VT}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Af(),$d))});var Or=UT,eC=VT;eC($d);Kf();dn();var{setLoader:WW,load:fk,provide:mk,getSync:hk}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Kf(),dp))});var pp=fk,FC=mk,Gf=hk;FC(dp);Xf();dn();var{setLoader:NW,load:xk,provide:Ek,getSync:Mk}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Xf(),gp))});var Qf=xk,VC=Ek,jC=Mk;VC(gp);nm();dn();var{setLoader:nO,load:Fk,provide:$k,getSync:Uk}=lt({fallbackImport:()=>Promise.resolve().then(()=>(nm(),Cp))});var rw=Fk,sw=$k,wp=Uk;sw(Cp);var kp=require("lucide");Lr();So();Ze();Pt();Ze();var Sp=require("lucide");Lr();var Vk=["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"],jk="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",qk="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",zk=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Ap=(e,t)=>{let n=x("div",["persona-message-bubble",e,...Vk].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},xp=e=>{let t=x("button",e.expandable?jk:qk);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},om=(e,t,n)=>{e.innerHTML="";let o=Nt(t?Sp.ChevronUp:Sp.ChevronDown,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},La=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=x("div","persona-flex persona-items-center");om(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},Ep=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?.();zk(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Mp=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&om(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"},Tp=(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&&om(c,o,n.iconColor),s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")};function Pp(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[n]:{...t==="tool"?Br:Ci,...e?.future?.v5Defaults===!0?bi.features?.[n]:{},...e?.features?.[n]}}}}function Ts(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[n]?.variant??(e?.future?.v5Defaults?"row":"card")}function Ul(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 $r(e,t,n,o){if(Ts(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?ge(g,16,"currentColor",2):c==="pending"?Nt(kp.Circle,16,"currentColor",2):c==="awaiting-approval"?Nt(kp.Clock,16,"currentColor",2):ge(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?"":Ul(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 iw(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 aw(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),La(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),$r(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}}kf();function lw(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 In(e){return e?.type==="runtype"||e?.type==="custom"}var Kk=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function cw(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:Kk()}catch{return!1}}var Gk=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},Vl=e=>{let t=null;return n=>{let o=nr();if(!o)return Ur(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=Gk(e?.renderer);i&&t.use({renderer:i})}return t.parse(n)}},jl=e=>e?Vl({markedOptions:e.options,renderer:e.renderer}):Vl(),Yk=Vl(),rm=e=>Yk(e),Ur=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),pw=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),dw=e=>`%%FORM_PLACEHOLDER_${e}%%`,uw=(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=dw(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=dw(t.length);return t.push({token:s,type:r}),s}),n},gw=e=>{let t=jl(e);return n=>{let o=[],r=uw(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="${pw(l)}"></div>`;s=s.replace(c,d)}),s}},fw=e=>{let t=[],n=uw(e,t),o=rm(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="${pw(s)}"></div>`;o=o.replace(i,c)}),o};var Xk={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"]},Qk=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,sm=()=>{let e=null;return t=>{let n=nr();if(!n)return Ur(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:")&&!Qk.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,Xk)}},Lp=e=>e===!1?null:typeof e=="function"?e:sm();var mw=/^\s*\|?[\s:|-]*-[\s:|-]*$/,hw=e=>e.includes("|"),yw=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())},Jk=e=>`| ${e.join(" | ")} |`,Zk=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,eP=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),bw=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(!hw(r)||mw.test(r)||!mw.test(s))continue;let i=yw(r).length;if(i<1)continue;let l=Zk(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()===""||!hw(p))break;let d=Jk(eP(yw(p),i));t[c]!==d&&(t[c]=d,n=!0)}o=c-1}return n?t.join(`
15
- `):e};var vw="var(--persona-md-table-scroll-fade, 24px)",Cw=new WeakSet;function Sw(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 ww(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":vw),e.style.setProperty("--persona-fade-r",r<=1?"0px":vw)}function im(e){Cw.has(e)||(Cw.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&ww(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(ww)}pi();dn();var{setLoader:AO,load:tP}=lt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var Aw=tP;var nP="agent_",oP="flow_";function xw(e){return e.startsWith(nP)?{kind:"agentId",agentId:e}:e.startsWith(oP)?{kind:"flowId",flowId:e}:null}function Ew(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=xw(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=xw(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 Mw(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ha(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function ks(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Tw(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}Dd();var rP=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),sP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iP=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=rP(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:sP(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},am=(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=iP(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};Cs();Sa();vp();_o();var aP="https://api.runtype.com/v1/dispatch",on=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},kw=e=>"reason"in e?e.reason:void 0,lP="The identity proof was rejected",lm=(e,t)=>e instanceof on&&e.code===t,cm=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),Pw=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),Lw=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function cP(e){switch(e){case"json":return Ld;case"regex-json":return Pd;case"xml":return Hd;default:return kd}}var wi=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??aP,this.#n={"Content-Type":"application/json","X-Persona-Version":Xn,...t.headers},this.debug=!!t.debug,this.#o=t.streamParser??cP(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 Aw().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:Sd,getToolDisplayTitle:ma,loadPolyfill:Ad});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=Ew(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$/,"")||Nd}#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 on("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":Xn,"X-Visitor-Token":s},signal:t.signal});if(c.status===401&&!o){o=!0;let p=await Or();n=await p.recoverFromUnauthorized(this.#W(),await p.readErrorCode(this.#W(),c),null,!0);continue}if(!c.ok)throw await(await Or()).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&&kw(n)===kw(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":Xn},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 on("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 on("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&p.status===401&&g.error==="visitor_required"?new on("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new on("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(!lm(r,"not_found")&&!lm(r,"visitor_required")&&!lm(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 on("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 on("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":Xn},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:on,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 Or()).listConversations(this.#W(),t)}async getConversation(t,n){return(await Or()).getConversation(this.#W(),t,n)}async finalizeDisplayProjections(t,n){return(await Or()).finalizeDisplayProjections(this.#W(),t,n)}async deleteConversation(t,n){return(await Or()).deleteConversation(this.#W(),t,n)}async deleteAllConversations(t){return(await Or()).deleteAllConversations(this.#W(),t)}async resetVisitor(){return(await Or()).resetVisitor(this.#W())}async dispatch(t,n){return t.signal?.throwIfAborted(),mi().catch(()=>{}),this.isClientTokenMode()?this.#be(t,n):this.isAgentMode()?this.#ae(t,n):this.#ve(t,n)}async#be(t,n){let o=Tw();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(cm).map(A=>{let L=g?Fl(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":Xn,...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 on("invalid_identity_proof",lP);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 on("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 on)&&!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 mi()).resolveApproval(this.#D(),t,n)}async#Y(t,n,o,r){let s=!!(n&&n.length>0),i=s?yv(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 mi()).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=am(Pw(t),p=>cm(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?Lw(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=[...fi(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=am(Pw(t),p=>cm(p)?Lw(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=[...fi(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}=Vv()??await mi();return s({config:()=>this.config,createStreamParser:this.#o,parseSSEEvent:this.#p,onSSEEvent:(i,l)=>this.#i?.(i,l)},t,n,o,r)}};var Vr=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function Hw(e){return e instanceof Vr}pi();Ca();Nr();ha();Nr();function dP(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 Iw(e,t){let n="`".repeat(Math.max(3,dP(t)+1));return`${n}${e}
13
+ ${E.description}`)},Vt=async E=>await Ns({host:$i(),title:o.deleteConversationConfirmTitle,description:o.deleteConversationConfirm,confirmLabel:o.deleteConversationConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Mc(E),"deleted"):"cancelled",Fs=async()=>{let E=B()==="verified-user";return await Ns({host:$i(),title:o.clearHistoryConfirmTitle,description:E?o.clearHistoryVerifiedConfirm:o.clearHistoryConfirm,confirmLabel:o.clearHistoryConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Ja(),"cleared"):"cancelled"},el=async()=>{if(!await Ns({host:$i(),title:o.resetIdentityConfirmTitle,description:o.resetIdentityConfirm,confirmLabel:o.resetIdentityConfirmLabel,cancelLabel:o.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:N}=await Za();return{outcome:"reset",remoteRevocationConfirmed:N}},tn=x("button","persona-history-earlier");tn.type="button",tn.textContent=o.showEarlierMessagesLabel,tn.setAttribute("data-persona-history-earlier",""),Object.assign(tn.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 Qt=()=>{if(!(L()&&!!e.historySessionState.nextMessageCursor&&!!e.session.getActiveConversationId())){tn.remove();return}tn.textContent=o.showEarlierMessagesLabel,tn.parentNode!==e.body&&e.body.insertBefore(tn,e.body.firstChild)};tn.addEventListener("click",()=>{let E=e.session.getActiveConversationId(),N=e.historySessionState.nextMessageCursor;if(!E||!N||tn.disabled)return;tn.disabled=!0;let ne=e.body.scrollHeight,pe=e.body.scrollTop;e.session.loadOlderMessages(E,N,{scope:B()}).then(()=>{e.body.scrollTop=pe+(e.body.scrollHeight-ne),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{tn.disabled=!1,Qt()})});let To=()=>{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){xn();return}Ke({invoker:E.button,keyboard:N.detail===0})}}),E},Jr=()=>{if(!L()){g?.remove(),d=null,g=null;return}if(g&&!g.isConnected&&(d=null,g=null),!d&&e.header){let pe=To();d=pe.button,g=pe.wrapper;let Re=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;Re?.parentNode&&e.header.contains(Re)?Re.parentNode.insertBefore(g,Re):e.header.appendChild(g)}if(!d||!g)return;let E=to()||e.historyVisible&&e.historyPresentation==="rail";if(g.style.display=E?"none":"",E){document.activeElement===d&&mt();return}let N=I();d.disabled=N,d.setAttribute("aria-disabled",N?"true":"false");let ne=N?o.openHistoryBusyLabel:o.openHistoryLabel;d.setAttribute("aria-label",ne),(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))},fr=!1,$s=()=>{let E=e.panelElements.clearChatButton;if(E){if(L()){fr||(y=E.getAttribute("aria-label")??"",fr=!0),E.setAttribute("aria-label",o.newConversationLabel),E.removeAttribute("title");return}fr&&(fr=!1,y&&E.setAttribute("aria-label",y))}},jn=()=>{o=Jf(e.config.features?.history?.copy),Jr(),gr(),$s(),Qt()};return e.historyChromeSync=jn,T(),jn(),e.destroyCallbacks.push(()=>{b?.(),C?.(),h+=1,Fi(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:L,historyScope:H,installHistoryProvider:T,syncHistoryChromeImpl:jn,syncHistoryPresentation:Vo,syncEarlierMessagesPill:Qt,openHistory:Ke,closeHistory:xn,openHistoryConversation:En,startNewConversation:Mo,updateHistoryConversation:Ds,deleteHistoryConversation:Mc,requestDeleteConversation:Vt,clearConversationHistory:Ja,resetHistoryIdentity:Za,railCollapseShortcut:Di,railCollapsible:D,railTriggerApplies:to,railOverlayMode:Ct,toggleRailCollapsed:Bi,toggleRailPinned:()=>lo(),get historyProvider(){return r},get historySurface(){return i},get railShell(){return xt},get railHost(){return xe},get railColumn(){return Wt}}}});var Ra,gm=Ve(()=>{"use strict";Ra=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 yk(e){return e.replace(/\/+$/,"")}async function bk(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 Ip,Dw=Ve(()=>{"use strict";gm();Ip=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 Ra(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=`${yk(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 bk(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 Rp,Nw=Ve(()=>{"use strict";Rp=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 Fw={};ys(Fw,{FallbackSpeechEngine:()=>Rp,RuntypeSpeechEngine:()=>Ip});var $w=Ve(()=>{"use strict";Dw();Nw()});var NI={};ys(NI,{ASK_USER_QUESTION_CLIENT_TOOL:()=>bf,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>yf,ASK_USER_QUESTION_TOOL_NAME:()=>Hl,AgentWidgetClient:()=>wi,AgentWidgetSession:()=>Wa,AttachmentManager:()=>Ai,BrowserSpeechEngine:()=>ks,DEFAULT_COMPONENTS:()=>HS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>AC,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>vi,DEFAULT_PALETTE:()=>PS,DEFAULT_SEMANTIC:()=>LS,DEFAULT_WIDGET_CONFIG:()=>EC,HistoryProviderError:()=>Vr,PRESETS:()=>Oh,PRESET_FULLSCREEN:()=>Wh,PRESET_MINIMAL:()=>Rh,PRESET_SHOP:()=>Ih,ReadAloudController:()=>Si,SUGGEST_REPLIES_CLIENT_TOOL:()=>_d,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>mf,SUGGEST_REPLIES_TOOL_NAME:()=>Oo,THEME_ZONES:()=>RS,VERSION:()=>Xn,WEBMCP_TOOL_PREFIX:()=>El,WebMcpBridge:()=>Ou,accessibilityPlugin:()=>Rx,animationsPlugin:()=>Wx,applyFeaturePreferences:()=>yh,applyThemeVariables:()=>Ei,attachHeaderToContainer:()=>Ti,brandPlugin:()=>Ox,buildComposer:()=>ki,buildDefaultHeader:()=>Fm,buildHeader:()=>jr,buildHeaderWithLayout:()=>Na,buildMinimalHeader:()=>$m,builtInClientToolsForDispatch:()=>fi,canonicalArtifactDisplayMode:()=>Yn,collectEnrichedPageContext:()=>Px,componentRegistry:()=>Fo,createActionManager:()=>mc,createAgentExperience:()=>vu,createAskUserQuestionBubble:()=>Wv,createBestAvailableVoiceProvider:()=>Hu,createBubbleWithLayout:()=>mA,createCSATFeedback:()=>hu,createComboButton:()=>Zp,createComponentMiddleware:()=>ax,createComponentStreamParser:()=>gu,createDefaultSanitizer:()=>sm,createDemoCarousel:()=>Jx,createDirectivePostprocessor:()=>gw,createDropdownMenu:()=>Pi,createFlexibleJsonStreamParser:()=>wv,createIconButton:()=>eo,createImagePart:()=>Yd,createJsonStreamParser:()=>Ld,createLabelButton:()=>Nm,createLocalStorageAdapter:()=>uu,createMarkdownProcessor:()=>Vl,createMarkdownProcessorFromConfig:()=>jl,createMessageActions:()=>Km,createNPSFeedback:()=>yu,createPlainTextParser:()=>Pd,createPlugin:()=>Dx,createRegexJsonParser:()=>kd,createRovingTablist:()=>aE,createSlashCommandsSource:()=>iE,createSplitButton:()=>aA,createStandardBubble:()=>Fa,createStaticMentionSource:()=>sE,createTextPart:()=>Ao,createTheme:()=>Gl,createThemeObserver:()=>Oa,createToggleGroup:()=>lc,createTypingIndicator:()=>Li,createVoiceProvider:()=>Xa,createWidgetHostLayout:()=>bc,createXmlParser:()=>Hd,default:()=>Ix,defaultActionHandlers:()=>Wi,defaultJsonActionParser:()=>fc,defaultMentionFilter:()=>_u,defaultParseRules:()=>Lh,detectColorScheme:()=>Xl,directivePostprocessor:()=>fw,ensureAskUserQuestionSheet:()=>Wd,escapeHtml:()=>Ur,extractComponentDirectiveFromMessage:()=>mu,fileToImagePart:()=>PC,formatEnrichedContext:()=>kx,generateAssistantMessageId:()=>Ps,generateCodeSnippet:()=>jx,generateMessageId:()=>Mw,generateStableSelector:()=>Hh,generateUserMessageId:()=>Ha,getActiveTheme:()=>No,getAgentWidgetHandles:()=>yx,getColorScheme:()=>xi,getDisplayText:()=>Gd,getHeaderLayout:()=>Um,getImageParts:()=>TC,getPreset:()=>Hx,hasComponentDirective:()=>hc,hasImages:()=>Pa,headerLayouts:()=>eu,highContrastPlugin:()=>Bx,initAgentWidget:()=>Mh,isAskUserQuestionMessage:()=>Ir,isComponentDirectiveType:()=>ix,isDockedMountMode:()=>Lt,isHistoryProviderError:()=>Hw,isSuggestRepliesMessage:()=>gi,isVoiceSupported:()=>Fh,isWebMcpToolName:()=>bs,isWelcomeVisible:()=>Ws,latestAgentSuggestions:()=>Bd,listRegisteredStreamAnimations:()=>tA,loadMarkdownParsers:()=>vd,markdownPostprocessor:()=>rm,mergeWithDefaults:()=>Ma,normalizeContent:()=>MC,normalizeMediaType:()=>vs,onMarkdownParsersReady:()=>ua,parseAskUserQuestionPayload:()=>Rr,parseSuggestRepliesPayload:()=>hf,parseWidgetPreferenceSlice:()=>hh,pickBestVoice:()=>Ia,pluginRegistry:()=>gc,reducedMotionPlugin:()=>_x,registerIcons:()=>gv,registerStreamAnimationPlugin:()=>ec,removeAskUserQuestionSheet:()=>Wr,renderComponentDirective:()=>fu,renderLoadingIndicatorWithFallback:()=>zm,renderLucideIcon:()=>ge,resolveArtifactDisplay:()=>lf,resolveArtifactDisplayMode:()=>or,resolveConfigPreferences:()=>uc,resolveDockConfig:()=>Zn,resolveSanitizer:()=>Lp,resolveTokens:()=>qp,resolveWelcomeConfig:()=>Ua,stripWebMcpPrefix:()=>af,themeToCssVariables:()=>zp,unregisterStreamAnimationPlugin:()=>eA,validateImageFile:()=>kC,validateTheme:()=>Mm});module.exports=UM(NI);var cv=require("marked"),dv=Bn(require("dompurify"),1);dn();var{setLoader:KI,load:VM,provide:jM,getSync:ef}=lt({fallbackImport:()=>Promise.resolve().then(()=>(iv(),sv))}),bd=new Set,av=()=>{let e=[...bd];bd.clear();for(let t of e)try{t()}catch{}};var vd=()=>{let e=ef();return e?Promise.resolve(e):VM().then(t=>(av(),t))},ua=e=>ef()?()=>{}:(bd.add(e),()=>{bd.delete(e)}),lv=e=>{jM(e),av()},nr=ef;lv({Marked:cv.Marked,DOMPurify:dv.default});var G=require("lucide"),pv={user:G.User,mail:G.Mail,phone:G.Phone,calendar:G.Calendar,clock:G.Clock,building:G.Building,"map-pin":G.MapPin,lock:G.Lock,key:G.Key,"credit-card":G.CreditCard,hash:G.Hash,globe:G.Globe,link:G.Link,"circle-check":G.CircleCheck,"circle-x":G.CircleX,"triangle-alert":G.TriangleAlert,info:G.Info,ban:G.Ban,shield:G.Shield,house:G.House,"pen-line":G.PenLine,save:G.Save,share:G.Share,funnel:G.Funnel,settings:G.Settings,"rotate-cw":G.RotateCw,"shopping-cart":G.ShoppingCart,"shopping-bag":G.ShoppingBag,package:G.Package,truck:G.Truck,tag:G.Tag,gift:G.Gift,receipt:G.Receipt,wallet:G.Wallet,store:G.Store,"dollar-sign":G.DollarSign,percent:G.Percent,play:G.Play,pause:G.Pause,"volume-x":G.VolumeX,camera:G.Camera,image:G.Image,film:G.Film,headphones:G.Headphones,"message-circle":G.MessageCircle,bell:G.Bell,heart:G.Heart,"eye-off":G.EyeOff,bookmark:G.Bookmark,"calendar-days":G.CalendarDays,timer:G.Timer,folder:G.Folder,"folder-open":G.FolderOpen,files:G.Files,"chart-column":G.ChartColumn,sparkles:G.Sparkles,zap:G.Zap,sun:G.Sun,moon:G.Moon,flag:G.Flag,lightbulb:G.Lightbulb,monitor:G.Monitor,smartphone:G.Smartphone};kt();fv(pv);vf();dn();var{setLoader:ER,load:PT,provide:kT,getSync:LT}=lt({fallbackImport:()=>Promise.resolve().then(()=>(vf(),Fd))});var mi=PT,Uv=kT,Vv=LT;Uv(Fd);Af();dn();var{setLoader:RR,load:VT,provide:jT}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Af(),$d))});var Or=VT,eC=jT;eC($d);Kf();dn();var{setLoader:OW,load:mP,provide:hP,getSync:yP}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Kf(),dp))});var pp=mP,FC=hP,Gf=yP;FC(dp);Xf();dn();var{setLoader:FW,load:EP,provide:MP,getSync:TP}=lt({fallbackImport:()=>Promise.resolve().then(()=>(Xf(),gp))});var Qf=EP,VC=MP,jC=TP;VC(gp);nm();dn();var{setLoader:oO,load:$P,provide:UP,getSync:VP}=lt({fallbackImport:()=>Promise.resolve().then(()=>(nm(),Cp))});var rw=$P,sw=UP,wp=VP;sw(Cp);var Pp=require("lucide");Lr();So();Ze();kt();Ze();var Sp=require("lucide");Lr();var jP=["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"],qP="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",zP="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",KP=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Ap=(e,t)=>{let n=x("div",["persona-message-bubble",e,...jP].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},xp=e=>{let t=x("button",e.expandable?qP:zP);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},om=(e,t,n)=>{e.innerHTML="";let o=Nt(t?Sp.ChevronUp:Sp.ChevronDown,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},La=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=x("div","persona-flex persona-items-center");om(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},Ep=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?.();KP(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Mp=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&om(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"},Tp=(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&&om(c,o,n.iconColor),s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")};function kp(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[n]:{...t==="tool"?Br:Ci,...e?.future?.v5Defaults===!0?bi.features?.[n]:{},...e?.features?.[n]}}}}function Ts(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[n]?.variant??(e?.future?.v5Defaults?"row":"card")}function Ul(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 $r(e,t,n,o){if(Ts(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?ge(g,16,"currentColor",2):c==="pending"?Nt(Pp.Circle,16,"currentColor",2):c==="awaiting-approval"?Nt(Pp.Clock,16,"currentColor",2):ge(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?"":Ul(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 iw(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 aw(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),La(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),$r(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}}Pf();function lw(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 In(e){return e?.type==="runtype"||e?.type==="custom"}var GP=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function cw(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:GP()}catch{return!1}}var YP=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},Vl=e=>{let t=null;return n=>{let o=nr();if(!o)return Ur(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=YP(e?.renderer);i&&t.use({renderer:i})}return t.parse(n)}},jl=e=>e?Vl({markedOptions:e.options,renderer:e.renderer}):Vl(),XP=Vl(),rm=e=>XP(e),Ur=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),pw=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),dw=e=>`%%FORM_PLACEHOLDER_${e}%%`,uw=(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=dw(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=dw(t.length);return t.push({token:s,type:r}),s}),n},gw=e=>{let t=jl(e);return n=>{let o=[],r=uw(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="${pw(l)}"></div>`;s=s.replace(c,d)}),s}},fw=e=>{let t=[],n=uw(e,t),o=rm(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="${pw(s)}"></div>`;o=o.replace(i,c)}),o};var QP={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"]},JP=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,sm=()=>{let e=null;return t=>{let n=nr();if(!n)return Ur(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:")&&!JP.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,QP)}},Lp=e=>e===!1?null:typeof e=="function"?e:sm();var mw=/^\s*\|?[\s:|-]*-[\s:|-]*$/,hw=e=>e.includes("|"),yw=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())},ZP=e=>`| ${e.join(" | ")} |`,ek=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,tk=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),bw=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(!hw(r)||mw.test(r)||!mw.test(s))continue;let i=yw(r).length;if(i<1)continue;let l=ek(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()===""||!hw(p))break;let d=ZP(tk(yw(p),i));t[c]!==d&&(t[c]=d,n=!0)}o=c-1}return n?t.join(`
15
+ `):e};var vw="var(--persona-md-table-scroll-fade, 24px)",Cw=new WeakSet;function Sw(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 ww(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":vw),e.style.setProperty("--persona-fade-r",r<=1?"0px":vw)}function im(e){Cw.has(e)||(Cw.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&ww(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(ww)}pi();dn();var{setLoader:xO,load:nk}=lt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var Aw=nk;var ok="agent_",rk="flow_";function xw(e){return e.startsWith(ok)?{kind:"agentId",agentId:e}:e.startsWith(rk)?{kind:"flowId",flowId:e}:null}function Ew(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=xw(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=xw(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 Mw(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ha(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ps(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Tw(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}Dd();var sk=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),ik=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ak=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=sk(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:ik(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},am=(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=ak(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};Cs();Sa();vp();_o();var lk="https://api.runtype.com/v1/dispatch",on=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Pw=e=>"reason"in e?e.reason:void 0,ck="The identity proof was rejected",lm=(e,t)=>e instanceof on&&e.code===t,cm=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),kw=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),Lw=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function dk(e){switch(e){case"json":return Ld;case"regex-json":return kd;case"xml":return Hd;default:return Pd}}var wi=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??lk,this.#n={"Content-Type":"application/json","X-Persona-Version":Xn,...t.headers},this.debug=!!t.debug,this.#o=t.streamParser??dk(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 Aw().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:Sd,getToolDisplayTitle:ma,loadPolyfill:Ad});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=Ew(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$/,"")||Nd}#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 on("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":Xn,"X-Visitor-Token":s},signal:t.signal});if(c.status===401&&!o){o=!0;let p=await Or();n=await p.recoverFromUnauthorized(this.#W(),await p.readErrorCode(this.#W(),c),null,!0);continue}if(!c.ok)throw await(await Or()).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&&Pw(n)===Pw(t);if(this.#S=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.#E])r(t)}}async#P(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":Xn},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 on("history_disabled","Visitor history is disabled for this surface");return this.#P({...t,omitVisitorFields:!0})}throw p.status===403&&g.error==="durable_recovery_disabled"?new on("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&p.status===401&&g.error==="visitor_required"?new on("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new on("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.#P({conversationId:t,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#k(r,t,!1)}catch(r){if(!lm(r,"not_found")&&!lm(r,"visitor_required")&&!lm(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.#P({storedSessionId:o}),s=await this.#re(r);return this.#k(s,t,n)}async#Z(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.#P({storedSessionId:n,identityProof:t}),s=this.#k(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.#P({storedSessionId:t.sessionId})}catch{return t}finally{this.#x=!1}}#k(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 on("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 on("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.#P({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.#P({});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":Xn},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:on,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 Or()).listConversations(this.#W(),t)}async getConversation(t,n){return(await Or()).getConversation(this.#W(),t,n)}async finalizeDisplayProjections(t,n){return(await Or()).finalizeDisplayProjections(this.#W(),t,n)}async deleteConversation(t,n){return(await Or()).deleteConversation(this.#W(),t,n)}async deleteAllConversations(t){return(await Or()).deleteAllConversations(this.#W(),t)}async resetVisitor(){return(await Or()).resetVisitor(this.#W())}async dispatch(t,n){return t.signal?.throwIfAborted(),mi().catch(()=>{}),this.isClientTokenMode()?this.#be(t,n):this.isAgentMode()?this.#ae(t,n):this.#ve(t,n)}async#be(t,n){let o=Tw();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.#P({...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.#k(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(cm).map(A=>{let L=g?Fl(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":Xn,...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 on("invalid_identity_proof",ck);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 on("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 on)&&!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 mi()).resolveApproval(this.#D(),t,n)}async#Y(t,n,o,r){let s=!!(n&&n.length>0),i=s?yv(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 mi()).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=am(kw(t),p=>cm(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?Lw(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=[...fi(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=am(kw(t),p=>cm(p)?Lw(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=[...fi(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}=Vv()??await mi();return s({config:()=>this.config,createStreamParser:this.#o,parseSSEEvent:this.#p,onSSEEvent:(i,l)=>this.#i?.(i,l)},t,n,o,r)}};var Vr=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function Hw(e){return e instanceof Vr}pi();Ca();Nr();ha();Nr();function pk(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 Iw(e,t){let n="`".repeat(Math.max(3,pk(t)+1));return`${n}${e}
17
17
  ${t}
18
- ${n}`}var pP=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function uP(e){let t=e?.text?.trim()??"";return t?Iw(pP(e),t):""}function Rw(e){let t=uP(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[Ao(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
18
+ ${n}`}var uk=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function gk(e){let t=e?.text?.trim()??"";return t?Iw(uk(e),t):""}function Rw(e){let t=gk(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[Ao(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
19
19
 
20
- `)}:{}}function Hp(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Ww(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 dm(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 Ow(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 dm(e,n.id)?n.id:null}return null}function pm(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}vp();function Ia(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 Ps=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):Ia(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 Si=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 ql=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)}};dn();var{setLoader:QO,load:gP,getSync:fP}=lt({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")});var zl=gP,_w=fP;function um(e){if(!e)return"";let t=mP(e);return Bw(t!==null?t:e)}function mP(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 Bw(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 Hp(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Ww(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 dm(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 Ow(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 dm(e,n.id)?n.id:null}return null}function pm(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}vp();function Ia(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 ks=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):Ia(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 Si=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 ql=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)}};dn();var{setLoader:JO,load:fk,getSync:mk}=lt({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")});var zl=fk,_w=mk;function um(e){if(!e)return"";let t=hk(e);return Bw(t!==null?t:e)}function hk(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 Bw(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 Uw=null;var fm=()=>Uw?Uw():Promise.resolve().then(()=>($w(),Fw));dn();var{setLoader:l_,load:bP}=lt({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")});var Vw=bP;var vP=["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 CP(e,t){return vP.some(n=>e[n]!==t[n])}var rr=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function mm(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 Uw=null;var fm=()=>Uw?Uw():Promise.resolve().then(()=>($w(),Fw));dn();var{setLoader:c_,load:vk}=lt({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")});var Vw=vk;var Ck=["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 wk(e,t){return Ck.some(n=>e[n]!==t[n])}var rr=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function mm(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 jw=e=>bs(e)||e===Oo,Wa=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 ql;this.#se=Promise.resolve();this.#z=null;this.#D=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Si(()=>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)&&Qf().catch(()=>{});let r=t.message.toolCall,s=!!r?.name&&(bs(r.name)||r.name===Oo&&xs(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 wi(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&&zl().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||fm().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 cw(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=Ps.isSupported()?new Ps({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 fm().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=zl().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(!In(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 ql,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 rr("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 Vr("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 rr("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 rr("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.#A)throw l.discard(),new rr("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=$l(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 rr("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 rr("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 rr("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 rr("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=$l(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=Fl(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=Fl(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 on&&(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 on?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 on&&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=lw(this.config,o),s=CP(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&In(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 wi(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"?Ha():n==="assistant"?ks():`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"?Ha():r==="assistant"?ks():`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(`
24
+ _Details: ${n.message}_`:o}var jw=e=>bs(e)||e===Oo,Wa=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.#P=null;this.#J=null;this.#B=!1;this.#R=null;this.#k=null;this.#F=null;this.#U=new ql;this.#se=Promise.resolve();this.#z=null;this.#D=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Si(()=>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)&&Qf().catch(()=>{});let r=t.message.toolCall,s=!!r?.name&&(bs(r.name)||r.name===Oo&&xs(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.#ke(),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.#ke(),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 wi(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;#P;#J;#B;#R;#Z(){this.config.voiceRecognition?.provider&&zl().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||fm().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 cw(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()}#k;#F;#U;#se;#z;#D;#ie(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=ks.isSupported()?new ks({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 fm().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=zl().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.#k},set pendingUser(r){o.#k=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(!In(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 ql,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.#k:null,o=this.#F;!n&&!o||(o&&this.#U.cancel(),t&&(this.#k=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.#P?.(),this.#P=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 rr("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 Vr("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 rr("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 rr("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.#A)throw l.discard(),new rr("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=$l(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 rr("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 rr("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 rr("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 rr("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.#P?.(),this.#P=null,this.#J=t,t&&(this.#P=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=$l(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=Fl(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=Fl(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 on&&(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 on?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 on&&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=lw(this.config,o),s=wk(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&In(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 wi(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"?Ha():n==="assistant"?Ps():`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"?Ha():r==="assistant"?Ps():`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(Ao(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(c){let p=[];i&&p.push(Ao(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??Ha(),c=ks();this.#s=null;let p=n?.contentParts&&ka(n.contentParts)?Ta:"",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=Rw({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=mm(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=Ww(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=ks();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=mm(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=jC();if(o)return t(o,n);let r=this.#de;return Qf().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=or(this.config.features?.artifacts,t),r=Ml(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=or(this.config.features?.artifacts,n),s=Ml(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=Vw().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=>mm(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=ks(),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=um(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(t){return Ia(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=um(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&&jw(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&&jw(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)})}};Ze();var xo=require("lucide");Lr();Pt();Nr();var wP={add:e=>IC(e)},SP=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Wp={allowedTypes:Dr,maxFileSize:10*1024*1024,maxFiles:4};function AP(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function xP(e){return e==="application/pdf"?xo.FileText:e.startsWith("text/")?xo.FileText:e.includes("word")?xo.FileText:e.includes("excel")||e.includes("spreadsheet")?xo.FileSpreadsheet:e==="application/json"?xo.FileCode:xo.File}var Ai=class e{constructor(t={}){this.attachments=[];this.#e=null;this.#n=new Map;this.#o=!1;this.config={allowedTypes:t.allowedTypes??Wp.allowedTypes,maxFileSize:t.maxFileSize??Wp.maxFileSize,maxFiles:t.maxFiles??Wp.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:wP}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:Wp.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=RC(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:AP(),file:o,previewUrl:Xd(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=SP(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=Xd(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=xP(t.file.type),f=Nt(g,20,"var(--persona-muted, #6b7280)",1.5);f&&d.appendChild(f);let h=x("span");h.textContent=WC(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=Q("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=Q("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=ge("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=Nt(xo.X,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 qw=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),EP=(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 zw(){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=>{EP(e.attachments,d)||(e.attachments=[...d],p())},setMentionRefs:d=>{qw(e.mentionRefs,d)||(e.mentionRefs=[...d],p())},setSelectedModelId:d=>{e.selectedModelId!==d&&(e.selectedModelId=d,p())},setActiveModeIds:d=>{qw(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()}}}Ze();var Jn=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},Kw=(e,t)=>{let n=x("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function Gw(e,t={}){let n=Jn(e,"[data-persona-composer-form]"),o=Jn(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:Jn(e,"[data-persona-composer-header]"),body:Jn(e,"[data-persona-composer-body]"),actionsStart:Jn(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Jn(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Jn(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Jn(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Jn(e,"[data-persona-composer-status]")},s=new Set,i=r.header;i||(s.add("header"),i=Kw("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=Kw(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=Jn(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:Jn(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Jn(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Jn(e,"[data-persona-composer-submit]")??void 0,micButton:Jn(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=[]}}}Ze();Pt();xa();Ms();function MP(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??MP(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,oe=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);oe=Math.min(Math.max(A.left+W,A.left),j)}n.style.top=`${B}px`,n.style.left=`${oe}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 oe=typeof V.composedPath=="function"?V.composedPath():[];oe.includes(n)||oe.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}}Ze();Pt();Ms();var TP='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',kP=["--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"],hm="data-persona-menu-focus",PP=new Set(["ArrowDown","ArrowUp","Home","End"]);function Yw(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(TP)??e}var LP=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function Xw(e){let t=e.label,n=!1,o=x("div","persona-send-button-wrapper"),r=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${so} ${Do}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=Q("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 J=ge("plus",Qn,"currentColor",1.5);J?r.appendChild(J):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 J=s.getRootNode().activeElement;return J instanceof HTMLElement?J:null},f=()=>{let k=g();for(let J of c){let U=!!k&&Yw(J)===k;J.toggleAttribute(hm,U&&d)}},h=()=>c.filter(k=>k.isConnected||s.contains(k)).map(Yw).filter(k=>!LP(k)),y=(k,J)=>{k.forEach((U,ue)=>{U.setAttribute("tabindex",ue===J?"0":"-1")})},b=k=>{let J=h();if(J.length===0)return;let U=(k%J.length+J.length)%J.length;p=U,y(J,U),J[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,oe=()=>(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 J of c)J.removeAttribute(hm);k&&r.focus()}},X=(k=0,J=!1)=>{if(n||W())return;d=J,tp(r,s,kP),oe().open(),r.setAttribute("aria-expanded","true");let U=h();y(U,-1),b(k<0?U.length-1:k),A=ue=>{let fe=typeof ue.composedPath=="function"?ue.composedPath():[];fe.includes(s)||fe.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):X(0)},T=k=>{if(k.key==="ArrowDown"||k.key==="Enter"||k.key===" "){k.preventDefault(),d=!0,W()?b(0):X(0,!0);return}k.key==="ArrowUp"&&(k.preventDefault(),d=!0,W()?b(-1):X(-1,!0))},_=k=>{switch(PP.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(hm);if(c=[...k],!W())return;let J=h();y(J,Math.min(p,J.length-1)),f()},isOpen:W,open:()=>X(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 sr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Qw="data-persona-composer-action",ym="data-persona-composer-disable-when-streaming",HP="core:overflow",IP=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function RP(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 bm(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 Jw=(e,t)=>{!e||typeof console>"u"||console.warn(t)},WP=(e,t)=>t.includes(":")?t:`${e}:${t}`;function OP(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){Jw(t,`[Persona] composer action "${l.id}" is already contributed by ${Zw(c)}; the ${Zw(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?WP(p,l.id):l.id,g=l.order??sr.custom;l.placement==="end"&&g>=sr.send&&(Jw(t,`[Persona] composer action "${d}" ordered at ${g} would render after send; clamped to ${sr.send-1}.`),g=sr.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 Zw=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",eS=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,_P=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function BP(e,t){if(!e||e==="always")return!0;let n=_P(t);return e==="when-text"?n:!n}var Ls=e=>e.kind==="custom",vm=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,DP=e=>{let t=vm(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},NP='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function FP(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(NP)||o.childNodes.forEach(n)};return n(e),t.trim()}var $P=e=>FP(e).length===0;function tS(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=ge(T.iconName,16,"currentColor",1.5);U&&k.appendChild(U)}let J=x("span","persona-composer-overflow-menu__label");J.textContent=T.shortLabel??T.label,_.append(k,J)},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(ym,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(),J=!!T.shortLabel;if(_.className=Dn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",so,Do,J&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),_.style.width=k&&!J?k:"",_.style.height=k??"",_.style.minWidth=k&&!J?k:"",_.style.minHeight=k??"",_.style.fontSize=J?"":"18px",_.style.lineHeight="1",_.style.color=T.iconColor??"",_.style.backgroundColor=T.backgroundColor??"",_.replaceChildren(),T.iconName){let U=ge(T.iconName,Qn,"currentColor",1.5);U&&_.appendChild(U)}if(J){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=vn({anchor:_,trigger:M.element,text:()=>T.tooltipText??T.label,enabled:!!T.tooltipText})},l=(M,T)=>{let _=M.action,k=Q("button",{attrs:{type:"button"}}),J=k;if(T==="bar"){let fe=x("div","persona-send-button-wrapper");fe.appendChild(k),J=fe}J.setAttribute(Qw,M.id);let U={resolved:M,element:J,button:k,owned:!0,managed:!0,busy:!1,visible:!0,mode:T},ue=fe=>{if(fe.preventDefault(),fe.stopPropagation(),U.busy||k.disabled)return;let me=U.resolved.action;U.mode==="menu"&&h?.close(!0);let He;try{He=me.onSelect(e.actionContext,fe)}catch(Ee){e.reportError(Ee,{actionId:U.resolved.id});return}!He||typeof He.then!="function"||(U.busy=!0,k.setAttribute("aria-busy","true"),He.catch(Ee=>{e.reportError(Ee,{actionId:U.resolved.id})}).finally(()=>{U.busy=!1,k.removeAttribute("aria-busy")}))};return k.addEventListener("click",ue),U.detach=()=>k.removeEventListener("click",ue),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(Qw,M.id),_.element.toggleAttribute(ym,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 _?Ls(_)?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 J=null;for(let U=_+1;U<T.length;U++){let ue=T[U];if(!ue.managed&&ue.element.parentElement===M){J=ue.element;break}}J?(k.element.parentElement!==M||k.element.nextSibling!==J)&&M.insertBefore(k.element,J):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=Xw({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),I=M=>{y!==M&&(b?.disconnect(),y=M,C=bm(M),!(typeof ResizeObserver>"u")&&(b=new ResizeObserver(T=>{let k=T[T.length-1]?.contentRect?.width??bm(M);k!==C&&(C=k,j())}),b.observe(M)))},H=(M,T)=>{let _=RP(M.collapseAutoActionsBelow,T);if(_===null)return!1;let k=C||bm(T);return k>0&&k<_},B=(M,T,_)=>{if(!T)return"bar";if(M.resolved.builtIn){let J=IP(M.resolved.id);return J&&T.includeBuiltIns?.includes(J)?"menu":"bar"}let k=M.resolved.presentation;return k==="overflow"||k==="auto"&&_?"menu":"bar"},V=M=>{let T=M.menuSlot;if(!T)return;if(!$P(M.element)){M.menuLabel?.remove(),M.menuLabel=void 0;return}let _=DP(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)},oe=(M,T)=>{if(M.mode===T)return M;let _=M.resolved.action;if(_&&!Ls(_)){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=Q("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Mf]:""}});k.appendChild(M.element),gC(vm(M.element)),M.menuSlot=k;let J=U=>{let ue=vm(M.element);if(ue.disabled)return;let fe=U.target===ue||ue.contains(U.target);h?.close(!0),fe||ue.click()};k.addEventListener("click",J,!0),M.detachMenuSlot=()=>k.removeEventListener("click",J,!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,J)=>{let U=M.children[J];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 J=k?H(k,M.footer):!1,U={start:[],end:[]},ue=[];for(let fe of n){let me=t.get(fe.id);if(!me)continue;let He=fe.action,Ee=He?eS(He.visible,T,!0)&&BP(He.visibility,T):!0;if(me.visible!==Ee&&(me.visible=Ee,!Ee&&me.managed&&(me.menuSlot??me.element).remove()),!!Ee){if(me=oe(me,B(me,k,J)),He){let Ie=eS(He.disabled,T,!1)||He.disableWhenStreaming===!0&&_;f(me,Ie),!Ls(He)&&He.pressed!==void 0&&me.button?.setAttribute("aria-pressed",He.pressed?"true":"false")}me.mode==="menu"?(V(me),ue.push(me)):U[fe.placement].push(me)}}if(ue.length>0){let fe=L();W(fe.panel,ue),fe.setItems(ue.map(Ie=>Ie.menuSlot??Ie.element)),fe.applyButtonSize();let me=Number.isFinite(k?.order)?k?.order:sr.overflow,He=U.start.findIndex(Ie=>Ie.resolved.order>me),Ee={resolved:{id:HP,placement:"start",presentation:"bar",order:me,sequence:-1,source:"core"},element:fe.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};U.start.splice(He<0?U.start.length:He,0,Ee)}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=OP(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 fe=p(_,"bar");fe&&t.set(_.id,fe);continue}let J=k.resolved.action,U=_.action;if(!!J!=!!U||J&&U&&Ls(J)!==Ls(U)||J&&U&&Ls(J)&&Ls(U)&&J.render!==U.render){d(k),t.delete(_.id);let fe=p(_,k.mode);fe&&t.set(_.id,fe);continue}k.resolved=_,_.builtIn?(k.managed=_.builtIn.managed===!0||k.mode==="menu",_.builtIn.element&&k.mode==="bar"&&(k.element=_.builtIn.element)):U&&!Ls(U)?i(k,U):U&&k.element.toggleAttribute(ym,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=[]}}}}Ze();Pt();Ms();var UP="core:model",VP=700,nS=16,jP=["--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"],oS=()=>{let e=Q("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=Q("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function rS(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=Q("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=Q("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}=oS();return h.append(c,y),{element:h,destroy:()=>{o===d&&(o=null),c.removeEventListener("change",g),c.removeEventListener("click",f)}}},i=()=>{let c=Q("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=Q("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")})),tp(c,g,jP),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 _=Q("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 fe=ge(T.icon,nS,"currentColor",1.5);if(fe){let me=x("span","persona-composer-model-option-icon");me.appendChild(fe),_.appendChild(me)}}let k=x("span","persona-composer-model-option-body"),J=x("span","persona-composer-model-option-label");if(J.textContent=T.label,k.appendChild(J),T.description){let fe=x("span","persona-composer-model-option-description");fe.textContent=T.description,k.appendChild(fe)}_.appendChild(k);let U=x("span","persona-composer-model-option-check");U.setAttribute("aria-hidden","true");let ue=ge("check",nS,"currentColor",2);return ue&&U.appendChild(ue),_.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 ue=B(U);return f.set(U.id,ue),ue}))}let k=r(T);for(let[U,ue]of f)ue.setAttribute("aria-selected",String(U===k?.id));p.textContent=k?.label??"";let J=e.getSuffix?.()??"";d.textContent=J,c.setAttribute("aria-label",[t,[k?.label,J].filter(Boolean).join(" ")].filter(Boolean).join(": "))};V(),o=V;let oe=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",oe),c.addEventListener("keydown",W),g.addEventListener("keydown",j);let{wrapper:X,chevron:M}=oS();return X.append(c,M),{element:X,destroy:()=>{o===V&&(o=null),c.removeEventListener("click",oe),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:UP,kind:"custom",placement:"end",order:VP,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?i():s()},repaint:()=>o?.()}}Ze();Pt();Ze();var Cm="[data-persona-composer-chip-row]";function _p(e){e.style.display=e.childElementCount>0?"flex":"none"}function wm(e){let t=e.querySelector(Cm);if(t)return t;let n=Q("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 qP=":scope > [data-persona-composer-mode]";function sS(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=p=>{let d=Q("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=ge(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=Q("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=ge("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(qP)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let d=()=>{p.remove(),_p(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}_p(t)},destroy:()=>{o=!0,c(),_p(t)}}}Ze();Pt();var iS=e=>`core:mode:${e}`;var Sm=e=>Math.min(300+e,499),aS=e=>`core:mode-group:${e}`;function Bp(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function zP(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function lS(e,t){return e?.length?e.filter(n=>!Bp(n.groupId,t)&&!zP(n.groupId,t)):[]}var KP=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function cS(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(KP(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 Dp(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function dS(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function pS(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var GP=16;function uS(e){let t=null;return{action:{id:aS(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=Q("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=Q("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let f=ge(p.iconName,GP,"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?.()}}Ze();Pt();function gS(e){let t=Q("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=Q("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=Hp(s.text),l.appendChild(c);let p=Q("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),d=ge("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()}}}Ze();Pt();function fS(e){let t=Q("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=Q("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),g=ge(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=Hp(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=Q("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()}}}Ze();function mS(e){let t=Q("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=Q("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=Q("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 hS(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 yS(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 bS(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 vS(e){return e.wrapped||e.text.includes(`
29
- `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function CS(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function wS(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 SS(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}ep();function Am(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 xS(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var YP=e=>typeof e?.then=="function";function AS(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 ES(e,t,n){let o;try{o=e(Am(t),{signal:n})}catch(r){return{status:"error",error:r}}return YP(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:AS(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):AS(t,o)}jf();qf();Vf();Nr();var Np=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?"circle":"pill"),Fp={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"};So();So();var Up="16px",Vp="transparent",XP=(()=>{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})(),Kl={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:XP,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"}},$p={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"}},io={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:vi,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Up,canvasBackground:Vp,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"}}},QP=Kl.colors.gray,JP={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},TS={...Kl,colors:{...Kl.colors,gray:QP}},ZP={...Kl,colors:{...Kl.colors,gray:JP},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}},kS=TS,PS=$p,e0={...$p,colors:{...$p.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...$p.typography,fontSize:"14px",lineHeight:"1.5"}},LS=PS,jp=io,t0={...io,launcher:Fp,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:{...io.input,borderRadius:"palette.radius.full"},introCard:{...io.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...io.suggestion.chip,fontWeight:"400"},card:{...io.suggestion.card,fontWeight:"400"},list:{...io.suggestion.list,fontWeight:"400"}},panel:{...io.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...io.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:{...io.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...io.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:{...io.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...io.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)"}},HS=jp,n0=e=>Es({future:e}),Em=e=>n0(e)==="v5"?{palette:ZP,semantic:e0,components:t0}:{palette:TS,semantic:PS,components:jp};function wn(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."))?wn(e,o):o}function qp(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=wn(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 Mm(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 IS(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]=IS(s,r):n[o]=r}return n}function o0(e,t){return t?IS(e,t):e}function Gl(e,t={}){let n=Em(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:o0(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=Mm(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 xm=e=>e.trim()==="0"?"0px":e,MS="--persona-",r0=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},s0=.179,Cn=(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[MS+s],r!==void 0)break;r!==void 0&&(e[MS+n]=r)}};function zp(e){let t=qp(e),n={};for(let[$,_e]of Object.entries(t)){let ye=$.replace(/\./g,"-");n[`--persona-${ye}`]=_e.value}Cn(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"],Cn(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"]]),Cn(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"]}`,Cn(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"]??Up,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Vp,Cn(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"]]),Cn(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"],Cn(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"],Cn(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[$,_e]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let ye=n[`--persona-components-history-overlay-${$}`];ye&&(n[`--persona-history-overlay-${_e}`]=ye)}for(let[$,_e]of[["background","bg"],["borderRadius","radius"]]){let ye=n[`--persona-components-history-menu-${$}`];ye&&(n[`--persona-history-menu-${_e}`]=ye)}let g=e.components?.history?.motion;if(g){let $=ut=>{if(ut===void 0)return;let Zt=String(ut).trim();return/^\d+(\.\d+)?$/.test(Zt)?`${Zt}ms`:Zt},_e=$(g.enterDurationMs);_e!==void 0&&(n["--persona-history-enter-ms"]=_e);let ye=$(g.exitDurationMs);ye!==void 0&&(n["--persona-history-exit-ms"]=ye),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 _e=n[`--persona-components-history-confirm-${$}`];_e&&(n[`--persona-history-confirm-${$}`]=_e)}for(let[$,_e]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let ye=n[`--persona-components-tooltip-${$}`];ye&&(n[`--persona-tooltip-${_e}`]=ye)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[$,_e]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let ye=n[`--persona-components-messageActions-${$}`];ye&&(n[`--persona-message-action-${_e}`]=ye)}Cn(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,Cn(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"]]),Cn(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),Cn(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"]]),Cn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Cn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Cn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Cn(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[$,_e]of V){let ye=n[`--persona-components-collapsibleWidget-${$}`]??n[`--persona-${_e}`];ye!==void 0&&(n[`--persona-cw-${$}`]=ye,n[`--cw-${$}`]=ye)}Cn(n,[["message-border","components-message-border","border"]]),Cn(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 oe=e.components,W=oe?.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=oe?.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 X=oe?.toggleGroup;X&&(X.gap&&(n["--persona-toggle-group-gap"]=X.gap),X.borderRadius&&(n["--persona-toggle-group-radius"]=X.borderRadius));let M=oe?.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"]=xm($.toggleGroupGap)),$.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=$.toggleBorderRadius),$.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=xm($.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"]=wn(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"]=xm($.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 _e=wn(e,$.toolbarBackground)??$.toolbarBackground;n["--persona-artifact-toolbar-bg"]=_e}}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"]=wn(e,$.background)??$.background),$.border&&(n["--persona-artifact-inline-border"]=$.border),$.borderRadius&&(n["--persona-artifact-inline-radius"]=$.borderRadius),$.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=wn(e,$.chromeBackground)??$.chromeBackground),$.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=wn(e,$.chromeBorder)??$.chromeBorder),$.titleColor&&(n["--persona-artifact-inline-title-color"]=wn(e,$.titleColor)??$.titleColor),$.mutedColor&&(n["--persona-artifact-inline-muted-color"]=wn(e,$.mutedColor)??$.mutedColor),$.frameHeight&&(n["--persona-artifact-inline-frame-height"]=$.frameHeight)}let T=oe?.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"]=wn(e,T.background)??T.background));let _=n["--persona-surface"],k=n["--persona-container"],J=n["--persona-palette-colors-gray-100"]??"#f3f4f6",U=n["--persona-palette-colors-gray-200"]??"#e5e7eb",ue=n["--persona-palette-colors-gray-300"]??"#d1d5db",fe=!k||k===_,me=r0(_??n["--persona-background"]),He=fe&&me!==void 0&&me<s0,Ee=He?"rgba(255, 255, 255, 0.08)":J,Ie=He?"rgba(255, 255, 255, 0.12)":U,yt=He?"rgba(255, 255, 255, 0.16)":ue,qe=fe?Ee:k,Oe=fe?Ie:k;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??qe,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Oe,fe&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??yt),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??qe,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??qe,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??qe,n}var RS={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"};qd();var i0=e=>!!e&&"launcher"in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode==="docked"),WS=(e,t)=>{if(!t||!i0(t))return e;let n=t.theme?.components?.panel?.width,o=t.darkTheme?.components?.panel?.width;return(xi(t)==="dark"?o??n:n)!=null?e:{...e,components:{...e.components,panel:{...e.components.panel,width:Es(t)==="v5"?"400px":"420px"}}}},a0={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"}}},Yl={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)"}}}},Tm=a0,l0={...Tm,colors:{...Tm.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"}}},c0=Yl,d0={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:{...Yl.components,button:{...Yl.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:{...Yl.components?.eventStream,badge:{...Yl.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"}}}}},p0=e=>Es({future:e})==="v5"?{palette:l0,components:d0}:{palette:Tm,components:c0},OS=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Xl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",u0=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Xl()},xi=e=>u0(e),g0=(e,t={})=>Gl(e,t),f0=(e,t={})=>{let n=p0(t.future),o=Bo(n.components,e??{})??{};return Gl({...o,palette:{...o.palette,colors:Es(t)==="v5"?Bo(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})},No=e=>{let t=xi(e),n=OS(e?.theme),o=Np(e)==="circle"?Fp:{...jp.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=Bo({components:{launcher:o}},n),s=OS(e?.darkTheme);return WS(t==="dark"?f0(Bo(r??{},s??{}),{future:e?.future}):g0(r,{future:e?.future}),e)},m0=e=>zp(e),Ei=(e,t)=>{let n=No(t),o=m0(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",xi(t)),e.setAttribute("data-persona-defaults",Es(t))},Oa=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Xl())});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(Xl());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())}};qd();var Kr=require("lucide");Pt();Lr();Ze();var Hs=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Kp="24px",km=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",Ql=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},_S=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);xa();Ud();yp();var BS=require("idiomorph"),Gp=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;BS.Idiomorph.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 DS=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Pm={index:-1,draft:""};function NS(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 FS(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 $S(){return new Map}function US(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function VS(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function jS(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function qS(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 zS(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function ir(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Mi(e,t){return ir(e)-e.scrollTop<=t}function KS(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 GS(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 YS(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Lm(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 XS(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}_o();var Jl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},h0=["pre","code","a","script","style"],Yp=e=>({type:e?.type??Jl.type,placeholder:e?.placeholder??Jl.placeholder,speed:e?.speed??Jl.speed,duration:e?.duration??Jl.duration,buffer:e?.buffer??Jl.buffer}),JS=[{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"}],Zl=new Map;for(let e of JS)Zl.set(e.name,e);var ZS=["wipe","glyph-cycle"],ec=e=>{Zl.set(e.name,e)},eA=e=>{JS.some(t=>t.name===e)||Zl.delete(e)},tA=()=>Array.from(Zl.keys()),tc=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Zl.get(e)??null,Xp=(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},y0=(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},b0=(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},Hm=/\s/,v0=(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},C0=(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(Hm.test(s[l])){let c=l;for(;c<s.length&&Hm.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&&!Hm.test(s[p]);)c.appendChild(y0(o,s[p],t,n.value)),n.value+=1,p+=1;i.appendChild(c),l=p}r.replaceChild(i,e)},w0=(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(b0(o,c,t,n.value)),n.value+=1));r.replaceChild(i,e)},nc=(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??h0).map(g=>g.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],c=i.nextNode();for(;c;)v0(c,s)||l.push(c),c=i.nextNode();let p={value:o?.startIndex??0},d=t==="char"?C0:w0;for(let g of l)d(g,n,p);return r.innerHTML},Qp=(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},oc=(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},QS=new WeakMap,S0=(e,t)=>{if(!e.styles)return;let n=QS.get(t);if(n||(n=new Set,QS.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)},Im=new WeakMap,A0=(e,t)=>{if(!e.onAttach)return;let n=Im.get(t);if(n||(n=new Map,Im.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},nA=e=>{let t=Im.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},rc=(e,t)=>{S0(e,t),A0(e,t)};dn();var{setLoader:jB,load:x0}=lt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var oA=x0;_o();function Rm(e,t=Pn){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 sc=0,Is=null;function Wm(e=document){if(sc++,sc===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Is={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,sc=Math.max(0,sc-1),sc===0&&Is)){let n=e.body,o=e.defaultView??window;n.style.overflow=Is.originalOverflow,n.style.position=Is.originalPosition,n.style.top=Is.originalTop,n.style.width=Is.originalWidth,o.scrollTo(0,Is.scrollY),Is=null}}}Ea();var ic={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Lt=e=>(e?.launcher?.mountMode??"floating")==="docked",Rs=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Zn=e=>{let t=e?.launcher?.dock,n=_r(e).dockWidth?t?.width:wn(No(e),"components.panel.width");return{side:t?.side??ic.side,width:n??ic.width,animate:t?.animate??ic.animate,reveal:t?.reveal??ic.reveal,maxHeight:t?.maxHeight??ic.maxHeight}};Ze();Ze();var sA=require("lucide");Pt();Lr();var Om=e=>e==="followUp"?"follow-up":e,_m=(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"}},rA=new WeakSet,E0=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,M0=e=>{E0()||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"})})},Bm=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=ge(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(Q("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&H.appendChild(Q("span",{className:"persona-suggestion__description",text:t.description})),I.appendChild(H),s!=="chip"){let B=Nt(sA.ArrowRight,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},ac=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??{},oe=b?.plugins??[],W=typeof b?.maxItems=="number"?Math.max(0,Math.floor(b.maxItems)):void 0,j=L?"followUps":"starters";!rA.has(V)&&V.debug===!0&&I!=="chip"&&V.suggestions?.[j]?.overflow!==void 0&&(rA.add(V),console.info(`[persona] suggestions.${j}.overflow applies to the "chip" variant only; the "${I}" variant manages its own stacking.`));let X=U=>U.map(_m).filter(ue=>ue!==null).map(ue=>({...ue,behavior:ue.behavior??H})),M=X(d??[]);oe.forEach(U=>{U.transformSuggestions&&(M=X(U.transformSuggestions({suggestions:M.map(ue=>({...ue})),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(ue=>ue.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,ue)=>{let fe=Bm({item:U,index:ue,surface:A,source:C,variant:I,streaming:k,config:V,plugins:oe,chipsConfig:y,session:g,getTextarea:()=>f,eventTarget:e,submitPrompt:b?.submitPrompt});_.appendChild(fe),n.push(fe),[...fe instanceof HTMLButtonElement?[fe]:[],...Array.from(fe.querySelectorAll("button"))].forEach(He=>{t.includes(He)||(He.disabled=k,t.push(He))})}),e.appendChild(_),i(),l();let J=JSON.stringify({normalized:T,surface:A,variant:I,source:C});J!==o&&(o=J,M0(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 ao={"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"};_o();Ze();Pt();So();Ze();Pt();xa();var T0="persona-header-control",k0="persona-header-control--glyph",P0="persona-header-control--sparse",L0=20,H0={x:[1.4,1.05]},iA="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",I0="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Jp=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,i]=H0[t]??[1,1.5],l=!o;e.classList.toggle(k0,l),e.classList.toggle(P0,l&&s!==1);let c=parseFloat(o??"")||L0,p=ge(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)},_a=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:i=iA,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=Q("button",{className:Dn(T0,"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||Nn.actionIconColor,backgroundColor:d,border:H?`${g||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:h,paddingLeft:y,paddingRight:y,paddingTop:b,paddingBottom:b}});return r?Jp(B,r,{iconSize:c,iconText:s}):s&&(B.textContent=s),I.appendChild(B),vn({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=iA,buttonSize:r,iconSize:s}=t,i=e?.launcher??{},l=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:p,wrapper:d}=_a({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}},Da=(e,t={})=>{let{wrapperClassName:n=I0,buttonSize:o,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},l=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:p,wrapper:d}=_a({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 Nn={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)"},Dm={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)"},R0={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)"},jr=e=>{let{config:t,showClose:n=!0}=e,o=Q("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:Nn.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??_l,i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,c=r.headerIconName,p=Q("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=ge(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=Q("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Nn.titleColor,...Dm}}),f=Q("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Nn.subtitleColor,...R0}});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=Da(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}},Ti=(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))};Ze();Ze();Pt();_o();function ki(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(wa)):(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=ge(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}}Ze();Pt();function eo(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:i,onClick:l,aria:c}=e,p=x("button",Dn(!i&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ge(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 Nm(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=ge(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 lc(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=eo({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 aA(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?eo({...C,icon:n,size:o??14}):Nm({...C,icon:n,iconSize:o??14}),L=eo({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=ki({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 Zp(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=ge(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=ki({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()}}}yp();var Fm=e=>{let t=jr({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 W0(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=_a({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?hp(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=Nl(o.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(o.menuItems?.length){let i=ki({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 $m=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=Nn.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=Zp({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}}))},oe=c.onSelect(B);oe instanceof Promise?oe.then(V,()=>{}):V(oe)},hover:c.hover,className:""});p=H.element,p.style.color=Nn.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=Nn.titleColor,Object.assign(d.style,Dm),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||W0(y,r?.trailingActions,r?.onAction??s);let b=i.clearChat??{},C=null,A=null;if(b.enabled??!0){let H=b.placement??"inline",B=Da(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}},eu={default:Fm,minimal:$m},Um=e=>eu[e]??eu.default,Na=(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=Um(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};Ze();Ms();var Pi=e=>{let{config:t}=e,n=Q("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=ip(),r=Q("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}=np(t);i();let l=op(t),c=Pa(t),p=rp(t),d=sp(t),g=Q("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=Q("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=Q("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),y=Q("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}};Ze();var tu=require("lucide");Lr();Ms();ep();var lA=()=>{let e=Q("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=Nt(tu.MessageSquare,16,"currentColor",1.5);n&&t.appendChild(n);let o=x("span","persona-pill-peek__text"),r=x("span","persona-pill-peek__caret"),s=Nt(tu.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},nu=e=>{let{config:t}=e,n=Q("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ip(),r=sp(t);r.style.display="none";let{textarea:s,attachAutoResize:i}=np(t,{defaultMaxLines:5});i();let l=op(t),c=Pa(t),p=rp(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let d=Q("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),g=Q("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&g.append(p.wrapper);let f=Q("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=Q("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}};Ze();Pt();Ze();zf();Pt();Nr();var O0=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}},_0=(e,t)=>{if(!e)return null;let n=O0(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},B0=(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},D0=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},jm=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(":"))},qm=320,gA=320,N0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),F0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),$0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),U0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),V0=e=>{if(!e||e.length===0)return null;let t=Q("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Q("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=x("span","persona-mention-chip-icon"),s=ge(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Q("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},j0=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Dl(o.ref,{readonly:!0,render:t}))}return n},cA="\uE000",dA="\uE001",q0=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=f=>`${cA}${r}:${f}${dA}`,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(j0(t,o));return}e.innerHTML=l;let p=new RegExp(`${cA}${r}:(\\d+)${dA}`),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(Dl(b.ref,{readonly:!0,render:o}),C),h=C}}},z0=(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=`${qm}px`,p.style.maxHeight=`${gA}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}),D0(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}},K0=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(!jm(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=`${qm}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},G0=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(!jm(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=`${qm}px`,r.style.maxHeight=`${gA}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}},Y0=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(!jm(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}},Li=()=>{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},zm=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Li};if(t){let r=t(o);if(r!==null)return r}return Li()},X0=(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},pA=(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},cc=(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},uA={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"}},Q0=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=uA[n??"bubble"]??uA.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)`)},ou="custom:",J0=e=>`${ou}${e}`,fA=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),Km=(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=fA(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=eo({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,J0(I.id)));return A},Fa=(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=cc(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=Em(s?.widgetConfig?.future).components.message,A=s?.widgetConfig?.theme?.components?.message;Q0(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=N0(e),I=e.content?.trim()??"",B=L.length>0&&I===Ta,V=Yp(s?.widgetConfig?.features?.streamAnimation),oe=s?.widgetConfig?.features?.streamAnimation?.plugins,W=e.role==="assistant"&&V.type!=="none"?tc(V.type,oe):null,j=e.role==="assistant"&&W?.isAnimating?.(e)===!0,X=e.role==="assistant"&&W!==null&&(!!e.streaming||j);X&&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"),X&&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=X?Xp(e.content??"",V.buffer,W,e,!!e.streaming):e.content??"",_=()=>{let Oe=t({text:T,message:e,streaming:!!e.streaming,raw:e.rawContent});return X&&W?.wrap==="char"?nc(Oe,"char",e.id,{skipTags:W.skipTags}):X&&W?.wrap==="word"?nc(Oe,"word",e.id,{skipTags:W.skipTags}):Oe},k=null;if(B?(k=document.createElement("div"),k.innerHTML=_(),k.style.display="none",M.appendChild(k)):e.contentSegments?.length?q0(M,e.contentSegments,Oe=>t({text:Oe,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):M.innerHTML=_(),X&&W?.useCaret&&!B&&I){let Oe=Qp(),$=M.querySelectorAll(".persona-stream-char, .persona-stream-word"),_e=$[$.length-1];if(_e?.parentNode)_e.parentNode.insertBefore(Oe,_e.nextSibling);else{let ye=M.lastElementChild;ye?ye.appendChild(Oe):M.appendChild(Oe)}}if(g&&h==="inline"&&e.createdAt){let Oe=pA(e,p,"span");Oe.classList.add("persona-timestamp-inline");let $=M.lastElementChild;$?$.appendChild(Oe):M.appendChild(Oe)}if(L.length>0){let Oe=z0(L,!B&&!!I,()=>{B&&k&&(k.style.display="")});Oe?b.appendChild(Oe):B&&k&&(k.style.display="")}let J=F0(e);if(J.length>0){let Oe=K0(J);Oe&&b.appendChild(Oe)}let U=$0(e);if(U.length>0){let Oe=G0(U);Oe&&b.appendChild(Oe)}let ue=U0(e);if(ue.length>0){let Oe=Y0(ue);Oe&&b.appendChild(Oe)}let fe=e.contentSegments?.length?null:V0(e.contextMentions);if(fe&&b.appendChild(fe),b.appendChild(M),g&&h==="below"&&e.createdAt){let Oe=pA(e,p);Oe.classList.add("persona-mt-1"),b.appendChild(Oe)}let me=e.role==="assistant"?_0(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Oe=!!(T&&T.trim()),$=V.placeholder==="skeleton",_e=$&&V.buffer==="line"&&Oe;if(Oe)_e&&b.appendChild(oc());else if($)b.appendChild(oc());else{let ye=zm("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ye&&b.appendChild(ye)}}me&&e.stopReason&&!e.streaming&&(I||(M.style.display="none"),b.appendChild(B0(e.stopReason,me)));let He=e.role==="assistant"&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&o?.enabled!==!1,Ee=s?.actionEligibility,Ie=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Ee?.canEdit===!0||o?.showQuote===!0&&Ee?.canQuote===!0||fA(o,"user").length>0);if((He||Ie)&&o){let Oe=Km(e,Ie?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,Ee);b.appendChild(Oe)}if(!d||e.role==="system")return b;let yt=x("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),qe=X0(c,e.role);return f==="right"||f==="left"&&e.role==="user"?yt.append(b,qe):yt.append(qe,b),yt},mA=(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}):Fa(e,t,n,o,r,s)};var Z0=40,eL=(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=ge(t.name,Z0);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(Q("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Q("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},hA=(e,t,n={})=>{let o=Q("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=Q("div",{className:"persona-welcome-head-text"},r,s),c=Q("div",{className:"persona-welcome-title-row"},o,l);return{host:Q("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}},$a=(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)},su=(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==="",eL(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")},tL="data-persona-welcome-plugin",yA="data-persona-welcome-overlay",ru="persona-welcome-overlay-active",Gm=new WeakMap,Ym=(e,t,n)=>{n.setAttribute(tL,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(yA,""),e.classList.contains(ru)||(Gm.set(e,e.scrollTop),e.classList.add(ru),e.scrollTop=0)},Xm=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(yA),e.classList.contains(ru)&&(e.classList.remove(ru),e.scrollTop=Gm.get(e)??e.scrollTop,Gm.delete(e))},bA=()=>{let e=Q("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},iu=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=Q("div",{className:cc("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(Q("div",{className:"persona-flex"},r)),e.hidden=!1},vA=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,CA=(e,t)=>{if(vA()||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},wA=(e,t,n,o=260)=>{if(t<=1||vA()||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 nL="Hello \u{1F44B}",oL="I can answer questions and help you get things done here.",SA=new WeakSet,Fn=(e,t)=>!!e&&e[t]!==void 0,rL=(e,t)=>{!e||e.debug!==!0||!t.length||SA.has(e)||(SA.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Ua=(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=Fn(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=i==="hero"&&!r&&n?.layout===void 0?"on-first-message":Fn(n,"dismiss")?n.dismiss:r||i==="hero"?"on-first-message":"never",c=[];Fn(n,"title")&&Fn(o,"welcomeTitle")&&c.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Fn(n,"subtitle")&&Fn(o,"welcomeSubtitle")&&c.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Fn(n,"variant")&&Fn(o,"showWelcomeCard")&&c.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),i==="hero"&&Fn(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"&&Fn(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=Ql(n?.anchorComposerTop)!==null;return Fn(n,"anchorComposerTop")&&!d&&c.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&(Fn(n,"anchorComposerTop")||Fn(n,"composerGap"))&&c.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),rL(e,c),{title:Fn(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":nL),kicker:n?.kicker??"",subtitle:Fn(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":oL),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()||Kp}},AA=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Ws=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");Ea();var sL="var(--persona-components-panel-maxWidth)",xA="var(--persona-components-panel-height)",iL="var(--persona-components-panel-maxHeight)",Hi=e=>{let t=_r(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0,r=o===0?`max(200px, ${xA})`:`max(200px, calc(${xA} - ${o}px))`;return{width:n??CC,maxWidth:n??sL,height:r,maxHeight:iL}},EA="16px",Jm="10px",Zm="14px",MA=e=>{let t=e?.launcher?.enabled??!0,n=Lt(e);if(Rs(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??Pn);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??Pn),{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=_r(e),h=g.launcherWidth||g.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?Hi(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&&ao[r.position]?ao[r.position]:ao["bottom-right"],i=x("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??Pn);let l=x("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=Hi(e);return l.style.width=c.width,l.style.maxWidth=c.maxWidth,i.appendChild(l),{wrapper:i,panel:l}},eh=e=>{let t=Q("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Om(e)}});return t.hidden=!0,t},TA=(e,t)=>{let n=eh("starter"),o=hA(e,n,{flatShadow:Lt(e)}),r=Ua(e);su(o,r),$a(t,o.host,Ws(r,e?.initialMessages));let s=bA();return iu(s,r.message,e),{welcome:o,greetingHost:s}},aL=(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:EA,iconSize:Jm});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 oe=Da(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:EA,iconSize:Zm});i=oe.button,l=oe.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let c=Q("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=Q("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}=TA(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=eh("followUp"),L=Hs(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=Q("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=nu({config:e}),{root:B,textNode:V}=lA();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}},kA=(e,t=!0)=>{if(Rs(e))return aL(e,t);let n=Q("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?Na(e,o,{showClose:t}):jr({config:e,showClose:t}),i=Q("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}=TA(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=eh("followUp"),b=Hs(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=Pi({config:e}),A=e?.layout?.showFooter!==!1;r?Ti(n,s,e):(s.header.style.display="none",Ti(n,s,e)),n.append(i);let L=Q("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}};Ms();Ze();Pt();_o();var th=(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(Ao(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(c){let p=[];i&&p.push(Ao(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??Ha(),c=Ps();this.#s=null;let p=n?.contentParts&&Pa(n.contentParts)?Ta:"",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=Rw({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=mm(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=Ww(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=Ps();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=mm(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;#Pe(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=jC();if(o)return t(o,n);let r=this.#de;return Qf().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.#Pe((r,s)=>r.resolveApproval(s,t,n,o))}resolveAskUserQuestion(t,n){return this.#Pe((o,r)=>o.resolveAskUserQuestion(r,t,n))}resolveWebMcpToolCall(t){return this.#Pe((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.#Pe((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=or(this.config.features?.artifacts,t),r=Ml(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=or(this.config.features?.artifacts,n),s=Ml(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=Vw().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.#ke(),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=>mm(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=Ps(),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.#ke()}#ke(){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=um(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(t){return Ia(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=um(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&&jw(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&&jw(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)})}};Ze();var xo=require("lucide");Lr();kt();Nr();var Sk={add:e=>IC(e)},Ak=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Wp={allowedTypes:Dr,maxFileSize:10*1024*1024,maxFiles:4};function xk(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ek(e){return e==="application/pdf"?xo.FileText:e.startsWith("text/")?xo.FileText:e.includes("word")?xo.FileText:e.includes("excel")||e.includes("spreadsheet")?xo.FileSpreadsheet:e==="application/json"?xo.FileCode:xo.File}var Ai=class e{constructor(t={}){this.attachments=[];this.#e=null;this.#n=new Map;this.#o=!1;this.config={allowedTypes:t.allowedTypes??Wp.allowedTypes,maxFileSize:t.maxFileSize??Wp.maxFileSize,maxFiles:t.maxFiles??Wp.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:Sk}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:Wp.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=RC(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:xk(),file:o,previewUrl:Xd(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=Ak(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=Xd(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=Ek(t.file.type),f=Nt(g,20,"var(--persona-muted, #6b7280)",1.5);f&&d.appendChild(f);let h=x("span");h.textContent=WC(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=Q("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=Q("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=ge("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=Nt(xo.X,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 qw=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),Mk=(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 zw(){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=>{Mk(e.attachments,d)||(e.attachments=[...d],p())},setMentionRefs:d=>{qw(e.mentionRefs,d)||(e.mentionRefs=[...d],p())},setSelectedModelId:d=>{e.selectedModelId!==d&&(e.selectedModelId=d,p())},setActiveModeIds:d=>{qw(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()}}}Ze();var Jn=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},Kw=(e,t)=>{let n=x("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function Gw(e,t={}){let n=Jn(e,"[data-persona-composer-form]"),o=Jn(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:Jn(e,"[data-persona-composer-header]"),body:Jn(e,"[data-persona-composer-body]"),actionsStart:Jn(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Jn(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Jn(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Jn(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Jn(e,"[data-persona-composer-status]")},s=new Set,i=r.header;i||(s.add("header"),i=Kw("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=Kw(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=Jn(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:Jn(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Jn(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Jn(e,"[data-persona-composer-submit]")??void 0,micButton:Jn(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=[]}}}Ze();kt();xa();Ms();function Tk(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??Tk(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,oe=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);oe=Math.min(Math.max(A.left+W,A.left),j)}n.style.top=`${B}px`,n.style.left=`${oe}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 oe=typeof V.composedPath=="function"?V.composedPath():[];oe.includes(n)||oe.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}}Ze();kt();Ms();var Pk='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',kk=["--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"],hm="data-persona-menu-focus",Lk=new Set(["ArrowDown","ArrowUp","Home","End"]);function Yw(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(Pk)??e}var Hk=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function Xw(e){let t=e.label,n=!1,o=x("div","persona-send-button-wrapper"),r=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${so} ${Do}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=Q("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 J=ge("plus",Qn,"currentColor",1.5);J?r.appendChild(J):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 J=s.getRootNode().activeElement;return J instanceof HTMLElement?J:null},f=()=>{let P=g();for(let J of c){let U=!!P&&Yw(J)===P;J.toggleAttribute(hm,U&&d)}},h=()=>c.filter(P=>P.isConnected||s.contains(P)).map(Yw).filter(P=>!Hk(P)),y=(P,J)=>{P.forEach((U,ue)=>{U.setAttribute("tabindex",ue===J?"0":"-1")})},b=P=>{let J=h();if(J.length===0)return;let U=(P%J.length+J.length)%J.length;p=U,y(J,U),J[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,oe=()=>(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=(P=!1)=>{if(W()){V?.close(),r.setAttribute("aria-expanded","false"),H(),B(),p=-1,d=!1;for(let J of c)J.removeAttribute(hm);P&&r.focus()}},X=(P=0,J=!1)=>{if(n||W())return;d=J,tp(r,s,kk),oe().open(),r.setAttribute("aria-expanded","true");let U=h();y(U,-1),b(P<0?U.length-1:P),A=ue=>{let fe=typeof ue.composedPath=="function"?ue.composedPath():[];fe.includes(s)||fe.includes(o)||j()},C().addEventListener("focusin",A,!0),L=()=>f(),s.addEventListener("focusin",L),I=()=>{d=!1},s.addEventListener("pointerdown",I,!0)},M=P=>{P.preventDefault(),P.stopPropagation(),W()?j(!0):X(0)},T=P=>{if(P.key==="ArrowDown"||P.key==="Enter"||P.key===" "){P.preventDefault(),d=!0,W()?b(0):X(0,!0);return}P.key==="ArrowUp"&&(P.preventDefault(),d=!0,W()?b(-1):X(-1,!0))},_=P=>{switch(Lk.has(P.key)&&(d=!0),P.key){case"ArrowDown":P.preventDefault(),b(p+1);return;case"ArrowUp":P.preventDefault(),b(p-1);return;case"Home":P.preventDefault(),b(0);return;case"End":P.preventDefault(),b(h().length-1);return;case"Escape":P.preventDefault(),P.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:P=>{for(let U of c)P.includes(U)||U.removeAttribute(hm);if(c=[...P],!W())return;let J=h();y(J,Math.min(p,J.length-1)),f()},isOpen:W,open:()=>X(0),close:j,setLabel:P=>{P!==t&&(t=P,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 sr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Qw="data-persona-composer-action",ym="data-persona-composer-disable-when-streaming",Ik="core:overflow",Rk=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function Wk(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 bm(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 Jw=(e,t)=>{!e||typeof console>"u"||console.warn(t)},Ok=(e,t)=>t.includes(":")?t:`${e}:${t}`;function _k(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){Jw(t,`[Persona] composer action "${l.id}" is already contributed by ${Zw(c)}; the ${Zw(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?Ok(p,l.id):l.id,g=l.order??sr.custom;l.placement==="end"&&g>=sr.send&&(Jw(t,`[Persona] composer action "${d}" ordered at ${g} would render after send; clamped to ${sr.send-1}.`),g=sr.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 Zw=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",eS=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,Bk=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function Dk(e,t){if(!e||e==="always")return!0;let n=Bk(t);return e==="when-text"?n:!n}var Ls=e=>e.kind==="custom",vm=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,Nk=e=>{let t=vm(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},Fk='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function $k(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(Fk)||o.childNodes.forEach(n)};return n(e),t.trim()}var Uk=e=>$k(e).length===0;function tS(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 P=x("span","persona-composer-overflow-menu__icon");if(T.iconName){let U=ge(T.iconName,16,"currentColor",1.5);U&&P.appendChild(U)}let J=x("span","persona-composer-overflow-menu__label");J.textContent=T.shortLabel??T.label,_.append(P,J)},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(ym,T.disableWhenStreaming===!0),M.mode==="menu"){M.tooltip?.destroy(),M.tooltip=void 0,s(M,T);return}_.removeAttribute("role"),_.removeAttribute("tabindex"),_.removeAttribute("title");let P=r(),J=!!T.shortLabel;if(_.className=Dn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",so,Do,J&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),_.style.width=P&&!J?P:"",_.style.height=P??"",_.style.minWidth=P&&!J?P:"",_.style.minHeight=P??"",_.style.fontSize=J?"":"18px",_.style.lineHeight="1",_.style.color=T.iconColor??"",_.style.backgroundColor=T.backgroundColor??"",_.replaceChildren(),T.iconName){let U=ge(T.iconName,Qn,"currentColor",1.5);U&&_.appendChild(U)}if(J){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=vn({anchor:_,trigger:M.element,text:()=>T.tooltipText??T.label,enabled:!!T.tooltipText})},l=(M,T)=>{let _=M.action,P=Q("button",{attrs:{type:"button"}}),J=P;if(T==="bar"){let fe=x("div","persona-send-button-wrapper");fe.appendChild(P),J=fe}J.setAttribute(Qw,M.id);let U={resolved:M,element:J,button:P,owned:!0,managed:!0,busy:!1,visible:!0,mode:T},ue=fe=>{if(fe.preventDefault(),fe.stopPropagation(),U.busy||P.disabled)return;let me=U.resolved.action;U.mode==="menu"&&h?.close(!0);let He;try{He=me.onSelect(e.actionContext,fe)}catch(Ee){e.reportError(Ee,{actionId:U.resolved.id});return}!He||typeof He.then!="function"||(U.busy=!0,P.setAttribute("aria-busy","true"),He.catch(Ee=>{e.reportError(Ee,{actionId:U.resolved.id})}).finally(()=>{U.busy=!1,P.removeAttribute("aria-busy")}))};return P.addEventListener("click",ue),U.detach=()=>P.removeEventListener("click",ue),i(U,_),U},c=M=>{let T=M.action,_;try{_=T.render({...e.actionContext,id:M.id,action:T})}catch(P){return e.reportError(P,{actionId:M.id}),null}return _?.element?(_.element.setAttribute(Qw,M.id),_.element.toggleAttribute(ym,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 P=M.builtIn.element;return P?{resolved:M,element:P,owned:!1,managed:M.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let _=M.action;return _?Ls(_)?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 P=T[_];if(!P.managed)continue;let J=null;for(let U=_+1;U<T.length;U++){let ue=T[U];if(!ue.managed&&ue.element.parentElement===M){J=ue.element;break}}J?(P.element.parentElement!==M||P.element.nextSibling!==J)&&M.insertBefore(P.element,J):M.lastChild!==P.element&&M.appendChild(P.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 P=_ instanceof HTMLButtonElement||_ instanceof HTMLSelectElement||_ instanceof HTMLInputElement||_ instanceof HTMLTextAreaElement?_:_.querySelector("button, select, input, textarea");P&&(P.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=Xw({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),I=M=>{y!==M&&(b?.disconnect(),y=M,C=bm(M),!(typeof ResizeObserver>"u")&&(b=new ResizeObserver(T=>{let P=T[T.length-1]?.contentRect?.width??bm(M);P!==C&&(C=P,j())}),b.observe(M)))},H=(M,T)=>{let _=Wk(M.collapseAutoActionsBelow,T);if(_===null)return!1;let P=C||bm(T);return P>0&&P<_},B=(M,T,_)=>{if(!T)return"bar";if(M.resolved.builtIn){let J=Rk(M.resolved.id);return J&&T.includeBuiltIns?.includes(J)?"menu":"bar"}let P=M.resolved.presentation;return P==="overflow"||P==="auto"&&_?"menu":"bar"},V=M=>{let T=M.menuSlot;if(!T)return;if(!Uk(M.element)){M.menuLabel?.remove(),M.menuLabel=void 0;return}let _=Nk(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)},oe=(M,T)=>{if(M.mode===T)return M;let _=M.resolved.action;if(_&&!Ls(_)){d(M),t.delete(M.resolved.id);let P=l(M.resolved,T);return t.set(M.resolved.id,P),P}if(T==="menu"){let P=Q("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Mf]:""}});P.appendChild(M.element),gC(vm(M.element)),M.menuSlot=P;let J=U=>{let ue=vm(M.element);if(ue.disabled)return;let fe=U.target===ue||ue.contains(U.target);h?.close(!0),fe||ue.click()};P.addEventListener("click",J,!0),M.detachMenuSlot=()=>P.removeEventListener("click",J,!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(P=>P.menuSlot??P.element);for(_.forEach((P,J)=>{let U=M.children[J];U!==P&&(U?M.insertBefore(P,U):M.appendChild(P))});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",P=A();P&&I(M.footer);let J=P?H(P,M.footer):!1,U={start:[],end:[]},ue=[];for(let fe of n){let me=t.get(fe.id);if(!me)continue;let He=fe.action,Ee=He?eS(He.visible,T,!0)&&Dk(He.visibility,T):!0;if(me.visible!==Ee&&(me.visible=Ee,!Ee&&me.managed&&(me.menuSlot??me.element).remove()),!!Ee){if(me=oe(me,B(me,P,J)),He){let Ie=eS(He.disabled,T,!1)||He.disableWhenStreaming===!0&&_;f(me,Ie),!Ls(He)&&He.pressed!==void 0&&me.button?.setAttribute("aria-pressed",He.pressed?"true":"false")}me.mode==="menu"?(V(me),ue.push(me)):U[fe.placement].push(me)}}if(ue.length>0){let fe=L();W(fe.panel,ue),fe.setItems(ue.map(Ie=>Ie.menuSlot??Ie.element)),fe.applyButtonSize();let me=Number.isFinite(P?.order)?P?.order:sr.overflow,He=U.start.findIndex(Ie=>Ie.resolved.order>me),Ee={resolved:{id:Ik,placement:"start",presentation:"bar",order:me,sequence:-1,source:"core"},element:fe.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};U.start.splice(He<0?U.start.length:He,0,Ee)}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=_k(e.collect()),T=new Set(M.map(_=>_.id));for(let[_,P]of t)T.has(_)||(d(P),t.delete(_));for(let _ of M){let P=t.get(_.id);if(!P){let fe=p(_,"bar");fe&&t.set(_.id,fe);continue}let J=P.resolved.action,U=_.action;if(!!J!=!!U||J&&U&&Ls(J)!==Ls(U)||J&&U&&Ls(J)&&Ls(U)&&J.render!==U.render){d(P),t.delete(_.id);let fe=p(_,P.mode);fe&&t.set(_.id,fe);continue}P.resolved=_,_.builtIn?(P.managed=_.builtIn.managed===!0||P.mode==="menu",_.builtIn.element&&P.mode==="bar"&&(P.element=_.builtIn.element)):U&&!Ls(U)?i(P,U):U&&P.element.toggleAttribute(ym,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=[]}}}}Ze();kt();Ms();var Vk="core:model",jk=700,nS=16,qk=["--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"],oS=()=>{let e=Q("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=Q("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function rS(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=Q("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=Q("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}=oS();return h.append(c,y),{element:h,destroy:()=>{o===d&&(o=null),c.removeEventListener("change",g),c.removeEventListener("click",f)}}},i=()=>{let c=Q("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=Q("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 P=(T%_.length+_.length)%_.length;_[P].focus()},L=T=>{if(b())return;y||(y=Op({anchor:c,content:g,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),tp(c,g,qk),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 _=T.currentTarget.getAttribute("data-persona-model-option");_&&I(_)},B=T=>{let _=Q("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 fe=ge(T.icon,nS,"currentColor",1.5);if(fe){let me=x("span","persona-composer-model-option-icon");me.appendChild(fe),_.appendChild(me)}}let P=x("span","persona-composer-model-option-body"),J=x("span","persona-composer-model-option-label");if(J.textContent=T.label,P.appendChild(J),T.description){let fe=x("span","persona-composer-model-option-description");fe.textContent=T.description,P.appendChild(fe)}_.appendChild(P);let U=x("span","persona-composer-model-option-check");U.setAttribute("aria-hidden","true");let ue=ge("check",nS,"currentColor",2);return ue&&U.appendChild(ue),_.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 ue=B(U);return f.set(U.id,ue),ue}))}let P=r(T);for(let[U,ue]of f)ue.setAttribute("aria-selected",String(U===P?.id));p.textContent=P?.label??"";let J=e.getSuffix?.()??"";d.textContent=J,c.setAttribute("aria-label",[t,[P?.label,J].filter(Boolean).join(" ")].filter(Boolean).join(": "))};V(),o=V;let oe=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()],P=_.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(_.length-1);return;case"Escape":T.preventDefault(),T.stopPropagation(),C(!0);return;case"Tab":C(!0);return;default:}};c.addEventListener("click",oe),c.addEventListener("keydown",W),g.addEventListener("keydown",j);let{wrapper:X,chevron:M}=oS();return X.append(c,M),{element:X,destroy:()=>{o===V&&(o=null),c.removeEventListener("click",oe),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:Vk,kind:"custom",placement:"end",order:jk,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?i():s()},repaint:()=>o?.()}}Ze();kt();Ze();var Cm="[data-persona-composer-chip-row]";function _p(e){e.style.display=e.childElementCount>0?"flex":"none"}function wm(e){let t=e.querySelector(Cm);if(t)return t;let n=Q("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 zk=":scope > [data-persona-composer-mode]";function sS(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=p=>{let d=Q("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=ge(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=Q("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=ge("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(zk)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let d=()=>{p.remove(),_p(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}_p(t)},destroy:()=>{o=!0,c(),_p(t)}}}Ze();kt();var iS=e=>`core:mode:${e}`;var Sm=e=>Math.min(300+e,499),aS=e=>`core:mode-group:${e}`;function Bp(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function Kk(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function lS(e,t){return e?.length?e.filter(n=>!Bp(n.groupId,t)&&!Kk(n.groupId,t)):[]}var Gk=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function cS(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(Gk(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 Dp(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function dS(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function pS(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var Yk=16;function uS(e){let t=null;return{action:{id:aS(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=Q("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=Q("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let f=ge(p.iconName,Yk,"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?.()}}Ze();kt();function gS(e){let t=Q("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=Q("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=Hp(s.text),l.appendChild(c);let p=Q("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),d=ge("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()}}}Ze();kt();function fS(e){let t=Q("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=Q("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),g=ge(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=Hp(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=Q("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()}}}Ze();function mS(e){let t=Q("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=Q("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=Q("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 hS(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 yS(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 bS(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 vS(e){return e.wrapped||e.text.includes(`
29
+ `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function CS(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function wS(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 SS(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}ep();function Am(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 xS(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var Xk=e=>typeof e?.then=="function";function AS(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 ES(e,t,n){let o;try{o=e(Am(t),{signal:n})}catch(r){return{status:"error",error:r}}return Xk(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:AS(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):AS(t,o)}jf();qf();Vf();Nr();var Np=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?"circle":"pill"),Fp={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"};So();So();var Up="16px",Vp="transparent",Qk=(()=>{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})(),Kl={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:Qk,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"}},$p={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"}},io={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:vi,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Up,canvasBackground:Vp,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"}}},Jk=Kl.colors.gray,Zk={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},TS={...Kl,colors:{...Kl.colors,gray:Jk}},e0={...Kl,colors:{...Kl.colors,gray:Zk},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}},PS=TS,kS=$p,t0={...$p,colors:{...$p.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...$p.typography,fontSize:"14px",lineHeight:"1.5"}},LS=kS,jp=io,n0={...io,launcher:Fp,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:{...io.input,borderRadius:"palette.radius.full"},introCard:{...io.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...io.suggestion.chip,fontWeight:"400"},card:{...io.suggestion.card,fontWeight:"400"},list:{...io.suggestion.list,fontWeight:"400"}},panel:{...io.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...io.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:{...io.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...io.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:{...io.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...io.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)"}},HS=jp,o0=e=>Es({future:e}),Em=e=>o0(e)==="v5"?{palette:e0,semantic:t0,components:n0}:{palette:TS,semantic:kS,components:jp};function wn(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."))?wn(e,o):o}function qp(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=wn(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 Mm(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 IS(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]=IS(s,r):n[o]=r}return n}function r0(e,t){return t?IS(e,t):e}function Gl(e,t={}){let n=Em(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:r0(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=Mm(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 xm=e=>e.trim()==="0"?"0px":e,MS="--persona-",s0=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},i0=.179,Cn=(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[MS+s],r!==void 0)break;r!==void 0&&(e[MS+n]=r)}};function zp(e){let t=qp(e),n={};for(let[$,_e]of Object.entries(t)){let ye=$.replace(/\./g,"-");n[`--persona-${ye}`]=_e.value}Cn(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"],Cn(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"]]),Cn(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"]}`,Cn(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"]??Up,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Vp,Cn(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"]]),Cn(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"],Cn(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"],Cn(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[$,_e]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let ye=n[`--persona-components-history-overlay-${$}`];ye&&(n[`--persona-history-overlay-${_e}`]=ye)}for(let[$,_e]of[["background","bg"],["borderRadius","radius"]]){let ye=n[`--persona-components-history-menu-${$}`];ye&&(n[`--persona-history-menu-${_e}`]=ye)}let g=e.components?.history?.motion;if(g){let $=ut=>{if(ut===void 0)return;let Zt=String(ut).trim();return/^\d+(\.\d+)?$/.test(Zt)?`${Zt}ms`:Zt},_e=$(g.enterDurationMs);_e!==void 0&&(n["--persona-history-enter-ms"]=_e);let ye=$(g.exitDurationMs);ye!==void 0&&(n["--persona-history-exit-ms"]=ye),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 _e=n[`--persona-components-history-confirm-${$}`];_e&&(n[`--persona-history-confirm-${$}`]=_e)}for(let[$,_e]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let ye=n[`--persona-components-tooltip-${$}`];ye&&(n[`--persona-tooltip-${_e}`]=ye)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[$,_e]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let ye=n[`--persona-components-messageActions-${$}`];ye&&(n[`--persona-message-action-${_e}`]=ye)}Cn(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,Cn(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"]]),Cn(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),Cn(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"]]),Cn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Cn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Cn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Cn(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[$,_e]of V){let ye=n[`--persona-components-collapsibleWidget-${$}`]??n[`--persona-${_e}`];ye!==void 0&&(n[`--persona-cw-${$}`]=ye,n[`--cw-${$}`]=ye)}Cn(n,[["message-border","components-message-border","border"]]),Cn(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 oe=e.components,W=oe?.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=oe?.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 X=oe?.toggleGroup;X&&(X.gap&&(n["--persona-toggle-group-gap"]=X.gap),X.borderRadius&&(n["--persona-toggle-group-radius"]=X.borderRadius));let M=oe?.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"]=xm($.toggleGroupGap)),$.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=$.toggleBorderRadius),$.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=xm($.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"]=wn(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"]=xm($.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 _e=wn(e,$.toolbarBackground)??$.toolbarBackground;n["--persona-artifact-toolbar-bg"]=_e}}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"]=wn(e,$.background)??$.background),$.border&&(n["--persona-artifact-inline-border"]=$.border),$.borderRadius&&(n["--persona-artifact-inline-radius"]=$.borderRadius),$.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=wn(e,$.chromeBackground)??$.chromeBackground),$.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=wn(e,$.chromeBorder)??$.chromeBorder),$.titleColor&&(n["--persona-artifact-inline-title-color"]=wn(e,$.titleColor)??$.titleColor),$.mutedColor&&(n["--persona-artifact-inline-muted-color"]=wn(e,$.mutedColor)??$.mutedColor),$.frameHeight&&(n["--persona-artifact-inline-frame-height"]=$.frameHeight)}let T=oe?.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"]=wn(e,T.background)??T.background));let _=n["--persona-surface"],P=n["--persona-container"],J=n["--persona-palette-colors-gray-100"]??"#f3f4f6",U=n["--persona-palette-colors-gray-200"]??"#e5e7eb",ue=n["--persona-palette-colors-gray-300"]??"#d1d5db",fe=!P||P===_,me=s0(_??n["--persona-background"]),He=fe&&me!==void 0&&me<i0,Ee=He?"rgba(255, 255, 255, 0.08)":J,Ie=He?"rgba(255, 255, 255, 0.12)":U,yt=He?"rgba(255, 255, 255, 0.16)":ue,qe=fe?Ee:P,Oe=fe?Ie:P;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??qe,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Oe,fe&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??yt),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??qe,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??qe,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??qe,n}var RS={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"};qd();var a0=e=>!!e&&"launcher"in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode==="docked"),WS=(e,t)=>{if(!t||!a0(t))return e;let n=t.theme?.components?.panel?.width,o=t.darkTheme?.components?.panel?.width;return(xi(t)==="dark"?o??n:n)!=null?e:{...e,components:{...e.components,panel:{...e.components.panel,width:Es(t)==="v5"?"400px":"420px"}}}},l0={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"}}},Yl={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)"}}}},Tm=l0,c0={...Tm,colors:{...Tm.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"}}},d0=Yl,p0={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:{...Yl.components,button:{...Yl.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:{...Yl.components?.eventStream,badge:{...Yl.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"}}}}},u0=e=>Es({future:e})==="v5"?{palette:c0,components:p0}:{palette:Tm,components:d0},OS=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Xl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",g0=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Xl()},xi=e=>g0(e),f0=(e,t={})=>Gl(e,t),m0=(e,t={})=>{let n=u0(t.future),o=Bo(n.components,e??{})??{};return Gl({...o,palette:{...o.palette,colors:Es(t)==="v5"?Bo(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})},No=e=>{let t=xi(e),n=OS(e?.theme),o=Np(e)==="circle"?Fp:{...jp.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=Bo({components:{launcher:o}},n),s=OS(e?.darkTheme);return WS(t==="dark"?m0(Bo(r??{},s??{}),{future:e?.future}):f0(r,{future:e?.future}),e)},h0=e=>zp(e),Ei=(e,t)=>{let n=No(t),o=h0(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",xi(t)),e.setAttribute("data-persona-defaults",Es(t))},Oa=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Xl())});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(Xl());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())}};qd();var Kr=require("lucide");kt();Lr();Ze();var Hs=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Kp="24px",Pm=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",Ql=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},_S=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);xa();Ud();yp();var BS=require("idiomorph"),Gp=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;BS.Idiomorph.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 DS=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var km={index:-1,draft:""};function NS(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 FS(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 $S(){return new Map}function US(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function VS(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function jS(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function qS(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 zS(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function ir(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Mi(e,t){return ir(e)-e.scrollTop<=t}function KS(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 GS(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 YS(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Lm(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 XS(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}_o();var Jl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},y0=["pre","code","a","script","style"],Yp=e=>({type:e?.type??Jl.type,placeholder:e?.placeholder??Jl.placeholder,speed:e?.speed??Jl.speed,duration:e?.duration??Jl.duration,buffer:e?.buffer??Jl.buffer}),JS=[{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"}],Zl=new Map;for(let e of JS)Zl.set(e.name,e);var ZS=["wipe","glyph-cycle"],ec=e=>{Zl.set(e.name,e)},eA=e=>{JS.some(t=>t.name===e)||Zl.delete(e)},tA=()=>Array.from(Zl.keys()),tc=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Zl.get(e)??null,Xp=(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},b0=(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},v0=(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},Hm=/\s/,C0=(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},w0=(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(Hm.test(s[l])){let c=l;for(;c<s.length&&Hm.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&&!Hm.test(s[p]);)c.appendChild(b0(o,s[p],t,n.value)),n.value+=1,p+=1;i.appendChild(c),l=p}r.replaceChild(i,e)},S0=(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(v0(o,c,t,n.value)),n.value+=1));r.replaceChild(i,e)},nc=(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??y0).map(g=>g.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],c=i.nextNode();for(;c;)C0(c,s)||l.push(c),c=i.nextNode();let p={value:o?.startIndex??0},d=t==="char"?w0:S0;for(let g of l)d(g,n,p);return r.innerHTML},Qp=(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},oc=(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},QS=new WeakMap,A0=(e,t)=>{if(!e.styles)return;let n=QS.get(t);if(n||(n=new Set,QS.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)},Im=new WeakMap,x0=(e,t)=>{if(!e.onAttach)return;let n=Im.get(t);if(n||(n=new Map,Im.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},nA=e=>{let t=Im.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},rc=(e,t)=>{A0(e,t),x0(e,t)};dn();var{setLoader:qB,load:E0}=lt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var oA=E0;_o();function Rm(e,t=kn){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 sc=0,Is=null;function Wm(e=document){if(sc++,sc===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Is={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,sc=Math.max(0,sc-1),sc===0&&Is)){let n=e.body,o=e.defaultView??window;n.style.overflow=Is.originalOverflow,n.style.position=Is.originalPosition,n.style.top=Is.originalTop,n.style.width=Is.originalWidth,o.scrollTo(0,Is.scrollY),Is=null}}}Ea();var ic={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Lt=e=>(e?.launcher?.mountMode??"floating")==="docked",Rs=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Zn=e=>{let t=e?.launcher?.dock,n=_r(e).dockWidth?t?.width:wn(No(e),"components.panel.width");return{side:t?.side??ic.side,width:n??ic.width,animate:t?.animate??ic.animate,reveal:t?.reveal??ic.reveal,maxHeight:t?.maxHeight??ic.maxHeight}};Ze();Ze();var sA=require("lucide");kt();Lr();var Om=e=>e==="followUp"?"follow-up":e,_m=(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"}},rA=new WeakSet,M0=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,T0=e=>{M0()||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"})})},Bm=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=ge(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(Q("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&H.appendChild(Q("span",{className:"persona-suggestion__description",text:t.description})),I.appendChild(H),s!=="chip"){let B=Nt(sA.ArrowRight,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},ac=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??{},oe=b?.plugins??[],W=typeof b?.maxItems=="number"?Math.max(0,Math.floor(b.maxItems)):void 0,j=L?"followUps":"starters";!rA.has(V)&&V.debug===!0&&I!=="chip"&&V.suggestions?.[j]?.overflow!==void 0&&(rA.add(V),console.info(`[persona] suggestions.${j}.overflow applies to the "chip" variant only; the "${I}" variant manages its own stacking.`));let X=U=>U.map(_m).filter(ue=>ue!==null).map(ue=>({...ue,behavior:ue.behavior??H})),M=X(d??[]);oe.forEach(U=>{U.transformSuggestions&&(M=X(U.transformSuggestions({suggestions:M.map(ue=>({...ue})),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(ue=>ue.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(),P=g.isStreaming();T.forEach((U,ue)=>{let fe=Bm({item:U,index:ue,surface:A,source:C,variant:I,streaming:P,config:V,plugins:oe,chipsConfig:y,session:g,getTextarea:()=>f,eventTarget:e,submitPrompt:b?.submitPrompt});_.appendChild(fe),n.push(fe),[...fe instanceof HTMLButtonElement?[fe]:[],...Array.from(fe.querySelectorAll("button"))].forEach(He=>{t.includes(He)||(He.disabled=P,t.push(He))})}),e.appendChild(_),i(),l();let J=JSON.stringify({normalized:T,surface:A,variant:I,source:C});J!==o&&(o=J,T0(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 ao={"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"};_o();Ze();kt();So();Ze();kt();xa();var P0="persona-header-control",k0="persona-header-control--glyph",L0="persona-header-control--sparse",H0=20,I0={x:[1.4,1.05]},iA="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",R0="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Jp=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,i]=I0[t]??[1,1.5],l=!o;e.classList.toggle(k0,l),e.classList.toggle(L0,l&&s!==1);let c=parseFloat(o??"")||H0,p=ge(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)},_a=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:i=iA,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=Q("button",{className:Dn(P0,"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||Nn.actionIconColor,backgroundColor:d,border:H?`${g||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:h,paddingLeft:y,paddingRight:y,paddingTop:b,paddingBottom:b}});return r?Jp(B,r,{iconSize:c,iconText:s}):s&&(B.textContent=s),I.appendChild(B),vn({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=iA,buttonSize:r,iconSize:s}=t,i=e?.launcher??{},l=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:p,wrapper:d}=_a({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}},Da=(e,t={})=>{let{wrapperClassName:n=R0,buttonSize:o,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},l=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:p,wrapper:d}=_a({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 Nn={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)"},Dm={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)"},W0={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)"},jr=e=>{let{config:t,showClose:n=!0}=e,o=Q("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:Nn.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??_l,i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,c=r.headerIconName,p=Q("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=ge(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=Q("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Nn.titleColor,...Dm}}),f=Q("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Nn.subtitleColor,...W0}});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=Da(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}},Ti=(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))};Ze();Ze();kt();_o();function Pi(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(wa)):(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=ge(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}}Ze();kt();function eo(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:i,onClick:l,aria:c}=e,p=x("button",Dn(!i&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ge(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 Nm(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=ge(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 lc(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=eo({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 aA(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?eo({...C,icon:n,size:o??14}):Nm({...C,icon:n,iconSize:o??14}),L=eo({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=Pi({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 Zp(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=ge(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=Pi({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()}}}yp();var Fm=e=>{let t=jr({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 O0(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=_a({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?hp(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=Nl(o.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(o.menuItems?.length){let i=Pi({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 $m=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=Nn.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=Zp({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}}))},oe=c.onSelect(B);oe instanceof Promise?oe.then(V,()=>{}):V(oe)},hover:c.hover,className:""});p=H.element,p.style.color=Nn.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=Nn.titleColor,Object.assign(d.style,Dm),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||O0(y,r?.trailingActions,r?.onAction??s);let b=i.clearChat??{},C=null,A=null;if(b.enabled??!0){let H=b.placement??"inline",B=Da(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}},eu={default:Fm,minimal:$m},Um=e=>eu[e]??eu.default,Na=(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=Um(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};Ze();Ms();var ki=e=>{let{config:t}=e,n=Q("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=ip(),r=Q("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}=np(t);i();let l=op(t),c=ka(t),p=rp(t),d=sp(t),g=Q("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=Q("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=Q("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),y=Q("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}};Ze();var tu=require("lucide");Lr();Ms();ep();var lA=()=>{let e=Q("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=Nt(tu.MessageSquare,16,"currentColor",1.5);n&&t.appendChild(n);let o=x("span","persona-pill-peek__text"),r=x("span","persona-pill-peek__caret"),s=Nt(tu.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},nu=e=>{let{config:t}=e,n=Q("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ip(),r=sp(t);r.style.display="none";let{textarea:s,attachAutoResize:i}=np(t,{defaultMaxLines:5});i();let l=op(t),c=ka(t),p=rp(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let d=Q("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),g=Q("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&g.append(p.wrapper);let f=Q("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=Q("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}};Ze();kt();Ze();zf();kt();Nr();var _0=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}},B0=(e,t)=>{if(!e)return null;let n=_0(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},D0=(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},N0=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},jm=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(":"))},qm=320,gA=320,F0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),$0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),U0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),V0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),j0=e=>{if(!e||e.length===0)return null;let t=Q("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Q("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=x("span","persona-mention-chip-icon"),s=ge(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Q("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},q0=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Dl(o.ref,{readonly:!0,render:t}))}return n},cA="\uE000",dA="\uE001",z0=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=f=>`${cA}${r}:${f}${dA}`,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(q0(t,o));return}e.innerHTML=l;let p=new RegExp(`${cA}${r}:(\\d+)${dA}`),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(Dl(b.ref,{readonly:!0,render:o}),C),h=C}}},K0=(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=`${qm}px`,p.style.maxHeight=`${gA}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}),N0(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}},G0=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(!jm(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=`${qm}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Y0=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(!jm(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=`${qm}px`,r.style.maxHeight=`${gA}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}},X0=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(!jm(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}},Li=()=>{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},zm=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Li};if(t){let r=t(o);if(r!==null)return r}return Li()},Q0=(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},pA=(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},cc=(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},uA={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"}},J0=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=uA[n??"bubble"]??uA.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)`)},ou="custom:",Z0=e=>`${ou}${e}`,fA=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),Km=(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=fA(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=eo({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,Z0(I.id)));return A},Fa=(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=cc(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=Em(s?.widgetConfig?.future).components.message,A=s?.widgetConfig?.theme?.components?.message;J0(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=F0(e),I=e.content?.trim()??"",B=L.length>0&&I===Ta,V=Yp(s?.widgetConfig?.features?.streamAnimation),oe=s?.widgetConfig?.features?.streamAnimation?.plugins,W=e.role==="assistant"&&V.type!=="none"?tc(V.type,oe):null,j=e.role==="assistant"&&W?.isAnimating?.(e)===!0,X=e.role==="assistant"&&W!==null&&(!!e.streaming||j);X&&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"),X&&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=X?Xp(e.content??"",V.buffer,W,e,!!e.streaming):e.content??"",_=()=>{let Oe=t({text:T,message:e,streaming:!!e.streaming,raw:e.rawContent});return X&&W?.wrap==="char"?nc(Oe,"char",e.id,{skipTags:W.skipTags}):X&&W?.wrap==="word"?nc(Oe,"word",e.id,{skipTags:W.skipTags}):Oe},P=null;if(B?(P=document.createElement("div"),P.innerHTML=_(),P.style.display="none",M.appendChild(P)):e.contentSegments?.length?z0(M,e.contentSegments,Oe=>t({text:Oe,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):M.innerHTML=_(),X&&W?.useCaret&&!B&&I){let Oe=Qp(),$=M.querySelectorAll(".persona-stream-char, .persona-stream-word"),_e=$[$.length-1];if(_e?.parentNode)_e.parentNode.insertBefore(Oe,_e.nextSibling);else{let ye=M.lastElementChild;ye?ye.appendChild(Oe):M.appendChild(Oe)}}if(g&&h==="inline"&&e.createdAt){let Oe=pA(e,p,"span");Oe.classList.add("persona-timestamp-inline");let $=M.lastElementChild;$?$.appendChild(Oe):M.appendChild(Oe)}if(L.length>0){let Oe=K0(L,!B&&!!I,()=>{B&&P&&(P.style.display="")});Oe?b.appendChild(Oe):B&&P&&(P.style.display="")}let J=$0(e);if(J.length>0){let Oe=G0(J);Oe&&b.appendChild(Oe)}let U=U0(e);if(U.length>0){let Oe=Y0(U);Oe&&b.appendChild(Oe)}let ue=V0(e);if(ue.length>0){let Oe=X0(ue);Oe&&b.appendChild(Oe)}let fe=e.contentSegments?.length?null:j0(e.contextMentions);if(fe&&b.appendChild(fe),b.appendChild(M),g&&h==="below"&&e.createdAt){let Oe=pA(e,p);Oe.classList.add("persona-mt-1"),b.appendChild(Oe)}let me=e.role==="assistant"?B0(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Oe=!!(T&&T.trim()),$=V.placeholder==="skeleton",_e=$&&V.buffer==="line"&&Oe;if(Oe)_e&&b.appendChild(oc());else if($)b.appendChild(oc());else{let ye=zm("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ye&&b.appendChild(ye)}}me&&e.stopReason&&!e.streaming&&(I||(M.style.display="none"),b.appendChild(D0(e.stopReason,me)));let He=e.role==="assistant"&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&o?.enabled!==!1,Ee=s?.actionEligibility,Ie=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Ee?.canEdit===!0||o?.showQuote===!0&&Ee?.canQuote===!0||fA(o,"user").length>0);if((He||Ie)&&o){let Oe=Km(e,Ie?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,Ee);b.appendChild(Oe)}if(!d||e.role==="system")return b;let yt=x("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),qe=Q0(c,e.role);return f==="right"||f==="left"&&e.role==="user"?yt.append(b,qe):yt.append(qe,b),yt},mA=(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}):Fa(e,t,n,o,r,s)};var eL=40,tL=(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=ge(t.name,eL);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(Q("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Q("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},hA=(e,t,n={})=>{let o=Q("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=Q("div",{className:"persona-welcome-head-text"},r,s),c=Q("div",{className:"persona-welcome-title-row"},o,l);return{host:Q("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}},$a=(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)},su=(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==="",tL(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")},nL="data-persona-welcome-plugin",yA="data-persona-welcome-overlay",ru="persona-welcome-overlay-active",Gm=new WeakMap,Ym=(e,t,n)=>{n.setAttribute(nL,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(yA,""),e.classList.contains(ru)||(Gm.set(e,e.scrollTop),e.classList.add(ru),e.scrollTop=0)},Xm=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(yA),e.classList.contains(ru)&&(e.classList.remove(ru),e.scrollTop=Gm.get(e)??e.scrollTop,Gm.delete(e))},bA=()=>{let e=Q("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},iu=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=Q("div",{className:cc("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(Q("div",{className:"persona-flex"},r)),e.hidden=!1},vA=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,CA=(e,t)=>{if(vA()||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},wA=(e,t,n,o=260)=>{if(t<=1||vA()||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 oL="Hello \u{1F44B}",rL="I can answer questions and help you get things done here.",SA=new WeakSet,Fn=(e,t)=>!!e&&e[t]!==void 0,sL=(e,t)=>{!e||e.debug!==!0||!t.length||SA.has(e)||(SA.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Ua=(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=Fn(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=i==="hero"&&!r&&n?.layout===void 0?"on-first-message":Fn(n,"dismiss")?n.dismiss:r||i==="hero"?"on-first-message":"never",c=[];Fn(n,"title")&&Fn(o,"welcomeTitle")&&c.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Fn(n,"subtitle")&&Fn(o,"welcomeSubtitle")&&c.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Fn(n,"variant")&&Fn(o,"showWelcomeCard")&&c.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),i==="hero"&&Fn(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"&&Fn(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=Ql(n?.anchorComposerTop)!==null;return Fn(n,"anchorComposerTop")&&!d&&c.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&(Fn(n,"anchorComposerTop")||Fn(n,"composerGap"))&&c.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),sL(e,c),{title:Fn(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":oL),kicker:n?.kicker??"",subtitle:Fn(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":rL),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()||Kp}},AA=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Ws=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");Ea();var iL="var(--persona-components-panel-maxWidth)",xA="var(--persona-components-panel-height)",aL="var(--persona-components-panel-maxHeight)",Hi=e=>{let t=_r(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0,r=o===0?`max(200px, ${xA})`:`max(200px, calc(${xA} - ${o}px))`;return{width:n??CC,maxWidth:n??iL,height:r,maxHeight:aL}},EA="16px",Jm="10px",Zm="14px",MA=e=>{let t=e?.launcher?.enabled??!0,n=Lt(e);if(Rs(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??kn);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??kn),{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=_r(e),h=g.launcherWidth||g.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?Hi(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&&ao[r.position]?ao[r.position]:ao["bottom-right"],i=x("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??kn);let l=x("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=Hi(e);return l.style.width=c.width,l.style.maxWidth=c.maxWidth,i.appendChild(l),{wrapper:i,panel:l}},eh=e=>{let t=Q("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Om(e)}});return t.hidden=!0,t},TA=(e,t)=>{let n=eh("starter"),o=hA(e,n,{flatShadow:Lt(e)}),r=Ua(e);su(o,r),$a(t,o.host,Ws(r,e?.initialMessages));let s=bA();return iu(s,r.message,e),{welcome:o,greetingHost:s}},lL=(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:EA,iconSize:Jm});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 oe=Da(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:EA,iconSize:Zm});i=oe.button,l=oe.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let c=Q("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=Q("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}=TA(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=eh("followUp"),L=Hs(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=Q("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=nu({config:e}),{root:B,textNode:V}=lA();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}},PA=(e,t=!0)=>{if(Rs(e))return lL(e,t);let n=Q("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?Na(e,o,{showClose:t}):jr({config:e,showClose:t}),i=Q("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}=TA(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=eh("followUp"),b=Hs(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=ki({config:e}),A=e?.layout?.showFooter!==!1;r?Ti(n,s,e):(s.header.style.display="none",Ti(n,s,e)),n.append(i);let L=Q("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}};Ms();Ze();kt();_o();var th=(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 jw=e=>bs(e)||e===Oo,Wa=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=Lt(s),c=Np(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=ge(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,oe=Math.max(V-B,8),W=ge(i.callToActionIconName,oe,"currentColor",1.5);W?y.appendChild(W):y.textContent=i.callToActionIconText??"\u2197"}else y.textContent=i.callToActionIconText??"\u2197"}let b=i.position&&ao[i.position]?ao[i.position]:ao["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??Pn));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}},lL="teaser-dismissed",LA=new Set,PA=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${lL}`},cL=(e,t)=>{if(LA.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},dL=(e,t)=>{if(LA.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},pL=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,uL=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Lt(e??{})?null:t},HA=(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=J=>{y(),g=!0,b(),dL(PA(o),J&&h())},A=J=>{!r||g||C(J==="user"&&p)},L=()=>{c=null,!(!s||g||f)&&(d=!0,p=!0,s.hidden=!1,!(pL()||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||cL(PA(o),h())||(y(),c=setTimeout(L,Math.max(0,r.delayMs??0)))},H=()=>{C(h()),t()},B=J=>{J.stopPropagation(),C(h())},oe=th(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=Q("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",H),i=Q("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",B),s=Q("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,i),n.insertBefore(s,oe.element)},X=()=>{let J=o.launcher?.position??"bottom-right",U=ao[J]??ao["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",oe.element.style.position="";return}n.className=Dn("persona-launcher-surface",U),n.setAttribute("data-teaser",J),n.style.zIndex=String(o.launcher?.zIndex??Pn),oe.element.style.position="static"},M=J=>{let U=uL(J);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=J=>{o=J,oe.update(J),M(J),X()},_=(J,U="user")=>{f=J,J&&A(U)},k=()=>{W(),oe.destroy(),n.remove()};return n.appendChild(oe.element),e&&(M(e),X()),{element:n,launcher:oe,get teaser(){return s?{element:s,show:L,dismiss:C}:null},setPanelOpen:_,update:T,destroy:k}};var IA=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=MA(e),s=kA(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}}},nh=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>th(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=HA(e,n);return{instance:r,element:r.element}};var gL=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},fL=(e,t,n)=>`${gL(e)}plugin:${t}:${n}`,RA=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=>fL(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}}}}};Ze();Pt();So();Cs();Ze();var Va=(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 mL=(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
- `):""},oh=(e,t,n)=>{Tp(e,t,{stateSet:n,previewKind:"reasoning",iconColor:"currentColor"})},rh=(e,t,n=new Set)=>{t=Pp(t,"reasoning");let o=e.reasoning,r=Ap("persona-reasoning-bubble",e.id);if(!o)return $r(r,e,t,"reasoning");let s=t?.features?.reasoningDisplay??{},i=s.expandable??Ci.expandable,l=i&&n.has(e.id),c=o.status!=="complete",p=mL(e,s.previewMaxLines??Ci.previewMaxLines),d=xp({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=Ts(t,"reasoning")==="row",y=h&&!c?`Thought for ${Ul(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=Md(o),U},L=b.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:y,previewText:p,isActive:c,config:t??{},elapsed:Md(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=bv(o),h||g.appendChild(I);let H=s.loadingAnimation??Ci.loadingAnimation,B=b.activeTextTemplate,V=b.completeTextTemplate,oe=c?B:V,W=L instanceof HTMLElement,j=(U,ue)=>{f.textContent="";let fe=Td(U,""),me=0;for(let He of fe){let Ee=He.styles.length>0?(()=>{let Ie=x("span",He.styles.map(yt=>`persona-tool-text-${yt}`).join(" "));return f.appendChild(Ie),Ie})():f;if(He.isDuration&&c)Ee.appendChild(A());else{let Ie=He.isDuration?Md(o):He.text;ue?me=Va(Ee,Ie,me):Ee.appendChild(document.createTextNode(Ie))}}};if(!W&&oe)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(oe,!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(oe,!0))}else j(oe,!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 ue=f.textContent||y;f.textContent="",Va(f,ue,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"),ue=ge(s.iconName,16,"currentColor",2);ue&&(U.appendChild(ue),d.appendChild(U))}let X="currentColor",M=La(d,g,{expandable:i,expanded:l,iconColor:X,metaGap:!1}),T=Ep({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),$r(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(""),J=x("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return J.textContent=k||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),_.appendChild(J),Mp({expanded:l,header:d,toggleIcon:M,content:_,collapsedPreview:T,iconColor:X}),r.append(d,T,_),$r(r,e,t,"reasoning")};Ze();Cs();Pt();var WA=e=>{if(e==null)return!0;if(typeof e=="string"){if(!e.trim())return!0;try{return WA(JSON.parse(e))}catch{return!1}}return typeof e=="object"&&Object.keys(e).length===0},hL=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 OA(e,t,n){let o=t.toolCall;if(!o)return;let r=n.toolCall??{},s=(l,c)=>{let p=Q("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=Q("div",{className:"persona-tool-detail-label",text:l,style:{color:r.labelTextColor}}),g=ya(c),f=Q("pre",{className:`persona-tool-detail-value${hL(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=Q("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${l.toLowerCase()}`,title:`Copy ${l.toLowerCase()}`}}),y=ge("copy",14,"currentColor",1.7);y&&h.appendChild(y),p.append(d,f,h),e.appendChild(p)};WA(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(Q("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var sh=new WeakMap;async function _A(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(sh.get(e));try{await navigator.clipboard.writeText(n.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let r=ge("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"}sh.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",o),e.title=o;let r=ge("copy",14,"currentColor",1.7);r&&e.replaceChildren(r),sh.delete(e)},1800))}Ze();So();Cs();var BA=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?"currentColor":"var(--persona-primary, #171717)"),yL=(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=Lt(s),c=Np(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=ge(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,oe=Math.max(V-B,8),W=ge(i.callToActionIconName,oe,"currentColor",1.5);W?y.appendChild(W):y.textContent=i.callToActionIconText??"\u2197"}else y.textContent=i.callToActionIconText??"\u2197"}let b=i.position&&ao[i.position]?ao[i.position]:ao["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??kn));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}},cL="teaser-dismissed",LA=new Set,kA=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${cL}`},dL=(e,t)=>{if(LA.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},pL=(e,t)=>{if(LA.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},uL=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,gL=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Lt(e??{})?null:t},HA=(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=J=>{y(),g=!0,b(),pL(kA(o),J&&h())},A=J=>{!r||g||C(J==="user"&&p)},L=()=>{c=null,!(!s||g||f)&&(d=!0,p=!0,s.hidden=!1,!(uL()||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||dL(kA(o),h())||(y(),c=setTimeout(L,Math.max(0,r.delayMs??0)))},H=()=>{C(h()),t()},B=J=>{J.stopPropagation(),C(h())},oe=th(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=Q("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",H),i=Q("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",B),s=Q("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,i),n.insertBefore(s,oe.element)},X=()=>{let J=o.launcher?.position??"bottom-right",U=ao[J]??ao["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",oe.element.style.position="";return}n.className=Dn("persona-launcher-surface",U),n.setAttribute("data-teaser",J),n.style.zIndex=String(o.launcher?.zIndex??kn),oe.element.style.position="static"},M=J=>{let U=gL(J);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=J=>{o=J,oe.update(J),M(J),X()},_=(J,U="user")=>{f=J,J&&A(U)},P=()=>{W(),oe.destroy(),n.remove()};return n.appendChild(oe.element),e&&(M(e),X()),{element:n,launcher:oe,get teaser(){return s?{element:s,show:L,dismiss:C}:null},setPanelOpen:_,update:T,destroy:P}};var IA=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=MA(e),s=PA(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}}},nh=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>th(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=HA(e,n);return{instance:r,element:r.element}};var fL=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},mL=(e,t,n)=>`${fL(e)}plugin:${t}:${n}`,RA=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=>mL(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}}}}};Ze();kt();So();Cs();Ze();var Va=(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 hL=(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
+ `):""},oh=(e,t,n)=>{Tp(e,t,{stateSet:n,previewKind:"reasoning",iconColor:"currentColor"})},rh=(e,t,n=new Set)=>{t=kp(t,"reasoning");let o=e.reasoning,r=Ap("persona-reasoning-bubble",e.id);if(!o)return $r(r,e,t,"reasoning");let s=t?.features?.reasoningDisplay??{},i=s.expandable??Ci.expandable,l=i&&n.has(e.id),c=o.status!=="complete",p=hL(e,s.previewMaxLines??Ci.previewMaxLines),d=xp({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=Ts(t,"reasoning")==="row",y=h&&!c?`Thought for ${Ul(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=Md(o),U},L=b.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:y,previewText:p,isActive:c,config:t??{},elapsed:Md(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=bv(o),h||g.appendChild(I);let H=s.loadingAnimation??Ci.loadingAnimation,B=b.activeTextTemplate,V=b.completeTextTemplate,oe=c?B:V,W=L instanceof HTMLElement,j=(U,ue)=>{f.textContent="";let fe=Td(U,""),me=0;for(let He of fe){let Ee=He.styles.length>0?(()=>{let Ie=x("span",He.styles.map(yt=>`persona-tool-text-${yt}`).join(" "));return f.appendChild(Ie),Ie})():f;if(He.isDuration&&c)Ee.appendChild(A());else{let Ie=He.isDuration?Md(o):He.text;ue?me=Va(Ee,Ie,me):Ee.appendChild(document.createTextNode(Ie))}}};if(!W&&oe)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(oe,!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(oe,!0))}else j(oe,!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 ue=f.textContent||y;f.textContent="",Va(f,ue,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"),ue=ge(s.iconName,16,"currentColor",2);ue&&(U.appendChild(ue),d.appendChild(U))}let X="currentColor",M=La(d,g,{expandable:i,expanded:l,iconColor:X,metaGap:!1}),T=Ep({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),$r(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 P=o.chunks.join(""),J=x("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return J.textContent=P||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),_.appendChild(J),Mp({expanded:l,header:d,toggleIcon:M,content:_,collapsedPreview:T,iconColor:X}),r.append(d,T,_),$r(r,e,t,"reasoning")};Ze();Cs();kt();var WA=e=>{if(e==null)return!0;if(typeof e=="string"){if(!e.trim())return!0;try{return WA(JSON.parse(e))}catch{return!1}}return typeof e=="object"&&Object.keys(e).length===0},yL=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 OA(e,t,n){let o=t.toolCall;if(!o)return;let r=n.toolCall??{},s=(l,c)=>{let p=Q("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=Q("div",{className:"persona-tool-detail-label",text:l,style:{color:r.labelTextColor}}),g=ya(c),f=Q("pre",{className:`persona-tool-detail-value${yL(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=Q("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${l.toLowerCase()}`,title:`Copy ${l.toLowerCase()}`}}),y=ge("copy",14,"currentColor",1.7);y&&h.appendChild(y),p.append(d,f,h),e.appendChild(p)};WA(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(Q("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var sh=new WeakMap;async function _A(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(sh.get(e));try{await navigator.clipboard.writeText(n.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let r=ge("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"}sh.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",o),e.title=o;let r=ge("copy",14,"currentColor",1.7);r&&e.replaceChildren(r),sh.delete(e)},1800))}Ze();So();Cs();var BA=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?"currentColor":"var(--persona-primary, #171717)"),bL=(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=ya(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
42
- `):""},ih=(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)"},bL=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??Br.collapsedMode,s=n?.success===!1?n.error||"Tool failed":yL(e,o?.previewMaxLines??Br.previewMaxLines),i=n?Ts(t,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:Cv(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=cf(n,c.activeTextTemplate,p):!l&&c.completeTextTemplate&&(p=cf(n,c.completeTextTemplate,p)),n.success===!1?p+=" \xB7 Failed":n.superseded&&(p+=" \xB7 Approved, ran again below"),{summary:p,previewText:s,isActive:l}},ah=(e,t,n,o)=>{Tp(e,t,{stateSet:n,previewKind:"tool",iconColor:BA(o?.toolCall??{},t.classList.contains("persona-activity-row"))})},lh=(e,t,n=new Set)=>{t=Pp(t,"tool");let o=e.toolCall,r=t?.toolCall??{},s=Ap("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 $r(s,e,t,"tool");let i=t?.features?.toolCallDisplay??{},l=i.expandable??Br.expandable,c=l&&n.has(e.id),{summary:p,previewText:d,isActive:g}=bL(e,t),f=xp({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=kl(o),T},A=r.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:p,previewText:d,collapsedMode:i.collapsedMode??Br.collapsedMode,isActive:g,config:t??{},elapsed:kl(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??Br.loadingAnimation,I=r.activeTextTemplate,H=r.completeTextTemplate,B=g?I:H,V=A instanceof HTMLElement,oe=(T,_)=>{y.textContent="";let k=o.name?.trim()||"tool",J=Td(T,k),U=0;for(let ue of J){let fe=ue.styles.length>0?(()=>{let me=x("span",ue.styles.map(He=>`persona-tool-text-${He}`).join(" "));return y.appendChild(me),me})():y;if(ue.isDuration&&g)fe.appendChild(C());else{let me=ue.isDuration?kl(o):ue.text;_?U=Va(fe,me,U):fe.appendChild(document.createTextNode(me))}}};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&&oe(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)oe(B,!0);else{let _=y.textContent||p;y.textContent="",Va(y,_,0)}}else B&&oe(B,!1);let W=BA(r,Ts(t,"tool")==="row"),j=La(f,h,{expandable:l,expanded:c,iconColor:W,metaGap:!0}),X=Ep({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,X),$r(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)OA(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",ih(k,r),k.textContent=ya(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",ih(k,r),k.textContent=o.chunks.join(""),T.append(_,k),M.appendChild(T)}if(o.success===!1&&M.appendChild(Q("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",ih(k,r),k.textContent=ya(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 Mp({expanded:c,header:f,toggleIcon:j,content:M,collapsedPreview:X,iconColor:W}),s.append(f,X,M),$r(s,e,t,"tool")};Rl();Ca();Cs();dn();var{setLoader:ZN,load:vL,provide:e1,getSync:CL}=lt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")});var DA=vL;var NA=CL;pi();dn();var{setLoader:o1,load:wL}=lt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var ch=wL;dn();var dh=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)})}},Fo=new dh;tf();var ph=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:d1,load:SL,provide:p1,getSync:AL}=lt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),ja=null,au=new Set,FA=e=>{if(ja)return ja;ja=e,e.initArtifactsUi({componentRegistry:Fo});for(let o of ph)Fo.has(o)||Fo.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=nr();t?e.__provideMarkdownParsers(t):ua(()=>{let o=nr();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>Cd());let n=[...au];au.clear();for(let o of n)try{o()}catch{}return e};var lu=()=>SL().then(FA);var qr=()=>{if(ja)return ja;let e=AL();return e?FA(e):null},uh=e=>ja?()=>{}:(au.add(e),()=>{au.delete(e)});function $n(e){return e?.features?.artifacts?.enabled===!0}function $A(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"),!$n(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 xL(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 UA=["panel","seamless","detached"];function gh(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&UA.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function fh(e){return!e||!$n(e)?!1:gh(e)==="detached"}function dc(e,t){if(!$n(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"),xL(e),$A(e,t);return}let n=t.features?.artifacts?.layout,o=gh(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)}$A(e,t)}function pc(e,t){for(let l of UA)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"),!$n(t))return;let n=t.features?.artifacts?.layout,o=gh(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 VA(e,t){return!t||!$n(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}ha();ha();var EL=new Set(["__proto__","prototype","constructor"]),ML=new Set(["collapsed","card","panel","inline"]),jA=new Set(["markdown","component"]),TL=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Ii=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),du=e=>!EL.has(e),mh=e=>typeof e=="string"&&ML.has(e),Ri=e=>Object.keys(e).length>0;function ar(e,t,n,o){e.push({path:t,code:n,message:o})}var kL="Ignored because this key is not part of the persisted preference schema.",cu="Ignored an unsupported value.",PL="Expected collapsed, panel, or inline.",LL='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',qA={kind:"mode",message:cu},qa={kind:"string",message:"Expected a CSS length string."},zr={kind:"boolean"},HL={paneWidth:qa,paneMaxWidth:qa,paneMinWidth:qa,expandedPanelWidth:qa,resizableMinWidth:qa,resizableMaxWidth:qa,expandLauncherPanelWhenOpen:zr,resizable:zr},IL={kind:"object",message:"Expected a preference object.",children:{showToolCalls:zr,showReasoning:zr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:cu},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:cu},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:cu},expandable:zr,grouped:zr}},reasoningDisplay:{kind:"object",children:{expandable:zr,activePreview:zr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:qA,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:qA,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:jA,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:jA}}},filePreview:{kind:"object",children:{enabled:zr}},layout:{kind:"object",children:HL}}}}};function zA(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:ar(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:ar(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:ar(o,n,"invalid_value",t.message);case"mode":return mh(e)?Yn(e):ar(o,n,"invalid_value",t.message);case"modeMap":{if(!Ii(e))return ar(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:vs(i);du(i)&&(r?r.has(i):TL.test(c))?mh(l)?s[c]=Yn(l):ar(o,`${n}.${i}`,"invalid_value",PL):ar(o,`${n}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":LL)}return Ri(s)?s:void 0}case"object":{if(t.bareMode&&mh(e))return Yn(e);if(!Ii(e))return ar(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))(!du(l)||!r.includes(l))&&ar(o,s(l),"unknown_key",kL);let i={};for(let l of r){let c=t.children[l],p=zA(e[l],c,s(l),o);if(c.deprecated&&e[l]!==void 0&&ar(o,s(l),"deprecated_key",c.deprecated),p===void 0)continue;let d=c.alias??l,g=i[d];i[d]=Ii(g)&&Ii(p)?{...g,...p}:p}return Ri(i)?i:void 0}}}function hh(e){let t=[];return{preferences:(e===null?void 0:zA(e,IL,"",t))??{},issues:t}}function za(e){if(Array.isArray(e))return e.map(za);if(!Ii(e))return e;let t={};for(let[n,o]of Object.entries(e))du(n)&&o!==void 0&&(t[n]=za(o));return t}function KA(e,t){let n=za(e);for(let[o,r]of Object.entries(t)){if(!du(o)||r===void 0)continue;let s=n[o];n[o]=Ii(s)&&Ii(r)?KA(s,r):za(r)}return n}function RL(e){let t={},n;for(let r of e){let s=hh(r).preferences;n=GA(n,s.artifacts?.display),t=KA(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function WL(e,t){if(t===void 0)return e===void 0?void 0:za(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}:{},...Ri(r)?{byMediaType:r}:{}};return Ri(s)?s:void 0}function GA(e,t){if(t===void 0)return e===void 0?void 0:za(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=WL(n.files,t.files),i={...o?{default:o}:{},...Ri(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Ri(i)?i:void 0}function yh(e={},t){let n=RL(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=GA(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 uc(e){let t=e.preferences;return!t||!Ri(t)?e:{...e,features:yh(e.features??{},[t])}}function OL(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 _L(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 BL(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function DL(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function bh(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 YA(e,t,n,o,r,s,i=200){let l=OL(r,200),c=DL(t,n,o,i);c=Math.max(l,c);let p=_L(s);return p!==null&&(c=Math.min(c,p)),BL(e,l,c)}dn();var{setLoader:b1,load:NL,provide:v1,getSync:FL}=lt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")});var XA=NL;var QA=FL;var vh=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()}},gc=new vh;So();So();Ea();Rf();var JA=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$L=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),ZA=(e,t,n)=>{if(!JA(e)||!JA(t)||$L.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]=ZA(e[r],t[r],s)}return o};function pu(e,t){let n=zd(bi),o=bC(e,t,n),r=Hf(vC(ZA(e,t,""),n,o),o);return Of(Ma(r),wC(e,t))}Ea();var ex=()=>{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 UL=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},VL=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},fc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=UL(e),n=VL(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}},Ch=e=>typeof e=="string"?e:e==null?"":String(e),Wi={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ch(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Ch(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:Ch(n.text)}}},tx=e=>Array.isArray(e)?e.map(t=>String(t)):[],mc=e=>{let t=new Set(tx(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(tx(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 jL=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}},qL=e=>e.map(t=>({...t,streaming:!1})),zL=e=>e.map(t=>({...t,status:"complete"})),uu=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?jL(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?qL(n.messages):void 0,artifacts:n.artifacts?zL(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 KL=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")},nx=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 KL(e)},GL=async(e,t)=>{let n=await nx(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await nx(`${e}\0${t}`)}`}};var ox=(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 X=p;p=W,c+=1;let M={previousToken:X,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 GL(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 X=JSON.parse(j);return typeof X?.expiresAt=="number"&&typeof X?.ownerNonce=="string"?X: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 X=setTimeout(M,W);function M(){clearTimeout(X),H.delete(M),window.removeEventListener("storage",T),j()}function T(_){(_.key===null||_.key===r)&&M()}H.add(M),window.addEventListener("storage",T)}),oe=async W=>{let j=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,X=Date.now()+15e3;for(;!l&&Date.now()<X;){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()?oe(W):B(W)},matches(W,j,X){return W===e&&j===t&&X===n},destroy(){l=!0,g.clear(),typeof window<"u"&&window.removeEventListener("storage",b),d&&I(d);for(let W of[...H])W()}}};dn();var{setLoader:H1,load:YL}=lt({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var rx=YL;var XL=null;function sx(){return XL}var Ka=require("partial-json");function QL(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function JL(e,t){if(!QL(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 gu(){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=(0,Ka.parse)(n,Ka.STR|Ka.OBJ),s=JL(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function ix(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}Ze();function fu(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Fo.get(e.component);if(!s){if(ph.includes(e.component)){lu().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 ax(){let e=gu();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function lx(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 hc(e){let t=lx(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 mu(e){let t=lx(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 ZL=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function hu(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=ZL}=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 oe=document.createElement("button");oe.type="button",oe.className="persona-feedback-rating-btn persona-feedback-star-btn",oe.setAttribute("role","radio"),oe.setAttribute("aria-checked","false"),oe.setAttribute("aria-label",`${V} star${V>1?"s":""}: ${p[V-1]}`),oe.title=p[V-1],oe.dataset.rating=String(V),oe.innerHTML=`
42
+ `):""},ih=(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)"},vL=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??Br.collapsedMode,s=n?.success===!1?n.error||"Tool failed":bL(e,o?.previewMaxLines??Br.previewMaxLines),i=n?Ts(t,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:Cv(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=cf(n,c.activeTextTemplate,p):!l&&c.completeTextTemplate&&(p=cf(n,c.completeTextTemplate,p)),n.success===!1?p+=" \xB7 Failed":n.superseded&&(p+=" \xB7 Approved, ran again below"),{summary:p,previewText:s,isActive:l}},ah=(e,t,n,o)=>{Tp(e,t,{stateSet:n,previewKind:"tool",iconColor:BA(o?.toolCall??{},t.classList.contains("persona-activity-row"))})},lh=(e,t,n=new Set)=>{t=kp(t,"tool");let o=e.toolCall,r=t?.toolCall??{},s=Ap("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 $r(s,e,t,"tool");let i=t?.features?.toolCallDisplay??{},l=i.expandable??Br.expandable,c=l&&n.has(e.id),{summary:p,previewText:d,isActive:g}=vL(e,t),f=xp({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=Pl(o),T},A=r.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:p,previewText:d,collapsedMode:i.collapsedMode??Br.collapsedMode,isActive:g,config:t??{},elapsed:Pl(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??Br.loadingAnimation,I=r.activeTextTemplate,H=r.completeTextTemplate,B=g?I:H,V=A instanceof HTMLElement,oe=(T,_)=>{y.textContent="";let P=o.name?.trim()||"tool",J=Td(T,P),U=0;for(let ue of J){let fe=ue.styles.length>0?(()=>{let me=x("span",ue.styles.map(He=>`persona-tool-text-${He}`).join(" "));return y.appendChild(me),me})():y;if(ue.isDuration&&g)fe.appendChild(C());else{let me=ue.isDuration?Pl(o):ue.text;_?U=Va(fe,me,U):fe.appendChild(document.createTextNode(me))}}};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&&oe(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)oe(B,!0);else{let _=y.textContent||p;y.textContent="",Va(y,_,0)}}else B&&oe(B,!1);let W=BA(r,Ts(t,"tool")==="row"),j=La(f,h,{expandable:l,expanded:c,iconColor:W,metaGap:!0}),X=Ep({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,X),$r(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)OA(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 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",ih(P,r),P.textContent=ya(o.args),T.append(_,P),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 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",ih(P,r),P.textContent=o.chunks.join(""),T.append(_,P),M.appendChild(T)}if(o.success===!1&&M.appendChild(Q("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 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",ih(P,r),P.textContent=ya(o.result),T.append(_,P),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 Mp({expanded:c,header:f,toggleIcon:j,content:M,collapsedPreview:X,iconColor:W}),s.append(f,X,M),$r(s,e,t,"tool")};Rl();Ca();Cs();dn();var{setLoader:e1,load:CL,provide:t1,getSync:wL}=lt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")});var DA=CL;var NA=wL;pi();dn();var{setLoader:r1,load:SL}=lt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var ch=SL;dn();var dh=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)})}},Fo=new dh;tf();var ph=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:p1,load:AL,provide:u1,getSync:xL}=lt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),ja=null,au=new Set,FA=e=>{if(ja)return ja;ja=e,e.initArtifactsUi({componentRegistry:Fo});for(let o of ph)Fo.has(o)||Fo.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=nr();t?e.__provideMarkdownParsers(t):ua(()=>{let o=nr();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>Cd());let n=[...au];au.clear();for(let o of n)try{o()}catch{}return e};var lu=()=>AL().then(FA);var qr=()=>{if(ja)return ja;let e=xL();return e?FA(e):null},uh=e=>ja?()=>{}:(au.add(e),()=>{au.delete(e)});function $n(e){return e?.features?.artifacts?.enabled===!0}function $A(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"),!$n(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 EL(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 UA=["panel","seamless","detached"];function gh(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&UA.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function fh(e){return!e||!$n(e)?!1:gh(e)==="detached"}function dc(e,t){if(!$n(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"),EL(e),$A(e,t);return}let n=t.features?.artifacts?.layout,o=gh(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)}$A(e,t)}function pc(e,t){for(let l of UA)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"),!$n(t))return;let n=t.features?.artifacts?.layout,o=gh(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 VA(e,t){return!t||!$n(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}ha();ha();var ML=new Set(["__proto__","prototype","constructor"]),TL=new Set(["collapsed","card","panel","inline"]),jA=new Set(["markdown","component"]),PL=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Ii=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),du=e=>!ML.has(e),mh=e=>typeof e=="string"&&TL.has(e),Ri=e=>Object.keys(e).length>0;function ar(e,t,n,o){e.push({path:t,code:n,message:o})}var kL="Ignored because this key is not part of the persisted preference schema.",cu="Ignored an unsupported value.",LL="Expected collapsed, panel, or inline.",HL='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',qA={kind:"mode",message:cu},qa={kind:"string",message:"Expected a CSS length string."},zr={kind:"boolean"},IL={paneWidth:qa,paneMaxWidth:qa,paneMinWidth:qa,expandedPanelWidth:qa,resizableMinWidth:qa,resizableMaxWidth:qa,expandLauncherPanelWhenOpen:zr,resizable:zr},RL={kind:"object",message:"Expected a preference object.",children:{showToolCalls:zr,showReasoning:zr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:cu},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:cu},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:cu},expandable:zr,grouped:zr}},reasoningDisplay:{kind:"object",children:{expandable:zr,activePreview:zr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:qA,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:qA,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:jA,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:jA}}},filePreview:{kind:"object",children:{enabled:zr}},layout:{kind:"object",children:IL}}}}};function zA(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:ar(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:ar(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:ar(o,n,"invalid_value",t.message);case"mode":return mh(e)?Yn(e):ar(o,n,"invalid_value",t.message);case"modeMap":{if(!Ii(e))return ar(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:vs(i);du(i)&&(r?r.has(i):PL.test(c))?mh(l)?s[c]=Yn(l):ar(o,`${n}.${i}`,"invalid_value",LL):ar(o,`${n}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":HL)}return Ri(s)?s:void 0}case"object":{if(t.bareMode&&mh(e))return Yn(e);if(!Ii(e))return ar(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))(!du(l)||!r.includes(l))&&ar(o,s(l),"unknown_key",kL);let i={};for(let l of r){let c=t.children[l],p=zA(e[l],c,s(l),o);if(c.deprecated&&e[l]!==void 0&&ar(o,s(l),"deprecated_key",c.deprecated),p===void 0)continue;let d=c.alias??l,g=i[d];i[d]=Ii(g)&&Ii(p)?{...g,...p}:p}return Ri(i)?i:void 0}}}function hh(e){let t=[];return{preferences:(e===null?void 0:zA(e,RL,"",t))??{},issues:t}}function za(e){if(Array.isArray(e))return e.map(za);if(!Ii(e))return e;let t={};for(let[n,o]of Object.entries(e))du(n)&&o!==void 0&&(t[n]=za(o));return t}function KA(e,t){let n=za(e);for(let[o,r]of Object.entries(t)){if(!du(o)||r===void 0)continue;let s=n[o];n[o]=Ii(s)&&Ii(r)?KA(s,r):za(r)}return n}function WL(e){let t={},n;for(let r of e){let s=hh(r).preferences;n=GA(n,s.artifacts?.display),t=KA(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function OL(e,t){if(t===void 0)return e===void 0?void 0:za(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}:{},...Ri(r)?{byMediaType:r}:{}};return Ri(s)?s:void 0}function GA(e,t){if(t===void 0)return e===void 0?void 0:za(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=OL(n.files,t.files),i={...o?{default:o}:{},...Ri(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Ri(i)?i:void 0}function yh(e={},t){let n=WL(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=GA(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 uc(e){let t=e.preferences;return!t||!Ri(t)?e:{...e,features:yh(e.features??{},[t])}}function _L(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 BL(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 DL(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function NL(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function bh(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 YA(e,t,n,o,r,s,i=200){let l=_L(r,200),c=NL(t,n,o,i);c=Math.max(l,c);let p=BL(s);return p!==null&&(c=Math.min(c,p)),DL(e,l,c)}dn();var{setLoader:v1,load:FL,provide:C1,getSync:$L}=lt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")});var XA=FL;var QA=$L;var vh=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()}},gc=new vh;So();So();Ea();Rf();var JA=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),UL=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),ZA=(e,t,n)=>{if(!JA(e)||!JA(t)||UL.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]=ZA(e[r],t[r],s)}return o};function pu(e,t){let n=zd(bi),o=bC(e,t,n),r=Hf(vC(ZA(e,t,""),n,o),o);return Of(Ma(r),wC(e,t))}Ea();var ex=()=>{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 VL=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},jL=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},fc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=VL(e),n=jL(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}},Ch=e=>typeof e=="string"?e:e==null?"":String(e),Wi={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ch(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Ch(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:Ch(n.text)}}},tx=e=>Array.isArray(e)?e.map(t=>String(t)):[],mc=e=>{let t=new Set(tx(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(tx(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 qL=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}},zL=e=>e.map(t=>({...t,streaming:!1})),KL=e=>e.map(t=>({...t,status:"complete"})),uu=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?qL(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?zL(n.messages):void 0,artifacts:n.artifacts?KL(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 GL=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")},nx=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 GL(e)},YL=async(e,t)=>{let n=await nx(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await nx(`${e}\0${t}`)}`}};var ox=(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 X=p;p=W,c+=1;let M={previousToken:X,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 YL(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 X=JSON.parse(j);return typeof X?.expiresAt=="number"&&typeof X?.ownerNonce=="string"?X: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 X=setTimeout(M,W);function M(){clearTimeout(X),H.delete(M),window.removeEventListener("storage",T),j()}function T(_){(_.key===null||_.key===r)&&M()}H.add(M),window.addEventListener("storage",T)}),oe=async W=>{let j=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,X=Date.now()+15e3;for(;!l&&Date.now()<X;){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()?oe(W):B(W)},matches(W,j,X){return W===e&&j===t&&X===n},destroy(){l=!0,g.clear(),typeof window<"u"&&window.removeEventListener("storage",b),d&&I(d);for(let W of[...H])W()}}};dn();var{setLoader:I1,load:XL}=lt({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var rx=XL;var QL=null;function sx(){return QL}var Ka=require("partial-json");function JL(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function ZL(e,t){if(!JL(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 gu(){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=(0,Ka.parse)(n,Ka.STR|Ka.OBJ),s=ZL(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function ix(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}Ze();function fu(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Fo.get(e.component);if(!s){if(ph.includes(e.component)){lu().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 ax(){let e=gu();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function lx(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 hc(e){let t=lx(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 mu(e){let t=lx(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 eH=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function hu(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=eH}=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 oe=document.createElement("button");oe.type="button",oe.className="persona-feedback-rating-btn persona-feedback-star-btn",oe.setAttribute("role","radio"),oe.setAttribute("aria-checked","false"),oe.setAttribute("aria-label",`${V} star${V>1?"s":""}: ${p[V-1]}`),oe.title=p[V-1],oe.dataset.rating=String(V),oe.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
- `,oe.addEventListener("click",()=>{g=V,A.forEach((W,j)=>{let X=j<V;W.classList.toggle("selected",X),W.setAttribute("aria-checked",j===V-1?"true":"false")})}),A.push(oe),C.appendChild(oe)}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 yu(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 oe=null;if(c){let M=document.createElement("div");M.className="persona-feedback-comment-container",oe=document.createElement("textarea"),oe.className="persona-feedback-comment",oe.placeholder=s,oe.rows=3,oe.setAttribute("aria-label","Additional comments"),M.appendChild(oe),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 X=document.createElement("button");return X.type="button",X.className="persona-feedback-btn persona-feedback-btn-submit",X.textContent=i,X.addEventListener("click",async()=>{if(f===null){B.classList.add("persona-feedback-shake"),setTimeout(()=>B.classList.remove("persona-feedback-shake"),500);return}X.disabled=!0,X.textContent="Submitting...";try{let M=oe?.value.trim()||void 0;await t(f,M),g.remove()}catch(M){X.disabled=!1,X.textContent=i,console.error("[NPS Feedback] Failed to submit:",M)}}),W.appendChild(j),W.appendChild(X),h.appendChild(W),g.appendChild(h),g}var Ga="persona-chat-history",nH=30*1e3,oH="Tap the mic to resume your voice call",rH=641,Ya="data-persona-composer-reason",yc="data-persona-composer-notice",sH={"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 iH(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=sH[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 bu(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 aH(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 lH(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var wh=e=>!e||typeof e!="object"?{}:{...e},cx=e=>e.map(t=>({...t,streaming:!1})),dx=(e,t,n)=>{let o=e?.markdown?jl(e.markdown):null,r=Lp(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=nr()!==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?bw(c):c,h=o(f);g=r&&d?r(h):h}else g=Ur(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)),Ur(l.text??"")}}};function px(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=ge(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 cH=(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},dH=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:cH(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),vu=(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=Ma(t),r=new Set,s=new Set,i=iw((a,u)=>{Mn.delete(a);let m=Array.from(Te.querySelectorAll("[data-message-id]")).find(v=>v.dataset.messageId===a);m&&(u==="tool"?ah(a,m,r,o):oh(a,m,s))}),l=new Map,c=()=>{uC({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};c();let p=o.features;o=uc(o);let d=gc.getForInstance(o.plugins),g=ZC(e),f=[],h=!1,y=RA(()=>o),b=null,C=null,A=null,L=!1,I=null,H=a=>{b=a,a.initApprovalUi({webMcpToolTitle:ma});let u=a.createBuiltInApprovalPlugin(l);C=u.plugin,A=u.teardown},B=()=>{if(b)return b;let a=NA();return a?(H(a),a):(DA().then(u=>{L||b||(H(u),I?.())}).catch(()=>{}),null)},V=!1,oe=!1,W=null,j=(a,u,m,v)=>{if(!a.querySelector("[data-tv-form]"))return;let w=QA();if(w){w.enhanceWithForms(a,u,m,v);return}XA().then(()=>{V||oe||!W||(oe=!0,W())}).catch(()=>{})};o.components&&Fo.registerAll(o.components);let X=ex(),T=o.persistState===!1?null:o.storageAdapter??uu(),_=!!o.clientToken&&typeof o.reconnectStream!="function",k={},J=null,U,ue=new Promise(a=>{U=a}),fe=()=>{},me=new Promise(a=>{fe=a}),He,Ee=!1,Ie=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&&(Ee=!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")J=a.then(u=>Ie(u??{messages:[],metadata:{}}));else{let m=Ie(a??{messages:[],metadata:{}});m.metadata&&(k=wh(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null}),He=m.draft}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=Ie({messages:[],metadata:{}});a.messages?.length&&(o={...o,initialMessages:a.messages})}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}J||U();let yt=()=>k,qe=a=>{k=a({...k})??{},Ji()},Oe=o.actionParsers&&o.actionParsers.length?o.actionParsers:[fc],$=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Wi.message,Wi.messageAndClick],_e=mc({parsers:Oe,handlers:$,getSessionMetadata:yt,updateSessionMetadata:qe,emit:X.emit,documentRef:typeof document<"u"?document:null});_e.syncFromMetadata();let ye=o.launcher?.enabled??!0,ut=o.launcher?.autoExpand??!1,Zt=o.autoFocusInput??!1,xt=ut,xe=ye,Wt=o.layout?.header?.layout,vt=!1,Le=()=>Rs(o),Xe=()=>ye||Le(),D=Le()?!1:ye?ut:!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=dx(o,_e,q),te=o.features?.showReasoning??!0,ve=o.features?.showToolCalls??!0,Me=o.features?.showEventStreamToggle??!1,Ce=o.features?.scrollToBottom??{},st=o.features?.scrollBehavior??{},Ct=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Qe=`${Ct()}event-stream`,pn=null,Eo=o.features?.eventStream?.maxEvents??2e3,ft=null,bt=null,Ft=null,_i=!1,rn=null,Sn=!1,lo=null,Bi=0,Di=(a,u)=>{ft?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(u)})},Qa=(a,u)=>{bt?.processEvent(a,u),ft?Di(a,u):Ft&&(Ft.length>=Eo&&Ft.shift(),Ft.push({type:a,payload:u}))},cr=()=>{ft||!Me||(Ft??=[],ch().then(a=>{if(_i||ft||!Me)return;pn=new a.EventStreamStore(Qe),ft=new a.EventStreamBuffer(Eo,pn),bt=bt??new a.ThroughputTracker,pn.open().then(()=>ft?.restore()).catch(m=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",m)});let u=Ft??[];Ft=null;for(let m of u)bt?.processEvent(m.type,m.payload),Di(m.type,m.payload)}).catch(()=>{}))};Me&&cr();let un=!1,Un=null,dr=()=>{},Vn=()=>{},pr=()=>{},Uo=()=>{},Yr=()=>{},wc=()=>Sn||un&&Un==="panel",to={onCopy:a=>{X.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=>{X.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)}},$h=o.statusIndicator??{},ur=(a,u=o.statusIndicator??{})=>a==="idle"?u.idleText??Yt.idle:a==="connecting"?u.connectingText??Yt.connecting:a==="connected"?u.connectedText??Yt.connected:a==="error"?u.errorText??Yt.error:a==="paused"?u.pausedText??Yt.paused:a==="resuming"?u.resumingText??Yt.resuming:Yt[a];function _s(a,u,m,v){if(!Le()&&(m.mode==="transient"||a.classList.contains("persona-mb-2"))&&(Tf(a,An,m),hi(a,m,v)),!(a.hasAttribute(Ya)||a.hasAttribute(yc)))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 Ln=IA({config:o,showClose:Xe()}),{wrapper:Je,panel:Ae,pillRoot:Xt}=Ln.shell,et=Ln.panelElements,{container:we,body:ae,messagesWrapper:Te,starterSuggestions:gr,transcriptSuggestions:Xr,suggestions:co,textarea:ce,sendButton:ke,composerForm:An,statusText:tt,welcomeHost:en,welcomeIconHolder:Sc,greetingHost:Rn,introKicker:Ac,introTitle:Bu,introSubtitle:Ni,closeButton:ze,iconHolder:Ht,headerTitle:Vo,headerSubtitle:jo,header:mt,footer:Ke,actionsRow:Fi}=et,xn=et.leftActions,Bs=et.rightActions,Wn=et.sendButtonWrapper,xc=et.setSendButtonMode,he=et.micButton,gn=et.micButtonWrapper,It=et.attachmentButton,sn=et.attachmentButtonWrapper,Et=et.attachmentInput,fn=et.attachmentPreviewsContainer;we.classList.add("persona-relative"),ae.classList.add("persona-relative");let Ec=12,Qr=()=>Ce.label??"",Du=()=>Ce.iconName??"arrow-down",Nu=()=>Ce.enabled!==!1,En=()=>st.mode??"anchor-top",Mo=()=>En()==="follow"||En()==="anchor-top"&&ll,Ds=()=>st.anchorTopOffset??16,Mc=()=>st.restorePosition??"bottom",Ja=()=>st.pauseOnInteraction===!0,Za=()=>st.showActivityWhilePinned!==!1,$i=()=>st.announce===!0,Ns=()=>st.scrollbar??"on-scroll",Vt=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");Vt.type="button",Vt.style.display="none",Vt.setAttribute("data-persona-scroll-to-bottom","true");let Fs=x("span","persona-flex persona-items-center"),el=x("span",""),tn=x("span","");tn.setAttribute("data-persona-scroll-to-bottom-count",""),tn.style.display="none",Vt.append(Fs,el,tn),we.appendChild(Vt);let Qt=x("div","persona-stream-anchor-spacer");Qt.setAttribute("aria-hidden","true"),Qt.setAttribute("data-persona-anchor-spacer",""),Qt.style.flexShrink="0",Qt.style.pointerEvents="none",Qt.style.height="0px",Qt.style.display="none",ae.appendChild(Qt);let To=x("div","persona-sr-only");To.setAttribute("aria-live","polite"),To.setAttribute("aria-atomic","true"),To.setAttribute("role","status"),To.setAttribute("data-persona-live-region",""),Object.assign(To.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"}),we.appendChild(To);let Jr=null,fr=null,$s=a=>{!$i()||!a||(fr=a,Jr===null&&(Jr=setTimeout(()=>{Jr=null,fr&&$i()&&(To.textContent=fr),fr=null},400)))},jn=()=>{let a=e.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&a.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(ye||Lt(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!Lt(o)},E=()=>Ua(o,jn()),N="empty",ne=0,pe=()=>ne||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,Re=()=>{let u=Ke.style.display==="none"?0:Ke.offsetHeight;Vt.style.bottom=`${u+pe()+Ec}px`};Re();let $t=()=>{Ki||(Ke.style.marginBottom=ne>0?`${ne}px`:"")},Ot=()=>{let a=km(o,Le()),u=E();e.setAttribute("data-persona-welcome-fullscreen",String(jn())),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=Ke.style.display==="none"?0:Ke.offsetHeight,w=u.anchor==="center"&&N==="empty"?Ql(u.anchorComposerTop)??Ql("44%"):null,P=w!==null&&u.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,z=P?getComputedStyle(ae):null,re=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,Y=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,ie=Math.max(0,(parseFloat(z?.paddingBottom??"")||0)-(a==="overlay"?re+Y:0)),le=P?ae.getBoundingClientRect().top-we.getBoundingClientRect().top:0,de=!P||en.hidden?0:(en.querySelector("[data-persona-welcome-plugin]")??en).offsetHeight,Pe=w===null||Le()?0:P?Math.max(0,Math.round((we.clientHeight-le-de-ie-v)/2)):_S({columnHeight:we.clientHeight,footerHeight:v,fraction:w});e.style.setProperty("--persona-composer-overlay-height",`${v}px`),e.style.setProperty("--persona-composer-lift",`${a==="overlay"?Pe:0}px`),ne=a==="block"?Pe:0,$t(),Re()},_t=()=>{let a=!!Qr();Vt.setAttribute("aria-label",Qr()||"Jump to latest"),Vt.title=Qr(),Vt.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),Fs.innerHTML="";let u=ge(Du(),"14px","currentColor",2);u?(Fs.appendChild(u),Fs.style.display=""):Fs.style.display="none",el.textContent=Qr(),el.style.display=a?"":"none"};_t();let je=null,at=null,be=zw(),Ui=a=>{try{we.dispatchEvent(new CustomEvent("persona:composer:state",{detail:a,bubbles:!0,composed:!0}))}catch{}};be.subscribe(Ui);let po=()=>{be.setText(ce?.value??"")},mr=()=>{be.setMentionRefs(at?.getMentionRefs()??[])},aE=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}),Uh=a=>{let u=Object.freeze(a.map(aE));be.setAttachments(u);try{o.attachments?.onChange?.(u)}catch(m){console.error("[AgentWidget] attachments.onChange failed:",m)}bg()};be.setSelectedModelId(o.composer?.selectedModelId);let tl=()=>o.composer?.modes??[],Vi=()=>lS(tl(),o.composer?.modeGroups);{let a=Dp(o.composer?.defaultActiveModeIds??[],tl());a.length&&be.setActiveModeIds(a)}function Vh(a){if(be.getState().selectedModelId!==a){be.setSelectedModelId(a),Zr?.repaint();try{o.composer?.onModelChange?.(a)}catch(u){console.error("[AgentWidget] composer.onModelChange failed:",u)}}}function Tc(a){be.setActiveModeIds(a),hr?.render(a,Vi()),ji.forEach(u=>u.repaint()),ko?.resolve(),ed(),Po()}function Fu(a){Tc(cS(be.getState().activeModeIds,a,tl(),o.composer?.modeGroups))}let Zr=null,$u=null,hr=null,ji=new Map,es=null;function qo(a){be.setQuote(a),es?.render(be.getState().quote),Po(),_y()}let jh=!1;function Uu(){let a=o.composer?.streamingSubmitBehavior??"block";return a!=="interrupt"?a:o.clientToken?"interrupt":(!jh&&o.debug===!0&&(jh=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let ts=null;function qi(a){be.setPendingSubmission(a),ts?.render(be.getState().pendingSubmission),Po()}let lE=a=>{let u=ji.get(a);if(u)return u;let m=uS({groupId:a,getGroup:()=>o.composer?.modeGroups?.find(v=>v.id===a),getModes:()=>tl().filter(v=>v.groupId===a),getActiveIds:()=>be.getState().activeModeIds,onSelect:v=>Fu(v)});return ji.set(a,m),m},cE=()=>{let a=[],u=be.getState().activeModeIds,m=new Set;if(tl().forEach((v,w)=>{if(Bp(v.groupId,o.composer?.modeGroups)){let P=v.groupId;if(m.has(P))return;m.add(P);let z=lE(P);z.action.order=Sm(w),z.action.label=o.composer?.modeGroups?.find(re=>re.id===P)?.label??P,a.push(z.action);return}a.push({id:iS(v.id),kind:"button",placement:"start",order:Sm(w),presentation:v.presentation??"auto",label:v.label,shortLabel:v.shortLabel,iconName:v.iconName,pressed:u.includes(v.id),onSelect:()=>Fu(v.id)})}),o.composer?.models?.length&&!d.some(v=>v.renderComposer)){let v=o.composer?.modelPicker?.presentation??"native";(!Zr||$u!==v)&&($u=v,Zr=rS({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>be.getState().selectedModelId,onSelect:w=>Vh(w),presentation:v,getSuffix:()=>o.composer?.modelPicker?.suffix})),a.push(Zr.action)}return a},Vu=null,qh=d.find(a=>a.renderHeader);if(qh?.renderHeader){let a=qh.renderHeader({config:o,defaultRenderer:()=>{let u=jr({config:o,showClose:Xe()});return Ti(we,u,o),u.header},onClose:()=>Mt(!1,"user")});if(a){let u=mt;u&&(u.replaceWith(a),mt=a,Ln.header.element=a)}}let zh=()=>{rn&&(ae.style.display="none",Ke.parentNode?.insertBefore(rn.element,Ke),rn.update())},ju=()=>{if(!ft){cr();return}if(Sn=!0,rn?zh():ch().then(u=>{rn||!Sn||!ft||(rn=u.createEventStreamView({buffer:ft,getFullHistory:()=>ft.getAllFromStore(),onClose:()=>zi(),config:o,plugins:d,getThroughput:()=>bt?.getMetric()??{status:"idle"},renderIconByName:ge}),zh())}).catch(()=>{zi()}),ht){ht.style.boxShadow=`inset 0 0 0 1.5px ${Nn.actionIconColor}`;let u=o.features?.eventStream?.classNames?.toggleButtonActive;u&&u.split(/\s+/).forEach(m=>m&&ht.classList.add(m))}let a=()=>{if(!Sn)return;let u=Date.now();u-Bi>=200&&(rn?.update(),Bi=u),lo=requestAnimationFrame(a)};Bi=0,lo=requestAnimationFrame(a),Tn(),X.emit("eventStream:opened",{timestamp:Date.now()})},zi=()=>{if(Sn){if(Sn=!1,rn&&rn.element.remove(),ae.style.display="",ht){ht.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(u=>u&&ht.classList.remove(u))}lo!==null&&(cancelAnimationFrame(lo),lo=null),Tn(),X.emit("eventStream:closed",{timestamp:Date.now()})}},ht=null;if(Me){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:"");ht=x("button",u),ht.style.width="28px",ht.style.height="28px",ht.style.color=Nn.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let m=Nt(Kr.Activity,"18px","currentColor",1.5);m&&ht.appendChild(m);let v=et.clearChatButtonWrapper,w=et.closeButtonWrapper,P=v||w;P&&P.parentNode===mt?mt.insertBefore(ht,P):mt.appendChild(ht),ht.addEventListener("click",()=>{Sn?zi():ju()})}let Kh=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??Dr).join(","),w.multiple=(u.maxFiles??4)>1,w.style.display="none",w.setAttribute("aria-label",u.buttonTooltipText??"Attach files"),a.appendChild(w)}},Ki=!1,Gh=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:()=>qb(),storage:y(u.id),onSubmit:w=>{!R||R.isStreaming()||cd(w.trim(),{consumeDraft:!1})},streaming:v,disabled:v,openAttachmentPicker:()=>{Yo()||Et?.click()},models:m?.models,selectedModelId:be.getState().selectedModelId??m?.selectedModelId,onModelChange:w=>Vh(w),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Vu?.()}:void 0})},Yh=Gh(()=>Pi({config:o}).footer);Yh&&(Ln.replaceComposer(Yh),Ke=Ln.composer.footer,Ki=!0);let ct=null,dE=a=>{An=a.form,ce=a.input,Wn=a.sendButton?a.sendButton.parentElement:null,a.sendButton&&(ke=a.sendButton),a.micButton&&(he=a.micButton,gn=a.micButton.parentElement),a.found.status&&(tt=a.found.status),a.found.suggestions&&(co=a.found.suggestions),a.attachmentButton&&(It=a.attachmentButton,sn=a.attachmentButton.parentElement),Et=a.attachmentInput??null,fn=a.attachmentPreviews??null,a.found.actionsRow&&(Fi=a.found.actionsRow),xn=a.found.actionsStart,Bs=a.found.actionsEnd};function qu(){let a=ce;if(!a)return;let u=o.composer?.inputAttributes,m=!u?.ariaLabel&&!(a instanceof HTMLTextAreaElement)?a.getAttribute("aria-label"):null;Zd(a,u),m&&a.setAttribute("aria-label",m),Jd(a,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Bl(a)}),OC(a,Qd(o.composer?.maxLines,Le()?5:3))}let Xh=a=>{ct=Gw(a,{debug:o.debug===!0}),ct&&dE(ct),qu()};Kh(Ke),Xh(Ke),po();let nl=Hs(o,Le());nl&&(Te.style.maxWidth=nl,Te.style.marginLeft="auto",Te.style.marginRight="auto",Te.style.width="100%",Rn.style.maxWidth=nl,Rn.style.marginLeft="auto",Rn.style.marginRight="auto",Rn.style.width="100%",gr.style.maxWidth=nl,Xr.style.maxWidth=nl,Xr.style.marginLeft="auto",Xr.style.marginRight="auto",Xr.style.width="100%");let Qh=()=>{let a=Hs(o,Le());if(!(!a||Le()))for(let u of[An,co,fn,tt])u&&(u.style.maxWidth=a,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%")};Qh();let Jh=()=>{!o.attachments?.enabled||!Et||!fn||(je?je.remountPreviews(fn):(je=Ai.fromConfig(o.attachments,Uh),je.setPreviewsContainer(fn)),ct?.addListener(Et,"change",a=>{let u=a.target;je?.handleFileSelect(u.files),u.value=""}),we.querySelector(".persona-attachment-drop-overlay")||we.appendChild(px(o.attachments.dropOverlay)))};Jh();let pE=()=>at?.prefetch(),zu=()=>{if(!o.contextMentions?.enabled||!ce)return;let a=Gf();if(!a){let v=ce;pp().then(()=>{at||ce!==v||!v.isConnected||(zu(),ko?.resolve())},()=>{});return}let u=ct?.header??null,m=u?wm(u):void 0;if(at=a.createContextMentionOrchestrator({deps:{loadContextMentions:lp,loadContextMentionsInline:cp,renderLucideIcon:ge,createMentionButton:ap},config:o,textarea:ce,anchor:An??ce,getMessages:()=>R.getMessages(),liveRegionHost:we,chipRow:m}),at&&!m){let v=ce;v.parentElement?.insertBefore(at.contextRow,v)}};zu();let ko=null,uE={getState:()=>be.getState(),getValue:()=>ce?.value??"",setValue:a=>{ce&&(ce.value=a,ce.dispatchEvent(new Event("input",{bubbles:!0})),po())},submit:()=>{SS(ct?.form??null)},openAttachmentPicker:()=>{Yo()||Et?.click()},toggleVoice:()=>{Vu?.()},requestRender:()=>ko?.resolve()},gE=()=>{let a=[];return(at?.affordanceButtons??[]).forEach((m,v)=>{a.push({id:`core:mention-${v}`,placement:"start",order:sr.mention+v,element:m,managed:!0})}),sn&&a.push({id:"core:attachment",placement:"start",order:sr.attachment,element:sn}),gn&&a.push({id:"core:mic",placement:"end",order:sr.mic,element:gn}),Wn&&a.push({id:"core:send",placement:"end",order:sr.send,element:Wn}),a},Zh=()=>{ko?.destroy(),ko=tS({getBindings:()=>ct,collect:()=>({builtIns:gE(),configActions:[...cE(),...o.composer?.actions??[]],plugins:d,contributionContext:{config:o,getState:()=>be.getState(),requestRender:()=>ko?.resolve()},debug:o.debug===!0}),actionContext:uE,getState:()=>be.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(a,u)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${u.actionId}" failed:`,a)}}),ko.resolve()};Zh();let Ku=()=>{if(hr?.destroy(),hr=null,!Vi().length)return;let a=ct?.header;a&&(hr=sS({row:wm(a),onRemove:u=>Fu(u),initialIds:be.getState().activeModeIds}),hr.render(be.getState().activeModeIds,Vi()))};Ku();let ey=()=>{es?.destroy(),es=null,ts?.destroy(),ts=null;let a=ct?.header;a&&(es=gS({onDismiss:()=>qo(void 0)}),a.appendChild(es.element),es.render(be.getState().quote),Uu()==="defer-one"&&(ts=fS({onEdit:()=>cM(),onRemove:()=>qi(void 0)}),a.appendChild(ts.element),ts.render(be.getState().pendingSubmission)))};ey();let Gu=CS(),fE=()=>{let a=ct?.header?.querySelector(Cm);if(a)return a.childElementCount>0;let u=be.getState();return u.mentionRefs.length>0||Dp(u.activeModeIds,Vi()).length>0};function Po(){let a=be.getState(),u=Gu.observe(wS(ce),a.text);Ke.toggleAttribute("data-persona-composer-compact",vS({text:a.text,wrapped:u,hasAttachments:a.attachments.length>0,hasChips:fE(),hasQuote:a.quote!==void 0,hasPendingSubmission:a.pendingSubmission!==void 0}))}function ty(){o.composer?.layout==="single-row"&&!Le()?Ke.setAttribute("data-persona-composer-layout","single-row"):Ke.removeAttribute("data-persona-composer-layout")}ty(),be.subscribe(()=>{ko?.sync(),bg(),Qc(),Po(),_y()}),Qc();let ny=!1,mE=a=>{if(ny||o.debug!==!0)return;let u=["messages","composer"].filter(m=>a[m]);u.length&&(ny=!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??{};mE(a);let u=v=>{switch(v){case"body-top":return ae.querySelector("[data-persona-intro-card]");case"messages":return Te;case"footer-top":return co;case"composer":return An;case"footer-bottom":return tt;default:return null}},m=(v,w)=>{switch(v){case"header-left":case"header-center":case"header-right":if(v==="header-left")mt.insertBefore(w,mt.firstChild);else if(v==="header-right")mt.appendChild(w);else{let P=mt.querySelector(".persona-flex-col");P?P.parentNode?.insertBefore(w,P.nextSibling):mt.appendChild(w)}break;case"body-top":{let P=ae.querySelector("[data-persona-intro-card]");P?P.replaceWith(w):ae.insertBefore(w,ae.firstChild);break}case"body-bottom":ae.appendChild(w);break;case"footer-top":co.replaceWith(w);break;case"footer-bottom":tt.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)}})(),Te.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(),_A(m))});let Yu=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;is(),ta();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),oh(w,v,s);else if(P==="tool")r.has(w)?r.delete(w):r.add(w),ah(w,v,r,o);else if(P==="approval"&&b){let re=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",Y=l.get(w)??re;l.set(w,!Y),b.updateApprovalDetailsUI(w,v,o,l)}Mn.delete(w)};Te.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Yu(a))}),Te.addEventListener("click",a=>{a.detail===0&&a.target.closest(".persona-activity-row")&&Yu(a)}),Te.addEventListener("keydown",a=>{let u=a.target;(a.key==="Enter"||a.key===" ")&&u.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Yu(a))}),Te.addEventListener("copy",a=>{let{clipboardData:u}=a;if(!u)return;let m=Te.getRootNode(),v=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let w=v.toString(),P=DS(w);!P||P===w||(u.setData("text/plain",P),a.preventDefault())});let Xu=new Map,oy=null,ry="idle",hE={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},yE=(a,u)=>{let{icon:m,label:v}=hE[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=ge(m,14,"currentColor",2);w&&(a.innerHTML="",a.appendChild(w))},sy=()=>{Te.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{let v=u.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;yE(u,v&&v===oy?ry:"idle")})};Te.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 re=R.getMessages().find(Y=>Y.id===w);if(re&&to.onCopy){let Y=re.content||"";navigator.clipboard.writeText(Y).then(()=>{m.classList.add("persona-message-action-success");let ie=Nt(Kr.Check,14,"currentColor",2);ie&&(m.innerHTML="",m.appendChild(ie)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let le=Nt(Kr.Copy,14,"currentColor",2);le&&(m.innerHTML="",m.appendChild(le))},2e3)}).catch(ie=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ie)}),to.onCopy(re)}}else if(P==="read-aloud")R.toggleReadAloud(w);else if(P==="upvote"||P==="downvote"){let re=(Xu.get(w)??null)===P,Y=P==="upvote"?"thumbs-up":"thumbs-down";if(re){Xu.delete(w),m.classList.remove("persona-message-action-active");let ie=ge(Y,14,"currentColor",2);ie&&(m.innerHTML="",m.appendChild(ie))}else{let ie=P==="upvote"?"downvote":"upvote",le=v.querySelector(`[data-action="${ie}"]`);if(le){le.classList.remove("persona-message-action-active");let dt=ge(ie==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);dt&&(le.innerHTML="",le.appendChild(dt))}Xu.set(w,P),m.classList.add("persona-message-action-active");let de=ge(Y,14,"currentColor",2);de&&(de.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(de)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let it=R.getMessages().find(gt=>gt.id===w);it&&to.onFeedback&&to.onFeedback({type:P,messageId:it.id,message:it})}}else if(P==="regenerate")kc?.regenerate(w);else if(P==="edit")kc?.edit(w);else if(P==="quote")kc?.quote(w);else if(P?.startsWith(ou)){let z=P.slice(ou.length),re=o.messageActions?.custom?.find(ie=>ie.id===z),Y=R.getMessages().find(ie=>ie.id===w);if(!re||!Y)return;try{re.onSelect(Y)}catch(ie){console.error(`[AgentWidget] messageActions.custom "${z}" onSelect failed:`,ie)}}});let kc=null;Te.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",Y=R.getMessages().find(le=>le.id===w);if(!Y?.approval)return;let ie=v.querySelector("[data-approval-buttons]");ie&&ie.querySelectorAll("button").forEach(de=>{de.disabled=!0,de.style.opacity="0.5",de.style.cursor="not-allowed"}),Y.approval.toolType==="webmcp"?R.resolveWebMcpApproval(w,z):R.resolveApproval(Y.approval,z)});let nt=null,iy=!1,ol=null,Us=()=>{},rl="none",Pc=null,uo={artifacts:[],selectedId:null},yr=!1,Lo=!1,sl=!1,Gi=!1,ay=()=>Gi||uo.artifacts.some(a=>or(o.features?.artifacts,a)==="panel"),Lc=()=>uo.artifacts.length>0&&!yr&&ay(),go={current:null},Qu=(a,u)=>{let m=R.getArtifactById(u),v=m?.markdown,w=m?.title||"artifact",P=m?.file,z=m?.artifactType??"markdown";if(!v){let ie=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ie){let de=R.getMessages().find(Pe=>Pe.id===ie);if(de?.rawContent)try{let Pe=JSON.parse(de.rawContent);v=Pe?.props?.markdown,w=Pe?.props?.title||w,Pe?.props?.file&&typeof Pe.props.file=="object"&&(P=Pe.props.file),!m&&typeof Pe?.props?.artifactType=="string"&&(z=Pe.props.artifactType)}catch{}}}return{markdown:v,title:w,file:P,artifactType:z}};Te.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:re}=Qu(m,v);if(!P)return;let Y=qr();Y&&Y.triggerArtifactDownload(Y.downloadInfoFor({title:z,markdown:P,file:re}))}),Te.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,Y=(w?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(gt=>gt.id===v);if(!Y)return;let{markdown:ie,title:le,file:de,artifactType:Pe}=Qu(m,z??""),it={artifactId:z,title:le,artifactType:Pe,markdown:ie,file:de};try{Promise.resolve(Y.onClick(it)).catch(()=>{})}catch{}}),Te.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=qr();if(!P)return;let z="";if(w)z=P.artifactCopyText(w);else{let{markdown:re,file:Y,artifactType:ie}=Qu(m,v);ie==="markdown"&&(z=P.artifactCopyText({id:v,artifactType:"markdown",status:"complete",markdown:re??"",...Y?{file:Y}:{}}))}z&&navigator.clipboard.writeText(z).then(()=>{let re=Nt(Kr.Check,16,"currentColor",2);re&&(m.replaceChildren(re),setTimeout(()=>{let Y=Nt(Kr.Copy,16,"currentColor",2);Y&&m.replaceChildren(Y)},1500))}).catch(()=>{})}),Te.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||(yr=!1,Gi=!0,Lo=!0,sl=!0,R.selectArtifact(v),Ho())}),Te.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(),yr=!1,Gi=!0,R.selectArtifact(v),Ho())}),Te.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 il=et.composerOverlay,Ju=a=>{pp().catch(()=>{}),Wd(a,o,il)},ly=null,bE={mount:e,overlay:il,sessionRef:go,config:()=>o},Hc=!1,cy=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=re=>{ly??=re.createAskUserSheetHandlers(bE),ly[a](u)},z=Gf();if(z){P(z);return}Hc||(Hc=!0,pp().then(re=>{Hc=!1,v.isConnected&&P(re)},()=>{Hc=!1}))};il.addEventListener("click",cy("click")),il.addEventListener("keydown",cy("keydown"));let dy=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=il.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",dy);let br=null,Ut=null,al=null,Ic=null,Rc=()=>{},py=!1,Wc="",Oc="";function Zu(){Ic?.(),Ic=null}let vE=()=>{let a=Bt?.railShell?Bt.railHost:null,u=a?.isConnected?a:null,m=u?u.getBoundingClientRect().width:0;return m<=0?200:m+360},uy=()=>{if(!br||!Ut)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){Ut.style.removeProperty("position"),Ut.style.removeProperty("left"),Ut.style.removeProperty("top"),Ut.style.removeProperty("bottom"),Ut.style.removeProperty("width"),Ut.style.removeProperty("z-index");return}let v=br.firstElementChild;if(!v||v===Ut)return;let w=10;Ut.style.position="absolute",Ut.style.top="0",Ut.style.bottom="0",Ut.style.width=`${w}px`,Ut.style.zIndex="5";let P=bh(br,u),z=v.offsetWidth+P/2-w/2;Ut.style.left=`${Math.max(0,z)}px`},_c=()=>{},gy=()=>{let a=e.ownerDocument.defaultView??window,u=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!u||a.innerWidth>m?!1:ye||Lt(o)},Bc=()=>!$n(o)||!Lc()||e.classList.contains("persona-artifact-narrow-host")||gy()||(e.ownerDocument.defaultView??window).innerWidth<rH?"none":fh(o)?"detached":"welded",Ho=()=>{if(!nt||!$n(o))return;dc(e,o),pc(e,o),_c();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,u=Ae.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=a);let m=Lc();nt.setVisible(m),nt.update(uo),yr?(nt.setMobileOpen(!1),nt.element.classList.add("persona-hidden"),nt.backdrop?.classList.add("persona-hidden"),Lo=!1,sl=!1):uo.artifacts.length>0&&ay()?(nt.element.classList.remove("persona-hidden"),nt.setMobileOpen(!0)):(nt.setMobileOpen(!1),nt.element.classList.add("persona-hidden"),nt.backdrop?.classList.add("persona-hidden"),Lo=!1,sl=!1);let v=o.features?.artifacts?.layout?.showExpandToggle===!0;if(nt.setExpandToggleVisible(v),nt.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),nt.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),nt.setCustomActions(o.features?.artifacts?.toolbarActions??[]),nt.setTabFade(o.features?.artifacts?.layout?.tabFade),nt.setRenderTabBar(o.features?.artifacts?.renderTabBar),!v&&!sl&&(Lo=!1),Lo!==py){let P=nt.element;Lo?(Wc=P.style.width,Oc=P.style.maxWidth,P.style.removeProperty("width"),P.style.removeProperty("max-width")):(Wc&&(P.style.width=Wc),Oc&&(P.style.maxWidth=Oc),Wc="",Oc=""),py=Lo}e.classList.toggle("persona-artifact-expanded",Lo),nt.setExpanded(Lo);let w=Bc();w!==rl&&(rl=w,Us()),Rc()};if($n(o)){Ae.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(we),br=u,u.appendChild(a),Ae.appendChild(u);let m=w=>{iy||nt||(nt=w.createArtifactPane(o,{onSelect:P=>go.current?.selectArtifact(P),onDismiss:()=>{yr=!0,Ho()},onToggleExpand:()=>{let P=!Lo,z=uo.selectedId??uo.artifacts[uo.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:z,expanded:P})!==!0&&(Lo=P,P||(sl=!1),Ho())}}),nt.element.classList.add("persona-hidden"),u.appendChild(nt.element),nt.backdrop&&Ae.appendChild(nt.backdrop),Rc(),Ho())},v=qr();v?m(v):(uh(()=>{let w=qr();w&&m(w)}),lu().catch(()=>{})),Rc=()=>{if(!br||!nt)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){al?.(),al=null,Zu(),Ut&&(Ut.remove(),Ut=null),nt.element.style.removeProperty("width"),nt.element.style.removeProperty("maxWidth");return}if(!Ut){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,re=z.defaultView??window,Y=ie=>{if(!nt||ie.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||re.innerWidth<=640)return;ie.preventDefault(),Zu();let le=ie.clientX,de=nt.element.getBoundingClientRect().width,Pe=o.features?.artifacts?.layout,it=dt=>{let Kn=br.getBoundingClientRect().width,Dt=e.classList.contains("persona-artifact-welded-split"),jt=bh(br,re),_n=Dt?0:P.getBoundingClientRect().width||6,Kt=de-(dt.clientX-le),wt=YA(Kt,Kn,jt,_n,Pe?.resizableMinWidth,Pe?.resizableMaxWidth,vE());nt.element.style.width=`${wt}px`,nt.element.style.maxWidth="none",uy()},gt=()=>{z.removeEventListener("pointermove",it),z.removeEventListener("pointerup",gt),z.removeEventListener("pointercancel",gt),Ic=null;try{P.releasePointerCapture(ie.pointerId)}catch{}};Ic=gt,z.addEventListener("pointermove",it),z.addEventListener("pointerup",gt),z.addEventListener("pointercancel",gt);try{P.setPointerCapture(ie.pointerId)}catch{}};P.addEventListener("pointerdown",Y),Ut=P,br.insertBefore(P,nt.element),al=()=>{P.removeEventListener("pointerdown",Y)}}if(Ut){let P=Lc();Ut.classList.toggle("persona-hidden",!P),uy()}},_c=()=>{if(!ye||!nt||(o.launcher?.sidebarMode??!1)||Lt(o)&&Zn(o).reveal==="emerge")return;let P=e.ownerDocument.defaultView??window,z=o.launcher?.mobileFullscreen??!0,re=o.launcher?.mobileBreakpoint??640;if(z&&P.innerWidth<=re||!VA(o,ye))return;let Y=Hi(o).width,ie=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Lc()?(Ae.style.width=ie,Ae.style.maxWidth=ie):(Ae.style.width=Y,Ae.style.maxWidth=Y)},typeof ResizeObserver<"u"&&(ol=new ResizeObserver(()=>{Ho()}),ol.observe(Ae))}else Ae.appendChild(we);Le()&&Xt&&(et.peekBanner&&Xt.appendChild(et.peekBanner),Xt.appendChild(Ke)),e.appendChild(Je),Xt&&e.appendChild(Xt);let eg=()=>{let a=gy()||Le()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!Lt(o);if(Te.style.gap=a?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",Te.style.setProperty("--persona-transcript-gap",Te.style.gap),Le()){Ae.style.width="100%",Ae.style.maxWidth="100%";let Be=o.launcher?.composerBar??{},Ye=Je.dataset.state==="expanded",Ue=Be.expandedSize??"anchored";if(!(Ye&&Ue!=="fullscreen")){we.style.background="",we.style.border="",we.style.borderRadius="",we.style.overflow="",we.style.boxShadow="";return}let nn=o.theme?.components?.panel,Gn=No(o),kr=(Pr,ci)=>Pr==null||Pr===""?ci:wn(Gn,Pr)??Pr,Jg="1px solid var(--persona-border)",li="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Zg="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";we.style.background="var(--persona-surface, #ffffff)",we.style.border=kr(nn?.border,Jg),we.style.borderRadius=kr(nn?.borderRadius,Zg),we.style.boxShadow=kr(nn?.shadow,li),we.style.overflow="hidden";return}let u=Lt(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,re=o.darkTheme?.components?.panel,Y=xi(o)==="dark"?Bo(z??{},re??{}):z,ie=No(o),le=(Be,Ye)=>Be==null||Be===""?Ye:wn(ie,Be)??Be,de=e.ownerDocument.defaultView??window,Pe=o.launcher?.mobileFullscreen??!0,it=o.launcher?.mobileBreakpoint??640,gt=de.innerWidth<=it,dt=Pe&&gt&&ye,Kn=u&&Pe&&gt,Dt=o.launcher?.position??"bottom-left",jt=Dt==="bottom-left"||Dt==="top-left",_n=o.launcher?.zIndex??Pn,Kt=(Be,Ye,Ue)=>`var(--persona-components-panel-modes-${Be}-${Ye}, ${Ue})`,wt=Y?.modes?.floating,Jo=le(wt?.border??Y?.border,Kt("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),Zo=le(wt?.shadow??Y?.shadow,Kt("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),bo=le(wt?.borderRadius??Y?.borderRadius,Kt("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),vo=P&&!dt&&!Kn,fs=dt||Kn?"mobile":vo?"floating":u?"docked":m?"sidebar":w?"inline":"floating",er=Y?.modes?.[fs];vo?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Io=vo?Jo:m||dt?"none":Jo,ms=vo?Zo:dt?"none":m?jt?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":w?"none":Zo;u&&!dt&&!vo&&(ms="none",Io="none");let xl=vo?bo:m||dt?"0":bo,ai=le(er?.border??Y?.border,Kt(fs,"border",Io)),O=le(er?.shadow??Y?.shadow,Kt(fs,"shadow",ms)),Ne=le(er?.borderRadius??Y?.borderRadius,Kt(fs,"borderRadius",xl)),Fe=Bc(),se=Fe==="detached",St=Fe==="welded";e.classList.toggle("persona-artifact-detached-split",se),e.classList.toggle("persona-artifact-welded-split",St);let Jt="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)))))",Tt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&$n(o)&&fh(o)&&w&&!u;e.classList.toggle("persona-artifact-chat-flush",Tt);let Gt=se||Tt?"none":O,ln=se?Jo:St?"none":ai,We=se?bo:Ne;Tt&&(ln="none",We="0");let kt=er?.borderRadius!=null&&er.borderRadius!==""||Y?.borderRadius!=null&&Y.borderRadius!=="",$e=Tt&&!kt?"0":Ne,cn=ae.scrollTop;e.style.cssText="",Je.style.cssText="",Ae.style.cssText="",we.style.cssText="",ae.style.cssText="",Ki||(Ke.style.cssText=""),Sn&&(ae.style.display="none"),(v||w)&&(e.style.minWidth="0");let Co=()=>{if(cn<=0)return;(ae.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ae.scrollTop===cn)return;let Ye=ae.scrollHeight-ae.clientHeight;Ye<=0||(ae.scrollTop=Math.min(cn,Ye))})};if(dt){Je.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"),Je.style.cssText=`
46
+ `,oe.addEventListener("click",()=>{g=V,A.forEach((W,j)=>{let X=j<V;W.classList.toggle("selected",X),W.setAttribute("aria-checked",j===V-1?"true":"false")})}),A.push(oe),C.appendChild(oe)}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 yu(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((_,P)=>{_.classList.toggle("selected",P===M),_.setAttribute("aria-checked",P===M?"true":"false")})}),V.push(T),B.appendChild(T)}A.appendChild(L),A.appendChild(B),h.appendChild(A);let oe=null;if(c){let M=document.createElement("div");M.className="persona-feedback-comment-container",oe=document.createElement("textarea"),oe.className="persona-feedback-comment",oe.placeholder=s,oe.rows=3,oe.setAttribute("aria-label","Additional comments"),M.appendChild(oe),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 X=document.createElement("button");return X.type="button",X.className="persona-feedback-btn persona-feedback-btn-submit",X.textContent=i,X.addEventListener("click",async()=>{if(f===null){B.classList.add("persona-feedback-shake"),setTimeout(()=>B.classList.remove("persona-feedback-shake"),500);return}X.disabled=!0,X.textContent="Submitting...";try{let M=oe?.value.trim()||void 0;await t(f,M),g.remove()}catch(M){X.disabled=!1,X.textContent=i,console.error("[NPS Feedback] Failed to submit:",M)}}),W.appendChild(j),W.appendChild(X),h.appendChild(W),g.appendChild(h),g}var Ga="persona-chat-history",oH=30*1e3,rH="Tap the mic to resume your voice call",sH=641,Ya="data-persona-composer-reason",yc="data-persona-composer-notice",iH={"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 aH(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=iH[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 bu(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 lH(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 cH(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var wh=e=>!e||typeof e!="object"?{}:{...e},cx=e=>e.map(t=>({...t,streaming:!1})),dx=(e,t,n)=>{let o=e?.markdown?jl(e.markdown):null,r=Lp(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=nr()!==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?bw(c):c,h=o(f);g=r&&d?r(h):h}else g=Ur(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)),Ur(l.text??"")}}};function px(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=ge(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 dH=(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},pH=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:dH(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),vu=(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=Ma(t),r=new Set,s=new Set,i=iw((a,u)=>{Mn.delete(a);let m=Array.from(Te.querySelectorAll("[data-message-id]")).find(v=>v.dataset.messageId===a);m&&(u==="tool"?ah(a,m,r,o):oh(a,m,s))}),l=new Map,c=()=>{uC({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};c();let p=o.features;o=uc(o);let d=gc.getForInstance(o.plugins),g=ZC(e),f=[],h=!1,y=RA(()=>o),b=null,C=null,A=null,L=!1,I=null,H=a=>{b=a,a.initApprovalUi({webMcpToolTitle:ma});let u=a.createBuiltInApprovalPlugin(l);C=u.plugin,A=u.teardown},B=()=>{if(b)return b;let a=NA();return a?(H(a),a):(DA().then(u=>{L||b||(H(u),I?.())}).catch(()=>{}),null)},V=!1,oe=!1,W=null,j=(a,u,m,v)=>{if(!a.querySelector("[data-tv-form]"))return;let w=QA();if(w){w.enhanceWithForms(a,u,m,v);return}XA().then(()=>{V||oe||!W||(oe=!0,W())}).catch(()=>{})};o.components&&Fo.registerAll(o.components);let X=ex(),T=o.persistState===!1?null:o.storageAdapter??uu(),_=!!o.clientToken&&typeof o.reconnectStream!="function",P={},J=null,U,ue=new Promise(a=>{U=a}),fe=()=>{},me=new Promise(a=>{fe=a}),He,Ee=!1,Ie=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&&(Ee=!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")J=a.then(u=>Ie(u??{messages:[],metadata:{}}));else{let m=Ie(a??{messages:[],metadata:{}});m.metadata&&(P=wh(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null}),He=m.draft}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=Ie({messages:[],metadata:{}});a.messages?.length&&(o={...o,initialMessages:a.messages})}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}J||U();let yt=()=>P,qe=a=>{P=a({...P})??{},Ji()},Oe=o.actionParsers&&o.actionParsers.length?o.actionParsers:[fc],$=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Wi.message,Wi.messageAndClick],_e=mc({parsers:Oe,handlers:$,getSessionMetadata:yt,updateSessionMetadata:qe,emit:X.emit,documentRef:typeof document<"u"?document:null});_e.syncFromMetadata();let ye=o.launcher?.enabled??!0,ut=o.launcher?.autoExpand??!1,Zt=o.autoFocusInput??!1,xt=ut,xe=ye,Wt=o.layout?.header?.layout,vt=!1,Le=()=>Rs(o),Xe=()=>ye||Le(),D=Le()?!1:ye?ut:!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=dx(o,_e,q),te=o.features?.showReasoning??!0,ve=o.features?.showToolCalls??!0,Me=o.features?.showEventStreamToggle??!1,Ce=o.features?.scrollToBottom??{},st=o.features?.scrollBehavior??{},Ct=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Qe=`${Ct()}event-stream`,pn=null,Eo=o.features?.eventStream?.maxEvents??2e3,ft=null,bt=null,Ft=null,_i=!1,rn=null,Sn=!1,lo=null,Bi=0,Di=(a,u)=>{ft?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(u)})},Qa=(a,u)=>{bt?.processEvent(a,u),ft?Di(a,u):Ft&&(Ft.length>=Eo&&Ft.shift(),Ft.push({type:a,payload:u}))},cr=()=>{ft||!Me||(Ft??=[],ch().then(a=>{if(_i||ft||!Me)return;pn=new a.EventStreamStore(Qe),ft=new a.EventStreamBuffer(Eo,pn),bt=bt??new a.ThroughputTracker,pn.open().then(()=>ft?.restore()).catch(m=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",m)});let u=Ft??[];Ft=null;for(let m of u)bt?.processEvent(m.type,m.payload),Di(m.type,m.payload)}).catch(()=>{}))};Me&&cr();let un=!1,Un=null,dr=()=>{},Vn=()=>{},pr=()=>{},Uo=()=>{},Yr=()=>{},wc=()=>Sn||un&&Un==="panel",to={onCopy:a=>{X.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=>{X.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)}},$h=o.statusIndicator??{},ur=(a,u=o.statusIndicator??{})=>a==="idle"?u.idleText??Yt.idle:a==="connecting"?u.connectingText??Yt.connecting:a==="connected"?u.connectedText??Yt.connected:a==="error"?u.errorText??Yt.error:a==="paused"?u.pausedText??Yt.paused:a==="resuming"?u.resumingText??Yt.resuming:Yt[a];function _s(a,u,m,v){if(!Le()&&(m.mode==="transient"||a.classList.contains("persona-mb-2"))&&(Tf(a,An,m),hi(a,m,v)),!(a.hasAttribute(Ya)||a.hasAttribute(yc)))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 Ln=IA({config:o,showClose:Xe()}),{wrapper:Je,panel:Ae,pillRoot:Xt}=Ln.shell,et=Ln.panelElements,{container:we,body:ae,messagesWrapper:Te,starterSuggestions:gr,transcriptSuggestions:Xr,suggestions:co,textarea:ce,sendButton:Pe,composerForm:An,statusText:tt,welcomeHost:en,welcomeIconHolder:Sc,greetingHost:Rn,introKicker:Ac,introTitle:Bu,introSubtitle:Ni,closeButton:ze,iconHolder:Ht,headerTitle:Vo,headerSubtitle:jo,header:mt,footer:Ke,actionsRow:Fi}=et,xn=et.leftActions,Bs=et.rightActions,Wn=et.sendButtonWrapper,xc=et.setSendButtonMode,he=et.micButton,gn=et.micButtonWrapper,It=et.attachmentButton,sn=et.attachmentButtonWrapper,Et=et.attachmentInput,fn=et.attachmentPreviewsContainer;we.classList.add("persona-relative"),ae.classList.add("persona-relative");let Ec=12,Qr=()=>Ce.label??"",Du=()=>Ce.iconName??"arrow-down",Nu=()=>Ce.enabled!==!1,En=()=>st.mode??"anchor-top",Mo=()=>En()==="follow"||En()==="anchor-top"&&ll,Ds=()=>st.anchorTopOffset??16,Mc=()=>st.restorePosition??"bottom",Ja=()=>st.pauseOnInteraction===!0,Za=()=>st.showActivityWhilePinned!==!1,$i=()=>st.announce===!0,Ns=()=>st.scrollbar??"on-scroll",Vt=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");Vt.type="button",Vt.style.display="none",Vt.setAttribute("data-persona-scroll-to-bottom","true");let Fs=x("span","persona-flex persona-items-center"),el=x("span",""),tn=x("span","");tn.setAttribute("data-persona-scroll-to-bottom-count",""),tn.style.display="none",Vt.append(Fs,el,tn),we.appendChild(Vt);let Qt=x("div","persona-stream-anchor-spacer");Qt.setAttribute("aria-hidden","true"),Qt.setAttribute("data-persona-anchor-spacer",""),Qt.style.flexShrink="0",Qt.style.pointerEvents="none",Qt.style.height="0px",Qt.style.display="none",ae.appendChild(Qt);let To=x("div","persona-sr-only");To.setAttribute("aria-live","polite"),To.setAttribute("aria-atomic","true"),To.setAttribute("role","status"),To.setAttribute("data-persona-live-region",""),Object.assign(To.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"}),we.appendChild(To);let Jr=null,fr=null,$s=a=>{!$i()||!a||(fr=a,Jr===null&&(Jr=setTimeout(()=>{Jr=null,fr&&$i()&&(To.textContent=fr),fr=null},400)))},jn=()=>{let a=e.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&a.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(ye||Lt(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!Lt(o)},E=()=>Ua(o,jn()),N="empty",ne=0,pe=()=>ne||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,Re=()=>{let u=Ke.style.display==="none"?0:Ke.offsetHeight;Vt.style.bottom=`${u+pe()+Ec}px`};Re();let $t=()=>{Ki||(Ke.style.marginBottom=ne>0?`${ne}px`:"")},Ot=()=>{let a=Pm(o,Le()),u=E();e.setAttribute("data-persona-welcome-fullscreen",String(jn())),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=Ke.style.display==="none"?0:Ke.offsetHeight,w=u.anchor==="center"&&N==="empty"?Ql(u.anchorComposerTop)??Ql("44%"):null,k=w!==null&&u.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,z=k?getComputedStyle(ae):null,re=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,Y=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,ie=Math.max(0,(parseFloat(z?.paddingBottom??"")||0)-(a==="overlay"?re+Y:0)),le=k?ae.getBoundingClientRect().top-we.getBoundingClientRect().top:0,de=!k||en.hidden?0:(en.querySelector("[data-persona-welcome-plugin]")??en).offsetHeight,ke=w===null||Le()?0:k?Math.max(0,Math.round((we.clientHeight-le-de-ie-v)/2)):_S({columnHeight:we.clientHeight,footerHeight:v,fraction:w});e.style.setProperty("--persona-composer-overlay-height",`${v}px`),e.style.setProperty("--persona-composer-lift",`${a==="overlay"?ke:0}px`),ne=a==="block"?ke:0,$t(),Re()},_t=()=>{let a=!!Qr();Vt.setAttribute("aria-label",Qr()||"Jump to latest"),Vt.title=Qr(),Vt.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),Fs.innerHTML="";let u=ge(Du(),"14px","currentColor",2);u?(Fs.appendChild(u),Fs.style.display=""):Fs.style.display="none",el.textContent=Qr(),el.style.display=a?"":"none"};_t();let je=null,at=null,be=zw(),Ui=a=>{try{we.dispatchEvent(new CustomEvent("persona:composer:state",{detail:a,bubbles:!0,composed:!0}))}catch{}};be.subscribe(Ui);let po=()=>{be.setText(ce?.value??"")},mr=()=>{be.setMentionRefs(at?.getMentionRefs()??[])},lE=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}),Uh=a=>{let u=Object.freeze(a.map(lE));be.setAttachments(u);try{o.attachments?.onChange?.(u)}catch(m){console.error("[AgentWidget] attachments.onChange failed:",m)}bg()};be.setSelectedModelId(o.composer?.selectedModelId);let tl=()=>o.composer?.modes??[],Vi=()=>lS(tl(),o.composer?.modeGroups);{let a=Dp(o.composer?.defaultActiveModeIds??[],tl());a.length&&be.setActiveModeIds(a)}function Vh(a){if(be.getState().selectedModelId!==a){be.setSelectedModelId(a),Zr?.repaint();try{o.composer?.onModelChange?.(a)}catch(u){console.error("[AgentWidget] composer.onModelChange failed:",u)}}}function Tc(a){be.setActiveModeIds(a),hr?.render(a,Vi()),ji.forEach(u=>u.repaint()),Po?.resolve(),ed(),ko()}function Fu(a){Tc(cS(be.getState().activeModeIds,a,tl(),o.composer?.modeGroups))}let Zr=null,$u=null,hr=null,ji=new Map,es=null;function qo(a){be.setQuote(a),es?.render(be.getState().quote),ko(),_y()}let jh=!1;function Uu(){let a=o.composer?.streamingSubmitBehavior??"block";return a!=="interrupt"?a:o.clientToken?"interrupt":(!jh&&o.debug===!0&&(jh=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let ts=null;function qi(a){be.setPendingSubmission(a),ts?.render(be.getState().pendingSubmission),ko()}let cE=a=>{let u=ji.get(a);if(u)return u;let m=uS({groupId:a,getGroup:()=>o.composer?.modeGroups?.find(v=>v.id===a),getModes:()=>tl().filter(v=>v.groupId===a),getActiveIds:()=>be.getState().activeModeIds,onSelect:v=>Fu(v)});return ji.set(a,m),m},dE=()=>{let a=[],u=be.getState().activeModeIds,m=new Set;if(tl().forEach((v,w)=>{if(Bp(v.groupId,o.composer?.modeGroups)){let k=v.groupId;if(m.has(k))return;m.add(k);let z=cE(k);z.action.order=Sm(w),z.action.label=o.composer?.modeGroups?.find(re=>re.id===k)?.label??k,a.push(z.action);return}a.push({id:iS(v.id),kind:"button",placement:"start",order:Sm(w),presentation:v.presentation??"auto",label:v.label,shortLabel:v.shortLabel,iconName:v.iconName,pressed:u.includes(v.id),onSelect:()=>Fu(v.id)})}),o.composer?.models?.length&&!d.some(v=>v.renderComposer)){let v=o.composer?.modelPicker?.presentation??"native";(!Zr||$u!==v)&&($u=v,Zr=rS({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>be.getState().selectedModelId,onSelect:w=>Vh(w),presentation:v,getSuffix:()=>o.composer?.modelPicker?.suffix})),a.push(Zr.action)}return a},Vu=null,qh=d.find(a=>a.renderHeader);if(qh?.renderHeader){let a=qh.renderHeader({config:o,defaultRenderer:()=>{let u=jr({config:o,showClose:Xe()});return Ti(we,u,o),u.header},onClose:()=>Mt(!1,"user")});if(a){let u=mt;u&&(u.replaceWith(a),mt=a,Ln.header.element=a)}}let zh=()=>{rn&&(ae.style.display="none",Ke.parentNode?.insertBefore(rn.element,Ke),rn.update())},ju=()=>{if(!ft){cr();return}if(Sn=!0,rn?zh():ch().then(u=>{rn||!Sn||!ft||(rn=u.createEventStreamView({buffer:ft,getFullHistory:()=>ft.getAllFromStore(),onClose:()=>zi(),config:o,plugins:d,getThroughput:()=>bt?.getMetric()??{status:"idle"},renderIconByName:ge}),zh())}).catch(()=>{zi()}),ht){ht.style.boxShadow=`inset 0 0 0 1.5px ${Nn.actionIconColor}`;let u=o.features?.eventStream?.classNames?.toggleButtonActive;u&&u.split(/\s+/).forEach(m=>m&&ht.classList.add(m))}let a=()=>{if(!Sn)return;let u=Date.now();u-Bi>=200&&(rn?.update(),Bi=u),lo=requestAnimationFrame(a)};Bi=0,lo=requestAnimationFrame(a),Tn(),X.emit("eventStream:opened",{timestamp:Date.now()})},zi=()=>{if(Sn){if(Sn=!1,rn&&rn.element.remove(),ae.style.display="",ht){ht.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(u=>u&&ht.classList.remove(u))}lo!==null&&(cancelAnimationFrame(lo),lo=null),Tn(),X.emit("eventStream:closed",{timestamp:Date.now()})}},ht=null;if(Me){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:"");ht=x("button",u),ht.style.width="28px",ht.style.height="28px",ht.style.color=Nn.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let m=Nt(Kr.Activity,"18px","currentColor",1.5);m&&ht.appendChild(m);let v=et.clearChatButtonWrapper,w=et.closeButtonWrapper,k=v||w;k&&k.parentNode===mt?mt.insertBefore(ht,k):mt.appendChild(ht),ht.addEventListener("click",()=>{Sn?zi():ju()})}let Kh=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??Dr).join(","),w.multiple=(u.maxFiles??4)>1,w.style.display="none",w.setAttribute("aria-label",u.buttonTooltipText??"Attach files"),a.appendChild(w)}},Ki=!1,Gh=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:()=>qb(),storage:y(u.id),onSubmit:w=>{!R||R.isStreaming()||cd(w.trim(),{consumeDraft:!1})},streaming:v,disabled:v,openAttachmentPicker:()=>{Yo()||Et?.click()},models:m?.models,selectedModelId:be.getState().selectedModelId??m?.selectedModelId,onModelChange:w=>Vh(w),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Vu?.()}:void 0})},Yh=Gh(()=>ki({config:o}).footer);Yh&&(Ln.replaceComposer(Yh),Ke=Ln.composer.footer,Ki=!0);let ct=null,pE=a=>{An=a.form,ce=a.input,Wn=a.sendButton?a.sendButton.parentElement:null,a.sendButton&&(Pe=a.sendButton),a.micButton&&(he=a.micButton,gn=a.micButton.parentElement),a.found.status&&(tt=a.found.status),a.found.suggestions&&(co=a.found.suggestions),a.attachmentButton&&(It=a.attachmentButton,sn=a.attachmentButton.parentElement),Et=a.attachmentInput??null,fn=a.attachmentPreviews??null,a.found.actionsRow&&(Fi=a.found.actionsRow),xn=a.found.actionsStart,Bs=a.found.actionsEnd};function qu(){let a=ce;if(!a)return;let u=o.composer?.inputAttributes,m=!u?.ariaLabel&&!(a instanceof HTMLTextAreaElement)?a.getAttribute("aria-label"):null;Zd(a,u),m&&a.setAttribute("aria-label",m),Jd(a,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Bl(a)}),OC(a,Qd(o.composer?.maxLines,Le()?5:3))}let Xh=a=>{ct=Gw(a,{debug:o.debug===!0}),ct&&pE(ct),qu()};Kh(Ke),Xh(Ke),po();let nl=Hs(o,Le());nl&&(Te.style.maxWidth=nl,Te.style.marginLeft="auto",Te.style.marginRight="auto",Te.style.width="100%",Rn.style.maxWidth=nl,Rn.style.marginLeft="auto",Rn.style.marginRight="auto",Rn.style.width="100%",gr.style.maxWidth=nl,Xr.style.maxWidth=nl,Xr.style.marginLeft="auto",Xr.style.marginRight="auto",Xr.style.width="100%");let Qh=()=>{let a=Hs(o,Le());if(!(!a||Le()))for(let u of[An,co,fn,tt])u&&(u.style.maxWidth=a,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%")};Qh();let Jh=()=>{!o.attachments?.enabled||!Et||!fn||(je?je.remountPreviews(fn):(je=Ai.fromConfig(o.attachments,Uh),je.setPreviewsContainer(fn)),ct?.addListener(Et,"change",a=>{let u=a.target;je?.handleFileSelect(u.files),u.value=""}),we.querySelector(".persona-attachment-drop-overlay")||we.appendChild(px(o.attachments.dropOverlay)))};Jh();let uE=()=>at?.prefetch(),zu=()=>{if(!o.contextMentions?.enabled||!ce)return;let a=Gf();if(!a){let v=ce;pp().then(()=>{at||ce!==v||!v.isConnected||(zu(),Po?.resolve())},()=>{});return}let u=ct?.header??null,m=u?wm(u):void 0;if(at=a.createContextMentionOrchestrator({deps:{loadContextMentions:lp,loadContextMentionsInline:cp,renderLucideIcon:ge,createMentionButton:ap},config:o,textarea:ce,anchor:An??ce,getMessages:()=>R.getMessages(),liveRegionHost:we,chipRow:m}),at&&!m){let v=ce;v.parentElement?.insertBefore(at.contextRow,v)}};zu();let Po=null,gE={getState:()=>be.getState(),getValue:()=>ce?.value??"",setValue:a=>{ce&&(ce.value=a,ce.dispatchEvent(new Event("input",{bubbles:!0})),po())},submit:()=>{SS(ct?.form??null)},openAttachmentPicker:()=>{Yo()||Et?.click()},toggleVoice:()=>{Vu?.()},requestRender:()=>Po?.resolve()},fE=()=>{let a=[];return(at?.affordanceButtons??[]).forEach((m,v)=>{a.push({id:`core:mention-${v}`,placement:"start",order:sr.mention+v,element:m,managed:!0})}),sn&&a.push({id:"core:attachment",placement:"start",order:sr.attachment,element:sn}),gn&&a.push({id:"core:mic",placement:"end",order:sr.mic,element:gn}),Wn&&a.push({id:"core:send",placement:"end",order:sr.send,element:Wn}),a},Zh=()=>{Po?.destroy(),Po=tS({getBindings:()=>ct,collect:()=>({builtIns:fE(),configActions:[...dE(),...o.composer?.actions??[]],plugins:d,contributionContext:{config:o,getState:()=>be.getState(),requestRender:()=>Po?.resolve()},debug:o.debug===!0}),actionContext:gE,getState:()=>be.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(a,u)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${u.actionId}" failed:`,a)}}),Po.resolve()};Zh();let Ku=()=>{if(hr?.destroy(),hr=null,!Vi().length)return;let a=ct?.header;a&&(hr=sS({row:wm(a),onRemove:u=>Fu(u),initialIds:be.getState().activeModeIds}),hr.render(be.getState().activeModeIds,Vi()))};Ku();let ey=()=>{es?.destroy(),es=null,ts?.destroy(),ts=null;let a=ct?.header;a&&(es=gS({onDismiss:()=>qo(void 0)}),a.appendChild(es.element),es.render(be.getState().quote),Uu()==="defer-one"&&(ts=fS({onEdit:()=>dM(),onRemove:()=>qi(void 0)}),a.appendChild(ts.element),ts.render(be.getState().pendingSubmission)))};ey();let Gu=CS(),mE=()=>{let a=ct?.header?.querySelector(Cm);if(a)return a.childElementCount>0;let u=be.getState();return u.mentionRefs.length>0||Dp(u.activeModeIds,Vi()).length>0};function ko(){let a=be.getState(),u=Gu.observe(wS(ce),a.text);Ke.toggleAttribute("data-persona-composer-compact",vS({text:a.text,wrapped:u,hasAttachments:a.attachments.length>0,hasChips:mE(),hasQuote:a.quote!==void 0,hasPendingSubmission:a.pendingSubmission!==void 0}))}function ty(){o.composer?.layout==="single-row"&&!Le()?Ke.setAttribute("data-persona-composer-layout","single-row"):Ke.removeAttribute("data-persona-composer-layout")}ty(),be.subscribe(()=>{Po?.sync(),bg(),Qc(),ko(),_y()}),Qc();let ny=!1,hE=a=>{if(ny||o.debug!==!0)return;let u=["messages","composer"].filter(m=>a[m]);u.length&&(ny=!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??{};hE(a);let u=v=>{switch(v){case"body-top":return ae.querySelector("[data-persona-intro-card]");case"messages":return Te;case"footer-top":return co;case"composer":return An;case"footer-bottom":return tt;default:return null}},m=(v,w)=>{switch(v){case"header-left":case"header-center":case"header-right":if(v==="header-left")mt.insertBefore(w,mt.firstChild);else if(v==="header-right")mt.appendChild(w);else{let k=mt.querySelector(".persona-flex-col");k?k.parentNode?.insertBefore(w,k.nextSibling):mt.appendChild(w)}break;case"body-top":{let k=ae.querySelector("[data-persona-intro-card]");k?k.replaceWith(w):ae.insertBefore(w,ae.firstChild);break}case"body-bottom":ae.appendChild(w);break;case"footer-top":co.replaceWith(w);break;case"footer-bottom":tt.replaceWith(w);break;default:break}};for(let[v,w]of Object.entries(a))if(w)try{let k=w({config:o,defaultContent:()=>u(v)});k&&m(v,k)}catch(k){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${v}":`,k)}})(),Te.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(),_A(m))});let Yu=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;is(),ta();let k=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(k==="reasoning")s.has(w)?s.delete(w):s.add(w),oh(w,v,s);else if(k==="tool")r.has(w)?r.delete(w):r.add(w),ah(w,v,r,o);else if(k==="approval"&&b){let re=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",Y=l.get(w)??re;l.set(w,!Y),b.updateApprovalDetailsUI(w,v,o,l)}Mn.delete(w)};Te.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Yu(a))}),Te.addEventListener("click",a=>{a.detail===0&&a.target.closest(".persona-activity-row")&&Yu(a)}),Te.addEventListener("keydown",a=>{let u=a.target;(a.key==="Enter"||a.key===" ")&&u.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Yu(a))}),Te.addEventListener("copy",a=>{let{clipboardData:u}=a;if(!u)return;let m=Te.getRootNode(),v=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let w=v.toString(),k=DS(w);!k||k===w||(u.setData("text/plain",k),a.preventDefault())});let Xu=new Map,oy=null,ry="idle",yE={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},bE=(a,u)=>{let{icon:m,label:v}=yE[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=ge(m,14,"currentColor",2);w&&(a.innerHTML="",a.appendChild(w))},sy=()=>{Te.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{let v=u.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;bE(u,v&&v===oy?ry:"idle")})};Te.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 k=m.getAttribute("data-action");if(k==="copy"){let re=R.getMessages().find(Y=>Y.id===w);if(re&&to.onCopy){let Y=re.content||"";navigator.clipboard.writeText(Y).then(()=>{m.classList.add("persona-message-action-success");let ie=Nt(Kr.Check,14,"currentColor",2);ie&&(m.innerHTML="",m.appendChild(ie)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let le=Nt(Kr.Copy,14,"currentColor",2);le&&(m.innerHTML="",m.appendChild(le))},2e3)}).catch(ie=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ie)}),to.onCopy(re)}}else if(k==="read-aloud")R.toggleReadAloud(w);else if(k==="upvote"||k==="downvote"){let re=(Xu.get(w)??null)===k,Y=k==="upvote"?"thumbs-up":"thumbs-down";if(re){Xu.delete(w),m.classList.remove("persona-message-action-active");let ie=ge(Y,14,"currentColor",2);ie&&(m.innerHTML="",m.appendChild(ie))}else{let ie=k==="upvote"?"downvote":"upvote",le=v.querySelector(`[data-action="${ie}"]`);if(le){le.classList.remove("persona-message-action-active");let dt=ge(ie==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);dt&&(le.innerHTML="",le.appendChild(dt))}Xu.set(w,k),m.classList.add("persona-message-action-active");let de=ge(Y,14,"currentColor",2);de&&(de.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(de)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let it=R.getMessages().find(gt=>gt.id===w);it&&to.onFeedback&&to.onFeedback({type:k,messageId:it.id,message:it})}}else if(k==="regenerate")Pc?.regenerate(w);else if(k==="edit")Pc?.edit(w);else if(k==="quote")Pc?.quote(w);else if(k?.startsWith(ou)){let z=k.slice(ou.length),re=o.messageActions?.custom?.find(ie=>ie.id===z),Y=R.getMessages().find(ie=>ie.id===w);if(!re||!Y)return;try{re.onSelect(Y)}catch(ie){console.error(`[AgentWidget] messageActions.custom "${z}" onSelect failed:`,ie)}}});let Pc=null;Te.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 k=m.getAttribute("data-approval-action");if(!k)return;let z=k==="approve"?"approved":"denied",Y=R.getMessages().find(le=>le.id===w);if(!Y?.approval)return;let ie=v.querySelector("[data-approval-buttons]");ie&&ie.querySelectorAll("button").forEach(de=>{de.disabled=!0,de.style.opacity="0.5",de.style.cursor="not-allowed"}),Y.approval.toolType==="webmcp"?R.resolveWebMcpApproval(w,z):R.resolveApproval(Y.approval,z)});let nt=null,iy=!1,ol=null,Us=()=>{},rl="none",kc=null,uo={artifacts:[],selectedId:null},yr=!1,Lo=!1,sl=!1,Gi=!1,ay=()=>Gi||uo.artifacts.some(a=>or(o.features?.artifacts,a)==="panel"),Lc=()=>uo.artifacts.length>0&&!yr&&ay(),go={current:null},Qu=(a,u)=>{let m=R.getArtifactById(u),v=m?.markdown,w=m?.title||"artifact",k=m?.file,z=m?.artifactType??"markdown";if(!v){let ie=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ie){let de=R.getMessages().find(ke=>ke.id===ie);if(de?.rawContent)try{let ke=JSON.parse(de.rawContent);v=ke?.props?.markdown,w=ke?.props?.title||w,ke?.props?.file&&typeof ke.props.file=="object"&&(k=ke.props.file),!m&&typeof ke?.props?.artifactType=="string"&&(z=ke.props.artifactType)}catch{}}}return{markdown:v,title:w,file:k,artifactType:z}};Te.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:k,title:z,file:re}=Qu(m,v);if(!k)return;let Y=qr();Y&&Y.triggerArtifactDownload(Y.downloadInfoFor({title:z,markdown:k,file:re}))}),Te.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]"),k=w?null:m.closest("[data-open-artifact]"),z=w?w.getAttribute("data-artifact-inline"):k?.getAttribute("data-open-artifact")??null,Y=(w?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(gt=>gt.id===v);if(!Y)return;let{markdown:ie,title:le,file:de,artifactType:ke}=Qu(m,z??""),it={artifactId:z,title:le,artifactType:ke,markdown:ie,file:de};try{Promise.resolve(Y.onClick(it)).catch(()=>{})}catch{}}),Te.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),k=qr();if(!k)return;let z="";if(w)z=k.artifactCopyText(w);else{let{markdown:re,file:Y,artifactType:ie}=Qu(m,v);ie==="markdown"&&(z=k.artifactCopyText({id:v,artifactType:"markdown",status:"complete",markdown:re??"",...Y?{file:Y}:{}}))}z&&navigator.clipboard.writeText(z).then(()=>{let re=Nt(Kr.Check,16,"currentColor",2);re&&(m.replaceChildren(re),setTimeout(()=>{let Y=Nt(Kr.Copy,16,"currentColor",2);Y&&m.replaceChildren(Y)},1500))}).catch(()=>{})}),Te.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||(yr=!1,Gi=!0,Lo=!0,sl=!0,R.selectArtifact(v),Ho())}),Te.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(),yr=!1,Gi=!0,R.selectArtifact(v),Ho())}),Te.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 il=et.composerOverlay,Ju=a=>{pp().catch(()=>{}),Wd(a,o,il)},ly=null,vE={mount:e,overlay:il,sessionRef:go,config:()=>o},Hc=!1,cy=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 k=re=>{ly??=re.createAskUserSheetHandlers(vE),ly[a](u)},z=Gf();if(z){k(z);return}Hc||(Hc=!0,pp().then(re=>{Hc=!1,v.isConnected&&k(re)},()=>{Hc=!1}))};il.addEventListener("click",cy("click")),il.addEventListener("keydown",cy("keydown"));let dy=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=il.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),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"]')[v-1];k&&(a.preventDefault(),k.click())};document.addEventListener("keydown",dy);let br=null,Ut=null,al=null,Ic=null,Rc=()=>{},py=!1,Wc="",Oc="";function Zu(){Ic?.(),Ic=null}let CE=()=>{let a=Bt?.railShell?Bt.railHost:null,u=a?.isConnected?a:null,m=u?u.getBoundingClientRect().width:0;return m<=0?200:m+360},uy=()=>{if(!br||!Ut)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){Ut.style.removeProperty("position"),Ut.style.removeProperty("left"),Ut.style.removeProperty("top"),Ut.style.removeProperty("bottom"),Ut.style.removeProperty("width"),Ut.style.removeProperty("z-index");return}let v=br.firstElementChild;if(!v||v===Ut)return;let w=10;Ut.style.position="absolute",Ut.style.top="0",Ut.style.bottom="0",Ut.style.width=`${w}px`,Ut.style.zIndex="5";let k=bh(br,u),z=v.offsetWidth+k/2-w/2;Ut.style.left=`${Math.max(0,z)}px`},_c=()=>{},gy=()=>{let a=e.ownerDocument.defaultView??window,u=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!u||a.innerWidth>m?!1:ye||Lt(o)},Bc=()=>!$n(o)||!Lc()||e.classList.contains("persona-artifact-narrow-host")||gy()||(e.ownerDocument.defaultView??window).innerWidth<sH?"none":fh(o)?"detached":"welded",Ho=()=>{if(!nt||!$n(o))return;dc(e,o),pc(e,o),_c();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,u=Ae.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=a);let m=Lc();nt.setVisible(m),nt.update(uo),yr?(nt.setMobileOpen(!1),nt.element.classList.add("persona-hidden"),nt.backdrop?.classList.add("persona-hidden"),Lo=!1,sl=!1):uo.artifacts.length>0&&ay()?(nt.element.classList.remove("persona-hidden"),nt.setMobileOpen(!0)):(nt.setMobileOpen(!1),nt.element.classList.add("persona-hidden"),nt.backdrop?.classList.add("persona-hidden"),Lo=!1,sl=!1);let v=o.features?.artifacts?.layout?.showExpandToggle===!0;if(nt.setExpandToggleVisible(v),nt.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),nt.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),nt.setCustomActions(o.features?.artifacts?.toolbarActions??[]),nt.setTabFade(o.features?.artifacts?.layout?.tabFade),nt.setRenderTabBar(o.features?.artifacts?.renderTabBar),!v&&!sl&&(Lo=!1),Lo!==py){let k=nt.element;Lo?(Wc=k.style.width,Oc=k.style.maxWidth,k.style.removeProperty("width"),k.style.removeProperty("max-width")):(Wc&&(k.style.width=Wc),Oc&&(k.style.maxWidth=Oc),Wc="",Oc=""),py=Lo}e.classList.toggle("persona-artifact-expanded",Lo),nt.setExpanded(Lo);let w=Bc();w!==rl&&(rl=w,Us()),Rc()};if($n(o)){Ae.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(we),br=u,u.appendChild(a),Ae.appendChild(u);let m=w=>{iy||nt||(nt=w.createArtifactPane(o,{onSelect:k=>go.current?.selectArtifact(k),onDismiss:()=>{yr=!0,Ho()},onToggleExpand:()=>{let k=!Lo,z=uo.selectedId??uo.artifacts[uo.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:z,expanded:k})!==!0&&(Lo=k,k||(sl=!1),Ho())}}),nt.element.classList.add("persona-hidden"),u.appendChild(nt.element),nt.backdrop&&Ae.appendChild(nt.backdrop),Rc(),Ho())},v=qr();v?m(v):(uh(()=>{let w=qr();w&&m(w)}),lu().catch(()=>{})),Rc=()=>{if(!br||!nt)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){al?.(),al=null,Zu(),Ut&&(Ut.remove(),Ut=null),nt.element.style.removeProperty("width"),nt.element.style.removeProperty("maxWidth");return}if(!Ut){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 z=e.ownerDocument,re=z.defaultView??window,Y=ie=>{if(!nt||ie.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||re.innerWidth<=640)return;ie.preventDefault(),Zu();let le=ie.clientX,de=nt.element.getBoundingClientRect().width,ke=o.features?.artifacts?.layout,it=dt=>{let Kn=br.getBoundingClientRect().width,Dt=e.classList.contains("persona-artifact-welded-split"),jt=bh(br,re),_n=Dt?0:k.getBoundingClientRect().width||6,Kt=de-(dt.clientX-le),wt=YA(Kt,Kn,jt,_n,ke?.resizableMinWidth,ke?.resizableMaxWidth,CE());nt.element.style.width=`${wt}px`,nt.element.style.maxWidth="none",uy()},gt=()=>{z.removeEventListener("pointermove",it),z.removeEventListener("pointerup",gt),z.removeEventListener("pointercancel",gt),Ic=null;try{k.releasePointerCapture(ie.pointerId)}catch{}};Ic=gt,z.addEventListener("pointermove",it),z.addEventListener("pointerup",gt),z.addEventListener("pointercancel",gt);try{k.setPointerCapture(ie.pointerId)}catch{}};k.addEventListener("pointerdown",Y),Ut=k,br.insertBefore(k,nt.element),al=()=>{k.removeEventListener("pointerdown",Y)}}if(Ut){let k=Lc();Ut.classList.toggle("persona-hidden",!k),uy()}},_c=()=>{if(!ye||!nt||(o.launcher?.sidebarMode??!1)||Lt(o)&&Zn(o).reveal==="emerge")return;let k=e.ownerDocument.defaultView??window,z=o.launcher?.mobileFullscreen??!0,re=o.launcher?.mobileBreakpoint??640;if(z&&k.innerWidth<=re||!VA(o,ye))return;let Y=Hi(o).width,ie=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Lc()?(Ae.style.width=ie,Ae.style.maxWidth=ie):(Ae.style.width=Y,Ae.style.maxWidth=Y)},typeof ResizeObserver<"u"&&(ol=new ResizeObserver(()=>{Ho()}),ol.observe(Ae))}else Ae.appendChild(we);Le()&&Xt&&(et.peekBanner&&Xt.appendChild(et.peekBanner),Xt.appendChild(Ke)),e.appendChild(Je),Xt&&e.appendChild(Xt);let eg=()=>{let a=gy()||Le()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!Lt(o);if(Te.style.gap=a?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",Te.style.setProperty("--persona-transcript-gap",Te.style.gap),Le()){Ae.style.width="100%",Ae.style.maxWidth="100%";let Be=o.launcher?.composerBar??{},Ye=Je.dataset.state==="expanded",Ue=Be.expandedSize??"anchored";if(!(Ye&&Ue!=="fullscreen")){we.style.background="",we.style.border="",we.style.borderRadius="",we.style.overflow="",we.style.boxShadow="";return}let nn=o.theme?.components?.panel,Gn=No(o),Pr=(kr,ci)=>kr==null||kr===""?ci:wn(Gn,kr)??kr,Jg="1px solid var(--persona-border)",li="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Zg="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";we.style.background="var(--persona-surface, #ffffff)",we.style.border=Pr(nn?.border,Jg),we.style.borderRadius=Pr(nn?.borderRadius,Zg),we.style.boxShadow=Pr(nn?.shadow,li),we.style.overflow="hidden";return}let u=Lt(o),m=o.launcher?.sidebarMode??!1,v=u||m||(o.launcher?.fullHeight??!1),w=o.launcher?.enabled===!1,k=o.launcher?.detachedPanel===!0,z=o.theme?.components?.panel,re=o.darkTheme?.components?.panel,Y=xi(o)==="dark"?Bo(z??{},re??{}):z,ie=No(o),le=(Be,Ye)=>Be==null||Be===""?Ye:wn(ie,Be)??Be,de=e.ownerDocument.defaultView??window,ke=o.launcher?.mobileFullscreen??!0,it=o.launcher?.mobileBreakpoint??640,gt=de.innerWidth<=it,dt=ke&&gt&&ye,Kn=u&&ke&&gt,Dt=o.launcher?.position??"bottom-left",jt=Dt==="bottom-left"||Dt==="top-left",_n=o.launcher?.zIndex??kn,Kt=(Be,Ye,Ue)=>`var(--persona-components-panel-modes-${Be}-${Ye}, ${Ue})`,wt=Y?.modes?.floating,Jo=le(wt?.border??Y?.border,Kt("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),Zo=le(wt?.shadow??Y?.shadow,Kt("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),bo=le(wt?.borderRadius??Y?.borderRadius,Kt("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),vo=k&&!dt&&!Kn,fs=dt||Kn?"mobile":vo?"floating":u?"docked":m?"sidebar":w?"inline":"floating",er=Y?.modes?.[fs];vo?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Io=vo?Jo:m||dt?"none":Jo,ms=vo?Zo:dt?"none":m?jt?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":w?"none":Zo;u&&!dt&&!vo&&(ms="none",Io="none");let xl=vo?bo:m||dt?"0":bo,ai=le(er?.border??Y?.border,Kt(fs,"border",Io)),O=le(er?.shadow??Y?.shadow,Kt(fs,"shadow",ms)),Ne=le(er?.borderRadius??Y?.borderRadius,Kt(fs,"borderRadius",xl)),Fe=Bc(),se=Fe==="detached",St=Fe==="welded";e.classList.toggle("persona-artifact-detached-split",se),e.classList.toggle("persona-artifact-welded-split",St);let Jt="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)))))",Tt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&$n(o)&&fh(o)&&w&&!u;e.classList.toggle("persona-artifact-chat-flush",Tt);let Gt=se||Tt?"none":O,ln=se?Jo:St?"none":ai,We=se?bo:Ne;Tt&&(ln="none",We="0");let Pt=er?.borderRadius!=null&&er.borderRadius!==""||Y?.borderRadius!=null&&Y.borderRadius!=="",$e=Tt&&!Pt?"0":Ne,cn=ae.scrollTop;e.style.cssText="",Je.style.cssText="",Ae.style.cssText="",we.style.cssText="",ae.style.cssText="",Ki||(Ke.style.cssText=""),Sn&&(ae.style.display="none"),(v||w)&&(e.style.minWidth="0");let Co=()=>{if(cn<=0)return;(ae.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ae.scrollTop===cn)return;let Ye=ae.scrollHeight-ae.clientHeight;Ye<=0||(ae.scrollTop=Math.min(cn,Ye))})};if(dt){Je.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"),Je.style.cssText=`
47
47
  position: fixed !important;
48
48
  inset: 0 !important;
49
49
  width: 100% !important;
@@ -79,7 +79,7 @@ _Details: ${n.message}_`:o}var jw=e=>bs(e)||e===Oo,Wa=class e{constructor(t={},n
79
79
  overflow: hidden !important;
80
80
  border-radius: 0 !important;
81
81
  border: none !important;
82
- `,ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.overflowY="auto",Ke.style.flexShrink="0",$t(),vt=!0,Co();return}let hn=Hi(o);if(!m&&!u)w&&v?(Ae.style.width="100%",Ae.style.maxWidth="100%"):(Ae.style.width=hn.width,Ae.style.maxWidth=hn.maxWidth);else if(u)if(Zn(o).reveal==="emerge"&&!P){let Ye=Zn(o).width;Ae.style.width=Ye,Ae.style.maxWidth=Ye}else Ae.style.width="100%",Ae.style.maxWidth="100%";if(_c(),Ae.style.boxShadow=Gt,Ae.style.borderRadius=$e,se?Ae.style.border="none":St&&(Ae.style.border=ai),we.style.border=ln,we.style.borderRadius=We,we.style.boxShadow=se&&!Tt?Jt:"",Tt&&(we.style.background="transparent",ae.style.background="transparent",Ke.style.background="transparent",Ke.style.borderTop="none"),St){let Be=o.features?.artifacts?.layout;Pc=Be?.unifiedSplitOuterRadius?.trim()||Be?.paneBorderRadius?.trim()||Ne}else Pc=null;let At=er?.border!=null||Y?.border!=null;if(u&&!dt&&!vo&&!se&&!St&&!At&&(we.style.border="none",Zn(o).side==="right"?we.style.borderLeft="1px solid var(--persona-border)":we.style.borderRight="1px solid var(--persona-border)"),u&&!dt&&St&&!At&&(Zn(o).side==="right"?Ae.style.borderLeft="1px solid var(--persona-border)":Ae.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%"),Je.style.display="flex",Je.style.flexDirection="column",Je.style.flex="1 1 0%",Je.style.minHeight="0",Je.style.maxHeight="100%",Je.style.height="100%",w&&(Je.style.overflow="hidden"),Ae.style.display="flex",Ae.style.flexDirection="column",Ae.style.flex="1 1 0%",Ae.style.minHeight="0",Ae.style.maxHeight="100%",Ae.style.height="100%",se||(Ae.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.overflow="hidden",ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.overflowY="auto",Ke.style.flexShrink="0"),w&&(vo||se||Tt)&&!u&&(Tt||(Je.style.padding="var(--persona-panel-inset)"),Je.style.background="var(--persona-panel-canvas-bg)"),Je.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&&(ao[Dt]??ao["bottom-right"]).split(" ").forEach(Ye=>Je.classList.add(Ye)),m){let Be=_r(o).sidebarWidth?o.launcher?.sidebarWidth??"420px":wn(No(o),"components.panel.width")??"420px";P?Je.style.cssText=`
82
+ `,ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.overflowY="auto",Ke.style.flexShrink="0",$t(),vt=!0,Co();return}let hn=Hi(o);if(!m&&!u)w&&v?(Ae.style.width="100%",Ae.style.maxWidth="100%"):(Ae.style.width=hn.width,Ae.style.maxWidth=hn.maxWidth);else if(u)if(Zn(o).reveal==="emerge"&&!k){let Ye=Zn(o).width;Ae.style.width=Ye,Ae.style.maxWidth=Ye}else Ae.style.width="100%",Ae.style.maxWidth="100%";if(_c(),Ae.style.boxShadow=Gt,Ae.style.borderRadius=$e,se?Ae.style.border="none":St&&(Ae.style.border=ai),we.style.border=ln,we.style.borderRadius=We,we.style.boxShadow=se&&!Tt?Jt:"",Tt&&(we.style.background="transparent",ae.style.background="transparent",Ke.style.background="transparent",Ke.style.borderTop="none"),St){let Be=o.features?.artifacts?.layout;kc=Be?.unifiedSplitOuterRadius?.trim()||Be?.paneBorderRadius?.trim()||Ne}else kc=null;let At=er?.border!=null||Y?.border!=null;if(u&&!dt&&!vo&&!se&&!St&&!At&&(we.style.border="none",Zn(o).side==="right"?we.style.borderLeft="1px solid var(--persona-border)":we.style.borderRight="1px solid var(--persona-border)"),u&&!dt&&St&&!At&&(Zn(o).side==="right"?Ae.style.borderLeft="1px solid var(--persona-border)":Ae.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%"),Je.style.display="flex",Je.style.flexDirection="column",Je.style.flex="1 1 0%",Je.style.minHeight="0",Je.style.maxHeight="100%",Je.style.height="100%",w&&(Je.style.overflow="hidden"),Ae.style.display="flex",Ae.style.flexDirection="column",Ae.style.flex="1 1 0%",Ae.style.minHeight="0",Ae.style.maxHeight="100%",Ae.style.height="100%",se||(Ae.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.overflow="hidden",ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.overflowY="auto",Ke.style.flexShrink="0"),w&&(vo||se||Tt)&&!u&&(Tt||(Je.style.padding="var(--persona-panel-inset)"),Je.style.background="var(--persona-panel-canvas-bg)"),Je.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&&(ao[Dt]??ao["bottom-right"]).split(" ").forEach(Ye=>Je.classList.add(Ye)),m){let Be=_r(o).sidebarWidth?o.launcher?.sidebarWidth??"420px":wn(No(o),"components.panel.width")??"420px";k?Je.style.cssText=`
83
83
  position: fixed !important;
84
84
  top: var(--persona-panel-inset) !important;
85
85
  bottom: var(--persona-panel-inset) !important;
@@ -137,9 +137,9 @@ _Details: ${n.message}_`:o}var jw=e=>bs(e)||e===Oo,Wa=class e{constructor(t={},n
137
137
  border-top: none !important;
138
138
  padding: 8px 16px 12px 16px !important;
139
139
  ${Tt?"background: transparent !important;":""}
140
- `)}if(!w&&!u){let Be="max-height: -moz-available !important; max-height: stretch !important;",Ye=m?"":"padding-top: 1.25em !important;",Ue=m?"":`z-index: ${o.launcher?.zIndex??Pn} !important;`;Je.style.cssText+=Be+Ye+Ue}$t(),Co()},tg=()=>{e.style.setProperty("--persona-content-max-width",Hs(o,Le()))},fy=!1;function my(){o.layout?.topFade&&ae.scrollTop>1?ae.setAttribute("data-persona-top-fade","true"):ae.removeAttribute("data-persona-top-fade")}let ng=()=>{my();let a=km(o,Le());Le()&&o.composer?.placement&&o.debug===!0&&!fy&&(fy=!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??Kp),Ot()},hy=()=>{if(Le())return;let a=Lt(o),u=o.launcher?.sidebarMode??!1;if(a||u||(o.launcher?.fullHeight??!1)||!ye)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=Hi(o);Ae.style.height=z.height,Ae.style.maxHeight=z.maxHeight};eg(),Ei(e,o),dc(e,o),pc(e,o),tg(),ng(),Us=()=>{eg(),hy(),Ei(e,o),dc(e,o),pc(e,o),tg(),ng(),Pc?e.style.setProperty("--persona-artifact-welded-outer-radius",Pc):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Vn(),dr()};let Se=[];Se.push(()=>{iy=!0}),Se.push(()=>{f.forEach(a=>a()),g.destroy()}),Se.push(()=>{document.removeEventListener("keydown",dy)}),Se.push(()=>{Jr!==null&&clearTimeout(Jr)});let zo=null,Ko=null;Se.push(()=>{zo?.(),zo=null,Ko?.(),Ko=null}),ol&&Se.push(()=>{ol?.disconnect(),ol=null}),Se.push(()=>{al?.(),al=null,Zu(),Ut&&(Ut.remove(),Ut=null),nt?.element.style.removeProperty("width"),nt?.element.style.removeProperty("maxWidth"),nt?.destroy()}),Me&&Se.push(()=>{_i=!0,Ft=null,lo!==null&&(cancelAnimationFrame(lo),lo=null),rn?.destroy(),rn=null,ft?.destroy(),ft=null,pn=null});let Vs=null,yy=()=>{Vs&&(Vs(),Vs=null),o.colorScheme==="auto"&&(Vs=Oa(()=>{Ei(e,o)}))};yy(),Se.push(()=>{Vs&&(Vs(),Vs=null)}),Se.push(()=>{L=!0,A?.()}),Se.push(()=>{V=!0});let by=!1;Se.push(()=>{by=!0});let og=(a,u)=>{let m=tc(a,u);return m||!ZS.includes(a)?m:(oA().then(v=>{if(by)return;ec(v.wipe),ec(v.glyphCycle);let w=tc(a,u);w&&rc(w,e)}).catch(()=>{}),null)},Dc=o.features?.streamAnimation;if(Dc?.type&&Dc.type!=="none"){let a=og(Dc.type,Dc.plugins);a&&rc(a,e),Se.push(()=>nA(e))}let vr=ac(co),vy=ac(gr),Cy=ac(Xr),js=[vr,vy,Cy];Se.push(()=>{js.forEach(a=>a.destroy())});let qs=null,R,zs=null,wy=!1,Sy=0,Ay=null,xy=a=>a.reduce((u,m)=>m.role==="user"?u+1:u,0),Ey=a=>{for(let u=a.length-1;u>=0;u--)if(gi(a[u]))return a[u].id??null;return null},My=!1,CE=()=>{My||o.debug!==!0||(My=!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".'))},Ty=!1,ky=!1,Py=(a,u)=>{Ty||o.debug!==!0||!u.enabled||u.expose||wy||ky&&(R.isStreaming()||a.some(gi)||(Ty=!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.")))},Ks=a=>{if(!R)return;let u=a??R.getMessages(),m=de=>{de.render([],R,ce,u)},v=de=>{js.forEach(Pe=>{Pe!==de&&m(Pe)})};zs&&(xy(u)>Sy||Ey(u)!==Ay)&&(zs=null);let w=xs(o);Py(u,w);let P=w.enabled?Bd(u):null,z=zs??P,re=zs?"host":"agent";if(z){let de=o.suggestions?.followUps,Pe=de?.placement??(de?"auto":"composer"),gt=(Pe==="auto"?Le()?"composer":"after-message":Pe)==="after-message"?Cy:vr;v(gt),gt.render(z,R,ce,u,o.suggestionChipsConfig,{source:re,surface:"followUp",variant:de?.variant??"chip",behavior:de?.behavior??"send",overflow:de?.overflow??"wrap",maxItems:de?.maxItems??4,config:o,plugins:d,submitPrompt:ld});return}if(u.some(de=>de.role==="user")){js.forEach(m);return}let Y=o.future?.v5Defaults===!0,ie=jn(),le=o.suggestions?.starters??(Y?{}:void 0);if(le){let de=Ws(E(),u),Pe=le.placement??"auto",it=Pe==="auto"?de?"welcome":"composer":Pe;if(it==="welcome"&&!de){CE(),js.forEach(m);return}let gt=it==="welcome"?vy:vr;v(gt),gt.render(le.items??o.suggestionChips,R,ce,u,o.suggestionChipsConfig,{surface:"starter",variant:le.variant??(Y&&!ie?"chip":"card"),behavior:le.behavior??"send",overflow:le.overflow??"wrap",maxItems:le.maxItems??(Y&&!ie?3:4),config:o,plugins:d,submitPrompt:ld});return}v(vr),vr.render(o.suggestionChips,R,ce,u,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:d,submitPrompt:ld})},Ly=()=>{zs&&(zs=null,Ks())},wE=a=>{let u=Array.isArray(a)?[...a]:[];if(!u.length){Ly();return}let m=R?R.getMessages():[];zs=u,wy=!0,Sy=xy(m),Ay=Ey(m),Ks(m)},no=!1,Mn=$S(),Yi=new Map,Gs=new Map,ns=new Map,Ys=null,os=null;function Xs(){if(!Ys)return;let a=Ys;Ys=null,os?.destroy(),os=null,Mn.delete(a),we.querySelector(`#wrapper-${a}`)?.removeAttribute("data-preserve-runtime"),R&&fo(Te,R.getMessages(),K)}let Qs=0,SE=nr()!==null,oo=zS(),ro=0,rs=null,qn=!1,Nc=!1,ss=0,an=null,Js=null,rg=!1,Xi=!1,Zs=null,ll=!0,Fc=!1,Qi=null,$c=!1,is=()=>{$c=!0,ME()},sg=null,AE=4,Cr=24,xE=80,EE=1e3,wr=null,Hy=()=>{e.setAttribute("data-persona-scrollbar",Ns()),Ns()!=="on-scroll"&&(wr!==null&&clearTimeout(wr),wr=null,ae.removeAttribute("data-persona-scrollbar-visible"))},ME=()=>{Ns()==="on-scroll"&&(ae.setAttribute("data-persona-scrollbar-visible",""),wr!==null&&clearTimeout(wr),wr=setTimeout(()=>{wr=null,Mi(ae,Cr)&&ae.removeAttribute("data-persona-scrollbar-visible")},EE))};Hy(),Se.push(()=>{wr!==null&&clearTimeout(wr)});let ig=new Map,ag=!1,Uc=null,Ge={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Po();let Iy=o.voiceRecognition?.autoResume??!1,lg=()=>R.isVoiceActive()||R.isBargeInActive(),Ry=!1,Sr=a=>{X.emit("voice:state",{active:Ge.active,source:a,timestamp:Date.now()})},zn=()=>{qe(a=>({...a,voiceState:{active:Ge.active,timestamp:Date.now(),manuallyDeactivated:Ge.manuallyDeactivated}}))},TE=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=wh(k.voiceState),u=!!a.active,m=Number(a.timestamp??0);Ge.manuallyDeactivated=!!a.manuallyDeactivated,u&&Date.now()-m<nH&&setTimeout(()=>{Ge.active||(Ge.manuallyDeactivated=!1,In(o.voiceRecognition?.provider)?R.toggleVoice().then(()=>{Ge.active=lg(),Sr("restore"),Ge.active?da():(zn(),ad(oH,1e4))}):ud("restore"))},In(o.voiceRecognition?.provider)?0:1e3)},Wy=a=>{Ry=!a.persisted,Ge.active&&zn()};typeof window<"u"&&(window.addEventListener("pagehide",Wy),Se.push(()=>window.removeEventListener("pagehide",Wy)));let kE=()=>R?cx(R.getMessages()).filter(a=>!a.__skipPersist):[],Vc=null,Oy=(a,u)=>{typeof console<"u"&&console.error(a,u)},jc=(a,u)=>{let m=()=>{try{let z=a();return!z||typeof z.then!="function"?null:Promise.resolve(z).catch(re=>{Oy(u,re)})}catch(z){return Oy(u,z),null}},v=Vc,w=v?v.then(()=>m()??void 0):m();if(!w)return;let P=w.finally(()=>{Vc===P&&(Vc=null)});Vc=P};function Ji(a){if(!T?.save)return;let u=a?cx(a):R?kE():[],m=_&&R?.getResumableHandle();m&&(k={...k,durableResume:{executionId:m.executionId,after:m.lastEventId}});let v={messages:u,metadata:k,artifacts:uo.artifacts,selectedArtifactId:uo.selectedId,...ei?{draft:ei}:{}};jc(()=>T.save(v),"[AgentWidget] Failed to persist state:")}let ei,qc=()=>!T?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,cl=bS({write:()=>{if(!qc())return;let a=be.getState(),u=hS({text:a.text,mentionRefs:a.mentionRefs,contentSegments:Ng(),selectedModelId:a.selectedModelId,activeModeIds:a.activeModeIds,quote:a.quote});JSON.stringify(u)!==JSON.stringify(ei)&&(ei=u,Ji())}});function _y(){qc()&&cl.schedule()}function cg(){cl.flush()}function By(a){if(!qc())return;let u=yS(a,{mentionSourceIds:(o.contextMentions?.sources??[]).map(m=>m.id),modelIds:(o.composer?.models??[]).map(m=>m.id),modes:o.composer?.modes??[]});u&&(ei=a,ce&&!ce.value&&(ce.value=u.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),po()),u.selectedModelId&&(be.setSelectedModelId(u.selectedModelId),Zr?.repaint()),Tc(u.activeModeIds??[]),u.quote&&qo(u.quote),cl.cancel())}function zc(){cl.cancel(),ei&&(ei=void 0,qc()&&Ji())}let Zi=null,Dy=()=>Je.querySelector("#persona-scroll-container")||ae,ea=()=>{Zi!==null&&(cancelAnimationFrame(Zi),Zi=null),qn=!1},Ny=()=>{rs!==null&&(cancelAnimationFrame(rs),rs=null),Nc=!1,ea()},PE=()=>no&&pg()&&(En()!=="anchor-top"||Za()),dg=()=>{let a=Qr()||"Jump to latest",u=PE();Vt.toggleAttribute("data-persona-scroll-to-bottom-streaming",u),ss>0?(tn.textContent=String(ss),tn.style.display="",Vt.setAttribute("aria-label",`${a} (${ss} new)`)):(tn.textContent="",tn.style.display="none",Vt.setAttribute("aria-label",u?`${a} (response streaming below)`:a))},Fy=()=>{ss!==0&&(ss=0,dg())},LE=()=>{let a=an?.spacerHeight??0;return a<=0?Mi(ae,Cr):Yc(a)-ae.scrollTop-ae.clientHeight<=Cr},pg=()=>Mo()?!oo.isFollowing():!LE(),ug=()=>!!R&&R.getMessages().length>0,Tn=()=>{if(!Nu()||wc()){Vt.parentNode&&Vt.remove(),Vt.style.display="none";return}Vt.parentNode!==we&&we.appendChild(Vt),Re();let u=ir(ae)>0&&pg()&&ug();u?dg():Fy(),Vt.style.display=u?"":"none"},ta=()=>{oo.pause()&&(Ny(),Tn())},Go=()=>{oo.resume(),Fy(),Tn()},as=(a=!1)=>{Mo()&&ug()&&oo.isFollowing()&&(!a&&!no||(rs!==null&&(cancelAnimationFrame(rs),rs=null),Nc=!0,rs=requestAnimationFrame(()=>{rs=null,Nc=!1,oo.isFollowing()&&HE(Dy(),a?220:140)})))},$y=(a,u,m,v=()=>!0)=>{let w=a.scrollTop,P=u(),z=P-w;if(ea(),Math.abs(z)<1){qn=!0,a.scrollTop=P,ro=a.scrollTop,qn=!1;return}let re=performance.now();qn=!0;let Y=le=>1-Math.pow(1-le,3),ie=le=>{if(!v()){ea();return}let de=u();de!==P&&(P=de,z=P-w);let Pe=le-re,it=Math.min(Pe/m,1),gt=Y(it),dt=w+z*gt;a.scrollTop=dt,ro=a.scrollTop,it<1?Zi=requestAnimationFrame(ie):(a.scrollTop=P,ro=a.scrollTop,Zi=null,qn=!1)};Zi=requestAnimationFrame(ie)},HE=(a,u=500)=>{let m=ir(a)-a.scrollTop;if(Math.abs(m)<1){ro=a.scrollTop;return}if(Math.abs(m)>=xE){ea(),qn=!0,a.scrollTop=ir(a),ro=a.scrollTop,qn=!1;return}$y(a,()=>ir(a),u,()=>oo.isFollowing())},gg=()=>{if(!ug()){Tn();return}let a=Dy();qn=!0,a.scrollTop=ir(a),ro=a.scrollTop,qn=!1,Tn()},ti=a=>{let u=0,m=a;for(;m&&m!==ae;)u+=m.offsetTop,m=m.offsetParent;return u},IE=()=>{let a=ae.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??ae.ownerDocument.getSelection()},Kc=()=>YS(IE(),ae),fg=()=>{if(Mc()!=="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=ae.querySelector(`[data-message-id="${m}"]`);if(!v)return!1;let w=Math.min(Math.max(0,ti(v)-Ds()),ir(ae));return qn=!0,ae.scrollTop=w,ro=ae.scrollTop,qn=!1,En()==="follow"&&!Mi(ae,Cr)&&oo.pause(),Tn(),!0},Gc=a=>{let u=Math.max(0,Math.round(a));Qt.style.height=`${u}px`,Qt.style.display=u>0?"":"none",an&&(an.spacerHeight=Math.max(0,a))},Yc=a=>{let u=parseFloat(getComputedStyle(ae).paddingBottom)||0,m=0;for(let w of Array.from(ae.children)){if(w===Qt||w.offsetHeight===0)continue;let P=ti(w)+w.offsetHeight;P>m&&(m=P)}let v=ae.scrollHeight-a;return m>0?Math.min(m+u,v):v},RE=()=>{if(!an||an.spacerHeight<=0)return;let a=Yc(an.spacerHeight),u=Math.max(0,Math.round(ae.scrollTop)+ae.clientHeight-a+Cr);u<an.spacerHeight&&(Gc(u),Tn())},ni=()=>{Js!==null&&(cancelAnimationFrame(Js),Js=null),ea(),an=null,Qt.style.height="0px",Qt.style.display="none"},Uy=a=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),mg=a=>ae.querySelector(`[data-message-id="${Uy(a)}"]`),Vy=a=>{Js!==null&&cancelAnimationFrame(Js),Js=requestAnimationFrame(()=>{Js=null;let u=Uy(a),m=ae.querySelector(`[data-message-id="${u}"]`);if(!m)return;let v=ti(m),w=an?.spacerHeight??0,P=Yc(w),{targetScrollTop:z,spacerHeight:re}=Lm({anchorOffsetTop:v,topOffset:Ds(),viewportHeight:ae.clientHeight,contentHeight:P,slack:Cr});an={initialSpacerHeight:re,contentHeightAtAnchor:P,spacerHeight:re},Gc(re),$y(ae,()=>m.isConnected?Math.max(0,ti(m)-Ds()):z,220)})},na=()=>{if(En()!=="anchor-top"||!an||!Qi)return;let a=mg(Qi);if(!a)return;ea();let u=an.spacerHeight,m=Yc(u),{targetScrollTop:v,spacerHeight:w}=Lm({anchorOffsetTop:ti(a),topOffset:Ds(),viewportHeight:ae.clientHeight,contentHeight:m,slack:Cr});an={initialSpacerHeight:w,contentHeightAtAnchor:m,spacerHeight:w},Gc(w),qn=!0,ae.scrollTop=v,ro=ae.scrollTop,qn=!1,Tn()},WE=()=>{if(Mo()){if(!oo.isFollowing()||Mi(ae,1))return;as(!no);return}if(an&&an.initialSpacerHeight>0){let a=ae.scrollHeight-an.spacerHeight,u=XS({initialSpacerHeight:an.initialSpacerHeight,contentHeightAtAnchor:an.contentHeightAtAnchor,currentContentHeight:a});u!==an.spacerHeight&&Gc(u)}Tn()},OE=a=>{let u=En();u==="follow"?(Go(),as(!0)):u==="anchor-top"&&(ll=!1,Fc=!0,$c=!1,Qi=a,Vy(a))},_E=()=>{if(En()==="anchor-top"){if(Fc){ll=!1;return}ll=!0,ni(),Go(),as(!0)}},BE=96,DE=a=>{if(Zs===null)return!0;let u=mg(Zs),m=mg(a);if(!u||!m)return!0;let v=ti(m)-ti(u);return Ds()+v>ae.clientHeight-BE},NE=a=>{if(En()!=="anchor-top"||!Fc||$c||Kc())return;let u=Zs===null;for(let m of a){if(!u){m.id===Zs&&(u=!0);continue}if(qS(m)){if(m.id===Qi||!DE(m.id))return;Qi=m.id,Vy(m.id);return}}},FE=a=>{let u=new Map;a.forEach(m=>{let v=ig.get(m.id);u.set(m.id,{streaming:m.streaming,role:m.role}),!v&&m.role==="assistant"&&(X.emit("assistant:message",m),!Xi&&(En()!=="anchor-top"||Za())&&pg()&&(ss+=1,dg(),Tn(),$s(ss===1?"1 new message below.":`${ss} new messages below.`))),m.role==="assistant"&&v?.streaming&&m.streaming===!1&&X.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(v?m.approval.status!=="pending"&&X.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):X.emit("approval:requested",{approval:m.approval,message:m}))}),ig.clear(),u.forEach((m,v)=>{ig.set(v,m)})},dl=(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")},Ar=(a,u)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${a}`,m.setAttribute("data-wrapper-id",a),dl(m,u),m},$E=(a,u,m)=>{let v=new Set;for(let O of u){let Ne=O.variant==="tool"?"tool":O.variant==="reasoning"?"reasoning":null;if(!Ne||Ts(o,Ne)!=="row")continue;let Fe=Ne==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;Fe?.expandable!==!1&&(v.add(O.id),i.observe(O,Ne,Ne==="tool"?r:s,Fe))}let w=document.createElement("div"),z=(()=>{let O=d.find(Ne=>Ne.renderLoadingIndicator);if(O?.renderLoadingIndicator)return O.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),re=(O,Ne)=>Ne==null?!1:typeof Ne=="string"?(O.textContent=Ne,!0):(O.appendChild(Ne),!0),Y=new Set,ie=new Map,le=new Set,de=d.some(O=>O.renderAskUserQuestion),Pe=[],it=[],gt=o.enableComponentStreaming!==!1,dt=o.approval!==!1,Kn=[],Dt=o.messageActions,jt=Dt?.showRegenerate===!0&&Dt.enabled!==!1&&go.current?.isStreaming()!==!0?Ow(u):null,_n=Dt?.showEdit===!0&&Dt.enabled!==!1,Kt=Dt?.showQuote===!0&&Dt.enabled!==!1,wt=null,Jo=o.features?.reasoningDisplay?.completedVisibility,Zo=O=>Jo==="removed"?!0:Jo==="removed-when-short"?vv(O,o.features?.reasoningDisplay?.shortThinkThreshold):!1,bo=o.features?.toolCallDisplay?.completedVisibility==="removed",vo=O=>O.variant==="reasoning"&&O.reasoning?.status==="complete"?Zo(O.reasoning):bo&&O.variant==="tool"&&O.toolCall?.status==="complete";if(u.forEach(O=>{if(vo(O))return;if(Y.add(O.id),ie.set(O.id,O.role),Ys===O.id&&os){let $e=Ar(O.id,O.role);$e.setAttribute("data-persona-message-edit-stub","true"),$e.setAttribute("data-preserve-runtime","true"),w.appendChild($e),wt={messageId:O.id,element:os.element};return}let Ne=de&&Ir(O),Fe=dt&&O.variant==="approval"&&!!O.approval,se=!Ne&&O.role==="assistant"&&!O.variant&&gt&&hc(O);!Fe&&ns.has(O.id)&&(a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),ns.delete(O.id)),!se&&Gs.has(O.id)&&(a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),Gs.delete(O.id));let St=Ir(O)?`:${O.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${O.agentMetadata?.askUserQuestionAnswers?Object.keys(O.agentMetadata.askUserQuestionAnswers).length:0}`:"",Jt={canRegenerate:jt===O.id,canEdit:_n&&pm(O),canQuote:Kt&&!O.variant&&(O.content?.trim().length??0)>0},Hn=`${Jt.canRegenerate?"r":""}${Jt.canEdit?"e":""}${Jt.canQuote?"q":""}`,mn=FS(O,Qs)+St+`:${Hn}`,Tt=Ne||Fe||se?null:US(Mn,O.id,mn);if(Tt){w.appendChild(Tt.cloneNode(!0)),Ir(O)&&O.toolCall?.id&&O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(le.add(O.toolCall.id),Ju(O));return}let Gt=null,ln=d.find($e=>!!(O.variant==="reasoning"&&$e.renderReasoning||O.variant==="tool"&&$e.renderToolCall||!O.variant&&$e.renderMessage)),We=o.layout?.messages;if(Ir(O)&&O.agentMetadata?.askUserQuestionAnswered===!0){Yi.delete(O.id),a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime");return}if(gi(O)&&xs(o).enabled)return;if(Ir(O)&&o.features?.askUserQuestion?.enabled!==!1){let $e=d.find(cn=>typeof cn.renderAskUserQuestion=="function");if($e&&go.current){let cn=Yi.get(O.id),Co=cn!==mn,hn=null;if(Co){let{payload:Ye,complete:Ue}=Rr(O),hs=O.id,nn=()=>go.current?.getMessages().find(Gn=>Gn.id===hs);hn=$e.renderAskUserQuestion({message:O,payload:Ye,complete:Ue,resolve:Gn=>{let kr=nn();kr&&go.current?.resolveAskUserQuestion(kr,Gn)},dismiss:()=>{let Gn=nn();Gn?.agentMetadata?.awaitingLocalTool&&(go.current?.markAskUserQuestionResolved(Gn),go.current?.resolveAskUserQuestion(Gn,"(dismissed)"))},config:o})}let At=cn!=null;if(Co&&hn===null&&!At){O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(le.add(O.toolCall.id),Ju(O));return}let Be=Ar(O.id,O.role);Be.setAttribute("data-ask-plugin-stub","true"),Be.setAttribute("data-preserve-runtime","true"),w.appendChild(Be),Pe.push({messageId:O.id,fingerprint:mn,bubble:hn});return}else{O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(le.add(O.toolCall.id),Ju(O));return}}else if(Fe){let $e=B();if(!$e){w.appendChild(Ar(O.id,O.role));return}let cn=d.find(Be=>typeof Be.renderApproval=="function")??C,hn=ns.get(O.id)!==mn,At=null;if(hn&&cn?.renderApproval){let Be=O.id,Ye=(Ue,hs)=>{let nn=go.current?.getMessages().find(Gn=>Gn.id===Be);nn?.approval&&(nn.approval.toolType==="webmcp"?go.current?.resolveWebMcpApproval(nn.id,Ue):go.current?.resolveApproval(nn.approval,Ue,hs))};At=cn.renderApproval({message:O,defaultRenderer:()=>$e.createApprovalBubble(O,o,l),config:o,approve:Ue=>Ye("approved",Ue),deny:Ue=>Ye("denied",Ue)})}if(hn&&At===null)a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),ns.delete(O.id),Gt=$e.createApprovalBubble(O,o,l);else{let Be=Ar(O.id,O.role);Be.setAttribute("data-approval-plugin-stub","true"),Be.setAttribute("data-preserve-runtime","true"),w.appendChild(Be),Kn.push({messageId:O.id,fingerprint:mn,bubble:At});return}}else if(ln)if(O.variant==="reasoning"&&O.reasoning&&ln.renderReasoning){if(!te)return;Gt=ln.renderReasoning({message:O,defaultRenderer:()=>rh(O,o,s),config:o})}else if(O.variant==="tool"&&O.toolCall&&ln.renderToolCall){if(!ve)return;Gt=ln.renderToolCall({message:O,defaultRenderer:()=>lh(O,o,r),config:o})}else ln.renderMessage&&(Gt=ln.renderMessage({message:O,defaultRenderer:()=>{let $e=Fa(O,m,We,o.messageActions,to,{loadingIndicatorRenderer:z,widgetConfig:o,actionEligibility:Jt});return O.role!=="user"&&j($e,O,o,R),$e},config:o}));if(!Gt&&se){let $e=mu(O);if($e){let cn=Gs.get(O.id),Co=cn!==mn,hn=o.wrapComponentDirectiveInBubble!==!1&&Fo.getOptions($e.component)?.bubbleChrome!==!1,At=null;if(Co){let Be=fu($e,{config:o,message:O,transform:m});if(Be&&$e.component==="PersonaArtifactInline"){let Ye=Be.hasAttribute("data-artifact-inline")?Be:Be.querySelector("[data-artifact-inline]"),Ue=Ye?.getAttribute("data-artifact-inline")??"",hs=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Ue):Ue,nn=Ue?a.querySelector(`#wrapper-${O.id}`)?.querySelector(`[data-artifact-inline="${hs}"]`)??null:null;Ye&&nn&&nn!==Ye&&qr()?.hasLiveInlineArtifactBlock(nn)&&(Ye===Be?Be=nn:Ye.replaceWith(nn))}if(Be)if(hn){let Ye=document.createElement("div");if(Ye.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ye.id=`bubble-${O.id}`,Ye.setAttribute("data-message-id",O.id),O.content&&O.content.trim()){let Ue=document.createElement("div");Ue.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Ue.innerHTML=m({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),Ye.appendChild(Ue)}Ye.appendChild(Be),At=Ye}else{let Ye=document.createElement("div");if(Ye.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ye.id=`bubble-${O.id}`,Ye.setAttribute("data-message-id",O.id),Ye.setAttribute("data-persona-component-directive","true"),O.content&&O.content.trim()){let Ue=document.createElement("div");Ue.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Ue.innerHTML=m({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),Ye.appendChild(Ue)}Ye.appendChild(Be),At=Ye}}if(At||cn!=null){let Be=Ar(O.id,O.role);Be.setAttribute("data-component-directive-stub","true"),Be.setAttribute("data-preserve-runtime","true"),w.appendChild(Be),it.push({messageId:O.id,fingerprint:mn,bubble:At});return}}}if(!Gt)if(O.variant==="reasoning"&&O.reasoning){if(!te)return;Gt=rh(O,o,s)}else if(O.variant==="tool"&&O.toolCall){if(!ve)return;Gt=lh(O,o,r)}else if(O.variant==="approval"&&O.approval){if(o.approval===!1)return;let $e=B();if(!$e)return;Gt=$e.createApprovalBubble(O,o,l)}else{let $e=o.layout?.messages;$e?.renderUserMessage&&O.role==="user"?Gt=$e.renderUserMessage({message:O,config:o,streaming:!!O.streaming}):$e?.renderAssistantMessage&&O.role==="assistant"?Gt=$e.renderAssistantMessage({message:O,config:o,streaming:!!O.streaming}):Gt=Fa(O,m,$e,o.messageActions,to,{loadingIndicatorRenderer:z,widgetConfig:o,actionEligibility:Jt}),O.role!=="user"&&Gt&&j(Gt,O,o,R)}let kt=Ar(O.id,O.role);kt.appendChild(Gt),VS(Mn,O.id,mn,kt),w.appendChild(kt)}),et.composerOverlay&&et.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let Fe=Ne.getAttribute("data-persona-ask-sheet-for");Fe&&!le.has(Fe)&&Wr(et.composerOverlay,Fe)}),o.features?.toolCallDisplay?.grouped){let O=[],Ne=[],Fe=o.features.toolCallDisplay.groupedMode==="summary";u.forEach(se=>{if(se.variant==="tool"&&se.toolCall&&ve){if(bo&&se.toolCall.status==="complete")return;Ne.push(se);return}se.variant==="reasoning"&&(!te||se.reasoning?.status==="complete"&&Zo(se.reasoning))||((Ne.length>1||Fe&&Ne.length>0)&&O.push(Ne),Ne=[])}),(Ne.length>1||Fe&&Ne.length>0)&&O.push(Ne),O.forEach(se=>{let St=se.map(We=>Array.from(w.children).find(kt=>kt instanceof HTMLElement&&kt.getAttribute("data-wrapper-id")===We.id)).filter(We=>!!We);if(St.length<(Fe?1:2))return;let Jt=Ar(`tool-group-${se[0].id}`,"assistant");if(Jt.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let We=`tool-group-${se[0].id}`,kt=se.some(At=>At.toolCall?.status!=="complete"),$e={...se[0],id:We,toolCall:{id:We,name:`${se.length} tools`,status:kt?"running":"complete",chunks:se.flatMap(At=>At.toolCall?.chunks??[]),success:!se.some(At=>At.toolCall?.success===!1)}};v.add(We),i.observe($e,"tool",r,o.features.toolCallDisplay);let cn=`${kt?"Using":"Used"} ${se.length} tools`,Co=o.toolCall?.renderGroupedSummary?.({messages:se,toolCalls:se.map(At=>At.toolCall),defaultSummary:cn,config:o}),hn=aw($e,o,r.has(We),Co??cn);hn.bubble.classList.add("persona-tool-group"),hn.body.dataset.personaToolGroupStack="true",St[0].before(Jt),Jt.appendChild(hn.bubble),St.forEach((At,Be)=>{At.style.setProperty("--persona-message-row-max-width","100%"),At.style.setProperty("--persona-activity-stagger",`${Be*40}ms`),At.classList.add("persona-activity-group-child"),hn.body.appendChild(At)});return}let Hn=document.createElement("div");Hn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Hn.setAttribute("data-persona-tool-group","true");let mn=document.createElement("div");mn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",mn.id=`tool-group-summary-${se[0].id}`;let Tt=`Called ${se.length} ${se.length===1?"tool":"tools"}`,Gt=o.toolCall?.renderGroupedSummary?.({messages:se,toolCalls:se.map(We=>We.toolCall).filter(We=>!!We),defaultSummary:Tt,config:o});re(mn,Gt)||(mn.textContent=Tt);let ln=document.createElement("div");ln.className="persona-tool-group-stack persona-flex persona-flex-col",ln.id=`tool-group-stack-${se[0].id}`,ln.setAttribute("data-persona-tool-group-stack","true"),Hn.appendChild(mn),Fe||Hn.appendChild(ln),Jt.appendChild(Hn),St[0].before(Jt),St.forEach((We,kt)=>{if(Fe){We.remove();return}We.style.setProperty("--persona-message-row-max-width","100%");let $e=document.createElement("div");$e.className="persona-tool-group-item persona-relative",$e.setAttribute("data-persona-tool-group-item","true"),kt<St.length-1&&$e.setAttribute("data-persona-tool-group-connector","true"),$e.appendChild(We),ln.appendChild($e)})})}i.prune(v),jS(Mn,Y);let fs=O=>O.variant==="tool"&&!ve||O.variant==="reasoning"&&!te||vo(O),er=u.some(O=>O.role==="assistant"&&O.streaming&&!fs(O)),Io=u.length-1;for(;Io>=0&&fs(u[Io]);)Io--;let ms=Io>=0?u[Io]:void 0,xl=Io<u.length-1,ai=ms?.role==="assistant"&&!ms.streaming&&ms.variant!=="approval"&&!xl;if(no&&u.some(O=>O.role==="user")&&!er&&!ai){let O={config:o,streaming:!0,location:"standalone",defaultRenderer:Li},Ne=d.find(se=>se.renderLoadingIndicator),Fe=null;if(Ne?.renderLoadingIndicator&&(Fe=Ne.renderLoadingIndicator(O)),Fe===null&&o.loadingIndicator?.render&&(Fe=o.loadingIndicator.render(O)),Fe===null&&(Fe=Li()),Fe){let se=document.createElement("div"),St=o.loadingIndicator?.showBubble!==!1,Jt=o.layout?.messages?.layout??"bubble";se.className=St?cc("assistant",Jt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),se.setAttribute("data-typing-indicator","true"),St&&(se.style.color="var(--persona-message-assistant-text, var(--persona-text))",Jt!=="flat"&&(se.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",se.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),se.appendChild(Fe);let Hn=Ar("typing-indicator","assistant");Hn.appendChild(se),w.appendChild(Hn)}}if(!no&&u.length>0){let O=u[u.length-1],Ne={config:o,lastMessage:O,messageCount:u.length},Fe=d.find(St=>St.renderIdleIndicator),se=null;if(Fe?.renderIdleIndicator&&(se=Fe.renderIdleIndicator(Ne)),se===null&&o.loadingIndicator?.renderIdle&&(se=o.loadingIndicator.renderIdle(Ne)),se){let St=document.createElement("div"),Jt=o.loadingIndicator?.showBubble!==!1;St.className=Jt?["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(" "),St.setAttribute("data-idle-indicator","true"),St.appendChild(se);let Hn=Ar("idle-indicator","assistant");Hn.appendChild(St),w.appendChild(Hn)}}if(Sw(w),Gp(a,w),im(a),wt){let{messageId:O,element:Ne}=wt,Fe=a.querySelector(`#wrapper-${O}`);Fe&&Ne.parentElement!==Fe&&(dl(Fe,ie.get(O)??"user"),Fe.replaceChildren(Ne))}if(Pe.length>0)for(let{messageId:O,fingerprint:Ne,bubble:Fe}of Pe){let se=a.querySelector(`#wrapper-${O}`);se&&(dl(se,ie.get(O)??"assistant"),Fe!==null&&(se.replaceChildren(Fe),se.setAttribute("data-bubble-fp",Ne),Yi.set(O,Ne)))}if(Yi.size>0)for(let O of Yi.keys())Y.has(O)||Yi.delete(O);if(it.length>0)for(let{messageId:O,fingerprint:Ne,bubble:Fe}of it){let se=a.querySelector(`#wrapper-${O}`);se&&(dl(se,ie.get(O)??"assistant"),Fe!==null&&(se.replaceChildren(Fe),se.setAttribute("data-bubble-fp",Ne),Gs.set(O,Ne)))}if(Gs.size>0)for(let O of Gs.keys())Y.has(O)||Gs.delete(O);if(Kn.length>0)for(let{messageId:O,fingerprint:Ne,bubble:Fe}of Kn){let se=a.querySelector(`#wrapper-${O}`);se&&(dl(se,ie.get(O)??"assistant"),Fe!==null&&(se.replaceChildren(Fe),se.setAttribute("data-bubble-fp",Ne),ns.set(O,Ne)))}if(ns.size>0)for(let O of ns.keys())Y.has(O)||ns.delete(O)},hg=!1,Xc=()=>{hg||(hg=!0,mi().catch(()=>{}),vd().catch(()=>{hg=!1}))},fo=(a,u,m)=>{u.length>0&&Xc(),$E(a,u,m),sy()},pl=null,UE=()=>{if(pl)return;let a=m=>{let v=m.composedPath();v.includes(Je)||Xt&&v.includes(Xt)||Mt(!1,"user")};pl=a,(e.ownerDocument??document).addEventListener("pointerdown",a,!0)},jy=()=>{if(!pl)return;(e.ownerDocument??document).removeEventListener("pointerdown",pl,!0),pl=null};Se.push(()=>jy());let ul=null,VE=()=>{if(ul)return;let a=m=>{m.key==="Escape"&&(m.isComposing||Mt(!1,"user"))};ul=a,(e.ownerDocument??document).addEventListener("keydown",a,!0)},qy=()=>{if(!ul)return;(e.ownerDocument??document).removeEventListener("keydown",ul,!0),ul=null};Se.push(()=>qy());let gl=!1,zy=new Set,jE=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},oa=()=>{if(!Le())return;let a=et.peekBanner,u=et.peekTextNode;if(!a||!u)return;if(D){a.classList.remove("persona-pill-peek--visible");return}let m=R?.getMessages()??[],v;for(let Dt=m.length-1;Dt>=0;Dt--){let jt=m[Dt];if(jt.role==="assistant"&&jt.content){v=jt;break}}if(!v){a.classList.remove("persona-pill-peek--visible");return}let w=v.content,P=!!v.streaming,z=jE(),re=Yp(z),Y=re.type!=="none"?og(re.type,z?.plugins):null,ie=Y?.isAnimating?.(v)===!0,le=Y!==null&&(P||ie);le&&Y&&!zy.has(Y.name)&&(rc(Y,e),zy.add(Y.name));let de=le&&Y?.containerClass?Y.containerClass:null,Pe=u.dataset.personaPeekStreamClass??null;Pe&&Pe!==de&&(u.classList.remove(Pe),delete u.dataset.personaPeekStreamClass),de&&Pe!==de&&(u.classList.add(de),u.dataset.personaPeekStreamClass=de),le?(u.style.setProperty("--persona-stream-step",`${re.speed}ms`),u.style.setProperty("--persona-stream-duration",`${re.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let it=le?Xp(w,re.buffer,Y,v,P):w;if(le&&re.placeholder==="skeleton"&&P&&(!it||!it.trim())){let Dt=document.createElement("div"),jt=oc();jt.classList.add("persona-pill-peek__skeleton"),Dt.appendChild(jt),Gp(u,Dt)}else{let Dt=Math.max(0,it.length-100),jt=it.length>100?it.slice(-100):it,_n=Ur(jt);if(!le||!Y){let Kt=it.length>100?`\u2026${jt}`:jt;u.textContent!==Kt&&(u.textContent=Kt)}else{let Kt=_n;(Y.wrap==="char"||Y.wrap==="word")&&(Kt=nc(_n,Y.wrap,`peek-${v.id}`,{skipTags:Y.skipTags,startIndex:Dt}));let wt=document.createElement("div");if(wt.innerHTML=Kt,Y.useCaret&&jt.length>0){let Jo=Qp(),Zo=wt.querySelectorAll(".persona-stream-char, .persona-stream-word"),bo=Zo[Zo.length-1];bo?.parentNode?bo.parentNode.insertBefore(Jo,bo.nextSibling):wt.appendChild(Jo)}Gp(u,wt),Y.onAfterRender?.({container:u,bubble:a,messageId:v.id,message:v,speed:re.speed,duration:re.duration})}}let Kn=no||gl;a.classList.toggle("persona-pill-peek--visible",Kn)};if(Le()){let a=et.peekBanner;if(a){let v=w=>{w.preventDefault(),w.stopPropagation(),Mt(!0,"user")};a.addEventListener("pointerdown",v),Se.push(()=>{a.removeEventListener("pointerdown",v)})}let u=()=>{gl||(gl=!0,oa())},m=()=>{gl&&(gl=!1,oa())};Ae.addEventListener("pointerenter",u),Ae.addEventListener("pointerleave",m),Se.push(()=>{Ae.removeEventListener("pointerenter",u),Ae.removeEventListener("pointerleave",m)}),Xt&&(Xt.addEventListener("pointerenter",u),Xt.addEventListener("pointerleave",m),Se.push(()=>{Xt.removeEventListener("pointerenter",u),Xt.removeEventListener("pointerleave",m)}))}let qE=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",re=u.modalMaxWidth??"880px",Y=u.modalMaxHeight??"min(90vh, 800px)",ie="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",de=Je.style;if(de.left="",de.right="",de.top="",de.bottom="",de.transform="",de.width="",de.maxWidth="",de.height="",de.maxHeight="",Xt){let Pe=Xt.style;Pe.bottom=v,Pe.width=w??""}if(a&&m!=="fullscreen"){if(m==="modal"){de.top="50%",de.left="50%",de.transform="translate(-50%, -50%)",de.bottom="auto",de.right="auto",de.width=re,de.maxWidth=ie,de.maxHeight=Y,de.height=Y;return}de.left="50%",de.transform="translateX(-50%)",de.bottom=`calc(${v} + ${le})`,de.top=z,de.width=P,de.maxWidth=ie}},fl=()=>{if(D&&Xc(),!Xe())return;if(Le()){let ie=(o.launcher?.composerBar??{}).expandedSize??"anchored",le=D?"expanded":"collapsed";Je.dataset.state=le,Je.dataset.expandedSize=ie,Xt&&(Xt.dataset.state=le,Xt.dataset.expandedSize=ie),Je.style.removeProperty("display"),Je.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),qE(D),we.style.display=D?"flex":"none",Us(),D?(UE(),VE()):(jy(),qy()),oa();return}let a=Lt(o),u=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,v=o.launcher?.mobileFullscreen??!0,w=u.innerWidth<=m,P=v&&w&&ye,z=Zn(o).reveal;D?(Je.style.removeProperty("display"),Je.style.display=a?"flex":"",Je.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-95","persona-opacity-0"),Ae.classList.add("persona-scale-100","persona-opacity-100"),qt?(qt.setPanelOpen(!0),qt.element.style.display="none"):On&&(On.style.display="none")):(a?a&&(z==="overlay"||z==="push")&&!P?(Je.style.removeProperty("display"),Je.style.display="flex",Je.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Je.style.setProperty("display","none","important"),Je.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Je.style.display="",Je.classList.add("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-100","persona-opacity-100"),Ae.classList.add("persona-scale-95","persona-opacity-0")),qt?(qt.setPanelOpen(!1),qt.element.style.display=a?"none":""):On&&(On.style.display=a?"none":""))},Mt=(a,u="user")=>{if(!Xe()||D===a)return;let m=D;D=a,fl();let v=(()=>{let P=o.launcher?.sidebarMode??!1,z=e.ownerDocument.defaultView??window,re=o.launcher?.mobileFullscreen??!0,Y=o.launcher?.mobileBreakpoint??640,ie=z.innerWidth<=Y,le=Lt(o)&&re&&ie,de=Le()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return P||re&&ie&&ye||le||de})();if(D&&v){if(!zo){let P=e.getRootNode(),z=P instanceof ShadowRoot?P.host:e.closest(".persona-host");z&&(zo=Rm(z,o.launcher?.zIndex??Pn))}Ko||(Ko=Wm(e.ownerDocument))}else D||(zo?.(),zo=null,Ko?.(),Ko=null);D&&(wl(),fg()||(En()==="follow"?as(!0):gg()));let w={open:D,source:u,timestamp:Date.now()};D&&!m?X.emit("widget:opened",w):!D&&m&&X.emit("widget:closed",w),X.emit("widget:state",{open:D,launcherEnabled:ye,voiceActive:Ge.active,streaming:R.isStreaming()})},ls={inputDisabled:!1,sendDisabled:!1},Yo=()=>ls.inputDisabled,yg=()=>In(o.voiceRecognition?.provider)&&!!R&&(R.isBargeInActive()||["listening","processing","speaking"].includes(R.getVoiceStatus())),oi=()=>ls.inputDisabled||ls.sendDisabled,zE=()=>(ls.inputDisabled?ls.inputReason:void 0)??(ls.sendDisabled?ls.sendReason:void 0);function bg(){if(!ke)return;if(be.getState().phase==="streaming"){ke.disabled=!1;return}let a=je?!je.isReady():!1;ke.disabled=oi()||a}function Qc(){if(!Wn)return;let a=be.getState(),u=o.sendButton?.visibility==="when-text"&&a.phase!=="streaming"&&a.text.trim().length===0&&a.attachments.length===0;Wn.toggleAttribute("data-persona-send-hidden",u)}function KE(){let a=zE();if(Le()){let u=An??Ke;a?u.setAttribute("title",a):u.removeAttribute("title"),Ke.toggleAttribute(Ya,!!a);return}if(a){tt.setAttribute("role","status"),tt.setAttribute("aria-live","polite"),tt.setAttribute(Ya,""),tt.removeAttribute(yc),tt.textContent=a,hi(tt,o.statusIndicator??{},"idle");return}if(tt.hasAttribute(Ya)&&(tt.removeAttribute("role"),tt.removeAttribute("aria-live"),tt.removeAttribute(Ya),h)){let u=R.getStatus();_s(tt,ur(u),o.statusIndicator??{},u)}}function vg(){let a=Nf(o.composer?.inputDisabled),u=Nf(o.composer?.sendDisabled);ls={inputDisabled:a.disabled,inputReason:a.reason,sendDisabled:u.disabled,sendReason:u.reason},be.setInputDisabled(a.disabled),be.setSendDisabled(u.disabled);let m=be.getState().phase==="streaming",v=a.disabled,w=m||v;ce&&(ce instanceof HTMLTextAreaElement?ce.disabled=v:ce.setAttribute("contenteditable",v?"false":"true"),ce.setAttribute("aria-disabled",v?"true":"false")),It&&(It.disabled=v),Et&&(Et.disabled=v);for(let P of at?.affordanceButtons??[])P.querySelectorAll("button").forEach(z=>{z.disabled=v});he&&(he.disabled=v||m&&!yg()),js.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})}),Eg.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})}),Ke.dataset.personaComposerStreaming=m?"true":"false",Ke.dataset.personaComposerInputDisabled=v?"true":"false",Ke.dataset.personaComposerSendDisabled=oi()?"true":"false",Ke.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(P=>{(P instanceof HTMLButtonElement||P instanceof HTMLInputElement||P instanceof HTMLTextAreaElement||P instanceof HTMLSelectElement)&&(P.disabled=m)}),bg(),KE()}let ml=a=>{be.setStreaming(a),xc(a?"stop":"send"),vg()},Jc=()=>{Ge.active||ce&&ce.focus()};X.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Jc(),200)});let Ky=null,Cg=!1,wg=!en.hidden,cs=null,Sg=!J,Zc=null;Se.push(()=>{Zc?.cancel(),Zc=null});let GE=a=>{let u=AA(a);if(u===N)return;N=u,e.setAttribute("data-persona-conversation-state",u);let m=pe();Ot(),Sg&&(Zc?.cancel(),Zc=wA(Ke,u==="active"?m:pe(),u==="active"?"drop":"rise",E().layout==="centered"?320:260)),na()},Gy=null,Yy,Xy=null,ra=null,Ag=!1,hl=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!==Gy||u.icon!==Yy)&&(Gy=m,Yy=u.icon,su({host:en,iconHolder:Sc,kicker:Ac,title:Bu,subtitle:Ni,starterSuggestions:gr},u));let v=u.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${u.message}`;v!==Xy&&(Xy=v,iu(Rn,u.message,o));let w=a??(R?R.getMessages():o.initialMessages);GE(w);let P=Cg,z=!P&&Ws(u,w),re=z!==wg;if(wg=z,ra){cs?.cancel(),cs=null,P!==Ag&&(Ag=P,P?Xm(ae,en,null):Ym(ae,en,ra)),$a(ae,en,!P);return}if(re&&!z&&!P&&u.dismiss==="on-first-message"&&Sg){cs=CA(en,ie=>{cs===ie&&(cs=null),!wg&&!ra&&($a(ae,en,!1),na()),ie?.cancel()});return}if(cs){if(!z&&!P)return;cs.cancel(),cs=null}let Y=!en.hidden;$a(ae,en,z),!z&&Y&&na()},xg=[],Eg=[],Mg=!1,Qy=null,Jy,Zy=()=>{Eg.length=0;let a=xg.splice(0,xg.length);for(let u of a)try{u()}catch(m){console.warn("[persona] renderWelcome cleanup threw",m)}};Se.push(Zy);let YE=(a,u)=>{let m=_m(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=Bm({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:()=>ce,eventTarget:en,submitPrompt:ld});return Eg.push(w),w},Tg=()=>{if(Mg)return;Mg=!0;let a=E();Qy=`${a.variant}|${a.layout}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`,Jy=a.icon;try{Zy(),Xm(ae,en,ra),ra=null,Ag=!1;let u=R?R.getMessages():o.initialMessages,m=Ws(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:()=>en,sendMessage:z=>{if(!R||R.isStreaming())return;let re=z.trim();re&&R.sendMessage(re)},requestRender:()=>Tg(),renderStarter:z=>YE(z,v++),storage:y(P.id),onCleanup:z=>{xg.push(z)}}),w))break;w&&w!==en&&(ra=w,Ym(ae,en,w))}finally{Mg=!1}hl()},XE=()=>{let a=E();`${a.variant}|${a.layout}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`===Qy&&a.icon===Jy||Tg()},ed=()=>{hl(),Ki||(ce.placeholder=pS(be.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!R?.isStreaming()&&(ke.textContent=o.copy?.sendButtonLabel??"Send")),ce.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ce.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},QE=!!o.setStoredConversationId,sa=a=>qe(u=>{let m={...u};return delete m[a],m}),td=a=>{let u=k[a];return typeof u=="string"?u:null},eb=()=>{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:()=>td("sessionId"),setStoredSessionId:a=>{qe(u=>({...u,sessionId:a}))},clearStoredSessionId:o.clearStoredSessionId??(()=>sa("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>td("conversationId")),setStoredConversationId:o.setStoredConversationId??(a=>{qe(u=>({...u,conversationId:a}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>sa("conversationId"))});let tb=()=>o.clientToken??null,nb=a=>ox(a,Ct(),o.persistState===!1),ob=tb(),mo=ob?nb(ob):null,JE=()=>{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")}},ds={...mo?{visitorStore:mo}:{},historyBootstrapReady:o.features?.history?.enabled===!0&&!wp()?Promise.all([ue,me]).then(()=>{}):ue,getStoredMessageCursor:()=>td("historyMessageCursor"),setStoredMessageCursor:a=>{if(a===null){sa("historyMessageCursor");return}qe(u=>({...u,historyMessageCursor:a}))},getPendingDisplayProjections:JE,setPendingDisplayProjections:a=>{if(!a){sa("pendingDisplayProjections");return}qe(u=>({...u,pendingDisplayProjections:a}))},getStoredResumableHandle:eb,setStoredResumableHandle:a=>{if(!a){sa("durableResume");return}qe(u=>({...u,durableResume:a}))},shouldResumeDurableConversation:()=>_&&eb()!==null,...QE?{}:{getStoredConversationRevision:()=>td("conversationRevision"),setStoredConversationRevision:a=>{if(a===null){sa("conversationRevision");return}qe(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),Se.push(()=>{u?.removeEventListener("pagehide",v),u?.removeEventListener("pageshow",w)}),o={...o,reconnectStream:o.reconnectStream??(P=>R.getClient().reconnectClientTokenStream(P)),onExecutionState:P=>{(P||!m)&&ds.setStoredResumableHandle?.(P?{executionId:P.executionId,after:P.lastEventId}:null),a?.(P)}}}let ZE=()=>{let a=tb();if(a&&mo?.matches(a,Ct(),o.persistState===!1)||!a&&!mo)return;mo?.destroy(),mo=a?nb(a):null;let u={...ds};mo?u.visitorStore=mo:delete u.visitorStore,ds=u,R.setHistoryInternals(ds)},ri=null,eM=()=>{ri==null&&(ri=setInterval(()=>{let a=Te.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(ri),ri=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")?Ul(u-v):Ed(u-v))})},100))},kg=(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,re)=>kg(z,u[re]));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)&&kg(m[z],v[z]))},rb=a=>{let{content:u,rawContent:m,llmContent:v,...w}=a;return w},Pg=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!hc(a),tM=(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))&&Pg(v)&&Pg(w)&&kg(rb(v),rb(w))},nd=null,ia=null,si=null,xr=null,Lg=null,nM=a=>{if(!_)return Ji(a);Lg=a,queueMicrotask(()=>{Lg===a&&(Lg=null,Ji(a))})},od=a=>{nd=a;let u,m;ia=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),!ia&&Pg(P)&&(ia={index:w,id:P.id}),u&&m&&ia)break}fo(Te,a,K),qr()?.updateInlineArtifactBlocks(Te,uo.artifacts,{suppressTransition:no}),eM(),hl(a),Ks(a),as(!no),FE(a),a.length===0&&(ni(),ll=!0,Fc=!1,Qi=null,$c=!1),!rg||Xi?(rg=!0,Zs=u?.id??null,sg=m?.id??null):u&&u.id!==Zs?(Zs=u.id,OE(u.id)):m&&m.id!==sg&&_E(),m&&(sg=m.id),NE(a);let v=Ge.lastUserMessageId;u&&u.id!==v&&(Ge.lastUserMessageId=u.id,X.emit("user:message",u)),Ge.lastUserMessageWasVoice=!!u?.viaVoice,nM(a),oa()},Hg=()=>{xr!==null&&(cancelAnimationFrame(xr),xr=null);let a=si;si=null,a&&od(a)},sb=()=>{xr!==null&&cancelAnimationFrame(xr),xr=null,si=null},oM=a=>{let u=si??nd;if(no&&u&&ia&&tM(u,a,ia)){si=a,xr===null&&(xr=requestAnimationFrame(()=>{xr=null;let m=si;si=null,m&&od(m)}));return}if(a.length===0){sb(),od(a);return}Hg(),od(a)};R=new Wa(o,{onMessagesChanged(a){oM(a)},onStatusChanged(a){let u=o.statusIndicator??{};_s(tt,(v=>v==="idle"?u.idleText??Yt.idle:v==="connecting"?u.connectingText??Yt.connecting:v==="connected"?u.connectedText??Yt.connected:v==="error"?u.errorText??Yt.error:v==="paused"?u.pausedText??Yt.paused:v==="resuming"?u.resumingText??Yt.resuming:Yt[v])(a),u,a),Yr()},onStreamingChanged(a){a||(R?.getMessages().length===0?sb():Hg()),no=a,ml(a),Yr(),R&&fo(Te,R.getMessages(),K),a||(as(!0),RE(),ky=!0,R&&Py(R.getMessages(),xs(o))),Tn(),$s(a?"Responding\u2026":"Response complete."),oa()},onVoiceStatusChanged(a){if(X.emit("voice:status",{status:a,timestamp:Date.now()}),a!=="disconnected"&&!In(o.voiceRecognition?.provider))return;let u=R.getVoiceNotice();switch(u&&ad(u,1e4),a){case"listening":if(!ag){let m=R.getVoiceDisclosure();m&&(ag=!0,Le()?(Uc=ce.placeholder,ce.placeholder=m,$s(m)):ad(m,1e4))}Tr(),da();break;case"processing":Tr(),MM();break;case"speaking":Tr(),TM();break;default:a==="idle"&&R.isBargeInActive()?(Tr(),da(),he?.setAttribute("aria-label","End voice session")):(Ge.active=!1,ag=!1,Uc!==null&&(ce.placeholder=Uc,Uc=null),Tr(),Sr("system"),Ry||zn());break}},onArtifactsState(a){uo=a,a.artifacts.length===0&&(Gi=!1),qr()?.updateInlineArtifactBlocks(Te,a.artifacts,{suppressTransition:no}),Ho(),Ji()},onHistoryStateChanged(a){pr(a)},onHistoryNotice(a){Uo(a)},onReconnect(a){let{executionId:u,lastEventId:m}=a.handle;a.phase==="paused"?X.emit("stream:paused",{executionId:u,after:m}):a.phase==="resuming"?X.emit("stream:resuming",{executionId:u,after:m,attempt:a.attempt??1}):X.emit("stream:resumed",{executionId:u,after:m})}},ds),go.current=R,Se.push(()=>R.cancel()),Se.push(()=>{R.destroy(),mo?.destroy(),mo=null});let Ig=null;if(R.onReadAloudChange((a,u)=>{oy=a,ry=u,sy();let m=a??Ig;a&&(Ig=a);let v=m?R.getMessages().find(w=>w.id===m)??null:null;X.emit("message:read-aloud",{messageId:m,message:v,state:u,timestamp:Date.now()}),u==="idle"&&(Ig=null)}),h=!0,rg=!0,o.voiceRecognition?.enabled===!0&&In(o.voiceRecognition.provider))try{R.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}let Bt=null,Rg=null,ib=!1,ab=R.getHistoryState(),yl=()=>o.features?.history?.enabled===!0,lb=a=>{a&&(To.textContent="",To.textContent=a)},Wg=()=>{f.forEach(m=>m()),f=[];let a=Bt,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:()=>un&&Un==="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}`}))};Wg();let rd=null,cb=!1,bl=()=>{if(!Vo)return;let a=o.layout?.header?.titleSource==="conversation",u=a&&rd?.trim()||null;Vo.textContent=u??o.launcher?.title??"Chat Assistant";let m=Vo.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")},rM=a=>{a!==rd&&(rd=a,bl())},sM=a=>{cb=a?.starred===!0,rM(a&&a.title.trim()||null),bl()};bl(),we.addEventListener("persona:title-menu-builtin",a=>{let u=a.detail?.actionId,m=R.getActiveConversationId();m&&(u==="delete"?Xo(v=>v.requestDeleteConversation(m)):u==="star"&&R.canUpdateConversations()&&Xo(v=>v.updateHistoryConversation(m,{starred:!cb})).catch(()=>{}))}),pr=a=>{ab=a,Bt?.historySurface?.view.setNewConversationRequired(a.recovery==="new_conversation_required"),ml(a.sendBlocked||no),Bt?.syncEarlierMessagesPill()},Uo=a=>{(a.code==="history_continuity_reset"||a.code==="conversation_deleted_recovered")&&(Mn.clear(),ni(),Go()),lb(a.message),Bt?.historySurface?.view.refresh()};let iM={get actionManager(){return _e},get activeConversationTitle(){return rd},announceHistory:lb,get applyRailChrome(){return Vn},set applyRailChrome(a){Vn=a},get artifactSplitRoot(){return br},get body(){return ae},get config(){return o},get container(){return we},get conversationOpenPendingEl(){return Ky},set conversationOpenPendingEl(a){Ky=a},get conversationOpenTakeover(){return Cg},set conversationOpenTakeover(a){Cg=a},currentKeyPrefix:Ct,destroyCallbacks:Se,eventBus:X,get footer(){return Ke},get header(){return mt},get historyChromeSync(){return Yr},set historyChromeSync(a){Yr=a},historyFeatureEnabled:yl,get historyInternals(){return ds},set historyInternals(a){ds=a},get historyPresentation(){return Un},set historyPresentation(a){Un=a},get historySessionState(){return ab},get historyVisible(){return un},set historyVisible(a){un=a},get isStreaming(){return no},jumpToBottomInstant:gg,get lastAppliedMessages(){return nd},set lastAppliedMessages(a){nd=a},get launcherEnabled(){return ye},get launcherSurfaceInstance(){return qt},maybeFocusInput:Jc,messageCache:Mn,get messagesWrapper(){return Te},mount:e,get open(){return D},panel:Ae,panelElements:et,get persistentMetadata(){return k},set persistentMetadata(a){k=a},plugins:d,get reapplyHistoryHostChrome(){return dr},set reapplyHistoryHostChrome(a){dr=a},repinAnchoredMessage:na,resetAnchorState:ni,restoreScrollPosition:fg,resumeAutoScroll:Go,runStorageMutation:jc,get session(){return R},setActiveConversationSummary:sM,storageAdapter:T,get suppressScrollSend(){return Xi},set suppressScrollSend(a){Xi=a},syncScrollToBottomButton:Tn,updateWelcome:hl,getHistoryProviderFactory:sx,historyErrors:{HistoryClientError:on,HistoryProviderError:Vr},isDockedMountMode:Lt,renderLucideIcon:ge,loadHistoryView:rx,createHeaderIconButton:_a,attachTooltip:vn},Og=a=>(!Bt&&!ib&&(Bt=a.createHistoryShell(iM),Bt.railCollapseShortcut()&&Wg()),Bt),_g=()=>{if(Bt)return Promise.resolve(Bt);let a=wp();return a?Promise.resolve(Og(a)):(Rg??=rw().then(Og,u=>{throw Rg=null,u}),Rg)},Xo=a=>{let u=wp(),m=Bt??(u?Og(u):null);return m?a(m):_g().then(v=>{if(!v)throw new Error("[AgentWidget] The widget was destroyed");return a(v)})},sd=()=>{Bt?.syncHistoryPresentation()};Se.push(()=>{ib=!0}),yl()&&_g().catch(()=>{}).finally(fe),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&R.initClientSession().then(()=>{let a=Bt;if(a?.historyAvailable())return R.reconcileBootConversation({scope:a.historyScope()})}).then(()=>{Bt?.syncEarlierMessagesPill()}).catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)});let Bg=()=>R.warmClientSession(),db=a=>{let u=o.sessionInit??"input",m=ct?.input??ce,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":(ct?.form??An)?.contains(v)))&&Bg()},pb=["input","pointerdown","keyup"];pb.forEach(a=>e.addEventListener(a,db));let ub,Dg,gb=()=>{let a=Dg;Dg=void 0;try{typeof a=="function"&&a()}catch{}},fb=()=>{let a=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(a!==ub){gb(),ub=a;try{Dg=a?.({warm:Bg,mount:e})}catch{}}};fb(),Se.push(()=>{pb.forEach(a=>e.removeEventListener(a,db)),gb()}),(Me||o.onSSEEvent)&&R.setSSEEventCallback((a,u)=>{o.onSSEEvent?.(a,u),Qa(a,u)});let mb=()=>{let a=o.resume??(_?ds.getStoredResumableHandle?.():null);a&&typeof o.reconnectStream=="function"&&R.resumeFromHandle(a)};J?J.then(a=>{if(a){if(a.metadata&&(k=wh(a.metadata),_e.syncFromMetadata()),a.messages?.length){Xi=!0;try{R.hydrateMessages(a.messages)}finally{Xi=!1}Xc()}a.artifacts?.length&&R.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null),By(a.draft)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>{Sg=!0,U(),mb()}):(By(He),mb());let aM=()=>{!Le()||D||!(o.launcher?.composerBar?.expandOnSubmit??!0)||Mt(!0,"auto")},lM=(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),dH(w)}}:a:u,Ng=()=>{let u=ce.getInlineMessageFields?.();return u&&u.contentSegments.some(v=>v.kind==="mention")?u.contentSegments:void 0},Er=!1,ii=null,id=()=>{ce.value="",ce.style.height="auto",po(),Cl()},aa=null;function ad(a,u=4e3){$s(a),!(Le()||!tt)&&(tt.hasAttribute(Ya)||(tt.setAttribute(yc,""),tt.setAttribute("role","status"),tt.setAttribute("aria-live","polite"),tt.textContent=a,hi(tt,o.statusIndicator??{},"idle"),aa&&clearTimeout(aa),aa=setTimeout(()=>{if(aa=null,!!tt?.hasAttribute(yc)&&(tt.removeAttribute(yc),tt.removeAttribute("role"),tt.removeAttribute("aria-live"),h)){let m=R.getStatus();_s(tt,ur(m),o.statusIndicator??{},m)}},u)))}function cM(){let a=be.getState().pendingSubmission;a&&(qi(void 0),ce&&(ce.value=a.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),po()),a.options.selectedModelId&&(be.setSelectedModelId(a.options.selectedModelId),Zr?.repaint()),a.options.activeModeIds?.length&&Tc(a.options.activeModeIds),a.options.quote&&qo(a.options.quote),ce?.focus())}let dM=a=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",a)},hb=(a={})=>{let u=(a.overrideText??ce?.value??"").trim();return a.resolveInlineCommand&&u?(at?.takeInlineCommand(u)??Promise.resolve(null)).then(m=>yb(a,u,m)):yb(a,u,null)},yb=(a,u,m)=>{if(m?.kind==="action"){id(),at?.clear(),mr();return}let v=m?.kind==="server"?m.mentions:null,w=m?.kind==="prompt"?m.sendText:u,P=a.pending?.contentParts,z=(je?.hasAttachments()??!1)||(P?.length??0)>0;if(!xS({text:w,hasAttachments:z,attachmentsReady:je?.isReady()??!0,hasMentions:at?.hasMentions()??!1,hasServerMentions:!!v,inputDisabled:Yo(),sendDisabled:oi()}))return;let re=R.isStreaming()?Uu():"block";if(re==="defer-one"&&!a.pending){if(be.getState().pendingSubmission){ad("One message is already queued. Edit or remove it first.");return}pM({intent:a,sendText:w,serverMentions:v});return}let Y={text:w,mentionRefs:[...at?.getMentionRefs()??[],...v?.refs??[]],contentSegments:m?.kind==="prompt"?void 0:Ng(),options:{...be.getState().selectedModelId&&{selectedModelId:be.getState().selectedModelId},...be.getState().activeModeIds.length>0&&{activeModeIds:[...be.getState().activeModeIds]},...be.getState().quote&&{quote:{...be.getState().quote}}},viaVoice:a.viaVoice};a.pending&&(Y.options={...a.pending.options},Y.contentSegments=a.pending.contentSegments,Y.mentionRefs=[...a.pending.mentionRefs],Y.viaVoice=a.pending.viaVoice);let ie=()=>{if(P?.length)return[...P];if(!je?.hasAttachments())return;let dt=[...je.getContentParts()];return Y.text&&dt.push(Ao(Y.text)),dt};Y.contentParts=ie();let le=()=>{Xs(),aM();let dt=at?.collectForSubmit()??null,Kn=lM(dt,v),Dt=ie();a.consumeDraft!==!1&&id();let jt={selectedModelId:Y.options.selectedModelId,activeModeIds:Y.options.activeModeIds},_n=re==="interrupt";_n&&R.cancel(),R.sendMessage(Y.text,{contentParts:Dt,mentions:Kn??void 0,contentSegments:Y.contentSegments,viaVoice:Y.viaVoice,composerOptions:jt,...Y.options.quote&&{quote:Y.options.quote},..._n&&{interrupt:!0}}),je?.hasAttachments()&&je.clearAttachments(),dt&&at?.clear(),mr();let Kt=be.getState().activeModeIds,wt=dS(Kt,o.composer?.modes);wt.length!==Kt.length&&Tc(wt),be.getState().quote&&qo(void 0),zc(),Gu.release(),Po()},de=o.composer?.onBeforeSend;if(!de){le();return}let Pe=new AbortController;ii=Pe;let it=dt=>{if(ii=null,dt.status==="error"){dM(dt.error);return}dt.status==="proceed"&&le()},gt=ES(de,Y,Pe.signal);if(!(gt instanceof Promise)){it(gt);return}return be.setPreparing(!0),gt.then(it).finally(()=>be.setPreparing(!1))};function pM(a){let u=be.getState(),m=je?.hasAttachments()??!1,v=m?[...je.getContentParts()]:[];m&&a.sendText&&v.push(Ao(a.sendText));let w=Am({text:a.sendText,contentParts:v.length?v:void 0,mentionRefs:[...at?.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});qi(w),a.intent.consumeDraft!==!1&&id(),m&&je.clearAttachments(),at?.clear(),mr(),u.quote&&qo(void 0),zc(),Gu.release(),Po(),$s("Message queued. It sends when the response finishes.")}function uM(){let a=be.getState().pendingSubmission;a&&(qi(void 0),cd(a.text,{consumeDraft:!1,pending:a}))}function gM(a){if(o.messageActions?.showEdit!==!0)return;let u=R.getMessages().find(m=>m.id===a);!u||!pm(u)||Ys!==a&&(Xs(),Ys=a,os=mS({messageId:a,initialText:u.content,onSave:m=>fM(a,m),onCancel:()=>Xs()}),Mn.delete(a),fo(Te,R.getMessages(),K),os.focus())}function fM(a,u){let m=os;if(Ys=null,os=null,m?.destroy(),Mn.delete(a),!R.resubmitFrom(a,{reason:"edit",replacement:{text:u,mentionRefs:[],options:{}}})){fo(Te,R.getMessages(),K);return}na()}function mM(a){if(R.isStreaming())return;let u=dm(R.getMessages(),a);u&&(Xs(),R.resubmitFrom(u,{reason:"retry"})&&na())}kc={regenerate:mM,edit:gM,quote:a=>{let m=R.getMessages().find(v=>v.id===a)?.content?.trim();m&&(qo({text:m,messageId:a}),ce?.focus())}};let vl=async a=>{if(!Er){Er=!0;try{await hb({resolveInlineCommand:!0,...a})}finally{Er=!1}}};function ld(a){oi()||(id(),cd(a,{consumeDraft:!1}))}let cd=(a,u)=>{if(Er)return;Er=!0;let m=()=>{Er=!1};try{let v=hb({...u,overrideText:a});v instanceof Promise?v.finally(m):m()}catch(v){throw m(),v}},hM=a=>{if(a.preventDefault(),R.isStreaming()){R.cancel(),bt?.reset(),rn?.update();return}Er||vl()},yM=()=>o.features?.composerHistory!==!1,Fg={...Pm},$g=!1,Cl=()=>{Fg={...Pm}},bM=()=>R.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),vM=a=>{if(!ce)return;$g=!0,ce.value=a,ce.dispatchEvent(new Event("input",{bubbles:!0})),$g=!1;let u=ce.value.length;ce.setSelectionRange(u,u)},CM=a=>{$g||(a.isComposing||at?.handleInput(a.inputType??void 0),Cl())},wM=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Bl(ce)}),SM=a=>{if(ce&&!Yo()&&!(!a.isComposing&&at?.handleKeydown(a))){if(yM()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let u=ce.selectionStart===0&&ce.selectionEnd===0,m=NS({direction:a.key==="ArrowUp"?"up":"down",history:bM(),currentValue:ce.value,atStart:u,state:Fg});if(Fg=m.state,m.handled){a.preventDefault(),m.value!==void 0&&vM(m.value);return}}if(BC(a,wM())){if(R.isStreaming()){if(a.preventDefault(),Uu()==="block"||Er||oi())return;Cl(),vl();return}if(Er){a.preventDefault();return}if(oi()){a.preventDefault();return}Cl(),a.preventDefault(),ke.click()}}},bb=a=>{if(!(a.key!=="Escape"||a.isComposing)&&a.composedPath().includes(we)){if(ii){ii.abort(),ii=null,a.preventDefault(),a.stopImmediatePropagation();return}R.isStreaming()&&(R.cancel(),bt?.reset(),rn?.update(),Cl(),a.preventDefault(),a.stopImmediatePropagation())}},AM=async a=>{if(o.attachments?.enabled!==!0||!je||Yo())return;let u=iH(a.clipboardData);u.length!==0&&(a.preventDefault(),await je.handleFiles(u))},ho=null,Qo=!1,la=null,Mr=null,Ug=()=>o.voiceRecognition?.completionBehavior==="review";function dd(a){he?.setAttribute("data-state",a),a==="recording"?EM():zg()}let vb="--persona-voice-level",Vg=.5,ca=null,jg=-1,pd=0,Cb=()=>{let a=[],u=gn??he?.parentElement??null;return u&&a.push(u),Ke&&a.push(Ke),a},qg=a=>{let u=Math.round(Math.max(0,Math.min(1,a))*100)/100;if(u!==jg){jg=u;for(let m of Cb())m.style.setProperty(vb,String(u))}},xM=()=>{jg=-1,pd=0;for(let a of Cb())a.style.removeProperty(vb)};function EM(){if(ca!==null)return;if(typeof requestAnimationFrame!="function"){qg(h?R.getVoiceLevel()??Vg:Vg);return}let a=()=>{ca=requestAnimationFrame(a);let u=h?R.getVoiceLevel():null;if(u===null){qg(Vg);return}pd+=(u-pd)*.3,qg(pd)};ca=requestAnimationFrame(a)}function zg(){ca!==null&&(cancelAnimationFrame(ca),ca=null),xM()}let wb=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ud=(a="user")=>{if(Qo||R.isStreaming())return;let u=wb();if(!u)return;ho=new u;let m=o.voiceRecognition??{},v=m.pauseDuration??2e3;ho.continuous=m.provider?.browser?.continuous??!0,ho.interimResults=!0,ho.lang=m.provider?.browser?.language??"en-US";let w=ce.value;ho.onresult=P=>{let z="",re="";for(let ie=0;ie<P.results.length;ie++){let le=P.results[ie],de=le[0].transcript;le.isFinal?z+=de+" ":re=de}let Y=w+z+re;ce.value=Y,po(),la&&clearTimeout(la),(z||re)&&(la=window.setTimeout(()=>{if(ce.value.trim()&&ho&&Qo){if(ps(),Ug())return;vl({viaVoice:!0})}},v))},ho.onerror=P=>{P.error!=="no-speech"&&ps()},ho.onend=()=>{if(Qo){let P=ce.value.trim();!Ug()&&P&&P!==w.trim()&&vl({viaVoice:!0}),ps()}};try{if(ho.start(),Qo=!0,Ge.active=!0,a!=="system"&&(Ge.manuallyDeactivated=!1),Sr(a),zn(),Po(),he){let P=o.voiceRecognition??{};Mr={backgroundColor:he.style.backgroundColor,color:he.style.color,borderColor:he.style.borderColor,iconName:P.iconName??"mic",iconSize:parseFloat(P.iconSize??"")||Qn};let z=P.recordingBackgroundColor,re=P.recordingIconColor,Y=P.recordingBorderColor;if(he.classList.add("persona-voice-recording"),dd("recording"),he.style.backgroundColor=z??"var(--persona-voice-recording-bg, #ef4444)",he.style.color=re??"var(--persona-voice-recording-indicator, #ffffff)",re){let ie=he.querySelector("svg");ie&&ie.setAttribute("stroke",re)}Y&&(he.style.borderColor=Y),he.setAttribute("aria-label","Stop voice recognition")}}catch{ps("system")}},ps=(a="user")=>{if(Qo){if(Qo=!1,la&&(clearTimeout(la),la=null),ho){try{ho.stop()}catch{}ho=null}if(Ge.active=!1,Sr(a),zn(),Po(),he){if(he.classList.remove("persona-voice-recording"),dd("idle"),Mr){he.style.backgroundColor=Mr.backgroundColor,he.style.color=Mr.color,he.style.borderColor=Mr.borderColor;let u=he.querySelector("svg");u&&u.setAttribute("stroke",Mr.color||"currentColor"),Mr=null}he.setAttribute("aria-label","Start voice recognition")}}},Sb=null,gd=a=>{let u=v=>{Sb??=v.createMicStateStyles({mic:()=>he,config:()=>o,session:()=>R,get original(){return Mr},set original(w){Mr=w},setMicState:dd,renderIcon:ge,iconFallbackPx:Qn}),a(Sb)},m=_w();m?u(m):zl().then(u,()=>{})},da=()=>gd(a=>a.recording()),MM=()=>gd(a=>a.processing()),TM=()=>gd(a=>a.speaking()),Tr=()=>gd(a=>a.reset()),Kg=()=>{if(!Yo()){if(In(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(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,zn(),Sr("user"),Tr()});return}R.toggleVoice().then(()=>{Ge.active=lg(),Ge.manuallyDeactivated=!Ge.active,zn(),Sr("user"),Ge.active?da():Tr()});return}if(Qo){let a=ce.value.trim();Ge.manuallyDeactivated=!0,zn(),ps("user"),a&&!Ug()&&vl()}else Ge.manuallyDeactivated=!1,zn(),ud("user")}};Vu=Kg;let Ab=()=>R.prewarmVoice(),xb=()=>{let a=o.voiceRecognition;return a?.enabled!==!0?!1:a.prewarm??(o.clientToken?"hover":!1)},Eb=a=>{xb()==="hover"&&he?.contains(a.target)&&Ab()},Mb=["pointerover","pointerdown","focusin"];Mb.forEach(a=>e.addEventListener(a,Eb));let Tb,kb=null,Gg,Pb=()=>{let a=Gg;Gg=void 0;try{typeof a=="function"&&a()}catch{}},Yg=()=>{let a=xb(),u=typeof a=="function"&&he?a:void 0,m=u?he:null;if(!(u===Tb&&m===kb)&&(Pb(),Tb=u,kb=m,!(!u||!m)))try{Gg=u({warm:Ab,micButton:m,mount:e})}catch{}};Yg(),Se.push(()=>{Mb.forEach(a=>e.removeEventListener(a,Eb)),Pb()}),he&&Se.push(()=>{In(o.voiceRecognition?.provider)?(R.isVoiceActive()&&R.toggleVoice(),Tr()):ps("system")});let kM=X.on("assistant:complete",()=>{be.getState().pendingSubmission&&setTimeout(()=>{R.isStreaming()||uM()},0)});Se.push(kM);let PM=X.on("assistant:complete",()=>{Iy&&(Ge.active||Ge.manuallyDeactivated||Iy==="assistant"&&!Ge.lastUserMessageWasVoice||setTimeout(()=>{!Ge.active&&!Ge.manuallyDeactivated&&(In(o.voiceRecognition?.provider)?R.toggleVoice().then(()=>{Ge.active=R.isVoiceActive(),Sr("auto"),R.isVoiceActive()&&da()}):ud("auto"))},600))});Se.push(PM);let LM=X.on("action:resubmit",()=>{setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)});Se.push(LM);let Lb=()=>{Mt(!D,"user")},qt=null,On=null;if(ye&&!Le()){let{instance:a,element:u}=nh({config:o,plugins:d,onToggle:Lb});qt=a,a||(On=u)}qt?e.appendChild(qt.element):On&&e.appendChild(On),fl(),Ks(),ed(),Tg(),ml(R.isStreaming()),fg()||(En()==="follow"?as(!0):gg()),TE(),Zt&&(!ye||Le()?setTimeout(()=>Jc(),0):D&&setTimeout(()=>Jc(),200));let us=null,Hb=()=>{us&&(us.disconnect(),us.observe(Ke),us.observe(we),us.observe(en))},Ib=jn(),wl=()=>{if(Le()){Re(),fl();return}let a=Lt(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&&ye;try{if(z){Us(),rl=Bc();return}let re=!1;vt&&(vt=!1,Us(),re=!0);let Y=Bc();if(!re&&Y!==rl&&(Us(),re=!0),rl=Y,re&&Rc(),!ye&&!a){Ae.style.height="",Ae.style.width="";return}if(!u&&!a){let ie=Hi(o);Ae.style.width=ie.width,Ae.style.maxWidth=ie.maxWidth}_c(),hy()}finally{Re(),Ot();let re=jn();if(re!==Ib&&(Ib=re,hl(),Ks()),fl(),D&&ye){let ie=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),le=o.launcher?.sidebarMode??!1,de=o.launcher?.mobileFullscreen??!0,Pe=Lt(o)&&de&&ie,it=le||de&&ie&&ye||Pe;if(it&&!Ko){let gt=e.getRootNode(),dt=gt instanceof ShadowRoot?gt.host:e.closest(".persona-host");dt&&!zo&&(zo=Rm(dt,o.launcher?.zIndex??Pn)),Ko=Wm(e.ownerDocument)}else it||(zo?.(),zo=null,Ko?.(),Ko=null)}}};wl();let fd=e.ownerDocument.defaultView??window;if(fd.addEventListener("resize",wl),Se.push(()=>fd.removeEventListener("resize",wl)),typeof ResizeObserver<"u"){us=new ResizeObserver(()=>{Ot()}),Hb(),Se.push(()=>{us?.disconnect(),us=null});let a=new ResizeObserver(()=>{sd()});a.observe(we),Se.push(()=>a.disconnect())}fd.addEventListener("resize",sd),Se.push(()=>fd.removeEventListener("resize",sd)),ro=ae.scrollTop;let Rb=ir(ae),Wb=()=>{my();let a=ae.scrollTop,u=ir(ae),m=u<Rb;if(Rb=u,!Mo()){ro=a,Tn();return}let{action:v,nextLastScrollTop:w}=KS({following:oo.isFollowing(),currentScrollTop:a,lastScrollTop:ro,nearBottom:Mi(ae,Cr),userScrollThreshold:AE,isAutoScrolling:qn||Nc||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ro=w,v==="resume"){Kc()||Go();return}v==="pause"&&ta()};if(ae.addEventListener("scroll",Wb,{passive:!0}),Se.push(()=>ae.removeEventListener("scroll",Wb)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{WE(),im(Te)});a.observe(Te),a.observe(ae),Se.push(()=>a.disconnect())}let Ob=()=>{Mo()&&oo.isFollowing()&&Kc()&&ta()},_b=ae.ownerDocument;_b.addEventListener("selectionchange",Ob),Se.push(()=>{_b.removeEventListener("selectionchange",Ob)});let HM=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Bb=a=>{HM.has(a.key)&&(is(),Ja()&&Mo()&&oo.isFollowing()&&ta())},Db=a=>{a.target?.closest("a, button, [tabindex], input, textarea, select")&&(is(),Ja()&&Mo()&&oo.isFollowing()&&ta())};ae.addEventListener("keydown",Bb),ae.addEventListener("focusin",Db),Se.push(()=>{ae.removeEventListener("keydown",Bb),ae.removeEventListener("focusin",Db)});let Nb=a=>{if(a.deltaY!==0&&is(),!Mo())return;let u=GS({following:oo.isFollowing(),deltaY:a.deltaY,nearBottom:Mi(ae,Cr),resumeWhenNearBottom:!0});u==="pause"?ta():u==="resume"&&!Kc()&&Go()};ae.addEventListener("wheel",Nb,{passive:!0}),ae.addEventListener("touchmove",is,{passive:!0}),ae.addEventListener("pointerdown",is,{passive:!0}),Se.push(()=>{ae.removeEventListener("touchmove",is),ae.removeEventListener("pointerdown",is)}),Se.push(()=>ae.removeEventListener("wheel",Nb)),Vt.addEventListener("click",()=>{ni(),ae.scrollTop=ae.scrollHeight,ro=ae.scrollTop,Go(),as(!0),Tn()}),Se.push(()=>Vt.remove()),Se.push(()=>{Ny(),ni()});let Fb=()=>{ze&&(qs&&(ze.removeEventListener("click",qs),qs=null),Xe()?(ze.style.display="",qs=()=>{Mt(!1,"user")},ze.addEventListener("click",qs)):ze.style.display="none")};Fb(),(()=>{let{clearChatButton:a}=et;a&&a.addEventListener("click",()=>{let u=Bt;if(u?.historyAvailable()){u.startNewConversation({focusComposer:!0}).catch(v=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",v)});return}R.clearMessages(),o.layout?.topFade&&(ae.scrollTop=0),ae.removeAttribute("data-persona-top-fade"),Mn.clear(),Go(),Wr(et.composerOverlay);try{localStorage.removeItem(Ga),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ga}`)}catch(v){console.error("[AgentWidget] Failed to clear default localStorage:",v)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ga)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&&jc(()=>T.clear(),"[AgentWidget] Failed to clear storage adapter:"),k={},_e.syncFromMetadata(),je?.clearAttachments(),zc(),qi(void 0),qo(void 0),Xs(),ft?.clear(),bt?.reset(),rn?.update()})})();let $b=[["keydown",SM],["input",CM],["input",po],["input",mr],["keyup",mr],["paste",AM],["focus",pE]],Ub=a=>{if(a)for(let[u,m]of $b)ct?.addListener(a,u,m)},IM=a=>{if(a)for(let[u,m]of $b)ct?.removeListener(a,u,m)},Vb=()=>{ct&&(ct.addListener(ct.form,"submit",hM),ct.addListener(ct.footer,"click",mr),Ub(ce),he&&ct.addListener(he,"click",Kg),Yg())};Vb();let jb=()=>{at?.onComposerSwap((a,u)=>{IM(u),ce=a,ct&&(ct.input=a),Ub(a),qu(),vg(),po()})};jb();let Xg=!1;function qb(){if(!Xg){Xg=!0;try{let a=ce?.value??"",u=Ke.ownerDocument??document,m=ce?u.activeElement===ce:!1;zg(),ct?.destroy(),ct=null,at?.destroy(),at=null;let v=null,w=()=>(v=Le()?nu({config:o}):Pi({config:o}),v.footer),P=Gh(w)??w();Ln.replaceComposer(P),Ke=Ln.composer.footer;let z=v!==null&&P===v.footer;Ki=!z,xc=z?v.setSendButtonMode:()=>{},Kh(Ke),Xh(Ke),Qh(),Jh(),zu(),jb(),Zh(),Ku(),ey(),Vb();let re=js.indexOf(vr);if(vr.destroy(),vr=ac(co),re>=0&&(js[re]=vr),ce&&(ce.value=a),po(),mr(),ed(),Ks(),ml(R.isStreaming()),o.statusIndicator?.mode==="transient"&&!Le()){let Y=R.getStatus();_s(tt,ur(Y),o.statusIndicator,Y)}Ge.active&&dd("recording"),Us(),Hb(),Re(),Po(),Qc(),m&&ce?.focus()}finally{Xg=!1}}}let Sl=e.ownerDocument??document;Sl.addEventListener("keydown",bb,!0);let zb=()=>{cg()},Kb=()=>{Sl.visibilityState==="hidden"&&cg()};typeof window<"u"&&(window.addEventListener("pagehide",zb),Sl.addEventListener("visibilitychange",Kb),Se.push(()=>{window.removeEventListener("pagehide",zb),Sl.removeEventListener("visibilitychange",Kb)}));let Gb="persona-attachment-drop-active",Al=0,Qg=()=>{Al=0,we.classList.remove(Gb)},pa=()=>o.attachments?.enabled===!0&&je!==null&&!Yo(),Yb=a=>{!bu(a.dataTransfer)||!pa()||(Al++,Al===1&&we.classList.add(Gb))},Xb=a=>{!bu(a.dataTransfer)||!pa()||(Al--,Al<=0&&Qg())},Qb=a=>{!bu(a.dataTransfer)||!pa()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},Jb=a=>{if(!bu(a.dataTransfer)||!pa())return;a.preventDefault(),a.stopPropagation(),Qg();let u=Array.from(a.dataTransfer.files??[]);u.length!==0&&je.handleFiles(u)},gs=!0;we.addEventListener("dragenter",Yb,gs),we.addEventListener("dragleave",Xb,gs),e.addEventListener("dragover",Qb,gs),e.addEventListener("drop",Jb,gs);let md=e.ownerDocument,Zb=a=>{pa()&&a.preventDefault()},ev=a=>{pa()&&a.preventDefault()};md.addEventListener("dragover",Zb),md.addEventListener("drop",ev),Se.push(()=>{ct?.destroy(),ct=null,zg(),ko?.destroy(),ko=null,hr?.destroy(),hr=null,es?.destroy(),es=null,ts?.destroy(),ts=null,Zr=null,$u=null,cg(),cl.destroy(),aa&&clearTimeout(aa),Xs(),ii?.abort(),ii=null,je?.destroy(),je=null,be.destroy(),Sl.removeEventListener("keydown",bb,!0),at?.destroy()}),Se.push(()=>{we.removeEventListener("dragenter",Yb,gs),we.removeEventListener("dragleave",Xb,gs),e.removeEventListener("dragover",Qb,gs),e.removeEventListener("drop",Jb,gs),md.removeEventListener("dragover",Zb),md.removeEventListener("drop",ev),Qg()}),Se.push(()=>{R.cancel()}),qt?Se.push(()=>{qt?.destroy()}):On&&Se.push(()=>{On?.remove()});let zt={update(a){let u=o.future?.v5Defaults===!0,m=o.toolCall,v=o.messageActions,w=o.layout?.messages,P=o.colorScheme,z=o.loadingIndicator,re=o.iterationDisplay,Y=o.features?.showReasoning,ie=o.features?.showToolCalls,le=o.features?.toolCallDisplay,de=o.features?.reasoningDisplay,Pe=o.features?.streamAnimation?.type,it=o.features?.history?.enabled===!0,gt=o.features?.history?.provider,dt=o.getIdentityProof,Kn=o.clientToken,Dt=o.contextMentions;o=pu({...o,features:p},a),p=o.features,o=uc(o),c(),eg(),Ei(e,o),dc(e,o),pc(e,o),Vn(),Ho(),o.colorScheme!==P&&yy();let jt=gc.getForInstance(o.plugins);d.length=0,d.push(...jt),Wg(),ye=o.launcher?.enabled??!0,ut=o.launcher?.autoExpand??!1,te=o.features?.showReasoning??!0,ve=o.features?.showToolCalls??!0,Ce=o.features?.scrollToBottom??{};let _n=En();st=o.features?.scrollBehavior??{},_n!==En()&&(ni(),Go()),Hy(),_t(),Tn();let Kt=Me;if(Me=o.features?.showEventStreamToggle??!1,Me&&!Kt){if(ft||(cr(),R.setSSEEventCallback((Z,ot)=>{o.onSSEEvent?.(Z,ot),Qa(Z,ot)})),!ht&&mt){let Z=o.features?.eventStream?.classNames,ot="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"+(Z?.toggleButton?" "+Z.toggleButton:"");ht=x("button",ot),ht.style.width="28px",ht.style.height="28px",ht.style.color=Nn.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let rt=Nt(Kr.Activity,"18px","currentColor",1.5);rt&&ht.appendChild(rt);let pt=et.clearChatButtonWrapper,Rt=et.closeButtonWrapper,kn=pt||Rt;kn&&kn.parentNode===mt?mt.insertBefore(ht,kn):mt.appendChild(ht),ht.addEventListener("click",()=>{Sn?zi():ju()})}}else!Me&&Kt&&(zi(),ht&&(ht.remove(),ht=null),ft?.clear(),pn?.destroy(),ft=null,pn=null,bt?.reset(),bt=null,Ft=null);if(o.launcher?.enabled===!1&&qt&&(qt.destroy(),qt=null),o.launcher?.enabled===!1&&On&&(On.remove(),On=null),o.launcher?.enabled!==!1&&!qt&&!On){let{instance:Z,element:ot}=nh({config:o,plugins:d,onToggle:Lb});qt=Z,Z||(On=ot),e.appendChild(ot)}qt&&qt.update(o),bl(),jo&&o.launcher?.subtitle!==void 0&&(jo.textContent=o.launcher.subtitle);let wt=o.layout?.header;if(wt?.layout!==Wt&&mt){let Z=wt?Na(o,wt,{showClose:Xe(),onClose:()=>Mt(!1,"user")}):jr({config:o,showClose:Xe(),onClose:()=>Mt(!1,"user")});Ln.replaceHeader(Z),mt=Ln.header.element,Ht=Ln.header.iconHolder,Vo=Ln.header.headerTitle,jo=Ln.header.headerSubtitle,ze=Ln.header.closeButton,Wt=wt?.layout,bl()}else if(wt){if(Ht&&(Ht.style.display=wt.showIcon===!1?"none":""),Vo&&(Vo.style.display=wt.showTitle===!1?"none":""),jo&&(jo.style.display=wt.showSubtitle===!1?"none":""),ze){let Z=Xe()&&wt.showCloseButton!==!1;ze.style.display=Z?"":"none"}if(et.clearChatButtonWrapper){let Z=wt.showClearChat;if(Z!==void 0){et.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:ot}=et;ot&&!ot.classList.contains("persona-absolute")&&(Z?ot.classList.remove("persona-ml-auto"):ot.classList.add("persona-ml-auto"))}}}let Zo=o.layout?.showHeader!==!1;mt&&(mt.style.display=Zo?"":"none");let bo=o.layout?.showFooter!==!1;Ke&&(Ke.style.display=bo?"":"none"),Re(),Tn(),ye!==xe?ye?Mt(ut,"auto"):(D=!0,fl()):ut!==xt&&Mt(ut,"auto"),xt=ut,xe=ye,wl(),Fb();let er=JSON.stringify(o.toolCall)!==JSON.stringify(m),Io=JSON.stringify(o.messageActions)!==JSON.stringify(v),ms=JSON.stringify(o.layout?.messages)!==JSON.stringify(w),xl=o.loadingIndicator?.render!==z?.render||o.loadingIndicator?.renderIdle!==z?.renderIdle||o.loadingIndicator?.showBubble!==z?.showBubble,ai=o.iterationDisplay!==re,O=(o.features?.showReasoning??!0)!==(Y??!0)||(o.features?.showToolCalls??!0)!==(ie??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(le)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(de);(o.future?.v5Defaults===!0!==u||er||Io||ms||xl||ai||O)&&R&&(Qs++,fo(Te,R.getMessages(),K));let Fe=o.features?.streamAnimation?.type;if(Fe!==Pe&&Fe&&Fe!=="none"){let Z=og(Fe,o.features?.streamAnimation?.plugins);Z&&rc(Z,e)}let se=o.launcher??{},St=se.headerIconHidden??!1,Jt=o.layout?.header?.showIcon,Hn=St||Jt===!1,mn=se.headerIconName,Tt=se.headerIconSize??_l;if(Ht){let Z=mt,ot=Z?.querySelector(".persona-flex-col");if(Hn)Ht.style.display="none",Z&&ot&&!Z.contains(ot)&&Z.insertBefore(ot,Z.firstChild);else{if(Ht.style.display="",Ht.style.height=Tt,Ht.style.width=Tt,Z&&ot&&(Z.contains(Ht)?Ht.nextSibling!==ot&&(Ht.remove(),Z.insertBefore(Ht,ot)):Z.insertBefore(Ht,ot)),mn){let pt=parseFloat(Tt)||24,Rt=ge(mn,pt*.6,"currentColor",1);Rt?(Rt.style.width=`calc(${pt}px * var(--persona-components-header-iconScale, 0.6))`,Rt.style.height=`calc(${pt}px * var(--persona-components-header-iconScale, 0.6))`,Ht.replaceChildren(Rt)):Ht.textContent=se.agentIconText??"\u{1F4AC}"}else if(se.iconUrl){let pt=Ht.querySelector("img");if(pt)pt.src=se.iconUrl,pt.style.height=Tt,pt.style.width=Tt;else{let Rt=document.createElement("img");Rt.src=se.iconUrl,Rt.alt="",Rt.className="persona-rounded-xl persona-object-cover",Rt.style.height=Tt,Rt.style.width=Tt,Ht.replaceChildren(Rt)}}else{let pt=Ht.querySelector("svg"),Rt=Ht.querySelector("img");(pt||Rt)&&Ht.replaceChildren(),Ht.textContent=se.agentIconText??"\u{1F4AC}"}let rt=Ht.querySelector("img");rt&&(rt.style.height=Tt,rt.style.width=Tt)}}let Gt=o.layout?.header?.showTitle,ln=o.layout?.header?.showSubtitle;if(Vo&&(Vo.style.display=Gt===!1?"none":""),jo&&(jo.style.display=ln===!1?"none":""),ze){let Z=Xe()&&o.layout?.header?.showCloseButton!==!1;if(ze.style.display=Z?"":"none",!Le()){let yn=se.closeButtonSize??"";ze.style.height=yn,ze.style.width=yn,ze.style.minWidth=yn,ze.style.minHeight=yn}let ot=se.closeButtonPlacement??"inline",{closeButtonWrapper:rt}=et,pt=ot==="top-right",Rt=rt?.classList.contains("persona-absolute");if(rt&&pt!==Rt)if(rt.remove(),pt){rt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let yn=Bt?.railColumn??we;yn.style.position="relative",yn.appendChild(rt)}else{let yn=se.clearChat?.placement??"inline",bn=se.clearChat?.enabled??!0;rt.className=bn&&yn==="inline"?"":"persona-ml-auto",mt&&mt.appendChild(rt)}if(ze.style.color=se.closeButtonColor||Nn.actionIconColor,se.closeButtonBackgroundColor?(ze.style.backgroundColor=se.closeButtonBackgroundColor,ze.classList.remove("hover:persona-bg-gray-100")):(ze.style.backgroundColor="",ze.classList.add("hover:persona-bg-gray-100")),se.closeButtonBorderWidth||se.closeButtonBorderColor){let yn=se.closeButtonBorderWidth||"0px",bn=se.closeButtonBorderColor||"transparent";ze.style.border=`${yn} solid ${bn}`,ze.classList.remove("persona-border-none")}else ze.style.border="",ze.classList.add("persona-border-none");se.closeButtonBorderRadius?(ze.style.borderRadius=se.closeButtonBorderRadius,ze.classList.remove("persona-rounded-full")):(ze.style.borderRadius="",ze.classList.add("persona-rounded-full")),se.closeButtonPaddingX?(ze.style.paddingLeft=se.closeButtonPaddingX,ze.style.paddingRight=se.closeButtonPaddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),se.closeButtonPaddingY?(ze.style.paddingTop=se.closeButtonPaddingY,ze.style.paddingBottom=se.closeButtonPaddingY):(ze.style.paddingTop="",ze.style.paddingBottom=""),Jp(ze,se.closeButtonIconName??"x",{iconSize:Le()?Jm:void 0,iconText:se.closeButtonIconText??"\xD7"});let kn=se.closeButtonTooltipText??"Close chat",Wo=se.closeButtonShowTooltip??!0;ze.setAttribute("aria-label",kn),rt&&vn({anchor:ze,trigger:rt,text:()=>ze?.getAttribute("aria-label")??kn,enabled:Wo})}let{clearChatButton:We,clearChatButtonWrapper:kt}=et;if(We){let Z=se.clearChat??{},ot=Z.enabled??!0,rt=o.layout?.header?.showClearChat,pt=rt!==void 0?rt:ot,Rt=Z.placement??"inline";if(kt){kt.style.display=pt?"":"none";let{closeButtonWrapper:kn}=et;!Le()&&kn&&!kn.classList.contains("persona-absolute")&&(pt?kn.classList.remove("persona-ml-auto"):kn.classList.add("persona-ml-auto"));let Wo=Rt==="top-right",yn=kt.classList.contains("persona-absolute");if(!Le()&&Wo!==yn&&pt){if(kt.remove(),Wo){kt.className="persona-absolute persona-top-4 persona-z-50",kt.style.right="48px";let tr=Bt?.railColumn??we;tr.style.position="relative",tr.appendChild(kt)}else{kt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",kt.style.right="";let tr=et.closeButtonWrapper;mt&&tr&&tr.parentElement===mt?mt.insertBefore(kt,tr):mt&&mt.appendChild(kt)}let bn=et.closeButtonWrapper;bn&&!bn.classList.contains("persona-absolute")&&(Wo?bn.classList.add("persona-ml-auto"):bn.classList.remove("persona-ml-auto"))}}if(pt){if(!Le()){let bn=Z.size??"";We.style.height=bn,We.style.width=bn,We.style.minWidth=bn,We.style.minHeight=bn}let kn=Z.iconColor??"";if(We.style.color=kn||Nn.actionIconColor,Jp(We,Z.iconName??"refresh-cw",{iconSize:Le()?Zm:void 0}),Z.backgroundColor?(We.style.backgroundColor=Z.backgroundColor,We.classList.remove("hover:persona-bg-gray-100")):(We.style.backgroundColor="",We.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let bn=Z.borderWidth||"0px",tr=Z.borderColor||"transparent";We.style.border=`${bn} solid ${tr}`,We.classList.remove("persona-border-none")}else We.style.border="",We.classList.add("persona-border-none");Z.borderRadius?(We.style.borderRadius=Z.borderRadius,We.classList.remove("persona-rounded-full")):(We.style.borderRadius="",We.classList.add("persona-rounded-full")),Z.paddingX?(We.style.paddingLeft=Z.paddingX,We.style.paddingRight=Z.paddingX):(We.style.paddingLeft="",We.style.paddingRight=""),Z.paddingY?(We.style.paddingTop=Z.paddingY,We.style.paddingBottom=Z.paddingY):(We.style.paddingTop="",We.style.paddingBottom="");let Wo=Z.tooltipText??"Clear chat",yn=Z.showTooltip??!0;We.setAttribute("aria-label",Wo),kt&&vn({anchor:We,trigger:kt,text:()=>We?.getAttribute("aria-label")??Wo,enabled:yn})}}let $e=o.actionParsers&&o.actionParsers.length?o.actionParsers:[fc],cn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Wi.message,Wi.messageAndClick];_e=mc({parsers:$e,handlers:cn,getSessionMetadata:yt,updateSessionMetadata:qe,emit:X.emit,documentRef:typeof document<"u"?document:null}),K=dx(o,_e,q),ZE(),R.updateConfig(o),fb(),(o.features?.history?.enabled===!0!==it||o.features?.history?.provider!==gt||o.getIdentityProof!==dt||o.clientToken!==Kn)&&(Bt?.closeHistory({restoreFocus:!1}),Bt?.installHistoryProvider()),Bt?.syncHistoryChromeImpl(),sd(),yl()&&!Bt&&_g().catch(()=>{}),fo(Te,R.getMessages(),K),Ks(),ed(),XE(),ml(R.isStreaming()),Dt!==o.contextMentions&&qb();let Co=o.voiceRecognition?.enabled===!0,hn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),At=In(o.voiceRecognition?.provider);if(Co&&(hn||At))if(!he||!gn){let Z=Pa(o);if(Z){he=Z.button,gn=Z.wrapper;let ot=Wn&&Wn.parentElement===Bs?Wn:null;Bs?Bs.insertBefore(gn,ot):An?.appendChild(gn),ct&&(ct.micButton=he),ct?.addListener(he,"click",Kg),he.disabled=Yo()||R.isStreaming()&&!yg()}}else{let Z=o.voiceRecognition??{},ot=o.sendButton??{},rt=Z.iconName??"mic",pt=Z.iconSize,Rt=parseFloat(pt??"")||Qn;he.classList.add(so),he.classList.toggle(Do,!pt),he.style.width=pt??"",he.style.height=pt??"",he.style.minWidth=pt??"",he.style.minHeight=pt??"";let kn=Z.iconColor??ot.textColor;he.innerHTML="";let Wo=ge(rt,Rt,kn||"currentColor",1.5);Wo?he.appendChild(Wo):he.textContent="\u{1F3A4}";let yn=Z.backgroundColor??ot.backgroundColor;yn?he.style.backgroundColor=yn:he.style.backgroundColor="",kn?he.style.color=kn:he.style.color="var(--persona-text, #111827)",Z.borderWidth?(he.style.borderWidth=Z.borderWidth,he.style.borderStyle="solid"):(he.style.borderWidth="",he.style.borderStyle=""),Z.borderColor?he.style.borderColor=Z.borderColor:he.style.borderColor="",Z.paddingX?(he.style.paddingLeft=Z.paddingX,he.style.paddingRight=Z.paddingX):(he.style.paddingLeft="",he.style.paddingRight=""),Z.paddingY?(he.style.paddingTop=Z.paddingY,he.style.paddingBottom=Z.paddingY):(he.style.paddingTop="",he.style.paddingBottom="");let bn=Z.tooltipText??"Start voice recognition",tr=Z.showTooltip??!1;he.setAttribute("aria-label",bn),gn&&vn({anchor:he,trigger:gn,text:()=>he?.getAttribute("aria-label")??bn,enabled:tr}),gn.style.display="",he.disabled=Yo()||R.isStreaming()&&!yg()}else he&&gn&&(gn.style.display="none",In(o.voiceRecognition?.provider)?R.isVoiceActive()&&R.toggleVoice():Qo&&ps());if(Yg(),o.attachments?.enabled===!0){if(!sn||!It){let Z=o.attachments??{};fn||(fn=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),fn.style.display="none",(ce.parentElement??An).insertBefore(fn,ce)),Et||(Et=document.createElement("input"),Et.type="file",Et.accept=(Z.allowedTypes??Dr).join(","),Et.multiple=(Z.maxFiles??4)>1,Et.style.display="none",Et.setAttribute("aria-label","Attach files"),(ce.parentElement??An).insertBefore(Et,ce)),sn=x("div","persona-send-button-wrapper"),It=x("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${so} ${Do}`),It.type="button",It.setAttribute("aria-label",Z.buttonTooltipText??"Attach file");let ot=Z.buttonIconName??"paperclip";It.style.fontSize="18px",It.style.lineHeight="1";let rt=ge(ot,Qn,"currentColor",1.5);rt?It.appendChild(rt):It.textContent="\u{1F4CE}",It.addEventListener("click",Rt=>{Rt.preventDefault(),Et?.click()}),sn.appendChild(It);let pt=Z.buttonTooltipText??"Attach file";vn({anchor:It,trigger:sn,text:()=>It?.getAttribute("aria-label")??pt}),xn?xn.append(sn):An.appendChild(sn),ct&&(ct.attachmentButton=It,ct.attachmentInput=Et??void 0,ct.attachmentPreviews=fn??void 0),!je&&Et&&fn&&(je=Ai.fromConfig(Z,Uh),je.setPreviewsContainer(fn),ct?.addListener(Et,"change",async()=>{je&&Et?.files&&(await je.handleFileSelect(Et.files),Et.value="")}))}else{sn.style.display="";let Z=o.attachments??{};Et&&(Et.accept=(Z.allowedTypes??Dr).join(","),Et.multiple=(Z.maxFiles??4)>1),je&&je.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles,adapter:Z.adapter})}if(we.querySelector(".persona-attachment-drop-overlay")?.remove(),we.appendChild(px(o.attachments?.dropOverlay)),It){let Z=o.attachments??{},ot=Z.buttonTooltipText??"Attach file";It.setAttribute("aria-label",ot),It.textContent="";let rt=ge(Z.buttonIconName??"paperclip",Qn,"currentColor",1.5);rt?It.appendChild(rt):It.textContent="\u{1F4CE}",sn&&vn({anchor:It,trigger:sn,text:()=>It?.getAttribute("aria-label")??ot})}}else sn&&(sn.style.display="none"),je&&je.clearAttachments(),we.querySelector(".persona-attachment-drop-overlay")?.remove();let Ue=o.sendButton??{},hs=Ue.useIcon??!1,nn=Ue.iconText??"\u2191",Gn=Ue.iconName,kr=Ue.tooltipText??"Send message",Jg=Ue.showTooltip??!1,li=Ue.size,Zg=parseFloat(li??"")||$f,Pr=Ue.backgroundColor,ci=Ue.textColor;if(hs){if(ke.style.width=li??"",ke.style.height=li??"",ke.style.minWidth=li??"",ke.style.minHeight=li??"",ke.style.fontSize="18px",ke.style.lineHeight="1",ci?ke.style.color=ci:ke.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!R.isStreaming())if(ke.innerHTML="",Gn){let Z=parseFloat(Ue.iconSize??"")||Math.round(Zg*.5),ot=ci?.trim()||"currentColor",rt=Ue.iconStrokeWidth??2,pt=ge(Gn,Z,ot,rt),Rt=ge(Ue.stopIconName??"square",Z,ot,rt);pt&&Rt?ke.appendChild(Uf(pt,Rt)):pt?ke.appendChild(pt):ke.textContent=nn}else ke.textContent=nn;ke.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${so}`,Pr?(ke.style.backgroundColor=Pr,ke.classList.remove("persona-bg-persona-primary")):(ke.style.backgroundColor="",ke.classList.add("persona-bg-persona-primary"))}else ke.textContent=o.copy?.sendButtonLabel??"Send",ke.style.width="",ke.style.height="",ke.style.minWidth="",ke.style.minHeight="",ke.style.fontSize="",ke.style.lineHeight="",ke.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",Pr?(ke.style.backgroundColor=Pr,ke.classList.remove("persona-bg-persona-accent")):ke.classList.add("persona-bg-persona-accent"),ci?ke.style.color=ci:ke.classList.add("persona-text-white");Ue.borderWidth?(ke.style.borderWidth=Ue.borderWidth,ke.style.borderStyle="solid"):(ke.style.borderWidth="",ke.style.borderStyle=""),Ue.borderColor?ke.style.borderColor=Ue.borderColor:ke.style.borderColor="",Ue.paddingX?(ke.style.paddingLeft=Ue.paddingX,ke.style.paddingRight=Ue.paddingX):(ke.style.paddingLeft="",ke.style.paddingRight=""),Ue.paddingY?(ke.style.paddingTop=Ue.paddingY,ke.style.paddingBottom=Ue.paddingY):(ke.style.paddingTop="",ke.style.paddingBottom=""),R.isStreaming()||ke.setAttribute("aria-label",kr),Qc(),Wn&&vn({anchor:ke,trigger:Wn,text:()=>ke.getAttribute("aria-label")??kr,enabled:Jg}),ty(),ng();let tv=Dp(be.getState().activeModeIds,o.composer?.modes);be.setActiveModeIds(tv),Vi().length>0!==!!hr&&Ku(),hr?.render(tv,Vi());for(let Z of[...ji.keys()])Bp(Z,o.composer?.modeGroups)||ji.delete(Z);ji.forEach(Z=>Z.repaint()),Zr?.repaint(),ko?.resolve();let hd=Hs(o,Le());if(tg(),hd){Te.style.maxWidth=hd,Te.style.marginLeft="auto",Te.style.marginRight="auto",Te.style.width="100%",Rn.style.maxWidth=hd,Rn.style.marginLeft="auto",Rn.style.marginRight="auto",Rn.style.width="100%";for(let Z of[An,co,fn,tt])Z&&(Z.style.maxWidth=hd,Z.style.marginLeft="auto",Z.style.marginRight="auto",Z.style.width="100%")}else{Te.style.maxWidth="",Te.style.marginLeft="",Te.style.marginRight="",Te.style.width="",Rn.style.maxWidth="",Rn.style.marginLeft="",Rn.style.marginRight="",Rn.style.width="";for(let Z of[An,co,fn,tt])Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight="",Z.style.width="")}let Ro=o.statusIndicator??{};if(Tf(tt,An,Ro),hi(tt,Ro,R?.getStatus()??"idle"),R){let Z=R.getStatus();_s(tt,(rt=>rt==="idle"?Ro.idleText??Yt.idle:rt==="connecting"?Ro.connectingText??Yt.connecting:rt==="connected"?Ro.connectedText??Yt.connected:rt==="error"?Ro.errorText??Yt.error:rt==="paused"?Ro.pausedText??Yt.paused:rt==="resuming"?Ro.resumingText??Yt.resuming:Yt[rt])(Z),Ro,Z)}tt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let OM=Ro.align==="left"?"persona-text-left":Ro.align==="center"?"persona-text-center":"persona-text-right";tt.classList.add(OM),qu(),vg(),Po(),dr()},open(){Xe()&&Mt(!0,"api")},close(){Xe()&&Mt(!1,"api")},toggle(){Xe()&&Mt(!D,"api")},reconnect(){R.reconnectNow()},clearChat(){yr=!1,i.clear(),r.clear(),s.clear(),l.clear(),R.clearMessages(),o.layout?.topFade&&(ae.scrollTop=0),ae.removeAttribute("data-persona-top-fade"),Mn.clear(),Go();try{localStorage.removeItem(Ga),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ga}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ga)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&&jc(()=>T.clear(),"[AgentWidget] Failed to clear storage adapter:"),k={},_e.syncFromMetadata(),je?.clearAttachments(),zc(),qi(void 0),qo(void 0),Xs(),ft?.clear(),bt?.reset(),rn?.update()},setMessage(a){return!ce||R.isStreaming()||Yo()?!1:(!D&&Xe()&&Mt(!0,"system"),ce.value=a,ce.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(R.isStreaming()||oi())return!1;let u=a?.trim()||ce.value.trim();return u?(!D&&Xe()&&Mt(!0,"system"),ce.value="",ce.style.height="auto",po(),cd(u,{consumeDraft:!1}),!0):!1},getComposerState(){return be.getState()},setQuote(a){let u=a?.text?.trim();u&&qo({...a,text:u})},clearQuote(){qo(void 0)},startVoiceRecognition(){return R.isStreaming()?!1:In(o.voiceRecognition?.provider)?(R.isVoiceActive()||R.isBargeInActive()||(!D&&Xe()&&Mt(!0,"system"),Ge.manuallyDeactivated=!1,zn(),R.toggleVoice().then(()=>{Ge.active=lg(),zn(),Sr("user"),Ge.active&&da()})),!0):Qo?!0:wb()?(!D&&Xe()&&Mt(!0,"system"),Ge.manuallyDeactivated=!1,zn(),ud("user"),!0):!1},stopVoiceRecognition(){return In(o.voiceRecognition?.provider)?!R.isVoiceActive()&&!R.isBargeInActive()?!1:((R.isBargeInActive()?R.deactivateBargeIn():R.toggleVoice()).then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,zn(),Sr("user"),Tr()}),!0):Qo?(Ge.manuallyDeactivated=!0,zn(),ps("user"),!0):!1},injectMessage(a){return!D&&Xe()&&Mt(!0,"system"),R.injectMessage(a)},injectAssistantMessage(a){!D&&Xe()&&Mt(!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&&Xe()&&Mt(!0,"system"),R.injectUserMessage(a)},injectSystemMessage(a){return!D&&Xe()&&Mt(!0,"system"),R.injectSystemMessage(a)},injectMessageBatch(a){return!D&&Xe()&&Mt(!0,"system"),R.injectMessageBatch(a)},injectComponentDirective(a){return!D&&Xe()&&Mt(!0,"system"),R.injectComponentDirective(a)},injectTestMessage(a){!D&&Xe()&&Mt(!0,"system"),R.injectTestEvent(a)},async connectStream(a,u){return R.connectStream(a,u)},__pushEventStreamEvent(a){Me&&(cr(),Qa(a.type,a.payload))},showEventStream(){Me&&ju()},hideEventStream(){Sn&&zi()},isEventStreamVisible(){return Sn},listConversations(a){return R.listConversations(a)},getActiveConversationId(){return R.getActiveConversationId()},openConversation(a,u){return Xo(m=>m.openHistoryConversation(a,{focusComposer:u?.focus===!0}))},startNewConversation(a){return Xo(u=>u.startNewConversation({focusComposer:a?.focus===!0}))},warmSession(){Bg()},deleteConversation(a){return Xo(u=>u.deleteHistoryConversation(a))},renameConversation(a,u){return Xo(m=>m.updateHistoryConversation(a,{title:u}))},setConversationStarred(a,u){return Xo(m=>m.updateHistoryConversation(a,{starred:u}))},clearConversationHistory(a){return Xo(u=>u.clearConversationHistory(a))},resetHistoryIdentity(){return Xo(a=>a.resetHistoryIdentity())},async getVisitorToken(){let a=mo;if(!a)return null;let u=await a.get();return a===mo?u:null},getHistoryIdentityStatus(){let a=Bt?.historyProvider;return a?a.getIdentityStatus():yl()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(a){return yl()?Xo(u=>u.openHistory({...a?.returnSurface?{returnSurface:a.returnSurface}:{},...a?.focus!==void 0?{focus:a.focus}:{}})):Promise.resolve()},hideHistory(a){Bt?.closeHistory(a?.restoreFocus!==void 0?{restoreFocus:a.restoreFocus}:void 0)},isHistoryVisible(){return un},showArtifacts(){$n(o)&&(yr=!1,Gi=!0,Ho(),nt?.setMobileOpen(!0))},hideArtifacts(){$n(o)&&(yr=!0,Ho())},upsertArtifact(a){return $n(o)?(or(o.features?.artifacts,{artifactType:a.artifactType,...a.artifactType==="markdown"&&a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{}})==="panel"&&(yr=!1,Gi=!0),R.upsertArtifact(a)):null},selectArtifact(a){$n(o)&&R.selectArtifact(a)},clearArtifacts(){$n(o)&&R.clearArtifacts()},getArtifacts(){return R?.getArtifacts()??[]},getSelectedArtifactId(){return R?.getSelectedArtifactId()??null},focusInput(){return ye&&!D&&!Le()||!ce?!1:(ce.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){wE(a)},clearFollowUpSuggestions(){Ly()},getMessages(){return R.getMessages()},getStatus(){return R.getStatus()},getPersistentMetadata(){return{...k}},updatePersistentMetadata(a){qe(a)},on(a,u){return X.on(a,u)},off(a,u){X.off(a,u)},isOpen(){return Xe()&&D},isVoiceActive(){return Ge.active},toggleReadAloud(a){R.toggleReadAloud(a)},stopReadAloud(){R.stopSpeaking()},getReadAloudState(a){return R.getReadAloudState(a)},onReadAloudChange(a){return R.onReadAloudChange(a)},getState(){return{open:Xe()&&D,launcherEnabled:ye,voiceActive:Ge.active,streaming:R.isStreaming()}},showCSATFeedback(a){!D&&Xe()&&Mt(!0,"system");let u=Te.querySelector(".persona-feedback-container");u&&u.remove();let m=hu({onSubmit:async(v,w)=>{R.isClientTokenMode()&&await R.submitCSATFeedback(v,w),a?.onSubmit?.(v,w)},onDismiss:a?.onDismiss,...a});Te.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!D&&Xe()&&Mt(!0,"system");let u=Te.querySelector(".persona-feedback-container");u&&u.remove();let m=yu({onSubmit:async(v,w)=>{R.isClientTokenMode()&&await R.submitNPSFeedback(v,w),a?.onSubmit?.(v,w)},onDismiss:a?.onDismiss,...a});Te.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(){Hg(),ri!=null&&(clearInterval(ri),ri=null),i.clear(),r.clear(),s.clear(),l.clear(),Se.forEach(a=>a()),Je.remove(),Xt?.remove(),qt?.destroy(),On?.remove(),qs&&ze.removeEventListener("click",qs)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,u={controller:zt,getMessages:zt.getMessages,getStatus:zt.getStatus,getMetadata:zt.getPersistentMetadata,updateMetadata:zt.updatePersistentMetadata,clearHistory:()=>zt.clearChat(),setVoiceActive:m=>m?zt.startVoiceRecognition():zt.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Se.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=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.focusInput()};if(window.addEventListener("persona:focusInput",u),Se.push(()=>{window.removeEventListener("persona:focusInput",u)}),Me){let ie=de=>{let Pe=de.detail;(!Pe?.instanceId||Pe.instanceId===a)&&zt.showEventStream()},le=de=>{let Pe=de.detail;(!Pe?.instanceId||Pe.instanceId===a)&&zt.hideEventStream()};window.addEventListener("persona:showEventStream",ie),window.addEventListener("persona:hideEventStream",le),Se.push(()=>{window.removeEventListener("persona:showEventStream",ie),window.removeEventListener("persona:hideEventStream",le)})}let m=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.showHistory()},v=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.hideHistory()};window.addEventListener("persona:showHistory",m),window.addEventListener("persona:hideHistory",v),Se.push(()=>{window.removeEventListener("persona:showHistory",m),window.removeEventListener("persona:hideHistory",v)});let w=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.showArtifacts()},P=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.hideArtifacts()},z=ie=>{let le=ie.detail;le?.instanceId&&le.instanceId!==a||le?.artifact&&zt.upsertArtifact(le.artifact)},re=ie=>{let le=ie.detail;le?.instanceId&&le.instanceId!==a||typeof le?.id=="string"&&zt.selectArtifact(le.id)},Y=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.clearArtifacts()};window.addEventListener("persona:showArtifacts",w),window.addEventListener("persona:hideArtifacts",P),window.addEventListener("persona:upsertArtifact",z),window.addEventListener("persona:selectArtifact",re),window.addEventListener("persona:clearArtifacts",Y),Se.push(()=>{window.removeEventListener("persona:showArtifacts",w),window.removeEventListener("persona:hideArtifacts",P),window.removeEventListener("persona:upsertArtifact",z),window.removeEventListener("persona:selectArtifact",re),window.removeEventListener("persona:clearArtifacts",Y)})}let yo=aH(o.persistState);if(yo&&Xe()){let a=lH(yo.storage),u=`${yo.keyPrefix}widget-open`,m=`${yo.keyPrefix}widget-voice`,v=`${yo.keyPrefix}widget-voice-mode`;if(a){let w=yo.persist?.openState&&a.getItem(u)==="true",P=yo.persist?.voiceState&&a.getItem(m)==="true",z=yo.persist?.voiceState&&a.getItem(v)==="true";if(w&&(qt?.setPanelOpen(!0,"auto"),setTimeout(()=>{zt.open(),setTimeout(()=>{if(P||z)zt.startVoiceRecognition();else if(yo.persist?.focusInput){let re=e.querySelector("textarea");re&&re.focus()}},100)},0)),yo.persist?.openState&&(X.on("widget:opened",()=>{a.setItem(u,"true")}),X.on("widget:closed",()=>{a.setItem(u,"false")})),yo.persist?.voiceState&&(X.on("voice:state",re=>{a.setItem(m,re.active?"true":"false")}),X.on("user:message",re=>{a.setItem(v,re.viaVoice?"true":"false")})),yo.clearOnChatClear){let re=()=>{a.removeItem(u),a.removeItem(m),a.removeItem(v)},Y=()=>re();window.addEventListener("persona:clear-chat",Y),Se.push(()=>{window.removeEventListener("persona:clear-chat",Y)})}}}if(Ee&&Xe()&&(qt?.setPanelOpen(!0,"auto"),setTimeout(()=>{zt.open()},0)),oa(),!SE){let a=ua(()=>{R&&(Qs++,Mn.clear(),fo(Te,R.getMessages(),K))});Se.push(a)}I=()=>{R&&(Qs++,Mn.clear(),fo(Te,R.getMessages(),K))},R.getMessages().length>0&&Xc(),W=()=>{R&&(Qs++,Mn.clear(),fo(Te,R.getMessages(),K))};let RM=uv(()=>{R&&(Qs++,Mn.clear(),fo(Te,R.getMessages(),K))});Se.push(RM);let WM=uh(()=>{R&&(Qs++,Mn.clear(),fo(Te,R.getMessages(),K),qr()?.updateInlineArtifactBlocks(Te,uo.artifacts,{suppressTransition:!0}),Ho())});return Se.push(WM),zt};_o();var ux=(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},pH=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},uH=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},gH=(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.")},gx=(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"},Eh=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=""},fx=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Eh(e)},Sh=e=>{e.style.transition=""},Ah=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=""},xh=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Cu=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},fH=(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))},mH=(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)},hH=e=>{let t=No(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:wn(t,r)??r;return{inset:o(n?.inset,Up),canvasBackground:o(n?.canvasBackground,Vp)}},mx=(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},yH=(e,t,n,o,r,s,i,l)=>{let c=Zn(s),p=c.reveal==="push",d=l!=null,g=l?.inset??"",f=l?.canvasBackground??"";fH(e,t,n,o,p),mH(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"),Ah(t),Sh(o),fx(o),xh(n),Cu(r,o),mx(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??Pn),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"),fx(o),pH(o,c.maxHeight),mx(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",Ah(t),Sh(o),xh(n),Cu(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",Sh(o),Eh(o),Cu(r,o);let L=ux(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="",Ah(t),Eh(o),xh(n),Cu(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",uH(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(${ux(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"}}},bH=(e,t)=>{let n=e.ownerDocument.createElement("div");return gx(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){gx(n,o)},destroy(){n.remove()}}},vH=(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?hH(t):null};b();let C=()=>{yH(i,l,c,p,d,t,g,y)},A=null,L=()=>{A?.(),A=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(A=Oa(()=>{b(),C()}))},I=()=>{h(),Zn(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,gH(i,Zn(t)))},V=i.ownerDocument.defaultView,oe=()=>{B()};return V?.addEventListener("resize",oe),Zn(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",oe),A?.(),A=null,h(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),i.remove()}}},bc=(e,t)=>Lt(t)?vH(e,t):bH(e,t);var CH=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},hx=(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)},wu=[],yx=()=>[...wu],Mh=e=>{let t=CH(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=bc(t,r),i,l=[],c=(C,A)=>{let I=!(A?.launcher?.enabled??!0)||Lt(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),hx(B,o)}else C.appendChild(H),hx(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=vu(C,r,{debugTools:e.debugTools}),d()},f=()=>{l.forEach(C=>C()),l=[],i.destroy()};g(),e.onChatReady?.();let h=C=>{f(),s.destroy(),s=bc(t,C),r=C,g()},y={update(C){let A=pu(r??{},C),L=Lt(r),I=Lt(A),H=Rs(r),B=Rs(A);if(L!==I||H!==B){h(A);return}r=A,s.updateConfig(r),i.update(C),p()},destroy(){f(),s.destroy();let C=wu.indexOf(b);C!==-1&&wu.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 wu.push(b),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=b),b};ha();Rl();Dd();Ca();pi();Cs();Nr();var Sx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),wH=new Set(["button","a","input","select","textarea","details","summary"]),SH=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Th=/\b(product|card|item|listing|result)\b/i,Ph=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,AH=3e3,xH=100;function Ax(e){let t=typeof e.className=="string"?e.className:"";if(Th.test(t)||e.id&&Th.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Th.test(o.value))return!0}return!1}function xx(e){return Ph.test((e.textContent??"").trim())}function Ex(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 EH(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function bx(e){let t=e.match(Ph);return t?t[0]:null}function vx(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 MH(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 TH="commerce-card",kH="result-card";function Cx(e){return!Ax(e)||!xx(e)||!Ex(e)&&!EH(e)?0:5200}function wx(e){return!Ax(e)||xx(e)||!Ex(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Lh=[{id:TH,scoreElement(e){return Cx(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||Ph.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(Cx(e)===0)return null;let{title:n,href:o}=vx(e),r=bx((e.textContent??"").trim())??bx(t.text)??"",s=MH(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(`
140
+ `)}if(!w&&!u){let Be="max-height: -moz-available !important; max-height: stretch !important;",Ye=m?"":"padding-top: 1.25em !important;",Ue=m?"":`z-index: ${o.launcher?.zIndex??kn} !important;`;Je.style.cssText+=Be+Ye+Ue}$t(),Co()},tg=()=>{e.style.setProperty("--persona-content-max-width",Hs(o,Le()))},fy=!1;function my(){o.layout?.topFade&&ae.scrollTop>1?ae.setAttribute("data-persona-top-fade","true"):ae.removeAttribute("data-persona-top-fade")}let ng=()=>{my();let a=Pm(o,Le());Le()&&o.composer?.placement&&o.debug===!0&&!fy&&(fy=!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??Kp),Ot()},hy=()=>{if(Le())return;let a=Lt(o),u=o.launcher?.sidebarMode??!1;if(a||u||(o.launcher?.fullHeight??!1)||!ye)return;let v=e.ownerDocument.defaultView??window,w=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640;if(w&&v.innerWidth<=k)return;let z=Hi(o);Ae.style.height=z.height,Ae.style.maxHeight=z.maxHeight};eg(),Ei(e,o),dc(e,o),pc(e,o),tg(),ng(),Us=()=>{eg(),hy(),Ei(e,o),dc(e,o),pc(e,o),tg(),ng(),kc?e.style.setProperty("--persona-artifact-welded-outer-radius",kc):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Vn(),dr()};let Se=[];Se.push(()=>{iy=!0}),Se.push(()=>{f.forEach(a=>a()),g.destroy()}),Se.push(()=>{document.removeEventListener("keydown",dy)}),Se.push(()=>{Jr!==null&&clearTimeout(Jr)});let zo=null,Ko=null;Se.push(()=>{zo?.(),zo=null,Ko?.(),Ko=null}),ol&&Se.push(()=>{ol?.disconnect(),ol=null}),Se.push(()=>{al?.(),al=null,Zu(),Ut&&(Ut.remove(),Ut=null),nt?.element.style.removeProperty("width"),nt?.element.style.removeProperty("maxWidth"),nt?.destroy()}),Me&&Se.push(()=>{_i=!0,Ft=null,lo!==null&&(cancelAnimationFrame(lo),lo=null),rn?.destroy(),rn=null,ft?.destroy(),ft=null,pn=null});let Vs=null,yy=()=>{Vs&&(Vs(),Vs=null),o.colorScheme==="auto"&&(Vs=Oa(()=>{Ei(e,o)}))};yy(),Se.push(()=>{Vs&&(Vs(),Vs=null)}),Se.push(()=>{L=!0,A?.()}),Se.push(()=>{V=!0});let by=!1;Se.push(()=>{by=!0});let og=(a,u)=>{let m=tc(a,u);return m||!ZS.includes(a)?m:(oA().then(v=>{if(by)return;ec(v.wipe),ec(v.glyphCycle);let w=tc(a,u);w&&rc(w,e)}).catch(()=>{}),null)},Dc=o.features?.streamAnimation;if(Dc?.type&&Dc.type!=="none"){let a=og(Dc.type,Dc.plugins);a&&rc(a,e),Se.push(()=>nA(e))}let vr=ac(co),vy=ac(gr),Cy=ac(Xr),js=[vr,vy,Cy];Se.push(()=>{js.forEach(a=>a.destroy())});let qs=null,R,zs=null,wy=!1,Sy=0,Ay=null,xy=a=>a.reduce((u,m)=>m.role==="user"?u+1:u,0),Ey=a=>{for(let u=a.length-1;u>=0;u--)if(gi(a[u]))return a[u].id??null;return null},My=!1,wE=()=>{My||o.debug!==!0||(My=!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".'))},Ty=!1,Py=!1,ky=(a,u)=>{Ty||o.debug!==!0||!u.enabled||u.expose||wy||Py&&(R.isStreaming()||a.some(gi)||(Ty=!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.")))},Ks=a=>{if(!R)return;let u=a??R.getMessages(),m=de=>{de.render([],R,ce,u)},v=de=>{js.forEach(ke=>{ke!==de&&m(ke)})};zs&&(xy(u)>Sy||Ey(u)!==Ay)&&(zs=null);let w=xs(o);ky(u,w);let k=w.enabled?Bd(u):null,z=zs??k,re=zs?"host":"agent";if(z){let de=o.suggestions?.followUps,ke=de?.placement??(de?"auto":"composer"),gt=(ke==="auto"?Le()?"composer":"after-message":ke)==="after-message"?Cy:vr;v(gt),gt.render(z,R,ce,u,o.suggestionChipsConfig,{source:re,surface:"followUp",variant:de?.variant??"chip",behavior:de?.behavior??"send",overflow:de?.overflow??"wrap",maxItems:de?.maxItems??4,config:o,plugins:d,submitPrompt:ld});return}if(u.some(de=>de.role==="user")){js.forEach(m);return}let Y=o.future?.v5Defaults===!0,ie=jn(),le=o.suggestions?.starters??(Y?{}:void 0);if(le){let de=Ws(E(),u),ke=le.placement??"auto",it=ke==="auto"?de?"welcome":"composer":ke;if(it==="welcome"&&!de){wE(),js.forEach(m);return}let gt=it==="welcome"?vy:vr;v(gt),gt.render(le.items??o.suggestionChips,R,ce,u,o.suggestionChipsConfig,{surface:"starter",variant:le.variant??(Y&&!ie?"chip":"card"),behavior:le.behavior??"send",overflow:le.overflow??"wrap",maxItems:le.maxItems??(Y&&!ie?3:4),config:o,plugins:d,submitPrompt:ld});return}v(vr),vr.render(o.suggestionChips,R,ce,u,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:d,submitPrompt:ld})},Ly=()=>{zs&&(zs=null,Ks())},SE=a=>{let u=Array.isArray(a)?[...a]:[];if(!u.length){Ly();return}let m=R?R.getMessages():[];zs=u,wy=!0,Sy=xy(m),Ay=Ey(m),Ks(m)},no=!1,Mn=$S(),Yi=new Map,Gs=new Map,ns=new Map,Ys=null,os=null;function Xs(){if(!Ys)return;let a=Ys;Ys=null,os?.destroy(),os=null,Mn.delete(a),we.querySelector(`#wrapper-${a}`)?.removeAttribute("data-preserve-runtime"),R&&fo(Te,R.getMessages(),K)}let Qs=0,AE=nr()!==null,oo=zS(),ro=0,rs=null,qn=!1,Nc=!1,ss=0,an=null,Js=null,rg=!1,Xi=!1,Zs=null,ll=!0,Fc=!1,Qi=null,$c=!1,is=()=>{$c=!0,TE()},sg=null,xE=4,Cr=24,EE=80,ME=1e3,wr=null,Hy=()=>{e.setAttribute("data-persona-scrollbar",Ns()),Ns()!=="on-scroll"&&(wr!==null&&clearTimeout(wr),wr=null,ae.removeAttribute("data-persona-scrollbar-visible"))},TE=()=>{Ns()==="on-scroll"&&(ae.setAttribute("data-persona-scrollbar-visible",""),wr!==null&&clearTimeout(wr),wr=setTimeout(()=>{wr=null,Mi(ae,Cr)&&ae.removeAttribute("data-persona-scrollbar-visible")},ME))};Hy(),Se.push(()=>{wr!==null&&clearTimeout(wr)});let ig=new Map,ag=!1,Uc=null,Ge={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};ko();let Iy=o.voiceRecognition?.autoResume??!1,lg=()=>R.isVoiceActive()||R.isBargeInActive(),Ry=!1,Sr=a=>{X.emit("voice:state",{active:Ge.active,source:a,timestamp:Date.now()})},zn=()=>{qe(a=>({...a,voiceState:{active:Ge.active,timestamp:Date.now(),manuallyDeactivated:Ge.manuallyDeactivated}}))},PE=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=wh(P.voiceState),u=!!a.active,m=Number(a.timestamp??0);Ge.manuallyDeactivated=!!a.manuallyDeactivated,u&&Date.now()-m<oH&&setTimeout(()=>{Ge.active||(Ge.manuallyDeactivated=!1,In(o.voiceRecognition?.provider)?R.toggleVoice().then(()=>{Ge.active=lg(),Sr("restore"),Ge.active?da():(zn(),ad(rH,1e4))}):ud("restore"))},In(o.voiceRecognition?.provider)?0:1e3)},Wy=a=>{Ry=!a.persisted,Ge.active&&zn()};typeof window<"u"&&(window.addEventListener("pagehide",Wy),Se.push(()=>window.removeEventListener("pagehide",Wy)));let kE=()=>R?cx(R.getMessages()).filter(a=>!a.__skipPersist):[],Vc=null,Oy=(a,u)=>{typeof console<"u"&&console.error(a,u)},jc=(a,u)=>{let m=()=>{try{let z=a();return!z||typeof z.then!="function"?null:Promise.resolve(z).catch(re=>{Oy(u,re)})}catch(z){return Oy(u,z),null}},v=Vc,w=v?v.then(()=>m()??void 0):m();if(!w)return;let k=w.finally(()=>{Vc===k&&(Vc=null)});Vc=k};function Ji(a){if(!T?.save)return;let u=a?cx(a):R?kE():[],m=_&&R?.getResumableHandle();m&&(P={...P,durableResume:{executionId:m.executionId,after:m.lastEventId}});let v={messages:u,metadata:P,artifacts:uo.artifacts,selectedArtifactId:uo.selectedId,...ei?{draft:ei}:{}};jc(()=>T.save(v),"[AgentWidget] Failed to persist state:")}let ei,qc=()=>!T?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,cl=bS({write:()=>{if(!qc())return;let a=be.getState(),u=hS({text:a.text,mentionRefs:a.mentionRefs,contentSegments:Ng(),selectedModelId:a.selectedModelId,activeModeIds:a.activeModeIds,quote:a.quote});JSON.stringify(u)!==JSON.stringify(ei)&&(ei=u,Ji())}});function _y(){qc()&&cl.schedule()}function cg(){cl.flush()}function By(a){if(!qc())return;let u=yS(a,{mentionSourceIds:(o.contextMentions?.sources??[]).map(m=>m.id),modelIds:(o.composer?.models??[]).map(m=>m.id),modes:o.composer?.modes??[]});u&&(ei=a,ce&&!ce.value&&(ce.value=u.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),po()),u.selectedModelId&&(be.setSelectedModelId(u.selectedModelId),Zr?.repaint()),Tc(u.activeModeIds??[]),u.quote&&qo(u.quote),cl.cancel())}function zc(){cl.cancel(),ei&&(ei=void 0,qc()&&Ji())}let Zi=null,Dy=()=>Je.querySelector("#persona-scroll-container")||ae,ea=()=>{Zi!==null&&(cancelAnimationFrame(Zi),Zi=null),qn=!1},Ny=()=>{rs!==null&&(cancelAnimationFrame(rs),rs=null),Nc=!1,ea()},LE=()=>no&&pg()&&(En()!=="anchor-top"||Za()),dg=()=>{let a=Qr()||"Jump to latest",u=LE();Vt.toggleAttribute("data-persona-scroll-to-bottom-streaming",u),ss>0?(tn.textContent=String(ss),tn.style.display="",Vt.setAttribute("aria-label",`${a} (${ss} new)`)):(tn.textContent="",tn.style.display="none",Vt.setAttribute("aria-label",u?`${a} (response streaming below)`:a))},Fy=()=>{ss!==0&&(ss=0,dg())},HE=()=>{let a=an?.spacerHeight??0;return a<=0?Mi(ae,Cr):Yc(a)-ae.scrollTop-ae.clientHeight<=Cr},pg=()=>Mo()?!oo.isFollowing():!HE(),ug=()=>!!R&&R.getMessages().length>0,Tn=()=>{if(!Nu()||wc()){Vt.parentNode&&Vt.remove(),Vt.style.display="none";return}Vt.parentNode!==we&&we.appendChild(Vt),Re();let u=ir(ae)>0&&pg()&&ug();u?dg():Fy(),Vt.style.display=u?"":"none"},ta=()=>{oo.pause()&&(Ny(),Tn())},Go=()=>{oo.resume(),Fy(),Tn()},as=(a=!1)=>{Mo()&&ug()&&oo.isFollowing()&&(!a&&!no||(rs!==null&&(cancelAnimationFrame(rs),rs=null),Nc=!0,rs=requestAnimationFrame(()=>{rs=null,Nc=!1,oo.isFollowing()&&IE(Dy(),a?220:140)})))},$y=(a,u,m,v=()=>!0)=>{let w=a.scrollTop,k=u(),z=k-w;if(ea(),Math.abs(z)<1){qn=!0,a.scrollTop=k,ro=a.scrollTop,qn=!1;return}let re=performance.now();qn=!0;let Y=le=>1-Math.pow(1-le,3),ie=le=>{if(!v()){ea();return}let de=u();de!==k&&(k=de,z=k-w);let ke=le-re,it=Math.min(ke/m,1),gt=Y(it),dt=w+z*gt;a.scrollTop=dt,ro=a.scrollTop,it<1?Zi=requestAnimationFrame(ie):(a.scrollTop=k,ro=a.scrollTop,Zi=null,qn=!1)};Zi=requestAnimationFrame(ie)},IE=(a,u=500)=>{let m=ir(a)-a.scrollTop;if(Math.abs(m)<1){ro=a.scrollTop;return}if(Math.abs(m)>=EE){ea(),qn=!0,a.scrollTop=ir(a),ro=a.scrollTop,qn=!1;return}$y(a,()=>ir(a),u,()=>oo.isFollowing())},gg=()=>{if(!ug()){Tn();return}let a=Dy();qn=!0,a.scrollTop=ir(a),ro=a.scrollTop,qn=!1,Tn()},ti=a=>{let u=0,m=a;for(;m&&m!==ae;)u+=m.offsetTop,m=m.offsetParent;return u},RE=()=>{let a=ae.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??ae.ownerDocument.getSelection()},Kc=()=>YS(RE(),ae),fg=()=>{if(Mc()!=="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,'\\"'),v=ae.querySelector(`[data-message-id="${m}"]`);if(!v)return!1;let w=Math.min(Math.max(0,ti(v)-Ds()),ir(ae));return qn=!0,ae.scrollTop=w,ro=ae.scrollTop,qn=!1,En()==="follow"&&!Mi(ae,Cr)&&oo.pause(),Tn(),!0},Gc=a=>{let u=Math.max(0,Math.round(a));Qt.style.height=`${u}px`,Qt.style.display=u>0?"":"none",an&&(an.spacerHeight=Math.max(0,a))},Yc=a=>{let u=parseFloat(getComputedStyle(ae).paddingBottom)||0,m=0;for(let w of Array.from(ae.children)){if(w===Qt||w.offsetHeight===0)continue;let k=ti(w)+w.offsetHeight;k>m&&(m=k)}let v=ae.scrollHeight-a;return m>0?Math.min(m+u,v):v},WE=()=>{if(!an||an.spacerHeight<=0)return;let a=Yc(an.spacerHeight),u=Math.max(0,Math.round(ae.scrollTop)+ae.clientHeight-a+Cr);u<an.spacerHeight&&(Gc(u),Tn())},ni=()=>{Js!==null&&(cancelAnimationFrame(Js),Js=null),ea(),an=null,Qt.style.height="0px",Qt.style.display="none"},Uy=a=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),mg=a=>ae.querySelector(`[data-message-id="${Uy(a)}"]`),Vy=a=>{Js!==null&&cancelAnimationFrame(Js),Js=requestAnimationFrame(()=>{Js=null;let u=Uy(a),m=ae.querySelector(`[data-message-id="${u}"]`);if(!m)return;let v=ti(m),w=an?.spacerHeight??0,k=Yc(w),{targetScrollTop:z,spacerHeight:re}=Lm({anchorOffsetTop:v,topOffset:Ds(),viewportHeight:ae.clientHeight,contentHeight:k,slack:Cr});an={initialSpacerHeight:re,contentHeightAtAnchor:k,spacerHeight:re},Gc(re),$y(ae,()=>m.isConnected?Math.max(0,ti(m)-Ds()):z,220)})},na=()=>{if(En()!=="anchor-top"||!an||!Qi)return;let a=mg(Qi);if(!a)return;ea();let u=an.spacerHeight,m=Yc(u),{targetScrollTop:v,spacerHeight:w}=Lm({anchorOffsetTop:ti(a),topOffset:Ds(),viewportHeight:ae.clientHeight,contentHeight:m,slack:Cr});an={initialSpacerHeight:w,contentHeightAtAnchor:m,spacerHeight:w},Gc(w),qn=!0,ae.scrollTop=v,ro=ae.scrollTop,qn=!1,Tn()},OE=()=>{if(Mo()){if(!oo.isFollowing()||Mi(ae,1))return;as(!no);return}if(an&&an.initialSpacerHeight>0){let a=ae.scrollHeight-an.spacerHeight,u=XS({initialSpacerHeight:an.initialSpacerHeight,contentHeightAtAnchor:an.contentHeightAtAnchor,currentContentHeight:a});u!==an.spacerHeight&&Gc(u)}Tn()},_E=a=>{let u=En();u==="follow"?(Go(),as(!0)):u==="anchor-top"&&(ll=!1,Fc=!0,$c=!1,Qi=a,Vy(a))},BE=()=>{if(En()==="anchor-top"){if(Fc){ll=!1;return}ll=!0,ni(),Go(),as(!0)}},DE=96,NE=a=>{if(Zs===null)return!0;let u=mg(Zs),m=mg(a);if(!u||!m)return!0;let v=ti(m)-ti(u);return Ds()+v>ae.clientHeight-DE},FE=a=>{if(En()!=="anchor-top"||!Fc||$c||Kc())return;let u=Zs===null;for(let m of a){if(!u){m.id===Zs&&(u=!0);continue}if(qS(m)){if(m.id===Qi||!NE(m.id))return;Qi=m.id,Vy(m.id);return}}},$E=a=>{let u=new Map;a.forEach(m=>{let v=ig.get(m.id);u.set(m.id,{streaming:m.streaming,role:m.role}),!v&&m.role==="assistant"&&(X.emit("assistant:message",m),!Xi&&(En()!=="anchor-top"||Za())&&pg()&&(ss+=1,dg(),Tn(),$s(ss===1?"1 new message below.":`${ss} new messages below.`))),m.role==="assistant"&&v?.streaming&&m.streaming===!1&&X.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(v?m.approval.status!=="pending"&&X.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):X.emit("approval:requested",{approval:m.approval,message:m}))}),ig.clear(),u.forEach((m,v)=>{ig.set(v,m)})},dl=(a,u)=>{let m=u==="user"?"user":"assistant",v=o.layout?.messages?.[m],w=v?.width??"content",k=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),k?a.style.setProperty("--persona-message-row-max-width",k):a.style.removeProperty("--persona-message-row-max-width")},Ar=(a,u)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${a}`,m.setAttribute("data-wrapper-id",a),dl(m,u),m},UE=(a,u,m)=>{let v=new Set;for(let O of u){let Ne=O.variant==="tool"?"tool":O.variant==="reasoning"?"reasoning":null;if(!Ne||Ts(o,Ne)!=="row")continue;let Fe=Ne==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;Fe?.expandable!==!1&&(v.add(O.id),i.observe(O,Ne,Ne==="tool"?r:s,Fe))}let w=document.createElement("div"),z=(()=>{let O=d.find(Ne=>Ne.renderLoadingIndicator);if(O?.renderLoadingIndicator)return O.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),re=(O,Ne)=>Ne==null?!1:typeof Ne=="string"?(O.textContent=Ne,!0):(O.appendChild(Ne),!0),Y=new Set,ie=new Map,le=new Set,de=d.some(O=>O.renderAskUserQuestion),ke=[],it=[],gt=o.enableComponentStreaming!==!1,dt=o.approval!==!1,Kn=[],Dt=o.messageActions,jt=Dt?.showRegenerate===!0&&Dt.enabled!==!1&&go.current?.isStreaming()!==!0?Ow(u):null,_n=Dt?.showEdit===!0&&Dt.enabled!==!1,Kt=Dt?.showQuote===!0&&Dt.enabled!==!1,wt=null,Jo=o.features?.reasoningDisplay?.completedVisibility,Zo=O=>Jo==="removed"?!0:Jo==="removed-when-short"?vv(O,o.features?.reasoningDisplay?.shortThinkThreshold):!1,bo=o.features?.toolCallDisplay?.completedVisibility==="removed",vo=O=>O.variant==="reasoning"&&O.reasoning?.status==="complete"?Zo(O.reasoning):bo&&O.variant==="tool"&&O.toolCall?.status==="complete";if(u.forEach(O=>{if(vo(O))return;if(Y.add(O.id),ie.set(O.id,O.role),Ys===O.id&&os){let $e=Ar(O.id,O.role);$e.setAttribute("data-persona-message-edit-stub","true"),$e.setAttribute("data-preserve-runtime","true"),w.appendChild($e),wt={messageId:O.id,element:os.element};return}let Ne=de&&Ir(O),Fe=dt&&O.variant==="approval"&&!!O.approval,se=!Ne&&O.role==="assistant"&&!O.variant&&gt&&hc(O);!Fe&&ns.has(O.id)&&(a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),ns.delete(O.id)),!se&&Gs.has(O.id)&&(a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),Gs.delete(O.id));let St=Ir(O)?`:${O.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${O.agentMetadata?.askUserQuestionAnswers?Object.keys(O.agentMetadata.askUserQuestionAnswers).length:0}`:"",Jt={canRegenerate:jt===O.id,canEdit:_n&&pm(O),canQuote:Kt&&!O.variant&&(O.content?.trim().length??0)>0},Hn=`${Jt.canRegenerate?"r":""}${Jt.canEdit?"e":""}${Jt.canQuote?"q":""}`,mn=FS(O,Qs)+St+`:${Hn}`,Tt=Ne||Fe||se?null:US(Mn,O.id,mn);if(Tt){w.appendChild(Tt.cloneNode(!0)),Ir(O)&&O.toolCall?.id&&O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(le.add(O.toolCall.id),Ju(O));return}let Gt=null,ln=d.find($e=>!!(O.variant==="reasoning"&&$e.renderReasoning||O.variant==="tool"&&$e.renderToolCall||!O.variant&&$e.renderMessage)),We=o.layout?.messages;if(Ir(O)&&O.agentMetadata?.askUserQuestionAnswered===!0){Yi.delete(O.id),a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime");return}if(gi(O)&&xs(o).enabled)return;if(Ir(O)&&o.features?.askUserQuestion?.enabled!==!1){let $e=d.find(cn=>typeof cn.renderAskUserQuestion=="function");if($e&&go.current){let cn=Yi.get(O.id),Co=cn!==mn,hn=null;if(Co){let{payload:Ye,complete:Ue}=Rr(O),hs=O.id,nn=()=>go.current?.getMessages().find(Gn=>Gn.id===hs);hn=$e.renderAskUserQuestion({message:O,payload:Ye,complete:Ue,resolve:Gn=>{let Pr=nn();Pr&&go.current?.resolveAskUserQuestion(Pr,Gn)},dismiss:()=>{let Gn=nn();Gn?.agentMetadata?.awaitingLocalTool&&(go.current?.markAskUserQuestionResolved(Gn),go.current?.resolveAskUserQuestion(Gn,"(dismissed)"))},config:o})}let At=cn!=null;if(Co&&hn===null&&!At){O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(le.add(O.toolCall.id),Ju(O));return}let Be=Ar(O.id,O.role);Be.setAttribute("data-ask-plugin-stub","true"),Be.setAttribute("data-preserve-runtime","true"),w.appendChild(Be),ke.push({messageId:O.id,fingerprint:mn,bubble:hn});return}else{O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(le.add(O.toolCall.id),Ju(O));return}}else if(Fe){let $e=B();if(!$e){w.appendChild(Ar(O.id,O.role));return}let cn=d.find(Be=>typeof Be.renderApproval=="function")??C,hn=ns.get(O.id)!==mn,At=null;if(hn&&cn?.renderApproval){let Be=O.id,Ye=(Ue,hs)=>{let nn=go.current?.getMessages().find(Gn=>Gn.id===Be);nn?.approval&&(nn.approval.toolType==="webmcp"?go.current?.resolveWebMcpApproval(nn.id,Ue):go.current?.resolveApproval(nn.approval,Ue,hs))};At=cn.renderApproval({message:O,defaultRenderer:()=>$e.createApprovalBubble(O,o,l),config:o,approve:Ue=>Ye("approved",Ue),deny:Ue=>Ye("denied",Ue)})}if(hn&&At===null)a.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),ns.delete(O.id),Gt=$e.createApprovalBubble(O,o,l);else{let Be=Ar(O.id,O.role);Be.setAttribute("data-approval-plugin-stub","true"),Be.setAttribute("data-preserve-runtime","true"),w.appendChild(Be),Kn.push({messageId:O.id,fingerprint:mn,bubble:At});return}}else if(ln)if(O.variant==="reasoning"&&O.reasoning&&ln.renderReasoning){if(!te)return;Gt=ln.renderReasoning({message:O,defaultRenderer:()=>rh(O,o,s),config:o})}else if(O.variant==="tool"&&O.toolCall&&ln.renderToolCall){if(!ve)return;Gt=ln.renderToolCall({message:O,defaultRenderer:()=>lh(O,o,r),config:o})}else ln.renderMessage&&(Gt=ln.renderMessage({message:O,defaultRenderer:()=>{let $e=Fa(O,m,We,o.messageActions,to,{loadingIndicatorRenderer:z,widgetConfig:o,actionEligibility:Jt});return O.role!=="user"&&j($e,O,o,R),$e},config:o}));if(!Gt&&se){let $e=mu(O);if($e){let cn=Gs.get(O.id),Co=cn!==mn,hn=o.wrapComponentDirectiveInBubble!==!1&&Fo.getOptions($e.component)?.bubbleChrome!==!1,At=null;if(Co){let Be=fu($e,{config:o,message:O,transform:m});if(Be&&$e.component==="PersonaArtifactInline"){let Ye=Be.hasAttribute("data-artifact-inline")?Be:Be.querySelector("[data-artifact-inline]"),Ue=Ye?.getAttribute("data-artifact-inline")??"",hs=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Ue):Ue,nn=Ue?a.querySelector(`#wrapper-${O.id}`)?.querySelector(`[data-artifact-inline="${hs}"]`)??null:null;Ye&&nn&&nn!==Ye&&qr()?.hasLiveInlineArtifactBlock(nn)&&(Ye===Be?Be=nn:Ye.replaceWith(nn))}if(Be)if(hn){let Ye=document.createElement("div");if(Ye.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ye.id=`bubble-${O.id}`,Ye.setAttribute("data-message-id",O.id),O.content&&O.content.trim()){let Ue=document.createElement("div");Ue.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Ue.innerHTML=m({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),Ye.appendChild(Ue)}Ye.appendChild(Be),At=Ye}else{let Ye=document.createElement("div");if(Ye.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ye.id=`bubble-${O.id}`,Ye.setAttribute("data-message-id",O.id),Ye.setAttribute("data-persona-component-directive","true"),O.content&&O.content.trim()){let Ue=document.createElement("div");Ue.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Ue.innerHTML=m({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),Ye.appendChild(Ue)}Ye.appendChild(Be),At=Ye}}if(At||cn!=null){let Be=Ar(O.id,O.role);Be.setAttribute("data-component-directive-stub","true"),Be.setAttribute("data-preserve-runtime","true"),w.appendChild(Be),it.push({messageId:O.id,fingerprint:mn,bubble:At});return}}}if(!Gt)if(O.variant==="reasoning"&&O.reasoning){if(!te)return;Gt=rh(O,o,s)}else if(O.variant==="tool"&&O.toolCall){if(!ve)return;Gt=lh(O,o,r)}else if(O.variant==="approval"&&O.approval){if(o.approval===!1)return;let $e=B();if(!$e)return;Gt=$e.createApprovalBubble(O,o,l)}else{let $e=o.layout?.messages;$e?.renderUserMessage&&O.role==="user"?Gt=$e.renderUserMessage({message:O,config:o,streaming:!!O.streaming}):$e?.renderAssistantMessage&&O.role==="assistant"?Gt=$e.renderAssistantMessage({message:O,config:o,streaming:!!O.streaming}):Gt=Fa(O,m,$e,o.messageActions,to,{loadingIndicatorRenderer:z,widgetConfig:o,actionEligibility:Jt}),O.role!=="user"&&Gt&&j(Gt,O,o,R)}let Pt=Ar(O.id,O.role);Pt.appendChild(Gt),VS(Mn,O.id,mn,Pt),w.appendChild(Pt)}),et.composerOverlay&&et.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let Fe=Ne.getAttribute("data-persona-ask-sheet-for");Fe&&!le.has(Fe)&&Wr(et.composerOverlay,Fe)}),o.features?.toolCallDisplay?.grouped){let O=[],Ne=[],Fe=o.features.toolCallDisplay.groupedMode==="summary";u.forEach(se=>{if(se.variant==="tool"&&se.toolCall&&ve){if(bo&&se.toolCall.status==="complete")return;Ne.push(se);return}se.variant==="reasoning"&&(!te||se.reasoning?.status==="complete"&&Zo(se.reasoning))||((Ne.length>1||Fe&&Ne.length>0)&&O.push(Ne),Ne=[])}),(Ne.length>1||Fe&&Ne.length>0)&&O.push(Ne),O.forEach(se=>{let St=se.map(We=>Array.from(w.children).find(Pt=>Pt instanceof HTMLElement&&Pt.getAttribute("data-wrapper-id")===We.id)).filter(We=>!!We);if(St.length<(Fe?1:2))return;let Jt=Ar(`tool-group-${se[0].id}`,"assistant");if(Jt.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let We=`tool-group-${se[0].id}`,Pt=se.some(At=>At.toolCall?.status!=="complete"),$e={...se[0],id:We,toolCall:{id:We,name:`${se.length} tools`,status:Pt?"running":"complete",chunks:se.flatMap(At=>At.toolCall?.chunks??[]),success:!se.some(At=>At.toolCall?.success===!1)}};v.add(We),i.observe($e,"tool",r,o.features.toolCallDisplay);let cn=`${Pt?"Using":"Used"} ${se.length} tools`,Co=o.toolCall?.renderGroupedSummary?.({messages:se,toolCalls:se.map(At=>At.toolCall),defaultSummary:cn,config:o}),hn=aw($e,o,r.has(We),Co??cn);hn.bubble.classList.add("persona-tool-group"),hn.body.dataset.personaToolGroupStack="true",St[0].before(Jt),Jt.appendChild(hn.bubble),St.forEach((At,Be)=>{At.style.setProperty("--persona-message-row-max-width","100%"),At.style.setProperty("--persona-activity-stagger",`${Be*40}ms`),At.classList.add("persona-activity-group-child"),hn.body.appendChild(At)});return}let Hn=document.createElement("div");Hn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Hn.setAttribute("data-persona-tool-group","true");let mn=document.createElement("div");mn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",mn.id=`tool-group-summary-${se[0].id}`;let Tt=`Called ${se.length} ${se.length===1?"tool":"tools"}`,Gt=o.toolCall?.renderGroupedSummary?.({messages:se,toolCalls:se.map(We=>We.toolCall).filter(We=>!!We),defaultSummary:Tt,config:o});re(mn,Gt)||(mn.textContent=Tt);let ln=document.createElement("div");ln.className="persona-tool-group-stack persona-flex persona-flex-col",ln.id=`tool-group-stack-${se[0].id}`,ln.setAttribute("data-persona-tool-group-stack","true"),Hn.appendChild(mn),Fe||Hn.appendChild(ln),Jt.appendChild(Hn),St[0].before(Jt),St.forEach((We,Pt)=>{if(Fe){We.remove();return}We.style.setProperty("--persona-message-row-max-width","100%");let $e=document.createElement("div");$e.className="persona-tool-group-item persona-relative",$e.setAttribute("data-persona-tool-group-item","true"),Pt<St.length-1&&$e.setAttribute("data-persona-tool-group-connector","true"),$e.appendChild(We),ln.appendChild($e)})})}i.prune(v),jS(Mn,Y);let fs=O=>O.variant==="tool"&&!ve||O.variant==="reasoning"&&!te||vo(O),er=u.some(O=>O.role==="assistant"&&O.streaming&&!fs(O)),Io=u.length-1;for(;Io>=0&&fs(u[Io]);)Io--;let ms=Io>=0?u[Io]:void 0,xl=Io<u.length-1,ai=ms?.role==="assistant"&&!ms.streaming&&ms.variant!=="approval"&&!xl;if(no&&u.some(O=>O.role==="user")&&!er&&!ai){let O={config:o,streaming:!0,location:"standalone",defaultRenderer:Li},Ne=d.find(se=>se.renderLoadingIndicator),Fe=null;if(Ne?.renderLoadingIndicator&&(Fe=Ne.renderLoadingIndicator(O)),Fe===null&&o.loadingIndicator?.render&&(Fe=o.loadingIndicator.render(O)),Fe===null&&(Fe=Li()),Fe){let se=document.createElement("div"),St=o.loadingIndicator?.showBubble!==!1,Jt=o.layout?.messages?.layout??"bubble";se.className=St?cc("assistant",Jt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),se.setAttribute("data-typing-indicator","true"),St&&(se.style.color="var(--persona-message-assistant-text, var(--persona-text))",Jt!=="flat"&&(se.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",se.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),se.appendChild(Fe);let Hn=Ar("typing-indicator","assistant");Hn.appendChild(se),w.appendChild(Hn)}}if(!no&&u.length>0){let O=u[u.length-1],Ne={config:o,lastMessage:O,messageCount:u.length},Fe=d.find(St=>St.renderIdleIndicator),se=null;if(Fe?.renderIdleIndicator&&(se=Fe.renderIdleIndicator(Ne)),se===null&&o.loadingIndicator?.renderIdle&&(se=o.loadingIndicator.renderIdle(Ne)),se){let St=document.createElement("div"),Jt=o.loadingIndicator?.showBubble!==!1;St.className=Jt?["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(" "),St.setAttribute("data-idle-indicator","true"),St.appendChild(se);let Hn=Ar("idle-indicator","assistant");Hn.appendChild(St),w.appendChild(Hn)}}if(Sw(w),Gp(a,w),im(a),wt){let{messageId:O,element:Ne}=wt,Fe=a.querySelector(`#wrapper-${O}`);Fe&&Ne.parentElement!==Fe&&(dl(Fe,ie.get(O)??"user"),Fe.replaceChildren(Ne))}if(ke.length>0)for(let{messageId:O,fingerprint:Ne,bubble:Fe}of ke){let se=a.querySelector(`#wrapper-${O}`);se&&(dl(se,ie.get(O)??"assistant"),Fe!==null&&(se.replaceChildren(Fe),se.setAttribute("data-bubble-fp",Ne),Yi.set(O,Ne)))}if(Yi.size>0)for(let O of Yi.keys())Y.has(O)||Yi.delete(O);if(it.length>0)for(let{messageId:O,fingerprint:Ne,bubble:Fe}of it){let se=a.querySelector(`#wrapper-${O}`);se&&(dl(se,ie.get(O)??"assistant"),Fe!==null&&(se.replaceChildren(Fe),se.setAttribute("data-bubble-fp",Ne),Gs.set(O,Ne)))}if(Gs.size>0)for(let O of Gs.keys())Y.has(O)||Gs.delete(O);if(Kn.length>0)for(let{messageId:O,fingerprint:Ne,bubble:Fe}of Kn){let se=a.querySelector(`#wrapper-${O}`);se&&(dl(se,ie.get(O)??"assistant"),Fe!==null&&(se.replaceChildren(Fe),se.setAttribute("data-bubble-fp",Ne),ns.set(O,Ne)))}if(ns.size>0)for(let O of ns.keys())Y.has(O)||ns.delete(O)},hg=!1,Xc=()=>{hg||(hg=!0,mi().catch(()=>{}),vd().catch(()=>{hg=!1}))},fo=(a,u,m)=>{u.length>0&&Xc(),UE(a,u,m),sy()},pl=null,VE=()=>{if(pl)return;let a=m=>{let v=m.composedPath();v.includes(Je)||Xt&&v.includes(Xt)||Mt(!1,"user")};pl=a,(e.ownerDocument??document).addEventListener("pointerdown",a,!0)},jy=()=>{if(!pl)return;(e.ownerDocument??document).removeEventListener("pointerdown",pl,!0),pl=null};Se.push(()=>jy());let ul=null,jE=()=>{if(ul)return;let a=m=>{m.key==="Escape"&&(m.isComposing||Mt(!1,"user"))};ul=a,(e.ownerDocument??document).addEventListener("keydown",a,!0)},qy=()=>{if(!ul)return;(e.ownerDocument??document).removeEventListener("keydown",ul,!0),ul=null};Se.push(()=>qy());let gl=!1,zy=new Set,qE=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},oa=()=>{if(!Le())return;let a=et.peekBanner,u=et.peekTextNode;if(!a||!u)return;if(D){a.classList.remove("persona-pill-peek--visible");return}let m=R?.getMessages()??[],v;for(let Dt=m.length-1;Dt>=0;Dt--){let jt=m[Dt];if(jt.role==="assistant"&&jt.content){v=jt;break}}if(!v){a.classList.remove("persona-pill-peek--visible");return}let w=v.content,k=!!v.streaming,z=qE(),re=Yp(z),Y=re.type!=="none"?og(re.type,z?.plugins):null,ie=Y?.isAnimating?.(v)===!0,le=Y!==null&&(k||ie);le&&Y&&!zy.has(Y.name)&&(rc(Y,e),zy.add(Y.name));let de=le&&Y?.containerClass?Y.containerClass:null,ke=u.dataset.personaPeekStreamClass??null;ke&&ke!==de&&(u.classList.remove(ke),delete u.dataset.personaPeekStreamClass),de&&ke!==de&&(u.classList.add(de),u.dataset.personaPeekStreamClass=de),le?(u.style.setProperty("--persona-stream-step",`${re.speed}ms`),u.style.setProperty("--persona-stream-duration",`${re.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let it=le?Xp(w,re.buffer,Y,v,k):w;if(le&&re.placeholder==="skeleton"&&k&&(!it||!it.trim())){let Dt=document.createElement("div"),jt=oc();jt.classList.add("persona-pill-peek__skeleton"),Dt.appendChild(jt),Gp(u,Dt)}else{let Dt=Math.max(0,it.length-100),jt=it.length>100?it.slice(-100):it,_n=Ur(jt);if(!le||!Y){let Kt=it.length>100?`\u2026${jt}`:jt;u.textContent!==Kt&&(u.textContent=Kt)}else{let Kt=_n;(Y.wrap==="char"||Y.wrap==="word")&&(Kt=nc(_n,Y.wrap,`peek-${v.id}`,{skipTags:Y.skipTags,startIndex:Dt}));let wt=document.createElement("div");if(wt.innerHTML=Kt,Y.useCaret&&jt.length>0){let Jo=Qp(),Zo=wt.querySelectorAll(".persona-stream-char, .persona-stream-word"),bo=Zo[Zo.length-1];bo?.parentNode?bo.parentNode.insertBefore(Jo,bo.nextSibling):wt.appendChild(Jo)}Gp(u,wt),Y.onAfterRender?.({container:u,bubble:a,messageId:v.id,message:v,speed:re.speed,duration:re.duration})}}let Kn=no||gl;a.classList.toggle("persona-pill-peek--visible",Kn)};if(Le()){let a=et.peekBanner;if(a){let v=w=>{w.preventDefault(),w.stopPropagation(),Mt(!0,"user")};a.addEventListener("pointerdown",v),Se.push(()=>{a.removeEventListener("pointerdown",v)})}let u=()=>{gl||(gl=!0,oa())},m=()=>{gl&&(gl=!1,oa())};Ae.addEventListener("pointerenter",u),Ae.addEventListener("pointerleave",m),Se.push(()=>{Ae.removeEventListener("pointerenter",u),Ae.removeEventListener("pointerleave",m)}),Xt&&(Xt.addEventListener("pointerenter",u),Xt.addEventListener("pointerleave",m),Se.push(()=>{Xt.removeEventListener("pointerenter",u),Xt.removeEventListener("pointerleave",m)}))}let zE=a=>{let u=o.launcher?.composerBar??{},m=u.expandedSize??"anchored",v=u.bottomOffset??"16px",w=u.collapsedMaxWidth,k=u.expandedMaxWidth??"880px",z=u.expandedTopOffset??"5vh",re=u.modalMaxWidth??"880px",Y=u.modalMaxHeight??"min(90vh, 800px)",ie="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",de=Je.style;if(de.left="",de.right="",de.top="",de.bottom="",de.transform="",de.width="",de.maxWidth="",de.height="",de.maxHeight="",Xt){let ke=Xt.style;ke.bottom=v,ke.width=w??""}if(a&&m!=="fullscreen"){if(m==="modal"){de.top="50%",de.left="50%",de.transform="translate(-50%, -50%)",de.bottom="auto",de.right="auto",de.width=re,de.maxWidth=ie,de.maxHeight=Y,de.height=Y;return}de.left="50%",de.transform="translateX(-50%)",de.bottom=`calc(${v} + ${le})`,de.top=z,de.width=k,de.maxWidth=ie}},fl=()=>{if(D&&Xc(),!Xe())return;if(Le()){let ie=(o.launcher?.composerBar??{}).expandedSize??"anchored",le=D?"expanded":"collapsed";Je.dataset.state=le,Je.dataset.expandedSize=ie,Xt&&(Xt.dataset.state=le,Xt.dataset.expandedSize=ie),Je.style.removeProperty("display"),Je.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),zE(D),we.style.display=D?"flex":"none",Us(),D?(VE(),jE()):(jy(),qy()),oa();return}let a=Lt(o),u=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,v=o.launcher?.mobileFullscreen??!0,w=u.innerWidth<=m,k=v&&w&&ye,z=Zn(o).reveal;D?(Je.style.removeProperty("display"),Je.style.display=a?"flex":"",Je.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-95","persona-opacity-0"),Ae.classList.add("persona-scale-100","persona-opacity-100"),qt?(qt.setPanelOpen(!0),qt.element.style.display="none"):On&&(On.style.display="none")):(a?a&&(z==="overlay"||z==="push")&&!k?(Je.style.removeProperty("display"),Je.style.display="flex",Je.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Je.style.setProperty("display","none","important"),Je.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Je.style.display="",Je.classList.add("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-100","persona-opacity-100"),Ae.classList.add("persona-scale-95","persona-opacity-0")),qt?(qt.setPanelOpen(!1),qt.element.style.display=a?"none":""):On&&(On.style.display=a?"none":""))},Mt=(a,u="user")=>{if(!Xe()||D===a)return;let m=D;D=a,fl();let v=(()=>{let k=o.launcher?.sidebarMode??!1,z=e.ownerDocument.defaultView??window,re=o.launcher?.mobileFullscreen??!0,Y=o.launcher?.mobileBreakpoint??640,ie=z.innerWidth<=Y,le=Lt(o)&&re&&ie,de=Le()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return k||re&&ie&&ye||le||de})();if(D&&v){if(!zo){let k=e.getRootNode(),z=k instanceof ShadowRoot?k.host:e.closest(".persona-host");z&&(zo=Rm(z,o.launcher?.zIndex??kn))}Ko||(Ko=Wm(e.ownerDocument))}else D||(zo?.(),zo=null,Ko?.(),Ko=null);D&&(wl(),fg()||(En()==="follow"?as(!0):gg()));let w={open:D,source:u,timestamp:Date.now()};D&&!m?X.emit("widget:opened",w):!D&&m&&X.emit("widget:closed",w),X.emit("widget:state",{open:D,launcherEnabled:ye,voiceActive:Ge.active,streaming:R.isStreaming()})},ls={inputDisabled:!1,sendDisabled:!1},Yo=()=>ls.inputDisabled,yg=()=>In(o.voiceRecognition?.provider)&&!!R&&(R.isBargeInActive()||["listening","processing","speaking"].includes(R.getVoiceStatus())),oi=()=>ls.inputDisabled||ls.sendDisabled,KE=()=>(ls.inputDisabled?ls.inputReason:void 0)??(ls.sendDisabled?ls.sendReason:void 0);function bg(){if(!Pe)return;if(be.getState().phase==="streaming"){Pe.disabled=!1;return}let a=je?!je.isReady():!1;Pe.disabled=oi()||a}function Qc(){if(!Wn)return;let a=be.getState(),u=o.sendButton?.visibility==="when-text"&&a.phase!=="streaming"&&a.text.trim().length===0&&a.attachments.length===0;Wn.toggleAttribute("data-persona-send-hidden",u)}function GE(){let a=KE();if(Le()){let u=An??Ke;a?u.setAttribute("title",a):u.removeAttribute("title"),Ke.toggleAttribute(Ya,!!a);return}if(a){tt.setAttribute("role","status"),tt.setAttribute("aria-live","polite"),tt.setAttribute(Ya,""),tt.removeAttribute(yc),tt.textContent=a,hi(tt,o.statusIndicator??{},"idle");return}if(tt.hasAttribute(Ya)&&(tt.removeAttribute("role"),tt.removeAttribute("aria-live"),tt.removeAttribute(Ya),h)){let u=R.getStatus();_s(tt,ur(u),o.statusIndicator??{},u)}}function vg(){let a=Nf(o.composer?.inputDisabled),u=Nf(o.composer?.sendDisabled);ls={inputDisabled:a.disabled,inputReason:a.reason,sendDisabled:u.disabled,sendReason:u.reason},be.setInputDisabled(a.disabled),be.setSendDisabled(u.disabled);let m=be.getState().phase==="streaming",v=a.disabled,w=m||v;ce&&(ce instanceof HTMLTextAreaElement?ce.disabled=v:ce.setAttribute("contenteditable",v?"false":"true"),ce.setAttribute("aria-disabled",v?"true":"false")),It&&(It.disabled=v),Et&&(Et.disabled=v);for(let k of at?.affordanceButtons??[])k.querySelectorAll("button").forEach(z=>{z.disabled=v});he&&(he.disabled=v||m&&!yg()),js.forEach(k=>{k.elements.forEach(z=>{z.toggleAttribute("data-disabled",w),z instanceof HTMLButtonElement||z.setAttribute("aria-disabled",w?"true":"false")}),k.buttons.forEach(z=>{z.disabled=w})}),Eg.forEach(k=>{k.toggleAttribute("data-disabled",w),k instanceof HTMLButtonElement?k.disabled=w:k.setAttribute("aria-disabled",w?"true":"false"),k.querySelectorAll("button").forEach(z=>{z.disabled=w})}),Ke.dataset.personaComposerStreaming=m?"true":"false",Ke.dataset.personaComposerInputDisabled=v?"true":"false",Ke.dataset.personaComposerSendDisabled=oi()?"true":"false",Ke.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(k=>{(k instanceof HTMLButtonElement||k instanceof HTMLInputElement||k instanceof HTMLTextAreaElement||k instanceof HTMLSelectElement)&&(k.disabled=m)}),bg(),GE()}let ml=a=>{be.setStreaming(a),xc(a?"stop":"send"),vg()},Jc=()=>{Ge.active||ce&&ce.focus()};X.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Jc(),200)});let Ky=null,Cg=!1,wg=!en.hidden,cs=null,Sg=!J,Zc=null;Se.push(()=>{Zc?.cancel(),Zc=null});let YE=a=>{let u=AA(a);if(u===N)return;N=u,e.setAttribute("data-persona-conversation-state",u);let m=pe();Ot(),Sg&&(Zc?.cancel(),Zc=wA(Ke,u==="active"?m:pe(),u==="active"?"drop":"rise",E().layout==="centered"?320:260)),na()},Gy=null,Yy,Xy=null,ra=null,Ag=!1,hl=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!==Gy||u.icon!==Yy)&&(Gy=m,Yy=u.icon,su({host:en,iconHolder:Sc,kicker:Ac,title:Bu,subtitle:Ni,starterSuggestions:gr},u));let v=u.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${u.message}`;v!==Xy&&(Xy=v,iu(Rn,u.message,o));let w=a??(R?R.getMessages():o.initialMessages);YE(w);let k=Cg,z=!k&&Ws(u,w),re=z!==wg;if(wg=z,ra){cs?.cancel(),cs=null,k!==Ag&&(Ag=k,k?Xm(ae,en,null):Ym(ae,en,ra)),$a(ae,en,!k);return}if(re&&!z&&!k&&u.dismiss==="on-first-message"&&Sg){cs=CA(en,ie=>{cs===ie&&(cs=null),!wg&&!ra&&($a(ae,en,!1),na()),ie?.cancel()});return}if(cs){if(!z&&!k)return;cs.cancel(),cs=null}let Y=!en.hidden;$a(ae,en,z),!z&&Y&&na()},xg=[],Eg=[],Mg=!1,Qy=null,Jy,Zy=()=>{Eg.length=0;let a=xg.splice(0,xg.length);for(let u of a)try{u()}catch(m){console.warn("[persona] renderWelcome cleanup threw",m)}};Se.push(Zy);let XE=(a,u)=>{let m=_m(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=Bm({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:()=>ce,eventTarget:en,submitPrompt:ld});return Eg.push(w),w},Tg=()=>{if(Mg)return;Mg=!0;let a=E();Qy=`${a.variant}|${a.layout}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`,Jy=a.icon;try{Zy(),Xm(ae,en,ra),ra=null,Ag=!1;let u=R?R.getMessages():o.initialMessages,m=Ws(a,u),v=0,w=null;for(let k of d)if(k.renderWelcome&&(w=k.renderWelcome({config:a,variant:a.variant,visible:m,defaultRenderer:()=>en,sendMessage:z=>{if(!R||R.isStreaming())return;let re=z.trim();re&&R.sendMessage(re)},requestRender:()=>Tg(),renderStarter:z=>XE(z,v++),storage:y(k.id),onCleanup:z=>{xg.push(z)}}),w))break;w&&w!==en&&(ra=w,Ym(ae,en,w))}finally{Mg=!1}hl()},QE=()=>{let a=E();`${a.variant}|${a.layout}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`===Qy&&a.icon===Jy||Tg()},ed=()=>{hl(),Ki||(ce.placeholder=pS(be.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!R?.isStreaming()&&(Pe.textContent=o.copy?.sendButtonLabel??"Send")),ce.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ce.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},JE=!!o.setStoredConversationId,sa=a=>qe(u=>{let m={...u};return delete m[a],m}),td=a=>{let u=P[a];return typeof u=="string"?u:null},eb=()=>{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:()=>td("sessionId"),setStoredSessionId:a=>{qe(u=>({...u,sessionId:a}))},clearStoredSessionId:o.clearStoredSessionId??(()=>sa("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>td("conversationId")),setStoredConversationId:o.setStoredConversationId??(a=>{qe(u=>({...u,conversationId:a}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>sa("conversationId"))});let tb=()=>o.clientToken??null,nb=a=>ox(a,Ct(),o.persistState===!1),ob=tb(),mo=ob?nb(ob):null,ZE=()=>{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")}},ds={...mo?{visitorStore:mo}:{},historyBootstrapReady:o.features?.history?.enabled===!0&&!wp()?Promise.all([ue,me]).then(()=>{}):ue,getStoredMessageCursor:()=>td("historyMessageCursor"),setStoredMessageCursor:a=>{if(a===null){sa("historyMessageCursor");return}qe(u=>({...u,historyMessageCursor:a}))},getPendingDisplayProjections:ZE,setPendingDisplayProjections:a=>{if(!a){sa("pendingDisplayProjections");return}qe(u=>({...u,pendingDisplayProjections:a}))},getStoredResumableHandle:eb,setStoredResumableHandle:a=>{if(!a){sa("durableResume");return}qe(u=>({...u,durableResume:a}))},shouldResumeDurableConversation:()=>_&&eb()!==null,...JE?{}:{getStoredConversationRevision:()=>td("conversationRevision"),setStoredConversationRevision:a=>{if(a===null){sa("conversationRevision");return}qe(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),Se.push(()=>{u?.removeEventListener("pagehide",v),u?.removeEventListener("pageshow",w)}),o={...o,reconnectStream:o.reconnectStream??(k=>R.getClient().reconnectClientTokenStream(k)),onExecutionState:k=>{(k||!m)&&ds.setStoredResumableHandle?.(k?{executionId:k.executionId,after:k.lastEventId}:null),a?.(k)}}}let eM=()=>{let a=tb();if(a&&mo?.matches(a,Ct(),o.persistState===!1)||!a&&!mo)return;mo?.destroy(),mo=a?nb(a):null;let u={...ds};mo?u.visitorStore=mo:delete u.visitorStore,ds=u,R.setHistoryInternals(ds)},ri=null,tM=()=>{ri==null&&(ri=setInterval(()=>{let a=Te.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(ri),ri=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")?Ul(u-v):Ed(u-v))})},100))},Pg=(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,re)=>Pg(z,u[re]));let m=a,v=u,w=Object.keys(m),k=Object.keys(v);return w.length===k.length&&w.every(z=>Object.prototype.hasOwnProperty.call(v,z)&&Pg(m[z],v[z]))},rb=a=>{let{content:u,rawContent:m,llmContent:v,...w}=a;return w},kg=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!hc(a),nM=(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))&&kg(v)&&kg(w)&&Pg(rb(v),rb(w))},nd=null,ia=null,si=null,xr=null,Lg=null,oM=a=>{if(!_)return Ji(a);Lg=a,queueMicrotask(()=>{Lg===a&&(Lg=null,Ji(a))})},od=a=>{nd=a;let u,m;ia=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),!ia&&kg(k)&&(ia={index:w,id:k.id}),u&&m&&ia)break}fo(Te,a,K),qr()?.updateInlineArtifactBlocks(Te,uo.artifacts,{suppressTransition:no}),tM(),hl(a),Ks(a),as(!no),$E(a),a.length===0&&(ni(),ll=!0,Fc=!1,Qi=null,$c=!1),!rg||Xi?(rg=!0,Zs=u?.id??null,sg=m?.id??null):u&&u.id!==Zs?(Zs=u.id,_E(u.id)):m&&m.id!==sg&&BE(),m&&(sg=m.id),FE(a);let v=Ge.lastUserMessageId;u&&u.id!==v&&(Ge.lastUserMessageId=u.id,X.emit("user:message",u)),Ge.lastUserMessageWasVoice=!!u?.viaVoice,oM(a),oa()},Hg=()=>{xr!==null&&(cancelAnimationFrame(xr),xr=null);let a=si;si=null,a&&od(a)},sb=()=>{xr!==null&&cancelAnimationFrame(xr),xr=null,si=null},rM=a=>{let u=si??nd;if(no&&u&&ia&&nM(u,a,ia)){si=a,xr===null&&(xr=requestAnimationFrame(()=>{xr=null;let m=si;si=null,m&&od(m)}));return}if(a.length===0){sb(),od(a);return}Hg(),od(a)};R=new Wa(o,{onMessagesChanged(a){rM(a)},onStatusChanged(a){let u=o.statusIndicator??{};_s(tt,(v=>v==="idle"?u.idleText??Yt.idle:v==="connecting"?u.connectingText??Yt.connecting:v==="connected"?u.connectedText??Yt.connected:v==="error"?u.errorText??Yt.error:v==="paused"?u.pausedText??Yt.paused:v==="resuming"?u.resumingText??Yt.resuming:Yt[v])(a),u,a),Yr()},onStreamingChanged(a){a||(R?.getMessages().length===0?sb():Hg()),no=a,ml(a),Yr(),R&&fo(Te,R.getMessages(),K),a||(as(!0),WE(),Py=!0,R&&ky(R.getMessages(),xs(o))),Tn(),$s(a?"Responding\u2026":"Response complete."),oa()},onVoiceStatusChanged(a){if(X.emit("voice:status",{status:a,timestamp:Date.now()}),a!=="disconnected"&&!In(o.voiceRecognition?.provider))return;let u=R.getVoiceNotice();switch(u&&ad(u,1e4),a){case"listening":if(!ag){let m=R.getVoiceDisclosure();m&&(ag=!0,Le()?(Uc=ce.placeholder,ce.placeholder=m,$s(m)):ad(m,1e4))}Tr(),da();break;case"processing":Tr(),TM();break;case"speaking":Tr(),PM();break;default:a==="idle"&&R.isBargeInActive()?(Tr(),da(),he?.setAttribute("aria-label","End voice session")):(Ge.active=!1,ag=!1,Uc!==null&&(ce.placeholder=Uc,Uc=null),Tr(),Sr("system"),Ry||zn());break}},onArtifactsState(a){uo=a,a.artifacts.length===0&&(Gi=!1),qr()?.updateInlineArtifactBlocks(Te,a.artifacts,{suppressTransition:no}),Ho(),Ji()},onHistoryStateChanged(a){pr(a)},onHistoryNotice(a){Uo(a)},onReconnect(a){let{executionId:u,lastEventId:m}=a.handle;a.phase==="paused"?X.emit("stream:paused",{executionId:u,after:m}):a.phase==="resuming"?X.emit("stream:resuming",{executionId:u,after:m,attempt:a.attempt??1}):X.emit("stream:resumed",{executionId:u,after:m})}},ds),go.current=R,Se.push(()=>R.cancel()),Se.push(()=>{R.destroy(),mo?.destroy(),mo=null});let Ig=null;if(R.onReadAloudChange((a,u)=>{oy=a,ry=u,sy();let m=a??Ig;a&&(Ig=a);let v=m?R.getMessages().find(w=>w.id===m)??null:null;X.emit("message:read-aloud",{messageId:m,message:v,state:u,timestamp:Date.now()}),u==="idle"&&(Ig=null)}),h=!0,rg=!0,o.voiceRecognition?.enabled===!0&&In(o.voiceRecognition.provider))try{R.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}let Bt=null,Rg=null,ib=!1,ab=R.getHistoryState(),yl=()=>o.features?.history?.enabled===!0,lb=a=>{a&&(To.textContent="",To.textContent=a)},Wg=()=>{f.forEach(m=>m()),f=[];let a=Bt,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:()=>un&&Un==="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}`}))};Wg();let rd=null,cb=!1,bl=()=>{if(!Vo)return;let a=o.layout?.header?.titleSource==="conversation",u=a&&rd?.trim()||null;Vo.textContent=u??o.launcher?.title??"Chat Assistant";let m=Vo.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")},sM=a=>{a!==rd&&(rd=a,bl())},iM=a=>{cb=a?.starred===!0,sM(a&&a.title.trim()||null),bl()};bl(),we.addEventListener("persona:title-menu-builtin",a=>{let u=a.detail?.actionId,m=R.getActiveConversationId();m&&(u==="delete"?Xo(v=>v.requestDeleteConversation(m)):u==="star"&&R.canUpdateConversations()&&Xo(v=>v.updateHistoryConversation(m,{starred:!cb})).catch(()=>{}))}),pr=a=>{ab=a,Bt?.historySurface?.view.setNewConversationRequired(a.recovery==="new_conversation_required"),ml(a.sendBlocked||no),Bt?.syncEarlierMessagesPill()},Uo=a=>{(a.code==="history_continuity_reset"||a.code==="conversation_deleted_recovered")&&(Mn.clear(),ni(),Go()),lb(a.message),Bt?.historySurface?.view.refresh()};let aM={get actionManager(){return _e},get activeConversationTitle(){return rd},announceHistory:lb,get applyRailChrome(){return Vn},set applyRailChrome(a){Vn=a},get artifactSplitRoot(){return br},get body(){return ae},get config(){return o},get container(){return we},get conversationOpenPendingEl(){return Ky},set conversationOpenPendingEl(a){Ky=a},get conversationOpenTakeover(){return Cg},set conversationOpenTakeover(a){Cg=a},currentKeyPrefix:Ct,destroyCallbacks:Se,eventBus:X,get footer(){return Ke},get header(){return mt},get historyChromeSync(){return Yr},set historyChromeSync(a){Yr=a},historyFeatureEnabled:yl,get historyInternals(){return ds},set historyInternals(a){ds=a},get historyPresentation(){return Un},set historyPresentation(a){Un=a},get historySessionState(){return ab},get historyVisible(){return un},set historyVisible(a){un=a},get isStreaming(){return no},jumpToBottomInstant:gg,get lastAppliedMessages(){return nd},set lastAppliedMessages(a){nd=a},get launcherEnabled(){return ye},get launcherSurfaceInstance(){return qt},maybeFocusInput:Jc,messageCache:Mn,get messagesWrapper(){return Te},mount:e,get open(){return D},panel:Ae,panelElements:et,get persistentMetadata(){return P},set persistentMetadata(a){P=a},plugins:d,get reapplyHistoryHostChrome(){return dr},set reapplyHistoryHostChrome(a){dr=a},repinAnchoredMessage:na,resetAnchorState:ni,restoreScrollPosition:fg,resumeAutoScroll:Go,runStorageMutation:jc,get session(){return R},setActiveConversationSummary:iM,storageAdapter:T,get suppressScrollSend(){return Xi},set suppressScrollSend(a){Xi=a},syncScrollToBottomButton:Tn,updateWelcome:hl,getHistoryProviderFactory:sx,historyErrors:{HistoryClientError:on,HistoryProviderError:Vr},isDockedMountMode:Lt,renderLucideIcon:ge,loadHistoryView:rx,createHeaderIconButton:_a,attachTooltip:vn},Og=a=>(!Bt&&!ib&&(Bt=a.createHistoryShell(aM),Bt.railCollapseShortcut()&&Wg()),Bt),_g=()=>{if(Bt)return Promise.resolve(Bt);let a=wp();return a?Promise.resolve(Og(a)):(Rg??=rw().then(Og,u=>{throw Rg=null,u}),Rg)},Xo=a=>{let u=wp(),m=Bt??(u?Og(u):null);return m?a(m):_g().then(v=>{if(!v)throw new Error("[AgentWidget] The widget was destroyed");return a(v)})},sd=()=>{Bt?.syncHistoryPresentation()};Se.push(()=>{ib=!0}),yl()&&_g().catch(()=>{}).finally(fe),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&R.initClientSession().then(()=>{let a=Bt;if(a?.historyAvailable())return R.reconcileBootConversation({scope:a.historyScope()})}).then(()=>{Bt?.syncEarlierMessagesPill()}).catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)});let Bg=()=>R.warmClientSession(),db=a=>{let u=o.sessionInit??"input",m=ct?.input??ce,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":(ct?.form??An)?.contains(v)))&&Bg()},pb=["input","pointerdown","keyup"];pb.forEach(a=>e.addEventListener(a,db));let ub,Dg,gb=()=>{let a=Dg;Dg=void 0;try{typeof a=="function"&&a()}catch{}},fb=()=>{let a=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(a!==ub){gb(),ub=a;try{Dg=a?.({warm:Bg,mount:e})}catch{}}};fb(),Se.push(()=>{pb.forEach(a=>e.removeEventListener(a,db)),gb()}),(Me||o.onSSEEvent)&&R.setSSEEventCallback((a,u)=>{o.onSSEEvent?.(a,u),Qa(a,u)});let mb=()=>{let a=o.resume??(_?ds.getStoredResumableHandle?.():null);a&&typeof o.reconnectStream=="function"&&R.resumeFromHandle(a)};J?J.then(a=>{if(a){if(a.metadata&&(P=wh(a.metadata),_e.syncFromMetadata()),a.messages?.length){Xi=!0;try{R.hydrateMessages(a.messages)}finally{Xi=!1}Xc()}a.artifacts?.length&&R.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null),By(a.draft)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>{Sg=!0,U(),mb()}):(By(He),mb());let lM=()=>{!Le()||D||!(o.launcher?.composerBar?.expandOnSubmit??!0)||Mt(!0,"auto")},cM=(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),pH(w)}}:a:u,Ng=()=>{let u=ce.getInlineMessageFields?.();return u&&u.contentSegments.some(v=>v.kind==="mention")?u.contentSegments:void 0},Er=!1,ii=null,id=()=>{ce.value="",ce.style.height="auto",po(),Cl()},aa=null;function ad(a,u=4e3){$s(a),!(Le()||!tt)&&(tt.hasAttribute(Ya)||(tt.setAttribute(yc,""),tt.setAttribute("role","status"),tt.setAttribute("aria-live","polite"),tt.textContent=a,hi(tt,o.statusIndicator??{},"idle"),aa&&clearTimeout(aa),aa=setTimeout(()=>{if(aa=null,!!tt?.hasAttribute(yc)&&(tt.removeAttribute(yc),tt.removeAttribute("role"),tt.removeAttribute("aria-live"),h)){let m=R.getStatus();_s(tt,ur(m),o.statusIndicator??{},m)}},u)))}function dM(){let a=be.getState().pendingSubmission;a&&(qi(void 0),ce&&(ce.value=a.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),po()),a.options.selectedModelId&&(be.setSelectedModelId(a.options.selectedModelId),Zr?.repaint()),a.options.activeModeIds?.length&&Tc(a.options.activeModeIds),a.options.quote&&qo(a.options.quote),ce?.focus())}let pM=a=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",a)},hb=(a={})=>{let u=(a.overrideText??ce?.value??"").trim();return a.resolveInlineCommand&&u?(at?.takeInlineCommand(u)??Promise.resolve(null)).then(m=>yb(a,u,m)):yb(a,u,null)},yb=(a,u,m)=>{if(m?.kind==="action"){id(),at?.clear(),mr();return}let v=m?.kind==="server"?m.mentions:null,w=m?.kind==="prompt"?m.sendText:u,k=a.pending?.contentParts,z=(je?.hasAttachments()??!1)||(k?.length??0)>0;if(!xS({text:w,hasAttachments:z,attachmentsReady:je?.isReady()??!0,hasMentions:at?.hasMentions()??!1,hasServerMentions:!!v,inputDisabled:Yo(),sendDisabled:oi()}))return;let re=R.isStreaming()?Uu():"block";if(re==="defer-one"&&!a.pending){if(be.getState().pendingSubmission){ad("One message is already queued. Edit or remove it first.");return}uM({intent:a,sendText:w,serverMentions:v});return}let Y={text:w,mentionRefs:[...at?.getMentionRefs()??[],...v?.refs??[]],contentSegments:m?.kind==="prompt"?void 0:Ng(),options:{...be.getState().selectedModelId&&{selectedModelId:be.getState().selectedModelId},...be.getState().activeModeIds.length>0&&{activeModeIds:[...be.getState().activeModeIds]},...be.getState().quote&&{quote:{...be.getState().quote}}},viaVoice:a.viaVoice};a.pending&&(Y.options={...a.pending.options},Y.contentSegments=a.pending.contentSegments,Y.mentionRefs=[...a.pending.mentionRefs],Y.viaVoice=a.pending.viaVoice);let ie=()=>{if(k?.length)return[...k];if(!je?.hasAttachments())return;let dt=[...je.getContentParts()];return Y.text&&dt.push(Ao(Y.text)),dt};Y.contentParts=ie();let le=()=>{Xs(),lM();let dt=at?.collectForSubmit()??null,Kn=cM(dt,v),Dt=ie();a.consumeDraft!==!1&&id();let jt={selectedModelId:Y.options.selectedModelId,activeModeIds:Y.options.activeModeIds},_n=re==="interrupt";_n&&R.cancel(),R.sendMessage(Y.text,{contentParts:Dt,mentions:Kn??void 0,contentSegments:Y.contentSegments,viaVoice:Y.viaVoice,composerOptions:jt,...Y.options.quote&&{quote:Y.options.quote},..._n&&{interrupt:!0}}),je?.hasAttachments()&&je.clearAttachments(),dt&&at?.clear(),mr();let Kt=be.getState().activeModeIds,wt=dS(Kt,o.composer?.modes);wt.length!==Kt.length&&Tc(wt),be.getState().quote&&qo(void 0),zc(),Gu.release(),ko()},de=o.composer?.onBeforeSend;if(!de){le();return}let ke=new AbortController;ii=ke;let it=dt=>{if(ii=null,dt.status==="error"){pM(dt.error);return}dt.status==="proceed"&&le()},gt=ES(de,Y,ke.signal);if(!(gt instanceof Promise)){it(gt);return}return be.setPreparing(!0),gt.then(it).finally(()=>be.setPreparing(!1))};function uM(a){let u=be.getState(),m=je?.hasAttachments()??!1,v=m?[...je.getContentParts()]:[];m&&a.sendText&&v.push(Ao(a.sendText));let w=Am({text:a.sendText,contentParts:v.length?v:void 0,mentionRefs:[...at?.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});qi(w),a.intent.consumeDraft!==!1&&id(),m&&je.clearAttachments(),at?.clear(),mr(),u.quote&&qo(void 0),zc(),Gu.release(),ko(),$s("Message queued. It sends when the response finishes.")}function gM(){let a=be.getState().pendingSubmission;a&&(qi(void 0),cd(a.text,{consumeDraft:!1,pending:a}))}function fM(a){if(o.messageActions?.showEdit!==!0)return;let u=R.getMessages().find(m=>m.id===a);!u||!pm(u)||Ys!==a&&(Xs(),Ys=a,os=mS({messageId:a,initialText:u.content,onSave:m=>mM(a,m),onCancel:()=>Xs()}),Mn.delete(a),fo(Te,R.getMessages(),K),os.focus())}function mM(a,u){let m=os;if(Ys=null,os=null,m?.destroy(),Mn.delete(a),!R.resubmitFrom(a,{reason:"edit",replacement:{text:u,mentionRefs:[],options:{}}})){fo(Te,R.getMessages(),K);return}na()}function hM(a){if(R.isStreaming())return;let u=dm(R.getMessages(),a);u&&(Xs(),R.resubmitFrom(u,{reason:"retry"})&&na())}Pc={regenerate:hM,edit:fM,quote:a=>{let m=R.getMessages().find(v=>v.id===a)?.content?.trim();m&&(qo({text:m,messageId:a}),ce?.focus())}};let vl=async a=>{if(!Er){Er=!0;try{await hb({resolveInlineCommand:!0,...a})}finally{Er=!1}}};function ld(a){oi()||(id(),cd(a,{consumeDraft:!1}))}let cd=(a,u)=>{if(Er)return;Er=!0;let m=()=>{Er=!1};try{let v=hb({...u,overrideText:a});v instanceof Promise?v.finally(m):m()}catch(v){throw m(),v}},yM=a=>{if(a.preventDefault(),R.isStreaming()){R.cancel(),bt?.reset(),rn?.update();return}Er||vl()},bM=()=>o.features?.composerHistory!==!1,Fg={...km},$g=!1,Cl=()=>{Fg={...km}},vM=()=>R.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),CM=a=>{if(!ce)return;$g=!0,ce.value=a,ce.dispatchEvent(new Event("input",{bubbles:!0})),$g=!1;let u=ce.value.length;ce.setSelectionRange(u,u)},wM=a=>{$g||(a.isComposing||at?.handleInput(a.inputType??void 0),Cl())},SM=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Bl(ce)}),AM=a=>{if(ce&&!Yo()&&!(!a.isComposing&&at?.handleKeydown(a))){if(bM()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let u=ce.selectionStart===0&&ce.selectionEnd===0,m=NS({direction:a.key==="ArrowUp"?"up":"down",history:vM(),currentValue:ce.value,atStart:u,state:Fg});if(Fg=m.state,m.handled){a.preventDefault(),m.value!==void 0&&CM(m.value);return}}if(BC(a,SM())){if(R.isStreaming()){if(a.preventDefault(),Uu()==="block"||Er||oi())return;Cl(),vl();return}if(Er){a.preventDefault();return}if(oi()){a.preventDefault();return}Cl(),a.preventDefault(),Pe.click()}}},bb=a=>{if(!(a.key!=="Escape"||a.isComposing)&&a.composedPath().includes(we)){if(ii){ii.abort(),ii=null,a.preventDefault(),a.stopImmediatePropagation();return}R.isStreaming()&&(R.cancel(),bt?.reset(),rn?.update(),Cl(),a.preventDefault(),a.stopImmediatePropagation())}},xM=async a=>{if(o.attachments?.enabled!==!0||!je||Yo())return;let u=aH(a.clipboardData);u.length!==0&&(a.preventDefault(),await je.handleFiles(u))},ho=null,Qo=!1,la=null,Mr=null,Ug=()=>o.voiceRecognition?.completionBehavior==="review";function dd(a){he?.setAttribute("data-state",a),a==="recording"?MM():zg()}let vb="--persona-voice-level",Vg=.5,ca=null,jg=-1,pd=0,Cb=()=>{let a=[],u=gn??he?.parentElement??null;return u&&a.push(u),Ke&&a.push(Ke),a},qg=a=>{let u=Math.round(Math.max(0,Math.min(1,a))*100)/100;if(u!==jg){jg=u;for(let m of Cb())m.style.setProperty(vb,String(u))}},EM=()=>{jg=-1,pd=0;for(let a of Cb())a.style.removeProperty(vb)};function MM(){if(ca!==null)return;if(typeof requestAnimationFrame!="function"){qg(h?R.getVoiceLevel()??Vg:Vg);return}let a=()=>{ca=requestAnimationFrame(a);let u=h?R.getVoiceLevel():null;if(u===null){qg(Vg);return}pd+=(u-pd)*.3,qg(pd)};ca=requestAnimationFrame(a)}function zg(){ca!==null&&(cancelAnimationFrame(ca),ca=null),EM()}let wb=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ud=(a="user")=>{if(Qo||R.isStreaming())return;let u=wb();if(!u)return;ho=new u;let m=o.voiceRecognition??{},v=m.pauseDuration??2e3;ho.continuous=m.provider?.browser?.continuous??!0,ho.interimResults=!0,ho.lang=m.provider?.browser?.language??"en-US";let w=ce.value;ho.onresult=k=>{let z="",re="";for(let ie=0;ie<k.results.length;ie++){let le=k.results[ie],de=le[0].transcript;le.isFinal?z+=de+" ":re=de}let Y=w+z+re;ce.value=Y,po(),la&&clearTimeout(la),(z||re)&&(la=window.setTimeout(()=>{if(ce.value.trim()&&ho&&Qo){if(ps(),Ug())return;vl({viaVoice:!0})}},v))},ho.onerror=k=>{k.error!=="no-speech"&&ps()},ho.onend=()=>{if(Qo){let k=ce.value.trim();!Ug()&&k&&k!==w.trim()&&vl({viaVoice:!0}),ps()}};try{if(ho.start(),Qo=!0,Ge.active=!0,a!=="system"&&(Ge.manuallyDeactivated=!1),Sr(a),zn(),ko(),he){let k=o.voiceRecognition??{};Mr={backgroundColor:he.style.backgroundColor,color:he.style.color,borderColor:he.style.borderColor,iconName:k.iconName??"mic",iconSize:parseFloat(k.iconSize??"")||Qn};let z=k.recordingBackgroundColor,re=k.recordingIconColor,Y=k.recordingBorderColor;if(he.classList.add("persona-voice-recording"),dd("recording"),he.style.backgroundColor=z??"var(--persona-voice-recording-bg, #ef4444)",he.style.color=re??"var(--persona-voice-recording-indicator, #ffffff)",re){let ie=he.querySelector("svg");ie&&ie.setAttribute("stroke",re)}Y&&(he.style.borderColor=Y),he.setAttribute("aria-label","Stop voice recognition")}}catch{ps("system")}},ps=(a="user")=>{if(Qo){if(Qo=!1,la&&(clearTimeout(la),la=null),ho){try{ho.stop()}catch{}ho=null}if(Ge.active=!1,Sr(a),zn(),ko(),he){if(he.classList.remove("persona-voice-recording"),dd("idle"),Mr){he.style.backgroundColor=Mr.backgroundColor,he.style.color=Mr.color,he.style.borderColor=Mr.borderColor;let u=he.querySelector("svg");u&&u.setAttribute("stroke",Mr.color||"currentColor"),Mr=null}he.setAttribute("aria-label","Start voice recognition")}}},Sb=null,gd=a=>{let u=v=>{Sb??=v.createMicStateStyles({mic:()=>he,config:()=>o,session:()=>R,get original(){return Mr},set original(w){Mr=w},setMicState:dd,renderIcon:ge,iconFallbackPx:Qn}),a(Sb)},m=_w();m?u(m):zl().then(u,()=>{})},da=()=>gd(a=>a.recording()),TM=()=>gd(a=>a.processing()),PM=()=>gd(a=>a.speaking()),Tr=()=>gd(a=>a.reset()),Kg=()=>{if(!Yo()){if(In(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(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,zn(),Sr("user"),Tr()});return}R.toggleVoice().then(()=>{Ge.active=lg(),Ge.manuallyDeactivated=!Ge.active,zn(),Sr("user"),Ge.active?da():Tr()});return}if(Qo){let a=ce.value.trim();Ge.manuallyDeactivated=!0,zn(),ps("user"),a&&!Ug()&&vl()}else Ge.manuallyDeactivated=!1,zn(),ud("user")}};Vu=Kg;let Ab=()=>R.prewarmVoice(),xb=()=>{let a=o.voiceRecognition;return a?.enabled!==!0?!1:a.prewarm??(o.clientToken?"hover":!1)},Eb=a=>{xb()==="hover"&&he?.contains(a.target)&&Ab()},Mb=["pointerover","pointerdown","focusin"];Mb.forEach(a=>e.addEventListener(a,Eb));let Tb,Pb=null,Gg,kb=()=>{let a=Gg;Gg=void 0;try{typeof a=="function"&&a()}catch{}},Yg=()=>{let a=xb(),u=typeof a=="function"&&he?a:void 0,m=u?he:null;if(!(u===Tb&&m===Pb)&&(kb(),Tb=u,Pb=m,!(!u||!m)))try{Gg=u({warm:Ab,micButton:m,mount:e})}catch{}};Yg(),Se.push(()=>{Mb.forEach(a=>e.removeEventListener(a,Eb)),kb()}),he&&Se.push(()=>{In(o.voiceRecognition?.provider)?(R.isVoiceActive()&&R.toggleVoice(),Tr()):ps("system")});let kM=X.on("assistant:complete",()=>{be.getState().pendingSubmission&&setTimeout(()=>{R.isStreaming()||gM()},0)});Se.push(kM);let LM=X.on("assistant:complete",()=>{Iy&&(Ge.active||Ge.manuallyDeactivated||Iy==="assistant"&&!Ge.lastUserMessageWasVoice||setTimeout(()=>{!Ge.active&&!Ge.manuallyDeactivated&&(In(o.voiceRecognition?.provider)?R.toggleVoice().then(()=>{Ge.active=R.isVoiceActive(),Sr("auto"),R.isVoiceActive()&&da()}):ud("auto"))},600))});Se.push(LM);let HM=X.on("action:resubmit",()=>{setTimeout(()=>{R&&!R.isStreaming()&&R.continueConversation()},100)});Se.push(HM);let Lb=()=>{Mt(!D,"user")},qt=null,On=null;if(ye&&!Le()){let{instance:a,element:u}=nh({config:o,plugins:d,onToggle:Lb});qt=a,a||(On=u)}qt?e.appendChild(qt.element):On&&e.appendChild(On),fl(),Ks(),ed(),Tg(),ml(R.isStreaming()),fg()||(En()==="follow"?as(!0):gg()),PE(),Zt&&(!ye||Le()?setTimeout(()=>Jc(),0):D&&setTimeout(()=>Jc(),200));let us=null,Hb=()=>{us&&(us.disconnect(),us.observe(Ke),us.observe(we),us.observe(en))},Ib=jn(),wl=()=>{if(Le()){Re(),fl();return}let a=Lt(o),u=o.launcher?.sidebarMode??!1,m=e.ownerDocument.defaultView??window,v=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640,k=m.innerWidth<=w,z=v&&k&&ye;try{if(z){Us(),rl=Bc();return}let re=!1;vt&&(vt=!1,Us(),re=!0);let Y=Bc();if(!re&&Y!==rl&&(Us(),re=!0),rl=Y,re&&Rc(),!ye&&!a){Ae.style.height="",Ae.style.width="";return}if(!u&&!a){let ie=Hi(o);Ae.style.width=ie.width,Ae.style.maxWidth=ie.maxWidth}_c(),hy()}finally{Re(),Ot();let re=jn();if(re!==Ib&&(Ib=re,hl(),Ks()),fl(),D&&ye){let ie=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),le=o.launcher?.sidebarMode??!1,de=o.launcher?.mobileFullscreen??!0,ke=Lt(o)&&de&&ie,it=le||de&&ie&&ye||ke;if(it&&!Ko){let gt=e.getRootNode(),dt=gt instanceof ShadowRoot?gt.host:e.closest(".persona-host");dt&&!zo&&(zo=Rm(dt,o.launcher?.zIndex??kn)),Ko=Wm(e.ownerDocument)}else it||(zo?.(),zo=null,Ko?.(),Ko=null)}}};wl();let fd=e.ownerDocument.defaultView??window;if(fd.addEventListener("resize",wl),Se.push(()=>fd.removeEventListener("resize",wl)),typeof ResizeObserver<"u"){us=new ResizeObserver(()=>{Ot()}),Hb(),Se.push(()=>{us?.disconnect(),us=null});let a=new ResizeObserver(()=>{sd()});a.observe(we),Se.push(()=>a.disconnect())}fd.addEventListener("resize",sd),Se.push(()=>fd.removeEventListener("resize",sd)),ro=ae.scrollTop;let Rb=ir(ae),Wb=()=>{my();let a=ae.scrollTop,u=ir(ae),m=u<Rb;if(Rb=u,!Mo()){ro=a,Tn();return}let{action:v,nextLastScrollTop:w}=KS({following:oo.isFollowing(),currentScrollTop:a,lastScrollTop:ro,nearBottom:Mi(ae,Cr),userScrollThreshold:xE,isAutoScrolling:qn||Nc||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ro=w,v==="resume"){Kc()||Go();return}v==="pause"&&ta()};if(ae.addEventListener("scroll",Wb,{passive:!0}),Se.push(()=>ae.removeEventListener("scroll",Wb)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{OE(),im(Te)});a.observe(Te),a.observe(ae),Se.push(()=>a.disconnect())}let Ob=()=>{Mo()&&oo.isFollowing()&&Kc()&&ta()},_b=ae.ownerDocument;_b.addEventListener("selectionchange",Ob),Se.push(()=>{_b.removeEventListener("selectionchange",Ob)});let IM=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Bb=a=>{IM.has(a.key)&&(is(),Ja()&&Mo()&&oo.isFollowing()&&ta())},Db=a=>{a.target?.closest("a, button, [tabindex], input, textarea, select")&&(is(),Ja()&&Mo()&&oo.isFollowing()&&ta())};ae.addEventListener("keydown",Bb),ae.addEventListener("focusin",Db),Se.push(()=>{ae.removeEventListener("keydown",Bb),ae.removeEventListener("focusin",Db)});let Nb=a=>{if(a.deltaY!==0&&is(),!Mo())return;let u=GS({following:oo.isFollowing(),deltaY:a.deltaY,nearBottom:Mi(ae,Cr),resumeWhenNearBottom:!0});u==="pause"?ta():u==="resume"&&!Kc()&&Go()};ae.addEventListener("wheel",Nb,{passive:!0}),ae.addEventListener("touchmove",is,{passive:!0}),ae.addEventListener("pointerdown",is,{passive:!0}),Se.push(()=>{ae.removeEventListener("touchmove",is),ae.removeEventListener("pointerdown",is)}),Se.push(()=>ae.removeEventListener("wheel",Nb)),Vt.addEventListener("click",()=>{ni(),ae.scrollTop=ae.scrollHeight,ro=ae.scrollTop,Go(),as(!0),Tn()}),Se.push(()=>Vt.remove()),Se.push(()=>{Ny(),ni()});let Fb=()=>{ze&&(qs&&(ze.removeEventListener("click",qs),qs=null),Xe()?(ze.style.display="",qs=()=>{Mt(!1,"user")},ze.addEventListener("click",qs)):ze.style.display="none")};Fb(),(()=>{let{clearChatButton:a}=et;a&&a.addEventListener("click",()=>{let u=Bt;if(u?.historyAvailable()){u.startNewConversation({focusComposer:!0}).catch(v=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",v)});return}R.clearMessages(),o.layout?.topFade&&(ae.scrollTop=0),ae.removeAttribute("data-persona-top-fade"),Mn.clear(),Go(),Wr(et.composerOverlay);try{localStorage.removeItem(Ga),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ga}`)}catch(v){console.error("[AgentWidget] Failed to clear default localStorage:",v)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ga)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&&jc(()=>T.clear(),"[AgentWidget] Failed to clear storage adapter:"),P={},_e.syncFromMetadata(),je?.clearAttachments(),zc(),qi(void 0),qo(void 0),Xs(),ft?.clear(),bt?.reset(),rn?.update()})})();let $b=[["keydown",AM],["input",wM],["input",po],["input",mr],["keyup",mr],["paste",xM],["focus",uE]],Ub=a=>{if(a)for(let[u,m]of $b)ct?.addListener(a,u,m)},RM=a=>{if(a)for(let[u,m]of $b)ct?.removeListener(a,u,m)},Vb=()=>{ct&&(ct.addListener(ct.form,"submit",yM),ct.addListener(ct.footer,"click",mr),Ub(ce),he&&ct.addListener(he,"click",Kg),Yg())};Vb();let jb=()=>{at?.onComposerSwap((a,u)=>{RM(u),ce=a,ct&&(ct.input=a),Ub(a),qu(),vg(),po()})};jb();let Xg=!1;function qb(){if(!Xg){Xg=!0;try{let a=ce?.value??"",u=Ke.ownerDocument??document,m=ce?u.activeElement===ce:!1;zg(),ct?.destroy(),ct=null,at?.destroy(),at=null;let v=null,w=()=>(v=Le()?nu({config:o}):ki({config:o}),v.footer),k=Gh(w)??w();Ln.replaceComposer(k),Ke=Ln.composer.footer;let z=v!==null&&k===v.footer;Ki=!z,xc=z?v.setSendButtonMode:()=>{},Kh(Ke),Xh(Ke),Qh(),Jh(),zu(),jb(),Zh(),Ku(),ey(),Vb();let re=js.indexOf(vr);if(vr.destroy(),vr=ac(co),re>=0&&(js[re]=vr),ce&&(ce.value=a),po(),mr(),ed(),Ks(),ml(R.isStreaming()),o.statusIndicator?.mode==="transient"&&!Le()){let Y=R.getStatus();_s(tt,ur(Y),o.statusIndicator,Y)}Ge.active&&dd("recording"),Us(),Hb(),Re(),ko(),Qc(),m&&ce?.focus()}finally{Xg=!1}}}let Sl=e.ownerDocument??document;Sl.addEventListener("keydown",bb,!0);let zb=()=>{cg()},Kb=()=>{Sl.visibilityState==="hidden"&&cg()};typeof window<"u"&&(window.addEventListener("pagehide",zb),Sl.addEventListener("visibilitychange",Kb),Se.push(()=>{window.removeEventListener("pagehide",zb),Sl.removeEventListener("visibilitychange",Kb)}));let Gb="persona-attachment-drop-active",Al=0,Qg=()=>{Al=0,we.classList.remove(Gb)},pa=()=>o.attachments?.enabled===!0&&je!==null&&!Yo(),Yb=a=>{!bu(a.dataTransfer)||!pa()||(Al++,Al===1&&we.classList.add(Gb))},Xb=a=>{!bu(a.dataTransfer)||!pa()||(Al--,Al<=0&&Qg())},Qb=a=>{!bu(a.dataTransfer)||!pa()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},Jb=a=>{if(!bu(a.dataTransfer)||!pa())return;a.preventDefault(),a.stopPropagation(),Qg();let u=Array.from(a.dataTransfer.files??[]);u.length!==0&&je.handleFiles(u)},gs=!0;we.addEventListener("dragenter",Yb,gs),we.addEventListener("dragleave",Xb,gs),e.addEventListener("dragover",Qb,gs),e.addEventListener("drop",Jb,gs);let md=e.ownerDocument,Zb=a=>{pa()&&a.preventDefault()},ev=a=>{pa()&&a.preventDefault()};md.addEventListener("dragover",Zb),md.addEventListener("drop",ev),Se.push(()=>{ct?.destroy(),ct=null,zg(),Po?.destroy(),Po=null,hr?.destroy(),hr=null,es?.destroy(),es=null,ts?.destroy(),ts=null,Zr=null,$u=null,cg(),cl.destroy(),aa&&clearTimeout(aa),Xs(),ii?.abort(),ii=null,je?.destroy(),je=null,be.destroy(),Sl.removeEventListener("keydown",bb,!0),at?.destroy()}),Se.push(()=>{we.removeEventListener("dragenter",Yb,gs),we.removeEventListener("dragleave",Xb,gs),e.removeEventListener("dragover",Qb,gs),e.removeEventListener("drop",Jb,gs),md.removeEventListener("dragover",Zb),md.removeEventListener("drop",ev),Qg()}),Se.push(()=>{R.cancel()}),qt?Se.push(()=>{qt?.destroy()}):On&&Se.push(()=>{On?.remove()});let zt={update(a){let u=o.future?.v5Defaults===!0,m=o.toolCall,v=o.messageActions,w=o.layout?.messages,k=o.colorScheme,z=o.loadingIndicator,re=o.iterationDisplay,Y=o.features?.showReasoning,ie=o.features?.showToolCalls,le=o.features?.toolCallDisplay,de=o.features?.reasoningDisplay,ke=o.features?.streamAnimation?.type,it=o.features?.history?.enabled===!0,gt=o.features?.history?.provider,dt=o.getIdentityProof,Kn=o.clientToken,Dt=o.contextMentions;o=pu({...o,features:p},a),p=o.features,o=uc(o),c(),eg(),Ei(e,o),dc(e,o),pc(e,o),Vn(),Ho(),o.colorScheme!==k&&yy();let jt=gc.getForInstance(o.plugins);d.length=0,d.push(...jt),Wg(),ye=o.launcher?.enabled??!0,ut=o.launcher?.autoExpand??!1,te=o.features?.showReasoning??!0,ve=o.features?.showToolCalls??!0,Ce=o.features?.scrollToBottom??{};let _n=En();st=o.features?.scrollBehavior??{},_n!==En()&&(ni(),Go()),Hy(),_t(),Tn();let Kt=Me;if(Me=o.features?.showEventStreamToggle??!1,Me&&!Kt){if(ft||(cr(),R.setSSEEventCallback((Z,ot)=>{o.onSSEEvent?.(Z,ot),Qa(Z,ot)})),!ht&&mt){let Z=o.features?.eventStream?.classNames,ot="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"+(Z?.toggleButton?" "+Z.toggleButton:"");ht=x("button",ot),ht.style.width="28px",ht.style.height="28px",ht.style.color=Nn.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let rt=Nt(Kr.Activity,"18px","currentColor",1.5);rt&&ht.appendChild(rt);let pt=et.clearChatButtonWrapper,Rt=et.closeButtonWrapper,Pn=pt||Rt;Pn&&Pn.parentNode===mt?mt.insertBefore(ht,Pn):mt.appendChild(ht),ht.addEventListener("click",()=>{Sn?zi():ju()})}}else!Me&&Kt&&(zi(),ht&&(ht.remove(),ht=null),ft?.clear(),pn?.destroy(),ft=null,pn=null,bt?.reset(),bt=null,Ft=null);if(o.launcher?.enabled===!1&&qt&&(qt.destroy(),qt=null),o.launcher?.enabled===!1&&On&&(On.remove(),On=null),o.launcher?.enabled!==!1&&!qt&&!On){let{instance:Z,element:ot}=nh({config:o,plugins:d,onToggle:Lb});qt=Z,Z||(On=ot),e.appendChild(ot)}qt&&qt.update(o),bl(),jo&&o.launcher?.subtitle!==void 0&&(jo.textContent=o.launcher.subtitle);let wt=o.layout?.header;if(wt?.layout!==Wt&&mt){let Z=wt?Na(o,wt,{showClose:Xe(),onClose:()=>Mt(!1,"user")}):jr({config:o,showClose:Xe(),onClose:()=>Mt(!1,"user")});Ln.replaceHeader(Z),mt=Ln.header.element,Ht=Ln.header.iconHolder,Vo=Ln.header.headerTitle,jo=Ln.header.headerSubtitle,ze=Ln.header.closeButton,Wt=wt?.layout,bl()}else if(wt){if(Ht&&(Ht.style.display=wt.showIcon===!1?"none":""),Vo&&(Vo.style.display=wt.showTitle===!1?"none":""),jo&&(jo.style.display=wt.showSubtitle===!1?"none":""),ze){let Z=Xe()&&wt.showCloseButton!==!1;ze.style.display=Z?"":"none"}if(et.clearChatButtonWrapper){let Z=wt.showClearChat;if(Z!==void 0){et.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:ot}=et;ot&&!ot.classList.contains("persona-absolute")&&(Z?ot.classList.remove("persona-ml-auto"):ot.classList.add("persona-ml-auto"))}}}let Zo=o.layout?.showHeader!==!1;mt&&(mt.style.display=Zo?"":"none");let bo=o.layout?.showFooter!==!1;Ke&&(Ke.style.display=bo?"":"none"),Re(),Tn(),ye!==xe?ye?Mt(ut,"auto"):(D=!0,fl()):ut!==xt&&Mt(ut,"auto"),xt=ut,xe=ye,wl(),Fb();let er=JSON.stringify(o.toolCall)!==JSON.stringify(m),Io=JSON.stringify(o.messageActions)!==JSON.stringify(v),ms=JSON.stringify(o.layout?.messages)!==JSON.stringify(w),xl=o.loadingIndicator?.render!==z?.render||o.loadingIndicator?.renderIdle!==z?.renderIdle||o.loadingIndicator?.showBubble!==z?.showBubble,ai=o.iterationDisplay!==re,O=(o.features?.showReasoning??!0)!==(Y??!0)||(o.features?.showToolCalls??!0)!==(ie??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(le)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(de);(o.future?.v5Defaults===!0!==u||er||Io||ms||xl||ai||O)&&R&&(Qs++,fo(Te,R.getMessages(),K));let Fe=o.features?.streamAnimation?.type;if(Fe!==ke&&Fe&&Fe!=="none"){let Z=og(Fe,o.features?.streamAnimation?.plugins);Z&&rc(Z,e)}let se=o.launcher??{},St=se.headerIconHidden??!1,Jt=o.layout?.header?.showIcon,Hn=St||Jt===!1,mn=se.headerIconName,Tt=se.headerIconSize??_l;if(Ht){let Z=mt,ot=Z?.querySelector(".persona-flex-col");if(Hn)Ht.style.display="none",Z&&ot&&!Z.contains(ot)&&Z.insertBefore(ot,Z.firstChild);else{if(Ht.style.display="",Ht.style.height=Tt,Ht.style.width=Tt,Z&&ot&&(Z.contains(Ht)?Ht.nextSibling!==ot&&(Ht.remove(),Z.insertBefore(Ht,ot)):Z.insertBefore(Ht,ot)),mn){let pt=parseFloat(Tt)||24,Rt=ge(mn,pt*.6,"currentColor",1);Rt?(Rt.style.width=`calc(${pt}px * var(--persona-components-header-iconScale, 0.6))`,Rt.style.height=`calc(${pt}px * var(--persona-components-header-iconScale, 0.6))`,Ht.replaceChildren(Rt)):Ht.textContent=se.agentIconText??"\u{1F4AC}"}else if(se.iconUrl){let pt=Ht.querySelector("img");if(pt)pt.src=se.iconUrl,pt.style.height=Tt,pt.style.width=Tt;else{let Rt=document.createElement("img");Rt.src=se.iconUrl,Rt.alt="",Rt.className="persona-rounded-xl persona-object-cover",Rt.style.height=Tt,Rt.style.width=Tt,Ht.replaceChildren(Rt)}}else{let pt=Ht.querySelector("svg"),Rt=Ht.querySelector("img");(pt||Rt)&&Ht.replaceChildren(),Ht.textContent=se.agentIconText??"\u{1F4AC}"}let rt=Ht.querySelector("img");rt&&(rt.style.height=Tt,rt.style.width=Tt)}}let Gt=o.layout?.header?.showTitle,ln=o.layout?.header?.showSubtitle;if(Vo&&(Vo.style.display=Gt===!1?"none":""),jo&&(jo.style.display=ln===!1?"none":""),ze){let Z=Xe()&&o.layout?.header?.showCloseButton!==!1;if(ze.style.display=Z?"":"none",!Le()){let yn=se.closeButtonSize??"";ze.style.height=yn,ze.style.width=yn,ze.style.minWidth=yn,ze.style.minHeight=yn}let ot=se.closeButtonPlacement??"inline",{closeButtonWrapper:rt}=et,pt=ot==="top-right",Rt=rt?.classList.contains("persona-absolute");if(rt&&pt!==Rt)if(rt.remove(),pt){rt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let yn=Bt?.railColumn??we;yn.style.position="relative",yn.appendChild(rt)}else{let yn=se.clearChat?.placement??"inline",bn=se.clearChat?.enabled??!0;rt.className=bn&&yn==="inline"?"":"persona-ml-auto",mt&&mt.appendChild(rt)}if(ze.style.color=se.closeButtonColor||Nn.actionIconColor,se.closeButtonBackgroundColor?(ze.style.backgroundColor=se.closeButtonBackgroundColor,ze.classList.remove("hover:persona-bg-gray-100")):(ze.style.backgroundColor="",ze.classList.add("hover:persona-bg-gray-100")),se.closeButtonBorderWidth||se.closeButtonBorderColor){let yn=se.closeButtonBorderWidth||"0px",bn=se.closeButtonBorderColor||"transparent";ze.style.border=`${yn} solid ${bn}`,ze.classList.remove("persona-border-none")}else ze.style.border="",ze.classList.add("persona-border-none");se.closeButtonBorderRadius?(ze.style.borderRadius=se.closeButtonBorderRadius,ze.classList.remove("persona-rounded-full")):(ze.style.borderRadius="",ze.classList.add("persona-rounded-full")),se.closeButtonPaddingX?(ze.style.paddingLeft=se.closeButtonPaddingX,ze.style.paddingRight=se.closeButtonPaddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),se.closeButtonPaddingY?(ze.style.paddingTop=se.closeButtonPaddingY,ze.style.paddingBottom=se.closeButtonPaddingY):(ze.style.paddingTop="",ze.style.paddingBottom=""),Jp(ze,se.closeButtonIconName??"x",{iconSize:Le()?Jm:void 0,iconText:se.closeButtonIconText??"\xD7"});let Pn=se.closeButtonTooltipText??"Close chat",Wo=se.closeButtonShowTooltip??!0;ze.setAttribute("aria-label",Pn),rt&&vn({anchor:ze,trigger:rt,text:()=>ze?.getAttribute("aria-label")??Pn,enabled:Wo})}let{clearChatButton:We,clearChatButtonWrapper:Pt}=et;if(We){let Z=se.clearChat??{},ot=Z.enabled??!0,rt=o.layout?.header?.showClearChat,pt=rt!==void 0?rt:ot,Rt=Z.placement??"inline";if(Pt){Pt.style.display=pt?"":"none";let{closeButtonWrapper:Pn}=et;!Le()&&Pn&&!Pn.classList.contains("persona-absolute")&&(pt?Pn.classList.remove("persona-ml-auto"):Pn.classList.add("persona-ml-auto"));let Wo=Rt==="top-right",yn=Pt.classList.contains("persona-absolute");if(!Le()&&Wo!==yn&&pt){if(Pt.remove(),Wo){Pt.className="persona-absolute persona-top-4 persona-z-50",Pt.style.right="48px";let tr=Bt?.railColumn??we;tr.style.position="relative",tr.appendChild(Pt)}else{Pt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Pt.style.right="";let tr=et.closeButtonWrapper;mt&&tr&&tr.parentElement===mt?mt.insertBefore(Pt,tr):mt&&mt.appendChild(Pt)}let bn=et.closeButtonWrapper;bn&&!bn.classList.contains("persona-absolute")&&(Wo?bn.classList.add("persona-ml-auto"):bn.classList.remove("persona-ml-auto"))}}if(pt){if(!Le()){let bn=Z.size??"";We.style.height=bn,We.style.width=bn,We.style.minWidth=bn,We.style.minHeight=bn}let Pn=Z.iconColor??"";if(We.style.color=Pn||Nn.actionIconColor,Jp(We,Z.iconName??"refresh-cw",{iconSize:Le()?Zm:void 0}),Z.backgroundColor?(We.style.backgroundColor=Z.backgroundColor,We.classList.remove("hover:persona-bg-gray-100")):(We.style.backgroundColor="",We.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let bn=Z.borderWidth||"0px",tr=Z.borderColor||"transparent";We.style.border=`${bn} solid ${tr}`,We.classList.remove("persona-border-none")}else We.style.border="",We.classList.add("persona-border-none");Z.borderRadius?(We.style.borderRadius=Z.borderRadius,We.classList.remove("persona-rounded-full")):(We.style.borderRadius="",We.classList.add("persona-rounded-full")),Z.paddingX?(We.style.paddingLeft=Z.paddingX,We.style.paddingRight=Z.paddingX):(We.style.paddingLeft="",We.style.paddingRight=""),Z.paddingY?(We.style.paddingTop=Z.paddingY,We.style.paddingBottom=Z.paddingY):(We.style.paddingTop="",We.style.paddingBottom="");let Wo=Z.tooltipText??"Clear chat",yn=Z.showTooltip??!0;We.setAttribute("aria-label",Wo),Pt&&vn({anchor:We,trigger:Pt,text:()=>We?.getAttribute("aria-label")??Wo,enabled:yn})}}let $e=o.actionParsers&&o.actionParsers.length?o.actionParsers:[fc],cn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Wi.message,Wi.messageAndClick];_e=mc({parsers:$e,handlers:cn,getSessionMetadata:yt,updateSessionMetadata:qe,emit:X.emit,documentRef:typeof document<"u"?document:null}),K=dx(o,_e,q),eM(),R.updateConfig(o),fb(),(o.features?.history?.enabled===!0!==it||o.features?.history?.provider!==gt||o.getIdentityProof!==dt||o.clientToken!==Kn)&&(Bt?.closeHistory({restoreFocus:!1}),Bt?.installHistoryProvider()),Bt?.syncHistoryChromeImpl(),sd(),yl()&&!Bt&&_g().catch(()=>{}),fo(Te,R.getMessages(),K),Ks(),ed(),QE(),ml(R.isStreaming()),Dt!==o.contextMentions&&qb();let Co=o.voiceRecognition?.enabled===!0,hn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),At=In(o.voiceRecognition?.provider);if(Co&&(hn||At))if(!he||!gn){let Z=ka(o);if(Z){he=Z.button,gn=Z.wrapper;let ot=Wn&&Wn.parentElement===Bs?Wn:null;Bs?Bs.insertBefore(gn,ot):An?.appendChild(gn),ct&&(ct.micButton=he),ct?.addListener(he,"click",Kg),he.disabled=Yo()||R.isStreaming()&&!yg()}}else{let Z=o.voiceRecognition??{},ot=o.sendButton??{},rt=Z.iconName??"mic",pt=Z.iconSize,Rt=parseFloat(pt??"")||Qn;he.classList.add(so),he.classList.toggle(Do,!pt),he.style.width=pt??"",he.style.height=pt??"",he.style.minWidth=pt??"",he.style.minHeight=pt??"";let Pn=Z.iconColor??ot.textColor;he.innerHTML="";let Wo=ge(rt,Rt,Pn||"currentColor",1.5);Wo?he.appendChild(Wo):he.textContent="\u{1F3A4}";let yn=Z.backgroundColor??ot.backgroundColor;yn?he.style.backgroundColor=yn:he.style.backgroundColor="",Pn?he.style.color=Pn:he.style.color="var(--persona-text, #111827)",Z.borderWidth?(he.style.borderWidth=Z.borderWidth,he.style.borderStyle="solid"):(he.style.borderWidth="",he.style.borderStyle=""),Z.borderColor?he.style.borderColor=Z.borderColor:he.style.borderColor="",Z.paddingX?(he.style.paddingLeft=Z.paddingX,he.style.paddingRight=Z.paddingX):(he.style.paddingLeft="",he.style.paddingRight=""),Z.paddingY?(he.style.paddingTop=Z.paddingY,he.style.paddingBottom=Z.paddingY):(he.style.paddingTop="",he.style.paddingBottom="");let bn=Z.tooltipText??"Start voice recognition",tr=Z.showTooltip??!1;he.setAttribute("aria-label",bn),gn&&vn({anchor:he,trigger:gn,text:()=>he?.getAttribute("aria-label")??bn,enabled:tr}),gn.style.display="",he.disabled=Yo()||R.isStreaming()&&!yg()}else he&&gn&&(gn.style.display="none",In(o.voiceRecognition?.provider)?R.isVoiceActive()&&R.toggleVoice():Qo&&ps());if(Yg(),o.attachments?.enabled===!0){if(!sn||!It){let Z=o.attachments??{};fn||(fn=x("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),fn.style.display="none",(ce.parentElement??An).insertBefore(fn,ce)),Et||(Et=document.createElement("input"),Et.type="file",Et.accept=(Z.allowedTypes??Dr).join(","),Et.multiple=(Z.maxFiles??4)>1,Et.style.display="none",Et.setAttribute("aria-label","Attach files"),(ce.parentElement??An).insertBefore(Et,ce)),sn=x("div","persona-send-button-wrapper"),It=x("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${so} ${Do}`),It.type="button",It.setAttribute("aria-label",Z.buttonTooltipText??"Attach file");let ot=Z.buttonIconName??"paperclip";It.style.fontSize="18px",It.style.lineHeight="1";let rt=ge(ot,Qn,"currentColor",1.5);rt?It.appendChild(rt):It.textContent="\u{1F4CE}",It.addEventListener("click",Rt=>{Rt.preventDefault(),Et?.click()}),sn.appendChild(It);let pt=Z.buttonTooltipText??"Attach file";vn({anchor:It,trigger:sn,text:()=>It?.getAttribute("aria-label")??pt}),xn?xn.append(sn):An.appendChild(sn),ct&&(ct.attachmentButton=It,ct.attachmentInput=Et??void 0,ct.attachmentPreviews=fn??void 0),!je&&Et&&fn&&(je=Ai.fromConfig(Z,Uh),je.setPreviewsContainer(fn),ct?.addListener(Et,"change",async()=>{je&&Et?.files&&(await je.handleFileSelect(Et.files),Et.value="")}))}else{sn.style.display="";let Z=o.attachments??{};Et&&(Et.accept=(Z.allowedTypes??Dr).join(","),Et.multiple=(Z.maxFiles??4)>1),je&&je.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles,adapter:Z.adapter})}if(we.querySelector(".persona-attachment-drop-overlay")?.remove(),we.appendChild(px(o.attachments?.dropOverlay)),It){let Z=o.attachments??{},ot=Z.buttonTooltipText??"Attach file";It.setAttribute("aria-label",ot),It.textContent="";let rt=ge(Z.buttonIconName??"paperclip",Qn,"currentColor",1.5);rt?It.appendChild(rt):It.textContent="\u{1F4CE}",sn&&vn({anchor:It,trigger:sn,text:()=>It?.getAttribute("aria-label")??ot})}}else sn&&(sn.style.display="none"),je&&je.clearAttachments(),we.querySelector(".persona-attachment-drop-overlay")?.remove();let Ue=o.sendButton??{},hs=Ue.useIcon??!1,nn=Ue.iconText??"\u2191",Gn=Ue.iconName,Pr=Ue.tooltipText??"Send message",Jg=Ue.showTooltip??!1,li=Ue.size,Zg=parseFloat(li??"")||$f,kr=Ue.backgroundColor,ci=Ue.textColor;if(hs){if(Pe.style.width=li??"",Pe.style.height=li??"",Pe.style.minWidth=li??"",Pe.style.minHeight=li??"",Pe.style.fontSize="18px",Pe.style.lineHeight="1",ci?Pe.style.color=ci:Pe.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!R.isStreaming())if(Pe.innerHTML="",Gn){let Z=parseFloat(Ue.iconSize??"")||Math.round(Zg*.5),ot=ci?.trim()||"currentColor",rt=Ue.iconStrokeWidth??2,pt=ge(Gn,Z,ot,rt),Rt=ge(Ue.stopIconName??"square",Z,ot,rt);pt&&Rt?Pe.appendChild(Uf(pt,Rt)):pt?Pe.appendChild(pt):Pe.textContent=nn}else Pe.textContent=nn;Pe.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${so}`,kr?(Pe.style.backgroundColor=kr,Pe.classList.remove("persona-bg-persona-primary")):(Pe.style.backgroundColor="",Pe.classList.add("persona-bg-persona-primary"))}else Pe.textContent=o.copy?.sendButtonLabel??"Send",Pe.style.width="",Pe.style.height="",Pe.style.minWidth="",Pe.style.minHeight="",Pe.style.fontSize="",Pe.style.lineHeight="",Pe.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",kr?(Pe.style.backgroundColor=kr,Pe.classList.remove("persona-bg-persona-accent")):Pe.classList.add("persona-bg-persona-accent"),ci?Pe.style.color=ci:Pe.classList.add("persona-text-white");Ue.borderWidth?(Pe.style.borderWidth=Ue.borderWidth,Pe.style.borderStyle="solid"):(Pe.style.borderWidth="",Pe.style.borderStyle=""),Ue.borderColor?Pe.style.borderColor=Ue.borderColor:Pe.style.borderColor="",Ue.paddingX?(Pe.style.paddingLeft=Ue.paddingX,Pe.style.paddingRight=Ue.paddingX):(Pe.style.paddingLeft="",Pe.style.paddingRight=""),Ue.paddingY?(Pe.style.paddingTop=Ue.paddingY,Pe.style.paddingBottom=Ue.paddingY):(Pe.style.paddingTop="",Pe.style.paddingBottom=""),R.isStreaming()||Pe.setAttribute("aria-label",Pr),Qc(),Wn&&vn({anchor:Pe,trigger:Wn,text:()=>Pe.getAttribute("aria-label")??Pr,enabled:Jg}),ty(),ng();let tv=Dp(be.getState().activeModeIds,o.composer?.modes);be.setActiveModeIds(tv),Vi().length>0!==!!hr&&Ku(),hr?.render(tv,Vi());for(let Z of[...ji.keys()])Bp(Z,o.composer?.modeGroups)||ji.delete(Z);ji.forEach(Z=>Z.repaint()),Zr?.repaint(),Po?.resolve();let hd=Hs(o,Le());if(tg(),hd){Te.style.maxWidth=hd,Te.style.marginLeft="auto",Te.style.marginRight="auto",Te.style.width="100%",Rn.style.maxWidth=hd,Rn.style.marginLeft="auto",Rn.style.marginRight="auto",Rn.style.width="100%";for(let Z of[An,co,fn,tt])Z&&(Z.style.maxWidth=hd,Z.style.marginLeft="auto",Z.style.marginRight="auto",Z.style.width="100%")}else{Te.style.maxWidth="",Te.style.marginLeft="",Te.style.marginRight="",Te.style.width="",Rn.style.maxWidth="",Rn.style.marginLeft="",Rn.style.marginRight="",Rn.style.width="";for(let Z of[An,co,fn,tt])Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight="",Z.style.width="")}let Ro=o.statusIndicator??{};if(Tf(tt,An,Ro),hi(tt,Ro,R?.getStatus()??"idle"),R){let Z=R.getStatus();_s(tt,(rt=>rt==="idle"?Ro.idleText??Yt.idle:rt==="connecting"?Ro.connectingText??Yt.connecting:rt==="connected"?Ro.connectedText??Yt.connected:rt==="error"?Ro.errorText??Yt.error:rt==="paused"?Ro.pausedText??Yt.paused:rt==="resuming"?Ro.resumingText??Yt.resuming:Yt[rt])(Z),Ro,Z)}tt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let _M=Ro.align==="left"?"persona-text-left":Ro.align==="center"?"persona-text-center":"persona-text-right";tt.classList.add(_M),qu(),vg(),ko(),dr()},open(){Xe()&&Mt(!0,"api")},close(){Xe()&&Mt(!1,"api")},toggle(){Xe()&&Mt(!D,"api")},reconnect(){R.reconnectNow()},clearChat(){yr=!1,i.clear(),r.clear(),s.clear(),l.clear(),R.clearMessages(),o.layout?.topFade&&(ae.scrollTop=0),ae.removeAttribute("data-persona-top-fade"),Mn.clear(),Go();try{localStorage.removeItem(Ga),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ga}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ga)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&&jc(()=>T.clear(),"[AgentWidget] Failed to clear storage adapter:"),P={},_e.syncFromMetadata(),je?.clearAttachments(),zc(),qi(void 0),qo(void 0),Xs(),ft?.clear(),bt?.reset(),rn?.update()},setMessage(a){return!ce||R.isStreaming()||Yo()?!1:(!D&&Xe()&&Mt(!0,"system"),ce.value=a,ce.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(R.isStreaming()||oi())return!1;let u=a?.trim()||ce.value.trim();return u?(!D&&Xe()&&Mt(!0,"system"),ce.value="",ce.style.height="auto",po(),cd(u,{consumeDraft:!1}),!0):!1},getComposerState(){return be.getState()},setQuote(a){let u=a?.text?.trim();u&&qo({...a,text:u})},clearQuote(){qo(void 0)},startVoiceRecognition(){return R.isStreaming()?!1:In(o.voiceRecognition?.provider)?(R.isVoiceActive()||R.isBargeInActive()||(!D&&Xe()&&Mt(!0,"system"),Ge.manuallyDeactivated=!1,zn(),R.toggleVoice().then(()=>{Ge.active=lg(),zn(),Sr("user"),Ge.active&&da()})),!0):Qo?!0:wb()?(!D&&Xe()&&Mt(!0,"system"),Ge.manuallyDeactivated=!1,zn(),ud("user"),!0):!1},stopVoiceRecognition(){return In(o.voiceRecognition?.provider)?!R.isVoiceActive()&&!R.isBargeInActive()?!1:((R.isBargeInActive()?R.deactivateBargeIn():R.toggleVoice()).then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,zn(),Sr("user"),Tr()}),!0):Qo?(Ge.manuallyDeactivated=!0,zn(),ps("user"),!0):!1},injectMessage(a){return!D&&Xe()&&Mt(!0,"system"),R.injectMessage(a)},injectAssistantMessage(a){!D&&Xe()&&Mt(!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&&Xe()&&Mt(!0,"system"),R.injectUserMessage(a)},injectSystemMessage(a){return!D&&Xe()&&Mt(!0,"system"),R.injectSystemMessage(a)},injectMessageBatch(a){return!D&&Xe()&&Mt(!0,"system"),R.injectMessageBatch(a)},injectComponentDirective(a){return!D&&Xe()&&Mt(!0,"system"),R.injectComponentDirective(a)},injectTestMessage(a){!D&&Xe()&&Mt(!0,"system"),R.injectTestEvent(a)},async connectStream(a,u){return R.connectStream(a,u)},__pushEventStreamEvent(a){Me&&(cr(),Qa(a.type,a.payload))},showEventStream(){Me&&ju()},hideEventStream(){Sn&&zi()},isEventStreamVisible(){return Sn},listConversations(a){return R.listConversations(a)},getActiveConversationId(){return R.getActiveConversationId()},openConversation(a,u){return Xo(m=>m.openHistoryConversation(a,{focusComposer:u?.focus===!0}))},startNewConversation(a){return Xo(u=>u.startNewConversation({focusComposer:a?.focus===!0}))},warmSession(){Bg()},deleteConversation(a){return Xo(u=>u.deleteHistoryConversation(a))},renameConversation(a,u){return Xo(m=>m.updateHistoryConversation(a,{title:u}))},setConversationStarred(a,u){return Xo(m=>m.updateHistoryConversation(a,{starred:u}))},clearConversationHistory(a){return Xo(u=>u.clearConversationHistory(a))},resetHistoryIdentity(){return Xo(a=>a.resetHistoryIdentity())},async getVisitorToken(){let a=mo;if(!a)return null;let u=await a.get();return a===mo?u:null},getHistoryIdentityStatus(){let a=Bt?.historyProvider;return a?a.getIdentityStatus():yl()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(a){return yl()?Xo(u=>u.openHistory({...a?.returnSurface?{returnSurface:a.returnSurface}:{},...a?.focus!==void 0?{focus:a.focus}:{}})):Promise.resolve()},hideHistory(a){Bt?.closeHistory(a?.restoreFocus!==void 0?{restoreFocus:a.restoreFocus}:void 0)},isHistoryVisible(){return un},showArtifacts(){$n(o)&&(yr=!1,Gi=!0,Ho(),nt?.setMobileOpen(!0))},hideArtifacts(){$n(o)&&(yr=!0,Ho())},upsertArtifact(a){return $n(o)?(or(o.features?.artifacts,{artifactType:a.artifactType,...a.artifactType==="markdown"&&a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{}})==="panel"&&(yr=!1,Gi=!0),R.upsertArtifact(a)):null},selectArtifact(a){$n(o)&&R.selectArtifact(a)},clearArtifacts(){$n(o)&&R.clearArtifacts()},getArtifacts(){return R?.getArtifacts()??[]},getSelectedArtifactId(){return R?.getSelectedArtifactId()??null},focusInput(){return ye&&!D&&!Le()||!ce?!1:(ce.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){SE(a)},clearFollowUpSuggestions(){Ly()},getMessages(){return R.getMessages()},getStatus(){return R.getStatus()},getPersistentMetadata(){return{...P}},updatePersistentMetadata(a){qe(a)},on(a,u){return X.on(a,u)},off(a,u){X.off(a,u)},isOpen(){return Xe()&&D},isVoiceActive(){return Ge.active},toggleReadAloud(a){R.toggleReadAloud(a)},stopReadAloud(){R.stopSpeaking()},getReadAloudState(a){return R.getReadAloudState(a)},onReadAloudChange(a){return R.onReadAloudChange(a)},getState(){return{open:Xe()&&D,launcherEnabled:ye,voiceActive:Ge.active,streaming:R.isStreaming()}},showCSATFeedback(a){!D&&Xe()&&Mt(!0,"system");let u=Te.querySelector(".persona-feedback-container");u&&u.remove();let m=hu({onSubmit:async(v,w)=>{R.isClientTokenMode()&&await R.submitCSATFeedback(v,w),a?.onSubmit?.(v,w)},onDismiss:a?.onDismiss,...a});Te.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!D&&Xe()&&Mt(!0,"system");let u=Te.querySelector(".persona-feedback-container");u&&u.remove();let m=yu({onSubmit:async(v,w)=>{R.isClientTokenMode()&&await R.submitNPSFeedback(v,w),a?.onSubmit?.(v,w)},onDismiss:a?.onDismiss,...a});Te.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(){Hg(),ri!=null&&(clearInterval(ri),ri=null),i.clear(),r.clear(),s.clear(),l.clear(),Se.forEach(a=>a()),Je.remove(),Xt?.remove(),qt?.destroy(),On?.remove(),qs&&ze.removeEventListener("click",qs)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,u={controller:zt,getMessages:zt.getMessages,getStatus:zt.getStatus,getMetadata:zt.getPersistentMetadata,updateMetadata:zt.updatePersistentMetadata,clearHistory:()=>zt.clearChat(),setVoiceActive:m=>m?zt.startVoiceRecognition():zt.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Se.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=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.focusInput()};if(window.addEventListener("persona:focusInput",u),Se.push(()=>{window.removeEventListener("persona:focusInput",u)}),Me){let ie=de=>{let ke=de.detail;(!ke?.instanceId||ke.instanceId===a)&&zt.showEventStream()},le=de=>{let ke=de.detail;(!ke?.instanceId||ke.instanceId===a)&&zt.hideEventStream()};window.addEventListener("persona:showEventStream",ie),window.addEventListener("persona:hideEventStream",le),Se.push(()=>{window.removeEventListener("persona:showEventStream",ie),window.removeEventListener("persona:hideEventStream",le)})}let m=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.showHistory()},v=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.hideHistory()};window.addEventListener("persona:showHistory",m),window.addEventListener("persona:hideHistory",v),Se.push(()=>{window.removeEventListener("persona:showHistory",m),window.removeEventListener("persona:hideHistory",v)});let w=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.showArtifacts()},k=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.hideArtifacts()},z=ie=>{let le=ie.detail;le?.instanceId&&le.instanceId!==a||le?.artifact&&zt.upsertArtifact(le.artifact)},re=ie=>{let le=ie.detail;le?.instanceId&&le.instanceId!==a||typeof le?.id=="string"&&zt.selectArtifact(le.id)},Y=ie=>{let le=ie.detail;(!le?.instanceId||le.instanceId===a)&&zt.clearArtifacts()};window.addEventListener("persona:showArtifacts",w),window.addEventListener("persona:hideArtifacts",k),window.addEventListener("persona:upsertArtifact",z),window.addEventListener("persona:selectArtifact",re),window.addEventListener("persona:clearArtifacts",Y),Se.push(()=>{window.removeEventListener("persona:showArtifacts",w),window.removeEventListener("persona:hideArtifacts",k),window.removeEventListener("persona:upsertArtifact",z),window.removeEventListener("persona:selectArtifact",re),window.removeEventListener("persona:clearArtifacts",Y)})}let yo=lH(o.persistState);if(yo&&Xe()){let a=cH(yo.storage),u=`${yo.keyPrefix}widget-open`,m=`${yo.keyPrefix}widget-voice`,v=`${yo.keyPrefix}widget-voice-mode`;if(a){let w=yo.persist?.openState&&a.getItem(u)==="true",k=yo.persist?.voiceState&&a.getItem(m)==="true",z=yo.persist?.voiceState&&a.getItem(v)==="true";if(w&&(qt?.setPanelOpen(!0,"auto"),setTimeout(()=>{zt.open(),setTimeout(()=>{if(k||z)zt.startVoiceRecognition();else if(yo.persist?.focusInput){let re=e.querySelector("textarea");re&&re.focus()}},100)},0)),yo.persist?.openState&&(X.on("widget:opened",()=>{a.setItem(u,"true")}),X.on("widget:closed",()=>{a.setItem(u,"false")})),yo.persist?.voiceState&&(X.on("voice:state",re=>{a.setItem(m,re.active?"true":"false")}),X.on("user:message",re=>{a.setItem(v,re.viaVoice?"true":"false")})),yo.clearOnChatClear){let re=()=>{a.removeItem(u),a.removeItem(m),a.removeItem(v)},Y=()=>re();window.addEventListener("persona:clear-chat",Y),Se.push(()=>{window.removeEventListener("persona:clear-chat",Y)})}}}if(Ee&&Xe()&&(qt?.setPanelOpen(!0,"auto"),setTimeout(()=>{zt.open()},0)),oa(),!AE){let a=ua(()=>{R&&(Qs++,Mn.clear(),fo(Te,R.getMessages(),K))});Se.push(a)}I=()=>{R&&(Qs++,Mn.clear(),fo(Te,R.getMessages(),K))},R.getMessages().length>0&&Xc(),W=()=>{R&&(Qs++,Mn.clear(),fo(Te,R.getMessages(),K))};let WM=uv(()=>{R&&(Qs++,Mn.clear(),fo(Te,R.getMessages(),K))});Se.push(WM);let OM=uh(()=>{R&&(Qs++,Mn.clear(),fo(Te,R.getMessages(),K),qr()?.updateInlineArtifactBlocks(Te,uo.artifacts,{suppressTransition:!0}),Ho())});return Se.push(OM),zt};_o();var ux=(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},uH=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},gH=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},fH=(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.")},gx=(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"},Eh=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=""},fx=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Eh(e)},Sh=e=>{e.style.transition=""},Ah=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=""},xh=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Cu=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},mH=(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))},hH=(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)},yH=e=>{let t=No(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:wn(t,r)??r;return{inset:o(n?.inset,Up),canvasBackground:o(n?.canvasBackground,Vp)}},mx=(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},bH=(e,t,n,o,r,s,i,l)=>{let c=Zn(s),p=c.reveal==="push",d=l!=null,g=l?.inset??"",f=l?.canvasBackground??"";mH(e,t,n,o,p),hH(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"),Ah(t),Sh(o),fx(o),xh(n),Cu(r,o),mx(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??kn),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"),fx(o),uH(o,c.maxHeight),mx(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",Ah(t),Sh(o),xh(n),Cu(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",Sh(o),Eh(o),Cu(r,o);let L=ux(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="",Ah(t),Eh(o),xh(n),Cu(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",gH(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(${ux(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"}}},vH=(e,t)=>{let n=e.ownerDocument.createElement("div");return gx(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){gx(n,o)},destroy(){n.remove()}}},CH=(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?yH(t):null};b();let C=()=>{bH(i,l,c,p,d,t,g,y)},A=null,L=()=>{A?.(),A=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(A=Oa(()=>{b(),C()}))},I=()=>{h(),Zn(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,fH(i,Zn(t)))},V=i.ownerDocument.defaultView,oe=()=>{B()};return V?.addEventListener("resize",oe),Zn(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",oe),A?.(),A=null,h(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),i.remove()}}},bc=(e,t)=>Lt(t)?CH(e,t):vH(e,t);var wH=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},hx=(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)},wu=[],yx=()=>[...wu],Mh=e=>{let t=wH(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=bc(t,r),i,l=[],c=(C,A)=>{let I=!(A?.launcher?.enabled??!0)||Lt(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),hx(B,o)}else C.appendChild(H),hx(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=vu(C,r,{debugTools:e.debugTools}),d()},f=()=>{l.forEach(C=>C()),l=[],i.destroy()};g(),e.onChatReady?.();let h=C=>{f(),s.destroy(),s=bc(t,C),r=C,g()},y={update(C){let A=pu(r??{},C),L=Lt(r),I=Lt(A),H=Rs(r),B=Rs(A);if(L!==I||H!==B){h(A);return}r=A,s.updateConfig(r),i.update(C),p()},destroy(){f(),s.destroy();let C=wu.indexOf(b);C!==-1&&wu.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 wu.push(b),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=b),b};ha();Rl();Dd();Ca();pi();Cs();Nr();var Sx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),SH=new Set(["button","a","input","select","textarea","details","summary"]),AH=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Th=/\b(product|card|item|listing|result)\b/i,kh=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,xH=3e3,EH=100;function Ax(e){let t=typeof e.className=="string"?e.className:"";if(Th.test(t)||e.id&&Th.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Th.test(o.value))return!0}return!1}function xx(e){return kh.test((e.textContent??"").trim())}function Ex(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 MH(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function bx(e){let t=e.match(kh);return t?t[0]:null}function vx(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 TH(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 PH="commerce-card",kH="result-card";function Cx(e){return!Ax(e)||!xx(e)||!Ex(e)&&!MH(e)?0:5200}function wx(e){return!Ax(e)||xx(e)||!Ex(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Lh=[{id:PH,scoreElement(e){return Cx(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||kh.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(Cx(e)===0)return null;let{title:n,href:o}=vx(e),r=bx((e.textContent??"").trim())??bx(t.text)??"",s=TH(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
141
  `)}},{id:kH,scoreElement(e){return wx(e)},formatSummary(e,t){if(wx(e)===0)return null;let{title:n,href:o}=vx(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
142
- `)}}];function PH(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function LH(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??Lh;return l==="simple"&&e.rules&&e.rules.length>0?(PH(),p=[]):l==="simple"&&(p=[]),{mode:l,maxElements:n,maxCandidates:c,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:i,rules:p}}function kh(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var HH=["data-testid","data-product","data-action","data-id","data-name","data-type"];function IH(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"||wH.has(t)||n&&SH.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Mx(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 RH(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 Hh(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${kh(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of HH){let s=e.getAttribute(r);if(s){let i=`${t}[${r}="${kh(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=>kh(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 WH(e){return e==="static"?xH:AH}function Tx(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Hh(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:IH(e),attributes:RH(e)}}function OH(e,t,n,o){let r=WH(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 _H(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 BH(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(Sx.has(d)){l=i.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){l=i.nextNode();continue}}catch{}if(e.visibleOnly&&!Mx(p)){l=i.nextNode();continue}let g=Tx(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}=OH(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;_H(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 DH(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(Sx.has(p)){s=r.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Mx(c)){s=r.nextNode();continue}let d=Tx(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 kx(e={}){let t=LH(e),n=t.root??document.body;return n?t.mode==="simple"?DH(t,n):BH(t,n):[]}var Su=100;function Px(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:
142
+ `)}}];function LH(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function HH(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??Lh;return l==="simple"&&e.rules&&e.rules.length>0?(LH(),p=[]):l==="simple"&&(p=[]),{mode:l,maxElements:n,maxCandidates:c,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:i,rules:p}}function Ph(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var IH=["data-testid","data-product","data-action","data-id","data-name","data-type"];function RH(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"||SH.has(t)||n&&AH.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Mx(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 WH(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 Hh(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${Ph(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of IH){let s=e.getAttribute(r);if(s){let i=`${t}[${r}="${Ph(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=>Ph(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 OH(e){return e==="static"?EH:xH}function Tx(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Hh(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:RH(e),attributes:WH(e)}}function _H(e,t,n,o){let r=OH(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 BH(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 DH(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(Sx.has(d)){l=i.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){l=i.nextNode();continue}}catch{}if(e.visibleOnly&&!Mx(p)){l=i.nextNode();continue}let g=Tx(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}=_H(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;BH(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 NH(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(Sx.has(p)){s=r.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Mx(c)){s=r.nextNode();continue}let d=Tx(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 Px(e={}){let t=HH(e),n=t.root??document.body;return n?t.mode==="simple"?NH(t,n):DH(t,n):[]}var Su=100;function kx(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(`
@@ -153,7 +153,7 @@ ${s.join(`
153
153
  ${s.join(`
154
154
  `)}`)}return o.join(`
155
155
 
156
- `)}Sa();Pt();So();So();var NH={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"}}},Lx={components:{panel:{borderRadius:"0",shadow:"none"}}},Ih={id:"shop",label:"Shopping Assistant",config:{theme:NH,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:vi},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"]}},Rh={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Lx}},Wh={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Lx}},Oh={shop:Ih,minimal:Rh,fullscreen:Wh};function Hx(e){return Oh[e]}var Ix=Mh;function Rx(){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 Wx(){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 Ox(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:lr(e.colors.primary,.95),100:lr(e.colors.primary,.9),200:lr(e.colors.primary,.8),300:lr(e.colors.primary,.7),400:lr(e.colors.primary,.6),500:e.colors.primary,600:lr(e.colors.primary,.8),700:lr(e.colors.primary,.7),800:lr(e.colors.primary,.6),900:lr(e.colors.primary,.5),950:lr(e.colors.primary,.45)}}),{...t,palette:n}}}}function _x(){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 Bx(){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 lr(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 Dx(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}Sa();function _h(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@${Xn}/dist`}function Gr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function FH(e){if(e)return{getHeaders:Gr(e.getHeaders),onFeedback:Gr(e.onFeedback),onCopy:Gr(e.onCopy),requestMiddleware:Gr(e.requestMiddleware),actionHandlers:Gr(e.actionHandlers),actionParsers:Gr(e.actionParsers),postprocessMessage:Gr(e.postprocessMessage),contextProviders:Gr(e.contextProviders),streamParser:Gr(e.streamParser)}}var Nx=`({ text, message }: any) => {
156
+ `)}Sa();kt();So();So();var FH={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"}}},Lx={components:{panel:{borderRadius:"0",shadow:"none"}}},Ih={id:"shop",label:"Shopping Assistant",config:{theme:FH,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:vi},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"]}},Rh={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Lx}},Wh={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Lx}},Oh={shop:Ih,minimal:Rh,fullscreen:Wh};function Hx(e){return Oh[e]}var Ix=Mh;function Rx(){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 Wx(){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 Ox(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:lr(e.colors.primary,.95),100:lr(e.colors.primary,.9),200:lr(e.colors.primary,.8),300:lr(e.colors.primary,.7),400:lr(e.colors.primary,.6),500:e.colors.primary,600:lr(e.colors.primary,.8),700:lr(e.colors.primary,.7),800:lr(e.colors.primary,.6),900:lr(e.colors.primary,.5),950:lr(e.colors.primary,.45)}}),{...t,palette:n}}}}function _x(){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 Bx(){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 lr(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 Dx(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}Sa();function _h(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@${Xn}/dist`}function Gr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function $H(e){if(e)return{getHeaders:Gr(e.getHeaders),onFeedback:Gr(e.onFeedback),onCopy:Gr(e.onCopy),requestMiddleware:Gr(e.requestMiddleware),actionHandlers:Gr(e.actionHandlers),actionParsers:Gr(e.actionParsers),postprocessMessage:Gr(e.postprocessMessage),contextProviders:Gr(e.contextProviders),streamParser:Gr(e.streamParser)}}var Nx=`({ 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
@@ -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
- }`,$H=`(parsed: any) => {
216
+ }`,UH=`(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
- }`,UH=`function(parsed) {
222
+ }`,VH=`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 VH(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 Au(e){return e.parserType??VH(e.streamParser)??"plain"}function xu(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 Eu(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 Mu(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 Tu(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 ku(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 Bh(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 Vx(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}: {`),Vx(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function Os(e,t,n,o){n&&(e.push(`${o}${t}: {`),Vx(e,n,`${o} `),e.push(`${o}},`))}function Pu(e,t,n){t.future?.v5Defaults!==void 0&&e.push(`${n}future: { v5Defaults: ${t.future.v5Defaults===!0} },`)}function vc(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function jx(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:FH(n.hooks)}:void 0;return t==="esm"?jH(o,r):t==="script-installer"?KH(o,r):t==="script-advanced"?YH(o,r):t==="react-component"?qH(o,r):t==="react-advanced"?zH(o,r):GH(o,r)}function jH(e,t){let n=t?.hooks,o=Au(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${vc(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}",`),Pu(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Os(s,"theme",e.theme," "),e.launcher&&Os(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(...Tu(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(...xu(e," ")),s.push(...Eu(e," ",n)),s.push(...Mu(e," ")),s.push(...ku(e," ")),s.push(...Bh(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 qH(e,t){let n=t?.hooks,o=Au(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: '${vc(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}",`),Pu(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Os(s,"theme",e.theme," "),e.launcher&&Os(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(...Tu(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(...xu(e," ")),s.push(...Eu(e," ",n)),s.push(...Mu(e," ")),s.push(...ku(e," ")),s.push(...Bh(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 zH(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: '${vc(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}",`),Pu(o,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Os(o,"theme",e.theme," "),e.launcher&&Os(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(...Tu(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(...xu(e," ")),o.push(...Eu(e," ",n)),o.push(...Mu(e," ")),o.push(...ku(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(${$H}),`)),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(` ${Nx}`),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(` ${Nx}`),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(` ${$x}`),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(` ${$x}`),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 qx(e){let t=Au(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 KH(e,t){let n=qx(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="${_h(t)}/install.global.js" data-config='${s}'></script>`}function GH(e,t){let n=t?.hooks,o=Au(e),r=o!=="plain",s=_h(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: '${vc(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}",`),Pu(i,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Os(i,"theme",e.theme," "),e.launcher&&Os(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(...Tu(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(...xu(e," ")),i.push(...Eu(e," ",n)),i.push(...Mu(e," ")),i.push(...ku(e," ")),i.push(...Bh(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 YH(e,t){let n=t?.hooks,o=qx(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
228
+ }`;function jH(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 Au(e){return e.parserType??jH(e.streamParser)??"plain"}function xu(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 Eu(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 Mu(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 Tu(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 Pu(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 Bh(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 Vx(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}: {`),Vx(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function Os(e,t,n,o){n&&(e.push(`${o}${t}: {`),Vx(e,n,`${o} `),e.push(`${o}},`))}function ku(e,t,n){t.future?.v5Defaults!==void 0&&e.push(`${n}future: { v5Defaults: ${t.future.v5Defaults===!0} },`)}function vc(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function jx(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:$H(n.hooks)}:void 0;return t==="esm"?qH(o,r):t==="script-installer"?GH(o,r):t==="script-advanced"?XH(o,r):t==="react-component"?zH(o,r):t==="react-advanced"?KH(o,r):YH(o,r)}function qH(e,t){let n=t?.hooks,o=Au(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${vc(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}",`),ku(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Os(s,"theme",e.theme," "),e.launcher&&Os(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(...Tu(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(...xu(e," ")),s.push(...Eu(e," ",n)),s.push(...Mu(e," ")),s.push(...Pu(e," ")),s.push(...Bh(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 zH(e,t){let n=t?.hooks,o=Au(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: '${vc(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}",`),ku(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Os(s,"theme",e.theme," "),e.launcher&&Os(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(...Tu(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(...xu(e," ")),s.push(...Eu(e," ",n)),s.push(...Mu(e," ")),s.push(...Pu(e," ")),s.push(...Bh(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 KH(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: '${vc(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}",`),ku(o,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Os(o,"theme",e.theme," "),e.launcher&&Os(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(...Tu(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(...xu(e," ")),o.push(...Eu(e," ",n)),o.push(...Mu(e," ")),o.push(...Pu(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(${UH}),`)),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(` ${Nx}`),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(` ${Nx}`),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(` ${$x}`),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(` ${$x}`),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 qx(e){let t=Au(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 GH(e,t){let n=qx(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="${_h(t)}/install.global.js" data-config='${s}'></script>`}function YH(e,t){let n=t?.hooks,o=Au(e),r=o!=="plain",s=_h(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: '${vc(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}",`),ku(i,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Os(i,"theme",e.theme," "),e.launcher&&Os(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(...Tu(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(...xu(e," ")),i.push(...Eu(e," ",n)),i.push(...Mu(e," ")),i.push(...Pu(e," ")),i.push(...Bh(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 XH(e,t){let n=t?.hooks,o=qx(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 = '${_h(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(${UH});`),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(` ${Fx}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Fx}`),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(` ${Ux}`),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(` ${Ux}`),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: '${vc(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
- `)}Ze();var Qx=require("lucide");Lr();var zx={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Kx=.1,Gx=.15,Yx=1.5,Dh=24,Xx=40,XH=`
235
+ `)};`,""," // Constants",` var CDN_BASE = '${_h(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(${VH});`),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(` ${Fx}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Fx}`),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(` ${Ux}`),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(` ${Ux}`),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: '${vc(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
+ `)}Ze();var Qx=require("lucide");Lr();var zx={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Kx=.1,Gx=.15,Yx=1.5,Dh=24,Xx=40,QH=`
237
237
  /* \u2500\u2500 Root \u2500\u2500 */
238
238
  .persona-dc-root {
239
239
  display: flex;
@@ -474,14 +474,14 @@ ${s.join(`
474
474
  min-height: 300px;
475
475
  }
476
476
  }
477
- `;function QH(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=XH,document.head.appendChild(e)}function JH(e,t){let n=e.clientWidth-Dh*2-Xx,o=e.clientHeight-Dh*2-Xx;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function ZH(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 Jx(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");QH();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=eo({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>_e(-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 oe=x("span","persona-dc-title-text"),W=x("span","persona-dc-title-chevron"),j=Nt(Qx.ChevronDown,12,"currentColor",2);j&&W.appendChild(j),V.append(oe,W);let X=x("div","persona-dc-dropdown");X.setAttribute("role","listbox"),X.style.display="none";let M=!1;function T(){X.innerHTML="";for(let xe=0;xe<n.length;xe++){let Wt=n[xe],vt=x("button","persona-dc-dropdown-item");vt.type="button",vt.setAttribute("role","option"),vt.setAttribute("aria-current",xe===d?"true":"false");let Le=x("span");if(Le.textContent=Wt.title,vt.appendChild(Le),Wt.description){let Xe=x("span","persona-dc-dropdown-desc");Xe.textContent=Wt.description,vt.appendChild(Xe)}vt.addEventListener("click",()=>{k(),ye(xe)}),X.appendChild(vt)}}function _(){M=!M,X.style.display=M?"":"none",V.setAttribute("aria-expanded",M?"true":"false"),M&&T()}function k(){M&&(M=!1,X.style.display="none",V.setAttribute("aria-expanded","false"))}V.addEventListener("click",xe=>{xe.stopPropagation(),_()});let J=()=>k();document.addEventListener("click",J),B.append(V,X);let U=eo({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>_e(1)}),ue=x("span","persona-dc-counter");L.append(H,B,U,ue);let fe=null;l&&(fe=lc({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:g,onSelect:xe=>{g=xe,yt.dataset.device=g,h=null,ut()}}),I.appendChild(fe.element));let me=null;if(i){let xe=x("div","persona-dc-zoom-controls"),Wt=eo({icon:"minus",label:"Zoom out",size:14,onClick:()=>{h=Math.max(Gx,(h??y)-Kx),ut()}});me=x("span","persona-dc-zoom-level"),me.title="Reset to 100%",me.style.cursor="pointer",me.addEventListener("click",()=>{h=1,ut()});let vt=eo({icon:"plus",label:"Zoom in",size:14,onClick:()=>{h=Math.min(Yx,(h??y)+Kx),ut()}}),Le=eo({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{h=null,ut()}});xe.append(Wt,me,vt,Le),I.appendChild(xe)}if(c){let xe=x("div","persona-dc-separator");I.appendChild(xe);let Wt=lc({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:vt=>{f=vt,yt.dataset.colorScheme=f,Oe()}});I.appendChild(Wt.element)}let He=x("div","persona-dc-separator");I.appendChild(He);let Ee=eo({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[d].url,"_blank")}});I.appendChild(Ee),A.append(L,I);let Ie=x("div","persona-dc-stage"),yt=x("div","persona-dc-iframe-wrapper");yt.dataset.device=g,yt.dataset.colorScheme=f;let qe=x("iframe","persona-dc-iframe");qe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),qe.setAttribute("loading","lazy"),qe.title=n[d].title,yt.appendChild(qe),Ie.appendChild(yt),C.append(A,Ie),e.appendChild(C);function Oe(){try{let xe=qe.contentDocument?.body;if(!xe)return;f==="dark"?xe.classList.add("theme-dark"):xe.classList.remove("theme-dark")}catch{}}qe.addEventListener("load",()=>Oe());function $(){let xe=n[d];oe.textContent=xe.title,ue.textContent=`${d+1} / ${n.length}`,qe.title=xe.title}function _e(xe){let Wt=((d+xe)%n.length+n.length)%n.length;ye(Wt)}function ye(xe){xe<0||xe>=n.length||(d=xe,qe.src=n[d].url,$(),p?.(d,n[d]))}function ut(){if(b)return;let xe=zx[g]??zx.desktop;y=JH(Ie,xe);let Wt=Math.max(Gx,Math.min(Yx,h??y));ZH(yt,qe,xe,Wt,g),me&&(me.textContent=`${Math.round(Wt*100)}%`)}let Zt=new ResizeObserver(()=>ut());Zt.observe(Ie),$(),qe.src=n[d].url,requestAnimationFrame(()=>ut());function xt(){b||(b=!0,Zt.disconnect(),document.removeEventListener("click",J),C.remove())}return{element:C,goTo:ye,next:()=>_e(1),prev:()=>_e(-1),getIndex:()=>d,setDevice(xe){g=xe,yt.dataset.device=xe,fe?.setSelected(xe),h=null,ut()},setColorScheme(xe){f=xe,yt.dataset.colorScheme=xe},setZoom(xe){h=xe,ut()},destroy:xt}}gm();Sa();var Nh=16e3,eI=24e3,tI=4096,nI=Nh*2*8,oI=4,rI=1380533830,sI=3e4,iI=1e3,aI=5e3,lI=3e4,cI=3e4,dI=6e5,pI="full-duplex-v1",uI=300,gI=2e3,fI=2e3,mI="runtype-browser-v1",hI=54e4,yI="You're talking to an AI assistant. Voice is processed by OpenAI.",bI=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."]]),Zx=["provider_error","server_restart"],Lu="Voice connection lost.",vI=8e3,CI=4e3,wI=12,eE=2e3;function SI(e,t){let n="Conversation so far:",o=t.slice(0,CI).trim(),r=vI-(o?o.length+2:0)-n.length,s=[];for(let l of e.slice(-wI).reverse()){let c=l.content.replace(/\s+/g," ").trim();if(!c)continue;c.length>eE&&(c=`${c.slice(0,eE-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 JH(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=QH,document.head.appendChild(e)}function ZH(e,t){let n=e.clientWidth-Dh*2-Xx,o=e.clientHeight-Dh*2-Xx;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function eI(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 Jx(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");JH();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=eo({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>_e(-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 oe=x("span","persona-dc-title-text"),W=x("span","persona-dc-title-chevron"),j=Nt(Qx.ChevronDown,12,"currentColor",2);j&&W.appendChild(j),V.append(oe,W);let X=x("div","persona-dc-dropdown");X.setAttribute("role","listbox"),X.style.display="none";let M=!1;function T(){X.innerHTML="";for(let xe=0;xe<n.length;xe++){let Wt=n[xe],vt=x("button","persona-dc-dropdown-item");vt.type="button",vt.setAttribute("role","option"),vt.setAttribute("aria-current",xe===d?"true":"false");let Le=x("span");if(Le.textContent=Wt.title,vt.appendChild(Le),Wt.description){let Xe=x("span","persona-dc-dropdown-desc");Xe.textContent=Wt.description,vt.appendChild(Xe)}vt.addEventListener("click",()=>{P(),ye(xe)}),X.appendChild(vt)}}function _(){M=!M,X.style.display=M?"":"none",V.setAttribute("aria-expanded",M?"true":"false"),M&&T()}function P(){M&&(M=!1,X.style.display="none",V.setAttribute("aria-expanded","false"))}V.addEventListener("click",xe=>{xe.stopPropagation(),_()});let J=()=>P();document.addEventListener("click",J),B.append(V,X);let U=eo({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>_e(1)}),ue=x("span","persona-dc-counter");L.append(H,B,U,ue);let fe=null;l&&(fe=lc({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:g,onSelect:xe=>{g=xe,yt.dataset.device=g,h=null,ut()}}),I.appendChild(fe.element));let me=null;if(i){let xe=x("div","persona-dc-zoom-controls"),Wt=eo({icon:"minus",label:"Zoom out",size:14,onClick:()=>{h=Math.max(Gx,(h??y)-Kx),ut()}});me=x("span","persona-dc-zoom-level"),me.title="Reset to 100%",me.style.cursor="pointer",me.addEventListener("click",()=>{h=1,ut()});let vt=eo({icon:"plus",label:"Zoom in",size:14,onClick:()=>{h=Math.min(Yx,(h??y)+Kx),ut()}}),Le=eo({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{h=null,ut()}});xe.append(Wt,me,vt,Le),I.appendChild(xe)}if(c){let xe=x("div","persona-dc-separator");I.appendChild(xe);let Wt=lc({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:vt=>{f=vt,yt.dataset.colorScheme=f,Oe()}});I.appendChild(Wt.element)}let He=x("div","persona-dc-separator");I.appendChild(He);let Ee=eo({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[d].url,"_blank")}});I.appendChild(Ee),A.append(L,I);let Ie=x("div","persona-dc-stage"),yt=x("div","persona-dc-iframe-wrapper");yt.dataset.device=g,yt.dataset.colorScheme=f;let qe=x("iframe","persona-dc-iframe");qe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),qe.setAttribute("loading","lazy"),qe.title=n[d].title,yt.appendChild(qe),Ie.appendChild(yt),C.append(A,Ie),e.appendChild(C);function Oe(){try{let xe=qe.contentDocument?.body;if(!xe)return;f==="dark"?xe.classList.add("theme-dark"):xe.classList.remove("theme-dark")}catch{}}qe.addEventListener("load",()=>Oe());function $(){let xe=n[d];oe.textContent=xe.title,ue.textContent=`${d+1} / ${n.length}`,qe.title=xe.title}function _e(xe){let Wt=((d+xe)%n.length+n.length)%n.length;ye(Wt)}function ye(xe){xe<0||xe>=n.length||(d=xe,qe.src=n[d].url,$(),p?.(d,n[d]))}function ut(){if(b)return;let xe=zx[g]??zx.desktop;y=ZH(Ie,xe);let Wt=Math.max(Gx,Math.min(Yx,h??y));eI(yt,qe,xe,Wt,g),me&&(me.textContent=`${Math.round(Wt*100)}%`)}let Zt=new ResizeObserver(()=>ut());Zt.observe(Ie),$(),qe.src=n[d].url,requestAnimationFrame(()=>ut());function xt(){b||(b=!0,Zt.disconnect(),document.removeEventListener("click",J),C.remove())}return{element:C,goTo:ye,next:()=>_e(1),prev:()=>_e(-1),getIndex:()=>d,setDevice(xe){g=xe,yt.dataset.device=xe,fe?.setSelected(xe),h=null,ut()},setColorScheme(xe){f=xe,yt.dataset.colorScheme=xe},setZoom(xe){h=xe,ut()},destroy:xt}}gm();Sa();var Nh=16e3,tI=24e3,nI=4096,oI=Nh*2*8,rI=4,sI=1380533830,iI=3e4,aI=1e3,lI=5e3,cI=3e4,dI=3e4,pI=6e5,uI="full-duplex-v1",gI=300,fI=2e3,mI=2e3,hI="runtype-browser-v1",yI=54e4,bI="You're talking to an AI assistant. Voice is processed by OpenAI.",vI=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."]]),Zx=["provider_error","server_restart"],Lu="Voice connection lost.",CI=8e3,wI=4e3,SI=12,eE=2e3;function AI(e,t){let n="Conversation so far:",o=t.slice(0,wI).trim(),r=CI-(o?o.length+2:0)-n.length,s=[];for(let l of e.slice(-SI).reverse()){let c=l.content.replace(/\s+/g," ").trim();if(!c)continue;c.length>eE&&(c=`${c.slice(0,eE-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 AI(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===rI?new Uint8Array(e,44):new Uint8Array(e)}function tE(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 xI(e){return tE(e).replace(/^ws/i,"http")}function EI(e){return typeof e!="number"||!Number.isFinite(e)?lI:Math.min(dI,Math.max(cI,Math.round(e)))}var Cc=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<sI)){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=`${xI(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=EI(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,aI)})]),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:mI,clientVersion:`persona/${Xn}`,voiceCapabilities:pI,clientCapabilities:r.join(",")});return o?.forEach((i,l)=>s.set(l,i)),`${tE(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:Nh,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:Nh});if(this.#n=c,c.state==="suspended"){if(await Promise.race([c.resume().catch(()=>{}),new Promise(f=>setTimeout(f,t?500:iI))]),s!==this.#l)return;if(c.state!=="running")throw t?new Error(this.#w=`${Lu} Tap the mic to reconnect.`):new Error("Audio blocked until a tap")}let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ra(eI);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=Zx.includes(t)&&!this.#Q;if(this.#ee(),o){this.#Q=!0,this.#u=!0,this.#w=t==="provider_error"?`${Lu} Reconnecting\u2026`:"Reconnecting\u2026",this.#_=setTimeout(()=>{this.#u=!1,this.#G=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#v("idle");return}if(Zx.includes(t))return this.#w=Lu,this.#le(new Error(Lu)),this.#v("error");if(t==="error")return this.#v("error");this.#w=t==="quota"&&n||bI.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||yI: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()+gI,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(tI,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>nI;)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*oI));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 SI(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),fI)})]);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,hI),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=AI(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+uI)}#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 Oi=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 Xa(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Cc(e.runtype);case"browser":if(!Oi.isSupported())throw new Error("Browser speech recognition not supported");return new Oi(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 Hu(e){if(e?.type==="custom"&&e.custom)return Xa({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Xa({type:"runtype",runtype:e.runtype});if(Oi.isSupported())return Xa({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Fh(e){try{return Hu(e),!0}catch{return!1}}var nE="webmcp:",MI=e=>e.startsWith(nE)?e.slice(nE.length):e,Iu={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Wu=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 Iu.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=kI(r.annotations);return{name:r.name,description:r.description,parametersSchema:PI(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 $o("WebMCP is not enabled on this widget.");let r=this.#i();if(!r){let y=typeof document<"u"&&!!document.modelContext;return $o(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=MI(t),i;try{i=await r.getTools()}catch(y){let b=y instanceof Error?y.message:String(y);return $o(`Failed to read WebMCP registry: ${b}`)}this.#r.recordToolDisplayTitles(i);let l=i.find(y=>y.name===s);if(!l)return $o(`WebMCP tool not registered on this page: ${s}`);if(!this.#c(s))return $o(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return $o("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 $o("User declined the tool call.");if(o?.aborted)return $o("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,RI(n),{signal:d.signal});return LI(y)}catch(y){if(g)return $o(`WebMCP tool '${s}' timed out after ${this.#n}ms`);if(o?.aborted)return $o("Aborted by cancel()");let b=y instanceof Error?y.message:String(y);return $o(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){Iu.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,Iu.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??HI;try{return await n(t)}catch(o){return Iu.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=>TI(t,o))}},TI=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Ru={type:"object",properties:{}},kI=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},PI=e=>{if(e===void 0||e==="")return{...Ru};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...Ru};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...Ru}}catch{return{...Ru}}},LI=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:WI(t)}]}},$o=e=>({isError:!0,content:[{type:"text",text:e}]}),HI=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=II(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
481
+ `)}function xI(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===sI?new Uint8Array(e,44):new Uint8Array(e)}function tE(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 EI(e){return tE(e).replace(/^ws/i,"http")}function MI(e){return typeof e!="number"||!Number.isFinite(e)?cI:Math.min(pI,Math.max(dI,Math.round(e)))}var Cc=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.#P=null;this.#J=null;this.#B=Promise.resolve();this.#R=new Set;this.#Z=new Set;this.#re=null;this.#k=!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;#P;#J;#B;#R;#Z;#re;#k;#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<iI)){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=`${EI(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=MI(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,lI)})]),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:hI,clientVersion:`persona/${Xn}`,voiceCapabilities:uI,clientCapabilities:r.join(",")});return o?.forEach((i,l)=>s.set(l,i)),`${tE(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:Nh,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:Nh});if(this.#n=c,c.state==="suspended"){if(await Promise.race([c.resume().catch(()=>{}),new Promise(f=>setTimeout(f,t?500:aI))]),s!==this.#l)return;if(c.state!=="running")throw t?new Error(this.#w=`${Lu} Tap the mic to reconnect.`):new Error("Audio blocked until a tap")}let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ra(tI);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=Zx.includes(t)&&!this.#Q;if(this.#ee(),o){this.#Q=!0,this.#u=!0,this.#w=t==="provider_error"?`${Lu} Reconnecting\u2026`:"Reconnecting\u2026",this.#_=setTimeout(()=>{this.#u=!1,this.#G=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#v("idle");return}if(Zx.includes(t))return this.#w=Lu,this.#le(new Error(Lu)),this.#v("error");if(t==="error")return this.#v("error");this.#w=t==="quota"&&n||vI.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||bI: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()+fI,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(nI,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>oI;)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*rI));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.#P=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.#k=!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.#k=!1):this.#k&&!this.#F.has(i)&&(this.#U.add(i),this.#k=!1)}else this.#k&&!this.#F.has(i)&&(this.#U.add(i),this.#k=!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 AI(t,n)}#ge(t){let n=this.#P;if(!n)return;this.#P=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),mI)})]);clearTimeout(n),o&&t.drop()}#we(t){this.#k=!0,this.#re=t}#Ee(t,n=!1){this.#y.add(t),this.#re===t&&(this.#k=!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,yI),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=xI(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+gI)}#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.#P=null,this.#J=null,this.#B=Promise.resolve(),this.#R.clear(),this.#Z.clear(),this.#re=null,this.#k=!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 Oi=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 Xa(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Cc(e.runtype);case"browser":if(!Oi.isSupported())throw new Error("Browser speech recognition not supported");return new Oi(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 Hu(e){if(e?.type==="custom"&&e.custom)return Xa({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Xa({type:"runtype",runtype:e.runtype});if(Oi.isSupported())return Xa({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Fh(e){try{return Hu(e),!0}catch{return!1}}var nE="webmcp:",TI=e=>e.startsWith(nE)?e.slice(nE.length):e,Iu={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Wu=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()).filter(oE)}catch(r){return Iu.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=kI(r.annotations);return{name:r.name,description:r.description,parametersSchema:LI(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 $o("WebMCP is not enabled on this widget.");let r=this.#i();if(!r){let y=typeof document<"u"&&!!document.modelContext;return $o(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=TI(t),i;try{i=(await r.getTools()).filter(oE)}catch(y){let b=y instanceof Error?y.message:String(y);return $o(`Failed to read WebMCP registry: ${b}`)}this.#r.recordToolDisplayTitles(i);let l=i.find(y=>y.name===s);if(!l)return $o(`WebMCP tool not registered on this page: ${s}`);if(!this.#c(s))return $o(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return $o("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 $o("User declined the tool call.");if(o?.aborted)return $o("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,II(n),{signal:d.signal});return HI(y)}catch(y){if(g)return $o(`WebMCP tool '${s}' timed out after ${this.#n}ms`);if(o?.aborted)return $o("Aborted by cancel()");let b=y instanceof Error?y.message:String(y);return $o(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}let t=await this.#r.loadPolyfill();"initializeWebMCPPolyfill"in t?t.initializeWebMCPPolyfill():t.installWebMCP(),this.#o=!0}catch(t){Iu.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,Iu.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??RI;try{return await n(t)}catch(o){return Iu.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=>PI(t,o))}},PI=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Ru={type:"object",properties:{}},kI=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},LI=e=>{if(e===void 0||e==="")return{...Ru};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...Ru};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...Ru}}catch{return{...Ru}}},HI=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:OI(t)}]}},II=e=>{let t;try{t=JSON.stringify(e)??"{}"}catch{t="{}"}let n=JSON.parse(t);if(n===null||typeof n!="object")throw new TypeError("WebMCP tool arguments must be an object or array.");return Object.defineProperty(n,Symbol.toPrimitive,{value:()=>t}),n},$o=e=>({isError:!0,content:[{type:"text",text:e}]}),RI=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=WI(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)},II=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)}},RI=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},WI=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};pi();var Ou=class extends Wu{constructor(t){super(t,{recordToolDisplayTitles:Sd,getToolDisplayTitle:ma,loadPolyfill:Ad})}};function OI(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 _I(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:OI(o,n)?2:3}function oE(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function _u(e,t){let n=t.trim();if(!n)return[...e].sort(oE);let o=[];for(let r of e){let s=_I(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:oE(r.item,s.item)),o.map(r=>r.item)}function BI(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 rE(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>_u(e.items,t),resolve:e.resolve}}function sE(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=>_u(t,BI(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 iE(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)}}}0&&(module.exports={ASK_USER_QUESTION_CLIENT_TOOL,ASK_USER_QUESTION_PARAMETERS_SCHEMA,ASK_USER_QUESTION_TOOL_NAME,AgentWidgetClient,AgentWidgetSession,AttachmentManager,BrowserSpeechEngine,DEFAULT_COMPONENTS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,DEFAULT_FLOATING_LAUNCHER_WIDTH,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,HistoryProviderError,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,ReadAloudController,SUGGEST_REPLIES_CLIENT_TOOL,SUGGEST_REPLIES_PARAMETERS_SCHEMA,SUGGEST_REPLIES_TOOL_NAME,THEME_ZONES,VERSION,WEBMCP_TOOL_PREFIX,WebMcpBridge,accessibilityPlugin,animationsPlugin,applyFeaturePreferences,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,builtInClientToolsForDispatch,canonicalArtifactDisplayMode,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createAskUserQuestionBubble,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComboButton,createComponentMiddleware,createComponentStreamParser,createDefaultSanitizer,createDemoCarousel,createDirectivePostprocessor,createDropdownMenu,createFlexibleJsonStreamParser,createIconButton,createImagePart,createJsonStreamParser,createLabelButton,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createPlugin,createRegexJsonParser,createRovingTablist,createSlashCommandsSource,createSplitButton,createStandardBubble,createStaticMentionSource,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,defaultMentionFilter,defaultParseRules,detectColorScheme,directivePostprocessor,ensureAskUserQuestionSheet,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getAgentWidgetHandles,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isAskUserQuestionMessage,isComponentDirectiveType,isDockedMountMode,isHistoryProviderError,isSuggestRepliesMessage,isVoiceSupported,isWebMcpToolName,isWelcomeVisible,latestAgentSuggestions,listRegisteredStreamAnimations,loadMarkdownParsers,markdownPostprocessor,mergeWithDefaults,normalizeContent,normalizeMediaType,onMarkdownParsersReady,parseAskUserQuestionPayload,parseSuggestRepliesPayload,parseWidgetPreferenceSlice,pickBestVoice,pluginRegistry,reducedMotionPlugin,registerIcons,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,renderLucideIcon,resolveArtifactDisplay,resolveArtifactDisplayMode,resolveConfigPreferences,resolveDockConfig,resolveSanitizer,resolveTokens,resolveWelcomeConfig,stripWebMcpPrefix,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
486
+ ${e.description}`:"");return window.confirm(n)},WI=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)}},oE=e=>(e.window===void 0||typeof window<"u"&&e.window===window)&&(e.origin===void 0||typeof location<"u"&&e.origin===location.origin),OI=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};pi();var Ou=class extends Wu{constructor(t){super(t,{recordToolDisplayTitles:Sd,getToolDisplayTitle:ma,loadPolyfill:Ad})}};function _I(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 BI(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:_I(o,n)?2:3}function rE(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function _u(e,t){let n=t.trim();if(!n)return[...e].sort(rE);let o=[];for(let r of e){let s=BI(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:rE(r.item,s.item)),o.map(r=>r.item)}function DI(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 sE(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>_u(e.items,t),resolve:e.resolve}}function iE(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=>_u(t,DI(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 aE(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)}}}0&&(module.exports={ASK_USER_QUESTION_CLIENT_TOOL,ASK_USER_QUESTION_PARAMETERS_SCHEMA,ASK_USER_QUESTION_TOOL_NAME,AgentWidgetClient,AgentWidgetSession,AttachmentManager,BrowserSpeechEngine,DEFAULT_COMPONENTS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,DEFAULT_FLOATING_LAUNCHER_WIDTH,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,HistoryProviderError,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,ReadAloudController,SUGGEST_REPLIES_CLIENT_TOOL,SUGGEST_REPLIES_PARAMETERS_SCHEMA,SUGGEST_REPLIES_TOOL_NAME,THEME_ZONES,VERSION,WEBMCP_TOOL_PREFIX,WebMcpBridge,accessibilityPlugin,animationsPlugin,applyFeaturePreferences,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,builtInClientToolsForDispatch,canonicalArtifactDisplayMode,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createAskUserQuestionBubble,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComboButton,createComponentMiddleware,createComponentStreamParser,createDefaultSanitizer,createDemoCarousel,createDirectivePostprocessor,createDropdownMenu,createFlexibleJsonStreamParser,createIconButton,createImagePart,createJsonStreamParser,createLabelButton,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createPlugin,createRegexJsonParser,createRovingTablist,createSlashCommandsSource,createSplitButton,createStandardBubble,createStaticMentionSource,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,defaultMentionFilter,defaultParseRules,detectColorScheme,directivePostprocessor,ensureAskUserQuestionSheet,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getAgentWidgetHandles,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isAskUserQuestionMessage,isComponentDirectiveType,isDockedMountMode,isHistoryProviderError,isSuggestRepliesMessage,isVoiceSupported,isWebMcpToolName,isWelcomeVisible,latestAgentSuggestions,listRegisteredStreamAnimations,loadMarkdownParsers,markdownPostprocessor,mergeWithDefaults,normalizeContent,normalizeMediaType,onMarkdownParsersReady,parseAskUserQuestionPayload,parseSuggestRepliesPayload,parseWidgetPreferenceSlice,pickBestVoice,pluginRegistry,reducedMotionPlugin,registerIcons,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,renderLucideIcon,resolveArtifactDisplay,resolveArtifactDisplayMode,resolveConfigPreferences,resolveDockConfig,resolveSanitizer,resolveTokens,resolveWelcomeConfig,stripWebMcpPrefix,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
487
487
  //# sourceMappingURL=index.cjs.map