@runtypelabs/persona 4.29.0 → 4.29.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 (126) hide show
  1. package/dist/animations/glyph-cycle.d.cts +1 -1
  2. package/dist/animations/glyph-cycle.d.ts +1 -1
  3. package/dist/animations/wipe.d.cts +1 -1
  4. package/dist/animations/wipe.d.ts +1 -1
  5. package/dist/approval-ui.cjs +3 -3
  6. package/dist/approval-ui.d.cts +1 -1
  7. package/dist/approval-ui.d.ts +1 -1
  8. package/dist/approval-ui.js +3 -3
  9. package/dist/artifacts-ui.d.cts +2 -2
  10. package/dist/artifacts-ui.d.ts +2 -2
  11. package/dist/chunk-B1-_pp-Y.js +4 -0
  12. package/dist/{chunk-DjOvgFsn.js → chunk-BcLIgi1h.js} +1 -1
  13. package/dist/chunk-Bm2-bemv.js +1 -0
  14. package/dist/chunk-BvhTpG6k.js +1 -0
  15. package/dist/chunk-Csks3Qw1.js +1 -0
  16. package/dist/chunk-D5B629Mj.js +1 -0
  17. package/dist/chunk-DGlFKA0r.js +9 -0
  18. package/dist/chunk-DO9_WSpy.js +1 -0
  19. package/dist/chunk-DTDHeUsG.js +1 -0
  20. package/dist/chunk-DjFpGFGA.js +1 -0
  21. package/dist/{chunk-dRBlrLd7.js → chunk-DtmtfIkd.js} +1 -1
  22. package/dist/client-history.js +1 -1
  23. package/dist/client-stream.js +1 -1
  24. package/dist/codegen.cjs +1 -1
  25. package/dist/codegen.js +1 -1
  26. package/dist/{composer-input-D3sB8_P_.d.cts → composer-input-B0P4OtNi.d.cts} +1 -1
  27. package/dist/{composer-input-D3sB8_P_.d.ts → composer-input-B0P4OtNi.d.ts} +1 -1
  28. package/dist/{context-mention-manager-D2qxE5op.d.cts → context-mention-manager-DmLI_RM6.d.cts} +1 -1
  29. package/dist/{context-mention-manager-D2qxE5op.d.ts → context-mention-manager-DmLI_RM6.d.ts} +1 -1
  30. package/dist/context-mentions-inline.d.cts +2 -2
  31. package/dist/context-mentions-inline.d.ts +2 -2
  32. package/dist/context-mentions.d.cts +3 -3
  33. package/dist/context-mentions.d.ts +3 -3
  34. package/dist/{defaults-Dsw66XqE.d.cts → defaults-DVo1wbZs.d.cts} +1 -1
  35. package/dist/{defaults-Dsw66XqE.d.ts → defaults-DVo1wbZs.d.ts} +1 -1
  36. package/dist/event-stream-view.d.cts +1 -1
  37. package/dist/event-stream-view.d.ts +1 -1
  38. package/dist/{fallback-speech-engine-DJpJcWAk.d.cts → fallback-speech-engine-BMnlmKnY.d.cts} +1 -1
  39. package/dist/{fallback-speech-engine-DJpJcWAk.d.ts → fallback-speech-engine-BMnlmKnY.d.ts} +1 -1
  40. package/dist/forms-ui.d.cts +2 -2
  41. package/dist/forms-ui.d.ts +2 -2
  42. package/dist/history-view.d.cts +1 -1
  43. package/dist/history-view.d.ts +1 -1
  44. package/dist/index.cjs +56 -56
  45. package/dist/index.cjs.map +1 -1
  46. package/dist/index.d.cts +6 -6
  47. package/dist/index.d.ts +6 -6
  48. package/dist/index.global.js +2 -3
  49. package/dist/index.global.js.map +1 -1
  50. package/dist/index.js +38 -38
  51. package/dist/index.js.map +1 -1
  52. package/dist/{markdown-parsers-loader-CCY7T4Up.d.cts → markdown-parsers-loader-CeovcyYf.d.cts} +1 -1
  53. package/dist/{markdown-parsers-loader-CCY7T4Up.d.ts → markdown-parsers-loader-CeovcyYf.d.ts} +1 -1
  54. package/dist/{preview-DKKpfTo7.d.cts → preview-Bkb4UrQC.d.cts} +2 -2
  55. package/dist/{preview-DKKpfTo7.d.ts → preview-Bkb4UrQC.d.ts} +2 -2
  56. package/dist/session-actions.js +1 -1
  57. package/dist/{session-DleMr9dZ.d.ts → session-iLyKipoM.d.cts} +21 -9
  58. package/dist/{session-DleMr9dZ.d.cts → session-iLyKipoM.d.ts} +21 -9
  59. package/dist/session-reconnect.cjs +1 -1
  60. package/dist/session-reconnect.d.cts +8 -2
  61. package/dist/session-reconnect.d.ts +8 -2
  62. package/dist/session-reconnect.js +1 -1
  63. package/dist/smart-dom-reader.d.cts +1 -1
  64. package/dist/smart-dom-reader.d.ts +1 -1
  65. package/dist/theme-editor-preview.cjs +61 -61
  66. package/dist/theme-editor-preview.d.cts +1 -1
  67. package/dist/theme-editor-preview.d.ts +1 -1
  68. package/dist/theme-editor-preview.js +40 -40
  69. package/dist/theme-editor.d.cts +2 -2
  70. package/dist/theme-editor.d.ts +2 -2
  71. package/dist/theme-reference.d.cts +2 -2
  72. package/dist/theme-reference.d.ts +2 -2
  73. package/dist/{types-oAZ1VReS.d.cts → types-BuDirJkQ.d.cts} +35 -3
  74. package/dist/{types-oAZ1VReS.d.ts → types-BuDirJkQ.d.ts} +35 -3
  75. package/dist/voice-client-tools.d.cts +1 -1
  76. package/dist/voice-client-tools.d.ts +1 -1
  77. package/dist/voice-runtime.cjs +3 -3
  78. package/dist/voice-runtime.d.cts +10 -4
  79. package/dist/voice-runtime.d.ts +10 -4
  80. package/dist/voice-runtime.js +5 -5
  81. package/dist/voice-worklet-player.d.cts +2 -2
  82. package/dist/voice-worklet-player.d.ts +2 -2
  83. package/dist/{webmcp-runtime-entry-Deg0NfmB.d.cts → webmcp-runtime-entry-CXLjRt1k.d.cts} +1 -1
  84. package/dist/{webmcp-runtime-entry-Deg0NfmB.d.ts → webmcp-runtime-entry-CXLjRt1k.d.ts} +1 -1
  85. package/dist/webmcp-runtime.d.cts +1 -1
  86. package/dist/webmcp-runtime.d.ts +1 -1
  87. package/dist/widget.css +1 -1
  88. package/package.json +1 -1
  89. package/src/client-approve.test.ts +17 -1
  90. package/src/client-resume.ts +15 -3
  91. package/src/client.interrupt.test.ts +21 -0
  92. package/src/client.ts +24 -4
  93. package/src/components/activity-row.ts +3 -2
  94. package/src/components/approval-actions.test.ts +8 -0
  95. package/src/components/approval-actions.ts +6 -2
  96. package/src/components/approval-bubble.test.ts +14 -0
  97. package/src/components/approval-bubble.ts +8 -1
  98. package/src/components/tool-bubble.ts +8 -5
  99. package/src/generated/runtype-openapi-contract.ts +1 -1
  100. package/src/resume-dedupe-local-only.test.ts +273 -0
  101. package/src/runtime/persist-state.test.ts +86 -0
  102. package/src/session-actions.ts +20 -6
  103. package/src/session-reconnect.ts +18 -1
  104. package/src/session.restored-browser-tools.test.ts +272 -0
  105. package/src/session.ts +176 -29
  106. package/src/session.voice.test.ts +169 -0
  107. package/src/styles/widget.css +4 -2
  108. package/src/types.ts +37 -2
  109. package/src/ui.restored-browser-tools.test.ts +128 -0
  110. package/src/ui.ts +32 -18
  111. package/src/utils/formatting.test.ts +9 -1
  112. package/src/utils/formatting.ts +4 -0
  113. package/src/utils/local-only-message.ts +15 -0
  114. package/src/utils/restored-browser-state.ts +50 -0
  115. package/src/utils/storage.ts +12 -1
  116. package/src/utils/voice-prior-tool-results.ts +37 -0
  117. package/src/voice/runtype-voice-provider.ts +13 -8
  118. package/src/voice/session-voice-wiring.ts +1 -2
  119. package/src/voice/voice-delegation.ts +10 -3
  120. package/src/voice/voice.test.ts +38 -2
  121. package/dist/chunk-B6zZsT6F.js +0 -1
  122. package/dist/chunk-CIVsNcrk.js +0 -1
  123. package/dist/chunk-CKdlNyzM.js +0 -9
  124. package/dist/chunk-DbhxjyOB.js +0 -4
  125. package/dist/chunk-DsdqLStH.js +0 -1
  126. package/dist/chunk-GIqbL2Eg.js +0 -1
package/dist/index.cjs CHANGED
@@ -1,27 +1,27 @@
1
- Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,o)=>(o=n==null?{}:e(i(n)),c(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));let u=require("marked"),d=require("dompurify");d=l(d,1);let f=require("lucide"),p=require("partial-json"),m=require("idiomorph");var h,g=o((()=>{h=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,r=null,i=null,a=null;return{setLoader:e=>{r=e,n&&(i=null,a=null)},load:()=>i?Promise.resolve(i):a||(a=(r??t)().then(e=>(i=e,e)).catch(e=>{throw a=null,e}),a),provide:e=>{i=e},getSync:()=>i}}})),_=/* @__PURE__ */ s({DOMPurify:()=>d.default,Marked:()=>u.Marked}),v=o((()=>{}));g();const{setLoader:y,load:b,provide:x,getSync:S}=h({fallbackImport:()=>Promise.resolve().then(()=>(v(),_))}),C=/* @__PURE__ */ new Set,w=()=>{let e=[...C];C.clear();for(let t of e)try{t()}catch{}},T=()=>{let e=S();return e?Promise.resolve(e):b().then(e=>(w(),e))},E=e=>S()?()=>{}:(C.add(e),()=>{C.delete(e)}),D=e=>{x(e),w()},O=S;D({Marked:u.Marked,DOMPurify:d.default});const ee={user:f.User,mail:f.Mail,phone:f.Phone,calendar:f.Calendar,clock:f.Clock,building:f.Building,"map-pin":f.MapPin,lock:f.Lock,key:f.Key,"credit-card":f.CreditCard,hash:f.Hash,globe:f.Globe,link:f.Link,"circle-check":f.CircleCheck,"circle-x":f.CircleX,"triangle-alert":f.TriangleAlert,info:f.Info,ban:f.Ban,shield:f.Shield,house:f.House,"pen-line":f.PenLine,save:f.Save,share:f.Share,funnel:f.Funnel,settings:f.Settings,"rotate-cw":f.RotateCw,"shopping-cart":f.ShoppingCart,"shopping-bag":f.ShoppingBag,package:f.Package,truck:f.Truck,tag:f.Tag,gift:f.Gift,receipt:f.Receipt,wallet:f.Wallet,store:f.Store,"dollar-sign":f.DollarSign,percent:f.Percent,play:f.Play,pause:f.Pause,"volume-x":f.VolumeX,camera:f.Camera,image:f.Image,film:f.Film,headphones:f.Headphones,"message-circle":f.MessageCircle,bell:f.Bell,heart:f.Heart,"eye-off":f.EyeOff,bookmark:f.Bookmark,"calendar-days":f.CalendarDays,timer:f.Timer,folder:f.Folder,"folder-open":f.FolderOpen,files:f.Files,"chart-column":f.ChartColumn,sparkles:f.Sparkles,zap:f.Zap,sun:f.Sun,moon:f.Moon,flag:f.Flag,lightbulb:f.Lightbulb,monitor:f.Monitor,smartphone:f.Smartphone};var k,A=o((()=>{k=(e,t=24,n=`currentColor`,r=2)=>{if(!Array.isArray(e))return null;let i=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return i.setAttribute(`width`,String(t)),i.setAttribute(`height`,String(t)),i.setAttribute(`viewBox`,`0 0 24 24`),i.setAttribute(`fill`,`none`),i.setAttribute(`stroke`,n),i.setAttribute(`stroke-width`,String(r)),i.setAttribute(`stroke-linecap`,`round`),i.setAttribute(`stroke-linejoin`,`round`),i.setAttribute(`aria-hidden`,`true`),e.forEach(e=>{if(!Array.isArray(e)||e.length<2)return;let t=e[0],n=e[1];if(!n)return;let r=document.createElementNS(`http://www.w3.org/2000/svg`,t);Object.entries(n).forEach(([e,t])=>{e!==`stroke`&&r.setAttribute(e,String(t))}),i.appendChild(r)}),i}})),j,te,ne,re=o((()=>{g(),{setLoader:j,load:te}=h({fallbackImport:()=>import(`@runtypelabs/persona/icons-extra`)}),ne=te})),ie,M,N,P,ae,oe,se,ce,le,ue,de,fe,pe,me,F,I=o((()=>{A(),re(),ie={activity:f.Activity,"arrow-down":f.ArrowDown,"arrow-up":f.ArrowUp,"arrow-up-right":f.ArrowUpRight,bot:f.Bot,"chevron-down":f.ChevronDown,"chevron-up":f.ChevronUp,"chevron-right":f.ChevronRight,"chevron-left":f.ChevronLeft,check:f.Check,clipboard:f.Clipboard,"clipboard-copy":f.ClipboardCopy,"code-xml":f.CodeXml,copy:f.Copy,file:f.File,"file-code":f.FileCode,"file-spreadsheet":f.FileSpreadsheet,"file-text":f.FileText,"image-plus":f.ImagePlus,loader:f.Loader,"loader-circle":f.LoaderCircle,mic:f.Mic,paperclip:f.Paperclip,quote:f.Quote,"refresh-cw":f.RefreshCw,search:f.Search,send:f.Send,"shield-alert":f.ShieldAlert,"shield-check":f.ShieldCheck,"shield-x":f.ShieldX,square:f.Square,"thumbs-down":f.ThumbsDown,"thumbs-up":f.ThumbsUp,upload:f.Upload,"volume-2":f.Volume2,x:f.X,"at-sign":f.AtSign,"arrow-left":f.ArrowLeft,"arrow-right":f.ArrowRight,"external-link":f.ExternalLink,ellipsis:f.Ellipsis,"ellipsis-vertical":f.EllipsisVertical,menu:f.Menu,"panel-left":f.PanelLeft,plus:f.Plus,minus:f.Minus,pencil:f.Pencil,trash:f.Trash,"trash-2":f.Trash2,download:f.Download,maximize:f.Maximize,minimize:f.Minimize,"message-square":f.MessageSquare,star:f.Star,eye:f.Eye,history:f.History},M=/* @__PURE__ */ `user.mail.phone.calendar.clock.building.map-pin.lock.key.credit-card.hash.globe.link.circle-check.circle-x.triangle-alert.info.ban.shield.house.pen-line.save.share.funnel.settings.rotate-cw.shopping-cart.shopping-bag.package.truck.tag.gift.receipt.wallet.store.dollar-sign.percent.play.pause.volume-x.camera.image.film.headphones.message-circle.bell.heart.eye-off.bookmark.calendar-days.timer.folder.folder-open.files.chart-column.sparkles.zap.sun.moon.flag.lightbulb.monitor.smartphone`.split(`.`),N=new Map(Object.entries(ie)),P=/* @__PURE__ */ new Set,ae=!1,oe=/* @__PURE__ */ new Set,se=e=>{let t=[...oe];e&&oe.clear();for(let e of t)try{e()}catch{}},ce=e=>ae?()=>{}:(oe.add(e),()=>{oe.delete(e)}),le=()=>{let e=0;for(let t of[...P]){let n=N.get(t.name);if(!n)continue;P.delete(t),e++;let r=k(n,t.size,t.color,t.strokeWidth);if(r)for(t.el.removeAttribute(`data-persona-icon-pending`);r.firstChild;)t.el.appendChild(r.firstChild)}return e},ue=e=>{for(let[t,n]of Object.entries(e))N.set(t,n);le()>0&&!ae&&se(!1)},de=e=>{if(!ae){for(let[t,n]of Object.entries(e))N.has(t)||N.set(t,n);ae=!0,le(),se(!0)}},fe=!1,pe=()=>{ne().then(e=>{if(!ae){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))N.has(t)||N.set(t,n);ae=!0,le(),se(!0)}}).catch(e=>{fe=!0,console.warn(`[Persona] Failed to load the icons-extra chunk`,e)})},me=(e,t,n)=>{let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`width`,String(e)),r.setAttribute(`height`,String(e)),r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,t),r.setAttribute(`stroke-width`,String(n)),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`data-persona-icon-pending`,`true`),r},F=(e,t=24,n=`currentColor`,r=2)=>{let i=N.get(e);if(i)return k(i,t,n,r);if(M.includes(e)){fe&&=!1;let i=me(t,n,r);if(P.size>=500){let e=P.values().next().value;e&&P.delete(e)}return P.add({el:i,name:e,size:t,color:n,strokeWidth:r}),pe(),i}return console.warn(`Lucide icon "${e}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null}}));I(),de(ee);function he(e){if(e.length===0)return`0:empty`;let t=e.map(e=>[e.name,e.description??``,e.parametersSchema?JSON.stringify(e.parametersSchema):``,e.origin??``,e.annotations?JSON.stringify(e.annotations):``].join(``)).sort();return`${e.length}:${_e(t.join(``))}`}function ge(e,t){let n=3735928559^t,r=1103547991^t;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function _e(e){return`${ge(e,0).toString(36)}.${ge(e,2654435761).toString(36)}`}var ve,ye,L,be,R,z,xe,Se,Ce=o((()=>{ve=`webmcp:`,ye=/* @__PURE__ */ new Map,L=e=>{ye.clear();for(let t of e){let e=t.title?.trim();e&&ye.set(t.name,e)}},be=e=>ye.get(z(e)),R=null,z=e=>e.startsWith(`webmcp:`)?e.slice(7):e,xe=e=>e.startsWith(ve),Se=()=>R?R():import(`@mcp-b/webmcp-polyfill`)}));function we(e){return e===`card`?`collapsed`:e}function Te(e){return e.split(`;`,1)[0].trim().toLowerCase()}function Ee(e,t){if(!e)return;let n=Object.entries(e);for(let[e,r]of n)if(Te(e)===t)return{mode:we(r),selector:Te(e)};let r=`${t.split(`/`,1)[0]}/*`;for(let[e,t]of n)if(Te(e)===r)return{mode:we(t),selector:r}}function De(e,t){let n=e?.display,r=typeof n==`string`?{default:n}:n??{};if(t.file&&r.files){if(typeof r.files==`string`)return{mode:we(r.files),matchedBy:{type:`files`}};let e=t.file.mimeType?Te(t.file.mimeType):void 0,n=e?Ee(r.files.byMediaType,e):void 0;if(e&&n)return{mode:n.mode,matchedBy:{type:`mediaType`,mediaType:e,selector:n.selector}};if(r.files.default)return{mode:we(r.files.default),matchedBy:{type:`files`}}}let i=r.byKind?.[t.artifactType];if(i)return{mode:we(i),matchedBy:{type:`kind`,kind:t.artifactType,configuredBy:`byKind`}};let a=r.byType?.[t.artifactType];if(a)return{mode:we(a),matchedBy:{type:`kind`,kind:t.artifactType,configuredBy:`byType`}};let o=t.presentation?.preferredMode;return o?{mode:we(o),matchedBy:{type:`preferredMode`}}:r.default?{mode:we(r.default),matchedBy:{type:`default`}}:{mode:`panel`,matchedBy:{type:`personaDefault`}}}function Oe(e,t){return De(e,t).mode}function ke(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 Ae=o((()=>{})),je,Me,Ne,Pe,Fe,Ie,Le,Re,ze,Be,Ve,He,Ue,We,Ge,Ke,qe,Je,Ye,Xe,Ze=o((()=>{je=e=>e.replace(/\\n/g,`
2
- `).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`),Me=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)}},Ne=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs===void 0?Math.max(0,t-n):e.durationMs)/1e3;return r<.1?`Thought for <0.1 seconds`:`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,``)} seconds`},Pe=e=>e.status===`complete`?Ne(e):e.status===`pending`?`Waiting`:``,Fe=(e,t)=>{let n=t?.durationMs??15e3,r=t?.chars??1200;return typeof e.durationMs==`number`?e.durationMs<n:(e.chunks??[]).join(``).length<r},Ie=e=>{let t=(typeof e.duration==`number`?e.duration:typeof e.durationMs==`number`?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return t<.1?`Used tool for <0.1 seconds`:`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,``)} seconds`},Le=e=>e.status===`complete`?Ie(e):`Using tool...`,Re=e=>{let t=e/1e3;return t<.1?`<0.1s`:t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,``)}s`},ze=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 Re(t)},Be=e=>{let t=e.durationMs===void 0?Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())):e.durationMs;return Re(t)},Ve=(e,t,n)=>{if(!t)return n;let r=e.name?.trim()||`tool`,i=ze(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,i)},He=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],i=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,o;for(;(o=i.exec(n))!==null;)o.index>a&&Ue(r,n.slice(a,o.index),[]),o[1]===void 0?o[2]===void 0?o[3]!==void 0&&Ue(r,o[3],[`dim`]):Ue(r,o[2],[`italic`]):Ue(r,o[1],[`bold`]),a=o.index+o[0].length;return a<n.length&&Ue(r,n.slice(a),[]),r},Ue=(e,t,n)=>{let r=t.split(`{duration}`);for(let t=0;t<r.length;t++)r[t]&&e.push({text:r[t],styles:n}),t<r.length-1&&e.push({text:`{duration}`,styles:n,isDuration:!0})},We=()=>{let e=null,t=0,n=e=>{let t=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/);if(t&&t[1])try{return t[1].replace(/\\n/g,`
1
+ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,o)=>(o=n==null?{}:e(i(n)),c(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));let u=require("marked"),d=require("dompurify");d=l(d,1);let f=require("lucide"),p=require("partial-json"),m=require("idiomorph");var h,g=o((()=>{h=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,r=null,i=null,a=null;return{setLoader:e=>{r=e,n&&(i=null,a=null)},load:()=>i?Promise.resolve(i):a||(a=(r??t)().then(e=>(i=e,e)).catch(e=>{throw a=null,e}),a),provide:e=>{i=e},getSync:()=>i}}})),_=/* @__PURE__ */ s({DOMPurify:()=>d.default,Marked:()=>u.Marked}),v=o((()=>{}));g();const{setLoader:y,load:b,provide:x,getSync:S}=h({fallbackImport:()=>Promise.resolve().then(()=>(v(),_))}),C=/* @__PURE__ */ new Set,w=()=>{let e=[...C];C.clear();for(let t of e)try{t()}catch{}},T=()=>{let e=S();return e?Promise.resolve(e):b().then(e=>(w(),e))},E=e=>S()?()=>{}:(C.add(e),()=>{C.delete(e)}),D=e=>{x(e),w()},O=S;D({Marked:u.Marked,DOMPurify:d.default});const ee={user:f.User,mail:f.Mail,phone:f.Phone,calendar:f.Calendar,clock:f.Clock,building:f.Building,"map-pin":f.MapPin,lock:f.Lock,key:f.Key,"credit-card":f.CreditCard,hash:f.Hash,globe:f.Globe,link:f.Link,"circle-check":f.CircleCheck,"circle-x":f.CircleX,"triangle-alert":f.TriangleAlert,info:f.Info,ban:f.Ban,shield:f.Shield,house:f.House,"pen-line":f.PenLine,save:f.Save,share:f.Share,funnel:f.Funnel,settings:f.Settings,"rotate-cw":f.RotateCw,"shopping-cart":f.ShoppingCart,"shopping-bag":f.ShoppingBag,package:f.Package,truck:f.Truck,tag:f.Tag,gift:f.Gift,receipt:f.Receipt,wallet:f.Wallet,store:f.Store,"dollar-sign":f.DollarSign,percent:f.Percent,play:f.Play,pause:f.Pause,"volume-x":f.VolumeX,camera:f.Camera,image:f.Image,film:f.Film,headphones:f.Headphones,"message-circle":f.MessageCircle,bell:f.Bell,heart:f.Heart,"eye-off":f.EyeOff,bookmark:f.Bookmark,"calendar-days":f.CalendarDays,timer:f.Timer,folder:f.Folder,"folder-open":f.FolderOpen,files:f.Files,"chart-column":f.ChartColumn,sparkles:f.Sparkles,zap:f.Zap,sun:f.Sun,moon:f.Moon,flag:f.Flag,lightbulb:f.Lightbulb,monitor:f.Monitor,smartphone:f.Smartphone};var k,A=o((()=>{k=(e,t=24,n=`currentColor`,r=2)=>{if(!Array.isArray(e))return null;let i=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return i.setAttribute(`width`,String(t)),i.setAttribute(`height`,String(t)),i.setAttribute(`viewBox`,`0 0 24 24`),i.setAttribute(`fill`,`none`),i.setAttribute(`stroke`,n),i.setAttribute(`stroke-width`,String(r)),i.setAttribute(`stroke-linecap`,`round`),i.setAttribute(`stroke-linejoin`,`round`),i.setAttribute(`aria-hidden`,`true`),e.forEach(e=>{if(!Array.isArray(e)||e.length<2)return;let t=e[0],n=e[1];if(!n)return;let r=document.createElementNS(`http://www.w3.org/2000/svg`,t);Object.entries(n).forEach(([e,t])=>{e!==`stroke`&&r.setAttribute(e,String(t))}),i.appendChild(r)}),i}})),te,ne,re,ie=o((()=>{g(),{setLoader:te,load:ne}=h({fallbackImport:()=>import(`@runtypelabs/persona/icons-extra`)}),re=ne})),ae,j,M,N,oe,se,ce,le,ue,de,fe,pe,me,he,P,F=o((()=>{A(),ie(),ae={activity:f.Activity,"arrow-down":f.ArrowDown,"arrow-up":f.ArrowUp,"arrow-up-right":f.ArrowUpRight,bot:f.Bot,"chevron-down":f.ChevronDown,"chevron-up":f.ChevronUp,"chevron-right":f.ChevronRight,"chevron-left":f.ChevronLeft,check:f.Check,clipboard:f.Clipboard,"clipboard-copy":f.ClipboardCopy,"code-xml":f.CodeXml,copy:f.Copy,file:f.File,"file-code":f.FileCode,"file-spreadsheet":f.FileSpreadsheet,"file-text":f.FileText,"image-plus":f.ImagePlus,loader:f.Loader,"loader-circle":f.LoaderCircle,mic:f.Mic,paperclip:f.Paperclip,quote:f.Quote,"refresh-cw":f.RefreshCw,search:f.Search,send:f.Send,"shield-alert":f.ShieldAlert,"shield-check":f.ShieldCheck,"shield-x":f.ShieldX,square:f.Square,"thumbs-down":f.ThumbsDown,"thumbs-up":f.ThumbsUp,upload:f.Upload,"volume-2":f.Volume2,x:f.X,"at-sign":f.AtSign,"arrow-left":f.ArrowLeft,"arrow-right":f.ArrowRight,"external-link":f.ExternalLink,ellipsis:f.Ellipsis,"ellipsis-vertical":f.EllipsisVertical,menu:f.Menu,"panel-left":f.PanelLeft,plus:f.Plus,minus:f.Minus,pencil:f.Pencil,trash:f.Trash,"trash-2":f.Trash2,download:f.Download,maximize:f.Maximize,minimize:f.Minimize,"message-square":f.MessageSquare,star:f.Star,eye:f.Eye,history:f.History},j=/* @__PURE__ */ `user.mail.phone.calendar.clock.building.map-pin.lock.key.credit-card.hash.globe.link.circle-check.circle-x.triangle-alert.info.ban.shield.house.pen-line.save.share.funnel.settings.rotate-cw.shopping-cart.shopping-bag.package.truck.tag.gift.receipt.wallet.store.dollar-sign.percent.play.pause.volume-x.camera.image.film.headphones.message-circle.bell.heart.eye-off.bookmark.calendar-days.timer.folder.folder-open.files.chart-column.sparkles.zap.sun.moon.flag.lightbulb.monitor.smartphone`.split(`.`),M=new Map(Object.entries(ae)),N=/* @__PURE__ */ new Set,oe=!1,se=/* @__PURE__ */ new Set,ce=e=>{let t=[...se];e&&se.clear();for(let e of t)try{e()}catch{}},le=e=>oe?()=>{}:(se.add(e),()=>{se.delete(e)}),ue=()=>{let e=0;for(let t of[...N]){let n=M.get(t.name);if(!n)continue;N.delete(t),e++;let r=k(n,t.size,t.color,t.strokeWidth);if(r)for(t.el.removeAttribute(`data-persona-icon-pending`);r.firstChild;)t.el.appendChild(r.firstChild)}return e},de=e=>{for(let[t,n]of Object.entries(e))M.set(t,n);ue()>0&&!oe&&ce(!1)},fe=e=>{if(!oe){for(let[t,n]of Object.entries(e))M.has(t)||M.set(t,n);oe=!0,ue(),ce(!0)}},pe=!1,me=()=>{re().then(e=>{if(!oe){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))M.has(t)||M.set(t,n);oe=!0,ue(),ce(!0)}}).catch(e=>{pe=!0,console.warn(`[Persona] Failed to load the icons-extra chunk`,e)})},he=(e,t,n)=>{let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`width`,String(e)),r.setAttribute(`height`,String(e)),r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,t),r.setAttribute(`stroke-width`,String(n)),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`data-persona-icon-pending`,`true`),r},P=(e,t=24,n=`currentColor`,r=2)=>{let i=M.get(e);if(i)return k(i,t,n,r);if(j.includes(e)){pe&&=!1;let i=he(t,n,r);if(N.size>=500){let e=N.values().next().value;e&&N.delete(e)}return N.add({el:i,name:e,size:t,color:n,strokeWidth:r}),me(),i}return console.warn(`Lucide icon "${e}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null}}));F(),fe(ee);function ge(e){if(e.length===0)return`0:empty`;let t=e.map(e=>[e.name,e.description??``,e.parametersSchema?JSON.stringify(e.parametersSchema):``,e.origin??``,e.annotations?JSON.stringify(e.annotations):``].join(``)).sort();return`${e.length}:${ve(t.join(``))}`}function _e(e,t){let n=3735928559^t,r=1103547991^t;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function ve(e){return`${_e(e,0).toString(36)}.${_e(e,2654435761).toString(36)}`}var ye,be,I,xe,L,R,Se,Ce,we=o((()=>{ye=`webmcp:`,be=/* @__PURE__ */ new Map,I=e=>{be.clear();for(let t of e){let e=t.title?.trim();e&&be.set(t.name,e)}},xe=e=>be.get(R(e)),L=null,R=e=>e.startsWith(`webmcp:`)?e.slice(7):e,Se=e=>e.startsWith(ye),Ce=()=>L?L():import(`@mcp-b/webmcp-polyfill`)}));function Te(e){return e===`card`?`collapsed`:e}function Ee(e){return e.split(`;`,1)[0].trim().toLowerCase()}function De(e,t){if(!e)return;let n=Object.entries(e);for(let[e,r]of n)if(Ee(e)===t)return{mode:Te(r),selector:Ee(e)};let r=`${t.split(`/`,1)[0]}/*`;for(let[e,t]of n)if(Ee(e)===r)return{mode:Te(t),selector:r}}function Oe(e,t){let n=e?.display,r=typeof n==`string`?{default:n}:n??{};if(t.file&&r.files){if(typeof r.files==`string`)return{mode:Te(r.files),matchedBy:{type:`files`}};let e=t.file.mimeType?Ee(t.file.mimeType):void 0,n=e?De(r.files.byMediaType,e):void 0;if(e&&n)return{mode:n.mode,matchedBy:{type:`mediaType`,mediaType:e,selector:n.selector}};if(r.files.default)return{mode:Te(r.files.default),matchedBy:{type:`files`}}}let i=r.byKind?.[t.artifactType];if(i)return{mode:Te(i),matchedBy:{type:`kind`,kind:t.artifactType,configuredBy:`byKind`}};let a=r.byType?.[t.artifactType];if(a)return{mode:Te(a),matchedBy:{type:`kind`,kind:t.artifactType,configuredBy:`byType`}};let o=t.presentation?.preferredMode;return o?{mode:Te(o),matchedBy:{type:`preferredMode`}}:r.default?{mode:Te(r.default),matchedBy:{type:`default`}}:{mode:`panel`,matchedBy:{type:`personaDefault`}}}function ke(e,t){return Oe(e,t).mode}function Ae(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 je=o((()=>{})),Me,Ne,Pe,Fe,Ie,Le,Re,ze,Be,Ve,He,Ue,We,Ge,Ke,qe,Je,Ye,Xe,Ze,Qe=o((()=>{Me=e=>e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`),Ne=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)}},Pe=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs===void 0?Math.max(0,t-n):e.durationMs)/1e3;return r<.1?`Thought for <0.1 seconds`:`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,``)} seconds`},Fe=e=>e.status===`complete`?Pe(e):e.status===`pending`?`Waiting`:``,Ie=(e,t)=>{let n=t?.durationMs??15e3,r=t?.chars??1200;return typeof e.durationMs==`number`?e.durationMs<n:(e.chunks??[]).join(``).length<r},Le=e=>{let t=(typeof e.duration==`number`?e.duration:typeof e.durationMs==`number`?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return t<.1?`Used tool for <0.1 seconds`:`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,``)} seconds`},Re=e=>e.status===`complete`?Le(e):`Using tool...`,ze=e=>{let t=e/1e3;return t<.1?`<0.1s`:t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,``)}s`},Be=e=>{if(e.interrupted&&e.duration===void 0&&e.durationMs===void 0&&(e.startedAt===void 0||e.completedAt===void 0))return``;let t=typeof e.duration==`number`?e.duration:typeof e.durationMs==`number`?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return ze(t)},Ve=e=>{let t=e.durationMs===void 0?Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())):e.durationMs;return ze(t)},He=(e,t,n)=>{if(!t)return n;let r=e.name?.trim()||`tool`,i=Be(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,i)},Ue=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],i=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,o;for(;(o=i.exec(n))!==null;)o.index>a&&We(r,n.slice(a,o.index),[]),o[1]===void 0?o[2]===void 0?o[3]!==void 0&&We(r,o[3],[`dim`]):We(r,o[2],[`italic`]):We(r,o[1],[`bold`]),a=o.index+o[0].length;return a<n.length&&We(r,n.slice(a),[]),r},We=(e,t,n)=>{let r=t.split(`{duration}`);for(let t=0;t<r.length;t++)r[t]&&e.push({text:r[t],styles:n}),t<r.length-1&&e.push({text:`{duration}`,styles:n,isDuration:!0})},Ge=()=>{let e=null,t=0,n=e=>{let t=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/);if(t&&t[1])try{return t[1].replace(/\\n/g,`
3
3
  `).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`)}catch{return t[1]}let n=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/);if(n&&n[1])try{return n[1].replace(/\\n/g,`
4
- `).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`)}catch{return n[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e===null?null:{text:e,raw:r};let i=r.trim();if(!i.startsWith(`{`)&&!i.startsWith(`[`))return null;let a=n(r);return a!==null&&(e=a),t=r.length,e===null?null:{text:e,raw:r}},close:async()=>{}}},Ge=e=>{try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.text==`string`)return t.text}catch{return null}return null},Ke=()=>{let e={processChunk:e=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},qe=()=>{let e=We();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)}},Je=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith(`{`)&&!r.startsWith(`[`))return null;if(n.length<=t)return e!==null||e===``?{text:e||``,raw:n}:null;try{let t=(0,p.parse)(n,p.STR|p.OBJ);t&&typeof t==`object`&&(t.component&&typeof t.component==`string`?e=typeof t.text==`string`?je(t.text):``:t.type===`init`&&t.form?e=``:typeof t.text==`string`&&(e=je(t.text)))}catch{}return t=n.length,e===null?null:{text:e,raw:n}},close:()=>{}}},Ye=e=>{let t=null,n=0,r=e||(e=>{if(!e||typeof e!=`object`)return null;let t=e=>typeof e==`string`?je(e):null;if(e.component&&typeof e.component==`string`)return typeof e.text==`string`?je(e.text):``;if(e.type===`init`&&e.form)return``;if(e.action)switch(e.action){case`nav_then_click`:return t(e.on_load_text)||t(e.text)||null;case`message`:case`message_and_click`:case`checkout`:return t(e.text)||null;default:return t(e.text)||t(e.display_text)||t(e.message)||null}return t(e.text)||t(e.display_text)||t(e.message)||t(e.content)||null});return{getExtractedText:()=>t,processChunk:e=>{let i=e.trim();if(!i.startsWith(`{`)&&!i.startsWith(`[`))return null;if(e.length<=n)return t===null?null:{text:t,raw:e};try{let n=(0,p.parse)(e,p.STR|p.OBJ),i=r(n);i!==null&&(t=i)}catch{}return n=e.length,{text:t||``,raw:e}},close:()=>{}}},Xe=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith(`<`))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}}})),B,V,Qe,H=o((()=>{B=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},V=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[e,n]of Object.entries(t.attrs))r.setAttribute(e,n);if(t.style){let e=r.style,n=t.style;for(let t of Object.keys(n)){let r=n[t];r!=null&&(e[t]=r)}}let i=n.filter(e=>e!=null);return i.length>0&&r.append(...i),r},Qe=(...e)=>e.filter(Boolean).join(` `)})),$e,et,tt,nt,rt,it,U,at,ot,W,G,K,st,ct,lt,q,J,ut,dt,ft,pt,mt,ht,gt,_t,vt,yt,Y,bt,xt,St,Ct,wt,Tt,Et,Dt,Ot,kt,X,At,jt,Mt,Nt,Pt,Ft,It,Lt,Rt,zt,Bt,Vt,Ht,Ut,Wt,Gt=o((()=>{H(),$e=`ask_user_question`,et=`data-persona-ask-sheet-for`,tt=`Other`,nt=`Other…`,rt=`Type your own answer here`,it=`Send`,U=`Next`,at=`Back`,ot=`Submit all`,W=`Skip`,G=3,K=`data-ask-current-index`,st=`data-ask-question-count`,ct=`data-ask-answers`,lt=`data-ask-grouped`,q=`data-ask-layout`,J=e=>e.layout===`pills`?`pills`:`rows`,ut=e=>e.getAttribute(`data-ask-layout`)===`pills`?`pills`:`rows`,dt=!1,ft=e=>e.replace(/["\\]/g,`\\$&`),pt=e=>e.variant===`tool`&&!!e.toolCall&&e.toolCall.name===`ask_user_question`,mt=e=>e?.features?.askUserQuestion??{},ht=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status===`complete`;if(t.args&&typeof t.args==`object`)return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let e=r.join(``),t=(0,p.parse)(e,p.STR|p.OBJ|p.ARR);if(t&&typeof t==`object`)return{payload:t,complete:n}}catch{}return{payload:null,complete:n}},gt=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!dt&&(dt=!0,typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},_t=e=>gt(e)[0]??null,vt=(e,t)=>gt(e)[t]??null,yt=(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))},Y=(e,t,n)=>{if(e!==`rows`)return null;let r=B(`span`,`persona-ask-row-affordance`);if(r.setAttribute(`aria-hidden`,`true`),t){let e=B(`span`,`persona-ask-row-check`);r.appendChild(e)}else{let e=B(`span`,`persona-ask-row-badge`);e.textContent=String(n+1),r.appendChild(e)}return r},bt=(e,t,n,r)=>{let i=B(`button`,n===`rows`?`persona-ask-pill persona-ask-row persona-pointer-events-auto`:`persona-ask-pill persona-pointer-events-auto`);if(i.type=`button`,i.setAttribute(`role`,r?`checkbox`:`button`),i.setAttribute(`aria-pressed`,`false`),i.setAttribute(`data-ask-user-action`,`pick`),i.setAttribute(`data-option-index`,String(t)),i.setAttribute(`data-option-label`,e.label),n===`rows`){let a=B(`span`,`persona-ask-row-content`),o=B(`span`,`persona-ask-row-label`);if(o.textContent=e.label,a.appendChild(o),e.description){let t=B(`span`,`persona-ask-row-description`);t.textContent=e.description,a.appendChild(t)}i.appendChild(a);let s=Y(n,r,t);s&&i.appendChild(s)}else i.textContent=e.label,e.description&&(i.title=e.description);return i},xt=e=>{let t=B(`span`,e===`rows`?`persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none`:`persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none`);return t.setAttribute(`aria-hidden`,`true`),t},St=(e,t,n,r)=>{let i=B(`div`,r===`rows`?`persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2`:`persona-ask-pills persona-flex persona-flex-wrap persona-gap-2`);i.setAttribute(`role`,`group`),i.setAttribute(`data-ask-pill-list`,`true`);let a=!!e?.multiSelect,o=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&typeof e.label==`string`&&e.label.length>0);if(o.length===0&&!n){for(let e=0;e<G;e++)i.appendChild(xt(r));return i}if(o.forEach((e,t)=>{i.appendChild(bt(e,t,r,a))}),e?.allowFreeText!==!1){let e=r===`rows`?tt:nt;if(r===`rows`){let n=B(`div`,`persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto`);n.setAttribute(`data-ask-user-action`,`focus-free-text`),n.setAttribute(`data-option-index`,String(o.length)),n.setAttribute(`data-ask-other-row`,`true`);let s=B(`span`,`persona-ask-row-content`),c=document.createElement(`input`);c.type=`text`,c.className=`persona-ask-row-input persona-flex-1 persona-pointer-events-auto`,c.placeholder=t.freeTextPlaceholder??rt,c.setAttribute(`data-ask-free-text-input`,`true`),c.setAttribute(`aria-label`,t.freeTextLabel??e),s.appendChild(c),n.appendChild(s);let l=Y(r,a,o.length);l&&n.appendChild(l),i.appendChild(n)}else{let n=B(`button`,`persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto`);n.type=`button`,n.setAttribute(`data-ask-user-action`,`open-free-text`),n.textContent=t.freeTextLabel??e,i.appendChild(n)}}return i},Ct=(e,t)=>{let n=B(`div`,t===`rows`?`persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2`:`persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2`);n.setAttribute(`data-ask-free-text-row`,`true`);let r=document.createElement(`input`);if(r.type=`text`,r.className=`persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto`,r.placeholder=e.freeTextPlaceholder??rt,r.setAttribute(`data-ask-free-text-input`,`true`),n.appendChild(r),t!==`rows`){let t=B(`button`,`persona-ask-free-text-submit persona-pointer-events-auto`);t.type=`button`,t.textContent=e.submitLabel??it,t.setAttribute(`data-ask-user-action`,`submit-free-text`),n.appendChild(t)}return n},wt=e=>{let t=B(`div`,`persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2`);t.setAttribute(`data-ask-multi-actions`,`true`);let n=B(`button`,`persona-ask-multi-submit persona-pointer-events-auto`);return n.type=`button`,n.textContent=e.submitLabel??it,n.setAttribute(`data-ask-user-action`,`submit-multi`),n.disabled=!0,t.appendChild(n),t},Tt=(e,t,n)=>{let r=B(`div`,`persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2`);r.setAttribute(`data-ask-nav-row`,`true`);let i=B(`button`,`persona-ask-nav-back persona-pointer-events-auto`);i.type=`button`,i.textContent=n.backLabel??at,i.setAttribute(`data-ask-user-action`,`back`),i.disabled=e===0,r.appendChild(i);let a=B(`div`,`persona-ask-nav-right persona-flex persona-items-center persona-gap-2`),o=B(`button`,`persona-ask-nav-skip persona-pointer-events-auto`);o.type=`button`,o.textContent=n.skipLabel??W,o.setAttribute(`data-ask-user-action`,`skip`),a.appendChild(o);let s=B(`button`,`persona-ask-nav-next persona-pointer-events-auto`);s.type=`button`;let c=e===t-1;return s.textContent=c?n.submitAllLabel??ot:n.nextLabel??U,s.setAttribute(`data-ask-user-action`,c?`submit-all`:`next`),s.disabled=!0,a.appendChild(s),r.appendChild(a),r},Et=e=>{let t=e.getAttribute(ct);if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e==`object`?e:{}}catch{return{}}},Dt=(e,t)=>{e.setAttribute(ct,JSON.stringify(t))},Ot=e=>{let t=Number(e.getAttribute(`data-ask-current-index`)??`0`);return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},kt=(e,t)=>{e.setAttribute(K,String(Math.max(0,Math.floor(t))))},X=e=>{let t=Number(e.getAttribute(`data-ask-question-count`)??`1`);return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},At=e=>e.getAttribute(lt)===`true`,jt=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!=`object`)return{};let r={};return t.forEach((e,t)=>{let i=typeof e?.question==`string`?e.question:``;if(i&&Object.prototype.hasOwnProperty.call(n,i)){let e=n[i];(typeof e==`string`||Array.isArray(e))&&(r[t]=e)}}),r},Mt=(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)))},Nt=(e,t)=>{let{payload:n}=ht(t),r=gt(n),i=Et(e),a={},o=/* @__PURE__ */ new Set;return r.forEach((e,t)=>{let n=typeof e?.question==`string`?e.question:``;n&&(o.has(n)&&typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${n}"; later answer wins.`),o.add(n),Object.prototype.hasOwnProperty.call(i,t)&&(a[n]=i[t]))}),a},Pt=e=>{let t=Et(e)[Ot(e)],n=/* @__PURE__ */ new Set;typeof t==`string`?n.add(t):Array.isArray(t)&&t.forEach(e=>n.add(e));let r=e.querySelectorAll(`[data-ask-user-action="pick"][data-option-label]`);r.forEach(e=>{let t=e.getAttribute(`data-option-label`)??``,r=n.has(t);e.setAttribute(`aria-pressed`,r?`true`:`false`),e.classList.toggle(`persona-ask-pill-selected`,r)});let i=new Set(Array.from(r).map(e=>e.getAttribute(`data-option-label`)??``)),a=e.querySelector(`[data-ask-free-text-input="true"]`);a&&(typeof t==`string`&&t.length>0&&!i.has(t)?(a.value=t,a.closest(`[data-ask-free-text-row="true"]`)?.classList.remove(`persona-hidden`)):a.value=``)},Ft=e=>{if(!At(e))return;let t=Et(e)[Ot(e)],n=typeof t==`string`&&t.length>0||Array.isArray(t)&&t.length>0,r=e.querySelector(`[data-ask-user-action="next"], [data-ask-user-action="submit-all"]`);r&&(r.disabled=!n);let i=e.querySelector(`[data-ask-user-action="submit-multi"]`);i&&(i.disabled=Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).length===0)},It=(e,t,n)=>{let r=mt(n),i=ut(e),{payload:a,complete:o}=ht(t),s=At(e),c=Ot(e),l=X(e),u=s?vt(a,c):_t(a),d=!!u?.multiSelect,f=e.querySelector(`[data-ask-step-inline="true"]`);f&&(f.textContent=s?`${c+1}/${l}`:``);let p=e.querySelector(`[data-ask-stepper="true"]`);p&&p.remove();let m=e.querySelector(`[data-ask-question="true"]`);if(m){let e=typeof u?.question==`string`?u.question:``;m.textContent=e,m.classList.toggle(`persona-ask-question-skeleton`,!e&&!o)}let h=e.querySelector(`[data-ask-pill-list="true"]`);if(h){let e=St(u,r,o,i);h.replaceWith(e)}if(i!==`rows`){let t=e.querySelector(`[data-ask-free-text-row="true"]`);t&&t.replaceWith(Ct(r,i))}let g=e.querySelector(`[data-ask-multi-actions="true"]`);!s&&d&&!g?e.appendChild(wt(r)):(!d||s)&&g&&g.remove(),e.setAttribute(`data-multi-select`,d?`true`:`false`);let _=e.querySelector(`[data-ask-nav-row="true"]`);if(s){let t=Tt(c,l,r);_?_.replaceWith(t):e.appendChild(t)}else _&&_.remove();Pt(e),Ft(e)},Lt=(e,t,n)=>{let r=mt(t),i=J(r),a=e.toolCall.id,o=gt(n),s=Math.max(1,o.length),c=s>1,l=jt(e,o),u=c?Mt(e,s):0,d=B(`div`,[`persona-ask-sheet`,`persona-ask-sheet--${i}`,`persona-pointer-events-auto`,`persona-ask-sheet-enter`].join(` `));d.setAttribute(et,a),d.setAttribute(`data-tool-call-id`,a),d.setAttribute(`data-message-id`,e.id),d.setAttribute(st,String(s)),d.setAttribute(K,String(u)),d.setAttribute(lt,c?`true`:`false`),d.setAttribute(q,i),Dt(d,l),d.setAttribute(`role`,`group`),d.setAttribute(`aria-label`,`Suggested answers`),r.slideInMs!==void 0&&d.style.setProperty(`--persona-ask-sheet-duration`,`${r.slideInMs}ms`),yt(d,r);let f=B(`div`,`persona-ask-sheet-header persona-flex persona-items-center persona-gap-3`),p=B(`div`,`persona-ask-sheet-question persona-flex-1`);p.setAttribute(`data-ask-question`,`true`),p.textContent=``,f.appendChild(p);let m=B(`span`,`persona-ask-sheet-step-inline`);m.setAttribute(`data-ask-step-inline`,`true`),m.textContent=``,f.appendChild(m),d.appendChild(f);let h=B(`div`,i===`rows`?`persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2`:`persona-ask-pills persona-flex persona-flex-wrap persona-gap-2`);return h.setAttribute(`data-ask-pill-list`,`true`),h.setAttribute(`role`,`group`),d.appendChild(h),i!==`rows`&&d.appendChild(Ct(r,i)),It(d,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>d.classList.remove(`persona-ask-sheet-enter`))}),d},Rt=(e,t,n)=>{let{payload:r}=ht(t),i=Math.max(1,gt(r).length);i>X(e)&&(e.setAttribute(st,String(i)),i>1&&!At(e)&&e.setAttribute(lt,`true`)),It(e,t,n)},zt=(e,t)=>{let n=B(`div`,`persona-ask-stub persona-inline-flex persona-items-center persona-gap-2`);n.id=`bubble-${e.id}`,n.setAttribute(`data-message-id`,e.id),n.setAttribute(`data-bubble-type`,`ask-user-question`);let r=mt(t);yt(n,r);let i=B(`span`,`persona-ask-stub-label`),{complete:a}=ht(e);return i.textContent=a?`Awaiting your response…`:`Preparing options…`,n.appendChild(i),n},Bt=(e,t,n)=>{if(!n||!pt(e)||mt(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${et}]`).forEach(e=>{e.getAttribute(et)!==r&&e.remove()});let i=n.querySelector(`[${et}="${ft(r)}"]`);if(i){Rt(i,e,t);return}let{payload:a}=ht(e),o=Lt(e,t,a);n.appendChild(o)},Vt=(e,t)=>{if(!e)return;let n=t?`[${et}="${ft(t)}"]`:`[${et}]`;e.querySelectorAll(n).forEach(e=>{e.classList.add(`persona-ask-sheet-leave`);let t=Number.parseInt(getComputedStyle(e).getPropertyValue(`--persona-ask-sheet-duration`)||`180`,10);setTimeout(()=>e.remove(),Number.isFinite(t)?t:180)})},Ht=e=>Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).map(e=>e.getAttribute(`data-option-label`)).filter(e=>typeof e==`string`&&e.length>0),Ut=(e,t)=>{let n=Et(e),r=Ot(e);typeof t==`string`&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Dt(e,n),Pt(e),Ft(e)},Wt=(e,t,n,r)=>{let i=X(e),a=Math.max(0,Math.min(i-1,r));kt(e,a),It(e,t,n)}})),Kt,qt,Jt,Yt,Xt,Zt,Qt,$t,en,tn,nn=o((()=>{Kt=`suggest_replies`,qt={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},Jt={name:Kt,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:qt,origin:`sdk`,annotations:{readOnlyHint:!0}},Yt=()=>({content:[{type:`text`,text:`Suggestions shown to the user.`}]}),Xt=e=>e.variant===`tool`&&e.toolCall?.name===`suggest_replies`,Zt=e=>{let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let r=n.flatMap(e=>{if(typeof e==`string`){let t=e.trim();return t?[t]:[]}if(!e||typeof e!=`object`)return[];let t=e;if(typeof t.label!=`string`||!t.label.trim())return[];let n={label:t.label.trim()};return typeof t.prompt==`string`&&t.prompt.trim()&&(n.prompt=t.prompt.trim()),typeof t.description==`string`&&t.description.trim()&&(n.description=t.description.trim()),[n]});return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},Qt=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return null;if(!Xt(n))continue;let r=Zt(n.toolCall?.args);return r.length>0?r:null}return null},$t=/* @__PURE__ */ new Set,en=(e,t,n)=>{let r=`${e}:${t}:${n}`;$t.has(r)||($t.add(r),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},tn=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,r=e=>{let r=t?.[e],i=n?.[e];r!==void 0&&i!==void 0&&r!==i&&en(e,i,r)};e&&(r(`enabled`),r(`expose`));let i=t?.enabled??n?.enabled??!0;return{enabled:i,expose:i?t?.expose??n?.expose??!1:!1}}})),rn,an,on,sn=o((()=>{Gt(),nn(),rn={type:`object`,properties:{questions:{type:`array`,minItems:1,maxItems:8,description:`Questions to ask the user. Prefer a single question.`,items:{type:`object`,properties:{question:{type:`string`,description:`The complete question, ending with a question mark.`},header:{type:`string`,maxLength:12,description:`Short topic label, e.g. "Auth method".`},options:{type:`array`,minItems:2,maxItems:4,description:`2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.`,items:{type:`object`,properties:{label:{type:`string`,description:`Concise choice text (1-5 words).`},description:{type:`string`,description:`What the option means or implies.`}},required:[`label`],additionalProperties:!1}},multiSelect:{type:`boolean`,description:`Allow selecting multiple options. Default false.`},allowFreeText:{type:`boolean`,description:`Show a free-text input. Default true.`}},required:[`question`,`options`],additionalProperties:!1}}},required:[`questions`],additionalProperties:!1},an={name:$e,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:rn,origin:`sdk`,annotations:{readOnlyHint:!0}},on=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(an),tn(e).expose&&t.push(Jt),t}})),cn,ln,un,dn=o((()=>{cn={idle:`Online`,connecting:`Connecting…`,connected:`Streaming…`,error:`Offline`,paused:`Connection lost…`,resuming:`Reconnecting…`},ln=1e5,un=100001}));async function fn(e,t,n){let r={"Content-Type":`application/json`,...e.headers};e.getHeaders&&Object.assign(r,await e.getHeaders());let i={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},a=(t,n)=>fetch(`${e.clientApiBase()}${t}`,{method:`POST`,headers:r,body:JSON.stringify({...n,...i})}),o=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return a(o);let{sessionId:s}=await e.initSession(),c=await a(`/v1/client/approve`,{sessionId:s});if(c.status===404){let e=await c.clone().json().catch(()=>null);if(!e||e.error===`Not Found`)return a(o)}return c}async function pn(e,t,n,r){let i=e.isClientTokenMode(),a=i?e.getClientApiUrl(`resume`):`${e.config.apiUrl?.replace(/\/+$/,``)||`https://api.runtype.com`}/resume`,o,s=null;if(i){let t=await e.initSession();o=t.sessionId,t.durableRecovery?.enabled===!0&&(s=await e.readVisitorToken())}let c={"Content-Type":`application/json`,...s?{"X-Visitor-Token":s}:{},...e.headers};e.getHeaders&&Object.assign(c,await e.getHeaders());let l={executionId:t,toolOutputs:n,streamResponse:r?.streamResponse??!0,...r?.after?{after:r.after}:{}};if(o&&(l.sessionId=o),i&&o){let t=[...on(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:n,commit:i}=await e.sendWithClientToolsDiff(o,t,t=>{let n={...l,...t};return e.debug&&console.debug(`[AgentWidgetClient] client token resume`,n),fetch(a,{method:`POST`,headers:c,body:JSON.stringify(n),signal:r?.signal})},{emptyMeansReplace:!0});return n.ok&&i(),n}return fetch(a,{method:`POST`,headers:c,body:JSON.stringify(l),signal:r?.signal})}var mn=o((()=>{sn(),dn()})),hn=/* @__PURE__ */ s({preferFinalStructuredContent:()=>_n,resolveApproval:()=>fn,resumeFlow:()=>pn,streamResponse:()=>Z});function gn(e){let t=e.toLowerCase(),n={"application/pdf":`pdf`,"application/json":`json`,"application/zip":`zip`,"text/plain":`txt`,"text/csv":`csv`,"text/markdown":`md`}[t];if(n)return`attachment.${n}`;let r=t.indexOf(`/`);if(r>0){let e=t.slice(r+1).split(`;`)[0]?.trim()??``;if(e&&e!==`octet-stream`&&/^[a-z0-9.+-]+$/i.test(e))return`attachment.${e}`}return`attachment`}function _n(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let i=yn(n);if(!yn(r))return e;if(!i||r===n||r.startsWith(n))return t;let a=Ge(e);return Ge(t)!==null&&a===null?t:e}async function vn(e,t,n,r,i,a,o){if(!e.parseSSEEvent)return!1;try{let s=await e.parseSSEEvent(t);if(s===null)return!1;let c=e=>{let t={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`assistant`,sequence:a(),...e!==void 0&&{partId:e}};return r.current=t,i(t),t},l=e=>r.current?r.current:c(e);if(s.text!==void 0){s.partId!==void 0&&o.current!==null&&s.partId!==o.current&&(r.current&&(r.current.streaming=!1,i(r.current)),c(s.partId)),s.partId!==void 0&&(o.current=s.partId);let e=l(s.partId);s.partId!==void 0&&!e.partId&&(e.partId=s.partId),e.content+=s.text,i(e)}return s.done&&(r.current&&(r.current.streaming=!1,i(r.current)),o.current=null,n({type:`status`,status:`idle`})),s.error&&(o.current=null,n({type:`error`,error:Error(s.error)})),!0}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] parseSSEEvent error:`,e),!1}}async function Z(e,t,n,r,i){let a=t.getReader(),o=new TextDecoder,s=``,c=Date.now(),l=0,u=()=>c+l++,d=e=>{let t=e.reasoning?{...e.reasoning,chunks:[...e.reasoning.chunks]}:void 0,n=e.toolCall?{...e.toolCall,chunks:e.toolCall.chunks?[...e.toolCall.chunks]:void 0}:void 0,r=e.tools?e.tools.map(e=>({...e,chunks:e.chunks?[...e.chunks]:void 0})):void 0;return{...e,reasoning:t,toolCall:n,tools:r}},f=e=>{if(e.role!==`assistant`||e.variant)return!0;let t=Array.isArray(e.contentParts)&&e.contentParts.length>0,n=typeof e.rawContent==`string`&&e.rawContent.trim()!==``;return typeof e.content==`string`&&e.content.trim()!==``||t||n||!!e.stopReason},p=e=>{f(e)&&n({type:`message`,message:d(e)})},m=null,h=null,g={current:null},_={current:null},v=null,y=``,b=/* @__PURE__ */ new Map,x=/* @__PURE__ */ new Map,S=/* @__PURE__ */ new Map,C=/* @__PURE__ */ new Map,w=/* @__PURE__ */ new Map,T=r,E=!1,D=()=>{if(m)return m;let e,t=``,n=v;return!E&&T?(e=T,E=!0,t=i??``):e=T&&n?`${T}_${n}`:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:e,role:`assistant`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u()},p(m),m},O=e=>{let t=C.get(e);if(t)return t;let n={id:`reason-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`reasoning`,sequence:u(),reasoning:{id:e,status:`streaming`,chunks:[]}};return C.set(e,n),p(n),n},ee=/* @__PURE__ */ new Set,k=/* @__PURE__ */ new Map,A=/* @__PURE__ */ new Set,j=/* @__PURE__ */ new Map,te=e=>{if(!e)return!1;let t=e.replace(/_+/g,`_`).replace(/^_|_$/g,``);return t===`emit_artifact_markdown`||t===`emit_artifact_component`},ne=e=>{let t=w.get(e);if(t)return t;let n={id:`tool-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`tool`,sequence:u(),toolCall:{id:e,status:`pending`}};return w.set(e,n),p(n),n},re=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`){let t=Number(e);if(!Number.isNaN(t)&&Number.isFinite(t))return t;let n=Date.parse(e);if(!Number.isNaN(n))return n}return Date.now()},ie=e=>{if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)}catch{return String(e)}},M=/* @__PURE__ */ new Map,N=/* @__PURE__ */ new Map,P=(e,t)=>{let n=ie(t),r=_n(N.get(e.id),n);e.rawContent=r;let i=M.get(e.id),a=t=>{let n=e.content??``;t.trim()!==``&&(n.trim().length===0||t.startsWith(n)||t.trimStart().startsWith(n.trim()))&&(e.content=t)},o=()=>{if(i){let e=i.close?.();e instanceof Promise&&e.catch(()=>{})}M.delete(e.id),N.delete(e.id),e.streaming=!1,p(e)};if(!i){a(n),o();return}let s=Ge(r);if(s!==null&&s.trim()!==``){a(s),o();return}let c=e=>{let t=typeof e==`string`?e:e?.text??null;if(t!==null&&t.trim()!==``)return t;let r=i.getExtractedText();return r!==null&&r.trim()!==``?r:n},l;try{l=i.processChunk(r)}catch{a(n),o();return}l instanceof Promise?l.then(e=>{a(c(e)),o()}).catch(()=>{a(n),o()}):(a(c(l)),o())},ae=null,oe=(t,n,r,i)=>{t.rawContent=n,M.has(t.id)||M.set(t.id,e.createStreamParser());let a=M.get(t.id),o=n.trim().startsWith(`{`)||n.trim().startsWith(`[`);if(o&&N.set(t.id,n),a.__isPlainTextParser===!0){t.content=i===void 0?t.content+r:n,N.delete(t.id),M.delete(t.id),t.rawContent=void 0,p(t);return}let s=a.processChunk(n);if(s instanceof Promise)s.then(e=>{let a=typeof e==`string`?e:e?.text??null;a!==null&&a.trim()!==``?(t.content=a,p(t)):!o&&!n.trim().startsWith(`<`)&&(t.content=i===void 0?t.content+r:n,N.delete(t.id),M.delete(t.id),t.rawContent=void 0,p(t))}).catch(()=>{t.content=i===void 0?t.content+r:n,N.delete(t.id),M.delete(t.id),t.rawContent=void 0,p(t)});else{let e=typeof s==`string`?s:s?.text??null;e!==null&&e.trim()!==``?(t.content=e,p(t)):!o&&!n.trim().startsWith(`<`)&&(t.content=i===void 0?t.content+r:n,N.delete(t.id),M.delete(t.id),t.rawContent=void 0,p(t))}},se=(e,t)=>{let n=t??e.content;if(n==null||n===``){e.streaming=!1,p(e);return}let r=N.get(e.id)??ie(n);e.rawContent=r;let i=M.get(e.id),a=null,o=!1;if(i&&(a=i.getExtractedText(),a===null&&(a=Ge(r)),a===null)){let t=i.processChunk(r);t instanceof Promise?(o=!0,t.then(t=>{let n=typeof t==`string`?t:t?.text??null;n!==null&&(e.content=n,e.streaming=!1,M.delete(e.id),N.delete(e.id),p(e))}).catch(()=>{})):a=typeof t==`string`?t:t?.text??null}if(!o){a!==null&&a.trim()!==``?e.content=a:N.has(e.id)||(e.content=ie(n));let t=M.get(e.id);if(t){let n=t.close?.();n instanceof Promise&&n.catch(()=>{}),M.delete(e.id)}N.delete(e.id),e.streaming=!1,p(e)}},ce=(e,t,n)=>{let r=x.get(e);if(r)return r;let i={id:`nested-${t}-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u(),...n?{variant:n}:{},...n===`reasoning`?{reasoning:{id:e,status:`streaming`,chunks:[]}}:{},agentMetadata:{parentToolId:t}};return x.set(e,i),p(i),i},le=[],ue,de=/* @__PURE__ */ new Map,fe=0,pe=`agent`,me=!1,F=null,I=null,he=e.config().iterationDisplay??`separate`;for(ue=()=>{for(let t=0;t<le.length;t++){let r=le[t];if(!me&&pe!==`flow`&&typeof r.stepType==`string`&&(pe=`flow`),r.type===`reasoning_start`){let e=typeof r.id==`string`?r.id:null,t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){b.set(e,t),ce(e,t,`reasoning`);continue}let n=r.id,i=O(n);i.reasoning=i.reasoning??{id:n,status:`streaming`,chunks:[]},i.reasoning.startedAt=i.reasoning.startedAt??Date.now(),i.reasoning.completedAt=void 0,i.reasoning.durationMs=void 0,(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),i.streaming=!0,i.reasoning.status=`streaming`,p(i)}else if(r.type===`reasoning_delta`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)&&x.has(e)){let t=x.get(e),n=r.delta;n&&t.reasoning&&(t.reasoning.chunks.push(String(n)),p(t));continue}let t=r.id,n=O(t);n.reasoning=n.reasoning??{id:t,status:`streaming`,chunks:[]},n.reasoning.startedAt=n.reasoning.startedAt??Date.now(),r.delta&&n.reasoning.chunks.push(r.delta),n.reasoning.status=`streaming`,n.streaming=!0,p(n)}else if(r.type===`reasoning_complete`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)&&x.has(e)){let t=x.get(e);if(t.reasoning){let e=typeof r.text==`string`?r.text:``;e&&t.reasoning.chunks.length===0&&t.reasoning.chunks.push(e),t.reasoning.status=`complete`,t.streaming=!1,p(t)}b.delete(e),x.delete(e);continue}let t=r.id,n=typeof r.text==`string`?r.text:``;!C.get(t)&&(n||r.scope===`loop`)&&O(t);let i=C.get(t);if(i?.reasoning){(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),n&&i.reasoning.chunks.length===0&&i.reasoning.chunks.push(n),i.reasoning.status=`complete`,i.reasoning.completedAt=Date.now();let e=i.reasoning.startedAt??Date.now();i.reasoning.durationMs=Math.max(0,(i.reasoning.completedAt??Date.now())-e),i.streaming=!1,p(i)}}else if(r.type===`tool_start`){m&&=(m.streaming=!1,p(m),null),typeof r.iteration==`number`&&(fe=r.iteration);let e=r.toolCallId,t=r.toolName;if(te(t)){ee.add(e);continue}let n=ne(e),i=n.toolCall??{id:e,status:`pending`};i.name=t??i.name,i.status=`running`,i.success=void 0,i.error=void 0,i.duration=void 0,r.parameters!==void 0&&(i.args=r.parameters),i.startedAt=i.startedAt??re(r.startedAt),i.completedAt=void 0,i.durationMs=void 0,n.toolCall=i,n.streaming=!0,r.executionId&&(n.agentMetadata={executionId:r.executionId,iteration:r.iteration}),p(n)}else if(r.type===`tool_output_delta`){let e=r.toolCallId;if(ee.has(e))continue;let t=ne(e),n=t.toolCall??{id:e,status:`running`};n.startedAt=n.startedAt??Date.now();let i=r.delta;i&&(n.chunks=n.chunks??[],n.chunks.push(String(i))),n.status=`running`,t.toolCall=n,t.streaming=!0,r.executionId&&(t.agentMetadata=t.agentMetadata??{executionId:r.executionId,iteration:fe}),p(t)}else if(r.type===`tool_complete`){let e=r.toolCallId;if(ee.has(e)){ee.delete(e);continue}let t=ne(e),n=t.toolCall??{id:e,status:`running`};n.status=`complete`,r.result!==void 0&&(n.result=r.result),n.name=r.toolName??n.name,n.success=r.success,n.error=r.error,n.completedAt=Date.now();let i=r.executionTime;if(typeof i==`number`)n.durationMs=i,n.duration=i;else{let e=n.startedAt??Date.now();n.durationMs=Math.max(0,(n.completedAt??Date.now())-e)}t.toolCall=n,t.streaming=!1,r.executionId&&(t.agentMetadata=t.agentMetadata??{executionId:r.executionId,iteration:r.iteration??fe}),p(t)}else if(r.type===`await`&&r.toolName){let e=typeof r.toolCallId==`string`&&r.toolCallId.length>0?r.toolCallId:void 0,t=e??r.toolId??`local-${u()}`,n=ne(t),i=r.toolName,a=r.origin===`webmcp`&&!xe(i)?`webmcp:${i}`:i,o=xe(a),s=n.toolCall??{id:t,status:`pending`};s.name=a,s.args=r.parameters,s.status=o?`running`:`complete`,s.chunks=s.chunks??[],s.startedAt=s.startedAt??re(r.awaitedAt),o?(s.completedAt=void 0,s.duration=void 0,s.durationMs=void 0):s.completedAt=s.completedAt??s.startedAt,n.toolCall=s,n.streaming=!1,n.agentMetadata={...n.agentMetadata,executionId:r.executionId??n.agentMetadata?.executionId,awaitingLocalTool:!0,...e?{webMcpToolCallId:e}:{}},p(n)}else if(r.type===`text_start`){let e=typeof r.id==`string`?r.id:null,t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){b.set(e,t);continue}let n=m;n&&(pe===`flow`?(se(n),ae=n):(n.streaming=!1,p(n)),m=null),v=typeof r.id==`string`?r.id:v,y=``}else if(r.type===`text_delta`){let e=typeof r.id==`string`?r.id:null,t=e?b.get(e):void 0;if(e&&t){let n=typeof r.delta==`string`?r.delta:``,i=(S.get(e)??``)+n;if(S.set(e,i),i.trim()===``)continue;let a=ce(e,t);a.agentMetadata={...a.agentMetadata,executionId:r.executionId,parentToolId:t},oe(a,i,n,void 0);continue}if(v=typeof r.id==`string`?r.id:v,pe===`flow`){let e=typeof r.delta==`string`?r.delta:``;if(y+=e,y.trim()===``)continue;let t=D();t.agentMetadata={executionId:r.executionId,iteration:fe},oe(t,y,e,void 0),h=t;continue}let n=typeof r.delta==`string`?r.delta:``;y+=n;let i=D();i.agentMetadata={executionId:r.executionId,iteration:fe,turnId:F??void 0,agentName:I?.agentName},oe(i,y,n,void 0),h=i}else if(r.type===`text_complete`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)){let t=x.get(e);t&&se(t),b.delete(e),S.delete(e),x.delete(e);continue}let t=m;t&&(pe===`flow`?(se(t),ae=t):((t.content??``)===``&&typeof r.text==`string`&&(t.content=r.text),t.streaming=!1,p(t)),m=null),v=null,y=``}else if(r.type===`step_complete`){if(r.stepType===`tool`)continue;if(r.success===!1){let e=r.error||`Step failed`;n({type:`error`,error:Error(e)});let t=m;t&&t.streaming&&(t.streaming=!1,p(t)),n({type:`status`,status:`idle`});continue}{let e=ae;ae=null;let t=r.stopReason,n=(r.result&&typeof r.result==`object`?r.result:null)?.response;if(e)t&&(e.stopReason=t),n==null?e.streaming!==!1&&(M.delete(e.id),N.delete(e.id),e.streaming=!1,p(e)):P(e,n);else{let e=n!=null&&n!==``;if(e||t&&t!==`end_turn`&&t!==`unknown`){let r=D();t&&(r.stopReason=t),e?se(r,n):(r.streaming=!1,p(r))}}continue}}else if(r.type===`execution_start`)pe=r.kind===`flow`?`flow`:`agent`,me=!0,pe===`agent`&&(I={executionId:r.executionId,agentId:r.agentId??`virtual`,agentName:r.agentName??``});else if(r.type===`turn_start`){let e=typeof r.iteration==`number`?r.iteration:fe;if(e!==fe){if(he===`separate`&&e>1){let e=m;e&&(e.streaming=!1,p(e),m=null)}fe=e}F=typeof r.id==`string`?r.id:null,h=null}else if(r.type===`tool_input_delta`){let e=r.toolCallId;if(e){let t=w.get(e);t?.toolCall&&(t.toolCall.chunks=t.toolCall.chunks??[],t.toolCall.chunks.push(r.delta??``),p(t))}}else if(r.type===`tool_input_complete`){if(ee.has(r.toolCallId))continue;let e=ne(r.toolCallId),t=e.toolCall;t.args=r.parameters,t.name=r.toolName??t.name,p(e)}else if(r.type===`turn_complete`){let e=r.stopReason,t=m??h;if(e&&t!==null){let n=r.id;(!n||t.agentMetadata?.turnId===n)&&(t.stopReason=e,p(t))}F===r.id&&(F=null)}else if(r.type===`media_start`){let e=String(r.id);de.set(e,{mediaType:typeof r.mediaType==`string`?r.mediaType:void 0,toolCallId:r.toolCallId,parts:[]})}else if(r.type===`media_delta`){let e=de.get(String(r.id));e&&typeof r.delta==`string`&&e.parts.push(r.delta)}else if(r.type===`media_complete`){let e=String(r.id),t=de.get(e);de.delete(e);let n=(typeof r.mediaType==`string`?r.mediaType:void 0)??t?.mediaType??`application/octet-stream`,i=typeof r.data==`string`?r.data:void 0,a=typeof r.url==`string`?r.url:t&&t.parts.length>0?t.parts.join(``):void 0,o=null;if(i)o={type:`media`,data:i,mediaType:n};else if(a){let e=n.toLowerCase();o={type:e===`image`||e.startsWith(`image/`)?`image-url`:`file-url`,url:a,mediaType:n}}let s=r.toolCallId??t?.toolCallId,c=o?[o]:[],l=[];for(let e of c){if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.type==`string`?t.type:void 0,r=typeof t.mediaType==`string`?t.mediaType.toLowerCase():``,i=null,a=``;if(n===`media`){let e=typeof t.data==`string`?t.data:void 0;if(!e)continue;a=r.length>0?r:`application/octet-stream`,i=`data:${a};base64,${e}`}else if(n===`image-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else if(n===`file-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else continue;if(i){if(n===`image-url`||a.startsWith(`image/`))l.push({type:`image`,image:i,...a.includes(`/`)?{mimeType:a}:{}});else if(a.startsWith(`audio/`))l.push({type:`audio`,audio:i,mimeType:a});else if(a.startsWith(`video/`))l.push({type:`video`,video:i,mimeType:a});else{let e=a||`application/octet-stream`;l.push({type:`file`,data:i,mimeType:e,filename:gn(e)})}}}if(l.length>0){let e=u(),t=s,n={id:`agent-media-${typeof t==`string`&&t.length>0?`${t}-${e}`:String(e)}`,role:`assistant`,content:``,contentParts:l,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e,agentMetadata:{executionId:r.executionId,iteration:fe}};p(n);let i=m;i&&(i.streaming=!1,p(i)),m=null,g.current=null}}else if(r.type===`execution_complete`){let e=m;e&&(r.kind===`flow`&&e.streaming!==!1?se(e):(e.streaming=!1,p(e)),m=null),v=null,y=``,ae=null,n({type:`status`,status:`idle`,terminal:!0})}else if(r.type===`execution_error`){let e=typeof r.error==`string`?r.error:r.error?.message??`Execution error`;n({type:`error`,error:Error(e)})}else if(r.type!==`ping`){if(r.type===`approval_start`){let e=r.approvalId??`approval-${u()}`,t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:u(),approval:{id:e,status:`pending`,agentId:I?.agentId??`virtual`,executionId:r.executionId??I?.executionId??``,toolName:r.toolName??``,toolType:r.toolType,description:r.description??`Execute ${r.toolName??`tool`}`,...typeof r.reason==`string`&&r.reason?{reason:r.reason}:{},parameters:r.parameters,...typeof r.toolCallId==`string`&&r.toolCallId?{toolCallId:r.toolCallId}:{}}};p(t)}else if(r.type===`approval_complete`){let e=r.approvalId;if(e){let t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:u(),approval:{id:e,status:r.decision??`approved`,agentId:I?.agentId??`virtual`,executionId:r.executionId??I?.executionId??``,toolName:``,description:``,resolvedAt:Date.now()}};p(t)}}else if(r.type===`artifact_start`||r.type===`artifact_delta`||r.type===`artifact_update`||r.type===`artifact_complete`){if(r.type===`artifact_start`){let t=r.artifactType,i=String(r.id),a=typeof r.title==`string`?r.title:void 0,o=r.file,s;if(o&&typeof o==`object`&&!Array.isArray(o)&&typeof o.path==`string`&&typeof o.mimeType==`string`&&(s={path:o.path,mimeType:o.mimeType,...typeof o.language==`string`?{language:o.language}:{}}),n({type:`artifact_start`,id:i,artifactType:t,title:a,component:typeof r.component==`string`?r.component:void 0,...s?{file:s}:{}}),j.set(i,{markdown:``,title:a,file:s}),!A.has(i)){A.add(i);let n=Oe(e.config().features?.artifacts,{artifactType:t,...s?{file:s}:{}}),o=typeof r.component==`string`?r.component:void 0,c={id:`artifact-ref-${i}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u(),rawContent:ke(n,{artifactId:i,title:a,artifactType:t,status:`streaming`,...s?{file:s}:{},...o?{component:o}:{}})};k.set(i,c),p(c)}}else if(r.type===`artifact_delta`){let e=String(r.id),t=typeof r.delta==`string`?r.delta:String(r.delta??``);n({type:`artifact_delta`,id:e,artDelta:t});let i=j.get(e);i&&(i.markdown+=t)}else if(r.type===`artifact_update`){let e=r.props&&typeof r.props==`object`&&!Array.isArray(r.props)?r.props:{};n({type:`artifact_update`,id:String(r.id),props:e,component:typeof r.component==`string`?r.component:void 0});let t=j.get(String(r.id));t&&(t.props={...t.props??{},...e})}else if(r.type===`artifact_complete`){let e=String(r.id);n({type:`artifact_complete`,id:e});let t=k.get(e);if(t){t.streaming=!1;try{let n=JSON.parse(t.rawContent??`{}`);if(n.props){n.props.status=`complete`;let t=j.get(e);t?.markdown&&(n.props.markdown=t.markdown),t?.file&&(n.props.file=t.file),n.component===`PersonaArtifactInline`&&t?.props&&Object.keys(t.props).length>0&&(n.props.componentProps=t.props)}t.rawContent=JSON.stringify(n)}catch{}j.delete(e),p(t),k.delete(e)}}}else if(r.type===`error`&&r.recoverable===!1&&r.error!=null&&r.error!==``){let e=typeof r.error==`string`?r.error:r.error?.message==null?`Execution error`:String(r.error.message);n({type:`error`,error:Error(e)});let t=m;t&&t.streaming&&(t.streaming=!1,p(t)),n({type:`status`,status:`idle`})}}}le.length=0};;){let{done:t,value:r}=await a.read();if(t)break;s+=o.decode(r,{stream:!0});let i=s.split(`
4
+ `).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`)}catch{return n[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e===null?null:{text:e,raw:r};let i=r.trim();if(!i.startsWith(`{`)&&!i.startsWith(`[`))return null;let a=n(r);return a!==null&&(e=a),t=r.length,e===null?null:{text:e,raw:r}},close:async()=>{}}},Ke=e=>{try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.text==`string`)return t.text}catch{return null}return null},qe=()=>{let e={processChunk:e=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Je=()=>{let e=Ge();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)}},Ye=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith(`{`)&&!r.startsWith(`[`))return null;if(n.length<=t)return e!==null||e===``?{text:e||``,raw:n}:null;try{let t=(0,p.parse)(n,p.STR|p.OBJ);t&&typeof t==`object`&&(t.component&&typeof t.component==`string`?e=typeof t.text==`string`?Me(t.text):``:t.type===`init`&&t.form?e=``:typeof t.text==`string`&&(e=Me(t.text)))}catch{}return t=n.length,e===null?null:{text:e,raw:n}},close:()=>{}}},Xe=e=>{let t=null,n=0,r=e||(e=>{if(!e||typeof e!=`object`)return null;let t=e=>typeof e==`string`?Me(e):null;if(e.component&&typeof e.component==`string`)return typeof e.text==`string`?Me(e.text):``;if(e.type===`init`&&e.form)return``;if(e.action)switch(e.action){case`nav_then_click`:return t(e.on_load_text)||t(e.text)||null;case`message`:case`message_and_click`:case`checkout`:return t(e.text)||null;default:return t(e.text)||t(e.display_text)||t(e.message)||null}return t(e.text)||t(e.display_text)||t(e.message)||t(e.content)||null});return{getExtractedText:()=>t,processChunk:e=>{let i=e.trim();if(!i.startsWith(`{`)&&!i.startsWith(`[`))return null;if(e.length<=n)return t===null?null:{text:t,raw:e};try{let n=(0,p.parse)(e,p.STR|p.OBJ),i=r(n);i!==null&&(t=i)}catch{}return n=e.length,{text:t||``,raw:e}},close:()=>{}}},Ze=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith(`<`))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}}})),z,B,$e,V=o((()=>{z=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},B=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[e,n]of Object.entries(t.attrs))r.setAttribute(e,n);if(t.style){let e=r.style,n=t.style;for(let t of Object.keys(n)){let r=n[t];r!=null&&(e[t]=r)}}let i=n.filter(e=>e!=null);return i.length>0&&r.append(...i),r},$e=(...e)=>e.filter(Boolean).join(` `)})),et,tt,nt,rt,it,at,H,ot,st,U,W,G,ct,lt,ut,K,q,dt,ft,pt,mt,ht,gt,_t,vt,yt,bt,J,xt,St,Ct,wt,Tt,Et,Dt,Ot,kt,At,Y,jt,Mt,Nt,Pt,Ft,It,Lt,Rt,zt,Bt,Vt,Ht,Ut,Wt,Gt,Kt=o((()=>{V(),et=`ask_user_question`,tt=`data-persona-ask-sheet-for`,nt=`Other`,rt=`Other…`,it=`Type your own answer here`,at=`Send`,H=`Next`,ot=`Back`,st=`Submit all`,U=`Skip`,W=3,G=`data-ask-current-index`,ct=`data-ask-question-count`,lt=`data-ask-answers`,ut=`data-ask-grouped`,K=`data-ask-layout`,q=e=>e.layout===`pills`?`pills`:`rows`,dt=e=>e.getAttribute(`data-ask-layout`)===`pills`?`pills`:`rows`,ft=!1,pt=e=>e.replace(/["\\]/g,`\\$&`),mt=e=>e.variant===`tool`&&!!e.toolCall&&e.toolCall.name===`ask_user_question`,ht=e=>e?.features?.askUserQuestion??{},gt=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status===`complete`;if(t.args&&typeof t.args==`object`)return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let e=r.join(``),t=(0,p.parse)(e,p.STR|p.OBJ|p.ARR);if(t&&typeof t==`object`)return{payload:t,complete:n}}catch{}return{payload:null,complete:n}},_t=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!ft&&(ft=!0,typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},vt=e=>_t(e)[0]??null,yt=(e,t)=>_t(e)[t]??null,bt=(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))},J=(e,t,n)=>{if(e!==`rows`)return null;let r=z(`span`,`persona-ask-row-affordance`);if(r.setAttribute(`aria-hidden`,`true`),t){let e=z(`span`,`persona-ask-row-check`);r.appendChild(e)}else{let e=z(`span`,`persona-ask-row-badge`);e.textContent=String(n+1),r.appendChild(e)}return r},xt=(e,t,n,r)=>{let i=z(`button`,n===`rows`?`persona-ask-pill persona-ask-row persona-pointer-events-auto`:`persona-ask-pill persona-pointer-events-auto`);if(i.type=`button`,i.setAttribute(`role`,r?`checkbox`:`button`),i.setAttribute(`aria-pressed`,`false`),i.setAttribute(`data-ask-user-action`,`pick`),i.setAttribute(`data-option-index`,String(t)),i.setAttribute(`data-option-label`,e.label),n===`rows`){let a=z(`span`,`persona-ask-row-content`),o=z(`span`,`persona-ask-row-label`);if(o.textContent=e.label,a.appendChild(o),e.description){let t=z(`span`,`persona-ask-row-description`);t.textContent=e.description,a.appendChild(t)}i.appendChild(a);let s=J(n,r,t);s&&i.appendChild(s)}else i.textContent=e.label,e.description&&(i.title=e.description);return i},St=e=>{let t=z(`span`,e===`rows`?`persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none`:`persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none`);return t.setAttribute(`aria-hidden`,`true`),t},Ct=(e,t,n,r)=>{let i=z(`div`,r===`rows`?`persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2`:`persona-ask-pills persona-flex persona-flex-wrap persona-gap-2`);i.setAttribute(`role`,`group`),i.setAttribute(`data-ask-pill-list`,`true`);let a=!!e?.multiSelect,o=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&typeof e.label==`string`&&e.label.length>0);if(o.length===0&&!n){for(let e=0;e<W;e++)i.appendChild(St(r));return i}if(o.forEach((e,t)=>{i.appendChild(xt(e,t,r,a))}),e?.allowFreeText!==!1){let e=r===`rows`?nt:rt;if(r===`rows`){let n=z(`div`,`persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto`);n.setAttribute(`data-ask-user-action`,`focus-free-text`),n.setAttribute(`data-option-index`,String(o.length)),n.setAttribute(`data-ask-other-row`,`true`);let s=z(`span`,`persona-ask-row-content`),c=document.createElement(`input`);c.type=`text`,c.className=`persona-ask-row-input persona-flex-1 persona-pointer-events-auto`,c.placeholder=t.freeTextPlaceholder??it,c.setAttribute(`data-ask-free-text-input`,`true`),c.setAttribute(`aria-label`,t.freeTextLabel??e),s.appendChild(c),n.appendChild(s);let l=J(r,a,o.length);l&&n.appendChild(l),i.appendChild(n)}else{let n=z(`button`,`persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto`);n.type=`button`,n.setAttribute(`data-ask-user-action`,`open-free-text`),n.textContent=t.freeTextLabel??e,i.appendChild(n)}}return i},wt=(e,t)=>{let n=z(`div`,t===`rows`?`persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2`:`persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2`);n.setAttribute(`data-ask-free-text-row`,`true`);let r=document.createElement(`input`);if(r.type=`text`,r.className=`persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto`,r.placeholder=e.freeTextPlaceholder??it,r.setAttribute(`data-ask-free-text-input`,`true`),n.appendChild(r),t!==`rows`){let t=z(`button`,`persona-ask-free-text-submit persona-pointer-events-auto`);t.type=`button`,t.textContent=e.submitLabel??at,t.setAttribute(`data-ask-user-action`,`submit-free-text`),n.appendChild(t)}return n},Tt=e=>{let t=z(`div`,`persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2`);t.setAttribute(`data-ask-multi-actions`,`true`);let n=z(`button`,`persona-ask-multi-submit persona-pointer-events-auto`);return n.type=`button`,n.textContent=e.submitLabel??at,n.setAttribute(`data-ask-user-action`,`submit-multi`),n.disabled=!0,t.appendChild(n),t},Et=(e,t,n)=>{let r=z(`div`,`persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2`);r.setAttribute(`data-ask-nav-row`,`true`);let i=z(`button`,`persona-ask-nav-back persona-pointer-events-auto`);i.type=`button`,i.textContent=n.backLabel??ot,i.setAttribute(`data-ask-user-action`,`back`),i.disabled=e===0,r.appendChild(i);let a=z(`div`,`persona-ask-nav-right persona-flex persona-items-center persona-gap-2`),o=z(`button`,`persona-ask-nav-skip persona-pointer-events-auto`);o.type=`button`,o.textContent=n.skipLabel??U,o.setAttribute(`data-ask-user-action`,`skip`),a.appendChild(o);let s=z(`button`,`persona-ask-nav-next persona-pointer-events-auto`);s.type=`button`;let c=e===t-1;return s.textContent=c?n.submitAllLabel??st:n.nextLabel??H,s.setAttribute(`data-ask-user-action`,c?`submit-all`:`next`),s.disabled=!0,a.appendChild(s),r.appendChild(a),r},Dt=e=>{let t=e.getAttribute(lt);if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e==`object`?e:{}}catch{return{}}},Ot=(e,t)=>{e.setAttribute(lt,JSON.stringify(t))},kt=e=>{let t=Number(e.getAttribute(`data-ask-current-index`)??`0`);return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},At=(e,t)=>{e.setAttribute(G,String(Math.max(0,Math.floor(t))))},Y=e=>{let t=Number(e.getAttribute(`data-ask-question-count`)??`1`);return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},jt=e=>e.getAttribute(ut)===`true`,Mt=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!=`object`)return{};let r={};return t.forEach((e,t)=>{let i=typeof e?.question==`string`?e.question:``;if(i&&Object.prototype.hasOwnProperty.call(n,i)){let e=n[i];(typeof e==`string`||Array.isArray(e))&&(r[t]=e)}}),r},Nt=(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)))},Pt=(e,t)=>{let{payload:n}=gt(t),r=_t(n),i=Dt(e),a={},o=/* @__PURE__ */ new Set;return r.forEach((e,t)=>{let n=typeof e?.question==`string`?e.question:``;n&&(o.has(n)&&typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${n}"; later answer wins.`),o.add(n),Object.prototype.hasOwnProperty.call(i,t)&&(a[n]=i[t]))}),a},Ft=e=>{let t=Dt(e)[kt(e)],n=/* @__PURE__ */ new Set;typeof t==`string`?n.add(t):Array.isArray(t)&&t.forEach(e=>n.add(e));let r=e.querySelectorAll(`[data-ask-user-action="pick"][data-option-label]`);r.forEach(e=>{let t=e.getAttribute(`data-option-label`)??``,r=n.has(t);e.setAttribute(`aria-pressed`,r?`true`:`false`),e.classList.toggle(`persona-ask-pill-selected`,r)});let i=new Set(Array.from(r).map(e=>e.getAttribute(`data-option-label`)??``)),a=e.querySelector(`[data-ask-free-text-input="true"]`);a&&(typeof t==`string`&&t.length>0&&!i.has(t)?(a.value=t,a.closest(`[data-ask-free-text-row="true"]`)?.classList.remove(`persona-hidden`)):a.value=``)},It=e=>{if(!jt(e))return;let t=Dt(e)[kt(e)],n=typeof t==`string`&&t.length>0||Array.isArray(t)&&t.length>0,r=e.querySelector(`[data-ask-user-action="next"], [data-ask-user-action="submit-all"]`);r&&(r.disabled=!n);let i=e.querySelector(`[data-ask-user-action="submit-multi"]`);i&&(i.disabled=Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).length===0)},Lt=(e,t,n)=>{let r=ht(n),i=dt(e),{payload:a,complete:o}=gt(t),s=jt(e),c=kt(e),l=Y(e),u=s?yt(a,c):vt(a),d=!!u?.multiSelect,f=e.querySelector(`[data-ask-step-inline="true"]`);f&&(f.textContent=s?`${c+1}/${l}`:``);let p=e.querySelector(`[data-ask-stepper="true"]`);p&&p.remove();let m=e.querySelector(`[data-ask-question="true"]`);if(m){let e=typeof u?.question==`string`?u.question:``;m.textContent=e,m.classList.toggle(`persona-ask-question-skeleton`,!e&&!o)}let h=e.querySelector(`[data-ask-pill-list="true"]`);if(h){let e=Ct(u,r,o,i);h.replaceWith(e)}if(i!==`rows`){let t=e.querySelector(`[data-ask-free-text-row="true"]`);t&&t.replaceWith(wt(r,i))}let g=e.querySelector(`[data-ask-multi-actions="true"]`);!s&&d&&!g?e.appendChild(Tt(r)):(!d||s)&&g&&g.remove(),e.setAttribute(`data-multi-select`,d?`true`:`false`);let _=e.querySelector(`[data-ask-nav-row="true"]`);if(s){let t=Et(c,l,r);_?_.replaceWith(t):e.appendChild(t)}else _&&_.remove();Ft(e),It(e)},Rt=(e,t,n)=>{let r=ht(t),i=q(r),a=e.toolCall.id,o=_t(n),s=Math.max(1,o.length),c=s>1,l=Mt(e,o),u=c?Nt(e,s):0,d=z(`div`,[`persona-ask-sheet`,`persona-ask-sheet--${i}`,`persona-pointer-events-auto`,`persona-ask-sheet-enter`].join(` `));d.setAttribute(tt,a),d.setAttribute(`data-tool-call-id`,a),d.setAttribute(`data-message-id`,e.id),d.setAttribute(ct,String(s)),d.setAttribute(G,String(u)),d.setAttribute(ut,c?`true`:`false`),d.setAttribute(K,i),Ot(d,l),d.setAttribute(`role`,`group`),d.setAttribute(`aria-label`,`Suggested answers`),r.slideInMs!==void 0&&d.style.setProperty(`--persona-ask-sheet-duration`,`${r.slideInMs}ms`),bt(d,r);let f=z(`div`,`persona-ask-sheet-header persona-flex persona-items-center persona-gap-3`),p=z(`div`,`persona-ask-sheet-question persona-flex-1`);p.setAttribute(`data-ask-question`,`true`),p.textContent=``,f.appendChild(p);let m=z(`span`,`persona-ask-sheet-step-inline`);m.setAttribute(`data-ask-step-inline`,`true`),m.textContent=``,f.appendChild(m),d.appendChild(f);let h=z(`div`,i===`rows`?`persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2`:`persona-ask-pills persona-flex persona-flex-wrap persona-gap-2`);return h.setAttribute(`data-ask-pill-list`,`true`),h.setAttribute(`role`,`group`),d.appendChild(h),i!==`rows`&&d.appendChild(wt(r,i)),Lt(d,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>d.classList.remove(`persona-ask-sheet-enter`))}),d},zt=(e,t,n)=>{let{payload:r}=gt(t),i=Math.max(1,_t(r).length);i>Y(e)&&(e.setAttribute(ct,String(i)),i>1&&!jt(e)&&e.setAttribute(ut,`true`)),Lt(e,t,n)},Bt=(e,t)=>{let n=z(`div`,`persona-ask-stub persona-inline-flex persona-items-center persona-gap-2`);n.id=`bubble-${e.id}`,n.setAttribute(`data-message-id`,e.id),n.setAttribute(`data-bubble-type`,`ask-user-question`);let r=ht(t);bt(n,r);let i=z(`span`,`persona-ask-stub-label`),{complete:a}=gt(e);return i.textContent=a?`Awaiting your response…`:`Preparing options…`,n.appendChild(i),n},Vt=(e,t,n)=>{if(!n||!mt(e)||ht(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${tt}]`).forEach(e=>{e.getAttribute(tt)!==r&&e.remove()});let i=n.querySelector(`[${tt}="${pt(r)}"]`);if(i){zt(i,e,t);return}let{payload:a}=gt(e),o=Rt(e,t,a);n.appendChild(o)},Ht=(e,t)=>{if(!e)return;let n=t?`[${tt}="${pt(t)}"]`:`[${tt}]`;e.querySelectorAll(n).forEach(e=>{e.classList.add(`persona-ask-sheet-leave`);let t=Number.parseInt(getComputedStyle(e).getPropertyValue(`--persona-ask-sheet-duration`)||`180`,10);setTimeout(()=>e.remove(),Number.isFinite(t)?t:180)})},Ut=e=>Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).map(e=>e.getAttribute(`data-option-label`)).filter(e=>typeof e==`string`&&e.length>0),Wt=(e,t)=>{let n=Dt(e),r=kt(e);typeof t==`string`&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Ot(e,n),Ft(e),It(e)},Gt=(e,t,n,r)=>{let i=Y(e),a=Math.max(0,Math.min(i-1,r));At(e,a),Lt(e,t,n)}})),qt,Jt,Yt,Xt,Zt,Qt,$t,en,tn,nn,rn=o((()=>{qt=`suggest_replies`,Jt={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},Yt={name:qt,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:Jt,origin:`sdk`,annotations:{readOnlyHint:!0}},Xt=()=>({content:[{type:`text`,text:`Suggestions shown to the user.`}]}),Zt=e=>e.variant===`tool`&&e.toolCall?.name===`suggest_replies`,Qt=e=>{let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let r=n.flatMap(e=>{if(typeof e==`string`){let t=e.trim();return t?[t]:[]}if(!e||typeof e!=`object`)return[];let t=e;if(typeof t.label!=`string`||!t.label.trim())return[];let n={label:t.label.trim()};return typeof t.prompt==`string`&&t.prompt.trim()&&(n.prompt=t.prompt.trim()),typeof t.description==`string`&&t.description.trim()&&(n.description=t.description.trim()),[n]});return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},$t=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return null;if(!Zt(n))continue;let r=Qt(n.toolCall?.args);return r.length>0?r:null}return null},en=/* @__PURE__ */ new Set,tn=(e,t,n)=>{let r=`${e}:${t}:${n}`;en.has(r)||(en.add(r),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},nn=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,r=e=>{let r=t?.[e],i=n?.[e];r!==void 0&&i!==void 0&&r!==i&&tn(e,i,r)};e&&(r(`enabled`),r(`expose`));let i=t?.enabled??n?.enabled??!0;return{enabled:i,expose:i?t?.expose??n?.expose??!1:!1}}})),an,on,sn,cn=o((()=>{Kt(),rn(),an={type:`object`,properties:{questions:{type:`array`,minItems:1,maxItems:8,description:`Questions to ask the user. Prefer a single question.`,items:{type:`object`,properties:{question:{type:`string`,description:`The complete question, ending with a question mark.`},header:{type:`string`,maxLength:12,description:`Short topic label, e.g. "Auth method".`},options:{type:`array`,minItems:2,maxItems:4,description:`2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.`,items:{type:`object`,properties:{label:{type:`string`,description:`Concise choice text (1-5 words).`},description:{type:`string`,description:`What the option means or implies.`}},required:[`label`],additionalProperties:!1}},multiSelect:{type:`boolean`,description:`Allow selecting multiple options. Default false.`},allowFreeText:{type:`boolean`,description:`Show a free-text input. Default true.`}},required:[`question`,`options`],additionalProperties:!1}}},required:[`questions`],additionalProperties:!1},on={name:et,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:an,origin:`sdk`,annotations:{readOnlyHint:!0}},sn=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(on),nn(e).expose&&t.push(Yt),t}})),ln,un,dn,fn=o((()=>{ln={idle:`Online`,connecting:`Connecting…`,connected:`Streaming…`,error:`Offline`,paused:`Connection lost…`,resuming:`Reconnecting…`},un=1e5,dn=100001}));async function pn(e,t,n,r){let i={"Content-Type":`application/json`,...e.headers};e.getHeaders&&Object.assign(i,await e.getHeaders());let a={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},o=(t,n)=>fetch(`${e.clientApiBase()}${t}`,{method:`POST`,headers:i,body:JSON.stringify({...n,...a})}),s=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return o(s);let{sessionId:c}=await e.initSession(),l=await o(`/v1/client/approve`,{sessionId:c,...r?.assistantMessageId?{assistantMessageId:r.assistantMessageId}:{}});if(l.status===404){let e=await l.clone().json().catch(()=>null);if(!e||e.error===`Not Found`)return o(s)}return l}async function mn(e,t,n,r){let i=e.isClientTokenMode(),a=i?e.getClientApiUrl(`resume`):`${e.config.apiUrl?.replace(/\/+$/,``)||`https://api.runtype.com`}/resume`,o,s=null;if(i){let t=await e.initSession();o=t.sessionId,t.durableRecovery?.enabled===!0&&(s=await e.readVisitorToken())}let c={"Content-Type":`application/json`,...s?{"X-Visitor-Token":s}:{},...e.headers};e.getHeaders&&Object.assign(c,await e.getHeaders());let l={executionId:t,toolOutputs:n,streamResponse:r?.streamResponse??!0,...r?.after?{after:r.after}:{}};if(o&&(l.sessionId=o,r?.assistantMessageId&&(l.assistantMessageId=r.assistantMessageId)),i&&o){let t=[...sn(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:n,commit:i}=await e.sendWithClientToolsDiff(o,t,t=>{let n={...l,...t};return e.debug&&console.debug(`[AgentWidgetClient] client token resume`,n),fetch(a,{method:`POST`,headers:c,body:JSON.stringify(n),signal:r?.signal})},{emptyMeansReplace:!0});return n.ok&&i(),n}return fetch(a,{method:`POST`,headers:c,body:JSON.stringify(l),signal:r?.signal})}var hn=o((()=>{cn(),fn()})),gn=/* @__PURE__ */ s({preferFinalStructuredContent:()=>vn,resolveApproval:()=>pn,resumeFlow:()=>mn,streamResponse:()=>X});function _n(e){let t=e.toLowerCase(),n={"application/pdf":`pdf`,"application/json":`json`,"application/zip":`zip`,"text/plain":`txt`,"text/csv":`csv`,"text/markdown":`md`}[t];if(n)return`attachment.${n}`;let r=t.indexOf(`/`);if(r>0){let e=t.slice(r+1).split(`;`)[0]?.trim()??``;if(e&&e!==`octet-stream`&&/^[a-z0-9.+-]+$/i.test(e))return`attachment.${e}`}return`attachment`}function vn(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let i=bn(n);if(!bn(r))return e;if(!i||r===n||r.startsWith(n))return t;let a=Ke(e);return Ke(t)!==null&&a===null?t:e}async function yn(e,t,n,r,i,a,o){if(!e.parseSSEEvent)return!1;try{let s=await e.parseSSEEvent(t);if(s===null)return!1;let c=e=>{let t={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`assistant`,sequence:a(),...e!==void 0&&{partId:e}};return r.current=t,i(t),t},l=e=>r.current?r.current:c(e);if(s.text!==void 0){s.partId!==void 0&&o.current!==null&&s.partId!==o.current&&(r.current&&(r.current.streaming=!1,i(r.current)),c(s.partId)),s.partId!==void 0&&(o.current=s.partId);let e=l(s.partId);s.partId!==void 0&&!e.partId&&(e.partId=s.partId),e.content+=s.text,i(e)}return s.done&&(r.current&&(r.current.streaming=!1,i(r.current)),o.current=null,n({type:`status`,status:`idle`})),s.error&&(o.current=null,n({type:`error`,error:Error(s.error)})),!0}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] parseSSEEvent error:`,e),!1}}async function X(e,t,n,r,i){let a=t.getReader(),o=new TextDecoder,s=``,c=Date.now(),l=0,u=()=>c+l++,d=e=>{let t=e.reasoning?{...e.reasoning,chunks:[...e.reasoning.chunks]}:void 0,n=e.toolCall?{...e.toolCall,chunks:e.toolCall.chunks?[...e.toolCall.chunks]:void 0}:void 0,r=e.tools?e.tools.map(e=>({...e,chunks:e.chunks?[...e.chunks]:void 0})):void 0;return{...e,reasoning:t,toolCall:n,tools:r}},f=e=>{if(e.role!==`assistant`||e.variant)return!0;let t=Array.isArray(e.contentParts)&&e.contentParts.length>0,n=typeof e.rawContent==`string`&&e.rawContent.trim()!==``;return typeof e.content==`string`&&e.content.trim()!==``||t||n||!!e.stopReason},p=e=>{f(e)&&n({type:`message`,message:d(e)})},m=null,h=null,g={current:null},_={current:null},v=null,y=``,b=/* @__PURE__ */ new Map,x=/* @__PURE__ */ new Map,S=/* @__PURE__ */ new Map,C=/* @__PURE__ */ new Map,w=/* @__PURE__ */ new Map,T=r,E=!1,D=()=>{if(m)return m;let e,t=``,n=v;return!E&&T?(e=T,E=!0,t=i??``):e=T&&n?`${T}_${n}`:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:e,role:`assistant`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u()},p(m),m},O=e=>{let t=C.get(e);if(t)return t;let n={id:`reason-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`reasoning`,sequence:u(),reasoning:{id:e,status:`streaming`,chunks:[]}};return C.set(e,n),p(n),n},ee=/* @__PURE__ */ new Set,k=/* @__PURE__ */ new Map,A=/* @__PURE__ */ new Set,te=/* @__PURE__ */ new Map,ne=e=>{if(!e)return!1;let t=e.replace(/_+/g,`_`).replace(/^_|_$/g,``);return t===`emit_artifact_markdown`||t===`emit_artifact_component`},re=e=>{let t=w.get(e);if(t)return t;let n={id:`tool-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`tool`,sequence:u(),toolCall:{id:e,status:`pending`}};return w.set(e,n),p(n),n},ie=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`){let t=Number(e);if(!Number.isNaN(t)&&Number.isFinite(t))return t;let n=Date.parse(e);if(!Number.isNaN(n))return n}return Date.now()},ae=e=>{if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)}catch{return String(e)}},j=/* @__PURE__ */ new Map,M=/* @__PURE__ */ new Map,N=(e,t)=>{let n=ae(t),r=vn(M.get(e.id),n);e.rawContent=r;let i=j.get(e.id),a=t=>{let n=e.content??``;t.trim()!==``&&(n.trim().length===0||t.startsWith(n)||t.trimStart().startsWith(n.trim()))&&(e.content=t)},o=()=>{if(i){let e=i.close?.();e instanceof Promise&&e.catch(()=>{})}j.delete(e.id),M.delete(e.id),e.streaming=!1,p(e)};if(!i){a(n),o();return}let s=Ke(r);if(s!==null&&s.trim()!==``){a(s),o();return}let c=e=>{let t=typeof e==`string`?e:e?.text??null;if(t!==null&&t.trim()!==``)return t;let r=i.getExtractedText();return r!==null&&r.trim()!==``?r:n},l;try{l=i.processChunk(r)}catch{a(n),o();return}l instanceof Promise?l.then(e=>{a(c(e)),o()}).catch(()=>{a(n),o()}):(a(c(l)),o())},oe=null,se=(t,n,r,i)=>{t.rawContent=n,j.has(t.id)||j.set(t.id,e.createStreamParser());let a=j.get(t.id),o=n.trim().startsWith(`{`)||n.trim().startsWith(`[`);if(o&&M.set(t.id,n),a.__isPlainTextParser===!0){t.content=i===void 0?t.content+r:n,M.delete(t.id),j.delete(t.id),t.rawContent=void 0,p(t);return}let s=a.processChunk(n);if(s instanceof Promise)s.then(e=>{let a=typeof e==`string`?e:e?.text??null;a!==null&&a.trim()!==``?(t.content=a,p(t)):!o&&!n.trim().startsWith(`<`)&&(t.content=i===void 0?t.content+r:n,M.delete(t.id),j.delete(t.id),t.rawContent=void 0,p(t))}).catch(()=>{t.content=i===void 0?t.content+r:n,M.delete(t.id),j.delete(t.id),t.rawContent=void 0,p(t)});else{let e=typeof s==`string`?s:s?.text??null;e!==null&&e.trim()!==``?(t.content=e,p(t)):!o&&!n.trim().startsWith(`<`)&&(t.content=i===void 0?t.content+r:n,M.delete(t.id),j.delete(t.id),t.rawContent=void 0,p(t))}},ce=(e,t)=>{let n=t??e.content;if(n==null||n===``){e.streaming=!1,p(e);return}let r=M.get(e.id)??ae(n);e.rawContent=r;let i=j.get(e.id),a=null,o=!1;if(i&&(a=i.getExtractedText(),a===null&&(a=Ke(r)),a===null)){let t=i.processChunk(r);t instanceof Promise?(o=!0,t.then(t=>{let n=typeof t==`string`?t:t?.text??null;n!==null&&(e.content=n,e.streaming=!1,j.delete(e.id),M.delete(e.id),p(e))}).catch(()=>{})):a=typeof t==`string`?t:t?.text??null}if(!o){a!==null&&a.trim()!==``?e.content=a:M.has(e.id)||(e.content=ae(n));let t=j.get(e.id);if(t){let n=t.close?.();n instanceof Promise&&n.catch(()=>{}),j.delete(e.id)}M.delete(e.id),e.streaming=!1,p(e)}},le=(e,t,n)=>{let r=x.get(e);if(r)return r;let i={id:`nested-${t}-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u(),...n?{variant:n}:{},...n===`reasoning`?{reasoning:{id:e,status:`streaming`,chunks:[]}}:{},agentMetadata:{parentToolId:t}};return x.set(e,i),p(i),i},ue=[],de,fe=/* @__PURE__ */ new Map,pe=0,me=`agent`,he=!1,P=null,F=null,ge=e.config().iterationDisplay??`separate`;for(de=()=>{for(let t=0;t<ue.length;t++){let r=ue[t];if(!he&&me!==`flow`&&typeof r.stepType==`string`&&(me=`flow`),r.type===`reasoning_start`){let e=typeof r.id==`string`?r.id:null,t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){b.set(e,t),le(e,t,`reasoning`);continue}let n=r.id,i=O(n);i.reasoning=i.reasoning??{id:n,status:`streaming`,chunks:[]},i.reasoning.startedAt=i.reasoning.startedAt??Date.now(),i.reasoning.completedAt=void 0,i.reasoning.durationMs=void 0,(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),i.streaming=!0,i.reasoning.status=`streaming`,p(i)}else if(r.type===`reasoning_delta`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)&&x.has(e)){let t=x.get(e),n=r.delta;n&&t.reasoning&&(t.reasoning.chunks.push(String(n)),p(t));continue}let t=r.id,n=O(t);n.reasoning=n.reasoning??{id:t,status:`streaming`,chunks:[]},n.reasoning.startedAt=n.reasoning.startedAt??Date.now(),r.delta&&n.reasoning.chunks.push(r.delta),n.reasoning.status=`streaming`,n.streaming=!0,p(n)}else if(r.type===`reasoning_complete`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)&&x.has(e)){let t=x.get(e);if(t.reasoning){let e=typeof r.text==`string`?r.text:``;e&&t.reasoning.chunks.length===0&&t.reasoning.chunks.push(e),t.reasoning.status=`complete`,t.streaming=!1,p(t)}b.delete(e),x.delete(e);continue}let t=r.id,n=typeof r.text==`string`?r.text:``;!C.get(t)&&(n||r.scope===`loop`)&&O(t);let i=C.get(t);if(i?.reasoning){(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),n&&i.reasoning.chunks.length===0&&i.reasoning.chunks.push(n),i.reasoning.status=`complete`,i.reasoning.completedAt=Date.now();let e=i.reasoning.startedAt??Date.now();i.reasoning.durationMs=Math.max(0,(i.reasoning.completedAt??Date.now())-e),i.streaming=!1,p(i)}}else if(r.type===`tool_start`){m&&=(m.streaming=!1,p(m),null),typeof r.iteration==`number`&&(pe=r.iteration);let e=r.toolCallId,t=r.toolName;if(ne(t)){ee.add(e);continue}let n=re(e),i=n.toolCall??{id:e,status:`pending`};i.name=t??i.name,i.status=`running`,i.success=void 0,i.error=void 0,i.duration=void 0,r.parameters!==void 0&&(i.args=r.parameters),i.startedAt=i.startedAt??ie(r.startedAt),i.completedAt=void 0,i.durationMs=void 0,n.toolCall=i,n.streaming=!0,r.executionId&&(n.agentMetadata={executionId:r.executionId,iteration:r.iteration}),p(n)}else if(r.type===`tool_output_delta`){let e=r.toolCallId;if(ee.has(e))continue;let t=re(e),n=t.toolCall??{id:e,status:`running`};n.startedAt=n.startedAt??Date.now();let i=r.delta;i&&(n.chunks=n.chunks??[],n.chunks.push(String(i))),n.status=`running`,t.toolCall=n,t.streaming=!0,r.executionId&&(t.agentMetadata=t.agentMetadata??{executionId:r.executionId,iteration:pe}),p(t)}else if(r.type===`tool_complete`){let e=r.toolCallId;if(ee.has(e)){ee.delete(e);continue}let t=re(e),n=t.toolCall??{id:e,status:`running`};n.status=`complete`,r.result!==void 0&&(n.result=r.result),n.name=r.toolName??n.name,n.success=r.success,n.error=r.error,n.completedAt=Date.now();let i=r.executionTime;if(typeof i==`number`)n.durationMs=i,n.duration=i;else{let e=n.startedAt??Date.now();n.durationMs=Math.max(0,(n.completedAt??Date.now())-e)}t.toolCall=n,t.streaming=!1,r.executionId&&(t.agentMetadata=t.agentMetadata??{executionId:r.executionId,iteration:r.iteration??pe}),p(t)}else if(r.type===`await`&&r.toolName){let e=typeof r.toolCallId==`string`&&r.toolCallId.length>0?r.toolCallId:void 0,t=e??r.toolId??`local-${u()}`,n=re(t),i=r.toolName,a=r.origin===`webmcp`&&!Se(i)?`webmcp:${i}`:i,o=Se(a),s=n.toolCall??{id:t,status:`pending`};s.name=a,s.args=r.parameters,s.status=o?`running`:`complete`,s.chunks=s.chunks??[],s.startedAt=s.startedAt??ie(r.awaitedAt),o?(s.completedAt=void 0,s.duration=void 0,s.durationMs=void 0):s.completedAt=s.completedAt??s.startedAt,n.toolCall=s,n.streaming=!1,n.agentMetadata={...n.agentMetadata,executionId:r.executionId??n.agentMetadata?.executionId,awaitingLocalTool:!0,...e?{webMcpToolCallId:e}:{}},p(n)}else if(r.type===`text_start`){let e=typeof r.id==`string`?r.id:null,t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){b.set(e,t);continue}let n=m;n&&(me===`flow`?(ce(n),oe=n):(n.streaming=!1,p(n)),m=null),v=typeof r.id==`string`?r.id:v,y=``}else if(r.type===`text_delta`){let e=typeof r.id==`string`?r.id:null,t=e?b.get(e):void 0;if(e&&t){let n=typeof r.delta==`string`?r.delta:``,i=(S.get(e)??``)+n;if(S.set(e,i),i.trim()===``)continue;let a=le(e,t);a.agentMetadata={...a.agentMetadata,executionId:r.executionId,parentToolId:t},se(a,i,n,void 0);continue}if(v=typeof r.id==`string`?r.id:v,me===`flow`){let e=typeof r.delta==`string`?r.delta:``;if(y+=e,y.trim()===``)continue;let t=D();t.agentMetadata={executionId:r.executionId,iteration:pe},se(t,y,e,void 0),h=t;continue}let n=typeof r.delta==`string`?r.delta:``;y+=n;let i=D();i.agentMetadata={executionId:r.executionId,iteration:pe,turnId:P??void 0,agentName:F?.agentName},se(i,y,n,void 0),h=i}else if(r.type===`text_complete`){let e=typeof r.id==`string`?r.id:null;if(e&&b.has(e)){let t=x.get(e);t&&ce(t),b.delete(e),S.delete(e),x.delete(e);continue}let t=m;t&&(me===`flow`?(ce(t),oe=t):((t.content??``)===``&&typeof r.text==`string`&&(t.content=r.text),t.streaming=!1,p(t)),m=null),v=null,y=``}else if(r.type===`step_complete`){if(r.stepType===`tool`)continue;if(r.success===!1){let e=r.error||`Step failed`;n({type:`error`,error:Error(e)});let t=m;t&&t.streaming&&(t.streaming=!1,p(t)),n({type:`status`,status:`idle`});continue}{let e=oe;oe=null;let t=r.stopReason,n=(r.result&&typeof r.result==`object`?r.result:null)?.response;if(e)t&&(e.stopReason=t),n==null?e.streaming!==!1&&(j.delete(e.id),M.delete(e.id),e.streaming=!1,p(e)):N(e,n);else{let e=n!=null&&n!==``;if(e||t&&t!==`end_turn`&&t!==`unknown`){let r=D();t&&(r.stopReason=t),e?ce(r,n):(r.streaming=!1,p(r))}}continue}}else if(r.type===`execution_start`)me=r.kind===`flow`?`flow`:`agent`,he=!0,me===`agent`&&(F={executionId:r.executionId,agentId:r.agentId??`virtual`,agentName:r.agentName??``});else if(r.type===`turn_start`){let e=typeof r.iteration==`number`?r.iteration:pe;if(e!==pe){if(ge===`separate`&&e>1){let e=m;e&&(e.streaming=!1,p(e),m=null)}pe=e}P=typeof r.id==`string`?r.id:null,h=null}else if(r.type===`tool_input_delta`){let e=r.toolCallId;if(e){let t=w.get(e);t?.toolCall&&(t.toolCall.chunks=t.toolCall.chunks??[],t.toolCall.chunks.push(r.delta??``),p(t))}}else if(r.type===`tool_input_complete`){if(ee.has(r.toolCallId))continue;let e=re(r.toolCallId),t=e.toolCall;t.args=r.parameters,t.name=r.toolName??t.name,p(e)}else if(r.type===`turn_complete`){let e=r.stopReason,t=m??h;if(e&&t!==null){let n=r.id;(!n||t.agentMetadata?.turnId===n)&&(t.stopReason=e,p(t))}P===r.id&&(P=null)}else if(r.type===`media_start`){let e=String(r.id);fe.set(e,{mediaType:typeof r.mediaType==`string`?r.mediaType:void 0,toolCallId:r.toolCallId,parts:[]})}else if(r.type===`media_delta`){let e=fe.get(String(r.id));e&&typeof r.delta==`string`&&e.parts.push(r.delta)}else if(r.type===`media_complete`){let e=String(r.id),t=fe.get(e);fe.delete(e);let n=(typeof r.mediaType==`string`?r.mediaType:void 0)??t?.mediaType??`application/octet-stream`,i=typeof r.data==`string`?r.data:void 0,a=typeof r.url==`string`?r.url:t&&t.parts.length>0?t.parts.join(``):void 0,o=null;if(i)o={type:`media`,data:i,mediaType:n};else if(a){let e=n.toLowerCase();o={type:e===`image`||e.startsWith(`image/`)?`image-url`:`file-url`,url:a,mediaType:n}}let s=r.toolCallId??t?.toolCallId,c=o?[o]:[],l=[];for(let e of c){if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.type==`string`?t.type:void 0,r=typeof t.mediaType==`string`?t.mediaType.toLowerCase():``,i=null,a=``;if(n===`media`){let e=typeof t.data==`string`?t.data:void 0;if(!e)continue;a=r.length>0?r:`application/octet-stream`,i=`data:${a};base64,${e}`}else if(n===`image-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else if(n===`file-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else continue;if(i){if(n===`image-url`||a.startsWith(`image/`))l.push({type:`image`,image:i,...a.includes(`/`)?{mimeType:a}:{}});else if(a.startsWith(`audio/`))l.push({type:`audio`,audio:i,mimeType:a});else if(a.startsWith(`video/`))l.push({type:`video`,video:i,mimeType:a});else{let e=a||`application/octet-stream`;l.push({type:`file`,data:i,mimeType:e,filename:_n(e)})}}}if(l.length>0){let e=u(),t=s,n={id:`agent-media-${typeof t==`string`&&t.length>0?`${t}-${e}`:String(e)}`,role:`assistant`,content:``,contentParts:l,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e,agentMetadata:{executionId:r.executionId,iteration:pe}};p(n);let i=m;i&&(i.streaming=!1,p(i)),m=null,g.current=null}}else if(r.type===`execution_complete`){let e=m;e&&(r.kind===`flow`&&e.streaming!==!1?ce(e):(e.streaming=!1,p(e)),m=null),v=null,y=``,oe=null,n({type:`status`,status:`idle`,terminal:!0})}else if(r.type===`execution_error`){let e=typeof r.error==`string`?r.error:r.error?.message??`Execution error`;n({type:`error`,error:Error(e)})}else if(r.type!==`ping`){if(r.type===`approval_start`){let e=r.approvalId??`approval-${u()}`,t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:u(),approval:{id:e,status:`pending`,agentId:F?.agentId??`virtual`,executionId:r.executionId??F?.executionId??``,toolName:r.toolName??``,toolType:r.toolType,description:r.description??`Execute ${r.toolName??`tool`}`,...typeof r.reason==`string`&&r.reason?{reason:r.reason}:{},parameters:r.parameters,...typeof r.toolCallId==`string`&&r.toolCallId?{toolCallId:r.toolCallId}:{}}};p(t)}else if(r.type===`approval_complete`){let e=r.approvalId;if(e){let t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:u(),approval:{id:e,status:r.decision??`approved`,agentId:F?.agentId??`virtual`,executionId:r.executionId??F?.executionId??``,toolName:``,description:``,resolvedAt:Date.now()}};p(t)}}else if(r.type===`artifact_start`||r.type===`artifact_delta`||r.type===`artifact_update`||r.type===`artifact_complete`){if(r.type===`artifact_start`){let t=r.artifactType,i=String(r.id),a=typeof r.title==`string`?r.title:void 0,o=r.file,s;if(o&&typeof o==`object`&&!Array.isArray(o)&&typeof o.path==`string`&&typeof o.mimeType==`string`&&(s={path:o.path,mimeType:o.mimeType,...typeof o.language==`string`?{language:o.language}:{}}),n({type:`artifact_start`,id:i,artifactType:t,title:a,component:typeof r.component==`string`?r.component:void 0,...s?{file:s}:{}}),te.set(i,{markdown:``,title:a,file:s}),!A.has(i)){A.add(i);let n=ke(e.config().features?.artifacts,{artifactType:t,...s?{file:s}:{}}),o=typeof r.component==`string`?r.component:void 0,c={id:`artifact-ref-${i}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:u(),rawContent:Ae(n,{artifactId:i,title:a,artifactType:t,status:`streaming`,...s?{file:s}:{},...o?{component:o}:{}})};k.set(i,c),p(c)}}else if(r.type===`artifact_delta`){let e=String(r.id),t=typeof r.delta==`string`?r.delta:String(r.delta??``);n({type:`artifact_delta`,id:e,artDelta:t});let i=te.get(e);i&&(i.markdown+=t)}else if(r.type===`artifact_update`){let e=r.props&&typeof r.props==`object`&&!Array.isArray(r.props)?r.props:{};n({type:`artifact_update`,id:String(r.id),props:e,component:typeof r.component==`string`?r.component:void 0});let t=te.get(String(r.id));t&&(t.props={...t.props??{},...e})}else if(r.type===`artifact_complete`){let e=String(r.id);n({type:`artifact_complete`,id:e});let t=k.get(e);if(t){t.streaming=!1;try{let n=JSON.parse(t.rawContent??`{}`);if(n.props){n.props.status=`complete`;let t=te.get(e);t?.markdown&&(n.props.markdown=t.markdown),t?.file&&(n.props.file=t.file),n.component===`PersonaArtifactInline`&&t?.props&&Object.keys(t.props).length>0&&(n.props.componentProps=t.props)}t.rawContent=JSON.stringify(n)}catch{}te.delete(e),p(t),k.delete(e)}}}else if(r.type===`error`&&r.recoverable===!1&&r.error!=null&&r.error!==``){let e=typeof r.error==`string`?r.error:r.error?.message==null?`Execution error`:String(r.error.message);n({type:`error`,error:Error(e)});let t=m;t&&t.streaming&&(t.streaming=!1,p(t)),n({type:`status`,status:`idle`})}}}ue.length=0};;){let{done:t,value:r}=await a.read();if(t)break;s+=o.decode(r,{stream:!0});let i=s.split(`
5
5
 
6
6
  `);s=i.pop()??``;for(let t of i){let r=t.split(`
7
- `),i=`message`,a=``,o=null;for(let e of r)e.startsWith(`event:`)?i=e.replace(`event:`,``).trim():e.startsWith(`data:`)?a+=e.replace(`data:`,``).trim():e.startsWith(`id:`)&&(o=e.slice(3).trim());let s=()=>{o!==null&&o!==``&&n({type:`cursor`,id:o})};if(!a){s();continue}let c;try{c=JSON.parse(a)}catch(e){n({type:`error`,error:e instanceof Error?e:/* @__PURE__ */ Error(`Failed to parse chat stream payload`)});continue}let l=typeof c==`object`&&c&&!Array.isArray(c)?c:null,d=i===`message`?typeof l?.type==`string`?l.type:`message`:i;if(e.onSSEEvent?.(d,c),e.parseSSEEvent){g.current=m;let t=await vn(e,c,n,g,p,u,_);if(g.current&&g.current!==m&&(m=g.current),t){s();continue}}l&&(le.push({...l,type:d}),ue()),s()}}ue()}var yn,bn=o((()=>{Ce(),Ae(),Ze(),mn(),yn=e=>e.startsWith(`{`)||e.startsWith(`[`)||e.startsWith(`<`)}));bn(),g();const{setLoader:xn,load:Sn,provide:Cn,getSync:wn}=h({fallbackImport:()=>Promise.resolve().then(()=>(bn(),hn))}),Tn=Sn,En=Cn,Dn=wn;En(hn);var On=`4.29.0`,kn,An=o((()=>{kn=On})),jn=/* @__PURE__ */ s({deleteAllConversations:()=>Kn,deleteConversation:()=>Gn,finalizeDisplayProjections:()=>Wn,getConversation:()=>Un,historyErrorFor:()=>Rn,listConversations:()=>Hn,readErrorCode:()=>In,recoverFromUnauthorized:()=>Ln,resetVisitor:()=>qn});function Mn(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function Nn(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function Pn(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`authentication_required`,`This browser is bound to a signed-in user and needs a fresh identity proof`);return n&&e.setHistoryIdentityStatus({state:`browser_only`,reason:`proof_unavailable_before_binding`}),null}async function Fn(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let i=await e.reinitWithProof(n);if(i.visitor?.identityStatus!==`admitted`||i.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,Zn);return i}async function In(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function Ln(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,Qn);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,$n);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,er);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function Rn(e,t,n){let r=await In(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,Zn);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,Qn)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,$n):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,er):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function zn(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`ignored`?new e.HistoryClientError(`identity_contract_violation`,`Server reported an ignored identity proof on a success response`):new e.HistoryClientError(`proof_not_admitted`,`The response did not acknowledge the identity proof this request sent`)}if(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function Bn(e,t,n){Vn(e);let r=n.trackIdentity!==!1,i=await e.initSession(),a=null;Nn(e,n.scope)===`verified-user`&&(a=await Pn(e,i,r),a&&(i=await Fn(e,i,a,r)));let o=e.historyInternals.visitorStore,s=!1;for(;;){let c=o?.revision()??0,l=await e.readVisitorToken();if(!l&&!n.visitorTokenOptional)throw new e.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let u=await fetch(Mn(e,t,{...n.query,sessionId:i.sessionId}),{method:n.method,headers:{"X-Persona-Version":kn,...l?{"X-Visitor-Token":l}:{},...a?{"X-Identity-Proof":a}:{},...n.body===void 0?{}:{"Content-Type":`application/json`}},...n.body===void 0?{}:{body:JSON.stringify(n.body)},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!s){s=!0,i=await Ln(e,await In(e,u),a,r);continue}if(!u.ok)throw await Rn(e,u,r);let d=u.headers.get(`X-History-Identity-Status`),f=await u.json().catch(()=>void 0);if(o&&o.revision()!==c)throw new e.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return zn(e,d,a!==null,r),f}}function Vn(e){if(!e.isClientTokenMode())throw Error(`Conversation history is only available in client token mode`);if(!e.isHistoryCapable())throw new e.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`)}async function Hn(e,t){let n=await Bn(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(Xn),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function Un(e,t,n){let r=await Bn(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Xn(r),messages:Array.isArray(r?.messages)?r.messages:[],nextMessageCursor:typeof r?.nextMessageCursor==`string`?r.nextMessageCursor:null,conversationRevision:typeof r?.conversationRevision==`string`?r.conversationRevision:null}}async function Wn(e,t,n){Vn(e);let r=0;for(let t of n){let n=t.displayContent.length;if(n>Jn)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${Jn} character limit`);r+=n}if(r>Yn)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${Yn} character limit`);await e.initSession();let i=e.historyInternals.visitorStore,a=i?.revision()??0,o=await Bn(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:`PATCH`,body:{messages:n},scope:`browser`,keepalive:r<=Yn,trackIdentity:!1}),s=typeof o?.conversationRevision==`string`?o.conversationRevision:null;return s&&e.clientSession?.conversationId===t&&(i?.revision()??0)===a&&e.historyInternals.setStoredConversationRevision?.(s),{conversationRevision:s}}async function Gn(e,t,n){let r=await Bn(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function Kn(e,t){let n=await Bn(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 qn(e){Vn(e),e.setHistoryIdentityStatus({state:`resetting`});try{await Bn(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var Jn,Yn,Xn,Zn,Qn,$n,er,tr=o((()=>{An(),Jn=32768,Yn=49152,Xn=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:``}},Zn=`The identity proof was not admitted; account history is unavailable`,Qn=`The identity proof was rejected`,$n=`The request carried no visitor credential`,er=`The stored visitor belongs to a different signed-in user`}));tr(),g();const{setLoader:nr,load:rr,provide:ir}=h({fallbackImport:()=>Promise.resolve().then(()=>(tr(),jn))}),ar=rr;ir(jn);var or,sr=o((()=>{Gt(),or=e=>{let{mount:t,overlay:n,sessionRef:r}=e,i=(e,i,a)=>{let o=i.trim();if(!o||!r.current)return;let s=e.getAttribute(`data-tool-call-id`)??``,c=a.source===`free-text`;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:answered`,{detail:{toolUseId:s,answer:o,answers:a.structured,values:a.values??(a.source===`multi`?o.split(`, `):[o]),isFreeText:c,source:a.source},bubbles:!0,composed:!0})),Vt(n,s);let l=r.current.getMessages().find(e=>e.toolCall?.id===s);l?.agentMetadata?.awaitingLocalTool?r.current.resolveAskUserQuestion(l,a.structured??o):r.current.sendMessage(o)},a=e=>{let t=r.current;if(!t)return;let n=e.getAttribute(`data-tool-call-id`)??``,i=t.getMessages().find(e=>e.toolCall?.id===n);i&&t.persistAskUserQuestionProgress(i,{answers:Nt(e,i),currentIndex:Ot(e)})},o=e=>Object.entries(e).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `),s=t=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let n=Ot(t);if(n>=X(t)-1)return;let i=r.current?.getMessages().find(e=>e.toolCall?.id===t.getAttribute(`data-tool-call-id`));i&&(Wt(t,i,e.config(),n+1),a(t))};return{click:c=>{let l=c.target.closest(`[data-ask-user-action]`);if(!l)return;let u=l.closest(`[data-persona-ask-sheet-for]`);if(!u)return;let d=l.getAttribute(`data-ask-user-action`);if(c.preventDefault(),c.stopPropagation(),d===`dismiss`){let e=u.getAttribute(`data-tool-call-id`)??``;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{toolUseId:e},bubbles:!0,composed:!0})),Vt(n,e);let i=r.current?.getMessages().find(t=>t.toolCall?.id===e);i?.agentMetadata?.awaitingLocalTool&&(r.current?.markAskUserQuestionResolved(i),r.current?.resolveAskUserQuestion(i,`(dismissed)`))}else if(d===`pick`){let e=l.getAttribute(`data-option-label`);if(!e)return;let t=u.getAttribute(`data-multi-select`)===`true`,n=At(u);if(n&&t){let t=Et(u)[Ot(u)],n=new Set(Array.isArray(t)?t:[]);n.has(e)?n.delete(e):n.add(e),Ut(u,Array.from(n)),a(u);return}if(n){Ut(u,e),a(u),s(u);return}if(t){let e=l.getAttribute(`aria-pressed`)===`true`;l.setAttribute(`aria-pressed`,e?`false`:`true`),l.classList.toggle(`persona-ask-pill-selected`,!e);let t=u.querySelector(`[data-ask-user-action="submit-multi"]`);t&&(t.disabled=Ht(u).length===0);return}i(u,e,{source:`pick`,values:[e]})}else if(d===`submit-multi`){let e=Ht(u);if(e.length===0)return;i(u,e.join(`, `),{source:`multi`,values:e})}else if(d===`open-free-text`){let e=u.querySelector(`[data-ask-free-text-row="true"]`);e&&(e.classList.remove(`persona-hidden`),e.querySelector(`[data-ask-free-text-input="true"]`)?.focus())}else if(d===`focus-free-text`)u.querySelector(`[data-ask-free-text-input="true"]`)?.focus();else if(d===`submit-free-text`){let e=u.querySelector(`[data-ask-free-text-input="true"]`)?.value??``;if(!e.trim())return;if(At(u)){Ut(u,e.trim()),a(u),s(u);return}i(u,e,{source:`free-text`})}else if(d===`next`||d===`back`){if(!r.current)return;let t=u.getAttribute(`data-tool-call-id`)??``,n=r.current.getMessages().find(e=>e.toolCall?.id===t);if(!n)return;let i=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;if(i){let e=Et(u)[Ot(u)];(typeof e!=`string`||e!==i)&&Ut(u,i)}let o=d===`next`?1:-1,s=Ot(u)+o;Wt(u,n,e.config(),s),a(u)}else if(d===`submit-all`){if(!r.current)return;let e=u.getAttribute(`data-tool-call-id`)??``,t=r.current.getMessages().find(t=>t.toolCall?.id===e);if(!t)return;let n=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;n&&Ut(u,n);let a=Nt(u,t);r.current.persistAskUserQuestionProgress(t,{answers:a,currentIndex:Ot(u)});let s=o(a);i(u,s||`(submitted)`,{source:`submit-all`,structured:a})}else if(d===`skip`){if(!r.current)return;let s=u.getAttribute(`data-tool-call-id`)??``,c=r.current.getMessages().find(e=>e.toolCall?.id===s);if(!c)return;let l=At(u),d=Ot(u),f=d>=X(u)-1;if(!l){t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{toolUseId:s},bubbles:!0,composed:!0})),Vt(n,s),c.agentMetadata?.awaitingLocalTool&&(r.current.markAskUserQuestionResolved(c),r.current.resolveAskUserQuestion(c,`(dismissed)`));return}Ut(u,``);let p=u.querySelector(`[data-ask-free-text-input="true"]`);if(p&&(p.value=``),f){let e=Nt(u,c),t=o(e);i(u,t||`(skipped)`,{source:`submit-all`,structured:e});return}Wt(u,c,e.config(),d+1),a(u)}},keydown:e=>{if(e.key!==`Enter`)return;let t=e.target;if(!t.matches?.(`[data-ask-free-text-input="true"]`))return;let n=t.closest(`[data-persona-ask-sheet-for]`);if(!n)return;e.preventDefault();let r=t.value;r.trim()&&(At(n)?(Ut(n,r.trim()),a(n),s(n)):i(n,r,{source:`free-text`}))}}}}));function cr(e,t,n){if(n===`input-start`)return t===0;let r=t>0?e[t-1]:``;return n===`line-start`?r===``||r===`
8
- `:r===``||fr.test(r)}function lr(e,t,n=`@`,r=`anywhere`,i=!1){if(!n||t<=0||t>e.length)return null;let a=t-1;for(;a>=0;){let o=e[a];if(o===n)return cr(e,a,r)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(o===`
9
- `||o===``||!i&&fr.test(o))return null;a--}return null}function ur(e,t,n){for(let r of n){let n=lr(e,t,r.trigger,r.position??`anywhere`,r.allowSpaces??!1);if(n)return{channel:r,match:n}}return null}function dr(e){return!e||e!==`insertFromPaste`&&e!==`insertFromDrop`}var fr,pr=o((()=>{fr=/\s/}));function mr(e){return[{trigger:e.trigger??`@`,position:e.triggerPosition??`anywhere`,allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},...(e.triggers??[]).map(e=>({trigger:e.trigger,position:e.triggerPosition??`anywhere`,allowSpaces:e.allowSpaces??!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton===!0,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText}))]}var hr=o((()=>{})),gr=o((()=>{}));function _r(e){e.delayMs!==void 0&&(Cr=Er(e.delayMs)),e.skipDelayMs!==void 0&&(wr=Er(e.skipDelayMs))}function vr(e){kr.get(e)?.hide()}function yr(e){kr.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:r,hint:i,enabled:a=!0,gap:o=br,viewportPadding:s=xr}=e,c=()=>t.ownerDocument,l=()=>c().defaultView??window,u=null,d=null,f=null,p=null,m,h=!1,g=!1,_=!1,v=()=>(typeof r==`function`?r():r).trim(),y=()=>(typeof i==`function`?i():i??``).trim(),b=()=>Er(e.delayMs??Cr),x=()=>Er(e.skipDelayMs??wr),S=()=>{m!==void 0&&(l().clearTimeout(m),m=void 0)},C=()=>{S();let e=u!==null;p?.(),p=null,u?.remove(),u=null,d=null,f=null,e&&Or(x())},w=()=>{if(!u)return;let e=c(),n=l(),r=t.getBoundingClientRect(),i=u.getBoundingClientRect(),a=e.documentElement.clientWidth||n.innerWidth,d=e.documentElement.clientHeight||n.innerHeight,f=a-s-i.width,p=r.left+r.width/2-i.width/2,m=Pr(p,s,f),h=r.top-s,g=d-s-r.bottom,_=h>=i.height+o||h>=g?`top`:`bottom`,v=_===`top`?r.top-o-i.height:r.bottom+o,y=d-s-i.height,b=Pr(v,s,y),x=r.left+r.width/2,S=Math.max(Sr,i.width-Sr),C=Pr(x-m,Sr,S);u.dataset.placement=_,u.style.left=`${m}px`,u.style.top=`${b}px`,u.style.setProperty(`--persona-tooltip-arrow-x`,`${C}px`)},T=()=>{if(_||!a||u||!t.isConnected||jr(t))return;let e=v(),n=Nr(t);if(!e||!n)return;let r=c(),i=l();u=r.createElement(`div`),u.className=`persona-control-tooltip`,u.setAttribute(`role`,`tooltip`),u.dataset.state=`measuring`,u.style.zIndex=String(un);let o=i.getComputedStyle?.(t);if(o){for(let e of Fr){let t=o.getPropertyValue(e).trim();t&&u.style.setProperty(e,t)}o.fontFamily&&(u.style.fontFamily=o.fontFamily)}d=r.createElement(`span`),d.className=`persona-control-tooltip__label`,d.textContent=e,u.appendChild(d);let s=y();s&&(f=r.createElement(`span`),f.className=`persona-control-tooltip__hint`,f.textContent=s,u.appendChild(f));let m=r.createElement(`span`);m.className=`persona-control-tooltip__arrow`,u.appendChild(m),n.appendChild(u),w(),u.dataset.state=`open`;let h=()=>{t.isConnected?(d&&(d.textContent=v()),f&&(f.textContent=y()),w()):C()};i.addEventListener(`scroll`,h,!0),i.addEventListener(`resize`,h);let g=t.getRootNode(),b=Mr(g)?g:r.documentElement,x=typeof MutationObserver>`u`?null:new MutationObserver(()=>{t.isConnected||C()});x?.observe(b,{childList:!0,subtree:!0}),p=()=>{i.removeEventListener(`scroll`,h,!0),i.removeEventListener(`resize`,h),x?.disconnect()}},E=e=>{_||u||(S(),e||b()<=0||Dr()?T():m=l().setTimeout(()=>{m=void 0,T()},b()))},D=()=>{h||g?E(g):C()},O=()=>{let e=l();e.matchMedia&&e.matchMedia(`(hover: none)`).matches||(h=!0,D())},ee=()=>{h=!1,D()},k=()=>{try{g=t.matches(`:focus-visible`)}catch{g=!0}D()},A=()=>{g=!1,D()},j=()=>{h=!1,g=!1,C()},te=e=>{e.key===`Escape`&&j()};n.addEventListener(`mouseenter`,O),n.addEventListener(`mouseleave`,ee),t.addEventListener(`focus`,k),t.addEventListener(`blur`,A),t.addEventListener(`keydown`,te),t.addEventListener(`click`,j);let ne={get isOpen(){return u!==null},show:T,hide:C,reposition:w,destroy:()=>{_||(_=!0,C(),n.removeEventListener(`mouseenter`,O),n.removeEventListener(`mouseleave`,ee),t.removeEventListener(`focus`,k),t.removeEventListener(`blur`,A),t.removeEventListener(`keydown`,te),t.removeEventListener(`click`,j),kr.delete(t))}};return kr.set(t,ne),ne}var br,xr,Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr,Nr,Pr,Fr,Ir=o((()=>{dn(),gr(),br=8,xr=8,Sr=10,Cr=200,wr=300,Tr=0,Er=e=>Math.max(0,e),Dr=()=>Date.now()<Tr,Or=e=>{Tr=e>0?Date.now()+e:0},kr=/* @__PURE__ */ new WeakMap,Ar=`data-persona-tooltip-suppressed`,jr=e=>typeof e.closest==`function`&&e.closest(`[data-persona-tooltip-suppressed]`)!==null,Mr=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&`host`in e,Nr=e=>{let t=e.getRootNode?.();return Mr(t)?t:e.ownerDocument.body},Pr=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),Fr=[...[`background`,`foreground`,`hint-fg`,`radius`,`font-size`,`padding`,`max-width`,`shadow`,`arrow-display`].map(e=>`--persona-tooltip-${e}`),`--persona-font-family`,`--persona-radius-sm`]})),Lr,Rr,zr,Br=o((()=>{Lr=(e,t)=>e.visible!==!1&&(e.mode!==`transient`||t===`connecting`||t===`paused`||t===`resuming`||t===`error`),Rr=(e,t,n)=>{let r=t.mode===`transient`,i=e.hasAttribute(`data-persona-composer-reason`)||e.hasAttribute(`data-persona-composer-notice`);e.style.display=Lr(t,n)||r&&i&&t.visible!==!1?``:`none`,e.classList.toggle(`persona-mt-2`,!r),e.classList.toggle(`persona-mb-2`,r)},zr=(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 Vr(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=Hr(t)&&Hr(r)?Vr(t,r):r}return n}var Hr,Ur=o((()=>{Hr=e=>typeof e==`object`&&!!e&&!Array.isArray(e)}));function Wr(e,t=``){return Object.entries(e).flatMap(([e,n])=>{let r=t?`${t}.${e}`:e;return Qr(n)?Wr(n,r):[r]})}function Gr(e,t){for(let n of t.split(`.`)){if(!Qr(e)||!Object.prototype.hasOwnProperty.call(e,n))return`absent`;if(e=e[n],e===void 0)return`clear`}return`explicit`}function Kr(e,t){return e?.[Zr]??t.filter(t=>Gr(e,t)===`explicit`)}function qr(e,t){return Object.defineProperty(e,Zr,{value:t,enumerable:!0,configurable:!0}),e}function Jr(e,t,n){return qr(e,Kr(t,Wr(n)))}function Yr(e,t,n){let r=t[Zr];if(r)return r;let i=new Set(Kr(e,n));for(let e of n){let n=Gr(t,e);n===`clear`&&i.delete(e),n===`explicit`&&i.add(e)}return[...i]}function Xr(e,t,n){let r={...e};for(let e of t){if(n.includes(e))continue;let t=e.split(`.`),i=r;for(let e of t.slice(0,-1)){let t=i[e];if(!Qr(t)){i=void 0;break}i[e]={...t},i=i[e]}i&&delete i[t[t.length-1]]}return r}var Zr,Qr,$r=o((()=>{Zr=Symbol(`persona.defaultsProvenance`),Qr=e=>typeof e==`object`&&!!e&&!Array.isArray(e)})),ei,ti,ni,ri,ii,ai,oi,si,ci=o((()=>{ei=Symbol(`persona.panelAliasProvenance`),ti=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),ni=(e,t)=>ti(e,t)&&e[t]!==void 0,ri=e=>({launcherWidth:ni(e?.launcher,`width`),legacyLauncherWidth:ni(e,`launcherWidth`),sidebarWidth:ni(e?.launcher,`sidebarWidth`),dockWidth:ni(e?.launcher?.dock,`width`)}),ii=e=>{let t=e?.[ei];return t?{...t}:ri(e)},ai=(e,t)=>(Object.defineProperty(e,ei,{value:t,enumerable:!0,configurable:!0}),e),oi=(e,t)=>ai(e,ii(t)),si=(e,t)=>{let n=t[ei];if(n)return{...n};let r=ii(e);return ti(t,`launcherWidth`)&&(r.legacyLauncherWidth=t.launcherWidth!==void 0),ti(t,`launcher`)&&t.launcher===void 0?(r.launcherWidth=!1,r.sidebarWidth=!1,r.dockWidth=!1,r):(ti(t.launcher,`width`)&&(r.launcherWidth=t.launcher?.width!==void 0),ti(t.launcher,`sidebarWidth`)&&(r.sidebarWidth=t.launcher?.sidebarWidth!==void 0),ti(t.launcher,`dock`)&&t.launcher?.dock===void 0?r.dockWidth=!1:ti(t.launcher?.dock,`width`)&&(r.dockWidth=t.launcher?.dock?.width!==void 0),r)}}));function li(e){return e?.future?.v5Defaults===!0?`v5`:`v4`}function ui(e){let t=li(e)===`v5`?Si:xi;return Vr(bi,t)}function di(e,t){if(e||t)return e?t?Vr(e,t):e:t}function fi(e){let t=ui(e);return e?Jr(oi({...t,...e,theme:di(t.theme,e.theme),darkTheme:di(t.darkTheme,e.darkTheme),launcher:{...t.launcher,...e.launcher,dock:{...t.launcher?.dock,...e.launcher?.dock},clearChat:{...t.launcher?.clearChat,...e.launcher?.clearChat}},...t.composer||e.composer?{composer:{...t.composer,...e.composer}}:{},tooltip:{...t.tooltip,...e.tooltip},copy:{...t.copy,...e.copy},sendButton:{...t.sendButton,...e.sendButton},statusIndicator:{...t.statusIndicator,...e.statusIndicator},voiceRecognition:{...t.voiceRecognition,...e.voiceRecognition},features:(()=>{let n=t.features?.artifacts,r=e.features?.artifacts,i=t.features?.scrollToBottom,a=e.features?.scrollToBottom,o=t.features?.scrollBehavior,s=e.features?.scrollBehavior,c=t.features?.streamAnimation,l=e.features?.streamAnimation,u=t.features?.askUserQuestion,d=e.features?.askUserQuestion,f=t.features?.history,p=e.features?.history,m=n===void 0&&r===void 0?void 0:{...n,...r,layout:{...n?.layout,...r?.layout}},h=i===void 0&&a===void 0?void 0:{...i,...a},g=o===void 0&&s===void 0?void 0:{...o,...s},_=c===void 0&&l===void 0?void 0:{...c,...l},v=u===void 0&&d===void 0?void 0:{...u,...d,styles:{...u?.styles,...d?.styles}},y=f===void 0&&p===void 0?void 0:{...f,...p,copy:{...f?.copy,...p?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...h===void 0?{}:{scrollToBottom:h},...g===void 0?{}:{scrollBehavior:g},...m===void 0?{}:{artifacts:m},..._===void 0?{}:{streamAnimation:_},...v===void 0?{}:{askUserQuestion:v},...y===void 0?{}:{history:y}}})(),suggestionChips:e.suggestionChips??t.suggestionChips,suggestionChipsConfig:{...t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...t.layout,...e.layout,header:{...t.layout?.header,...e.layout?.header},messages:{...t.layout?.messages,...e.layout?.messages,...t.layout?.messages?.user||e.layout?.messages?.user?{user:{...t.layout?.messages?.user,...e.layout?.messages?.user}}:{},...t.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...t.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...t.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...t.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...t.layout?.slots,...e.layout?.slots}},markdown:{...t.markdown,...e.markdown,options:{...t.markdown?.options,...e.markdown?.options}},messageActions:{...t.messageActions,...e.messageActions}},e),e,Si):Jr(oi(t),void 0,Si)}var pi,mi,hi,gi,_i,vi,yi,bi,xi,Q,Si,Ci,wi=o((()=>{Ur(),$r(),ci(),gr(),pi=`min(440px, calc(100vw - 24px))`,mi=`440px`,hi=`40px`,gi=`How can I help...`,_i={collapsedMode:`tool-call`,activePreview:!1,grouped:!1,groupedMode:`stack`,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},vi={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},yi={enabled:!0,mountMode:`floating`,dock:{side:`right`,width:`420px`},title:`Chat Assistant`,subtitle:`Here to help you get answers fast`,agentIconText:`💬`,agentIconName:`bot`,headerIconName:`bot`,position:`bottom-right`,width:pi,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:`40px`,headerIconSize:hi,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)`},bi={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:yi,copy:{inputPlaceholder:gi,sendButtonLabel:`Send`},sendButton:{borderWidth:`0px`,paddingX:`12px`,paddingY:`10px`,borderColor:void 0,useIcon:!0,iconText:`↑`,showTooltip:!0,tooltipText:`Send message`,iconName:`send`},statusIndicator:{visible:!0,idleText:`Online`,connectingText:`Connecting…`,connectedText:`Streaming…`,errorText:`Offline`},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:`mic`,borderWidth:`0px`,iconColor:void 0,backgroundColor:`transparent`,borderColor:`transparent`,recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:`transparent`,showTooltip:!0,tooltipText:`Start voice recognition`},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:`arrow-down`,label:``},scrollBehavior:{mode:`anchor-top`,anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:_i,reasoningDisplay:vi,streamAnimation:{type:`none`,placeholder:`none`,speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:`Other…`,freeTextPlaceholder:`Type your answer…`,submitLabel:`Send`},history:{enabled:!1,presentation:`panel`,showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:[`Show me what you can help with`,`Walk me through getting started`,`Answer a question about this page`],suggestionChipsConfig:{fontFamily:`sans-serif`,fontWeight:`500`,paddingX:`12px`,paddingY:`6px`},layout:{header:{layout:`default`,showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:`bubble`,avatar:{show:!1,position:`left`},timestamp:{show:!1,position:`below`},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:`hover`,align:`right`,layout:`pill-inside`},debug:!1},xi={},Q={variant:`circle`,width:`min(400px, calc(100vw - 24px))`,headerIconSize:`20px`},Si={launcher:Q,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`}}}},Ci=ui()}));function Ti(e){return typeof e==`string`?[{type:`text`,text:e}]:e}function Ei(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Di(e){return typeof e!=`string`&&e.some(e=>e.type===`image`)}function Oi(e){return typeof e==`string`?[]:e.filter(e=>e.type===`image`)}function ki(e){return{type:`text`,text:e}}function Ai(e,t){return{type:`image`,image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function ji(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result;t({type:`image`,image:n,mimeType:e.type,alt:e.name})},r.onerror=()=>n(/* @__PURE__ */ Error(`Failed to read file`)),r.readAsDataURL(e)})}function Mi(e,t=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`],n=10485760){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(`, `)}`}}function Ni(e){return Bi.includes(e)||e.startsWith(`image/`)}function Pi(e){return Ni(e.type)}function $(e,t,n){return{type:`file`,data:e,mimeType:t,filename:n}}async function Fi(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result;Pi(e)?t({type:`image`,image:n,mimeType:e.type,alt:e.name}):t({type:`file`,data:n,mimeType:e.type,filename:e.name})},r.onerror=()=>n(/* @__PURE__ */ Error(`Failed to read file`)),r.readAsDataURL(e)})}function Ii(e,t=Hi,n=10485760){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(`, `)}`}}function Li(e){let t=e.split(`.`);return t.length>1?t.pop().toLowerCase():``}function Ri(e,t){let n=Li(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 zi,Bi,Vi,Hi,Ui=o((()=>{zi=`[Image]`,Bi=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/svg+xml`,`image/bmp`],Vi=[`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`],Hi=[...Bi,...Vi]}));function Wi(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let n=t.getComputedStyle(e).lineHeight;if(!n||!n.trim().endsWith(`px`))return 20;let r=parseFloat(n);return Number.isFinite(r)&&r>0?r:20}function Gi(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:e>0?e:t}function Ki(e,t){e.style.maxHeight=`${t*Wi(e)}px`,e.style.overflowY=`auto`}function qi(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 Ji(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Yi(e,t){if(e.key!==`Enter`||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,r=t.submitKey??`enter`;return r===`none`?!1:r===`mod-enter`?n:n||!Ji(t)}function Xi(e){return(e.submitKey??`enter`)===`enter`?Ji(e)?`enter`:`send`:`enter`}function Zi(e,t){e.setAttribute(`enterkeyhint`,Xi(t))}function Qi(e,t){let n=t?.autocomplete;e.setAttribute(`autocomplete`,typeof n==`string`&&n?n:`off`);let r=(t,n)=>{n===void 0?e.removeAttribute(t):e.setAttribute(t,n)};r(`autocapitalize`,typeof t?.autocapitalize==`string`?t.autocapitalize:void 0),r(`spellcheck`,typeof t?.spellcheck==`boolean`?String(t.spellcheck):void 0),r(`inputmode`,typeof t?.inputmode==`string`&&t.inputmode?t.inputmode:void 0),r(`aria-label`,typeof t?.ariaLabel==`string`&&t.ariaLabel?t.ariaLabel:void 0)}function $i(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 ea=o((()=>{})),ta,na,ra,ia,aa,oa,sa,ca,la,ua,da=o((()=>{Br(),H(),I(),wi(),Ui(),Ir(),ea(),ta=`persona-composer-control`,na=`persona-composer-control--glyph`,ra=(e,t,n)=>{let r=e.ownerDocument?.defaultView;if(!r)return;let i=r.getComputedStyle(e);for(let e of n){let n=i.getPropertyValue(e).trim();n?t.style.setProperty(e,n):t.style.removeProperty(e)}},ia=(e,t)=>{let n=B(`textarea`);n.setAttribute(`data-persona-composer-input`,``),n.placeholder=e?.copy?.inputPlaceholder??`How can I help...`,n.dir=`auto`,Zi(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:qi(n)}),Qi(n,e?.composer?.inputAttributes),n.className=`persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea`,n.rows=1,n.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,n.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`;let r=Gi(e?.composer?.maxLines,t?.defaultMaxLines??3),i=`${r*20}px`;n.style.maxHeight=i,n.style.overflowY=`auto`;let a=()=>{let e=n.style.maxHeight;if(e!==i){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=r*Wi(n);return i=`${t}px`,n.style.maxHeight=i,t},o=()=>{n.addEventListener(`input`,()=>{n.style.height=`auto`;let e=Math.min(n.scrollHeight,a());n.style.height=`${e}px`})};return n.style.border=`none`,n.style.outline=`none`,n.style.borderWidth=`0`,n.style.borderStyle=`none`,n.style.borderColor=`transparent`,n.addEventListener(`focus`,()=>{n.style.border=`none`,n.style.outline=`none`,n.style.borderWidth=`0`,n.style.borderStyle=`none`,n.style.borderColor=`transparent`,n.style.boxShadow=`none`}),n.addEventListener(`blur`,()=>{n.style.border=`none`,n.style.outline=`none`}),{textarea:n,attachAutoResize:o}},aa=(e,t,n=`send`)=>{let r=V(`span`,{className:`persona-composer-glyph-stack`,attrs:{"data-mode":n,"data-persona-glyph-stack":``}});return e.setAttribute(`data-glyph`,`send`),t.setAttribute(`data-glyph`,`stop`),r.append(e,t),r},oa=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,r=t.iconText??`↑`,i=t.iconName,a=t.stopIconName??`square`,o=t.tooltipText??`Send message`,s=t.stopTooltipText??`Stop generating`,c=e?.copy?.sendButtonLabel??`Send`,l=e?.copy?.stopButtonLabel??`Stop`,u=t.showTooltip??!1,d=t.size,f=parseFloat(d??``)||40,p=t.backgroundColor,m=t.textColor,h=B(`div`,`persona-send-button-wrapper`),g=V(`button`,{className:Qe(`persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer`,n?`persona-flex persona-items-center persona-justify-center ${ta}`:`persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold`,n&&!p&&`persona-bg-persona-primary`,!n&&!m&&`persona-text-white`),attrs:{type:`submit`,"data-persona-composer-submit":``,"data-persona-send-mode":`send`},style:{width:n?d:void 0,height:n?d:void 0,minWidth:n?d:void 0,minHeight:n?d:void 0,fontSize:n?`18px`:void 0,lineHeight:n?`1`:void 0,color:n?m||`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`:m||void 0,backgroundColor:n&&p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?`solid`:void 0,borderColor:t.borderColor||void 0,paddingLeft:n?`0`:t.paddingX||void 0,paddingRight:n?`0`:t.paddingX||void 0,paddingTop:n?`0`:t.paddingY||void 0,paddingBottom:n?`0`:t.paddingY||void 0}}),_=null,v=null,y=null;if(n){let e=parseFloat(t.iconSize??``)||Math.round(f*.5),n=t.iconStrokeWidth??2,o=m?.trim()||`currentColor`;if(i&&(_=F(i,e,o,n)),v=F(a,e,o,n),!t.iconSize)for(let t of[_,v])t&&(t.style.width=`var(--persona-components-composer-sendIconSize, ${e}px)`,t.style.height=`var(--persona-components-composer-sendIconSize, ${e}px)`);_&&v?(y=aa(_,v),g.appendChild(y)):_?g.appendChild(_):(g.textContent=r,v=null)}else g.textContent=c;g.setAttribute(`aria-label`,o),h.appendChild(g),yr({anchor:g,trigger:h,text:()=>g.getAttribute(`aria-label`)??``,enabled:u});let b=`send`;return{button:g,wrapper:h,setMode:e=>{if(e===b)return;b=e;let t=e===`stop`?s:o;g.setAttribute(`aria-label`,t),g.setAttribute(`data-persona-send-mode`,e),n?(g.querySelector(`[data-persona-glyph-stack]`)??y)?.setAttribute(`data-mode`,e):g.textContent=e===`stop`?l:c},glyphStack:y}},sa=e=>{let t=e?.voiceRecognition??{};if(t.enabled!==!0)return null;let n=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),r=t.provider?.type===`runtype`,i=t.provider?.type===`custom`;if(!(n||r||i))return null;let a=t.iconName??`mic`,o=t.iconSize,s=parseFloat(o??``)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,l=t.iconColor??e?.sendButton?.textColor,u=B(`div`,`persona-send-button-wrapper`),d=V(`button`,{className:Qe(`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer`,ta,!o&&`persona-composer-control--glyph`),attrs:{type:`button`,"data-persona-composer-mic":``,"data-state":`idle`,"aria-label":t.tooltipText??`Start voice recognition`},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:`18px`,lineHeight:`1`,color:l||`var(--persona-text, #111827)`,backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?`solid`:void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),f=F(a,s,l||`currentColor`,1.5);f?d.appendChild(f):d.textContent=`🎤`,u.appendChild(d);let p=t.tooltipText??`Start voice recognition`;return yr({anchor:d,trigger:u,text:()=>d.getAttribute(`aria-label`)??p,enabled:t.showTooltip??!1}),{button:d,wrapper:u}},ca=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=B(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`);n.setAttribute(`data-persona-composer-attachment-previews`,``),n.style.display=`none`;let r=B(`input`);r.type=`file`,r.setAttribute(`data-persona-composer-attachment-input`,``),r.accept=(t.allowedTypes??Hi).join(`,`),r.multiple=(t.maxFiles??4)>1,r.style.display=`none`,r.setAttribute(`aria-label`,`Attach files`);let i=t.buttonIconName??`paperclip`,a=B(`div`,`persona-send-button-wrapper`),o=V(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${ta} ${na}`,attrs:{type:`button`,"data-persona-composer-attachment-button":``,"aria-label":t.buttonTooltipText??`Attach file`},style:{fontSize:`18px`,lineHeight:`1`}}),s=F(i,24,`currentColor`,1.5);s?o.appendChild(s):o.textContent=`📎`,o.addEventListener(`click`,e=>{e.preventDefault(),r.click()}),a.appendChild(o);let c=t.buttonTooltipText??`Attach file`;return yr({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??c}),{button:o,wrapper:a,input:r,previewsContainer:n}},la=e=>{let t=e?.statusIndicator??{},n=t.align===`left`?`persona-text-left`:t.align===`center`?`persona-text-center`:`persona-text-right`,r=B(`div`,`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute(`data-persona-composer-status`,``),Rr(r,t,`idle`);let i=t.idleText??`Online`;if(t.idleLink){let e=B(`a`);e.href=t.idleLink,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=i,e.style.color=`inherit`,e.style.textDecoration=`none`,r.appendChild(e)}else r.textContent=i;return r},ua=()=>V(`div`,{className:`persona-mb-3 persona-flex persona-flex-wrap persona-gap-2`,attrs:{"data-persona-composer-suggestions":``}})}));function fa(e){let{config:t,onOpen:n}=e,r=t.buttonIconName??`plus`,i=t.buttonTooltipText??`Add context`,a=B(`div`,`persona-send-button-wrapper`),o=V(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${ta} ${na}`,attrs:{type:`button`,"data-persona-composer-mention-button":``,"aria-label":i,"aria-haspopup":`listbox`,"aria-expanded":`false`},style:{fontSize:`18px`,lineHeight:`1`}}),s=F(r,24,`currentColor`,1.5);return s?o.appendChild(s):o.textContent=`+`,o.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n()}),a.appendChild(o),yr({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??i}),{button:o,wrapper:a}}var pa=o((()=>{H(),I(),Ir(),da()})),ma,ha,ga,_a=o((()=>{g(),{setLoader:ma,load:ha}=h({fallbackImport:()=>import(`@runtypelabs/persona/context-mentions`)}),ga=ha})),va,ya,ba,xa=o((()=>{g(),{setLoader:va,load:ya}=h({fallbackImport:()=>import(`@runtypelabs/persona/context-mentions-inline`),resetOnSetLoader:!0}),ba=ya}));function Sa(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=V(`span`,{className:Qe(`persona-mention-token`,t.readonly&&`persona-mention-token-readonly`),attrs:{"data-mention-source":e.sourceId,title:e.label,role:`img`,"aria-label":`${e.label} mention`}});e.color&&n.style.setProperty(`--persona-mention-token-accent`,e.color);let r=F(e.iconName??`at-sign`,13,`currentColor`,2);if(r){let e=B(`span`,`persona-mention-token-icon`);e.appendChild(r),n.appendChild(e)}return n.appendChild(V(`span`,{className:`persona-mention-token-label`,text:`@${e.label}`})),n}var Ca=o((()=>{H(),I()}));function wa(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:r,createMentionButton:i}=e.deps??Ta,a=e.config.contextMentions;if(!a?.enabled)return null;let o=mr(a).filter(e=>e.sources.length>0);if(o.length===0)return typeof console<`u`&&console.warn(`[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled.`),null;let s=o.filter(e=>e.sources.some(e=>typeof e.matchCommand==`function`)),c=e=>s.some(t=>t.trigger?t.position===`line-start`?e.split(`
7
+ `),i=`message`,a=``,o=null;for(let e of r)e.startsWith(`event:`)?i=e.replace(`event:`,``).trim():e.startsWith(`data:`)?a+=e.replace(`data:`,``).trim():e.startsWith(`id:`)&&(o=e.slice(3).trim());let s=()=>{o!==null&&o!==``&&n({type:`cursor`,id:o})};if(!a){s();continue}let c;try{c=JSON.parse(a)}catch(e){n({type:`error`,error:e instanceof Error?e:/* @__PURE__ */ Error(`Failed to parse chat stream payload`)});continue}let l=typeof c==`object`&&c&&!Array.isArray(c)?c:null,d=i===`message`?typeof l?.type==`string`?l.type:`message`:i;if(e.onSSEEvent?.(d,c),e.parseSSEEvent){g.current=m;let t=await yn(e,c,n,g,p,u,_);if(g.current&&g.current!==m&&(m=g.current),t){s();continue}}l&&(ue.push({...l,type:d}),de()),s()}}de()}var bn,xn=o((()=>{we(),je(),Qe(),hn(),bn=e=>e.startsWith(`{`)||e.startsWith(`[`)||e.startsWith(`<`)}));xn(),g();const{setLoader:Sn,load:Cn,provide:wn,getSync:Tn}=h({fallbackImport:()=>Promise.resolve().then(()=>(xn(),gn))}),En=Cn,Dn=wn,On=Tn;Dn(gn);var kn=`4.29.1`,An,jn=o((()=>{An=kn})),Mn=/* @__PURE__ */ s({deleteAllConversations:()=>qn,deleteConversation:()=>Kn,finalizeDisplayProjections:()=>Gn,getConversation:()=>Wn,historyErrorFor:()=>zn,listConversations:()=>Un,readErrorCode:()=>Ln,recoverFromUnauthorized:()=>Rn,resetVisitor:()=>Jn});function Nn(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function Pn(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function Fn(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`authentication_required`,`This browser is bound to a signed-in user and needs a fresh identity proof`);return n&&e.setHistoryIdentityStatus({state:`browser_only`,reason:`proof_unavailable_before_binding`}),null}async function In(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let i=await e.reinitWithProof(n);if(i.visitor?.identityStatus!==`admitted`||i.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,Qn);return i}async function Ln(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function Rn(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,$n);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,er);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,tr);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function zn(e,t,n){let r=await Ln(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,Qn);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,$n)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,er):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,tr):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function Bn(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`ignored`?new e.HistoryClientError(`identity_contract_violation`,`Server reported an ignored identity proof on a success response`):new e.HistoryClientError(`proof_not_admitted`,`The response did not acknowledge the identity proof this request sent`)}if(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function Vn(e,t,n){Hn(e);let r=n.trackIdentity!==!1,i=await e.initSession(),a=null;Pn(e,n.scope)===`verified-user`&&(a=await Fn(e,i,r),a&&(i=await In(e,i,a,r)));let o=e.historyInternals.visitorStore,s=!1;for(;;){let c=o?.revision()??0,l=await e.readVisitorToken();if(!l&&!n.visitorTokenOptional)throw new e.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let u=await fetch(Nn(e,t,{...n.query,sessionId:i.sessionId}),{method:n.method,headers:{"X-Persona-Version":An,...l?{"X-Visitor-Token":l}:{},...a?{"X-Identity-Proof":a}:{},...n.body===void 0?{}:{"Content-Type":`application/json`}},...n.body===void 0?{}:{body:JSON.stringify(n.body)},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!s){s=!0,i=await Rn(e,await Ln(e,u),a,r);continue}if(!u.ok)throw await zn(e,u,r);let d=u.headers.get(`X-History-Identity-Status`),f=await u.json().catch(()=>void 0);if(o&&o.revision()!==c)throw new e.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return Bn(e,d,a!==null,r),f}}function Hn(e){if(!e.isClientTokenMode())throw Error(`Conversation history is only available in client token mode`);if(!e.isHistoryCapable())throw new e.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`)}async function Un(e,t){let n=await Vn(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(Zn),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function Wn(e,t,n){let r=await Vn(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Zn(r),messages:Array.isArray(r?.messages)?r.messages:[],nextMessageCursor:typeof r?.nextMessageCursor==`string`?r.nextMessageCursor:null,conversationRevision:typeof r?.conversationRevision==`string`?r.conversationRevision:null}}async function Gn(e,t,n){Hn(e);let r=0;for(let t of n){let n=t.displayContent.length;if(n>Yn)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${Yn} character limit`);r+=n}if(r>Xn)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${Xn} character limit`);await e.initSession();let i=e.historyInternals.visitorStore,a=i?.revision()??0,o=await Vn(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:`PATCH`,body:{messages:n},scope:`browser`,keepalive:r<=Xn,trackIdentity:!1}),s=typeof o?.conversationRevision==`string`?o.conversationRevision:null;return s&&e.clientSession?.conversationId===t&&(i?.revision()??0)===a&&e.historyInternals.setStoredConversationRevision?.(s),{conversationRevision:s}}async function Kn(e,t,n){let r=await Vn(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function qn(e,t){let n=await Vn(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 Jn(e){Hn(e),e.setHistoryIdentityStatus({state:`resetting`});try{await Vn(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var Yn,Xn,Zn,Qn,$n,er,tr,nr=o((()=>{jn(),Yn=32768,Xn=49152,Zn=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:``}},Qn=`The identity proof was not admitted; account history is unavailable`,$n=`The identity proof was rejected`,er=`The request carried no visitor credential`,tr=`The stored visitor belongs to a different signed-in user`}));nr(),g();const{setLoader:rr,load:ir,provide:ar}=h({fallbackImport:()=>Promise.resolve().then(()=>(nr(),Mn))}),or=ir;ar(Mn);var sr,cr=o((()=>{Kt(),sr=e=>{let{mount:t,overlay:n,sessionRef:r}=e,i=(e,i,a)=>{let o=i.trim();if(!o||!r.current)return;let s=e.getAttribute(`data-tool-call-id`)??``,c=a.source===`free-text`;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:answered`,{detail:{toolUseId:s,answer:o,answers:a.structured,values:a.values??(a.source===`multi`?o.split(`, `):[o]),isFreeText:c,source:a.source},bubbles:!0,composed:!0})),Ht(n,s);let l=r.current.getMessages().find(e=>e.toolCall?.id===s);l?.agentMetadata?.awaitingLocalTool?r.current.resolveAskUserQuestion(l,a.structured??o):r.current.sendMessage(o)},a=e=>{let t=r.current;if(!t)return;let n=e.getAttribute(`data-tool-call-id`)??``,i=t.getMessages().find(e=>e.toolCall?.id===n);i&&t.persistAskUserQuestionProgress(i,{answers:Pt(e,i),currentIndex:kt(e)})},o=e=>Object.entries(e).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `),s=t=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let n=kt(t);if(n>=Y(t)-1)return;let i=r.current?.getMessages().find(e=>e.toolCall?.id===t.getAttribute(`data-tool-call-id`));i&&(Gt(t,i,e.config(),n+1),a(t))};return{click:c=>{let l=c.target.closest(`[data-ask-user-action]`);if(!l)return;let u=l.closest(`[data-persona-ask-sheet-for]`);if(!u)return;let d=l.getAttribute(`data-ask-user-action`);if(c.preventDefault(),c.stopPropagation(),d===`dismiss`){let e=u.getAttribute(`data-tool-call-id`)??``;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{toolUseId:e},bubbles:!0,composed:!0})),Ht(n,e);let i=r.current?.getMessages().find(t=>t.toolCall?.id===e);i?.agentMetadata?.awaitingLocalTool&&(r.current?.markAskUserQuestionResolved(i),r.current?.resolveAskUserQuestion(i,`(dismissed)`))}else if(d===`pick`){let e=l.getAttribute(`data-option-label`);if(!e)return;let t=u.getAttribute(`data-multi-select`)===`true`,n=jt(u);if(n&&t){let t=Dt(u)[kt(u)],n=new Set(Array.isArray(t)?t:[]);n.has(e)?n.delete(e):n.add(e),Wt(u,Array.from(n)),a(u);return}if(n){Wt(u,e),a(u),s(u);return}if(t){let e=l.getAttribute(`aria-pressed`)===`true`;l.setAttribute(`aria-pressed`,e?`false`:`true`),l.classList.toggle(`persona-ask-pill-selected`,!e);let t=u.querySelector(`[data-ask-user-action="submit-multi"]`);t&&(t.disabled=Ut(u).length===0);return}i(u,e,{source:`pick`,values:[e]})}else if(d===`submit-multi`){let e=Ut(u);if(e.length===0)return;i(u,e.join(`, `),{source:`multi`,values:e})}else if(d===`open-free-text`){let e=u.querySelector(`[data-ask-free-text-row="true"]`);e&&(e.classList.remove(`persona-hidden`),e.querySelector(`[data-ask-free-text-input="true"]`)?.focus())}else if(d===`focus-free-text`)u.querySelector(`[data-ask-free-text-input="true"]`)?.focus();else if(d===`submit-free-text`){let e=u.querySelector(`[data-ask-free-text-input="true"]`)?.value??``;if(!e.trim())return;if(jt(u)){Wt(u,e.trim()),a(u),s(u);return}i(u,e,{source:`free-text`})}else if(d===`next`||d===`back`){if(!r.current)return;let t=u.getAttribute(`data-tool-call-id`)??``,n=r.current.getMessages().find(e=>e.toolCall?.id===t);if(!n)return;let i=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;if(i){let e=Dt(u)[kt(u)];(typeof e!=`string`||e!==i)&&Wt(u,i)}let o=d===`next`?1:-1,s=kt(u)+o;Gt(u,n,e.config(),s),a(u)}else if(d===`submit-all`){if(!r.current)return;let e=u.getAttribute(`data-tool-call-id`)??``,t=r.current.getMessages().find(t=>t.toolCall?.id===e);if(!t)return;let n=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;n&&Wt(u,n);let a=Pt(u,t);r.current.persistAskUserQuestionProgress(t,{answers:a,currentIndex:kt(u)});let s=o(a);i(u,s||`(submitted)`,{source:`submit-all`,structured:a})}else if(d===`skip`){if(!r.current)return;let s=u.getAttribute(`data-tool-call-id`)??``,c=r.current.getMessages().find(e=>e.toolCall?.id===s);if(!c)return;let l=jt(u),d=kt(u),f=d>=Y(u)-1;if(!l){t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{toolUseId:s},bubbles:!0,composed:!0})),Ht(n,s),c.agentMetadata?.awaitingLocalTool&&(r.current.markAskUserQuestionResolved(c),r.current.resolveAskUserQuestion(c,`(dismissed)`));return}Wt(u,``);let p=u.querySelector(`[data-ask-free-text-input="true"]`);if(p&&(p.value=``),f){let e=Pt(u,c),t=o(e);i(u,t||`(skipped)`,{source:`submit-all`,structured:e});return}Gt(u,c,e.config(),d+1),a(u)}},keydown:e=>{if(e.key!==`Enter`)return;let t=e.target;if(!t.matches?.(`[data-ask-free-text-input="true"]`))return;let n=t.closest(`[data-persona-ask-sheet-for]`);if(!n)return;e.preventDefault();let r=t.value;r.trim()&&(jt(n)?(Wt(n,r.trim()),a(n),s(n)):i(n,r,{source:`free-text`}))}}}}));function lr(e,t,n){if(n===`input-start`)return t===0;let r=t>0?e[t-1]:``;return n===`line-start`?r===``||r===`
8
+ `:r===``||pr.test(r)}function ur(e,t,n=`@`,r=`anywhere`,i=!1){if(!n||t<=0||t>e.length)return null;let a=t-1;for(;a>=0;){let o=e[a];if(o===n)return lr(e,a,r)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(o===`
9
+ `||o===``||!i&&pr.test(o))return null;a--}return null}function dr(e,t,n){for(let r of n){let n=ur(e,t,r.trigger,r.position??`anywhere`,r.allowSpaces??!1);if(n)return{channel:r,match:n}}return null}function fr(e){return!e||e!==`insertFromPaste`&&e!==`insertFromDrop`}var pr,mr=o((()=>{pr=/\s/}));function hr(e){return[{trigger:e.trigger??`@`,position:e.triggerPosition??`anywhere`,allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},...(e.triggers??[]).map(e=>({trigger:e.trigger,position:e.triggerPosition??`anywhere`,allowSpaces:e.allowSpaces??!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton===!0,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText}))]}var gr=o((()=>{})),_r=o((()=>{}));function vr(e){e.delayMs!==void 0&&(wr=Dr(e.delayMs)),e.skipDelayMs!==void 0&&(Tr=Dr(e.skipDelayMs))}function yr(e){Ar.get(e)?.hide()}function br(e){Ar.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:r,hint:i,enabled:a=!0,gap:o=xr,viewportPadding:s=Sr}=e,c=()=>t.ownerDocument,l=()=>c().defaultView??window,u=null,d=null,f=null,p=null,m,h=!1,g=!1,_=!1,v=()=>(typeof r==`function`?r():r).trim(),y=()=>(typeof i==`function`?i():i??``).trim(),b=()=>Dr(e.delayMs??wr),x=()=>Dr(e.skipDelayMs??Tr),S=()=>{m!==void 0&&(l().clearTimeout(m),m=void 0)},C=()=>{S();let e=u!==null;p?.(),p=null,u?.remove(),u=null,d=null,f=null,e&&kr(x())},w=()=>{if(!u)return;let e=c(),n=l(),r=t.getBoundingClientRect(),i=u.getBoundingClientRect(),a=e.documentElement.clientWidth||n.innerWidth,d=e.documentElement.clientHeight||n.innerHeight,f=a-s-i.width,p=r.left+r.width/2-i.width/2,m=Fr(p,s,f),h=r.top-s,g=d-s-r.bottom,_=h>=i.height+o||h>=g?`top`:`bottom`,v=_===`top`?r.top-o-i.height:r.bottom+o,y=d-s-i.height,b=Fr(v,s,y),x=r.left+r.width/2,S=Math.max(Cr,i.width-Cr),C=Fr(x-m,Cr,S);u.dataset.placement=_,u.style.left=`${m}px`,u.style.top=`${b}px`,u.style.setProperty(`--persona-tooltip-arrow-x`,`${C}px`)},T=()=>{if(_||!a||u||!t.isConnected||Mr(t))return;let e=v(),n=Pr(t);if(!e||!n)return;let r=c(),i=l();u=r.createElement(`div`),u.className=`persona-control-tooltip`,u.setAttribute(`role`,`tooltip`),u.dataset.state=`measuring`,u.style.zIndex=String(dn);let o=i.getComputedStyle?.(t);if(o){for(let e of Ir){let t=o.getPropertyValue(e).trim();t&&u.style.setProperty(e,t)}o.fontFamily&&(u.style.fontFamily=o.fontFamily)}d=r.createElement(`span`),d.className=`persona-control-tooltip__label`,d.textContent=e,u.appendChild(d);let s=y();s&&(f=r.createElement(`span`),f.className=`persona-control-tooltip__hint`,f.textContent=s,u.appendChild(f));let m=r.createElement(`span`);m.className=`persona-control-tooltip__arrow`,u.appendChild(m),n.appendChild(u),w(),u.dataset.state=`open`;let h=()=>{t.isConnected?(d&&(d.textContent=v()),f&&(f.textContent=y()),w()):C()};i.addEventListener(`scroll`,h,!0),i.addEventListener(`resize`,h);let g=t.getRootNode(),b=Nr(g)?g:r.documentElement,x=typeof MutationObserver>`u`?null:new MutationObserver(()=>{t.isConnected||C()});x?.observe(b,{childList:!0,subtree:!0}),p=()=>{i.removeEventListener(`scroll`,h,!0),i.removeEventListener(`resize`,h),x?.disconnect()}},E=e=>{_||u||(S(),e||b()<=0||Or()?T():m=l().setTimeout(()=>{m=void 0,T()},b()))},D=()=>{h||g?E(g):C()},O=()=>{let e=l();e.matchMedia&&e.matchMedia(`(hover: none)`).matches||(h=!0,D())},ee=()=>{h=!1,D()},k=()=>{try{g=t.matches(`:focus-visible`)}catch{g=!0}D()},A=()=>{g=!1,D()},te=()=>{h=!1,g=!1,C()},ne=e=>{e.key===`Escape`&&te()};n.addEventListener(`mouseenter`,O),n.addEventListener(`mouseleave`,ee),t.addEventListener(`focus`,k),t.addEventListener(`blur`,A),t.addEventListener(`keydown`,ne),t.addEventListener(`click`,te);let re={get isOpen(){return u!==null},show:T,hide:C,reposition:w,destroy:()=>{_||(_=!0,C(),n.removeEventListener(`mouseenter`,O),n.removeEventListener(`mouseleave`,ee),t.removeEventListener(`focus`,k),t.removeEventListener(`blur`,A),t.removeEventListener(`keydown`,ne),t.removeEventListener(`click`,te),Ar.delete(t))}};return Ar.set(t,re),re}var xr,Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr,Nr,Pr,Fr,Ir,Lr=o((()=>{fn(),_r(),xr=8,Sr=8,Cr=10,wr=200,Tr=300,Er=0,Dr=e=>Math.max(0,e),Or=()=>Date.now()<Er,kr=e=>{Er=e>0?Date.now()+e:0},Ar=/* @__PURE__ */ new WeakMap,jr=`data-persona-tooltip-suppressed`,Mr=e=>typeof e.closest==`function`&&e.closest(`[data-persona-tooltip-suppressed]`)!==null,Nr=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&`host`in e,Pr=e=>{let t=e.getRootNode?.();return Nr(t)?t:e.ownerDocument.body},Fr=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),Ir=[...[`background`,`foreground`,`hint-fg`,`radius`,`font-size`,`padding`,`max-width`,`shadow`,`arrow-display`].map(e=>`--persona-tooltip-${e}`),`--persona-font-family`,`--persona-radius-sm`]})),Rr,zr,Br,Vr=o((()=>{Rr=(e,t)=>e.visible!==!1&&(e.mode!==`transient`||t===`connecting`||t===`paused`||t===`resuming`||t===`error`),zr=(e,t,n)=>{let r=t.mode===`transient`,i=e.hasAttribute(`data-persona-composer-reason`)||e.hasAttribute(`data-persona-composer-notice`);e.style.display=Rr(t,n)||r&&i&&t.visible!==!1?``:`none`,e.classList.toggle(`persona-mt-2`,!r),e.classList.toggle(`persona-mb-2`,r)},Br=(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 Hr(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=Ur(t)&&Ur(r)?Hr(t,r):r}return n}var Ur,Wr=o((()=>{Ur=e=>typeof e==`object`&&!!e&&!Array.isArray(e)}));function Gr(e,t=``){return Object.entries(e).flatMap(([e,n])=>{let r=t?`${t}.${e}`:e;return $r(n)?Gr(n,r):[r]})}function Kr(e,t){for(let n of t.split(`.`)){if(!$r(e)||!Object.prototype.hasOwnProperty.call(e,n))return`absent`;if(e=e[n],e===void 0)return`clear`}return`explicit`}function qr(e,t){return e?.[Qr]??t.filter(t=>Kr(e,t)===`explicit`)}function Jr(e,t){return Object.defineProperty(e,Qr,{value:t,enumerable:!0,configurable:!0}),e}function Yr(e,t,n){return Jr(e,qr(t,Gr(n)))}function Xr(e,t,n){let r=t[Qr];if(r)return r;let i=new Set(qr(e,n));for(let e of n){let n=Kr(t,e);n===`clear`&&i.delete(e),n===`explicit`&&i.add(e)}return[...i]}function Zr(e,t,n){let r={...e};for(let e of t){if(n.includes(e))continue;let t=e.split(`.`),i=r;for(let e of t.slice(0,-1)){let t=i[e];if(!$r(t)){i=void 0;break}i[e]={...t},i=i[e]}i&&delete i[t[t.length-1]]}return r}var Qr,$r,ei=o((()=>{Qr=Symbol(`persona.defaultsProvenance`),$r=e=>typeof e==`object`&&!!e&&!Array.isArray(e)})),ti,ni,ri,ii,ai,oi,si,ci,li=o((()=>{ti=Symbol(`persona.panelAliasProvenance`),ni=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),ri=(e,t)=>ni(e,t)&&e[t]!==void 0,ii=e=>({launcherWidth:ri(e?.launcher,`width`),legacyLauncherWidth:ri(e,`launcherWidth`),sidebarWidth:ri(e?.launcher,`sidebarWidth`),dockWidth:ri(e?.launcher?.dock,`width`)}),ai=e=>{let t=e?.[ti];return t?{...t}:ii(e)},oi=(e,t)=>(Object.defineProperty(e,ti,{value:t,enumerable:!0,configurable:!0}),e),si=(e,t)=>oi(e,ai(t)),ci=(e,t)=>{let n=t[ti];if(n)return{...n};let r=ai(e);return ni(t,`launcherWidth`)&&(r.legacyLauncherWidth=t.launcherWidth!==void 0),ni(t,`launcher`)&&t.launcher===void 0?(r.launcherWidth=!1,r.sidebarWidth=!1,r.dockWidth=!1,r):(ni(t.launcher,`width`)&&(r.launcherWidth=t.launcher?.width!==void 0),ni(t.launcher,`sidebarWidth`)&&(r.sidebarWidth=t.launcher?.sidebarWidth!==void 0),ni(t.launcher,`dock`)&&t.launcher?.dock===void 0?r.dockWidth=!1:ni(t.launcher?.dock,`width`)&&(r.dockWidth=t.launcher?.dock?.width!==void 0),r)}}));function ui(e){return e?.future?.v5Defaults===!0?`v5`:`v4`}function di(e){let t=ui(e)===`v5`?Ci:Si;return Hr(xi,t)}function fi(e,t){if(e||t)return e?t?Hr(e,t):e:t}function pi(e){let t=di(e);return e?Yr(si({...t,...e,theme:fi(t.theme,e.theme),darkTheme:fi(t.darkTheme,e.darkTheme),launcher:{...t.launcher,...e.launcher,dock:{...t.launcher?.dock,...e.launcher?.dock},clearChat:{...t.launcher?.clearChat,...e.launcher?.clearChat}},...t.composer||e.composer?{composer:{...t.composer,...e.composer}}:{},tooltip:{...t.tooltip,...e.tooltip},copy:{...t.copy,...e.copy},sendButton:{...t.sendButton,...e.sendButton},statusIndicator:{...t.statusIndicator,...e.statusIndicator},voiceRecognition:{...t.voiceRecognition,...e.voiceRecognition},features:(()=>{let n=t.features?.artifacts,r=e.features?.artifacts,i=t.features?.scrollToBottom,a=e.features?.scrollToBottom,o=t.features?.scrollBehavior,s=e.features?.scrollBehavior,c=t.features?.streamAnimation,l=e.features?.streamAnimation,u=t.features?.askUserQuestion,d=e.features?.askUserQuestion,f=t.features?.history,p=e.features?.history,m=n===void 0&&r===void 0?void 0:{...n,...r,layout:{...n?.layout,...r?.layout}},h=i===void 0&&a===void 0?void 0:{...i,...a},g=o===void 0&&s===void 0?void 0:{...o,...s},_=c===void 0&&l===void 0?void 0:{...c,...l},v=u===void 0&&d===void 0?void 0:{...u,...d,styles:{...u?.styles,...d?.styles}},y=f===void 0&&p===void 0?void 0:{...f,...p,copy:{...f?.copy,...p?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...h===void 0?{}:{scrollToBottom:h},...g===void 0?{}:{scrollBehavior:g},...m===void 0?{}:{artifacts:m},..._===void 0?{}:{streamAnimation:_},...v===void 0?{}:{askUserQuestion:v},...y===void 0?{}:{history:y}}})(),suggestionChips:e.suggestionChips??t.suggestionChips,suggestionChipsConfig:{...t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...t.layout,...e.layout,header:{...t.layout?.header,...e.layout?.header},messages:{...t.layout?.messages,...e.layout?.messages,...t.layout?.messages?.user||e.layout?.messages?.user?{user:{...t.layout?.messages?.user,...e.layout?.messages?.user}}:{},...t.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...t.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...t.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...t.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...t.layout?.slots,...e.layout?.slots}},markdown:{...t.markdown,...e.markdown,options:{...t.markdown?.options,...e.markdown?.options}},messageActions:{...t.messageActions,...e.messageActions}},e),e,Ci):Yr(si(t),void 0,Ci)}var mi,hi,gi,_i,vi,yi,bi,xi,Si,Z,Ci,wi,Ti=o((()=>{Wr(),ei(),li(),_r(),mi=`min(440px, calc(100vw - 24px))`,hi=`440px`,gi=`40px`,_i=`How can I help...`,vi={collapsedMode:`tool-call`,activePreview:!1,grouped:!1,groupedMode:`stack`,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},yi={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},bi={enabled:!0,mountMode:`floating`,dock:{side:`right`,width:`420px`},title:`Chat Assistant`,subtitle:`Here to help you get answers fast`,agentIconText:`💬`,agentIconName:`bot`,headerIconName:`bot`,position:`bottom-right`,width:mi,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:`40px`,headerIconSize:gi,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)`},xi={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:bi,copy:{inputPlaceholder:_i,sendButtonLabel:`Send`},sendButton:{borderWidth:`0px`,paddingX:`12px`,paddingY:`10px`,borderColor:void 0,useIcon:!0,iconText:`↑`,showTooltip:!0,tooltipText:`Send message`,iconName:`send`},statusIndicator:{visible:!0,idleText:`Online`,connectingText:`Connecting…`,connectedText:`Streaming…`,errorText:`Offline`},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:`mic`,borderWidth:`0px`,iconColor:void 0,backgroundColor:`transparent`,borderColor:`transparent`,recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:`transparent`,showTooltip:!0,tooltipText:`Start voice recognition`},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:`arrow-down`,label:``},scrollBehavior:{mode:`anchor-top`,anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:vi,reasoningDisplay:yi,streamAnimation:{type:`none`,placeholder:`none`,speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:`Other…`,freeTextPlaceholder:`Type your answer…`,submitLabel:`Send`},history:{enabled:!1,presentation:`panel`,showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:[`Show me what you can help with`,`Walk me through getting started`,`Answer a question about this page`],suggestionChipsConfig:{fontFamily:`sans-serif`,fontWeight:`500`,paddingX:`12px`,paddingY:`6px`},layout:{header:{layout:`default`,showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:`bubble`,avatar:{show:!1,position:`left`},timestamp:{show:!1,position:`below`},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:`hover`,align:`right`,layout:`pill-inside`},debug:!1},Si={},Z={variant:`circle`,width:`min(400px, calc(100vw - 24px))`,headerIconSize:`20px`},Ci={launcher:Z,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`}}}},wi=di()}));function Ei(e){return typeof e==`string`?[{type:`text`,text:e}]:e}function Di(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function Oi(e){return typeof e!=`string`&&e.some(e=>e.type===`image`)}function ki(e){return typeof e==`string`?[]:e.filter(e=>e.type===`image`)}function Ai(e){return{type:`text`,text:e}}function ji(e,t){return{type:`image`,image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Mi(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result;t({type:`image`,image:n,mimeType:e.type,alt:e.name})},r.onerror=()=>n(/* @__PURE__ */ Error(`Failed to read file`)),r.readAsDataURL(e)})}function Ni(e,t=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`],n=10485760){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(`, `)}`}}function Pi(e){return Vi.includes(e)||e.startsWith(`image/`)}function Fi(e){return Pi(e.type)}function Q(e,t,n){return{type:`file`,data:e,mimeType:t,filename:n}}async function Ii(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result;Fi(e)?t({type:`image`,image:n,mimeType:e.type,alt:e.name}):t({type:`file`,data:n,mimeType:e.type,filename:e.name})},r.onerror=()=>n(/* @__PURE__ */ Error(`Failed to read file`)),r.readAsDataURL(e)})}function Li(e,t=Ui,n=10485760){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(`, `)}`}}function Ri(e){let t=e.split(`.`);return t.length>1?t.pop().toLowerCase():``}function zi(e,t){let n=Ri(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 Bi,Vi,Hi,Ui,Wi=o((()=>{Bi=`[Image]`,Vi=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/svg+xml`,`image/bmp`],Hi=[`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`],Ui=[...Vi,...Hi]}));function Gi(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let n=t.getComputedStyle(e).lineHeight;if(!n||!n.trim().endsWith(`px`))return 20;let r=parseFloat(n);return Number.isFinite(r)&&r>0?r:20}function Ki(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:e>0?e:t}function qi(e,t){e.style.maxHeight=`${t*Gi(e)}px`,e.style.overflowY=`auto`}function Ji(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 Yi(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Xi(e,t){if(e.key!==`Enter`||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,r=t.submitKey??`enter`;return r===`none`?!1:r===`mod-enter`?n:n||!Yi(t)}function Zi(e){return(e.submitKey??`enter`)===`enter`?Yi(e)?`enter`:`send`:`enter`}function Qi(e,t){e.setAttribute(`enterkeyhint`,Zi(t))}function $i(e,t){let n=t?.autocomplete;e.setAttribute(`autocomplete`,typeof n==`string`&&n?n:`off`);let r=(t,n)=>{n===void 0?e.removeAttribute(t):e.setAttribute(t,n)};r(`autocapitalize`,typeof t?.autocapitalize==`string`?t.autocapitalize:void 0),r(`spellcheck`,typeof t?.spellcheck==`boolean`?String(t.spellcheck):void 0),r(`inputmode`,typeof t?.inputmode==`string`&&t.inputmode?t.inputmode:void 0),r(`aria-label`,typeof t?.ariaLabel==`string`&&t.ariaLabel?t.ariaLabel:void 0)}function ea(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 ta=o((()=>{})),na,ra,ia,aa,oa,sa,ca,la,ua,da,fa=o((()=>{Vr(),V(),F(),Ti(),Wi(),Lr(),ta(),na=`persona-composer-control`,ra=`persona-composer-control--glyph`,ia=(e,t,n)=>{let r=e.ownerDocument?.defaultView;if(!r)return;let i=r.getComputedStyle(e);for(let e of n){let n=i.getPropertyValue(e).trim();n?t.style.setProperty(e,n):t.style.removeProperty(e)}},aa=(e,t)=>{let n=z(`textarea`);n.setAttribute(`data-persona-composer-input`,``),n.placeholder=e?.copy?.inputPlaceholder??`How can I help...`,n.dir=`auto`,Qi(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Ji(n)}),$i(n,e?.composer?.inputAttributes),n.className=`persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea`,n.rows=1,n.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,n.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`;let r=Ki(e?.composer?.maxLines,t?.defaultMaxLines??3),i=`${r*20}px`;n.style.maxHeight=i,n.style.overflowY=`auto`;let a=()=>{let e=n.style.maxHeight;if(e!==i){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=r*Gi(n);return i=`${t}px`,n.style.maxHeight=i,t},o=()=>{n.addEventListener(`input`,()=>{n.style.height=`auto`;let e=Math.min(n.scrollHeight,a());n.style.height=`${e}px`})};return n.style.border=`none`,n.style.outline=`none`,n.style.borderWidth=`0`,n.style.borderStyle=`none`,n.style.borderColor=`transparent`,n.addEventListener(`focus`,()=>{n.style.border=`none`,n.style.outline=`none`,n.style.borderWidth=`0`,n.style.borderStyle=`none`,n.style.borderColor=`transparent`,n.style.boxShadow=`none`}),n.addEventListener(`blur`,()=>{n.style.border=`none`,n.style.outline=`none`}),{textarea:n,attachAutoResize:o}},oa=(e,t,n=`send`)=>{let r=B(`span`,{className:`persona-composer-glyph-stack`,attrs:{"data-mode":n,"data-persona-glyph-stack":``}});return e.setAttribute(`data-glyph`,`send`),t.setAttribute(`data-glyph`,`stop`),r.append(e,t),r},sa=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,r=t.iconText??`↑`,i=t.iconName,a=t.stopIconName??`square`,o=t.tooltipText??`Send message`,s=t.stopTooltipText??`Stop generating`,c=e?.copy?.sendButtonLabel??`Send`,l=e?.copy?.stopButtonLabel??`Stop`,u=t.showTooltip??!1,d=t.size,f=parseFloat(d??``)||40,p=t.backgroundColor,m=t.textColor,h=z(`div`,`persona-send-button-wrapper`),g=B(`button`,{className:$e(`persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer`,n?`persona-flex persona-items-center persona-justify-center ${na}`:`persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold`,n&&!p&&`persona-bg-persona-primary`,!n&&!m&&`persona-text-white`),attrs:{type:`submit`,"data-persona-composer-submit":``,"data-persona-send-mode":`send`},style:{width:n?d:void 0,height:n?d:void 0,minWidth:n?d:void 0,minHeight:n?d:void 0,fontSize:n?`18px`:void 0,lineHeight:n?`1`:void 0,color:n?m||`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`:m||void 0,backgroundColor:n&&p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?`solid`:void 0,borderColor:t.borderColor||void 0,paddingLeft:n?`0`:t.paddingX||void 0,paddingRight:n?`0`:t.paddingX||void 0,paddingTop:n?`0`:t.paddingY||void 0,paddingBottom:n?`0`:t.paddingY||void 0}}),_=null,v=null,y=null;if(n){let e=parseFloat(t.iconSize??``)||Math.round(f*.5),n=t.iconStrokeWidth??2,o=m?.trim()||`currentColor`;if(i&&(_=P(i,e,o,n)),v=P(a,e,o,n),!t.iconSize)for(let t of[_,v])t&&(t.style.width=`var(--persona-components-composer-sendIconSize, ${e}px)`,t.style.height=`var(--persona-components-composer-sendIconSize, ${e}px)`);_&&v?(y=oa(_,v),g.appendChild(y)):_?g.appendChild(_):(g.textContent=r,v=null)}else g.textContent=c;g.setAttribute(`aria-label`,o),h.appendChild(g),br({anchor:g,trigger:h,text:()=>g.getAttribute(`aria-label`)??``,enabled:u});let b=`send`;return{button:g,wrapper:h,setMode:e=>{if(e===b)return;b=e;let t=e===`stop`?s:o;g.setAttribute(`aria-label`,t),g.setAttribute(`data-persona-send-mode`,e),n?(g.querySelector(`[data-persona-glyph-stack]`)??y)?.setAttribute(`data-mode`,e):g.textContent=e===`stop`?l:c},glyphStack:y}},ca=e=>{let t=e?.voiceRecognition??{};if(t.enabled!==!0)return null;let n=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),r=t.provider?.type===`runtype`,i=t.provider?.type===`custom`;if(!(n||r||i))return null;let a=t.iconName??`mic`,o=t.iconSize,s=parseFloat(o??``)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,l=t.iconColor??e?.sendButton?.textColor,u=z(`div`,`persona-send-button-wrapper`),d=B(`button`,{className:$e(`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer`,na,!o&&`persona-composer-control--glyph`),attrs:{type:`button`,"data-persona-composer-mic":``,"data-state":`idle`,"aria-label":t.tooltipText??`Start voice recognition`},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:`18px`,lineHeight:`1`,color:l||`var(--persona-text, #111827)`,backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?`solid`:void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),f=P(a,s,l||`currentColor`,1.5);f?d.appendChild(f):d.textContent=`🎤`,u.appendChild(d);let p=t.tooltipText??`Start voice recognition`;return br({anchor:d,trigger:u,text:()=>d.getAttribute(`aria-label`)??p,enabled:t.showTooltip??!1}),{button:d,wrapper:u}},la=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=z(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`);n.setAttribute(`data-persona-composer-attachment-previews`,``),n.style.display=`none`;let r=z(`input`);r.type=`file`,r.setAttribute(`data-persona-composer-attachment-input`,``),r.accept=(t.allowedTypes??Ui).join(`,`),r.multiple=(t.maxFiles??4)>1,r.style.display=`none`,r.setAttribute(`aria-label`,`Attach files`);let i=t.buttonIconName??`paperclip`,a=z(`div`,`persona-send-button-wrapper`),o=B(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${na} ${ra}`,attrs:{type:`button`,"data-persona-composer-attachment-button":``,"aria-label":t.buttonTooltipText??`Attach file`},style:{fontSize:`18px`,lineHeight:`1`}}),s=P(i,24,`currentColor`,1.5);s?o.appendChild(s):o.textContent=`📎`,o.addEventListener(`click`,e=>{e.preventDefault(),r.click()}),a.appendChild(o);let c=t.buttonTooltipText??`Attach file`;return br({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??c}),{button:o,wrapper:a,input:r,previewsContainer:n}},ua=e=>{let t=e?.statusIndicator??{},n=t.align===`left`?`persona-text-left`:t.align===`center`?`persona-text-center`:`persona-text-right`,r=z(`div`,`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute(`data-persona-composer-status`,``),zr(r,t,`idle`);let i=t.idleText??`Online`;if(t.idleLink){let e=z(`a`);e.href=t.idleLink,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=i,e.style.color=`inherit`,e.style.textDecoration=`none`,r.appendChild(e)}else r.textContent=i;return r},da=()=>B(`div`,{className:`persona-mb-3 persona-flex persona-flex-wrap persona-gap-2`,attrs:{"data-persona-composer-suggestions":``}})}));function pa(e){let{config:t,onOpen:n}=e,r=t.buttonIconName??`plus`,i=t.buttonTooltipText??`Add context`,a=z(`div`,`persona-send-button-wrapper`),o=B(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${na} ${ra}`,attrs:{type:`button`,"data-persona-composer-mention-button":``,"aria-label":i,"aria-haspopup":`listbox`,"aria-expanded":`false`},style:{fontSize:`18px`,lineHeight:`1`}}),s=P(r,24,`currentColor`,1.5);return s?o.appendChild(s):o.textContent=`+`,o.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n()}),a.appendChild(o),br({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??i}),{button:o,wrapper:a}}var ma=o((()=>{V(),F(),Lr(),fa()})),ha,ga,_a,va=o((()=>{g(),{setLoader:ha,load:ga}=h({fallbackImport:()=>import(`@runtypelabs/persona/context-mentions`)}),_a=ga})),ya,ba,xa,Sa=o((()=>{g(),{setLoader:ya,load:ba}=h({fallbackImport:()=>import(`@runtypelabs/persona/context-mentions-inline`),resetOnSetLoader:!0}),xa=ba}));function Ca(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=B(`span`,{className:$e(`persona-mention-token`,t.readonly&&`persona-mention-token-readonly`),attrs:{"data-mention-source":e.sourceId,title:e.label,role:`img`,"aria-label":`${e.label} mention`}});e.color&&n.style.setProperty(`--persona-mention-token-accent`,e.color);let r=P(e.iconName??`at-sign`,13,`currentColor`,2);if(r){let e=z(`span`,`persona-mention-token-icon`);e.appendChild(r),n.appendChild(e)}return n.appendChild(B(`span`,{className:`persona-mention-token-label`,text:`@${e.label}`})),n}var wa=o((()=>{V(),F()}));function Ta(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:r,createMentionButton:i}=e.deps??Ea,a=e.config.contextMentions;if(!a?.enabled)return null;let o=hr(a).filter(e=>e.sources.length>0);if(o.length===0)return typeof console<`u`&&console.warn(`[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled.`),null;let s=o.filter(e=>e.sources.some(e=>typeof e.matchCommand==`function`)),c=e=>s.some(t=>t.trigger?t.position===`line-start`?e.split(`
10
10
  `).some(e=>e.startsWith(t.trigger)):(t.position===`anywhere`?e:e.split(`
11
- `)[0]).startsWith(t.trigger):!1),l=(e,t)=>{if(typeof window<`u`)try{window.dispatchEvent(new CustomEvent(`persona:mention:${e}`,{detail:t}))}catch{}},u=!e.chipRow,d=e.chipRow??V(`div`,{className:`persona-mention-context-row`,attrs:{"data-persona-mention-context-row":``}}),f=null,p=null,m=e.textarea,h=null,g=null,_=null,v=null,y=()=>{if(f)return Promise.resolve(f);if(p)return p;let n=t().then(t=>(t.setMentionIconRenderer(r),f=t.mountContextMentions({mentionConfig:a,textarea:e.textarea,composerInput:h??void 0,anchor:e.anchor,contextRow:d,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:S,emit:l}),f)).catch(e=>(typeof console<`u`&&console.warn(`[Persona] Failed to load context mentions runtime`,e),p===n&&(p=null),null));return p=n,n};a.display===`inline`&&n().then(t=>{let n=t.mountInlineComposer({textarea:e.textarea,renderToken:e=>Sa(e,{render:a.renderMentionToken}),onMentionRemoved:e=>f?.untrackMention(e)});h=n.input,g=n.destroy;let r=m;r.replaceWith(n.element),m=n.element,v={next:n.element,prev:r},_?.(n.element,r),f?f.rebindComposer(n.input):p&&p.then(e=>e?.rebindComposer(n.input))}).catch(e=>{typeof console<`u`&&console.warn(`[Persona] Failed to load inline mention composer`,e)});let b=[],x=/* @__PURE__ */ new Map;for(let e of o){if(!e.showButton)continue;let t=i({config:{...a,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},onOpen:()=>{y().then(t=>t?.openMenu(e.trigger))}});b.push(t),x.set(e.trigger,t.button)}let S=(e,t,n)=>{let r=x.get(t);r&&(r.setAttribute(`aria-expanded`,e?`true`:`false`),e?r.setAttribute(`aria-controls`,n):r.removeAttribute(`aria-controls`))};return{affordanceButtons:b.map(e=>e.wrapper),contextRow:d,handleInput:e=>{if(f){f.handleInput();return}if(!dr(e))return;let t=m,n=t.selectionStart??0;ur(t.value,n,o)&&y().then(e=>e?.handleInput())},handleKeydown:e=>{if(f?.isMenuOpen())return f.handleKeydown(e);if(e.key===`Backspace`&&f?.hasMentions()&&!v){let t=m,n=t.selectionStart===0&&t.selectionEnd===0;if((t.value.length===0||n)&&f.removeLastChip())return e.preventDefault(),!0}return!1},isMenuOpen:()=>f?.isMenuOpen()??!1,hasMentions:()=>f?.hasMentions()??!1,getMentionRefs:()=>f?.getMentionRefs()??[],collectForSubmit:()=>f?.collectForSubmit()??null,takeInlineCommand:async e=>c(e)?(f??await y())?.dispatchInlineCommand(e)??null:null,clear:()=>f?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:e=>{_=e,v&&e(v.next,v.prev)},destroy:()=>{f?.destroy(),g?.();for(let e of b)e.wrapper.remove();u&&d.remove()}}}var Ta,Ea=o((()=>{H(),pr(),hr(),pa(),_a(),I(),xa(),Ca(),Ta={loadContextMentions:()=>ga(),loadContextMentionsInline:()=>ba(),renderLucideIcon:(...e)=>F(...e),createMentionButton:(...e)=>fa(...e)}})),Da=/* @__PURE__ */ s({createAskUserSheetHandlers:()=>or,createContextMentionOrchestrator:()=>wa}),Oa=o((()=>{sr(),Ea()}));Oa(),g();const{setLoader:ka,load:Aa,provide:ja,getSync:Ma}=h({fallbackImport:()=>Promise.resolve().then(()=>(Oa(),Da))}),Na=Aa,Pa=ja,Fa=Ma;Pa(Da);var Ia=/* @__PURE__ */ s({resolveApproval:()=>La,resolveAskUserQuestion:()=>Ra,resolveWebMcpToolCall:()=>Wa,resolveWebMcpToolCallBatch:()=>Ua});async function La(e,t,n,r){let i=`approval-${t.id}`,a=`approval-error-${t.id}`,o={};e.s.approvalTokens.set(i,o);let s={...t,status:n,resolvedAt:Date.now()},c=e.s.messages.find(e=>e.id===i),l={id:i,role:`assistant`,content:``,createdAt:c?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),...c?.sequence===void 0?{}:{sequence:c.sequence},streaming:!1,variant:`approval`,approval:s};e.s.upsertMessage(l),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let u=e.s.config.approval,d=u&&typeof u==`object`?u.onDecision:void 0;try{let c;if(c=d?await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):await e.s.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let r=null;if(c instanceof Response){if(!c.ok){let n=await c.json().catch(()=>null),r=n?.message??n?.error??`Approval request failed: ${c.status}`,u=n?.code===`APPROVAL_ALREADY_RESOLVED`||c.status===404&&/no paused execution/i.test(String(n?.error)),d=e.s.messages.find(e=>e.id===i);throw e.s.approvalTokens.get(i)===o&&d?.approval?.resolvedAt===s.resolvedAt&&(e.s.upsertMessage({...l,approval:u?{...s,status:`timeout`}:t}),u&&e.settleApprovalPausedToolCall(i),e.s.upsertMessage({id:a,role:`assistant`,content:r,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})),Error(r)}r=c.body}else c instanceof ReadableStream&&(r=c);e.s.approvalTokens.get(i)===o&&e.s.messages.some(e=>e.id===a)&&(e.s.messages=e.s.messages.filter(e=>e.id!==a),e.s.callbacks.onMessagesChanged([...e.s.messages])),r?await e.s.connectStream(r,{allowReentry:!0}):(n===`denied`&&(e.settleApprovalPausedToolCall(i),e.appendMessage({id:`denial-${t.id}`,role:`assistant`,content:`Tool execution was denied by user.`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})),e.setStreaming(!1),e.s.abortController=null)}else e.setStreaming(!1),e.s.abortController=null}catch(t){let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));e.setStreaming(!1),e.s.abortController=null,n||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}finally{e.s.approvalTokens.get(i)===o&&e.s.approvalTokens.delete(i)}}async function Ra(e,t,n){if(e.s.messages.find(e=>e.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,i=t.toolCall?.name;if(!r||!i){e.s.callbacks.onError?.(/* @__PURE__ */ Error(`resolveAskUserQuestion: message is missing executionId or toolCall.name`));return}let a=typeof n==`string`?void 0:n;if(a===void 0&&typeof n==`string`){let e=t.toolCall?.args,r=Array.isArray(e?.questions)?e.questions:[];if(r.length===1){let e=typeof r[0]?.question==`string`?r[0].question:``;e&&(a={[e]:n})}}e.s.markAskUserQuestionResolved(t,a),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let o=t.toolCall.id,s=t.toolCall?.args,c=Array.isArray(s?.questions)?s.questions:[];if(c.length===0){let t=typeof n==`string`?n:Object.entries(n).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `);e.appendMessage({id:`ask-user-answer-${o}`,role:`user`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})}else{let t=a??{};c.forEach((n,r)=>{let i=typeof n?.question==`string`?n.question:``;if(!i)return;let a=t[i],s=Array.isArray(a)?a.join(`, `):typeof a==`string`?a:``;e.appendMessage({id:`ask-user-q-${o}-${r}`,role:`assistant`,content:i,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()}),e.appendMessage({id:`ask-user-a-${o}-${r}`,role:`user`,content:s||`*Skipped*`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})})}try{let t=await e.s.client.resumeFlow(r,{[i]:n},{after:e.resumeAfter(r)});if(!t.ok){let e=await t.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${t.status}`)}t.body?await e.s.connectStream(t.body,{allowReentry:!0}):(e.setStreaming(!1),e.s.abortController=null)}catch(t){let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));e.setStreaming(!1),e.s.abortController=null,n||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}}function za(e,t){let n=[e.s.messages.find(e=>e.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let e of n)if(typeof e==`number`&&Number.isFinite(e))return e;return Date.now()}function Ba(e,t){return t.toolCall?.name===`suggest_replies`&&(e.s.messages.find(e=>e.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function Va(e,t){let n=za(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 Ha(e,t,n,r,i=Date.now(),a){e.s.messages.some(e=>e.id===t.id)&&e.s.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:`complete`,result:n,startedAt:r,completedAt:i,duration:void 0,durationMs:Math.max(0,i-r)}:t.toolCall})}async function Ua(e,t,n){let r=[],i=new AbortController;e.s.webMcpResolveControllers.add(i),e.setStreaming(!0);let a=async n=>{let a=n.toolCall?.name,o=n.toolCall?.id;if(!a||!o)return null;let s=`${t}:${o}`;if(e.s.webMcpInflightKeys.has(s)||e.s.webMcpResolvedKeys.has(s)||Ba(e,n))return null;e.s.webMcpInflightKeys.add(s),r.push(s);let c=Va(e,n),l=n.agentMetadata?.webMcpToolCallId??a;if(a===`suggest_replies`)return{dedupeKey:s,resumeKey:l,output:Yt(),toolMessage:n,startedAt:c,completedAt:Date.now()};let u=e.s.client.executeWebMcpToolCall(a,n.toolCall?.args,i.signal),d;if(!u)d={isError:!0,content:[{type:`text`,text:`WebMCP not enabled on this widget.`}]};else try{d=await u}catch(t){let r=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));return r||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t))),Ha(e,n,Ka(r?`Aborted by cancel()`:qa(t)),c),e.s.webMcpInflightKeys.delete(s),null}return i.signal.aborted?(Ha(e,n,Ka(`Aborted by cancel()`),c),e.s.webMcpInflightKeys.delete(s),null):{dedupeKey:s,resumeKey:l,output:d,toolMessage:n,startedAt:c,completedAt:Date.now()}},o;if(e.s.config.webmcp?.execution===`sequential`){o=[];for(let e of n)o.push(await a(e))}else o=await Promise.all(n.map(a));let s=[];try{if(s=o.filter(e=>e!==null),s.length===0)return;let n={};for(let e of s)n[e.resumeKey]=e.output;let r=await e.s.client.resumeFlow(t,n,{signal:i.signal,after:e.resumeAfter(t)});if(!r.ok){let e=await r.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${r.status}`)}let a=s[0].dedupeKey;for(let t of s){e.s.webMcpResolvedKeys.add(t.dedupeKey);let n=t.toolMessage.toolCall?.name,r=t.toolMessage.agentMetadata?.webMcpToolCallId;Ha(e,t.toolMessage,t.output,t.startedAt,t.completedAt,{...n===`suggest_replies`?{suggestRepliesResolved:!0}:{},...n&&r?{clientToolAnswer:{toolCallId:r,toolName:n,args:t.toolMessage.toolCall?.args,result:t.output,batch:a}}:{}})}r.body&&await e.s.connectStream(r.body,{allowReentry:!0})}catch(t){if(!(t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`))))e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)));else for(let t of s)Ha(e,t.toolMessage,Ka(`Aborted by cancel()`),t.startedAt)}finally{for(let t of r)e.s.webMcpInflightKeys.delete(t);e.s.webMcpResolveControllers.delete(i),e.s.webMcpResolveControllers.size===0&&!e.s.abortController&&e.setStreaming(!1)}}async function Wa(e,t){let n=t.agentMetadata?.executionId,r=t.toolCall?.name,i=t.toolCall?.id;if(!n){e.s.callbacks.onError?.(/* @__PURE__ */ Error(`WebMCP await missing executionId: dispatch left paused.`));return}if(!r)return;if(!i){let t=`${n}:__no_tool_id__:${r}`;if(e.s.webMcpInflightKeys.has(t)||e.s.webMcpResolvedKeys.has(t))return;e.s.webMcpInflightKeys.add(t);try{await Ga(e,n,r,{isError:!0,content:[{type:`text`,text:`WebMCP await missing toolCall.id: cannot execute the page tool.`}]}),e.s.webMcpResolvedKeys.add(t)}catch(t){e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}finally{e.s.webMcpInflightKeys.delete(t)}return}let a=`${n}:${i}`;if(!(e.s.webMcpInflightKeys.has(a)||e.s.webMcpResolvedKeys.has(a)||Ba(e,t)))return Ua(e,n,[t])}async function Ga(e,t,n,r,i){let a=await e.s.client.resumeFlow(t,{[n]:r},{signal:i?.signal,after:e.resumeAfter(t)});if(!a.ok){let e=await a.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${a.status}`)}i?.onHttpOk?.(),a.body?await e.s.connectStream(a.body,{allowReentry:!0}):e.s.webMcpResolveControllers.size===0&&(e.setStreaming(!1),e.s.abortController=null)}var Ka,qa,Ja=o((()=>{nn(),Ka=e=>({isError:!0,content:[{type:`text`,text:e}]}),qa=(e,t=`WebMCP tool execution failed.`)=>e instanceof Error&&e.message?e.message:typeof e==`string`&&e?e:t}));Ja(),g();const{setLoader:Ya,load:Xa,provide:Za,getSync:Qa}=h({fallbackImport:()=>Promise.resolve().then(()=>(Ja(),Ia))}),$a=Xa,eo=Za,to=Qa;eo(Ia);function no(e){if(!e)return io;let t={...io};for(let n of ro){let r=e[n];typeof r==`string`&&r.length>0&&(t[n]=r)}return t}var ro,io,ao=o((()=>{ro=/* @__PURE__ */ `viewTitle.openHistoryLabel.openHistoryBusyLabel.newConversationLabel.expandLabel.collapseLabel.resizeLabel.showEarlierMessagesLabel.openConversationLoadingLabel.openConversationErrorTitle.openConversationRetryLabel.openConversationBackLabel.confirmCancelLabel.deleteConversationConfirmTitle.deleteConversationConfirm.deleteConversationConfirmLabel.clearHistoryConfirmTitle.clearHistoryConfirm.clearHistoryVerifiedConfirm.clearHistoryConfirmLabel.resetIdentityConfirmTitle.resetIdentityConfirm.resetIdentityConfirmLabel.conversationDeletedNotice.identityResetNotice.identityResetUnconfirmedNotice`.split(`.`),io={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 oo(e){let{plugins:t,config:n}=e,r=!1,i=!1,a=!1,o=!1,s=null,c=[],l=()=>{for(let e of c.splice(0))try{e()}catch(e){so(`renderHistoryView cleanup`,e)}},u=(e,n)=>{for(let r of t){let t=r[e];if(t)try{let e=t(n);if(e)return e}catch(t){so(e,t)}}return null},d=()=>({presentation:e.getPresentation(),config:n}),f={header:t=>o?u(`renderHistoryHeader`,Object.freeze({...d(),returnSurface:e.getReturnSurface(),identityStatus:co(t.identityStatus),pendingAction:uo(t.pendingAction),copy:co(t.copy),actions:Object.freeze({close:h.close,startNewConversation:h.startNewConversation}),defaultRenderer:t.defaultRenderer})):null,conversation:e=>o?u(`renderHistoryConversation`,Object.freeze({...d(),conversation:lo(e.conversation),active:e.active,pending:e.pending,open:e.open,requestDelete:e.requestDelete,defaultRenderer:e.defaultRenderer})):null,state:e=>o?u(`renderHistoryState`,Object.freeze({...d(),state:co(e.state),identityStatus:co(e.identityStatus),copy:co(e.copy),...e.retry?{retry:e.retry}:{},...e.startNewConversation?{startNewConversation:e.startNewConversation}:{},defaultRenderer:e.defaultRenderer})):null},p=t.flatMap(t=>(t.railSections??[]).map(t=>({...t,placement:t.placement??`above-conversations`,items:[],render:n=>t.render(Object.freeze({collapsed:n,presentation:e.getPresentation(),actions:h}))}))),m=e.createView({slots:f,renderDom:!1,onModelChange:()=>y(),railSections:p}),h=Object.freeze({...m.operations,close:e.close}),g=()=>(o=!0,m.setDomRenderEnabled(!0),m.element),_=t=>Object.freeze({conversations:Object.freeze(t.conversations.map(lo)),activeConversationId:t.activeConversationId,state:co(t.state),pendingAction:uo(t.pendingAction),identityStatus:co(t.identityStatus),nextCursor:t.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:co(m.copy),actions:h,defaultRenderer:g,requestRender:()=>y(),onCleanup:e=>{c.push(e)}}),v=()=>{o=!1;let e=null;for(let n of t)if(n.renderHistoryView){try{e=n.renderHistoryView(_(m.getModel()))}catch(t){so(`renderHistoryView`,t),e=null}if(e)break}let n=!e||e.contains(m.element);return o=n,m.setDomRenderEnabled(n),e??m.element};function y(){if(!(!a||r||i)){i=!0;try{l();let t=v();if(t===s)return;let n=s;s=t,e.onElementChanged(t,n)}finally{i=!1}}}return a=!0,y(),{view:m,get element(){return s??m.element},requestRender:y,dispose:()=>{r=!0,l()}}}var so,co,lo,uo,fo=o((()=>{so=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},co=e=>Object.freeze({...e}),lo=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),uo=e=>e?co(e):null})),po,mo,ho,go,_o,vo,yo,bo,xo,So,Co,wo,To=o((()=>{po=null,mo=()=>{if(po!==null)return po;if(typeof navigator>`u`)return!1;let e=navigator.userAgentData?.platform??navigator.platform??``;return/mac|iphone|ipad|ipod/i.test(e)},ho=`ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space`,go=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},_o=e=>{let t=e.toLowerCase().split(`+`).map(e=>e.trim()),n=t.pop(),r={key:n,mod:!1,shift:!1,alt:!1};for(let n of t)if(n===`mod`||n===`cmd`||n===`ctrl`)r.mod=!0;else if(n===`shift`)r.shift=!0;else if(n===`alt`||n===`option`)r.alt=!0;else return go(`unknown modifier in`,e),null;return!r.mod||r.shift&&r.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(go(`unsupported`,e),null):(n===`space`&&(r.key=` `),r)},vo=e=>ho.split(` `).find(t=>t.toLowerCase()===e)??(e===` `?`Space`:e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),yo=(e,t)=>{let n=_o(e);if(!n)return``;let r=mo(),i=vo(n.key);if(!t&&r)return`${n.alt?`⌥`:``}${n.shift?`⇧`:``}⌘${i}`;let a=[t?r?`Meta`:`Control`:`Ctrl`];return n.alt&&a.push(`Alt`),n.shift&&a.push(`Shift`),a.push(i),a.join(`+`)},bo=e=>yo(e,!1),xo=e=>yo(e,!0),So=(e,t)=>t.key?.toLowerCase()===e.key&&(mo()?t.metaKey:t.ctrlKey)===e.mod&&!(mo()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Co=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`||e.isContentEditable},wo=e=>{let t=/* @__PURE__ */ new Map,n=e?.ownerDocument??(typeof document<`u`?document:null),r=(t,n)=>{if((t.scope??`widget`)===`page`)return!0;if(!e)return!1;let r=n.composedPath?.();return r?.length?r.includes(e):e.contains(n.target)},i=e=>{if(e.isComposing||!t.size)return;let n=e.composedPath?.()[0]??e.target;for(let i of t.values())if(So(i.parsed,e)&&i.when?.()!==!1&&r(i,e)&&(i.allowInInput||!Co(n))){e.preventDefault();try{i.run(e)}catch(e){go(`${i.id} threw on`,i.combo),console.warn(e)}return}};return n?.addEventListener(`keydown`,i),{register(e){let n=_o(e.combo);if(!n)return()=>{};let r=`${n.mod?`m`:``}${n.shift?`s`:``}${n.alt?`a`:``}${n.key}`,i=t.get(r);return i?(go(`${i.id} already owns`,e.combo),()=>{}):(t.set(r,{...e,parsed:n}),e.element?.setAttribute(`aria-keyshortcuts`,xo(e.combo)),()=>{t.get(r)?.id===e.id&&t.delete(r),e.element?.removeAttribute(`aria-keyshortcuts`)})},destroy(){t.clear(),n?.removeEventListener(`keydown`,i)}}}}));function Eo(e){if(typeof e!=`string`||e===``)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Do(e){return typeof e==`string`?e:void 0}function Oo(e){if(typeof e!=`object`||!e)return null;let t=e;switch(t.type){case`text`:return typeof t.text==`string`?ki(t.text):null;case`image`:return typeof t.image==`string`?Ai(t.image,{mimeType:Do(t.mimeType),alt:Do(t.alt)}):null;case`file`:return typeof t.data==`string`&&typeof t.mimeType==`string`&&typeof t.filename==`string`?$(t.data,t.mimeType,t.filename):null;case`audio`:return typeof t.audio==`string`?{type:`audio`,audio:t.audio,...Do(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case`video`:return typeof t.video==`string`?{type:`video`,video:t.video,...Do(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function ko(e,t){let n=Eo(t),r=e.map(e=>Eo(e.timestamp)),i=Array(e.length),a=0;for(;a<r.length;){let e=r[a];if(e!==null){i[a]=e,a+=1;continue}let t=a;for(;t+1<r.length&&r[t+1]===null;)t+=1;let o=t-a+1,s=a>0?i[a-1]:null,c=t+1<r.length?r[t+1]:null,l=c!==null&&n!==null?Math.min(c,n):c??n;for(let e=0;e<o;e+=1)i[a+e]=l===null?s===null?Po+e:s+e+1:l-(o-e);a=t+1}return i.map(e=>new Date(e).toISOString())}function Ao(e,t){let n=ko(e,t?.beforeCreatedAt),r=[];return e.forEach((e,t)=>{if(typeof e?.id!=`string`||e.id===``||!No.includes(e.role))return;let i=e.role,a=n[t];if(e.displayAvailable===!1)r.push({id:e.id,role:i,content:``,createdAt:a,agentMetadata:{historyDisplayUnavailable:!0}});else if(typeof e.displayContent==`string`)r.push({id:e.id,role:i,content:e.displayContent,createdAt:a});else if(typeof e.content==`string`)r.push({id:e.id,role:i,content:e.content,createdAt:a});else if(Array.isArray(e.content)){let t=e.content.map(Oo).filter(e=>e!==null),n=Ei(t);r.push({id:e.id,role:i,content:n||(Di(t)?`[Image]`:``),createdAt:a,...t.length>0&&{contentParts:t}})}else r.push({id:e.id,role:i,content:``,createdAt:a})}),r}function jo(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 Mo(e,t){let n=/* @__PURE__ */ new Map;for(let t of e)n.set(t.id,t);for(let e of t)n.set(e.id,e);return[...n.values()].sort((e,t)=>{let n=new Date(e.createdAt).getTime(),r=new Date(t.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(r)&&n!==r)return n-r;let i=e.sequence??0,a=t.sequence??0;return i===a?e.id.localeCompare(t.id):i-a})}var No,Po,Fo=o((()=>{Ui(),No=[`user`,`assistant`,`system`],Po=0}));function Io(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let t=Ro.get(e.code)??`unavailable`;return new n(t,Bo(t),{...e.retryAfterSeconds===void 0?{}:{retryAfterSeconds:e.retryAfterSeconds}})}return new n(`unavailable`,Bo(`unavailable`))}function Lo(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,r=e.getIdentityProofConfigured()?[`browser`,`verified-user`]:[`browser`],i={scopes:r},a=e=>{if(!r.includes(e))throw new t(`unsupported_scope`,Bo(`unsupported_scope`))},o=async(t,n)=>{a(t);try{return await n()}catch(t){throw Io(t,e.errors)}},s=t=>{let n=!1;return{conversationId:t.session.conversationId??``,conversationRevision:t.session.conversationRevision??``,async commit(){n||(n=!0,t.commit(),await e.onActivationCommitted(t.session))},discard(){n||(n=!0,t.discard())}}};return{capabilities:i,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(e){return n().subscribeHistoryIdentityStatus(e)},subscribeAvailability(e){return n().subscribeHistoryAvailability(e)},async list(e){return o(e.context.scope,async()=>{let t=await n().listConversations({...e.cursor?{cursor:e.cursor}:{},...e.limit===void 0?{}:{limit:e.limit},...e.targetId?{targetId:e.targetId}:{},scope:e.context.scope});return{items:t.data,nextCursor:t.nextCursor}})},async getPage(e,t){return o(t.context.scope,async()=>{let r=await n().getConversation(e,{...t.cursor?{messageCursor:t.cursor}:{},scope:t.context.scope}),i=Ao(r.messages,{...t.beforeCreatedAt?{beforeCreatedAt:t.beforeCreatedAt}:{}});return{summary:r.summary,messages:Mo([],i),conversationRevision:r.conversationRevision??``,nextCursor:r.nextMessageCursor}})},async prepareOpen(e,t){return o(t.context.scope,async()=>s(await n().prepareConversationSession(e)))},async prepareStartNew(e){return o(e.context.scope,async()=>s(await n().prepareNewConversationSession()))},async delete(e,t){await o(t.context.scope,()=>n().deleteConversation(e,{scope:t.context.scope}))},async deleteAll(e){return o(e.context.scope,()=>n().deleteAllConversations({...e.targetId===void 0?{}:{targetId:e.targetId},scope:e.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var Ro,zo,Bo,Vo=o((()=>{Fo(),Ro=/* @__PURE__ */ new Map([[`not_found`,`not_found`],[`conversation_deleted`,`not_found`],[`rate_limited`,`rate_limited`],[`authentication_required`,`authentication_required`],[`invalid_identity_proof`,`authentication_required`],[`visitor_identity_mismatch`,`authentication_required`],[`visitor_required`,`authentication_required`],[`identity_provider_failed`,`identity_provider_failed`],[`proof_not_admitted`,`proof_not_admitted`],[`identity_contract_violation`,`proof_not_admitted`],[`unauthorized`,`authentication_failed`],[`visitor_token_missing`,`authentication_failed`],[`conversation_credential_missing`,`authentication_failed`]]),zo=/* @__PURE__ */ new Map([[`not_found`,`That conversation is no longer available.`],[`rate_limited`,`Too many history requests.`],[`authentication_failed`,`History access was not authorized.`],[`authentication_required`,`Sign in again to view account history.`],[`identity_provider_failed`,`The identity provider did not respond.`],[`proof_not_admitted`,`Account history is not available for this configuration.`],[`unsupported_scope`,`This history scope is not supported.`],[`unavailable`,`Conversation history is unavailable right now.`]]),Bo=e=>zo.get(e)??`Conversation history is unavailable right now.`})),Ho=/* @__PURE__ */ s({createHistoryShell:()=>Uo}),Uo,Wo=o((()=>{ao(),fo(),H(),To(),dn(),Vo(),Uo=e=>{let t=no(e.config.features?.history?.copy),n=null,r=!1,i=null,a=null,o=`conversation`,s=null,c=null,l=null,u=null,d=0,f=null,p=null,m=null,h=`persona-history-${Math.random().toString(36).slice(2,8)}`,g=()=>e.historyFeatureEnabled()&&!!n&&!r,_=()=>{let t=e.session.getStatus();return e.isStreaming||t===`paused`||t===`resuming`},v=()=>{let t=e.config.features?.history?.scope;if(t)return t;let r=e.config.getIdentityProof?`verified-user`:`browser`,i=n?.capabilities.scopes;return!i||i.includes(r)?r:i[0]??r},y=()=>a?.scope??v(),b=()=>e.session.getClientSession()?.targetId??null,x=e=>`${e.state}:${`reason`in e?e.reason:``}`,S=t=>{let n=x(t);n!==u&&(u=n,e.eventBus.emit(`history:identityStatusChanged`,{status:t,timestamp:Date.now()}))},C=null,w=null,T=()=>{if(!e.historyFeatureEnabled())return null;let t=e.getHistoryProviderFactory();if(t)return t();let n=e.config.features?.history?.provider;return n?typeof n==`function`?(C!==n&&(C=n,w=n()),w):n:e.session.isClientTokenMode()?Lo({errors:e.historyErrors,client:e.session.getClient(),getIdentityProofConfigured:()=>typeof e.config.getIdentityProof==`function`,onActivationCommitted:t=>e.session.bindActivatedSession(t),getClient:()=>e.session.getClient()}):null},E=()=>{p?.(),p=null,m?.(),m=null,r=!1,n=T();let t={...e.historyInternals};n?t.historyProvider=n:delete t.historyProvider,e.historyInternals=t,e.session.setHistoryInternals(e.historyInternals),n&&(p=n.subscribeAvailability?.(e=>{r=!e,e||ft({restoreFocus:!1}),Bt()})??null,m=n.subscribeIdentityStatus(e=>S(e)),u=x(n.getIdentityStatus()))},D=()=>{let t=e.config.features?.history?.presentation??`panel`;if(t===`panel`||t===`auto`&&e.launcherEnabled&&!e.isDockedMountMode(e.config))return`panel`;let n=e.artifactSplitRoot??e.container;return(n.getBoundingClientRect().width||n.clientWidth)>=720?`rail`:`panel`},O=(e,t)=>{t?(e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`inert`,``)):(e.removeAttribute(`aria-hidden`),e.removeAttribute(`inert`))},ee=`data-persona-history-suppressed`,k=null,A=null,j=null,te=null,ne=null,re=``,ie=()=>e.header===ne?re:e.config.layout?.showHeader===!1?`none`:``,M=()=>e.historyPresentation===`panel`&&!!j&&te===j.element&&e.config.layout?.showHeader!==!1&&ie()!==`none`,N=()=>{for(let t of Array.from(e.header.children))t!==k&&t.setAttribute(ee,``)},P=()=>{for(let t of Array.from(e.container.querySelectorAll(`[${ee}]`)))t.removeAttribute(ee)},ae=()=>{let t=j;if(!t)return;if(Array.from(e.header.children).some(e=>e!==k&&!e.hasAttribute(ee))){A&&A!==e.header&&(A.style.removeProperty(`min-height`),A=null);let t=e.header.offsetHeight;t>0&&(e.header.style.minHeight=`${t}px`,A=e.header)}k||=B(`div`,`persona-history-header-host`),t.setHeaderPlacement(`external`);let n=t.getHeaderElement();n.parentNode!==k&&k.replaceChildren(n),k.parentNode!==e.header&&e.header.appendChild(k),N()},oe=()=>{A&&=(A.style.removeProperty(`min-height`),null),k&&(j?.setHeaderPlacement(`inline`),k.remove(),k=null,P())},se=null,ce=()=>{se&&(e.body.style.display=`none`,O(e.body,!0),e.footer.hidden=!0,O(e.footer,!0),M()?(ae(),e.header.style.display=ie(),O(e.header,!1)):(oe(),e.header.style.display=`none`,O(e.header,!0)))};e.reapplyHistoryHostChrome=ce;let le=t=>{let n=e.body.style.display,r=e.footer.hidden,i=e.footer,a=e.header,o=e.header.style.display;ne=a,re=o,se=()=>{se=null,oe(),ne=null,e.body.style.display=n,O(e.body,!1),i.hidden=r,O(i,!1),e.footer!==i&&(e.footer.hidden=!1,O(e.footer,!1)),a.style.display=o,O(a,!1),e.header!==a&&(e.header.style.display=e.config.layout?.showHeader===!1?`none`:``,O(e.header,!1))},e.footer.parentNode?.insertBefore(t,e.footer),ce()},ue=null,de=null,fe=null,pe=null,me=()=>[e.header,e.panelElements.closeButtonWrapper,e.panelElements.clearChatButtonWrapper,e.body,e.footer],F=()=>e.config.features?.history?.rail?.collapsible!==!1,I=()=>e.config.features?.history?.rail?.side===`right`?`right`:`left`,he=e=>Math.min(400,Math.max(200,Math.round(e))),ge=()=>e.config.features?.history?.rail?.resizable===!0,_e,ve=()=>{if(_e===void 0&&(_e=null,e.config.persistState!==!1))try{let t=Number(window.localStorage.getItem(`${e.currentKeyPrefix()}rail-width`));t&&(_e=t)}catch{}return _e},ye=()=>he(ve()??e.config.features?.history?.rail?.width??260),L=t=>{if(_e=t,e.config.persistState!==!1)try{window.localStorage.setItem(`${e.currentKeyPrefix()}rail-width`,String(t))}catch{}},be=()=>F()&&e.config.features?.history?.rail?.collapsedBehavior===`overlay`,R=!1,z=e=>{let t=B(`img`);return t.src=e,t.alt=``,t.setAttribute(`aria-hidden`,`true`),t},xe=()=>{let t=e.config.features?.history?.rail?.brand;if(!t)return;let n=!1,r;return i=>{if(t.render)try{return t.render({collapsed:i})??null}catch(e){return n||(n=!0,console.warn(`[persona] history rail brand threw`,e)),null}return r===void 0&&(r=t.iconUrl?z(t.iconUrl):t.icon?e.renderLucideIcon(t.icon,20):null),r?r.cloneNode(!0):null}},Se=()=>e.config.features?.history?.rail?.sections?.map(t=>{let n=!1,r=e=>{n||(n=!0,console.warn(`[persona] history rail section threw`,t.id,e))};return{id:t.id,title:t.title,placement:t.placement??`above-conversations`,items:t.items.map(t=>{let n;return{id:t.id,label:t.label,badge:t.badge,iconNode:()=>{if(n!==void 0)return n;try{n=t.renderIcon?t.renderIcon()??null:t.iconUrl?z(t.iconUrl):t.icon?e.renderLucideIcon(t.icon,20):null}catch(e){r(e),n=null}return n},onSelect:()=>{try{t.onSelect()}catch(e){r(e)}}}})}})??[],Ce=e=>{let t=Se();for(let n of e)t.some(e=>e.id===n.id)?console.warn(`[persona] duplicate history rail section id`,n.id):t.push(n);return t.length?t:void 0},we=null,Te=()=>`${e.currentKeyPrefix()}rail-collapsed`,Ee=()=>{if(we===null&&(we=e.config.features?.history?.rail?.defaultCollapsed===!0,e.config.persistState!==!1))try{let e=window.localStorage.getItem(Te());e&&(we=e===`1`)}catch{}return we},De=t=>{if(we=t,e.config.persistState!==!1)try{window.localStorage.setItem(Te(),t?`1`:`0`)}catch{}},Oe=()=>e.historyPresentation===`rail`&&F()&&!be()&&Ee(),ke=()=>{},Ae=()=>{be()?ke():(De(!Ee()),i?.view.setCollapsed(Oe()),e.applyRailChrome(),e.repinAnchoredMessage())},je=()=>{let t=e.config.features?.history?.rail?.collapseShortcut;return!t||!_o(t)?null:{combo:t,hint:bo(t),aria:xo(t)}},Me=`var(--persona-history-overlay-margin,8px)`,Ne=null,Pe=null,Fe=0,Ie=null,Le=null,Re=!1,ze=0,Be=()=>window.matchMedia?.(`(pointer: coarse)`).matches===!0,Ve=()=>g()&&be()&&(e.historyPresentation??D())===`rail`,He=()=>e.historyVisible&&!R,Ue=()=>{Le!==null&&clearTimeout(Le),Le=null},We=()=>{e.loadHistoryView().catch(()=>{})},Ge=()=>{Ue(),R&&(Le=setTimeout(()=>{Le=null,!Re&&R&&(Ie?.contains(document.activeElement)||ft({restoreFocus:!1}))},300))},Ke=(e,t)=>{let n=Ie?.getBoundingClientRect();if(!n)return!1;let r=Ne?.getBoundingClientRect(),i=r?Math.min(r.top,n.top):n.top;return e>=n.left&&e<=n.right&&t>=i&&t<=n.bottom||!!r&&e>=r.left&&e<=r.right&&t>=r.top&&t<=r.bottom},qe=e=>{R&&(Re=Ke(e.clientX,e.clientY),Re?Ue():Le===null&&Ge())},Je=t=>{!e.historyVisible&&Ve()&&(R=!0,ut({invoker:Ne,keyboard:t?.keyboard===!0}).then(()=>{e.historyVisible?!Re&&document.activeElement!==Ne&&ft():R=!1}))},Ye=()=>{let e=te?.querySelector(`[data-persona-history-focus="collapse"]`);e&&(e.setAttribute(`aria-label`,R?t.expandLabel:t.collapseLabel),e.setAttribute(`aria-expanded`,R?`false`:`true`))},Xe=()=>{De(!1);let t=i;if(!R||!t){ut({invoker:Ne});return}let n=document.activeElement===Ne;R=!1,K(),t.element.remove(),ct(t.element),Ye(),n&&J(),e.repinAnchoredMessage(),Bt()},Ze=()=>{De(!0),ft()};ke=()=>{!e.historyVisible||R?Xe():Ze()};let H=()=>{let n=je(),r=e.createHeaderIconButton({ariaLabel:t.expandLabel,iconName:`panel-left`,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`,extraClassName:`persona-rail-trigger`,tooltip:!1,attrs:{"data-persona-rail-trigger":``,"aria-controls":h,...n?{"aria-keyshortcuts":n.aria}:{}}}),i=r.button;i.addEventListener(`mouseenter`,()=>{Re=!0,Ue(),!(Be()||Date.now()<ze)&&Je()}),i.addEventListener(`mouseleave`,()=>{Re=!1,ze=0,Ge()}),i.addEventListener(`focus`,()=>{e.historyVisible||We()}),i.addEventListener(`click`,t=>{g()&&(t.detail!==0&&Be()&&!e.historyVisible?Je():Xe())}),Ne=i,Pe=r.wrapper},$e=()=>{if(Pe&&!Pe.isConnected&&(Pe=null,Ne=null),!Ve()){Pe?.remove(),Pe=null,Ne=null;return}Ne||H();let n=Pe,r=Ne;if(!n||!r)return;let i=I()===`right`?null:e.header.firstChild;(i??e.header.lastChild)!==n&&e.header.insertBefore(n,i),n.style.display=He()||Fe>0?`none`:``,r.setAttribute(`aria-label`,t.expandLabel),r.setAttribute(`aria-expanded`,e.historyVisible?`true`:`false`),Ie&&e.applyRailChrome()},et=e=>{if(!R)return;let t=e.target;t instanceof Node&&(Ie?.contains(t)||Pe?.contains(t)||t instanceof Element&&t.closest(`.persona-dropdown-menu,[role="alertdialog"]`)||ft({restoreFocus:!1}))};document.addEventListener(`pointerdown`,et,!0),e.destroyCallbacks.push(()=>{document.removeEventListener(`pointerdown`,et,!0),document.removeEventListener(`pointermove`,qe),nt?.(),Ue()});let tt=null,nt=null,rt=t=>{L(he(t)),e.applyRailChrome(),e.repinAnchoredMessage()},it=()=>{let t=B(`div`,`persona-rail-resizer`);return t.tabIndex=0,t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-valuemin`,`200`),t.setAttribute(`aria-valuemax`,`400`),t.addEventListener(`pointerdown`,n=>{let r=de;if(!r||n.button!==0)return;n.preventDefault(),nt?.();let i=n.clientX,a=r.getBoundingClientRect().width||ye(),o=I()===`right`?-1:1,s=a,c=e.mount.ownerDocument;r.style.transition=`none`;let l=e=>{s=he(a+o*(e.clientX-i)),r.style.flex=`0 0 ${s}px`,t.setAttribute(`aria-valuenow`,String(s))},u=()=>{nt=null,c.removeEventListener(`pointermove`,l),c.removeEventListener(`pointerup`,u),c.removeEventListener(`pointercancel`,u),r.style.removeProperty(`transition`);try{t.releasePointerCapture(n.pointerId)}catch{}rt(s)};nt=u,c.addEventListener(`pointermove`,l),c.addEventListener(`pointerup`,u),c.addEventListener(`pointercancel`,u);try{t.setPointerCapture(n.pointerId)}catch{}}),t.addEventListener(`keydown`,e=>{let t=I()===`right`?-16:16,n=ye(),r=e.key===`ArrowRight`?n+t:e.key===`ArrowLeft`?n-t:e.key===`Home`?200:e.key===`End`?400:null;r!==null&&(e.preventDefault(),rt(r))}),t},U=(e,n)=>{if(!ge()||Oe()){nt?.(),tt?.remove();return}let r=tt??it();tt=r,r.setAttribute(`aria-label`,t.resizeLabel),r.setAttribute(`aria-valuenow`,String(ye())),r.nextElementSibling!==n&&e.insertBefore(r,n)};e.applyRailChrome=()=>{i?.view.setRailSide(I());let t=I()===`right`,n=Ie;if(n){let r=Ne?Ne.getBoundingClientRect().bottom-e.container.getBoundingClientRect().top:0;n.style.top=`calc(${Math.max(0,Math.round(r))}px + ${Me})`,n.style.width=`${ye()}px`,n.style.left=t?``:Me,n.style.right=t?Me:``}let r=de,a=ue,o=fe;if(!r||!a||!o)return;r.style.flex=`0 0 ${Oe()?52:ye()}px`;let s=`1px solid var(--persona-divider,#e5e7eb)`;r.style.borderRight=t?``:s,r.style.borderLeft=t?s:``;let c=t?o:r;a.firstElementChild!==c&&a.append(c,t?r:o),U(a,t?r:o)};let at=t=>{if(pe&&de){pe.replaceWith(t),pe=null,e.applyRailChrome();return}let n=B(`div`,`persona-history-rail-shell`);n.style.cssText=`display:flex;flex-direction:row;flex:1 1 auto;min-height:0`;let r=B(`div`,`persona-history-rail-conversation`);r.style.cssText=`display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative`;let i=B(`div`,`persona-history-rail-host`);i.style.cssText=`display:flex;min-height:0;overflow:hidden`,e.container.insertBefore(n,e.header.parentNode===e.container?e.header:e.body);for(let t of me())t?.parentNode===e.container&&r.appendChild(t);n.append(i,r),i.appendChild(t),ue=n,de=i,fe=r,e.applyRailChrome()},ot=()=>{if(ue)return;let t=B(`div`,`persona-history-rail-placeholder`);t.style.cssText=`flex:1 1 auto;min-height:0`,pe=t,at(t),e.repinAnchoredMessage()},W=()=>{pe&&(K(),e.repinAnchoredMessage())},G=t=>{let n=B(`div`,`persona-history-rail-overlay`);n.style.cssText=`position:absolute;bottom:${Me};display:flex;overflow:hidden;z-index:${un-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,e.container.style.position=`relative`,e.container.appendChild(n),n.appendChild(t),document.addEventListener(`pointermove`,qe),Ie=n,e.applyRailChrome(),Ye()},K=()=>{se?.(),Ie&&=(Re&&(ze=Date.now()+150),document.removeEventListener(`pointermove`,qe),Ie.remove(),null);let t=ue;if(t){nt?.();for(let n of me())n&&t.contains(n)&&e.container.insertBefore(n,t);t.remove(),ue=null,de=null,fe=null,pe=null}},st=e=>{te=e,e.id=h,e.style.flex=`1 1 auto`,e.style.minHeight=`0`},ct=t=>{st(t),(e.historyPresentation!==`rail`||R)&&W(),e.historyPresentation===`rail`?R?G(t):at(t):le(t)},lt=()=>{if($e(),Lt(),!e.historyVisible||!i)return;let t=D();if(t===e.historyPresentation)return;let n=document.activeElement,r=n instanceof HTMLElement&&(i.element.contains(n)||k?.contains(n)===!0)?n:null;K(),i.element.remove(),i.view.setHeaderPlacement(`inline`),e.historyPresentation=t,i.view.setPresentation(t),i.view.setCollapsed(Oe()),i.requestRender(),i.element.isConnected||ct(i.element),r?.isConnected?r.focus():J(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),Bt()},q=(e,t)=>k?.querySelector(t)??e.querySelector(t),J=()=>{let e=i?.element??te;if(!e)return;let t=q(e,`[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]`);if(t){t.focus();return}let n=q(e,`.persona-history-title`)??e;n.tabIndex=-1,n.focus()},ut=async r=>{if(!g()||e.historyVisible)return;let l=n;if(!l)return;if(!R&&Ve()&&Ee()){$e();return}dt();let u=++d;o=r?.returnSurface??`conversation`,s=r?.invoker??c;let f=Ve()&&!R;f&&(Fe+=1,$e(),ot());let p;try{p=await e.loadHistoryView()}catch{e.announceHistory(t.openHistoryLabel),f&&(--Fe,u===d&&(W(),$e()));return}if(f&&--Fe,u!==d||e.historyVisible)return;a={scope:v()},e.historyPresentation=D(),e.historyVisible=!0;let m=e.historyPresentation===`panel`&&e.config.layout?.showHeader!==!1&&e.header.style.display!==`none`?`external`:`inline`,h=e.config.features?.history?.rowAvatar,_=je(),y=_?{hint:_.hint,aria:_.aria}:null,x={provider:l,context:a,targetId:b(),presentation:e.historyPresentation,collapsible:F(),collapsed:Oe(),railSide:I(),renderRailHeader:e.config.features?.history?.rail?.renderHeader,railBrand:xe(),onToggleCollapse:Ae,...y?{collapseShortcut:y}:{},headerPlacement:m,showScopeStatus:e.config.features?.history?.showScopeStatus!==!1,showDelete:e.config.features?.history?.showDelete!==!1,showDeleteAll:e.config.features?.history?.showDeleteAll!==!1,...e.config.features?.history?.listActions?.length?{listActions:e.config.features.history.listActions}:{},rowAvatar:h===!1?!1:typeof h==`string`?h:e.config.launcher?.iconUrl,activeConversationId:e.session.getActiveConversationId(),...e.config.features?.history?.grouping?{grouping:e.config.features.history.grouping}:{},...e.config.features?.history?.copy?{copy:e.config.features.history.copy}:{},...e.config.features?.history?.pageSize===void 0?{}:{pageSize:e.config.features.history.pageSize},onSelect:e=>wt(e,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:t=>e.setActiveConversationSummary(t),attachTooltip:e.attachTooltip,onStartNew:()=>Tt({focusComposer:!0}),onClose:()=>ft(),onRequestDeleteConversation:e=>jt(e),onRequestClearHistory:()=>Mt(),...l.resetDevice?{onRequestResetIdentity:()=>Nt()}:{}};i=oo({plugins:e.plugins,config:e.config,getPresentation:()=>e.historyPresentation??`panel`,getReturnSurface:()=>o,close:()=>ft(),createView:({slots:t,renderDom:n,onModelChange:r,railSections:i})=>(j=p.createHistoryView({...x,railSections:Ce(i),slots:t,renderDom:n,onModelChange:r,onAnnounce:e.announceHistory}),j),onElementChanged:(e,t)=>{if(!t?.isConnected)return ct(e);st(e),t.replaceWith(e),ce()}}),i.view.setNewConversationRequired(e.historySessionState.recovery===`new_conversation_required`),r?.focus!==!1&&(e.historyPresentation!==`rail`||r?.keyboard===!0)&&J(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),Bt(),e.eventBus.emit(`history:opened`,{presentation:e.historyPresentation,returnSurface:o,timestamp:Date.now()})},dt=()=>{},ft=t=>{if(!e.historyVisible)return;d+=1;let n=o,r=s,l=i,u=t?.restoreFocus!==!1;e.historyVisible=!1;let f=!1,p=null,m=()=>{if(!f){if(f=!0,dt=()=>{},p!==null&&clearTimeout(p),R=!1,Ue(),K(),l?.dispose(),l?.view.destroy(),l?.element.remove(),i===l&&(i=null,j=null,te=null,e.historyPresentation=null,a=null,s=null),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),Bt(),u){let t=r??c;t?.isConnected?t.focus():e.maybeFocusInput()}e.eventBus.emit(`history:closed`,{returnSurface:n,timestamp:Date.now()})}},h=l&&l.element===l.view.element?l.view.playExit():null;h?(dt=m,p=setTimeout(m,250),h.then(m)):m()},pt=t=>{if(t.key===`Escape`&&e.historyVisible&&i){if(e.historyPresentation===`rail`){let e=t.target;if(!(e instanceof Node)||!(i.element.contains(e)||R&&Pe?.contains(e)===!0))return}t.preventDefault(),t.stopPropagation(),ft()}};e.container.addEventListener(`keydown`,pt),e.destroyCallbacks.push(()=>e.container.removeEventListener(`keydown`,pt));let mt=0,ht=null,gt=()=>{ht&&clearTimeout(ht),ht=null};e.destroyCallbacks.push(gt);let _t=()=>{gt();let t=e.conversationOpenPendingEl;t&&(e.conversationOpenTakeover=!0,t.hidden=!1,e.messagesWrapper.style.display=`none`,e.updateWelcome())},vt=()=>{mt+=1,gt(),e.conversationOpenPendingEl&&(e.conversationOpenPendingEl.remove(),e.conversationOpenPendingEl=null,e.conversationOpenTakeover=!1,e.messagesWrapper.style.removeProperty(`display`),O(e.footer,!1),e.updateWelcome())},yt=()=>{try{if(window.matchMedia?.(`(prefers-reduced-motion: reduce)`)?.matches)return;e.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:`ease-out`})}catch{}},Y=(e,t)=>V(`div`,{className:Qe(`persona-conversation-loading-bubble`,t&&`persona-conversation-loading-bubble--trailing`),attrs:{"aria-hidden":`true`},style:{width:e}}),bt=()=>V(`div`,{className:`persona-conversation-loading-body`},Y(`58%`,!1),Y(`72%`,!0),Y(`44%`,!1)),xt=t=>{e.conversationOpenPendingEl?.remove(),e.conversationOpenPendingEl=t,t.hidden=!e.conversationOpenTakeover,e.body.insertBefore(t,e.messagesWrapper),gt(),e.conversationOpenTakeover||(ht=setTimeout(_t,250)),O(e.footer,!0)},St=()=>{let n={config:e.config,streaming:!1,location:`conversation-open`,defaultRenderer:bt},r=null,i=e.plugins.find(e=>e.renderLoadingIndicator);i?.renderLoadingIndicator&&(r=i.renderLoadingIndicator(n)),r===null&&e.config.loadingIndicator?.render&&(r=e.config.loadingIndicator.render(n)),xt(V(`div`,{className:`persona-conversation-loading`,attrs:{role:`status`,"aria-label":t.openConversationLoadingLabel}},r??bt()))},Ct=n=>{let r=()=>{wt(n,{focusComposer:!0}).catch(()=>{})},i=g()?()=>{vt(),ut()}:void 0,a=(e,t)=>{let n=V(`button`,{className:`persona-conversation-loading-error-action`,attrs:{type:`button`},text:e});return n.addEventListener(`click`,t),n},o=()=>V(`div`,{className:`persona-conversation-loading-error-body`},V(`p`,{className:`persona-conversation-loading-error-title`,text:t.openConversationErrorTitle}),V(`div`,{className:`persona-conversation-loading-error-actions`},a(t.openConversationRetryLabel,r),i?a(t.openConversationBackLabel,i):null)),s=Object.freeze({conversationId:n,config:e.config,copy:Object.freeze({title:t.openConversationErrorTitle,retryLabel:t.openConversationRetryLabel,backLabel:t.openConversationBackLabel}),retry:r,...i?{back:i}:{},defaultRenderer:o}),c=null;for(let t of e.plugins)if(t.renderHistoryOpenError){try{c=t.renderHistoryOpenError(s)}catch(e){console.warn(`[persona] renderHistoryOpenError threw`,e),c=null}if(c)break}xt(V(`div`,{className:`persona-conversation-loading-error`,attrs:{role:`alert`}},c??o())),_t()};e.eventBus.on(`history:closed`,()=>{e.conversationOpenPendingEl&&O(e.footer,!0)});let wt=async(t,{focusComposer:n=!1}={})=>{let r=y(),a=!!i;i?.view.setActiveConversationId(t),vt();let o=mt;St(),e.historyVisible&&(e.historyPresentation===`panel`||R)&&ft({restoreFocus:!1}),e.suppressScrollSend=!0;try{await e.session.openConversation(t,{scope:r})}catch(e){throw o===mt&&Ct(t),e}finally{e.suppressScrollSend=!1}o===mt&&(vt(),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.restoreScrollPosition()||e.jumpToBottomInstant(),yt(),Ft(),a||e.setActiveConversationSummary(null),e.eventBus.emit(`history:conversationOpened`,{conversationId:t,title:e.activeConversationTitle,scope:r,timestamp:Date.now()}),n&&e.maybeFocusInput())},Tt=async({focusComposer:t=!1}={})=>{vt(),await e.session.startNewConversation({scope:y()}),e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.jumpToBottomInstant(),Ft();let n=e.session.getActiveConversationId();i?.view.setActiveConversationId(n),e.eventBus.emit(`history:conversationStarted`,{conversationId:n,timestamp:Date.now()}),e.historyVisible&&(e.historyPresentation===`panel`||R)&&ft({restoreFocus:!1}),t&&e.maybeFocusInput()},Et=async(t,n)=>{let r=await e.session.updateConversation(t,{...n,...n.title===void 0?{}:{title:n.title.trim()}});return i?.view.applyConversationSummary(r),!i&&t===e.session.getActiveConversationId()&&e.setActiveConversationSummary(r),r},Dt=async t=>{let n=y(),r=e.session.getActiveConversationId()===t;await e.session.deleteConversation(t,{scope:n}),i?.view.removeConversationSummary(t),r&&(e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Ft()),e.eventBus.emit(`history:conversationDeleted`,{conversationId:t,scope:n,wasActive:r,timestamp:Date.now()})},Ot=async t=>{let n=t?.scope??y(),r=t?.allTargets?null:t?.targetId??b(),i=await e.session.clearConversationHistory({...r?{targetId:r}:{},scope:n});return e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),Ft(),e.eventBus.emit(`history:cleared`,{deleted:i.deleted,scope:n,targetId:r,timestamp:Date.now()}),i},kt=async()=>{if(!n?.resetDevice)throw Error(`[Persona] resetHistoryIdentity() requires a history provider that can reset this device`);let r=!1;try{r=(await e.session.resetHistoryDevice()).remoteRevocationConfirmed}finally{e.setActiveConversationSummary(null),e.session.clearArtifacts(),e.messageCache.clear(),e.lastAppliedMessages=null,e.config.clearStoredSessionId?.(),e.config.clearStoredConversationId?.(),e.persistentMetadata={},e.actionManager.syncFromMetadata();let t=e.storageAdapter;t?.clear&&e.runStorageMutation(()=>t.clear(),`[AgentWidget] Failed to clear storage adapter:`),e.resetAnchorState(),e.resumeAutoScroll(),Ft(),ft({restoreFocus:!1}),e.maybeFocusInput(),e.open||e.launcherSurfaceInstance?.launcher.element.focus()}return e.announceHistory(r?t.identityResetNotice:t.identityResetUnconfirmedNotice),e.eventBus.emit(`history:identityReset`,{remoteRevocationConfirmed:r,timestamp:Date.now()}),{remoteRevocationConfirmed:r}},X=()=>e.artifactSplitRoot?e.panel:e.container,At=async t=>{let n=await e.loadHistoryView().catch(()=>null);return typeof n?.showHistoryConfirm==`function`?n.showHistoryConfirm(t):window.confirm(`${t.title}\n\n${t.description}`)},jt=async e=>await At({host:X(),title:t.deleteConversationConfirmTitle,description:t.deleteConversationConfirm,confirmLabel:t.deleteConversationConfirmLabel,cancelLabel:t.confirmCancelLabel})?(await Dt(e),`deleted`):`cancelled`,Mt=async()=>{let e=y()===`verified-user`;return await At({host:X(),title:t.clearHistoryConfirmTitle,description:e?t.clearHistoryVerifiedConfirm:t.clearHistoryConfirm,confirmLabel:t.clearHistoryConfirmLabel,cancelLabel:t.confirmCancelLabel})?(await Ot(),`cleared`):`cancelled`},Nt=async()=>{if(!await At({host:X(),title:t.resetIdentityConfirmTitle,description:t.resetIdentityConfirm,confirmLabel:t.resetIdentityConfirmLabel,cancelLabel:t.confirmCancelLabel}))return{outcome:`cancelled`};let{remoteRevocationConfirmed:e}=await kt();return{outcome:`reset`,remoteRevocationConfirmed:e}},Pt=B(`button`,`persona-history-earlier`);Pt.type=`button`,Pt.textContent=t.showEarlierMessagesLabel,Pt.setAttribute(`data-persona-history-earlier`,``),Object.assign(Pt.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 Ft=()=>{g()&&e.historySessionState.nextMessageCursor&&e.session.getActiveConversationId()?(Pt.textContent=t.showEarlierMessagesLabel,Pt.parentNode!==e.body&&e.body.insertBefore(Pt,e.body.firstChild)):Pt.remove()};Pt.addEventListener(`click`,()=>{let t=e.session.getActiveConversationId(),n=e.historySessionState.nextMessageCursor;if(!t||!n||Pt.disabled)return;Pt.disabled=!0;let r=e.body.scrollHeight,i=e.body.scrollTop;e.session.loadOlderMessages(t,n,{scope:y()}).then(()=>{e.body.scrollTop=i+(e.body.scrollHeight-r),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Pt.disabled=!1,Ft()})});let It=()=>{let n=e.createHeaderIconButton({ariaLabel:t.openHistoryLabel,iconName:`history`,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`,extraClassName:`persona-history-toggle`,attrs:{"data-persona-history-toggle":``}});return n.button.addEventListener(`click`,t=>{g()&&!_()&&(e.historyVisible?ft():ut({invoker:n.button,keyboard:t.detail===0}))}),n},Lt=()=>{if(!g()){l?.remove(),c=null,l=null;return}if(l&&!l.isConnected&&(c=null,l=null),!c&&e.header){let t=It();c=t.button,l=t.wrapper;let n=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;n?.parentNode&&e.header.contains(n)?n.parentNode.insertBefore(l,n):e.header.appendChild(l)}if(!c||!l)return;let n=Ve()||e.historyVisible&&e.historyPresentation===`rail`;if(l.style.display=n?`none`:``,n){document.activeElement===c&&J();return}let r=_();c.disabled=r,c.setAttribute(`aria-disabled`,r?`true`:`false`);let i=r?t.openHistoryBusyLabel:t.openHistoryLabel;c.setAttribute(`aria-label`,i),(e.config.features?.history?.presentation??`panel`)===`panel`?(c.removeAttribute(`aria-expanded`),c.removeAttribute(`aria-controls`)):(c.setAttribute(`aria-expanded`,e.historyVisible?`true`:`false`),c.setAttribute(`aria-controls`,h))},Rt=!1,zt=()=>{let n=e.panelElements.clearChatButton;n&&(g()?(Rt||=(f=n.getAttribute(`aria-label`)??``,!0),n.setAttribute(`aria-label`,t.newConversationLabel),n.removeAttribute(`title`)):Rt&&(Rt=!1,f&&n.setAttribute(`aria-label`,f)))},Bt=()=>{t=no(e.config.features?.history?.copy),Lt(),$e(),zt(),Ft()};return e.historyChromeSync=Bt,E(),Bt(),e.destroyCallbacks.push(()=>{p?.(),m?.(),d+=1,dt(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:g,historyScope:v,installHistoryProvider:E,syncHistoryChromeImpl:Bt,syncHistoryPresentation:lt,syncEarlierMessagesPill:Ft,openHistory:ut,closeHistory:ft,openHistoryConversation:wt,startNewConversation:Tt,updateHistoryConversation:Et,deleteHistoryConversation:Dt,requestDeleteConversation:jt,clearConversationHistory:Ot,resetHistoryIdentity:kt,railCollapseShortcut:je,railCollapsible:F,railTriggerApplies:Ve,railOverlayMode:be,toggleRailCollapsed:Ae,toggleRailPinned:()=>ke(),get historyProvider(){return n},get historySurface(){return i},get railShell(){return ue},get railHost(){return de},get railColumn(){return fe}}}}));Wo(),g();const{setLoader:Go,load:Ko,provide:qo,getSync:Jo}=h({fallbackImport:()=>Promise.resolve().then(()=>(Wo(),Ho))}),Yo=Ko,Xo=qo,Zo=Jo;Xo(Ho),H(),A();const Qo=[`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`],$o=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),es=(e,t)=>{let n=B(`div`,[`persona-message-bubble`,e,...Qo].join(` `));return n.id=`bubble-${t}`,n.setAttribute(`data-message-id`,t),n},ts=e=>{let t=B(`button`,e.expandable?`persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none`:`persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none`);return t.type=`button`,e.expandable&&(t.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),t.setAttribute(`data-expand-header`,`true`)),t.setAttribute(`data-bubble-type`,e.bubbleType),t},ns=(e,t,n)=>{e.innerHTML=``;let r=k(t?f.ChevronUp:f.ChevronDown,16,n,2);r?e.appendChild(r):e.textContent=t?`Hide`:`Show`},rs=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let r=B(`div`,`persona-flex persona-items-center`);ns(r,n.expanded,n.iconColor);let i=B(`div`,n.metaGap?`persona-flex persona-items-center persona-gap-2 persona-ml-auto`:`persona-flex persona-items-center persona-ml-auto`);return i.append(r),e.append(t,i),r},is=e=>{let t=B(`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?.();$o(t,n)||(t.textContent=e.previewText),t.style.display=``}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},as=e=>{e.header.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),e.toggleIcon&&ns(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`},os=(e,t,n)=>{let r=n.stateSet.has(e),i=t.querySelector(`button[data-expand-header="true"]`),a=t.querySelector(`.persona-border-t`),o=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!i||!a)return;i.setAttribute(`aria-expanded`,r?`true`:`false`);let s=i.querySelector(`.persona-ml-auto`)?.querySelector(`:scope > .persona-flex.persona-items-center`);s&&ns(s,r,n.iconColor),a.style.display=r?``:`none`,o&&(o.style.display=r?`none`:o.textContent||o.childNodes.length?``:`none`)};A(),wi(),H(),I();function ss(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return{...e,features:{...e?.features,[n]:{...t===`tool`?_i:vi,...e?.future?.v5Defaults===!0?Si.features?.[n]:{},...e?.features?.[n]}}}}function cs(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return e?.features?.[n]?.variant??(e?.future?.v5Defaults?`row`:`card`)}function ls(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 us(e,t,n,r){if(cs(n,r)!==`row`)return e;e.className=`persona-message-bubble persona-${r}-bubble persona-activity-row`,e.dataset.activityKind=r,r===`tool`&&n.toolCall?.shadow===void 0&&(e.style.boxShadow=`var(--persona-tool-bubble-shadow, none)`);let i=e.querySelector(`:scope > button`);if(!i)return e;i.className=`persona-activity-header`;let a=r===`tool`?t.toolCall:t.reasoning,o=a?.status!==`complete`,s=t.approval?.status??t.toolCall?.approvalStatus,c=s===`denied`?`denied`:s===`pending`?`awaiting-approval`:t.toolCall?.success===!1?`error`:o?a?.status===`pending`?`pending`:`running`:`done`;e.dataset.activityState=c;let l=B(`span`,`persona-activity-icon`);l.dataset.activityIcon=c;let u={pending:`circle`,running:`loader-circle`,done:`check`,error:`x`,denied:`x`,"awaiting-approval":`clock`},d=r===`reasoning`?n.features?.reasoningDisplay?.iconName:void 0,p=d?F(d,16,`currentColor`,2):c===`pending`?k(f.Circle,16,`currentColor`,2):c===`awaiting-approval`?k(f.Clock,16,`currentColor`,2):F(u[c],16,`currentColor`,2);p&&l.appendChild(p),i.querySelector(`.persona-reasoning-header-icon`)?.remove();let m=r===`tool`?`toolCallDisplay`:`reasoningDisplay`,h=n.features?.[m]?.iconVisibility??(n.future?.v5Defaults?`active`:`always`);if((h===`always`||h===`active`&&c!==`done`)&&i.prepend(l),r===`tool`&&a){let e=B(`span`,`persona-activity-duration`);o&&a.startedAt&&e.setAttribute(`data-tool-elapsed`,String(a.startedAt));let n=(r===`tool`?t.toolCall?.duration:void 0)??a.durationMs??(a.completedAt!==void 0&&a.startedAt!==void 0?a.completedAt-a.startedAt:void 0);e.textContent=n===void 0?``:ls(n),i.appendChild(e)}i.querySelector(`:scope > div:not(.persona-ml-auto)`)?.classList.add(`persona-activity-label`),i.querySelector(`.persona-ml-auto`)?.classList.add(`persona-activity-chevron`);let g=e.querySelector(`:scope > .persona-border-t`);return g?.classList.add(`persona-activity-body`),g&&(g.id=`activity-details-${t.id}`,i.setAttribute(`aria-controls`,g.id)),e}function ds(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map,a=e=>{clearTimeout(i.get(e)),i.delete(e)};return{observe(a,o,s,c={}){let l=o===`tool`?a.toolCall:a.reasoning;if(l&&!n.has(a.id)&&(!t.has(a.id)&&l.status!==`complete`&&l.chunks?.some(Boolean)&&(t.add(a.id),c.autoExpand!==!1&&s.add(a.id)),t.has(a.id)&&l.status===`complete`&&!r.has(a.id))){if(r.add(a.id),c.autoCollapseDelay===!1)return;i.set(a.id,setTimeout(()=>{i.delete(a.id),s.delete(a.id),e(a.id,o)},c.autoCollapseDelay??1e3))}},manual(e){n.add(e),a(e)},prune(e){for(let i of/* @__PURE__ */ new Set([...t,...n,...r]))e.has(i)||(a(i),t.delete(i),n.delete(i),r.delete(i))},clear(){for(let e of i.keys())a(e);t.clear(),n.clear(),r.clear()}}}function fs(e,t,n,r){let i=B(`div`,``);i.id=`bubble-${e.id}`,i.dataset.messageId=e.id;let a=B(`button`,``);a.type=`button`,a.dataset.expandHeader=`true`,a.dataset.bubbleType=`tool`,a.setAttribute(`aria-expanded`,String(n));let o=B(`div`,``);typeof r==`string`?o.textContent=r:o.appendChild(r),rs(a,o,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||`currentColor`,metaGap:!0});let s=B(`div`,`persona-border-t`);return s.id=`activity-details-${e.id}`,s.style.display=n?``:`none`,a.setAttribute(`aria-controls`,s.id),i.append(a,s),us(i,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:`row`}}},`tool`),i.dataset.personaToolGroup=`true`,t.features?.toolCallDisplay?.loadingAnimation===`shimmer`&&(i.dataset.activityGroupShimmer=`true`),{bubble:i,body:s}}function ps(e,t){let n=e.voiceRecognition,r=t.voiceRecognition;return n?.enabled===!0!=(r?.enabled===!0)||n?.provider?.type!==r?.provider?.type||n?.provider?.custom!==r?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==r?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(r?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function ms(e){return e?.type===`runtype`||e?.type===`custom`}const hs=()=>typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window);function gs(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:hs()}catch{return!1}}const _s=e=>{if(!e)return;let t={},n=e;if(n.heading){let e=n.heading;t.heading=(t,n,r)=>e({type:`heading`,raw:r,depth:n,text:t,tokens:[]})}if(n.code){let e=n.code;t.code=(t,n,r)=>e({type:`code`,raw:``,text:t,lang:n,escaped:r})}if(n.blockquote){let e=n.blockquote;t.blockquote=t=>e({type:`blockquote`,raw:``,text:t,tokens:[]})}if(n.table){let e=n.table;t.table=(t,n)=>e({type:`table`,raw:``,header:[],rows:[],align:[],headerHtml:t,bodyHtml:n})}if(n.link){let e=n.link;t.link=(t,n,r)=>e({type:`link`,raw:``,href:t,title:n??null,text:r,tokens:[]})}if(n.image){let e=n.image;t.image=(t,n,r)=>e({type:`image`,raw:``,href:t,title:n??null,text:r})}if(n.list){let e=n.list;t.list=(t,n,r)=>e({type:`list`,raw:``,ordered:n,start:r,loose:!1,items:[],itemsHtml:t})}if(n.listitem){let e=n.listitem;t.listitem=(t,n,r)=>e({type:`list_item`,raw:``,task:n,checked:r,loose:!1,text:t,tokens:[]})}if(n.paragraph){let e=n.paragraph;t.paragraph=t=>e({type:`paragraph`,raw:``,text:t,tokens:[]})}if(n.codespan){let e=n.codespan;t.codespan=t=>e({type:`codespan`,raw:``,text:t})}if(n.strong){let e=n.strong;t.strong=t=>e({type:`strong`,raw:``,text:t,tokens:[]})}if(n.em){let e=n.em;t.em=t=>e({type:`em`,raw:``,text:t,tokens:[]})}if(n.del){let e=n.del;t.del=t=>e({type:`del`,raw:``,text:t,tokens:[]})}if(n.html){let e=n.html;t.html=t=>e({type:`html`,raw:t,text:t})}if(n.text){let e=n.text;t.text=t=>e({type:`text`,raw:t,text:t})}if(n.checkbox){let e=n.checkbox;t.checkbox=t=>e({checked:t})}return n.hr&&(t.hr=n.hr),n.br&&(t.br=n.br),t},vs=e=>{let t=null;return n=>{let r=O();if(!r)return Ss(n);if(!t){let{Marked:n}=r,i=e?.markedOptions;t=new n({gfm:i?.gfm??!0,breaks:i?.breaks??!0,pedantic:i?.pedantic,silent:i?.silent});let a=_s(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},ys=e=>e?vs({markedOptions:e.options,renderer:e.renderer}):vs(),bs=vs(),xs=e=>bs(e),Ss=e=>e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`),Cs=e=>e.replace(/"/g,`&quot;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`),ws=e=>`%%FORM_PLACEHOLDER_${e}%%`,Ts=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,n)=>{try{let e=JSON.parse(n.trim());if(e&&typeof e==`object`&&e.component===`form`&&e.type){let n=ws(t.length);return t.push({token:n,type:String(e.type)}),n}}catch{return e}return e}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,n)=>{let r=ws(t.length);return t.push({token:r,type:n}),r}),n},Es=e=>{let t=ys(e);return e=>{let n=[],r=Ts(e,n),i=t(r);return n.forEach(({token:e,type:t})=>{let n=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`g`),r=`<div class="persona-form-directive" data-tv-form="${Cs(t)}"></div>`;i=i.replace(n,r)}),i}},Ds=e=>{let t=[],n=Ts(e,t),r=xs(n);return t.forEach(({token:e,type:t})=>{let n=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`g`),i=`<div class="persona-form-directive" data-tv-form="${Cs(t)}"></div>`;r=r.replace(n,i)}),r},Os={ALLOWED_TAGS:/* @__PURE__ */ `h1.h2.h3.h4.h5.h6.p.br.hr.div.span.ul.ol.li.dl.dt.dd.strong.em.b.i.u.s.del.ins.mark.small.sub.sup.abbr.kbd.var.samp.code.a.img.blockquote.pre.details.summary.table.thead.tbody.tfoot.tr.th.td.caption.colgroup.col.input.label.select.option.textarea.button`.split(`.`),ALLOWED_ATTR:/* @__PURE__ */ `href.src.alt.title.target.rel.loading.width.height.colspan.rowspan.scope.class.id.type.name.value.placeholder.disabled.checked.for.aria-label.aria-hidden.aria-expanded.role.tabindex.data-tv-form.data-message-id.data-persona-component-directive.data-preserve-animation.data-persona-instance`.split(`.`)},ks=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,As=()=>{let e=null;return t=>{let n=O();if(!n)return Ss(t);if(!e){let{DOMPurify:t}=n;e=t(typeof window<`u`?window:void 0),e.addHook(`uponSanitizeAttribute`,(e,t)=>{if(t.attrName===`src`||t.attrName===`href`){let e=t.attrValue;e.toLowerCase().startsWith(`data:`)&&!ks.test(e)&&(t.attrValue=``,t.keepAttr=!1)}})}return e.sanitize(t,Os)}},js=e=>e===!1?null:typeof e==`function`?e:As(),Ms=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Ns=e=>e.includes(`|`),Ps=e=>{let t=e.trim();return t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&(t=t.slice(0,-1)),t.split(`|`).map(e=>e.trim())},Fs=e=>`| ${e.join(` | `)} |`,Is=e=>`| ${Array.from({length:e},()=>`---`).join(` | `)} |`,Ls=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>``)),Rs=e=>{if(!e||!e.includes(`|`))return e;let t=e.split(`
12
- `),n=!1;for(let e=0;e<t.length-1;e++){let r=t[e],i=t[e+1];if(!Ns(r)||Ms.test(r)||!Ms.test(i))continue;let a=Ps(r).length;if(a<1)continue;let o=Is(a);t[e+1]!==o&&(t[e+1]=o,n=!0);let s=e+2;for(;s<t.length;s++){let e=t[s];if(e.trim()===``||!Ns(e))break;let r=Fs(Ls(Ps(e),a));t[s]!==r&&(t[s]=r,n=!0)}e=s-1}return n?t.join(`
13
- `):e},zs=`var(--persona-md-table-scroll-fade, 24px)`,Bs=/* @__PURE__ */ new WeakSet;function Vs(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(`persona-table-scroll`))return;let t=document.createElement(`div`);t.className=`persona-table-scroll`,e.replaceWith(t),t.appendChild(e)})}function Hs(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute(`data-persona-scroll-x`);return}e.setAttribute(`data-persona-scroll-x`,``);let n=getComputedStyle(e).direction===`rtl`?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty(`--persona-fade-l`,n<=1?`0px`:zs),e.style.setProperty(`--persona-fade-r`,r<=1?`0px`:zs)}function Us(e){Bs.has(e)||(Bs.add(e),e.addEventListener(`scroll`,e=>{let t=e.target;t?.classList?.contains(`persona-table-scroll`)&&Hs(t)},!0)),e.querySelectorAll(`.persona-table-scroll`).forEach(Hs)}g();const{setLoader:Ws,load:Gs}=h({fallbackImport:()=>import(`@runtypelabs/persona/webmcp-runtime`)}),Ks=Gs;g();const{setLoader:qs,load:Js}=h({fallbackImport:()=>import(`@runtypelabs/persona/voice-client-tools`)}),Ys=Js;function Xs(e){return e.startsWith(`agent_`)?{kind:`agentId`,agentId:e}:e.startsWith(`flow_`)?{kind:`flowId`,flowId:e}:null}function Zs(e,t){let n=e.trim();if(!n)throw Error("[Persona] `target` is empty.");let r=n.indexOf(`:`);if(r>0){let e=n.slice(0,r),i=n.slice(r+1);if(e===`runtype`){let e=Xs(i);if(e)return e;throw Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let a=t?.[e];if(!a)throw Error(`[Persona] No target provider registered for "${e}". Add a \`targetProviders.${e}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:`payload`,payload:a(i).payload}}let i=Xs(n);if(i)return i;let a=t?.default;if(a)return{kind:`payload`,payload:a(n).payload};throw Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function Qs(){return`msg_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function $s(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function ec(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function tc(){return`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}const nc=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),rc=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ic=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=nc(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:rc(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},ac=(e,t)=>{let n=[],r=[],i=[],a=``,o,s=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let c of e){let e=ic(c);if(e){let t=c.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==o)&&s(),r.length===0&&(a=c.createdAt,o=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let l=t(c);l&&(s(),n.push(l))}return s(),n};Ce(),sn(),Ze(),An(),Fo(),dn();var oc=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryClientError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};const sc=e=>`reason`in e?e.reason:void 0,cc=(e,t)=>e instanceof oc&&e.code===t,lc=e=>!e.voiceCaption&&!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),uc=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),dc=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function fc(e){switch(e){case`json`:return Je;case`regex-json`:return qe;case`xml`:return Xe;default:return Ke}}var pc=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;constructor(e={},t={}){if(this.config=e,this.historyInternals=t,this.#l=null,this.clientSession=null,this.#u=null,this.#d=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null,this.#p=!1,this.#m=!1,this.#h=!1,this.#g=null,this.#_=/* @__PURE__ */ new Set,this.#v=/* @__PURE__ */ new Set,this.webMcpBridge=null,this.#y=null,this.#H=null,this.#W=null,e.target&&(e.agentId||e.flowId||e.agent))throw Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??`https://api.runtype.com/v1/dispatch`,this.#t={"Content-Type":`application/json`,"X-Persona-Version":kn,...e.headers},this.debug=!!e.debug,this.#n=e.streamParser??fc(e.parserType),this.#r=e.contextProviders??[],this.#i=e.requestMiddleware,this.#a=e.customFetch,this.#o=e.parseSSEEvent,this.#s=e.getHeaders,e.webmcp?.enabled===!0&&(this.#y=this.#x(e.webmcp))}#x(e){return Ks().then(t=>{let n=new t.WebMcpBridge(e,{recordToolDisplayTitles:L,getToolDisplayTitle:be,loadPolyfill:Se});return this.#b!==void 0&&n.setConfirmHandler(this.#b),this.webMcpBridge=n,n}).catch(e=>(this.#y=null,console.warn(`[Persona] Failed to load the WebMCP runtime chunk`,e),null))}#S(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled===!0?(this.#y||=this.#x(this.config.webmcp),this.#y):Promise.resolve(null)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#c=e}setWebMcpConfirmHandler(e){this.#b=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}getVoiceClientTools(){if(this.config.webmcp?.enabled!==!0)return null;let e=()=>this.#S(),t={open:async e=>(await Ys()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await(await e())?.snapshotForDispatch()??[];return{tools:t,fingerprint:he(t)}},onChange:t=>{let n=null,r=!1;return e().then(e=>{e&&!r&&(n=e.watchToolChanges(t))}),()=>{r=!0,n?.()}},execute:async(t,n,r)=>{let i=await e();return i?i.executeVoiceToolCall(t,n,r):{status:`failed`,error:{message:`WebMCP runtime failed to load.`}}}};return t}executeWebMcpToolCall(e,t,n){return this.config.webmcp?.enabled===!0?this.#S().then(r=>r?r.executeToolCall(e,t,n):{isError:!0,content:[{type:`text`,text:`WebMCP runtime failed to load.`}]}):null}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#C(){let{agentId:e,flowId:t,target:n,targetProviders:r}=this.config;if(!n)return{agentId:e,flowId:t};let i=Zs(n,r);return i.kind===`agentId`?{agentId:i.agentId}:i.kind===`flowId`?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.#C().agentId)}#w(){return this.config.apiUrl?.replace(/\/+$/,``).replace(/\/v1\/dispatch$/,``)||`https://api.runtype.com`}#T(e){return`${this.#w()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),n=!1;for(;;){let r=t.conversationId,i=await this.readVisitorToken();if(t.durableRecovery?.enabled!==!0||!r||!i)throw new oc(`visitor_token_missing`,`Durable recovery is not enabled for this client session`);let a=`${this.#w()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,o=new URLSearchParams({sessionId:t.sessionId,after:e.after}),s=await fetch(`${a}?${o}`,{method:`GET`,headers:{"X-Persona-Version":kn,"X-Visitor-Token":i},signal:e.signal});if(s.status===401&&!n){n=!0;let e=await ar();t=await e.recoverFromUnauthorized(this.#G(),await e.readErrorCode(this.#G(),s),null,!0)}else{if(!s.ok)throw await(await ar()).historyErrorFor(this.#G(),s,!0);return s}}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#u||e&&/* @__PURE__ */ new Date<e.expiresAt||this.#d===e?null:(this.#d=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw Error(`initSession() only available in client token mode`);if(this.clientSession&&/* @__PURE__ */ new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#u)return this.#u;let e=this.#u=this.#N().then(t=>this.#u===e?(this.clientSession=t,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#u===e&&(this.#u=null)});return e}#E(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#p}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#D(){if(!this.#p){this.#j({state:`unavailable`,reason:`history_disabled`}),this.#p=!0,!this.#m&&typeof console<`u`&&(this.#m=!0,console.warn(`[Persona] Visitor history is disabled for this surface; continuing without it.`)),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#v])e(!1)}}getHistoryIdentityStatus(){return this.#g??this.#O()}subscribeHistoryIdentityStatus(e){return this.#_.add(e),()=>{this.#_.delete(e)}}subscribeHistoryAvailability(e){return this.#v.add(e),this.#p&&e(!1),()=>{this.#v.delete(e)}}#O(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#p?{state:`unavailable`,reason:`history_disabled`}:this.#k():{state:`unavailable`,reason:`ineligible_mode`}}#k(){let e=this.#g;return e?.state===`browser_only`?e:this.#A()}#A(){return this.config.features?.history?.scope===`browser`?{state:`browser_only`,reason:`configured_browser_scope`}:this.config.getIdentityProof?{state:`browser_only`,reason:`proof_unavailable_before_binding`}:{state:`browser_only`,reason:`no_identity_provider`}}#j(e){let t=this.getHistoryIdentityStatus(),n=t.state===e.state&&sc(t)===sc(e);if(this.#g=e,!n){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#_])t(e)}}async#M(e){let t=this.#E()&&!e.omitVisitorFields,n=!e.omitVisitorFields,r=null;(t||n)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let i=this.#C(),a=i.agentId??i.flowId,o=t||e.durableResume?e.conversationId:void 0,s={token:this.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(t||n)&&r?{visitorToken:r}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...o?{conversationId:o}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let c=await fetch(this.#T(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":kn},body:JSON.stringify(s),signal:e.signal});if(!c.ok){let n=await c.json().catch(()=>({error:`Session initialization failed`}));if(t&&c.status===403&&n.error===`visitor_history_disabled`){if(this.#D(),o)throw new oc(`history_disabled`,`Visitor history is disabled for this surface`);return this.#M({...e,omitVisitorFields:!0})}throw c.status===403&&n.error===`durable_recovery_disabled`?new oc(`history_disabled`,`Durable recovery is disabled for this surface`):(t||e.durableResume)&&c.status===401&&n.error===`visitor_required`?new oc(`visitor_required`,`Visitor credential no longer resolves`):o&&c.status===404?new oc(`not_found`,`Conversation not found`):c.status===401?Error(`Invalid client token: ${n.hint||n.error}`):c.status===403?Error(`Origin not allowed: ${n.hint||n.error}`):Error(n.error||`Failed to initialize session`)}let l=await c.json();return l.visitor?.token&&await this.historyInternals.visitorStore?.set(l.visitor.token),{sessionId:l.sessionId,expiresAt:new Date(l.expiresAt),flow:l.flow,...l.conversationId?{conversationId:l.conversationId}:{},...l.targetId?{targetId:l.targetId}:{},...l.conversationRevision?{conversationRevision:l.conversationRevision}:{},...l.durableRecovery?{durableRecovery:l.durableRecovery}:{},...l.visitor?{visitor:l.visitor}:{},config:{welcomeMessage:l.config.welcomeMessage,placeholder:l.config.placeholder,theme:l.config.theme}}}async#N(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,t=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#E()&&!t)return this.#P(e,!1);let n=await this.readVisitorToken();if(e&&n)try{let n=await this.#M({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#R(n,e,!1)}catch(n){if(!cc(n,`not_found`)&&!cc(n,`visitor_required`)&&!cc(n,`history_disabled`))throw n;return t&&this.historyInternals.setStoredResumableHandle?.(null),this.#P(e,!0)}return this.#P(e,!1)}async#P(e,t){let n=this.historyInternals.visitorStore;return n&&!await this.readVisitorToken()?n.withFirstInitLock(()=>this.#F(e,t)):this.#F(e,t)}async#F(e,t){let n=this.config.getStoredSessionId?.()||null,r=await this.#M({storedSessionId:n}),i=await this.#L(r);return this.#R(i,e,t)}async#I(e){let t=this.config.getStoredSessionId?.()||null,n=this.config.getStoredConversationId?.()||null,r=await this.#M({storedSessionId:t,identityProof:e}),i=this.#R(r,n,!1);return this.clientSession=i,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint(),i}async#L(e){if(!e.visitor?.token||this.#h||!this.#E()&&e.durableRecovery?.enabled!==!0)return e;this.#h=!0;try{return await this.#M({storedSessionId:e.sessionId})}catch{return e}finally{this.#h=!1}}#R(e,t,n){let r=e.conversationId;return r&&t&&(n||r!==t)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#z(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#d=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw Error(`prepareConversationSession() only available in client token mode`);if(!this.#E())throw new oc(`history_disabled`,`Visitor history is disabled for this surface`);await this.historyInternals.historyBootstrapReady;let n=t?.proof??null;if(!await this.readVisitorToken()&&!n)throw new oc(`conversation_credential_missing`,`Reopening a conversation requires a stored visitor token or an identity proof`);let r=await this.#M({conversationId:e,identityProof:n});return this.#z(r)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error(`prepareNewConversationSession() only available in client token mode`);await this.historyInternals.historyBootstrapReady;let e=await this.#M({});return this.#z(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#E()&&this.#j(this.#A())}clearClientSession(){this.clientSession=null,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null}#B(){return`${this.#w()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw Error(`sendFeedback() only available in client token mode`);if(!this.getClientSession())throw Error(`No active session. Please initialize session first.`);if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let t={...e,...this.config.clientToken&&{token:this.config.clientToken}},n=await fetch(this.#B(),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":kn},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:`Feedback submission failed`}));throw n.status===401?(this.clientSession=null,this.#d=!1,this.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async submitMessageFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`csat`,rating:e,comment:t})}async submitNPSFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`nps`,rating:e,comment:t})}async#V(e){e?.throwIfAborted();let t=this.config.identityProvider;if(t===void 0)return;let n=this.config.getIdentityProof;if(!t.trim()||!n)throw Error(`Chat identity requires identityProvider and getIdentityProof.`);let r,i;try{let t=Promise.resolve().then(()=>n());r=e?await Promise.race([t,new Promise((t,n)=>{i=()=>n(e.reason),e.addEventListener(`abort`,i,{once:!0}),e.aborted&&i()})]):await t}catch{throw e?.throwIfAborted(),Error(`The identity proof provider failed.`)}finally{i&&e?.removeEventListener(`abort`,i)}if(typeof r!=`string`||!r.trim())throw Error(`A fresh identity proof is required to send this message.`);return{provider:t,token:r}}#H;#U(){let e=this;return this.#H??={get config(){return e.config},headers:this.#t,getHeaders:this.#s,debug:this.debug,clientApiBase:()=>e.#w(),getClientApiUrl:t=>e.#T(t),getWebMcpBridge:()=>e.#S(),sendWithClientToolsDiff:(t,n,r,i)=>e.#Y(t,n,r,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#W;#G(){let e=this;return this.#W??={HistoryClientError:oc,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#w(),setHistoryIdentityStatus:t=>e.#j(t),browserOnlyStatus:()=>e.#k(),derivedBrowserOnly:()=>e.#A(),reinitWithProof:t=>e.#I(t),isHistoryCapable:()=>e.#E(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await ar()).listConversations(this.#G(),e)}async getConversation(e,t){return(await ar()).getConversation(this.#G(),e,t)}async finalizeDisplayProjections(e,t){return(await ar()).finalizeDisplayProjections(this.#G(),e,t)}async deleteConversation(e,t){return(await ar()).deleteConversation(this.#G(),e,t)}async deleteAllConversations(e){return(await ar()).deleteAllConversations(this.#G(),e)}async resetVisitor(){return(await ar()).resetVisitor(this.#G())}async dispatch(e,t){return e.signal?.throwIfAborted(),Tn().catch(()=>{}),this.isClientTokenMode()?this.#K(e,t):this.isAgentMode()?this.#J(e,t):this.#q(e,t)}async#K(e,t){let n=tc();this.#l=n;let r=()=>this.#l===n,i=e=>{r()&&t(e)};t({type:`status`,status:`connecting`});try{let t=()=>{if(e.signal?.throwIfAborted(),!r())throw new DOMException(`Turn superseded`,`AbortError`)},a=this.clientSession??await this.initSession();t();let o=async()=>{t();let n=a,r=n.durableRecovery?.enabled===!0;if(r&&(!n.conversationId||!await this.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);t();let i=await this.#M({...r||this.#E()?{conversationId:n.conversationId,durableResume:r}:{storedSessionId:n.sessionId},signal:e.signal});if(t(),n.conversationId&&i.conversationId!==n.conversationId||r&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);a=this.#R(i,n.conversationId??null,!1),this.clientSession=a,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(a)};Date.now()>=a.expiresAt.getTime()-6e4&&await o();let s=await this.#te(e.messages),c=s.metadata?Object.fromEntries(Object.entries(s.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,l=this.#E(),u={sessionId:a.sessionId,messages:e.messages.filter(lc).map(e=>{let t=l?jo(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...c&&Object.keys(c).length>0&&{metadata:c},...s.inputs&&Object.keys(s.inputs).length>0&&{inputs:s.inputs},...s.context&&{context:s.context},turnId:n,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0}}},d=async()=>{t();let n=a.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return t(),this.#Y(a.sessionId,s.clientTools,async r=>{t();let i=await this.#V(e.signal);t();let o={...u,sessionId:a.sessionId,...r,...i&&{identityProof:i}};return this.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...o,...i&&{identityProof:{provider:i.provider,token:`[REDACTED]`}}}),fetch(this.#T(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":kn,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(o),signal:e.signal})})},f=await d();if(t(),f.response.status===401){let e=await f.response.clone().json().catch(()=>null);t(),e?.error===`Session not found or expired`&&(await o(),f=await d(),t())}let{response:p,commit:m}=f;if(!p.ok){let e=await p.json().catch(()=>({error:`Chat request failed`}));if(p.status===401&&e.error===`invalid_identity_proof`){let e=new oc(`invalid_identity_proof`,`The identity proof was rejected`);throw i({type:`error`,error:e}),e}if(p.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw i({type:`error`,error:e}),e}if(p.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw i({type:`error`,error:t}),t}if(p.status===410&&e.error===`conversation_deleted`){let e=new oc(`conversation_deleted`,`This conversation was deleted`);throw i({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw i({type:`error`,error:t}),t}if(!p.body){let e=/* @__PURE__ */ Error(`No response body received`);throw i({type:`error`,error:e}),e}m(),i({type:`status`,status:`connected`});try{await this.#ne(p.body,i,e.assistantMessageId)}finally{i({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof oc)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&i({type:`error`,error:t}),t}}async#q(e,t){t({type:`status`,status:`connecting`});let n=await this.#te(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t)}finally{t({type:`status`,status:`idle`})}}async#J(e,t){t({type:`status`,status:`connecting`});let n=await this.#ee(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t,e.assistantMessageId)}finally{t({type:`status`,status:`idle`})}}async processStream(e,t,n,r){t({type:`status`,status:`connected`});try{await this.#ne(e,t,n,r)}finally{t({type:`status`,status:`idle`})}}async resolveApproval(e,t){return(await Tn()).resolveApproval(this.#U(),e,t)}async#Y(e,t,n,r){let i=!!(t&&t.length>0),a=i?he(t):void 0,o=this.clientToolsFingerprintSessionId===e,s=i&&o&&this.lastSentClientToolsFingerprint===a,c=!i&&r?.emptyMeansReplace===!0&&this.#f===e,l=!1,u;for(let e=0;u=await n({...i&&(l||!s)&&t?{clientTools:t}:{},...c?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&e===0&&i&&(await u.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)l=!0,this.lastSentClientToolsFingerprint=null;return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,i?this.#f=e:c&&(this.#f=null)}}}async resumeFlow(e,t,n){return(await Tn()).resumeFlow(this.#U(),e,t,n)}#X(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#Z(e){let t={};this.#r.length&&await Promise.all(this.#r.map(async n=>{try{let r=await n({messages:e,config:this.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#X(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#Q(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#$(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}async#ee(e,t){let n=this.#C().agentId;if(!this.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=ac(uc(e),e=>lc(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?dc(e):null),i=this.#Q(t),a={agent:this.#$(this.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.config.agentOptions}};i&&(a.composerOptions=i);let o=[...on(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let s=await this.#Z(e);return s&&(a.context=s),a}async#te(e,t){let n=ac(uc(e),e=>lc(e)?dc(e):null),r=this.#C(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...on(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#Z(e);o&&(i.context=o);let s=this.#Q(t);if(s&&(i.composerOptions=s),this.#i)try{let e=await this.#i({payload:{...i},config:this.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}async#ne(e,t,n,r){let{streamResponse:i}=Dn()??await Tn();return i({config:()=>this.config,createStreamParser:this.#n,parseSSEEvent:this.#o,onSSEEvent:(e,t)=>this.#c?.(e,t)},e,t,n,r)}},mc=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryProviderError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};function hc(e){return e instanceof mc}function gc(e){let t=0;for(let n of e.split(`
14
- `)){let e=/^ {0,3}(`+)/.exec(n);e&&e[1].length>t&&(t=e[1].length)}return t}function _c(e,t){let n="`".repeat(Math.max(3,gc(t)+1));return`${n}${e}\n${t}\n${n}`}Ui();const vc=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:`quoted-text`;function yc(e){let t=e?.text?.trim()??``;return t?_c(vc(e),t):``}function bc(e){let t=yc(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[ki(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
11
+ `)[0]).startsWith(t.trigger):!1),l=(e,t)=>{if(typeof window<`u`)try{window.dispatchEvent(new CustomEvent(`persona:mention:${e}`,{detail:t}))}catch{}},u=!e.chipRow,d=e.chipRow??B(`div`,{className:`persona-mention-context-row`,attrs:{"data-persona-mention-context-row":``}}),f=null,p=null,m=e.textarea,h=null,g=null,_=null,v=null,y=()=>{if(f)return Promise.resolve(f);if(p)return p;let n=t().then(t=>(t.setMentionIconRenderer(r),f=t.mountContextMentions({mentionConfig:a,textarea:e.textarea,composerInput:h??void 0,anchor:e.anchor,contextRow:d,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:S,emit:l}),f)).catch(e=>(typeof console<`u`&&console.warn(`[Persona] Failed to load context mentions runtime`,e),p===n&&(p=null),null));return p=n,n};a.display===`inline`&&n().then(t=>{let n=t.mountInlineComposer({textarea:e.textarea,renderToken:e=>Ca(e,{render:a.renderMentionToken}),onMentionRemoved:e=>f?.untrackMention(e)});h=n.input,g=n.destroy;let r=m;r.replaceWith(n.element),m=n.element,v={next:n.element,prev:r},_?.(n.element,r),f?f.rebindComposer(n.input):p&&p.then(e=>e?.rebindComposer(n.input))}).catch(e=>{typeof console<`u`&&console.warn(`[Persona] Failed to load inline mention composer`,e)});let b=[],x=/* @__PURE__ */ new Map;for(let e of o){if(!e.showButton)continue;let t=i({config:{...a,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},onOpen:()=>{y().then(t=>t?.openMenu(e.trigger))}});b.push(t),x.set(e.trigger,t.button)}let S=(e,t,n)=>{let r=x.get(t);r&&(r.setAttribute(`aria-expanded`,e?`true`:`false`),e?r.setAttribute(`aria-controls`,n):r.removeAttribute(`aria-controls`))};return{affordanceButtons:b.map(e=>e.wrapper),contextRow:d,handleInput:e=>{if(f){f.handleInput();return}if(!fr(e))return;let t=m,n=t.selectionStart??0;dr(t.value,n,o)&&y().then(e=>e?.handleInput())},handleKeydown:e=>{if(f?.isMenuOpen())return f.handleKeydown(e);if(e.key===`Backspace`&&f?.hasMentions()&&!v){let t=m,n=t.selectionStart===0&&t.selectionEnd===0;if((t.value.length===0||n)&&f.removeLastChip())return e.preventDefault(),!0}return!1},isMenuOpen:()=>f?.isMenuOpen()??!1,hasMentions:()=>f?.hasMentions()??!1,getMentionRefs:()=>f?.getMentionRefs()??[],collectForSubmit:()=>f?.collectForSubmit()??null,takeInlineCommand:async e=>c(e)?(f??await y())?.dispatchInlineCommand(e)??null:null,clear:()=>f?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:e=>{_=e,v&&e(v.next,v.prev)},destroy:()=>{f?.destroy(),g?.();for(let e of b)e.wrapper.remove();u&&d.remove()}}}var Ea,Da=o((()=>{V(),mr(),gr(),ma(),va(),F(),Sa(),wa(),Ea={loadContextMentions:()=>_a(),loadContextMentionsInline:()=>xa(),renderLucideIcon:(...e)=>P(...e),createMentionButton:(...e)=>pa(...e)}})),Oa=/* @__PURE__ */ s({createAskUserSheetHandlers:()=>sr,createContextMentionOrchestrator:()=>Ta}),ka=o((()=>{cr(),Da()}));ka(),g();const{setLoader:Aa,load:ja,provide:Ma,getSync:Na}=h({fallbackImport:()=>Promise.resolve().then(()=>(ka(),Oa))}),Pa=ja,Fa=Ma,Ia=Na;Fa(Oa);function La(){return`msg_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function Ra(){return`usr_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function za(){return`ast_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}function Ba(){return`turn_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,10)}`}var Va=o((()=>{})),Ha=/* @__PURE__ */ s({resolveApproval:()=>Ua,resolveAskUserQuestion:()=>Wa,resolveWebMcpToolCall:()=>Ya,resolveWebMcpToolCallBatch:()=>Ja});async function Ua(e,t,n,r){let i=`approval-${t.id}`,a=`approval-error-${t.id}`,o=za(),s={};e.s.approvalTokens.set(i,s);let c={...t,status:n,resolvedAt:Date.now()},l=e.s.messages.find(e=>e.id===i),u={id:i,role:`assistant`,content:``,createdAt:l?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),...l?.sequence===void 0?{}:{sequence:l.sequence},streaming:!1,variant:`approval`,approval:c};e.s.upsertMessage(u),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let d=e.s.config.approval,f=d&&typeof d==`object`?d.onDecision:void 0;try{let l;if(l=f?await f({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):await e.s.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n,{assistantMessageId:o}),l){let r=null;if(l instanceof Response){if(!l.ok){let n=await l.json().catch(()=>null),r=n?.message??n?.error??`Approval request failed: ${l.status}`,o=n?.code===`APPROVAL_ALREADY_RESOLVED`||l.status===404&&/no paused execution/i.test(String(n?.error)),d=e.s.messages.find(e=>e.id===i);throw e.s.approvalTokens.get(i)===s&&d?.approval?.resolvedAt===c.resolvedAt&&(e.s.upsertMessage({...u,approval:o?{...c,status:`timeout`}:t}),o&&e.settleApprovalPausedToolCall(i),e.s.upsertMessage({id:a,role:`assistant`,content:r,localOnly:!0,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})),Error(r)}r=l.body}else l instanceof ReadableStream&&(r=l);e.s.approvalTokens.get(i)===s&&e.s.messages.some(e=>e.id===a)&&(e.s.messages=e.s.messages.filter(e=>e.id!==a),e.s.callbacks.onMessagesChanged([...e.s.messages])),r?await e.s.connectStream(r,{allowReentry:!0,assistantMessageId:o}):(n===`denied`&&(e.settleApprovalPausedToolCall(i),e.appendMessage({id:`denial-${t.id}`,role:`assistant`,content:`Tool execution was denied by user.`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})),e.setStreaming(!1),e.s.abortController=null)}else e.setStreaming(!1),e.s.abortController=null}catch(t){let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));e.setStreaming(!1),e.s.abortController=null,n||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}finally{e.s.approvalTokens.get(i)===s&&e.s.approvalTokens.delete(i)}}async function Wa(e,t,n){if(e.s.messages.find(e=>e.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,i=t.toolCall?.name;if(!r||!i){e.s.callbacks.onError?.(/* @__PURE__ */ Error(`resolveAskUserQuestion: message is missing executionId or toolCall.name`));return}let a=typeof n==`string`?void 0:n;if(a===void 0&&typeof n==`string`){let e=t.toolCall?.args,r=Array.isArray(e?.questions)?e.questions:[];if(r.length===1){let e=typeof r[0]?.question==`string`?r[0].question:``;e&&(a={[e]:n})}}e.s.markAskUserQuestionResolved(t,a),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let o=t.toolCall.id,s=t.toolCall?.args,c=Array.isArray(s?.questions)?s.questions:[];if(c.length===0){let t=typeof n==`string`?n:Object.entries(n).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `);e.appendMessage({id:`ask-user-answer-${o}`,role:`user`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})}else{let t=a??{};c.forEach((n,r)=>{let i=typeof n?.question==`string`?n.question:``;if(!i)return;let a=t[i],s=Array.isArray(a)?a.join(`, `):typeof a==`string`?a:``;e.appendMessage({id:`ask-user-q-${o}-${r}`,role:`assistant`,content:i,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()}),e.appendMessage({id:`ask-user-a-${o}-${r}`,role:`user`,content:s||`*Skipped*`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()})})}try{let t=za(),a=await e.s.client.resumeFlow(r,{[i]:n},{after:e.resumeAfter(r),assistantMessageId:t});if(!a.ok){let e=await a.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${a.status}`)}a.body?await e.s.connectStream(a.body,{allowReentry:!0,assistantMessageId:t}):(e.setStreaming(!1),e.s.abortController=null)}catch(t){let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));e.setStreaming(!1),e.s.abortController=null,n||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}}function Ga(e,t){let n=[e.s.messages.find(e=>e.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let e of n)if(typeof e==`number`&&Number.isFinite(e))return e;return Date.now()}function $(e,t){return t.toolCall?.name===`suggest_replies`&&(e.s.messages.find(e=>e.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function Ka(e,t){let n=Ga(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 qa(e,t,n,r,i=Date.now(),a){e.s.messages.some(e=>e.id===t.id)&&e.s.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:`complete`,result:n,startedAt:r,completedAt:i,duration:void 0,durationMs:Math.max(0,i-r)}:t.toolCall})}async function Ja(e,t,n){let r=[],i=new AbortController;e.s.webMcpResolveControllers.add(i),e.setStreaming(!0);let a=async n=>{let a=n.toolCall?.name,o=n.toolCall?.id;if(!a||!o)return null;let s=`${t}:${o}`;if(e.s.webMcpInflightKeys.has(s)||e.s.webMcpResolvedKeys.has(s)||$(e,n))return null;e.s.webMcpInflightKeys.add(s),r.push(s);let c=Ka(e,n),l=n.agentMetadata?.webMcpToolCallId??a;if(a===`suggest_replies`)return{dedupeKey:s,resumeKey:l,output:Xt(),toolMessage:n,startedAt:c,completedAt:Date.now()};let u=e.s.client.executeWebMcpToolCall(a,n.toolCall?.args,i.signal),d;if(!u)d={isError:!0,content:[{type:`text`,text:`WebMCP not enabled on this widget.`}]};else try{d=await u}catch(t){let r=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));return r||e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t))),qa(e,n,Za(r?`Aborted by cancel()`:Qa(t)),c),e.s.webMcpInflightKeys.delete(s),null}return i.signal.aborted?(qa(e,n,Za(`Aborted by cancel()`),c),e.s.webMcpInflightKeys.delete(s),null):{dedupeKey:s,resumeKey:l,output:d,toolMessage:n,startedAt:c,completedAt:Date.now()}},o;if(e.s.config.webmcp?.execution===`sequential`){o=[];for(let e of n)o.push(await a(e))}else o=await Promise.all(n.map(a));let s=[];try{if(s=o.filter(e=>e!==null),s.length===0)return;let n={};for(let e of s)n[e.resumeKey]=e.output;let r=za(),a=await e.s.client.resumeFlow(t,n,{signal:i.signal,after:e.resumeAfter(t),assistantMessageId:r});if(!a.ok){let e=await a.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${a.status}`)}let c=s[0].dedupeKey;for(let t of s){e.s.webMcpResolvedKeys.add(t.dedupeKey);let n=t.toolMessage.toolCall?.name,r=t.toolMessage.agentMetadata?.webMcpToolCallId;qa(e,t.toolMessage,t.output,t.startedAt,t.completedAt,{...n===`suggest_replies`?{suggestRepliesResolved:!0}:{},...n&&r?{clientToolAnswer:{toolCallId:r,toolName:n,args:t.toolMessage.toolCall?.args,result:t.output,batch:c}}:{}})}a.body&&await e.s.connectStream(a.body,{allowReentry:!0,assistantMessageId:r})}catch(t){if(!(t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`))))e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)));else for(let t of s)qa(e,t.toolMessage,Za(`Aborted by cancel()`),t.startedAt)}finally{for(let t of r)e.s.webMcpInflightKeys.delete(t);e.s.webMcpResolveControllers.delete(i),e.s.webMcpResolveControllers.size===0&&!e.s.abortController&&e.setStreaming(!1)}}async function Ya(e,t){let n=t.agentMetadata?.executionId,r=t.toolCall?.name,i=t.toolCall?.id;if(!n){e.s.callbacks.onError?.(/* @__PURE__ */ Error(`WebMCP await missing executionId: dispatch left paused.`));return}if(!r)return;if(!i){let t=`${n}:__no_tool_id__:${r}`;if(e.s.webMcpInflightKeys.has(t)||e.s.webMcpResolvedKeys.has(t))return;e.s.webMcpInflightKeys.add(t);try{await Xa(e,n,r,{isError:!0,content:[{type:`text`,text:`WebMCP await missing toolCall.id: cannot execute the page tool.`}]}),e.s.webMcpResolvedKeys.add(t)}catch(t){e.s.callbacks.onError?.(t instanceof Error?t:Error(String(t)))}finally{e.s.webMcpInflightKeys.delete(t)}return}let a=`${n}:${i}`;if(!(e.s.webMcpInflightKeys.has(a)||e.s.webMcpResolvedKeys.has(a)||$(e,t)))return Ja(e,n,[t])}async function Xa(e,t,n,r,i){let a=za(),o=await e.s.client.resumeFlow(t,{[n]:r},{signal:i?.signal,after:e.resumeAfter(t),assistantMessageId:a});if(!o.ok){let e=await o.json().catch(()=>null);throw Error(e?.error??`Resume failed: ${o.status}`)}i?.onHttpOk?.(),o.body?await e.s.connectStream(o.body,{allowReentry:!0,assistantMessageId:a}):e.s.webMcpResolveControllers.size===0&&(e.setStreaming(!1),e.s.abortController=null)}var Za,Qa,$a=o((()=>{Va(),rn(),Za=e=>({isError:!0,content:[{type:`text`,text:e}]}),Qa=(e,t=`WebMCP tool execution failed.`)=>e instanceof Error&&e.message?e.message:typeof e==`string`&&e?e:t}));$a(),g();const{setLoader:eo,load:to,provide:no,getSync:ro}=h({fallbackImport:()=>Promise.resolve().then(()=>($a(),Ha))}),io=to,ao=no,oo=ro;ao(Ha);function so(e){if(!e)return lo;let t={...lo};for(let n of co){let r=e[n];typeof r==`string`&&r.length>0&&(t[n]=r)}return t}var co,lo,uo=o((()=>{co=/* @__PURE__ */ `viewTitle.openHistoryLabel.openHistoryBusyLabel.newConversationLabel.expandLabel.collapseLabel.resizeLabel.showEarlierMessagesLabel.openConversationLoadingLabel.openConversationErrorTitle.openConversationRetryLabel.openConversationBackLabel.confirmCancelLabel.deleteConversationConfirmTitle.deleteConversationConfirm.deleteConversationConfirmLabel.clearHistoryConfirmTitle.clearHistoryConfirm.clearHistoryVerifiedConfirm.clearHistoryConfirmLabel.resetIdentityConfirmTitle.resetIdentityConfirm.resetIdentityConfirmLabel.conversationDeletedNotice.identityResetNotice.identityResetUnconfirmedNotice`.split(`.`),lo={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 fo(e){let{plugins:t,config:n}=e,r=!1,i=!1,a=!1,o=!1,s=null,c=[],l=()=>{for(let e of c.splice(0))try{e()}catch(e){po(`renderHistoryView cleanup`,e)}},u=(e,n)=>{for(let r of t){let t=r[e];if(t)try{let e=t(n);if(e)return e}catch(t){po(e,t)}}return null},d=()=>({presentation:e.getPresentation(),config:n}),f={header:t=>o?u(`renderHistoryHeader`,Object.freeze({...d(),returnSurface:e.getReturnSurface(),identityStatus:mo(t.identityStatus),pendingAction:go(t.pendingAction),copy:mo(t.copy),actions:Object.freeze({close:h.close,startNewConversation:h.startNewConversation}),defaultRenderer:t.defaultRenderer})):null,conversation:e=>o?u(`renderHistoryConversation`,Object.freeze({...d(),conversation:ho(e.conversation),active:e.active,pending:e.pending,open:e.open,requestDelete:e.requestDelete,defaultRenderer:e.defaultRenderer})):null,state:e=>o?u(`renderHistoryState`,Object.freeze({...d(),state:mo(e.state),identityStatus:mo(e.identityStatus),copy:mo(e.copy),...e.retry?{retry:e.retry}:{},...e.startNewConversation?{startNewConversation:e.startNewConversation}:{},defaultRenderer:e.defaultRenderer})):null},p=t.flatMap(t=>(t.railSections??[]).map(t=>({...t,placement:t.placement??`above-conversations`,items:[],render:n=>t.render(Object.freeze({collapsed:n,presentation:e.getPresentation(),actions:h}))}))),m=e.createView({slots:f,renderDom:!1,onModelChange:()=>y(),railSections:p}),h=Object.freeze({...m.operations,close:e.close}),g=()=>(o=!0,m.setDomRenderEnabled(!0),m.element),_=t=>Object.freeze({conversations:Object.freeze(t.conversations.map(ho)),activeConversationId:t.activeConversationId,state:mo(t.state),pendingAction:go(t.pendingAction),identityStatus:mo(t.identityStatus),nextCursor:t.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:mo(m.copy),actions:h,defaultRenderer:g,requestRender:()=>y(),onCleanup:e=>{c.push(e)}}),v=()=>{o=!1;let e=null;for(let n of t)if(n.renderHistoryView){try{e=n.renderHistoryView(_(m.getModel()))}catch(t){po(`renderHistoryView`,t),e=null}if(e)break}let n=!e||e.contains(m.element);return o=n,m.setDomRenderEnabled(n),e??m.element};function y(){if(!(!a||r||i)){i=!0;try{l();let t=v();if(t===s)return;let n=s;s=t,e.onElementChanged(t,n)}finally{i=!1}}}return a=!0,y(),{view:m,get element(){return s??m.element},requestRender:y,dispose:()=>{r=!0,l()}}}var po,mo,ho,go,_o=o((()=>{po=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},mo=e=>Object.freeze({...e}),ho=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),go=e=>e?mo(e):null})),vo,yo,bo,xo,So,Co,wo,To,Eo,Do,Oo,ko,Ao=o((()=>{vo=null,yo=()=>{if(vo!==null)return vo;if(typeof navigator>`u`)return!1;let e=navigator.userAgentData?.platform??navigator.platform??``;return/mac|iphone|ipad|ipod/i.test(e)},bo=`ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space`,xo=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},So=e=>{let t=e.toLowerCase().split(`+`).map(e=>e.trim()),n=t.pop(),r={key:n,mod:!1,shift:!1,alt:!1};for(let n of t)if(n===`mod`||n===`cmd`||n===`ctrl`)r.mod=!0;else if(n===`shift`)r.shift=!0;else if(n===`alt`||n===`option`)r.alt=!0;else return xo(`unknown modifier in`,e),null;return!r.mod||r.shift&&r.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(xo(`unsupported`,e),null):(n===`space`&&(r.key=` `),r)},Co=e=>bo.split(` `).find(t=>t.toLowerCase()===e)??(e===` `?`Space`:e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),wo=(e,t)=>{let n=So(e);if(!n)return``;let r=yo(),i=Co(n.key);if(!t&&r)return`${n.alt?`⌥`:``}${n.shift?`⇧`:``}⌘${i}`;let a=[t?r?`Meta`:`Control`:`Ctrl`];return n.alt&&a.push(`Alt`),n.shift&&a.push(`Shift`),a.push(i),a.join(`+`)},To=e=>wo(e,!1),Eo=e=>wo(e,!0),Do=(e,t)=>t.key?.toLowerCase()===e.key&&(yo()?t.metaKey:t.ctrlKey)===e.mod&&!(yo()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Oo=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`||e.isContentEditable},ko=e=>{let t=/* @__PURE__ */ new Map,n=e?.ownerDocument??(typeof document<`u`?document:null),r=(t,n)=>{if((t.scope??`widget`)===`page`)return!0;if(!e)return!1;let r=n.composedPath?.();return r?.length?r.includes(e):e.contains(n.target)},i=e=>{if(e.isComposing||!t.size)return;let n=e.composedPath?.()[0]??e.target;for(let i of t.values())if(Do(i.parsed,e)&&i.when?.()!==!1&&r(i,e)&&(i.allowInInput||!Oo(n))){e.preventDefault();try{i.run(e)}catch(e){xo(`${i.id} threw on`,i.combo),console.warn(e)}return}};return n?.addEventListener(`keydown`,i),{register(e){let n=So(e.combo);if(!n)return()=>{};let r=`${n.mod?`m`:``}${n.shift?`s`:``}${n.alt?`a`:``}${n.key}`,i=t.get(r);return i?(xo(`${i.id} already owns`,e.combo),()=>{}):(t.set(r,{...e,parsed:n}),e.element?.setAttribute(`aria-keyshortcuts`,Eo(e.combo)),()=>{t.get(r)?.id===e.id&&t.delete(r),e.element?.removeAttribute(`aria-keyshortcuts`)})},destroy(){t.clear(),n?.removeEventListener(`keydown`,i)}}}}));function jo(e){if(typeof e!=`string`||e===``)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Mo(e){return typeof e==`string`?e:void 0}function No(e){if(typeof e!=`object`||!e)return null;let t=e;switch(t.type){case`text`:return typeof t.text==`string`?Ai(t.text):null;case`image`:return typeof t.image==`string`?ji(t.image,{mimeType:Mo(t.mimeType),alt:Mo(t.alt)}):null;case`file`:return typeof t.data==`string`&&typeof t.mimeType==`string`&&typeof t.filename==`string`?Q(t.data,t.mimeType,t.filename):null;case`audio`:return typeof t.audio==`string`?{type:`audio`,audio:t.audio,...Mo(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case`video`:return typeof t.video==`string`?{type:`video`,video:t.video,...Mo(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function Po(e,t){let n=jo(t),r=e.map(e=>jo(e.timestamp)),i=Array(e.length),a=0;for(;a<r.length;){let e=r[a];if(e!==null){i[a]=e,a+=1;continue}let t=a;for(;t+1<r.length&&r[t+1]===null;)t+=1;let o=t-a+1,s=a>0?i[a-1]:null,c=t+1<r.length?r[t+1]:null,l=c!==null&&n!==null?Math.min(c,n):c??n;for(let e=0;e<o;e+=1)i[a+e]=l===null?s===null?zo+e:s+e+1:l-(o-e);a=t+1}return i.map(e=>new Date(e).toISOString())}function Fo(e,t){let n=Po(e,t?.beforeCreatedAt),r=[];return e.forEach((e,t)=>{if(typeof e?.id!=`string`||e.id===``||!Ro.includes(e.role))return;let i=e.role,a=n[t];if(e.displayAvailable===!1)r.push({id:e.id,role:i,content:``,createdAt:a,agentMetadata:{historyDisplayUnavailable:!0}});else if(typeof e.displayContent==`string`)r.push({id:e.id,role:i,content:e.displayContent,createdAt:a});else if(typeof e.content==`string`)r.push({id:e.id,role:i,content:e.content,createdAt:a});else if(Array.isArray(e.content)){let t=e.content.map(No).filter(e=>e!==null),n=Di(t);r.push({id:e.id,role:i,content:n||(Oi(t)?`[Image]`:``),createdAt:a,...t.length>0&&{contentParts:t}})}else r.push({id:e.id,role:i,content:``,createdAt:a})}),r}function Io(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 Lo(e,t){let n=/* @__PURE__ */ new Map;for(let t of e)n.set(t.id,t);for(let e of t)n.set(e.id,e);return[...n.values()].sort((e,t)=>{let n=new Date(e.createdAt).getTime(),r=new Date(t.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(r)&&n!==r)return n-r;let i=e.sequence??0,a=t.sequence??0;return i===a?e.id.localeCompare(t.id):i-a})}var Ro,zo,Bo=o((()=>{Wi(),Ro=[`user`,`assistant`,`system`],zo=0}));function Vo(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let t=Uo.get(e.code)??`unavailable`;return new n(t,Go(t),{...e.retryAfterSeconds===void 0?{}:{retryAfterSeconds:e.retryAfterSeconds}})}return new n(`unavailable`,Go(`unavailable`))}function Ho(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,r=e.getIdentityProofConfigured()?[`browser`,`verified-user`]:[`browser`],i={scopes:r},a=e=>{if(!r.includes(e))throw new t(`unsupported_scope`,Go(`unsupported_scope`))},o=async(t,n)=>{a(t);try{return await n()}catch(t){throw Vo(t,e.errors)}},s=t=>{let n=!1;return{conversationId:t.session.conversationId??``,conversationRevision:t.session.conversationRevision??``,async commit(){n||(n=!0,t.commit(),await e.onActivationCommitted(t.session))},discard(){n||(n=!0,t.discard())}}};return{capabilities:i,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(e){return n().subscribeHistoryIdentityStatus(e)},subscribeAvailability(e){return n().subscribeHistoryAvailability(e)},async list(e){return o(e.context.scope,async()=>{let t=await n().listConversations({...e.cursor?{cursor:e.cursor}:{},...e.limit===void 0?{}:{limit:e.limit},...e.targetId?{targetId:e.targetId}:{},scope:e.context.scope});return{items:t.data,nextCursor:t.nextCursor}})},async getPage(e,t){return o(t.context.scope,async()=>{let r=await n().getConversation(e,{...t.cursor?{messageCursor:t.cursor}:{},scope:t.context.scope}),i=Fo(r.messages,{...t.beforeCreatedAt?{beforeCreatedAt:t.beforeCreatedAt}:{}});return{summary:r.summary,messages:Lo([],i),conversationRevision:r.conversationRevision??``,nextCursor:r.nextMessageCursor}})},async prepareOpen(e,t){return o(t.context.scope,async()=>s(await n().prepareConversationSession(e)))},async prepareStartNew(e){return o(e.context.scope,async()=>s(await n().prepareNewConversationSession()))},async delete(e,t){await o(t.context.scope,()=>n().deleteConversation(e,{scope:t.context.scope}))},async deleteAll(e){return o(e.context.scope,()=>n().deleteAllConversations({...e.targetId===void 0?{}:{targetId:e.targetId},scope:e.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var Uo,Wo,Go,Ko=o((()=>{Bo(),Uo=/* @__PURE__ */ new Map([[`not_found`,`not_found`],[`conversation_deleted`,`not_found`],[`rate_limited`,`rate_limited`],[`authentication_required`,`authentication_required`],[`invalid_identity_proof`,`authentication_required`],[`visitor_identity_mismatch`,`authentication_required`],[`visitor_required`,`authentication_required`],[`identity_provider_failed`,`identity_provider_failed`],[`proof_not_admitted`,`proof_not_admitted`],[`identity_contract_violation`,`proof_not_admitted`],[`unauthorized`,`authentication_failed`],[`visitor_token_missing`,`authentication_failed`],[`conversation_credential_missing`,`authentication_failed`]]),Wo=/* @__PURE__ */ new Map([[`not_found`,`That conversation is no longer available.`],[`rate_limited`,`Too many history requests.`],[`authentication_failed`,`History access was not authorized.`],[`authentication_required`,`Sign in again to view account history.`],[`identity_provider_failed`,`The identity provider did not respond.`],[`proof_not_admitted`,`Account history is not available for this configuration.`],[`unsupported_scope`,`This history scope is not supported.`],[`unavailable`,`Conversation history is unavailable right now.`]]),Go=e=>Wo.get(e)??`Conversation history is unavailable right now.`})),qo=/* @__PURE__ */ s({createHistoryShell:()=>Jo}),Jo,Yo=o((()=>{uo(),_o(),V(),Ao(),fn(),Ko(),Jo=e=>{let t=so(e.config.features?.history?.copy),n=null,r=!1,i=null,a=null,o=`conversation`,s=null,c=null,l=null,u=null,d=0,f=null,p=null,m=null,h=`persona-history-${Math.random().toString(36).slice(2,8)}`,g=()=>e.historyFeatureEnabled()&&!!n&&!r,_=()=>{let t=e.session.getStatus();return e.isStreaming||t===`paused`||t===`resuming`},v=()=>{let t=e.config.features?.history?.scope;if(t)return t;let r=e.config.getIdentityProof?`verified-user`:`browser`,i=n?.capabilities.scopes;return!i||i.includes(r)?r:i[0]??r},y=()=>a?.scope??v(),b=()=>e.session.getClientSession()?.targetId??null,x=e=>`${e.state}:${`reason`in e?e.reason:``}`,S=t=>{let n=x(t);n!==u&&(u=n,e.eventBus.emit(`history:identityStatusChanged`,{status:t,timestamp:Date.now()}))},C=null,w=null,T=()=>{if(!e.historyFeatureEnabled())return null;let t=e.getHistoryProviderFactory();if(t)return t();let n=e.config.features?.history?.provider;return n?typeof n==`function`?(C!==n&&(C=n,w=n()),w):n:e.session.isClientTokenMode()?Ho({errors:e.historyErrors,client:e.session.getClient(),getIdentityProofConfigured:()=>typeof e.config.getIdentityProof==`function`,onActivationCommitted:t=>e.session.bindActivatedSession(t),getClient:()=>e.session.getClient()}):null},E=()=>{p?.(),p=null,m?.(),m=null,r=!1,n=T();let t={...e.historyInternals};n?t.historyProvider=n:delete t.historyProvider,e.historyInternals=t,e.session.setHistoryInternals(e.historyInternals),n&&(p=n.subscribeAvailability?.(e=>{r=!e,e||pt({restoreFocus:!1}),Vt()})??null,m=n.subscribeIdentityStatus(e=>S(e)),u=x(n.getIdentityStatus()))},D=()=>{let t=e.config.features?.history?.presentation??`panel`;if(t===`panel`||t===`auto`&&e.launcherEnabled&&!e.isDockedMountMode(e.config))return`panel`;let n=e.artifactSplitRoot??e.container;return(n.getBoundingClientRect().width||n.clientWidth)>=720?`rail`:`panel`},O=(e,t)=>{t?(e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`inert`,``)):(e.removeAttribute(`aria-hidden`),e.removeAttribute(`inert`))},ee=`data-persona-history-suppressed`,k=null,A=null,te=null,ne=null,re=null,ie=``,ae=()=>e.header===re?ie:e.config.layout?.showHeader===!1?`none`:``,j=()=>e.historyPresentation===`panel`&&!!te&&ne===te.element&&e.config.layout?.showHeader!==!1&&ae()!==`none`,M=()=>{for(let t of Array.from(e.header.children))t!==k&&t.setAttribute(ee,``)},N=()=>{for(let t of Array.from(e.container.querySelectorAll(`[${ee}]`)))t.removeAttribute(ee)},oe=()=>{let t=te;if(!t)return;if(Array.from(e.header.children).some(e=>e!==k&&!e.hasAttribute(ee))){A&&A!==e.header&&(A.style.removeProperty(`min-height`),A=null);let t=e.header.offsetHeight;t>0&&(e.header.style.minHeight=`${t}px`,A=e.header)}k||=z(`div`,`persona-history-header-host`),t.setHeaderPlacement(`external`);let n=t.getHeaderElement();n.parentNode!==k&&k.replaceChildren(n),k.parentNode!==e.header&&e.header.appendChild(k),M()},se=()=>{A&&=(A.style.removeProperty(`min-height`),null),k&&(te?.setHeaderPlacement(`inline`),k.remove(),k=null,N())},ce=null,le=()=>{ce&&(e.body.style.display=`none`,O(e.body,!0),e.footer.hidden=!0,O(e.footer,!0),j()?(oe(),e.header.style.display=ae(),O(e.header,!1)):(se(),e.header.style.display=`none`,O(e.header,!0)))};e.reapplyHistoryHostChrome=le;let ue=t=>{let n=e.body.style.display,r=e.footer.hidden,i=e.footer,a=e.header,o=e.header.style.display;re=a,ie=o,ce=()=>{ce=null,se(),re=null,e.body.style.display=n,O(e.body,!1),i.hidden=r,O(i,!1),e.footer!==i&&(e.footer.hidden=!1,O(e.footer,!1)),a.style.display=o,O(a,!1),e.header!==a&&(e.header.style.display=e.config.layout?.showHeader===!1?`none`:``,O(e.header,!1))},e.footer.parentNode?.insertBefore(t,e.footer),le()},de=null,fe=null,pe=null,me=null,he=()=>[e.header,e.panelElements.closeButtonWrapper,e.panelElements.clearChatButtonWrapper,e.body,e.footer],P=()=>e.config.features?.history?.rail?.collapsible!==!1,F=()=>e.config.features?.history?.rail?.side===`right`?`right`:`left`,ge=e=>Math.min(400,Math.max(200,Math.round(e))),_e=()=>e.config.features?.history?.rail?.resizable===!0,ve,ye=()=>{if(ve===void 0&&(ve=null,e.config.persistState!==!1))try{let t=Number(window.localStorage.getItem(`${e.currentKeyPrefix()}rail-width`));t&&(ve=t)}catch{}return ve},be=()=>ge(ye()??e.config.features?.history?.rail?.width??260),I=t=>{if(ve=t,e.config.persistState!==!1)try{window.localStorage.setItem(`${e.currentKeyPrefix()}rail-width`,String(t))}catch{}},xe=()=>P()&&e.config.features?.history?.rail?.collapsedBehavior===`overlay`,L=!1,R=e=>{let t=z(`img`);return t.src=e,t.alt=``,t.setAttribute(`aria-hidden`,`true`),t},Se=()=>{let t=e.config.features?.history?.rail?.brand;if(!t)return;let n=!1,r;return i=>{if(t.render)try{return t.render({collapsed:i})??null}catch(e){return n||(n=!0,console.warn(`[persona] history rail brand threw`,e)),null}return r===void 0&&(r=t.iconUrl?R(t.iconUrl):t.icon?e.renderLucideIcon(t.icon,20):null),r?r.cloneNode(!0):null}},Ce=()=>e.config.features?.history?.rail?.sections?.map(t=>{let n=!1,r=e=>{n||(n=!0,console.warn(`[persona] history rail section threw`,t.id,e))};return{id:t.id,title:t.title,placement:t.placement??`above-conversations`,items:t.items.map(t=>{let n;return{id:t.id,label:t.label,badge:t.badge,iconNode:()=>{if(n!==void 0)return n;try{n=t.renderIcon?t.renderIcon()??null:t.iconUrl?R(t.iconUrl):t.icon?e.renderLucideIcon(t.icon,20):null}catch(e){r(e),n=null}return n},onSelect:()=>{try{t.onSelect()}catch(e){r(e)}}}})}})??[],we=e=>{let t=Ce();for(let n of e)t.some(e=>e.id===n.id)?console.warn(`[persona] duplicate history rail section id`,n.id):t.push(n);return t.length?t:void 0},Te=null,Ee=()=>`${e.currentKeyPrefix()}rail-collapsed`,De=()=>{if(Te===null&&(Te=e.config.features?.history?.rail?.defaultCollapsed===!0,e.config.persistState!==!1))try{let e=window.localStorage.getItem(Ee());e&&(Te=e===`1`)}catch{}return Te},Oe=t=>{if(Te=t,e.config.persistState!==!1)try{window.localStorage.setItem(Ee(),t?`1`:`0`)}catch{}},ke=()=>e.historyPresentation===`rail`&&P()&&!xe()&&De(),Ae=()=>{},je=()=>{xe()?Ae():(Oe(!De()),i?.view.setCollapsed(ke()),e.applyRailChrome(),e.repinAnchoredMessage())},Me=()=>{let t=e.config.features?.history?.rail?.collapseShortcut;return!t||!So(t)?null:{combo:t,hint:To(t),aria:Eo(t)}},Ne=`var(--persona-history-overlay-margin,8px)`,Pe=null,Fe=null,Ie=0,Le=null,Re=null,ze=!1,Be=0,Ve=()=>window.matchMedia?.(`(pointer: coarse)`).matches===!0,He=()=>g()&&xe()&&(e.historyPresentation??D())===`rail`,Ue=()=>e.historyVisible&&!L,We=()=>{Re!==null&&clearTimeout(Re),Re=null},Ge=()=>{e.loadHistoryView().catch(()=>{})},Ke=()=>{We(),L&&(Re=setTimeout(()=>{Re=null,!ze&&L&&(Le?.contains(document.activeElement)||pt({restoreFocus:!1}))},300))},qe=(e,t)=>{let n=Le?.getBoundingClientRect();if(!n)return!1;let r=Pe?.getBoundingClientRect(),i=r?Math.min(r.top,n.top):n.top;return e>=n.left&&e<=n.right&&t>=i&&t<=n.bottom||!!r&&e>=r.left&&e<=r.right&&t>=r.top&&t<=r.bottom},Je=e=>{L&&(ze=qe(e.clientX,e.clientY),ze?We():Re===null&&Ke())},Ye=t=>{!e.historyVisible&&He()&&(L=!0,dt({invoker:Pe,keyboard:t?.keyboard===!0}).then(()=>{e.historyVisible?!ze&&document.activeElement!==Pe&&pt():L=!1}))},Xe=()=>{let e=ne?.querySelector(`[data-persona-history-focus="collapse"]`);e&&(e.setAttribute(`aria-label`,L?t.expandLabel:t.collapseLabel),e.setAttribute(`aria-expanded`,L?`false`:`true`))},Ze=()=>{Oe(!1);let t=i;if(!L||!t){dt({invoker:Pe});return}let n=document.activeElement===Pe;L=!1,G(),t.element.remove(),lt(t.element),Xe(),n&&q(),e.repinAnchoredMessage(),Vt()},Qe=()=>{Oe(!0),pt()};Ae=()=>{!e.historyVisible||L?Ze():Qe()};let V=()=>{let n=Me(),r=e.createHeaderIconButton({ariaLabel:t.expandLabel,iconName:`panel-left`,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`,extraClassName:`persona-rail-trigger`,tooltip:!1,attrs:{"data-persona-rail-trigger":``,"aria-controls":h,...n?{"aria-keyshortcuts":n.aria}:{}}}),i=r.button;i.addEventListener(`mouseenter`,()=>{ze=!0,We(),!(Ve()||Date.now()<Be)&&Ye()}),i.addEventListener(`mouseleave`,()=>{ze=!1,Be=0,Ke()}),i.addEventListener(`focus`,()=>{e.historyVisible||Ge()}),i.addEventListener(`click`,t=>{g()&&(t.detail!==0&&Ve()&&!e.historyVisible?Ye():Ze())}),Pe=i,Fe=r.wrapper},et=()=>{if(Fe&&!Fe.isConnected&&(Fe=null,Pe=null),!He()){Fe?.remove(),Fe=null,Pe=null;return}Pe||V();let n=Fe,r=Pe;if(!n||!r)return;let i=F()===`right`?null:e.header.firstChild;(i??e.header.lastChild)!==n&&e.header.insertBefore(n,i),n.style.display=Ue()||Ie>0?`none`:``,r.setAttribute(`aria-label`,t.expandLabel),r.setAttribute(`aria-expanded`,e.historyVisible?`true`:`false`),Le&&e.applyRailChrome()},tt=e=>{if(!L)return;let t=e.target;t instanceof Node&&(Le?.contains(t)||Fe?.contains(t)||t instanceof Element&&t.closest(`.persona-dropdown-menu,[role="alertdialog"]`)||pt({restoreFocus:!1}))};document.addEventListener(`pointerdown`,tt,!0),e.destroyCallbacks.push(()=>{document.removeEventListener(`pointerdown`,tt,!0),document.removeEventListener(`pointermove`,Je),rt?.(),We()});let nt=null,rt=null,it=t=>{I(ge(t)),e.applyRailChrome(),e.repinAnchoredMessage()},at=()=>{let t=z(`div`,`persona-rail-resizer`);return t.tabIndex=0,t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-valuemin`,`200`),t.setAttribute(`aria-valuemax`,`400`),t.addEventListener(`pointerdown`,n=>{let r=fe;if(!r||n.button!==0)return;n.preventDefault(),rt?.();let i=n.clientX,a=r.getBoundingClientRect().width||be(),o=F()===`right`?-1:1,s=a,c=e.mount.ownerDocument;r.style.transition=`none`;let l=e=>{s=ge(a+o*(e.clientX-i)),r.style.flex=`0 0 ${s}px`,t.setAttribute(`aria-valuenow`,String(s))},u=()=>{rt=null,c.removeEventListener(`pointermove`,l),c.removeEventListener(`pointerup`,u),c.removeEventListener(`pointercancel`,u),r.style.removeProperty(`transition`);try{t.releasePointerCapture(n.pointerId)}catch{}it(s)};rt=u,c.addEventListener(`pointermove`,l),c.addEventListener(`pointerup`,u),c.addEventListener(`pointercancel`,u);try{t.setPointerCapture(n.pointerId)}catch{}}),t.addEventListener(`keydown`,e=>{let t=F()===`right`?-16:16,n=be(),r=e.key===`ArrowRight`?n+t:e.key===`ArrowLeft`?n-t:e.key===`Home`?200:e.key===`End`?400:null;r!==null&&(e.preventDefault(),it(r))}),t},H=(e,n)=>{if(!_e()||ke()){rt?.(),nt?.remove();return}let r=nt??at();nt=r,r.setAttribute(`aria-label`,t.resizeLabel),r.setAttribute(`aria-valuenow`,String(be())),r.nextElementSibling!==n&&e.insertBefore(r,n)};e.applyRailChrome=()=>{i?.view.setRailSide(F());let t=F()===`right`,n=Le;if(n){let r=Pe?Pe.getBoundingClientRect().bottom-e.container.getBoundingClientRect().top:0;n.style.top=`calc(${Math.max(0,Math.round(r))}px + ${Ne})`,n.style.width=`${be()}px`,n.style.left=t?``:Ne,n.style.right=t?Ne:``}let r=fe,a=de,o=pe;if(!r||!a||!o)return;r.style.flex=`0 0 ${ke()?52:be()}px`;let s=`1px solid var(--persona-divider,#e5e7eb)`;r.style.borderRight=t?``:s,r.style.borderLeft=t?s:``;let c=t?o:r;a.firstElementChild!==c&&a.append(c,t?r:o),H(a,t?r:o)};let ot=t=>{if(me&&fe){me.replaceWith(t),me=null,e.applyRailChrome();return}let n=z(`div`,`persona-history-rail-shell`);n.style.cssText=`display:flex;flex-direction:row;flex:1 1 auto;min-height:0`;let r=z(`div`,`persona-history-rail-conversation`);r.style.cssText=`display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative`;let i=z(`div`,`persona-history-rail-host`);i.style.cssText=`display:flex;min-height:0;overflow:hidden`,e.container.insertBefore(n,e.header.parentNode===e.container?e.header:e.body);for(let t of he())t?.parentNode===e.container&&r.appendChild(t);n.append(i,r),i.appendChild(t),de=n,fe=i,pe=r,e.applyRailChrome()},st=()=>{if(de)return;let t=z(`div`,`persona-history-rail-placeholder`);t.style.cssText=`flex:1 1 auto;min-height:0`,me=t,ot(t),e.repinAnchoredMessage()},U=()=>{me&&(G(),e.repinAnchoredMessage())},W=t=>{let n=z(`div`,`persona-history-rail-overlay`);n.style.cssText=`position:absolute;bottom:${Ne};display:flex;overflow:hidden;z-index:${dn-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,e.container.style.position=`relative`,e.container.appendChild(n),n.appendChild(t),document.addEventListener(`pointermove`,Je),Le=n,e.applyRailChrome(),Xe()},G=()=>{ce?.(),Le&&=(ze&&(Be=Date.now()+150),document.removeEventListener(`pointermove`,Je),Le.remove(),null);let t=de;if(t){rt?.();for(let n of he())n&&t.contains(n)&&e.container.insertBefore(n,t);t.remove(),de=null,fe=null,pe=null,me=null}},ct=e=>{ne=e,e.id=h,e.style.flex=`1 1 auto`,e.style.minHeight=`0`},lt=t=>{ct(t),(e.historyPresentation!==`rail`||L)&&U(),e.historyPresentation===`rail`?L?W(t):ot(t):ue(t)},ut=()=>{if(et(),Rt(),!e.historyVisible||!i)return;let t=D();if(t===e.historyPresentation)return;let n=document.activeElement,r=n instanceof HTMLElement&&(i.element.contains(n)||k?.contains(n)===!0)?n:null;G(),i.element.remove(),i.view.setHeaderPlacement(`inline`),e.historyPresentation=t,i.view.setPresentation(t),i.view.setCollapsed(ke()),i.requestRender(),i.element.isConnected||lt(i.element),r?.isConnected?r.focus():q(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),Vt()},K=(e,t)=>k?.querySelector(t)??e.querySelector(t),q=()=>{let e=i?.element??ne;if(!e)return;let t=K(e,`[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]`);if(t){t.focus();return}let n=K(e,`.persona-history-title`)??e;n.tabIndex=-1,n.focus()},dt=async r=>{if(!g()||e.historyVisible)return;let l=n;if(!l)return;if(!L&&He()&&De()){et();return}ft();let u=++d;o=r?.returnSurface??`conversation`,s=r?.invoker??c;let f=He()&&!L;f&&(Ie+=1,et(),st());let p;try{p=await e.loadHistoryView()}catch{e.announceHistory(t.openHistoryLabel),f&&(--Ie,u===d&&(U(),et()));return}if(f&&--Ie,u!==d||e.historyVisible)return;a={scope:v()},e.historyPresentation=D(),e.historyVisible=!0;let m=e.historyPresentation===`panel`&&e.config.layout?.showHeader!==!1&&e.header.style.display!==`none`?`external`:`inline`,h=e.config.features?.history?.rowAvatar,_=Me(),y=_?{hint:_.hint,aria:_.aria}:null,x={provider:l,context:a,targetId:b(),presentation:e.historyPresentation,collapsible:P(),collapsed:ke(),railSide:F(),renderRailHeader:e.config.features?.history?.rail?.renderHeader,railBrand:Se(),onToggleCollapse:je,...y?{collapseShortcut:y}:{},headerPlacement:m,showScopeStatus:e.config.features?.history?.showScopeStatus!==!1,showDelete:e.config.features?.history?.showDelete!==!1,showDeleteAll:e.config.features?.history?.showDeleteAll!==!1,...e.config.features?.history?.listActions?.length?{listActions:e.config.features.history.listActions}:{},rowAvatar:h===!1?!1:typeof h==`string`?h:e.config.launcher?.iconUrl,activeConversationId:e.session.getActiveConversationId(),...e.config.features?.history?.grouping?{grouping:e.config.features.history.grouping}:{},...e.config.features?.history?.copy?{copy:e.config.features.history.copy}:{},...e.config.features?.history?.pageSize===void 0?{}:{pageSize:e.config.features.history.pageSize},onSelect:e=>Tt(e,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:t=>e.setActiveConversationSummary(t),attachTooltip:e.attachTooltip,onStartNew:()=>Et({focusComposer:!0}),onClose:()=>pt(),onRequestDeleteConversation:e=>Mt(e),onRequestClearHistory:()=>Nt(),...l.resetDevice?{onRequestResetIdentity:()=>Pt()}:{}};i=fo({plugins:e.plugins,config:e.config,getPresentation:()=>e.historyPresentation??`panel`,getReturnSurface:()=>o,close:()=>pt(),createView:({slots:t,renderDom:n,onModelChange:r,railSections:i})=>(te=p.createHistoryView({...x,railSections:we(i),slots:t,renderDom:n,onModelChange:r,onAnnounce:e.announceHistory}),te),onElementChanged:(e,t)=>{if(!t?.isConnected)return lt(e);ct(e),t.replaceWith(e),le()}}),i.view.setNewConversationRequired(e.historySessionState.recovery===`new_conversation_required`),r?.focus!==!1&&(e.historyPresentation!==`rail`||r?.keyboard===!0)&&q(),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),Vt(),e.eventBus.emit(`history:opened`,{presentation:e.historyPresentation,returnSurface:o,timestamp:Date.now()})},ft=()=>{},pt=t=>{if(!e.historyVisible)return;d+=1;let n=o,r=s,l=i,u=t?.restoreFocus!==!1;e.historyVisible=!1;let f=!1,p=null,m=()=>{if(!f){if(f=!0,ft=()=>{},p!==null&&clearTimeout(p),L=!1,We(),G(),l?.dispose(),l?.view.destroy(),l?.element.remove(),i===l&&(i=null,te=null,ne=null,e.historyPresentation=null,a=null,s=null),e.syncScrollToBottomButton(),e.repinAnchoredMessage(),Vt(),u){let t=r??c;t?.isConnected?t.focus():e.maybeFocusInput()}e.eventBus.emit(`history:closed`,{returnSurface:n,timestamp:Date.now()})}},h=l&&l.element===l.view.element?l.view.playExit():null;h?(ft=m,p=setTimeout(m,250),h.then(m)):m()},mt=t=>{if(t.key===`Escape`&&e.historyVisible&&i){if(e.historyPresentation===`rail`){let e=t.target;if(!(e instanceof Node)||!(i.element.contains(e)||L&&Fe?.contains(e)===!0))return}t.preventDefault(),t.stopPropagation(),pt()}};e.container.addEventListener(`keydown`,mt),e.destroyCallbacks.push(()=>e.container.removeEventListener(`keydown`,mt));let ht=0,gt=null,_t=()=>{gt&&clearTimeout(gt),gt=null};e.destroyCallbacks.push(_t);let vt=()=>{_t();let t=e.conversationOpenPendingEl;t&&(e.conversationOpenTakeover=!0,t.hidden=!1,e.messagesWrapper.style.display=`none`,e.updateWelcome())},yt=()=>{ht+=1,_t(),e.conversationOpenPendingEl&&(e.conversationOpenPendingEl.remove(),e.conversationOpenPendingEl=null,e.conversationOpenTakeover=!1,e.messagesWrapper.style.removeProperty(`display`),O(e.footer,!1),e.updateWelcome())},bt=()=>{try{if(window.matchMedia?.(`(prefers-reduced-motion: reduce)`)?.matches)return;e.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:`ease-out`})}catch{}},J=(e,t)=>B(`div`,{className:$e(`persona-conversation-loading-bubble`,t&&`persona-conversation-loading-bubble--trailing`),attrs:{"aria-hidden":`true`},style:{width:e}}),xt=()=>B(`div`,{className:`persona-conversation-loading-body`},J(`58%`,!1),J(`72%`,!0),J(`44%`,!1)),St=t=>{e.conversationOpenPendingEl?.remove(),e.conversationOpenPendingEl=t,t.hidden=!e.conversationOpenTakeover,e.body.insertBefore(t,e.messagesWrapper),_t(),e.conversationOpenTakeover||(gt=setTimeout(vt,250)),O(e.footer,!0)},Ct=()=>{let n={config:e.config,streaming:!1,location:`conversation-open`,defaultRenderer:xt},r=null,i=e.plugins.find(e=>e.renderLoadingIndicator);i?.renderLoadingIndicator&&(r=i.renderLoadingIndicator(n)),r===null&&e.config.loadingIndicator?.render&&(r=e.config.loadingIndicator.render(n)),St(B(`div`,{className:`persona-conversation-loading`,attrs:{role:`status`,"aria-label":t.openConversationLoadingLabel}},r??xt()))},wt=n=>{let r=()=>{Tt(n,{focusComposer:!0}).catch(()=>{})},i=g()?()=>{yt(),dt()}:void 0,a=(e,t)=>{let n=B(`button`,{className:`persona-conversation-loading-error-action`,attrs:{type:`button`},text:e});return n.addEventListener(`click`,t),n},o=()=>B(`div`,{className:`persona-conversation-loading-error-body`},B(`p`,{className:`persona-conversation-loading-error-title`,text:t.openConversationErrorTitle}),B(`div`,{className:`persona-conversation-loading-error-actions`},a(t.openConversationRetryLabel,r),i?a(t.openConversationBackLabel,i):null)),s=Object.freeze({conversationId:n,config:e.config,copy:Object.freeze({title:t.openConversationErrorTitle,retryLabel:t.openConversationRetryLabel,backLabel:t.openConversationBackLabel}),retry:r,...i?{back:i}:{},defaultRenderer:o}),c=null;for(let t of e.plugins)if(t.renderHistoryOpenError){try{c=t.renderHistoryOpenError(s)}catch(e){console.warn(`[persona] renderHistoryOpenError threw`,e),c=null}if(c)break}St(B(`div`,{className:`persona-conversation-loading-error`,attrs:{role:`alert`}},c??o())),vt()};e.eventBus.on(`history:closed`,()=>{e.conversationOpenPendingEl&&O(e.footer,!0)});let Tt=async(t,{focusComposer:n=!1}={})=>{let r=y(),a=!!i;i?.view.setActiveConversationId(t),yt();let o=ht;Ct(),e.historyVisible&&(e.historyPresentation===`panel`||L)&&pt({restoreFocus:!1}),e.suppressScrollSend=!0;try{await e.session.openConversation(t,{scope:r})}catch(e){throw o===ht&&wt(t),e}finally{e.suppressScrollSend=!1}o===ht&&(yt(),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.restoreScrollPosition()||e.jumpToBottomInstant(),bt(),It(),a||e.setActiveConversationSummary(null),e.eventBus.emit(`history:conversationOpened`,{conversationId:t,title:e.activeConversationTitle,scope:r,timestamp:Date.now()}),n&&e.maybeFocusInput())},Et=async({focusComposer:t=!1}={})=>{yt(),await e.session.startNewConversation({scope:y()}),e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),e.jumpToBottomInstant(),It();let n=e.session.getActiveConversationId();i?.view.setActiveConversationId(n),e.eventBus.emit(`history:conversationStarted`,{conversationId:n,timestamp:Date.now()}),e.historyVisible&&(e.historyPresentation===`panel`||L)&&pt({restoreFocus:!1}),t&&e.maybeFocusInput()},Dt=async(t,n)=>{let r=await e.session.updateConversation(t,{...n,...n.title===void 0?{}:{title:n.title.trim()}});return i?.view.applyConversationSummary(r),!i&&t===e.session.getActiveConversationId()&&e.setActiveConversationSummary(r),r},Ot=async t=>{let n=y(),r=e.session.getActiveConversationId()===t;await e.session.deleteConversation(t,{scope:n}),i?.view.removeConversationSummary(t),r&&(e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),It()),e.eventBus.emit(`history:conversationDeleted`,{conversationId:t,scope:n,wasActive:r,timestamp:Date.now()})},kt=async t=>{let n=t?.scope??y(),r=t?.allTargets?null:t?.targetId??b(),i=await e.session.clearConversationHistory({...r?{targetId:r}:{},scope:n});return e.setActiveConversationSummary(null),e.messageCache.clear(),e.resetAnchorState(),e.resumeAutoScroll(),It(),e.eventBus.emit(`history:cleared`,{deleted:i.deleted,scope:n,targetId:r,timestamp:Date.now()}),i},At=async()=>{if(!n?.resetDevice)throw Error(`[Persona] resetHistoryIdentity() requires a history provider that can reset this device`);let r=!1;try{r=(await e.session.resetHistoryDevice()).remoteRevocationConfirmed}finally{e.setActiveConversationSummary(null),e.session.clearArtifacts(),e.messageCache.clear(),e.lastAppliedMessages=null,e.config.clearStoredSessionId?.(),e.config.clearStoredConversationId?.(),e.persistentMetadata={},e.actionManager.syncFromMetadata();let t=e.storageAdapter;t?.clear&&e.runStorageMutation(()=>t.clear(),`[AgentWidget] Failed to clear storage adapter:`),e.resetAnchorState(),e.resumeAutoScroll(),It(),pt({restoreFocus:!1}),e.maybeFocusInput(),e.open||e.launcherSurfaceInstance?.launcher.element.focus()}return e.announceHistory(r?t.identityResetNotice:t.identityResetUnconfirmedNotice),e.eventBus.emit(`history:identityReset`,{remoteRevocationConfirmed:r,timestamp:Date.now()}),{remoteRevocationConfirmed:r}},Y=()=>e.artifactSplitRoot?e.panel:e.container,jt=async t=>{let n=await e.loadHistoryView().catch(()=>null);return typeof n?.showHistoryConfirm==`function`?n.showHistoryConfirm(t):window.confirm(`${t.title}\n\n${t.description}`)},Mt=async e=>await jt({host:Y(),title:t.deleteConversationConfirmTitle,description:t.deleteConversationConfirm,confirmLabel:t.deleteConversationConfirmLabel,cancelLabel:t.confirmCancelLabel})?(await Ot(e),`deleted`):`cancelled`,Nt=async()=>{let e=y()===`verified-user`;return await jt({host:Y(),title:t.clearHistoryConfirmTitle,description:e?t.clearHistoryVerifiedConfirm:t.clearHistoryConfirm,confirmLabel:t.clearHistoryConfirmLabel,cancelLabel:t.confirmCancelLabel})?(await kt(),`cleared`):`cancelled`},Pt=async()=>{if(!await jt({host:Y(),title:t.resetIdentityConfirmTitle,description:t.resetIdentityConfirm,confirmLabel:t.resetIdentityConfirmLabel,cancelLabel:t.confirmCancelLabel}))return{outcome:`cancelled`};let{remoteRevocationConfirmed:e}=await At();return{outcome:`reset`,remoteRevocationConfirmed:e}},Ft=z(`button`,`persona-history-earlier`);Ft.type=`button`,Ft.textContent=t.showEarlierMessagesLabel,Ft.setAttribute(`data-persona-history-earlier`,``),Object.assign(Ft.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 It=()=>{g()&&e.historySessionState.nextMessageCursor&&e.session.getActiveConversationId()?(Ft.textContent=t.showEarlierMessagesLabel,Ft.parentNode!==e.body&&e.body.insertBefore(Ft,e.body.firstChild)):Ft.remove()};Ft.addEventListener(`click`,()=>{let t=e.session.getActiveConversationId(),n=e.historySessionState.nextMessageCursor;if(!t||!n||Ft.disabled)return;Ft.disabled=!0;let r=e.body.scrollHeight,i=e.body.scrollTop;e.session.loadOlderMessages(t,n,{scope:y()}).then(()=>{e.body.scrollTop=i+(e.body.scrollHeight-r),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Ft.disabled=!1,It()})});let Lt=()=>{let n=e.createHeaderIconButton({ariaLabel:t.openHistoryLabel,iconName:`history`,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`,extraClassName:`persona-history-toggle`,attrs:{"data-persona-history-toggle":``}});return n.button.addEventListener(`click`,t=>{g()&&!_()&&(e.historyVisible?pt():dt({invoker:n.button,keyboard:t.detail===0}))}),n},Rt=()=>{if(!g()){l?.remove(),c=null,l=null;return}if(l&&!l.isConnected&&(c=null,l=null),!c&&e.header){let t=Lt();c=t.button,l=t.wrapper;let n=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;n?.parentNode&&e.header.contains(n)?n.parentNode.insertBefore(l,n):e.header.appendChild(l)}if(!c||!l)return;let n=He()||e.historyVisible&&e.historyPresentation===`rail`;if(l.style.display=n?`none`:``,n){document.activeElement===c&&q();return}let r=_();c.disabled=r,c.setAttribute(`aria-disabled`,r?`true`:`false`);let i=r?t.openHistoryBusyLabel:t.openHistoryLabel;c.setAttribute(`aria-label`,i),(e.config.features?.history?.presentation??`panel`)===`panel`?(c.removeAttribute(`aria-expanded`),c.removeAttribute(`aria-controls`)):(c.setAttribute(`aria-expanded`,e.historyVisible?`true`:`false`),c.setAttribute(`aria-controls`,h))},zt=!1,Bt=()=>{let n=e.panelElements.clearChatButton;n&&(g()?(zt||=(f=n.getAttribute(`aria-label`)??``,!0),n.setAttribute(`aria-label`,t.newConversationLabel),n.removeAttribute(`title`)):zt&&(zt=!1,f&&n.setAttribute(`aria-label`,f)))},Vt=()=>{t=so(e.config.features?.history?.copy),Rt(),et(),Bt(),It()};return e.historyChromeSync=Vt,E(),Vt(),e.destroyCallbacks.push(()=>{p?.(),m?.(),d+=1,ft(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:g,historyScope:v,installHistoryProvider:E,syncHistoryChromeImpl:Vt,syncHistoryPresentation:ut,syncEarlierMessagesPill:It,openHistory:dt,closeHistory:pt,openHistoryConversation:Tt,startNewConversation:Et,updateHistoryConversation:Dt,deleteHistoryConversation:Ot,requestDeleteConversation:Mt,clearConversationHistory:kt,resetHistoryIdentity:At,railCollapseShortcut:Me,railCollapsible:P,railTriggerApplies:He,railOverlayMode:xe,toggleRailCollapsed:je,toggleRailPinned:()=>Ae(),get historyProvider(){return n},get historySurface(){return i},get railShell(){return de},get railHost(){return fe},get railColumn(){return pe}}}}));Yo(),g();const{setLoader:Xo,load:Zo,provide:Qo,getSync:$o}=h({fallbackImport:()=>Promise.resolve().then(()=>(Yo(),qo))}),es=Zo,ts=Qo,ns=$o;ts(qo),we();function rs(e){return e.toolType===`webmcp`&&!e.executionId}function is(e){let t=e.approval,n=t?.status===`pending`&&rs(t),r=!1,i=t=>!t.name||!Se(t.name)||(r=!0,!(t.status!==`complete`||e.agentMetadata?.awaitingLocalTool===!0&&t.result===void 0&&t.success===void 0))?t:{...t,status:`complete`,interrupted:!0,success:!1,error:`The chat restarted and this browser tool was interrupted. Request a fresh proposal to try again.`,approvalStatus:t.approvalStatus===`pending`?`timeout`:t.approvalStatus,startedAt:t.completedAt===void 0?void 0:t.startedAt},a=e.toolCall?i(e.toolCall):void 0,o=e.tools?.map(i);return{...e,streaming:r||n?!1:e.streaming,...n?{approval:{...t,status:`timeout`,interrupted:!0}}:{},...a?{toolCall:a}:{},...o?{tools:o}:{},...r&&e.agentMetadata?.awaitingLocalTool?{agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1}}:{}}}V(),A();const as=[`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`],os=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),ss=(e,t)=>{let n=z(`div`,[`persona-message-bubble`,e,...as].join(` `));return n.id=`bubble-${t}`,n.setAttribute(`data-message-id`,t),n},cs=e=>{let t=z(`button`,e.expandable?`persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none`:`persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none`);return t.type=`button`,e.expandable&&(t.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),t.setAttribute(`data-expand-header`,`true`)),t.setAttribute(`data-bubble-type`,e.bubbleType),t},ls=(e,t,n)=>{e.innerHTML=``;let r=k(t?f.ChevronUp:f.ChevronDown,16,n,2);r?e.appendChild(r):e.textContent=t?`Hide`:`Show`},us=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let r=z(`div`,`persona-flex persona-items-center`);ls(r,n.expanded,n.iconColor);let i=z(`div`,n.metaGap?`persona-flex persona-items-center persona-gap-2 persona-ml-auto`:`persona-flex persona-items-center persona-ml-auto`);return i.append(r),e.append(t,i),r},ds=e=>{let t=z(`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?.();os(t,n)||(t.textContent=e.previewText),t.style.display=``}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},fs=e=>{e.header.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),e.toggleIcon&&ls(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`},ps=(e,t,n)=>{let r=n.stateSet.has(e),i=t.querySelector(`button[data-expand-header="true"]`),a=t.querySelector(`.persona-border-t`),o=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!i||!a)return;i.setAttribute(`aria-expanded`,r?`true`:`false`);let s=i.querySelector(`.persona-ml-auto`)?.querySelector(`:scope > .persona-flex.persona-items-center`);s&&ls(s,r,n.iconColor),a.style.display=r?``:`none`,o&&(o.style.display=r?`none`:o.textContent||o.childNodes.length?``:`none`)};A(),Ti(),V(),F();function ms(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return{...e,features:{...e?.features,[n]:{...t===`tool`?vi:yi,...e?.future?.v5Defaults===!0?Ci.features?.[n]:{},...e?.features?.[n]}}}}function hs(e,t){let n=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return e?.features?.[n]?.variant??(e?.future?.v5Defaults?`row`:`card`)}function gs(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 _s(e,t,n,r){if(hs(n,r)!==`row`)return e;e.className=`persona-message-bubble persona-${r}-bubble persona-activity-row`,e.dataset.activityKind=r,r===`tool`&&n.toolCall?.shadow===void 0&&(e.style.boxShadow=`var(--persona-tool-bubble-shadow, none)`);let i=e.querySelector(`:scope > button`);if(!i)return e;i.className=`persona-activity-header`;let a=r===`tool`?t.toolCall:t.reasoning,o=a?.status!==`complete`,s=t.approval?.status??t.toolCall?.approvalStatus,c=t.toolCall?.interrupted?`interrupted`:s===`denied`?`denied`:s===`pending`?`awaiting-approval`:t.toolCall?.success===!1?`error`:o?a?.status===`pending`?`pending`:`running`:`done`;e.dataset.activityState=c;let l=z(`span`,`persona-activity-icon`);l.dataset.activityIcon=c;let u={pending:`circle`,running:`loader-circle`,done:`check`,error:`x`,denied:`x`,interrupted:`x`,"awaiting-approval":`clock`},d=r===`reasoning`?n.features?.reasoningDisplay?.iconName:void 0,p=d?P(d,16,`currentColor`,2):c===`pending`?k(f.Circle,16,`currentColor`,2):c===`awaiting-approval`?k(f.Clock,16,`currentColor`,2):P(u[c],16,`currentColor`,2);p&&l.appendChild(p),i.querySelector(`.persona-reasoning-header-icon`)?.remove();let m=r===`tool`?`toolCallDisplay`:`reasoningDisplay`,h=n.features?.[m]?.iconVisibility??(n.future?.v5Defaults?`active`:`always`);if((h===`always`||h===`active`&&c!==`done`)&&i.prepend(l),r===`tool`&&a){let e=z(`span`,`persona-activity-duration`);o&&a.startedAt&&e.setAttribute(`data-tool-elapsed`,String(a.startedAt));let n=(r===`tool`?t.toolCall?.duration:void 0)??a.durationMs??(a.completedAt!==void 0&&a.startedAt!==void 0?a.completedAt-a.startedAt:void 0);e.textContent=n===void 0?``:gs(n),i.appendChild(e)}i.querySelector(`:scope > div:not(.persona-ml-auto)`)?.classList.add(`persona-activity-label`),i.querySelector(`.persona-ml-auto`)?.classList.add(`persona-activity-chevron`);let g=e.querySelector(`:scope > .persona-border-t`);return g?.classList.add(`persona-activity-body`),g&&(g.id=`activity-details-${t.id}`,i.setAttribute(`aria-controls`,g.id)),e}function vs(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map,a=e=>{clearTimeout(i.get(e)),i.delete(e)};return{observe(a,o,s,c={}){let l=o===`tool`?a.toolCall:a.reasoning;if(l&&!n.has(a.id)&&(!t.has(a.id)&&l.status!==`complete`&&l.chunks?.some(Boolean)&&(t.add(a.id),c.autoExpand!==!1&&s.add(a.id)),t.has(a.id)&&l.status===`complete`&&!r.has(a.id))){if(r.add(a.id),c.autoCollapseDelay===!1)return;i.set(a.id,setTimeout(()=>{i.delete(a.id),s.delete(a.id),e(a.id,o)},c.autoCollapseDelay??1e3))}},manual(e){n.add(e),a(e)},prune(e){for(let i of/* @__PURE__ */ new Set([...t,...n,...r]))e.has(i)||(a(i),t.delete(i),n.delete(i),r.delete(i))},clear(){for(let e of i.keys())a(e);t.clear(),n.clear(),r.clear()}}}function ys(e,t,n,r){let i=z(`div`,``);i.id=`bubble-${e.id}`,i.dataset.messageId=e.id;let a=z(`button`,``);a.type=`button`,a.dataset.expandHeader=`true`,a.dataset.bubbleType=`tool`,a.setAttribute(`aria-expanded`,String(n));let o=z(`div`,``);typeof r==`string`?o.textContent=r:o.appendChild(r),us(a,o,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||`currentColor`,metaGap:!0});let s=z(`div`,`persona-border-t`);return s.id=`activity-details-${e.id}`,s.style.display=n?``:`none`,a.setAttribute(`aria-controls`,s.id),i.append(a,s),_s(i,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:`row`}}},`tool`),i.dataset.personaToolGroup=`true`,t.features?.toolCallDisplay?.loadingAnimation===`shimmer`&&(i.dataset.activityGroupShimmer=`true`),{bubble:i,body:s}}function bs(e,t){let n=e.voiceRecognition,r=t.voiceRecognition;return n?.enabled===!0!=(r?.enabled===!0)||n?.provider?.type!==r?.provider?.type||n?.provider?.custom!==r?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==r?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(r?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function xs(e){return e?.type===`runtype`||e?.type===`custom`}const Ss=()=>typeof window<`u`&&(`SpeechRecognition`in window||`webkitSpeechRecognition`in window);function Cs(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:Ss()}catch{return!1}}const ws=e=>{if(!e)return;let t={},n=e;if(n.heading){let e=n.heading;t.heading=(t,n,r)=>e({type:`heading`,raw:r,depth:n,text:t,tokens:[]})}if(n.code){let e=n.code;t.code=(t,n,r)=>e({type:`code`,raw:``,text:t,lang:n,escaped:r})}if(n.blockquote){let e=n.blockquote;t.blockquote=t=>e({type:`blockquote`,raw:``,text:t,tokens:[]})}if(n.table){let e=n.table;t.table=(t,n)=>e({type:`table`,raw:``,header:[],rows:[],align:[],headerHtml:t,bodyHtml:n})}if(n.link){let e=n.link;t.link=(t,n,r)=>e({type:`link`,raw:``,href:t,title:n??null,text:r,tokens:[]})}if(n.image){let e=n.image;t.image=(t,n,r)=>e({type:`image`,raw:``,href:t,title:n??null,text:r})}if(n.list){let e=n.list;t.list=(t,n,r)=>e({type:`list`,raw:``,ordered:n,start:r,loose:!1,items:[],itemsHtml:t})}if(n.listitem){let e=n.listitem;t.listitem=(t,n,r)=>e({type:`list_item`,raw:``,task:n,checked:r,loose:!1,text:t,tokens:[]})}if(n.paragraph){let e=n.paragraph;t.paragraph=t=>e({type:`paragraph`,raw:``,text:t,tokens:[]})}if(n.codespan){let e=n.codespan;t.codespan=t=>e({type:`codespan`,raw:``,text:t})}if(n.strong){let e=n.strong;t.strong=t=>e({type:`strong`,raw:``,text:t,tokens:[]})}if(n.em){let e=n.em;t.em=t=>e({type:`em`,raw:``,text:t,tokens:[]})}if(n.del){let e=n.del;t.del=t=>e({type:`del`,raw:``,text:t,tokens:[]})}if(n.html){let e=n.html;t.html=t=>e({type:`html`,raw:t,text:t})}if(n.text){let e=n.text;t.text=t=>e({type:`text`,raw:t,text:t})}if(n.checkbox){let e=n.checkbox;t.checkbox=t=>e({checked:t})}return n.hr&&(t.hr=n.hr),n.br&&(t.br=n.br),t},Ts=e=>{let t=null;return n=>{let r=O();if(!r)return ks(n);if(!t){let{Marked:n}=r,i=e?.markedOptions;t=new n({gfm:i?.gfm??!0,breaks:i?.breaks??!0,pedantic:i?.pedantic,silent:i?.silent});let a=ws(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},Es=e=>e?Ts({markedOptions:e.options,renderer:e.renderer}):Ts(),Ds=Ts(),Os=e=>Ds(e),ks=e=>e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`),As=e=>e.replace(/"/g,`&quot;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`),js=e=>`%%FORM_PLACEHOLDER_${e}%%`,Ms=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,n)=>{try{let e=JSON.parse(n.trim());if(e&&typeof e==`object`&&e.component===`form`&&e.type){let n=js(t.length);return t.push({token:n,type:String(e.type)}),n}}catch{return e}return e}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,n)=>{let r=js(t.length);return t.push({token:r,type:n}),r}),n},Ns=e=>{let t=Es(e);return e=>{let n=[],r=Ms(e,n),i=t(r);return n.forEach(({token:e,type:t})=>{let n=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`g`),r=`<div class="persona-form-directive" data-tv-form="${As(t)}"></div>`;i=i.replace(n,r)}),i}},Ps=e=>{let t=[],n=Ms(e,t),r=Os(n);return t.forEach(({token:e,type:t})=>{let n=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),`g`),i=`<div class="persona-form-directive" data-tv-form="${As(t)}"></div>`;r=r.replace(n,i)}),r},Fs={ALLOWED_TAGS:/* @__PURE__ */ `h1.h2.h3.h4.h5.h6.p.br.hr.div.span.ul.ol.li.dl.dt.dd.strong.em.b.i.u.s.del.ins.mark.small.sub.sup.abbr.kbd.var.samp.code.a.img.blockquote.pre.details.summary.table.thead.tbody.tfoot.tr.th.td.caption.colgroup.col.input.label.select.option.textarea.button`.split(`.`),ALLOWED_ATTR:/* @__PURE__ */ `href.src.alt.title.target.rel.loading.width.height.colspan.rowspan.scope.class.id.type.name.value.placeholder.disabled.checked.for.aria-label.aria-hidden.aria-expanded.role.tabindex.data-tv-form.data-message-id.data-persona-component-directive.data-preserve-animation.data-persona-instance`.split(`.`)},Is=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ls=()=>{let e=null;return t=>{let n=O();if(!n)return ks(t);if(!e){let{DOMPurify:t}=n;e=t(typeof window<`u`?window:void 0),e.addHook(`uponSanitizeAttribute`,(e,t)=>{if(t.attrName===`src`||t.attrName===`href`){let e=t.attrValue;e.toLowerCase().startsWith(`data:`)&&!Is.test(e)&&(t.attrValue=``,t.keepAttr=!1)}})}return e.sanitize(t,Fs)}},Rs=e=>e===!1?null:typeof e==`function`?e:Ls(),zs=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Bs=e=>e.includes(`|`),Vs=e=>{let t=e.trim();return t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&(t=t.slice(0,-1)),t.split(`|`).map(e=>e.trim())},Hs=e=>`| ${e.join(` | `)} |`,Us=e=>`| ${Array.from({length:e},()=>`---`).join(` | `)} |`,Ws=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>``)),Gs=e=>{if(!e||!e.includes(`|`))return e;let t=e.split(`
12
+ `),n=!1;for(let e=0;e<t.length-1;e++){let r=t[e],i=t[e+1];if(!Bs(r)||zs.test(r)||!zs.test(i))continue;let a=Vs(r).length;if(a<1)continue;let o=Us(a);t[e+1]!==o&&(t[e+1]=o,n=!0);let s=e+2;for(;s<t.length;s++){let e=t[s];if(e.trim()===``||!Bs(e))break;let r=Hs(Ws(Vs(e),a));t[s]!==r&&(t[s]=r,n=!0)}e=s-1}return n?t.join(`
13
+ `):e},Ks=`var(--persona-md-table-scroll-fade, 24px)`,qs=/* @__PURE__ */ new WeakSet;function Js(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(`persona-table-scroll`))return;let t=document.createElement(`div`);t.className=`persona-table-scroll`,e.replaceWith(t),t.appendChild(e)})}function Ys(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute(`data-persona-scroll-x`);return}e.setAttribute(`data-persona-scroll-x`,``);let n=getComputedStyle(e).direction===`rtl`?t+e.scrollLeft:e.scrollLeft,r=t-n;e.style.setProperty(`--persona-fade-l`,n<=1?`0px`:Ks),e.style.setProperty(`--persona-fade-r`,r<=1?`0px`:Ks)}function Xs(e){qs.has(e)||(qs.add(e),e.addEventListener(`scroll`,e=>{let t=e.target;t?.classList?.contains(`persona-table-scroll`)&&Ys(t)},!0)),e.querySelectorAll(`.persona-table-scroll`).forEach(Ys)}g();const{setLoader:Zs,load:Qs}=h({fallbackImport:()=>import(`@runtypelabs/persona/webmcp-runtime`)}),$s=Qs;g();const{setLoader:ec,load:tc}=h({fallbackImport:()=>import(`@runtypelabs/persona/voice-client-tools`)}),nc=tc;function rc(e){return e.startsWith(`agent_`)?{kind:`agentId`,agentId:e}:e.startsWith(`flow_`)?{kind:`flowId`,flowId:e}:null}function ic(e,t){let n=e.trim();if(!n)throw Error("[Persona] `target` is empty.");let r=n.indexOf(`:`);if(r>0){let e=n.slice(0,r),i=n.slice(r+1);if(e===`runtype`){let e=rc(i);if(e)return e;throw Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let a=t?.[e];if(!a)throw Error(`[Persona] No target provider registered for "${e}". Add a \`targetProviders.${e}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:`payload`,payload:a(i).payload}}let i=rc(n);if(i)return i;let a=t?.default;if(a)return{kind:`payload`,payload:a(n).payload};throw Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}const ac=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),oc=e=>typeof e==`object`&&!!e&&!Array.isArray(e),sc=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=ac(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:oc(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},cc=(e,t)=>{let n=[],r=[],i=[],a=``,o,s=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let c of e){let e=sc(c);if(e){let t=c.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==o)&&s(),r.length===0&&(a=c.createdAt,o=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let l=t(c);l&&(s(),n.push(l))}return s(),n},lc=e=>e.localOnly===!0||e.role===`assistant`&&typeof e.id==`string`&&e.id.startsWith(`reconnect-failed-`);we(),Va(),cn(),Qe(),jn(),Bo(),fn();var uc=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryClientError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};const dc=e=>`reason`in e?e.reason:void 0,fc=(e,t)=>e instanceof uc&&e.code===t,pc=e=>e.voiceCaption||lc(e)?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),mc=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),hc=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function gc(e){switch(e){case`json`:return Ye;case`regex-json`:return Je;case`xml`:return Ze;default:return qe}}var _c=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;constructor(e={},t={}){if(this.config=e,this.historyInternals=t,this.#l=null,this.clientSession=null,this.#u=null,this.#d=!1,this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null,this.#p=!1,this.#m=!1,this.#h=!1,this.#g=null,this.#_=/* @__PURE__ */ new Set,this.#v=/* @__PURE__ */ new Set,this.webMcpBridge=null,this.#y=null,this.#H=null,this.#W=null,e.target&&(e.agentId||e.flowId||e.agent))throw Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??`https://api.runtype.com/v1/dispatch`,this.#t={"Content-Type":`application/json`,"X-Persona-Version":An,...e.headers},this.debug=!!e.debug,this.#n=e.streamParser??gc(e.parserType),this.#r=e.contextProviders??[],this.#i=e.requestMiddleware,this.#a=e.customFetch,this.#o=e.parseSSEEvent,this.#s=e.getHeaders,e.webmcp?.enabled===!0&&(this.#y=this.#x(e.webmcp))}#x(e){return $s().then(t=>{let n=new t.WebMcpBridge(e,{recordToolDisplayTitles:I,getToolDisplayTitle:xe,loadPolyfill:Ce});return this.#b!==void 0&&n.setConfirmHandler(this.#b),this.webMcpBridge=n,n}).catch(e=>(this.#y=null,console.warn(`[Persona] Failed to load the WebMCP runtime chunk`,e),null))}#S(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled===!0?(this.#y||=this.#x(this.config.webmcp),this.#y):Promise.resolve(null)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#c=e}setWebMcpConfirmHandler(e){this.#b=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}getVoiceClientTools(){if(this.config.webmcp?.enabled!==!0)return null;let e=()=>this.#S(),t={open:async e=>(await nc()).createVoiceClientToolsSession(t,e),snapshot:async()=>{let t=await(await e())?.snapshotForDispatch()??[];return{tools:t,fingerprint:ge(t)}},onChange:t=>{let n=null,r=!1;return e().then(e=>{e&&!r&&(n=e.watchToolChanges(t))}),()=>{r=!0,n?.()}},execute:async(t,n,r)=>{let i=await e();return i?i.executeVoiceToolCall(t,n,r):{status:`failed`,error:{message:`WebMCP runtime failed to load.`}}}};return t}executeWebMcpToolCall(e,t,n){return this.config.webmcp?.enabled===!0?this.#S().then(r=>r?r.executeToolCall(e,t,n):{isError:!0,content:[{type:`text`,text:`WebMCP runtime failed to load.`}]}):null}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#C(){let{agentId:e,flowId:t,target:n,targetProviders:r}=this.config;if(!n)return{agentId:e,flowId:t};let i=ic(n,r);return i.kind===`agentId`?{agentId:i.agentId}:i.kind===`flowId`?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.#C().agentId)}#w(){return this.config.apiUrl?.replace(/\/+$/,``).replace(/\/v1\/dispatch$/,``)||`https://api.runtype.com`}#T(e){return`${this.#w()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let t=await this.initSession(),n=!1;for(;;){let r=t.conversationId,i=await this.readVisitorToken();if(t.durableRecovery?.enabled!==!0||!r||!i)throw new uc(`visitor_token_missing`,`Durable recovery is not enabled for this client session`);let a=`${this.#w()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(e.executionId)}/events`,o=new URLSearchParams({sessionId:t.sessionId,after:e.after}),s=await fetch(`${a}?${o}`,{method:`GET`,headers:{"X-Persona-Version":An,"X-Visitor-Token":i},signal:e.signal});if(s.status===401&&!n){n=!0;let e=await or();t=await e.recoverFromUnauthorized(this.#G(),await e.readErrorCode(this.#G(),s),null,!0)}else{if(!s.ok)throw await(await or()).historyErrorFor(this.#G(),s,!0);return s}}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#u||e&&/* @__PURE__ */ new Date<e.expiresAt||this.#d===e?null:(this.#d=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw Error(`initSession() only available in client token mode`);if(this.clientSession&&/* @__PURE__ */ new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#u)return this.#u;let e=this.#u=this.#N().then(t=>this.#u===e?(this.clientSession=t,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t):this.initSession()).finally(()=>{this.#u===e&&(this.#u=null)});return e}#E(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#p}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#D(){if(!this.#p){this.#j({state:`unavailable`,reason:`history_disabled`}),this.#p=!0,!this.#m&&typeof console<`u`&&(this.#m=!0,console.warn(`[Persona] Visitor history is disabled for this surface; continuing without it.`)),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#v])e(!1)}}getHistoryIdentityStatus(){return this.#g??this.#O()}subscribeHistoryIdentityStatus(e){return this.#_.add(e),()=>{this.#_.delete(e)}}subscribeHistoryAvailability(e){return this.#v.add(e),this.#p&&e(!1),()=>{this.#v.delete(e)}}#O(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#p?{state:`unavailable`,reason:`history_disabled`}:this.#k():{state:`unavailable`,reason:`ineligible_mode`}}#k(){let e=this.#g;return e?.state===`browser_only`?e:this.#A()}#A(){return this.config.features?.history?.scope===`browser`?{state:`browser_only`,reason:`configured_browser_scope`}:this.config.getIdentityProof?{state:`browser_only`,reason:`proof_unavailable_before_binding`}:{state:`browser_only`,reason:`no_identity_provider`}}#j(e){let t=this.getHistoryIdentityStatus(),n=t.state===e.state&&dc(t)===dc(e);if(this.#g=e,!n){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let t of[...this.#_])t(e)}}async#M(e){let t=this.#E()&&!e.omitVisitorFields,n=!e.omitVisitorFields,r=null;(t||n)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let i=this.#C(),a=i.agentId??i.flowId,o=t||e.durableResume?e.conversationId:void 0,s={token:this.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(t||n)&&r?{visitorToken:r}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...o?{conversationId:o}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let c=await fetch(this.#T(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":An},body:JSON.stringify(s),signal:e.signal});if(!c.ok){let n=await c.json().catch(()=>({error:`Session initialization failed`}));if(t&&c.status===403&&n.error===`visitor_history_disabled`){if(this.#D(),o)throw new uc(`history_disabled`,`Visitor history is disabled for this surface`);return this.#M({...e,omitVisitorFields:!0})}throw c.status===403&&n.error===`durable_recovery_disabled`?new uc(`history_disabled`,`Durable recovery is disabled for this surface`):(t||e.durableResume)&&c.status===401&&n.error===`visitor_required`?new uc(`visitor_required`,`Visitor credential no longer resolves`):o&&c.status===404?new uc(`not_found`,`Conversation not found`):c.status===401?Error(`Invalid client token: ${n.hint||n.error}`):c.status===403?Error(`Origin not allowed: ${n.hint||n.error}`):Error(n.error||`Failed to initialize session`)}let l=await c.json();return l.visitor?.token&&await this.historyInternals.visitorStore?.set(l.visitor.token),{sessionId:l.sessionId,expiresAt:new Date(l.expiresAt),flow:l.flow,...l.conversationId?{conversationId:l.conversationId}:{},...l.targetId?{targetId:l.targetId}:{},...l.conversationRevision?{conversationRevision:l.conversationRevision}:{},...l.durableRecovery?{durableRecovery:l.durableRecovery}:{},...l.visitor?{visitor:l.visitor}:{},config:{welcomeMessage:l.config.welcomeMessage,placeholder:l.config.placeholder,theme:l.config.theme}}}async#N(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,t=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#E()&&!t)return this.#P(e,!1);let n=await this.readVisitorToken();if(e&&n)try{let n=await this.#M({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#R(n,e,!1)}catch(n){if(!fc(n,`not_found`)&&!fc(n,`visitor_required`)&&!fc(n,`history_disabled`))throw n;return t&&this.historyInternals.setStoredResumableHandle?.(null),this.#P(e,!0)}return this.#P(e,!1)}async#P(e,t){let n=this.historyInternals.visitorStore;return n&&!await this.readVisitorToken()?n.withFirstInitLock(()=>this.#F(e,t)):this.#F(e,t)}async#F(e,t){let n=this.config.getStoredSessionId?.()||null,r=await this.#M({storedSessionId:n}),i=await this.#L(r);return this.#R(i,e,t)}async#I(e){let t=this.config.getStoredSessionId?.()||null,n=this.config.getStoredConversationId?.()||null,r=await this.#M({storedSessionId:t,identityProof:e}),i=this.#R(r,n,!1);return this.clientSession=i,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint(),i}async#L(e){if(!e.visitor?.token||this.#h||!this.#E()&&e.durableRecovery?.enabled!==!0)return e;this.#h=!0;try{return await this.#M({storedSessionId:e.sessionId})}catch{return e}finally{this.#h=!1}}#R(e,t,n){let r=e.conversationId;return r&&t&&(n||r!==t)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:t,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#z(e){let t=!1;return{session:e,commit:()=>{t||(t=!0,this.clientSession=e,this.#d=!1,this.resetClientToolsFingerprint())},discard:()=>{t=!0}}}async prepareConversationSession(e,t){if(!this.isClientTokenMode())throw Error(`prepareConversationSession() only available in client token mode`);if(!this.#E())throw new uc(`history_disabled`,`Visitor history is disabled for this surface`);await this.historyInternals.historyBootstrapReady;let n=t?.proof??null;if(!await this.readVisitorToken()&&!n)throw new uc(`conversation_credential_missing`,`Reopening a conversation requires a stored visitor token or an identity proof`);let r=await this.#M({conversationId:e,identityProof:n});return this.#z(r)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw Error(`prepareNewConversationSession() only available in client token mode`);await this.historyInternals.historyBootstrapReady;let e=await this.#M({});return this.#z(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#E()&&this.#j(this.#A())}clearClientSession(){this.clientSession=null,this.#u=null,this.#d=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#f=null}#B(){return`${this.#w()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw Error(`sendFeedback() only available in client token mode`);if(!this.getClientSession())throw Error(`No active session. Please initialize session first.`);if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let t={...e,...this.config.clientToken&&{token:this.config.clientToken}},n=await fetch(this.#B(),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":An},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:`Feedback submission failed`}));throw n.status===401?(this.clientSession=null,this.#d=!1,this.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async submitMessageFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`csat`,rating:e,comment:t})}async submitNPSFeedback(e,t){let n=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:n.sessionId,type:`nps`,rating:e,comment:t})}async#V(e){e?.throwIfAborted();let t=this.config.identityProvider;if(t===void 0)return;let n=this.config.getIdentityProof;if(!t.trim()||!n)throw Error(`Chat identity requires identityProvider and getIdentityProof.`);let r,i;try{let t=Promise.resolve().then(()=>n());r=e?await Promise.race([t,new Promise((t,n)=>{i=()=>n(e.reason),e.addEventListener(`abort`,i,{once:!0}),e.aborted&&i()})]):await t}catch{throw e?.throwIfAborted(),Error(`The identity proof provider failed.`)}finally{i&&e?.removeEventListener(`abort`,i)}if(typeof r!=`string`||!r.trim())throw Error(`A fresh identity proof is required to send this message.`);return{provider:t,token:r}}#H;#U(){let e=this;return this.#H??={get config(){return e.config},headers:this.#t,getHeaders:this.#s,debug:this.debug,clientApiBase:()=>e.#w(),getClientApiUrl:t=>e.#T(t),getWebMcpBridge:()=>e.#S(),sendWithClientToolsDiff:(t,n,r,i)=>e.#Y(t,n,r,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#W;#G(){let e=this;return this.#W??={HistoryClientError:uc,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#w(),setHistoryIdentityStatus:t=>e.#j(t),browserOnlyStatus:()=>e.#k(),derivedBrowserOnly:()=>e.#A(),reinitWithProof:t=>e.#I(t),isHistoryCapable:()=>e.#E(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await or()).listConversations(this.#G(),e)}async getConversation(e,t){return(await or()).getConversation(this.#G(),e,t)}async finalizeDisplayProjections(e,t){return(await or()).finalizeDisplayProjections(this.#G(),e,t)}async deleteConversation(e,t){return(await or()).deleteConversation(this.#G(),e,t)}async deleteAllConversations(e){return(await or()).deleteAllConversations(this.#G(),e)}async resetVisitor(){return(await or()).resetVisitor(this.#G())}async dispatch(e,t){return e.signal?.throwIfAborted(),En().catch(()=>{}),this.isClientTokenMode()?this.#K(e,t):this.isAgentMode()?this.#J(e,t):this.#q(e,t)}async#K(e,t){let n=Ba();this.#l=n;let r=()=>this.#l===n,i=e=>{r()&&t(e)};t({type:`status`,status:`connecting`});try{let t=()=>{if(e.signal?.throwIfAborted(),!r())throw new DOMException(`Turn superseded`,`AbortError`)},a=this.clientSession??await this.initSession();t();let o=async()=>{t();let n=a,r=n.durableRecovery?.enabled===!0;if(r&&(!n.conversationId||!await this.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);t();let i=await this.#M({...r||this.#E()?{conversationId:n.conversationId,durableResume:r}:{storedSessionId:n.sessionId},signal:e.signal});if(t(),n.conversationId&&i.conversationId!==n.conversationId||r&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);a=this.#R(i,n.conversationId??null,!1),this.clientSession=a,this.#d=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(a)};Date.now()>=a.expiresAt.getTime()-6e4&&await o();let s=await this.#te(e.messages),c=s.metadata?Object.fromEntries(Object.entries(s.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,l=this.#E(),u={sessionId:a.sessionId,messages:e.messages.filter(pc).map(e=>{let t=l?Io(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...c&&Object.keys(c).length>0&&{metadata:c},...s.inputs&&Object.keys(s.inputs).length>0&&{inputs:s.inputs},...s.context&&{context:s.context},turnId:n,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},d=async()=>{t();let n=a.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return t(),this.#Y(a.sessionId,s.clientTools,async r=>{t();let i=await this.#V(e.signal);t();let o={...u,sessionId:a.sessionId,...r,...i&&{identityProof:i}};return this.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...o,...i&&{identityProof:{provider:i.provider,token:`[REDACTED]`}}}),fetch(this.#T(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":An,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(o),signal:e.signal})})},f=await d();if(t(),f.response.status===401){let e=await f.response.clone().json().catch(()=>null);t(),e?.error===`Session not found or expired`&&(await o(),f=await d(),t())}let{response:p,commit:m}=f;if(!p.ok){let e=await p.json().catch(()=>({error:`Chat request failed`}));if(p.status===401&&e.error===`invalid_identity_proof`){let e=new uc(`invalid_identity_proof`,`The identity proof was rejected`);throw i({type:`error`,error:e}),e}if(p.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw i({type:`error`,error:e}),e}if(p.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw i({type:`error`,error:t}),t}if(p.status===410&&e.error===`conversation_deleted`){let e=new uc(`conversation_deleted`,`This conversation was deleted`);throw i({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw i({type:`error`,error:t}),t}if(!p.body){let e=/* @__PURE__ */ Error(`No response body received`);throw i({type:`error`,error:e}),e}m(),i({type:`status`,status:`connected`});try{await this.#ne(p.body,i,e.assistantMessageId)}finally{i({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof uc)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&i({type:`error`,error:t}),t}}async#q(e,t){t({type:`status`,status:`connecting`});let n=await this.#te(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t)}finally{t({type:`status`,status:`idle`})}}async#J(e,t){t({type:`status`,status:`connecting`});let n=await this.#ee(e.messages,e.composerOptions);this.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.#t};if(this.#s)try{let e=await this.#s();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.#a)try{i=await this.#a(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.#e,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.#ne(i.body,t,e.assistantMessageId)}finally{t({type:`status`,status:`idle`})}}async processStream(e,t,n,r){t({type:`status`,status:`connected`});try{await this.#ne(e,t,n,r)}finally{t({type:`status`,status:`idle`})}}async resolveApproval(e,t,n){return(await En()).resolveApproval(this.#U(),e,t,n)}async#Y(e,t,n,r){let i=!!(t&&t.length>0),a=i?ge(t):void 0,o=this.clientToolsFingerprintSessionId===e,s=i&&o&&this.lastSentClientToolsFingerprint===a,c=!i&&r?.emptyMeansReplace===!0&&this.#f===e,l=!1,u;for(let e=0;u=await n({...i&&(l||!s)&&t?{clientTools:t}:{},...c?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&e===0&&i&&(await u.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)l=!0,this.lastSentClientToolsFingerprint=null;return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,i?this.#f=e:c&&(this.#f=null)}}}async resumeFlow(e,t,n){return(await En()).resumeFlow(this.#U(),e,t,n)}#X(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#Z(e){let t={};this.#r.length&&await Promise.all(this.#r.map(async n=>{try{let r=await n({messages:e,config:this.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#X(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#Q(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#$(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}async#ee(e,t){let n=this.#C().agentId;if(!this.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=cc(mc(e),e=>pc(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?hc(e):null),i=this.#Q(t),a={agent:this.#$(this.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.config.agentOptions}};i&&(a.composerOptions=i);let o=[...sn(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let s=await this.#Z(e);return s&&(a.context=s),a}async#te(e,t){let n=cc(mc(e),e=>pc(e)?hc(e):null),r=this.#C(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...sn(this.config),...await(await this.#S())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#Z(e);o&&(i.context=o);let s=this.#Q(t);if(s&&(i.composerOptions=s),this.#i)try{let e=await this.#i({payload:{...i},config:this.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}async#ne(e,t,n,r){let{streamResponse:i}=On()??await En();return i({config:()=>this.config,createStreamParser:this.#n,parseSSEEvent:this.#o,onSSEEvent:(e,t)=>this.#c?.(e,t)},e,t,n,r)}},vc=class extends Error{constructor(e,t,n){super(t),this.name=`HistoryProviderError`,this.code=e,n?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=n.retryAfterSeconds)}};function yc(e){return e instanceof vc}const bc=e=>typeof e==`object`&&!!e&&!Array.isArray(e),xc=(e,t)=>{let n=/* @__PURE__ */ new Set;return(Array.isArray(e)?e:[]).flatMap(e=>{if(!bc(e))return[];let{toolCallId:r,name:i}=e;if(typeof r!=`string`||!r||typeof i!=`string`||!i||n.has(r))return[];n.add(r);let a=bc(e.arguments)?e.arguments:{},o=e.result??null;return[{id:`voice-tool-${r}`,role:`assistant`,variant:`tool`,content:``,createdAt:t,streaming:!1,toolCall:{id:r,name:i,status:`complete`,args:a,result:o},agentMetadata:{clientToolAnswer:{toolCallId:r,toolName:i,args:a,result:o}}}]})};function Sc(e){let t=0;for(let n of e.split(`
14
+ `)){let e=/^ {0,3}(`+)/.exec(n);e&&e[1].length>t&&(t=e[1].length)}return t}function Cc(e,t){let n="`".repeat(Math.max(3,Sc(t)+1));return`${n}${e}\n${t}\n${n}`}Wi();const wc=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:`quoted-text`;function Tc(e){let t=e?.text?.trim()??``;return t?Cc(wc(e),t):``}function Ec(e){let t=Tc(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[Ai(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
15
15
 
16
- `)}:{}}function xc(e,t=140){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Sc(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1||e[n].role!==`user`)return null;let r=n+1;for(;r<e.length&&e[r].role!==`user`;)r+=1;return{start:n,end:r}}function Cc(e,t){let n=e.findIndex(e=>e.id===t);if(n<=0)return null;for(let t=n-1;t>=0;--t)if(e[t].role===`user`)return e[t].id;return null}function wc(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role===`user`||n.streaming)return null;if(!(n.role!==`assistant`||n.variant))return Cc(e,n.id)?n.id:null}return null}function Tc(e){return e.role!==`user`||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||e.rawContent!==void 0||e.llmContent!==void 0&&e.llmContent!==e.content||e.quote?!1:typeof e.content==`string`&&e.content.length>0}function Ec(e){for(let t of[`Microsoft Jenny Online (Natural) - English (United States)`,`Microsoft Aria Online (Natural) - English (United States)`,`Microsoft Guy Online (Natural) - English (United States)`,`Google US English`,`Google UK English Female`,`Ava (Premium)`,`Evan (Enhanced)`,`Samantha (Enhanced)`,`Samantha`,`Daniel`,`Karen`,`Microsoft David Desktop - English (United States)`,`Microsoft Zira Desktop - English (United States)`]){let n=e.find(e=>e.name===t);if(n)return n}return e.find(e=>e.lang.startsWith(`en`))??e[0]}var Dc=class e{constructor(e={}){this.options=e,this.id=`browser`,this.supportsPause=!0}static isSupported(){return typeof window<`u`&&`speechSynthesis`in window}speak(t,n){if(!e.isSupported()){n.onError?.(/* @__PURE__ */ Error(`Web Speech API is unavailable`));return}let r=window.speechSynthesis;r.cancel();let i=new SpeechSynthesisUtterance(t.text),a=r.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(i.voice=e)}else a.length>0&&(i.voice=this.options.pickVoice?this.options.pickVoice(a):Ec(a));t.rate!==void 0&&(i.rate=t.rate),t.pitch!==void 0&&(i.pitch=t.pitch),i.onend=()=>n.onEnd?.(),i.onerror=e=>{let t=e.error;t===`canceled`||t===`interrupted`?n.onEnd?.():n.onError?.(Error(t||`Speech synthesis failed`))},setTimeout(()=>{r.speak(i),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},Oc=class{#e=null;#t=null;#n=`idle`;#r=/* @__PURE__ */ new Set;#i=0;#a;constructor(e){this.#a=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#t===e?this.#n:`idle`}activeMessageId(){return this.#t}onChange(e){return this.#r.add(e),()=>this.#r.delete(e)}toggle(e,t){if(this.#t===e){if(this.#n===`playing`){this.#e?.supportsPause?(this.#e.pause(),this.#o(e,`paused`)):this.stop();return}if(this.#n===`paused`){this.#e?.resume(),this.#o(e,`playing`);return}if(this.#n===`loading`){this.stop();return}}this.play(e,t)}async play(e,t){let n=++this.#i;this.#e?.stop(),this.#o(e,`loading`);try{if(!this.#e){let e=await this.#a();if(n!==this.#i)return;if(!e){this.#o(null,`idle`);return}this.#e=e}this.#e.speak(t,{onStart:()=>{n===this.#i&&this.#o(e,`playing`)},onEnd:()=>{n===this.#i&&this.#o(null,`idle`)},onError:()=>{n===this.#i&&this.#o(null,`idle`)}})}catch{n===this.#i&&this.#o(null,`idle`)}}stop(){this.#i++,this.#e?.stop(),this.#o(null,`idle`)}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#r.clear()}#o(e,t){this.#t=t===`idle`?null:e,this.#n=t;for(let e of this.#r)e(this.#t,this.#n)}},kc=class{#e;#t=!1;start(e){this.#e=e,this.#t=!1}cancel(){this.#t=!0}accepts(e){return!this.#t&&(!e||!this.#e||e===this.#e)}};g();const{setLoader:Ac,load:jc,getSync:Mc}=h({fallbackImport:()=>import(`@runtypelabs/persona/voice-runtime`)}),Nc=jc,Pc=Mc;function Fc(e){if(!e)return``;let t=Ic(e);return Lc(t===null?e:t)}function Ic(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith(`{`))return null;try{let e=JSON.parse(t);if(e&&typeof e==`object`&&typeof e.text==`string`)return e.text}catch{}return null}function Lc(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,`
16
+ `)}:{}}function Dc(e,t=140){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Oc(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1||e[n].role!==`user`)return null;let r=n+1;for(;r<e.length&&e[r].role!==`user`;)r+=1;return{start:n,end:r}}function kc(e,t){let n=e.findIndex(e=>e.id===t);if(n<=0)return null;for(let t=n-1;t>=0;--t)if(e[t].role===`user`)return e[t].id;return null}function Ac(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role===`user`||n.streaming)return null;if(!(n.role!==`assistant`||n.variant))return kc(e,n.id)?n.id:null}return null}function jc(e){return e.role!==`user`||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||e.rawContent!==void 0||e.llmContent!==void 0&&e.llmContent!==e.content||e.quote?!1:typeof e.content==`string`&&e.content.length>0}function Mc(e){for(let t of[`Microsoft Jenny Online (Natural) - English (United States)`,`Microsoft Aria Online (Natural) - English (United States)`,`Microsoft Guy Online (Natural) - English (United States)`,`Google US English`,`Google UK English Female`,`Ava (Premium)`,`Evan (Enhanced)`,`Samantha (Enhanced)`,`Samantha`,`Daniel`,`Karen`,`Microsoft David Desktop - English (United States)`,`Microsoft Zira Desktop - English (United States)`]){let n=e.find(e=>e.name===t);if(n)return n}return e.find(e=>e.lang.startsWith(`en`))??e[0]}var Nc=class e{constructor(e={}){this.options=e,this.id=`browser`,this.supportsPause=!0}static isSupported(){return typeof window<`u`&&`speechSynthesis`in window}speak(t,n){if(!e.isSupported()){n.onError?.(/* @__PURE__ */ Error(`Web Speech API is unavailable`));return}let r=window.speechSynthesis;r.cancel();let i=new SpeechSynthesisUtterance(t.text),a=r.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(i.voice=e)}else a.length>0&&(i.voice=this.options.pickVoice?this.options.pickVoice(a):Mc(a));t.rate!==void 0&&(i.rate=t.rate),t.pitch!==void 0&&(i.pitch=t.pitch),i.onend=()=>n.onEnd?.(),i.onerror=e=>{let t=e.error;t===`canceled`||t===`interrupted`?n.onEnd?.():n.onError?.(Error(t||`Speech synthesis failed`))},setTimeout(()=>{r.speak(i),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},Pc=class{#e=null;#t=null;#n=`idle`;#r=/* @__PURE__ */ new Set;#i=0;#a;constructor(e){this.#a=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#t===e?this.#n:`idle`}activeMessageId(){return this.#t}onChange(e){return this.#r.add(e),()=>this.#r.delete(e)}toggle(e,t){if(this.#t===e){if(this.#n===`playing`){this.#e?.supportsPause?(this.#e.pause(),this.#o(e,`paused`)):this.stop();return}if(this.#n===`paused`){this.#e?.resume(),this.#o(e,`playing`);return}if(this.#n===`loading`){this.stop();return}}this.play(e,t)}async play(e,t){let n=++this.#i;this.#e?.stop(),this.#o(e,`loading`);try{if(!this.#e){let e=await this.#a();if(n!==this.#i)return;if(!e){this.#o(null,`idle`);return}this.#e=e}this.#e.speak(t,{onStart:()=>{n===this.#i&&this.#o(e,`playing`)},onEnd:()=>{n===this.#i&&this.#o(null,`idle`)},onError:()=>{n===this.#i&&this.#o(null,`idle`)}})}catch{n===this.#i&&this.#o(null,`idle`)}}stop(){this.#i++,this.#e?.stop(),this.#o(null,`idle`)}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#r.clear()}#o(e,t){this.#t=t===`idle`?null:e,this.#n=t;for(let e of this.#r)e(this.#t,this.#n)}},Fc=class{#e;#t=!1;start(e){this.#e=e,this.#t=!1}cancel(){this.#t=!0}accepts(e){return!this.#t&&(!e||!this.#e||e===this.#e)}};g();const{setLoader:Ic,load:Lc,getSync:Rc}=h({fallbackImport:()=>import(`@runtypelabs/persona/voice-runtime`)}),zc=Lc,Bc=Rc;function Vc(e){if(!e)return``;let t=Hc(e);return Uc(t===null?e:t)}function Hc(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith(`{`))return null;try{let e=JSON.parse(t);if(e&&typeof e==`object`&&typeof e.text==`string`)return e.text}catch{}return null}function Uc(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,`
17
17
  `),t=t.replace(/\n{2,}/g,`
18
- `),t.trim()}var Rc,zc=o((()=>{Rc=class{#e=null;#t=0;#n=[];#r=[];#i=[];#a=!1;#o=!1;#s=0;#c=!1;#l=!1;#u;#d=[];#f=0;#p=!1;#m;#h;#g;#_=null;constructor(e=24e3,t={}){this.#h=e;let n=Math.max(0,t.prebufferMs??0);this.#g=Math.round(e*n/1e3),this.#u=this.#g>0}#v(){if(!this.#e){let e=typeof window<`u`?window:void 0;if(!e)throw Error(`AudioPlaybackManager requires a browser environment`);let t=e.AudioContext||e.webkitAudioContext;this.#e=new t({sampleRate:this.#h})}let e=this.#e;return e.state===`suspended`&&!this.#l&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.#_){let n=new Uint8Array(this.#_.length+e.length);n.set(this.#_),n.set(e,this.#_.length),t=n,this.#_=null}if(t.length%2!=0&&(this.#_=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.#S(t);n.length!==0&&(this.#u?(this.#d.push(n),this.#f+=n.length,clearTimeout(this.#m),this.#f>=this.#g?this.#y():this.#p&&(this.#m=setTimeout(()=>this.#y(),this.#g/this.#h*1e3))):this.#b(n))}markStreamEnd(){this.#d.length>0&&this.#y(),this.#o=!0,this.#x()}flush(){for(let e of this.#n){e.onended=null;try{e.stop(),e.disconnect()}catch{}}this.#n=[],this.#s=0,this.#t=0,this.#a=!1,this.#o=!1,this.#r=[],this.#i=[],this.#_=null,this.#d=[],this.#f=0,this.#u=this.#g>0,this.#c=!1,clearTimeout(this.#m)}setContinuousMode(e){this.#p=e}isPlaying(){return this.#a}onFinished(e){this.#r.push(e)}onStarted(e){this.#i.push(e)}pause(){this.#l=!0,this.#e&&this.#e.state===`running`&&this.#e.suspend()}resume(){this.#l=!1,this.#e&&this.#e.state===`suspended`&&this.#e.resume()}async destroy(){this.flush(),this.#e&&=(await this.#e.close(),null)}#y(){this.#u=!1;let e=this.#d;this.#d=[],this.#f=0;for(let t of e)this.#b(t)}#b(e){if(e.length===0)return;let t=this.#v(),n=t.createBuffer(1,e.length,this.#h);n.getChannelData(0).set(e);let r=t.createBufferSource();r.buffer=n,r.connect(t.destination);let i=t.currentTime;if(this.#t===0?this.#t=i:this.#t<i&&(this.#t=i,this.#g>0&&(this.#u=!0)),r.start(this.#t),this.#t+=n.duration,this.#n.push(r),this.#s++,this.#a=!0,!this.#c){this.#c=!0;let e=this.#i.slice();this.#i=[];for(let t of e)t()}r.onended=()=>{let e=this.#n.indexOf(r);e!==-1&&(this.#n.splice(e,1),this.#s--,this.#x())}}#x(){if(this.#o&&this.#s<=0&&this.#d.length===0){this.#a=!1,this.#o=!1;let e=this.#r.slice();this.#r=[];for(let t of e)t()}}#S(e){let t=Math.floor(e.length/2),n=new Float32Array(t),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let e=0;e<t;e++){let t=r.getInt16(e*2,!0);n[e]=t/32768}return n}}}));function Bc(e){return e.replace(/\/+$/,``)}async function Vc(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 Hc,Uc=o((()=>{zc(),Hc=class{#e;#t;#n;#r;constructor(e){this.id=`runtype-tts`,this.supportsPause=!0,this.#e=null,this.#t=null,this.#n=0,this.#r=e}#i(){return this.#t??=Promise.resolve(this.#r.createPlaybackEngine?this.#r.createPlaybackEngine():new Rc(24e3,{prebufferMs:this.#r.prebufferMs??200})).then(e=>this.#e=e)}speak(e,t){let n=++this.#n;this.#a(n,e,t)}async#a(e,t,n){try{let r=await this.#i();if(e!==this.#n)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.#n&&n.onStart?.()}),r.onFinished(()=>{e===this.#n&&n.onEnd?.()});let i=`${Bc(this.#r.host)}/v1/agents/${encodeURIComponent(this.#r.agentId)}/speak`,a=await fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.#r.clientToken}`},body:JSON.stringify({text:t.text,voice:t.voice??this.#r.voice,format:`pcm`})});if(e!==this.#n)return;if(!a.ok||!a.body)throw Error(await Vc(a));let o=a.body.getReader();for(;;){let{done:t,value:n}=await o.read();if(e!==this.#n){await o.cancel().catch(()=>{});return}if(t)break;n&&n.byteLength>0&&r.enqueue(n)}r.markStreamEnd()}catch(t){if(e!==this.#n)return;let r=t instanceof Error?t:Error(String(t));this.#r.onError?.(r),n.onError?.(r)}}pause(){this.#e?.pause()}resume(){this.#e?.resume()}stop(){this.#n++,this.#e?.flush()}destroy(){this.#n++,this.#e?.destroy(),this.#e=null,this.#t=null}}})),Wc,Gc=o((()=>{Wc=class{#e;#t;#n;#r;constructor(e,t,n={}){this.id=`fallback`,this.#t=e,this.#n=t,this.#r=n,this.#e=e}get supportsPause(){return this.#e.supportsPause}speak(e,t){this.#e=this.#t;let n=!1;this.#t.speak(e,{onStart:()=>{n=!0,t.onStart?.()},onEnd:()=>t.onEnd?.(),onError:r=>{n?t.onError?.(r):(this.#r.onFallback?.(r),this.#e=this.#n,this.#n.speak(e,t))}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#t.destroy?.(),this.#n.destroy?.()}}})),Kc=/* @__PURE__ */ s({FallbackSpeechEngine:()=>Wc,RuntypeSpeechEngine:()=>Hc}),qc=o((()=>{Uc(),Gc()}));const Jc=()=>Promise.resolve().then(()=>(qc(),Kc));g();const{setLoader:Yc,load:Xc}=h({fallbackImport:()=>import(`@runtypelabs/persona/session-reconnect`)}),Zc=Xc;Ce(),nn(),Ui(),Ae(),Fo();const Qc=/* @__PURE__ */ `apiUrl.clientToken.flowId.agentId.target.targetProviders.agent.agentOptions.headers.getHeaders.webmcp.streamParser.parserType.contextProviders.requestMiddleware.customFetch.parseSSEEvent.onSessionInit.onSessionExpired.getStoredSessionId.setStoredSessionId.getIdentityProof.identityProvider.getStoredConversationId.setStoredConversationId.clearStoredConversationId.clearStoredSessionId`.split(`.`);function $c(e,t){return Qc.some(n=>e[n]!==t[n])}var el=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function tl(e,t){let n=e instanceof Error?e:Error(String(e));if(typeof t==`string`)return t;if(typeof t==`function`)return t(n);let r=`Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.`;return n.message?`${r}\n\n_Details: ${n.message}_`:r}const nl=e=>xe(e)||e===`suggest_replies`;var rl=class e{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;constructor(e={},t,n={}){this.config=e,this.callbacks=t,this.historyInternals=n,this.status=`idle`,this.streaming=!1,this.#e=/* @__PURE__ */ new Map,this.abortController=null,this.#n=Date.now(),this.clientSession=null,this.agentExecution=null,this.#r=null,this.#i=null,this.#a=!1,this.#o=null,this.#s=null,this.#c=null,this.artifacts=/* @__PURE__ */ new Map,this.#l=null,this.webMcpInflightKeys=/* @__PURE__ */ new Set,this.webMcpResolvedKeys=/* @__PURE__ */ new Set,this.webMcpResolveControllers=/* @__PURE__ */ new Set,this.#u=0,this.webMcpApprovalResolvers=/* @__PURE__ */ new Map,this.#d=0,this.approvalTokens=/* @__PURE__ */ new Map,this.webMcpAwaitBatches=/* @__PURE__ */ new Map,this.#f=null,this.#p=null,this.#m=0,this.#h=0,this.#g=!1,this.#_=`disconnected`,this.#v=null,this.#y=null,this.#b=null,this.#x=0,this.#S=!1,this.#C=null,this.#w=!1,this.#T=null,this.#E=/* @__PURE__ */ new Map,this.#D=null,this.#O=/* @__PURE__ */ new Map,this.#k=null,this.#A=null,this.#j=!1,this.#M=null,this.#N=null,this.#P=!1,this.#F=null,this.#R=null,this.#z=null,this.#B=new kc,this.#V=Promise.resolve(),this.#H=null,this.#U=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new Oc(()=>this.#W()),this.#Fe=null,this.#Ie=0,this.handleEvent=e=>{let t=this.#U,n=!1;if(t&&(e.type===`error`||e.type===`status`&&e.status===`error`?t.failed=!0:e.type===`message`&&e.message.role===`assistant`&&(t.dropped||this.ttsSpokenMessageIds.add(e.message.id),t.ids.includes(e.message.id)||t.ids.push(e.message.id),n=!0)),e.type===`message`){this.upsertMessage(e.message),n&&t.onUpdate?.(),e.message.variant===`approval`&&e.message.approval&&e.message.approval.status!==`pending`&&this.#e.set(e.message.id,this.#t),e.message.role===`assistant`&&!e.message.variant&&e.message.streaming&&(this.#i=e.message.id),(e.message.variant===`approval`||e.message.agentMetadata?.awaitingLocalTool===!0)&&$a().catch(()=>{});let r=e.message.toolCall,i=!!r?.name&&(xe(r.name)||r.name===`suggest_replies`&&tn(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&i&&this.#Re(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:``,agentName:e.message.agentMetadata.agentName??``,status:`running`,currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type===`cursor`)this.#qe(e.id);else if(e.type===`status`){if(e.status===`idle`&&!e.terminal&&this.#Je()){this.#Xe();return}if(this.#rt(e.status),e.status===`connecting`)this.#it(!0);else if(e.status===`idle`||e.status===`error`){this.#Ye()||this.#tt(),this.webMcpResolveControllers.size===0&&(this.#it(!1),this.abortController=null,this.#De(),this.#Se());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status===`running`&&(e.status===`error`?this.agentExecution.status=`error`:t||(this.agentExecution.status=`complete`)),this.#ze()}}else e.type===`error`?(this.#rt(`error`),this.#tt(),this.webMcpResolveControllers.size===0&&(this.#it(!1),this.abortController=null),this.agentExecution?.status===`running`&&(this.agentExecution.status=`error`),this.callbacks.onError?.(e.error)):(e.type===`artifact_start`||e.type===`artifact_delta`||e.type===`artifact_update`||e.type===`artifact_complete`)&&this.#Ke(e)},this.historyInternals=this.#X(n),this.messages=[...e.initialMessages??[]].map(e=>({...e,sequence:e.sequence??this.#ut()})),this.messages=this.#dt(this.messages),this.client=new pc(e,this.historyInternals),this.#pe(),this.#Pe();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:`complete`});e.initialSelectedArtifactId!=null&&(this.#l=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#Ge(),this.callbacks.onStatusChanged(this.status),this.#L(),this.#I()}#I(){this.config.voiceRecognition?.provider&&Nc().catch(()=>{})}#L(){let e=this.config.textToSpeech;if(e?.provider!==`runtype`||e.createEngine)return;let t=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&n&&this.config.clientToken&&Jc().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status===`running`}isVoiceSupported(){return gs(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#g}getVoiceStatus(){return this.#_}getVoiceNotice(){return this.#f?.takeNotice?.()??null}getVoiceDisclosure(){return this.#f?.getDisclosure?.()??null}getVoiceLevel(){return this.#f?.onLevel?this.#h:null}getVoiceInterruptionMode(){return this.#f?.getInterruptionMode?this.#f.getInterruptionMode():`none`}stopVoicePlayback(){this.#f?.stopPlayback&&(this.#B.cancel(),this.#H?.cancel(),this.#f.stopPlayback())}isBargeInActive(){return this.#f?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#f?.deactivateBargeIn&&await this.#f.deactivateBargeIn()}#R;#z;#B;#V;#H;#U;#W(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=Dc.isSupported()?new Dc({pickVoice:e?.pickVoice}):null;if(e?.provider===`runtype`){let n=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,a=e.browserFallback!==!1;if(n&&r&&i)return Jc().then(({RuntypeSpeechEngine:o,FallbackSpeechEngine:s})=>{let c=new o({host:n,agentId:r,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new s(c,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):c});if(a&&t)return i&&console.warn(`[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId).`),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error(`Voice configuration not provided`);this.cleanupVoice();let n=this.#V,r=++this.#m;this.#p=Nc().then(async e=>{await n,r===this.#m&&this.#G(e,e.createVoiceProvider(t))}).catch(e=>{console.error(`Failed to setup voice:`,e)}).finally(()=>{r===this.#m&&(this.#p=null)})}catch(e){console.error(`Failed to setup voice:`,e)}}#G(e,t){this.#f=t;let n=this;e.wireSessionVoice({session:this,provider:()=>n.#f,generation:()=>n.#m,get keyed(){return n.#H},set keyed(e){n.#H=e},get pendingUser(){return n.#R},set pendingUser(e){n.#R=e},get pendingAssistant(){return n.#z},set pendingAssistant(e){n.#z=e},turns:()=>n.#B,busy:()=>n.#K(),setStreaming:e=>n.#it(e),setDelegation:e=>{n.#U=e},setLevel:e=>{n.#h=e},setStatus:e=>{n.#_=e,n.#g=e===`listening`},settlePending:e=>n.#J(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#f&&this.#p&&await this.#p,!this.#f)console.error(`Voice not configured`);else if(this.#g)await this.#f.stopListening();else{this.stopSpeaking();try{await this.#f.startListening()}catch(e){console.error(`Failed to start voice:`,e)}}}prewarmVoice(){if(!ms(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#m,t=()=>{let t=this.#f;t?.prewarm&&e===this.#m&&(this.#g||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#f&&this.#p?this.#p.then(t,()=>{}):t()}#K(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#a||this.status===`resuming`}cleanupVoice(){let e=this.#f!==null;if(this.#m++,this.#p=null,this.#f){let e=this.#f;this.#f=null,this.#V=this.#q(e)}this.#g=!1,this.#_=`disconnected`,this.#J(!0),this.#H?.settle(),this.#H=null,this.#B=new kc,e&&this.callbacks.onVoiceStatusChanged?.(`disconnected`)}async#q(e){try{await e.disconnect()}catch(e){console.error(`Failed to disconnect voice:`,e)}}#J(e){let t=e?this.#R:null,n=this.#z;(t||n)&&(n&&this.#B.cancel(),e&&(this.#R=null),this.#z=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==n?[e]:e.id===n&&!e.content.trim()?[]:[{...e,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.#it(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case`runtype`:return{type:`runtype`,runtype:{agentId:e.runtype?.agentId??this.config.agentId??``,clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};case`browser`:return{type:`browser`,browser:{language:e.browser?.language||`en-US`,continuous:e.browser?.continuous}};case`custom`:return{type:`custom`,custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#A=this.historyInternals.getStoredConversationRevision?.()??null,this.#j=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#Y(e,t)}#Y(e,t=!this.messages.length){if(this.#S||!e.config.welcomeMessage||!t)return;let n=this.messages[0],r={id:`welcome-${Date.now()}`,role:`assistant`,content:e.config.welcomeMessage,createdAt:n?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),sequence:n?(n.sequence??0)-1:this.#ut()};this.#ct(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?/* @__PURE__ */ new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){this.historyInternals=this.#X(e),this.client.setHistoryInternals(this.historyInternals),this.#pe()}destroy(){this.cleanupVoice(),this.#M?.(),this.#M=null,this.#N=null}#X(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#fe(e),t?.(e)}}}get#Z(){return this.historyInternals.historyProvider??null}#Q(){let e=this.#Z;if(!e)throw new el(`history_unavailable`,`No conversation history provider is installed`);return e}#$(e){let t=this.#Q(),n=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?`verified-user`:`browser`,i=n??(t.capabilities.scopes.includes(r)?r:t.capabilities.scopes[0]??r);if(!t.capabilities.scopes.includes(i))throw new mc(`unsupported_scope`,`This history scope is not supported.`);return{scope:i}}getHistoryState(){return{activeConversationId:this.#v,conversationRevision:this.#y,nextMessageCursor:this.#b,recovery:this.#C,sendBlocked:this.#w}}getActiveConversationId(){return this.#v}#ee(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#te(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#T;e&&await e.catch(()=>{});let t=this.#D;t&&await t.catch(()=>{})}#ne(){if(this.streaming||this.status===`paused`||this.status===`resuming`)throw new el(`conversation_busy`,`Finish or stop the current turn before switching conversations`)}listConversations(e){return this.#Q().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit===void 0?{}:{limit:e.limit},...e?.targetId===void 0?{}:{targetId:e.targetId},context:this.#$(e?.scope)})}async openConversation(e,t){let n=this.#Q();this.#ne();let r=this.#$(t?.scope);await this.awaitHistorySettled();let i=++this.#x,a=await n.getPage(e,{context:r});if(i!==this.#x)throw new el(`superseded`,`A later selection won`);let o=await n.prepareOpen(e,{context:r});if(i!==this.#x)throw o.discard(),new el(`superseded`,`A later selection won`);this.#S=!0;try{await this.#ce(o)}finally{this.#S=!1}this.#v=o.conversationId||e,this.#y=o.conversationRevision||a.conversationRevision||null,this.#b=a.nextCursor,this.#C=null,this.#w=!1,this.#ue();for(let e of a.messages)this.#O.set(e.id,e.content);return this.#le(),this.hydrateMessages(a.messages),this.#ee(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,t,n){let r=this.#Q(),i=this.#$(n?.scope),a=t??this.#b;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let o=`${e} ${a}`,s=this.#E.get(o);if(s)return s;let c=this.#re(r,e,a,i).finally(()=>{this.#E.delete(o)});return this.#E.set(o,c),c}async#re(e,t,n,r){let i=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:n,...i?{beforeCreatedAt:i}:{},context:r});if(this.#v&&this.#v!==t)return{messages:[],nextMessageCursor:a.nextCursor};let o=Mo(this.messages,a.messages);this.messages=this.#dt(o.map(e=>this.#lt(e))),this.#b=a.nextCursor;for(let e of a.messages)this.#O.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#ee(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=++this.#x,i=await t.prepareStartNew({context:n});if(r!==this.#x)throw i.discard(),new el(`superseded`,`A later action won`);await this.#ie(i)}async#ie(e){this.#de(),await this.#ce(e),this.#v=e.conversationId||null,this.#y=e.conversationRevision||null,this.#b=null,this.#C=null,this.#w=!1,this.#le(),this.#ee()}async deleteConversation(e,t){let n=this.#Q(),r=this.#$(t?.scope);await this.awaitHistorySettled(),await n.delete(e,{context:r}),e===this.#v&&await this.#ae(r)}async updateConversation(e,t,n){let r=this.#Q();if(!r.update)throw new el(`history_unavailable`,`This history provider cannot update conversations`);let i=this.#$(n?.scope);return await this.awaitHistorySettled(),r.update(e,t,{context:i})}canUpdateConversations(){return typeof this.#Z?.update==`function`}async clearConversationHistory(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=await t.deleteAll({...e?.targetId===void 0?{}:{targetId:e.targetId},context:n});return await this.#ae(n),r}async resetHistoryDevice(){let e=this.#Q();if(!e.resetDevice)throw new el(`history_unavailable`,`This history provider cannot reset the device`);this.#x+=1,this.#D=null;try{return await e.resetDevice()}finally{this.#de(),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#w=!1,this.#ee()}}async#ae(e){this.#x+=1,this.#D=null,this.#de(),this.#v=null,this.#y=null,this.#b=null,this.#w=!0,this.#C=null,this.#ee(),await this.#oe(e)}async#oe(e){let t=this.#Z;if(!t)this.#w=!1,this.#ee();else try{let n=await t.prepareStartNew({context:e});await this.#ie(n)}catch{this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`)}}async#se(){if(this.#C===`new_conversation_required`&&this.#Z&&(this.#C=null,await this.#oe(this.#$()),this.#C===`new_conversation_required`))throw new el(`new_conversation_required`,`A new conversation is required before sending`)}async#ce(e){await e.commit();let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#v=e.conversationId,this.#y=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#S||this.#Y(e)}#le(){this.#v?this.config.setStoredConversationId?.(this.#v):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#y),this.historyInternals.setStoredMessageCursor?.(this.#b)}#ue(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#We(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#O.clear(),this.#ye(null)}#de(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#et(),this.#Ve(),this.#Ie++,this.messages=[],this.#ue(),this.#E.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#it(!1),this.#rt(`idle`),this.callbacks.onMessagesChanged([...this.messages])}#fe(e){this.#x+=1,this.#D=null,this.#w=!0,this.#de(),this.#v=e.conversationId,this.#y=null,this.#b=null,this.#C=null,this.#ee(),this.#te(`history_continuity_reset`,`This browser was reconnected to a different conversation, so the previous messages were cleared.`),this.#T=Promise.resolve().then(()=>{this.#w=!1,this.#T=null,this.#ee()})}#pe(){let e=this.historyInternals.visitorStore??null;e!==this.#N&&(this.#M?.(),this.#M=null,this.#N=e,e&&(this.#M=e.subscribe(e=>this.#me(e))))}#me(e){if(e.source!==`external`||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#x+=1,this.#D=null,this.#P=!0,this.#F=null;let t=this.messages.length>0;t||this.#v!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#de():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#E.clear(),this.#ye(null)),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#ee(),t&&this.#te(`history_continuity_reset`,`This browser's conversation history was reset in another tab, so the previous messages were cleared.`)}#he(){return this.#P?(this.#F||=this.#ge().finally(()=>{this.#F=null}),this.#F):Promise.resolve()}async#ge(){if(!this.isClientTokenMode())this.#P=!1;else try{this.bindActivatedSession(await this.client.initSession()),this.#P=!1}catch{}}reconcileBootConversation(e){let t=this.#Z,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#v;if(!t||!n)return Promise.resolve();let r=this.#$(e?.scope);this.#w=!0,this.#ee();let i=this.#_e(t,n,r).finally(()=>{this.#w=this.#C!==null,this.#T===i&&(this.#T=null),this.#ee()});return this.#T=i,i}async#_e(e,t,n){this.#v=t;let r=this.clientSession?.conversationRevision??this.#y??null,i=this.#j?this.#A:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#j=!1,this.#b=this.historyInternals.getStoredMessageCursor?.()??this.#b,await this.replayPendingProjections(),r&&i&&r===i){this.#y=r;return}let a=await e.getPage(t,{context:n}),o=new Set(a.messages.map(e=>e.id)),s=this.messages.some(e=>o.has(e.id)),c=a.messages[0]?.createdAt,l;if(!s)l=a.messages.map(e=>this.#lt(e));else{let e=this.#r?this.#i:null;l=Mo(this.messages.filter(t=>o.has(t.id)||t.id===e?!0:c!==void 0&&t.createdAt<c),a.messages).map(e=>this.#lt(e))}this.#b=a.nextCursor,this.#y=a.conversationRevision||r||null,this.#O.clear();for(let e of a.messages)this.#O.set(e.id,e.content);this.#le(),this.messages=this.#dt(l),this.callbacks.onMessagesChanged([...this.messages])}#ve(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#ye(e){this.#k=e,this.historyInternals.setPendingDisplayProjections?.(e)}#be(){return this.historyInternals.getPendingDisplayProjections?.()??this.#k}#xe(e){if(this.#ve())for(let t of e){let e=jo(t);e!==void 0&&this.#O.set(t.id,e)}}#Se(){if(!this.#ve())return;let e=this.#v;if(!e)return;let t=[];for(let e of this.messages){if(e.role!==`assistant`||e.streaming)continue;let n=jo(e);n!==void 0&&this.#O.get(e.id)!==n&&t.push({id:e.id,displayContent:n})}t.length!==0&&(this.#ye({conversationId:e,messageIds:t.map(e=>e.id)}),this.#Ce(e,t))}#Ce(e,t){let n=(this.#D??Promise.resolve()).catch(()=>{}).then(()=>this.#we(e,t,!1)).finally(()=>{this.#D===n&&(this.#D=null)});this.#D=n}async#we(e,t,n){if(this.#v!==e)return;let r=t.filter(e=>this.#O.get(e.id)!==e.displayContent);if(r.length===0)this.#Ee(e,t);else try{let{conversationRevision:n}=await this.client.finalizeDisplayProjections(e,r);for(let e of r)this.#O.set(e.id,e.displayContent);this.#v===e&&n&&(this.#y=n),this.#Ee(e,t)}catch(i){if(!n&&this.#Te(i)){await this.#we(e,r,!0);return}if(i instanceof oc&&(i.code===`not_found`||i.code===`conversation_deleted`)){this.#Ee(e,t);return}this.#te(`projection_finalization_failed`,`Some message formatting could not be saved for history; it will be retried.`)}}#Te(e){return e instanceof oc?e.code===`request_failed`:e instanceof Error}#Ee(e,t){let n=this.#be();if(!n||n.conversationId!==e)return;let r=new Set(t.map(e=>e.id)),i=n.messageIds.filter(e=>!r.has(e));this.#ye(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#ve())return;let e=this.#be();if(!e)return;if(this.#v&&e.conversationId!==this.#v){this.#ye(null);return}let t=[];for(let n of e.messageIds){let e=this.messages.find(e=>e.id===n);e&&typeof e.content==`string`&&t.push({id:n,displayContent:e.content})}t.length===0?this.#ye(null):(this.#Ce(e.conversationId,t),await this.#D?.catch(()=>{}))}#De(){this.#v&&(this.#y=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Oe(){await this.awaitHistorySettled(),await this.#he(),this.#C===`new_conversation_required`&&await this.#se()}static#ke(e){return e instanceof oc&&e.code===`conversation_deleted`}async#Ae(t,n,r,i,a){this.#xe(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken},this.handleEvent);return}catch(t){if(!e.#ke(t))throw t;let o=await this.#je(i);if(!o)throw t;this.#xe([o]),await this.client.dispatch({messages:[o],signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken},this.handleEvent)}}async#je(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let n={...t};this.#x+=1,this.#D=null,this.#de(),this.#v=null,this.#y=null,this.#b=null,this.#S=!0;try{let e=this.#Z;if(e){let t=await e.prepareStartNew({context:this.#$()});await this.#ie(t)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`),null}finally{this.#S=!1}return this.#ct(n),this.#it(!0),this.#te(`conversation_deleted_recovered`,`That conversation was deleted. Started a new conversation.`),this.messages.find(e=>e.id===n.id)??n}updateConfig(e){let t=this.config.features?.artifacts?.display,n={...this.config,...e},r=ps(this.config,n),i=$c(this.config,n);this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&ms(n.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(n.features?.artifacts?.display);if(!i){this.client.updateConfig(n),a&&this.#Ue();return}this.#Ve(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.client=new pc(this.config,this.historyInternals),a&&this.#Ue(),this.#Pe(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:n,llmContent:r,contentParts:i,id:a,createdAt:o,sequence:s,streaming:c=!1,voiceProcessing:l,voiceCaption:u,rawContent:d}=e,f={id:a??(t===`user`?$s():t===`assistant`?ec():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:n,createdAt:o??(/* @__PURE__ */ new Date()).toISOString(),sequence:s??this.#ut(),streaming:c,...r!==void 0&&{llmContent:r},...i!==void 0&&{contentParts:i},...l!==void 0&&{voiceProcessing:l},...u&&{voiceCaption:u},...d!==void 0&&{rawContent:d}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:`assistant`})}injectUserMessage(e){return this.injectMessage({...e,role:`user`})}injectSystemMessage(e){return this.injectMessage({...e,role:`system`})}injectMessageBatch(e){let t=[];for(let n of e){let{role:e,content:r,llmContent:i,contentParts:a,id:o,createdAt:s,sequence:c,streaming:l=!1,voiceProcessing:u,rawContent:d}=n,f={id:o??(e===`user`?$s():e===`assistant`?ec():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:e,content:r,createdAt:s??(/* @__PURE__ */ new Date()).toISOString(),sequence:c??this.#ut(),streaming:l,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a},...u!==void 0&&{voiceProcessing:u},...d!==void 0&&{rawContent:d}};t.push(f)}return this.messages=this.#dt([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:r=``,llmContent:i,id:a,createdAt:o,sequence:s}=e,c={text:r,component:t,props:n};return this.injectMessage({role:`assistant`,content:r,rawContent:JSON.stringify(c),...i!==void 0&&{llmContent:i},...a!==void 0&&{id:a},...o!==void 0&&{createdAt:o},...s!==void 0&&{sequence:s}})}async#Me(e,t,n){let r;try{r=await n()}catch{return}let i=r.blocks.join(`
18
+ `),t.trim()}var Wc,Gc=o((()=>{Wc=class{#e=null;#t=0;#n=[];#r=[];#i=[];#a=!1;#o=!1;#s=0;#c=!1;#l=!1;#u;#d=[];#f=0;#p=!1;#m;#h;#g;#_=null;constructor(e=24e3,t={}){this.#h=e;let n=Math.max(0,t.prebufferMs??0);this.#g=Math.round(e*n/1e3),this.#u=this.#g>0}#v(){if(!this.#e){let e=typeof window<`u`?window:void 0;if(!e)throw Error(`AudioPlaybackManager requires a browser environment`);let t=e.AudioContext||e.webkitAudioContext;this.#e=new t({sampleRate:this.#h})}let e=this.#e;return e.state===`suspended`&&!this.#l&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.#_){let n=new Uint8Array(this.#_.length+e.length);n.set(this.#_),n.set(e,this.#_.length),t=n,this.#_=null}if(t.length%2!=0&&(this.#_=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.#S(t);n.length!==0&&(this.#u?(this.#d.push(n),this.#f+=n.length,clearTimeout(this.#m),this.#f>=this.#g?this.#y():this.#p&&(this.#m=setTimeout(()=>this.#y(),this.#g/this.#h*1e3))):this.#b(n))}markStreamEnd(){this.#d.length>0&&this.#y(),this.#o=!0,this.#x()}flush(){for(let e of this.#n){e.onended=null;try{e.stop(),e.disconnect()}catch{}}this.#n=[],this.#s=0,this.#t=0,this.#a=!1,this.#o=!1,this.#r=[],this.#i=[],this.#_=null,this.#d=[],this.#f=0,this.#u=this.#g>0,this.#c=!1,clearTimeout(this.#m)}setContinuousMode(e){this.#p=e}isPlaying(){return this.#a}onFinished(e){this.#r.push(e)}onStarted(e){this.#i.push(e)}pause(){this.#l=!0,this.#e&&this.#e.state===`running`&&this.#e.suspend()}resume(){this.#l=!1,this.#e&&this.#e.state===`suspended`&&this.#e.resume()}async destroy(){this.flush(),this.#e&&=(await this.#e.close(),null)}#y(){this.#u=!1;let e=this.#d;this.#d=[],this.#f=0;for(let t of e)this.#b(t)}#b(e){if(e.length===0)return;let t=this.#v(),n=t.createBuffer(1,e.length,this.#h);n.getChannelData(0).set(e);let r=t.createBufferSource();r.buffer=n,r.connect(t.destination);let i=t.currentTime;if(this.#t===0?this.#t=i:this.#t<i&&(this.#t=i,this.#g>0&&(this.#u=!0)),r.start(this.#t),this.#t+=n.duration,this.#n.push(r),this.#s++,this.#a=!0,!this.#c){this.#c=!0;let e=this.#i.slice();this.#i=[];for(let t of e)t()}r.onended=()=>{let e=this.#n.indexOf(r);e!==-1&&(this.#n.splice(e,1),this.#s--,this.#x())}}#x(){if(this.#o&&this.#s<=0&&this.#d.length===0){this.#a=!1,this.#o=!1;let e=this.#r.slice();this.#r=[];for(let t of e)t()}}#S(e){let t=Math.floor(e.length/2),n=new Float32Array(t),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let e=0;e<t;e++){let t=r.getInt16(e*2,!0);n[e]=t/32768}return n}}}));function Kc(e){return e.replace(/\/+$/,``)}async function qc(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 Jc,Yc=o((()=>{Gc(),Jc=class{#e;#t;#n;#r;constructor(e){this.id=`runtype-tts`,this.supportsPause=!0,this.#e=null,this.#t=null,this.#n=0,this.#r=e}#i(){return this.#t??=Promise.resolve(this.#r.createPlaybackEngine?this.#r.createPlaybackEngine():new Wc(24e3,{prebufferMs:this.#r.prebufferMs??200})).then(e=>this.#e=e)}speak(e,t){let n=++this.#n;this.#a(n,e,t)}async#a(e,t,n){try{let r=await this.#i();if(e!==this.#n)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.#n&&n.onStart?.()}),r.onFinished(()=>{e===this.#n&&n.onEnd?.()});let i=`${Kc(this.#r.host)}/v1/agents/${encodeURIComponent(this.#r.agentId)}/speak`,a=await fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.#r.clientToken}`},body:JSON.stringify({text:t.text,voice:t.voice??this.#r.voice,format:`pcm`})});if(e!==this.#n)return;if(!a.ok||!a.body)throw Error(await qc(a));let o=a.body.getReader();for(;;){let{done:t,value:n}=await o.read();if(e!==this.#n){await o.cancel().catch(()=>{});return}if(t)break;n&&n.byteLength>0&&r.enqueue(n)}r.markStreamEnd()}catch(t){if(e!==this.#n)return;let r=t instanceof Error?t:Error(String(t));this.#r.onError?.(r),n.onError?.(r)}}pause(){this.#e?.pause()}resume(){this.#e?.resume()}stop(){this.#n++,this.#e?.flush()}destroy(){this.#n++,this.#e?.destroy(),this.#e=null,this.#t=null}}})),Xc,Zc=o((()=>{Xc=class{#e;#t;#n;#r;constructor(e,t,n={}){this.id=`fallback`,this.#t=e,this.#n=t,this.#r=n,this.#e=e}get supportsPause(){return this.#e.supportsPause}speak(e,t){this.#e=this.#t;let n=!1;this.#t.speak(e,{onStart:()=>{n=!0,t.onStart?.()},onEnd:()=>t.onEnd?.(),onError:r=>{n?t.onError?.(r):(this.#r.onFallback?.(r),this.#e=this.#n,this.#n.speak(e,t))}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#t.destroy?.(),this.#n.destroy?.()}}})),Qc=/* @__PURE__ */ s({FallbackSpeechEngine:()=>Xc,RuntypeSpeechEngine:()=>Jc}),$c=o((()=>{Yc(),Zc()}));const el=()=>Promise.resolve().then(()=>($c(),Qc));g();const{setLoader:tl,load:nl}=h({fallbackImport:()=>import(`@runtypelabs/persona/session-reconnect`)}),rl=nl;we(),rn(),Va(),Wi(),je(),Bo();const il=/* @__PURE__ */ `apiUrl.clientToken.flowId.agentId.target.targetProviders.agent.agentOptions.headers.getHeaders.webmcp.streamParser.parserType.contextProviders.requestMiddleware.customFetch.parseSSEEvent.onSessionInit.onSessionExpired.getStoredSessionId.setStoredSessionId.getIdentityProof.identityProvider.getStoredConversationId.setStoredConversationId.clearStoredConversationId.clearStoredSessionId`.split(`.`);function al(e,t){return il.some(n=>e[n]!==t[n])}var ol=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function sl(e,t){let n=e instanceof Error?e:Error(String(e));if(typeof t==`string`)return t;if(typeof t==`function`)return t(n);let r=`Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.`;return n.message?`${r}\n\n_Details: ${n.message}_`:r}const cl=e=>Se(e)||e===`suggest_replies`;var ll=class e{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;constructor(e={},t,n={}){this.config=e,this.callbacks=t,this.historyInternals=n,this.status=`idle`,this.streaming=!1,this.#e=/* @__PURE__ */ new Map,this.abortController=null,this.#n=Date.now(),this.clientSession=null,this.agentExecution=null,this.#r=null,this.#i=null,this.#a=!1,this.#o=null,this.#s=null,this.#c=null,this.artifacts=/* @__PURE__ */ new Map,this.#l=null,this.webMcpInflightKeys=/* @__PURE__ */ new Set,this.webMcpResolvedKeys=/* @__PURE__ */ new Set,this.webMcpResolveControllers=/* @__PURE__ */ new Set,this.#u=0,this.webMcpApprovalResolvers=/* @__PURE__ */ new Map,this.#d=0,this.approvalTokens=/* @__PURE__ */ new Map,this.webMcpAwaitBatches=/* @__PURE__ */ new Map,this.#f=null,this.#p=null,this.#m=0,this.#h=0,this.#g=!1,this.#_=`disconnected`,this.#v=null,this.#y=null,this.#b=null,this.#x=0,this.#S=!1,this.#C=null,this.#w=!1,this.#T=null,this.#E=/* @__PURE__ */ new Map,this.#D=null,this.#O=/* @__PURE__ */ new Map,this.#k=null,this.#A=null,this.#j=!1,this.#M=null,this.#N=null,this.#P=!1,this.#F=null,this.#R=null,this.#z=null,this.#B=new Fc,this.#V=Promise.resolve(),this.#H=null,this.#U=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new Pc(()=>this.#W()),this.#Ie=null,this.#Le=0,this.handleEvent=e=>{let t=this.#U,n=!1;if(t&&(e.type===`error`||e.type===`status`&&e.status===`error`?t.failed=!0:e.type===`message`&&e.message.role===`assistant`&&(t.dropped||this.ttsSpokenMessageIds.add(e.message.id),t.ids.includes(e.message.id)||t.ids.push(e.message.id),n=!0)),e.type===`message`){this.upsertMessage(e.message),n&&t.onUpdate?.(),e.message.variant===`approval`&&e.message.approval&&e.message.approval.status!==`pending`&&this.#e.set(e.message.id,this.#t),e.message.role===`assistant`&&!e.message.variant&&e.message.streaming&&(this.#i=e.message.id),(e.message.variant===`approval`||e.message.agentMetadata?.awaitingLocalTool===!0)&&io().catch(()=>{});let r=e.message.toolCall,i=!!r?.name&&(Se(r.name)||r.name===`suggest_replies`&&nn(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&i&&this.messages.find(t=>t.id===e.message.id)?.agentMetadata?.awaitingLocalTool===!0&&this.#ze(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:``,agentName:e.message.agentMetadata.agentName??``,status:`running`,currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type===`cursor`)this.#Je(e.id);else if(e.type===`status`){if(e.status===`idle`&&!e.terminal&&this.#Ye()){this.#Ze();return}if(this.#st(e.status),e.status===`connecting`)this.#ct(!0);else if(e.status===`idle`||e.status===`error`){this.#Xe()||this.#at(),this.webMcpResolveControllers.size===0&&(this.#ct(!1),this.abortController=null,this.#Oe(),this.#Ce());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status===`running`&&(e.status===`error`?this.agentExecution.status=`error`:t||(this.agentExecution.status=`complete`)),this.#Be()}}else e.type===`error`?(this.#st(`error`),this.#at(),this.webMcpResolveControllers.size===0&&(this.#ct(!1),this.abortController=null),this.agentExecution?.status===`running`&&(this.agentExecution.status=`error`),this.callbacks.onError?.(e.error)):(e.type===`artifact_start`||e.type===`artifact_delta`||e.type===`artifact_update`||e.type===`artifact_complete`)&&this.#qe(e)},this.historyInternals=this.#X(n),this.messages=[...e.initialMessages??[]].map(e=>({...is(e),sequence:e.sequence??this.#mt()})),this.messages=this.#ht(this.messages),this.client=new _c(e,this.historyInternals),this.#me(),this.#Fe();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:`complete`});e.initialSelectedArtifactId!=null&&(this.#l=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#Ke(),this.callbacks.onStatusChanged(this.status),this.#L(),this.#I()}#I(){this.config.voiceRecognition?.provider&&zc().catch(()=>{})}#L(){let e=this.config.textToSpeech;if(e?.provider!==`runtype`||e.createEngine)return;let t=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&n&&this.config.clientToken&&el().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status===`running`}isVoiceSupported(){return Cs(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#g}getVoiceStatus(){return this.#_}getVoiceNotice(){return this.#f?.takeNotice?.()??null}getVoiceDisclosure(){return this.#f?.getDisclosure?.()??null}getVoiceLevel(){return this.#f?.onLevel?this.#h:null}getVoiceInterruptionMode(){return this.#f?.getInterruptionMode?this.#f.getInterruptionMode():`none`}stopVoicePlayback(){this.#f?.stopPlayback&&(this.#B.cancel(),this.#H?.cancel(),this.#f.stopPlayback())}isBargeInActive(){return this.#f?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#f?.deactivateBargeIn&&await this.#f.deactivateBargeIn()}#R;#z;#B;#V;#H;#U;#W(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=Nc.isSupported()?new Nc({pickVoice:e?.pickVoice}):null;if(e?.provider===`runtype`){let n=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,a=e.browserFallback!==!1;if(n&&r&&i)return el().then(({RuntypeSpeechEngine:o,FallbackSpeechEngine:s})=>{let c=new o({host:n,agentId:r,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new s(c,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):c});if(a&&t)return i&&console.warn(`[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId).`),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error(`Voice configuration not provided`);this.cleanupVoice();let n=this.#V,r=++this.#m;this.#p=zc().then(async e=>{await n,r===this.#m&&this.#G(e,e.createVoiceProvider(t))}).catch(e=>{console.error(`Failed to setup voice:`,e)}).finally(()=>{r===this.#m&&(this.#p=null)})}catch(e){console.error(`Failed to setup voice:`,e)}}#G(e,t){this.#f=t;let n=this;e.wireSessionVoice({session:this,provider:()=>n.#f,generation:()=>n.#m,get keyed(){return n.#H},set keyed(e){n.#H=e},get pendingUser(){return n.#R},set pendingUser(e){n.#R=e},get pendingAssistant(){return n.#z},set pendingAssistant(e){n.#z=e},turns:()=>n.#B,busy:()=>n.#K(),setStreaming:e=>n.#ct(e),setDelegation:e=>{n.#U=e},setLevel:e=>{n.#h=e},setStatus:e=>{n.#_=e,n.#g=e===`listening`},settlePending:e=>n.#J(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){if(!this.#f&&this.#p&&await this.#p,!this.#f)console.error(`Voice not configured`);else if(this.#g)await this.#f.stopListening();else{this.stopSpeaking();try{await this.#f.startListening()}catch(e){console.error(`Failed to start voice:`,e)}}}prewarmVoice(){if(!xs(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#m,t=()=>{let t=this.#f;t?.prewarm&&e===this.#m&&(this.#g||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#f&&this.#p?this.#p.then(t,()=>{}):t()}#K(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#a||this.status===`resuming`}cleanupVoice(){let e=this.#f!==null;if(this.#m++,this.#p=null,this.#f){let e=this.#f;this.#f=null,this.#V=this.#q(e)}this.#g=!1,this.#_=`disconnected`,this.#J(!0),this.#H?.settle(),this.#H=null,this.#B=new Fc,e&&this.callbacks.onVoiceStatusChanged?.(`disconnected`)}async#q(e){try{await e.disconnect()}catch(e){console.error(`Failed to disconnect voice:`,e)}}#J(e){let t=e?this.#R:null,n=this.#z;(t||n)&&(n&&this.#B.cancel(),e&&(this.#R=null),this.#z=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==n?[e]:e.id===n&&!e.content.trim()?[]:[{...e,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.#ct(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case`runtype`:return{type:`runtype`,runtype:{agentId:e.runtype?.agentId??this.config.agentId??``,clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};case`browser`:return{type:`browser`,browser:{language:e.browser?.language||`en-US`,continuous:e.browser?.continuous}};case`custom`:return{type:`custom`,custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#A=this.historyInternals.getStoredConversationRevision?.()??null,this.#j=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#Y(e,t)}#Y(e,t=!this.messages.length){if(this.#S||!e.config.welcomeMessage||!t)return;let n=this.messages[0],r={id:`welcome-${Date.now()}`,role:`assistant`,content:e.config.welcomeMessage,createdAt:n?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),sequence:n?(n.sequence??0)-1:this.#mt()};this.#ft(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?/* @__PURE__ */ new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){this.historyInternals=this.#X(e),this.client.setHistoryInternals(this.historyInternals),this.#me()}destroy(){this.cleanupVoice(),this.#M?.(),this.#M=null,this.#N=null}#X(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#pe(e),t?.(e)}}}get#Z(){return this.historyInternals.historyProvider??null}#Q(){let e=this.#Z;if(!e)throw new ol(`history_unavailable`,`No conversation history provider is installed`);return e}#$(e){let t=this.#Q(),n=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?`verified-user`:`browser`,i=n??(t.capabilities.scopes.includes(r)?r:t.capabilities.scopes[0]??r);if(!t.capabilities.scopes.includes(i))throw new vc(`unsupported_scope`,`This history scope is not supported.`);return{scope:i}}getHistoryState(){return{activeConversationId:this.#v,conversationRevision:this.#y,nextMessageCursor:this.#b,recovery:this.#C,sendBlocked:this.#w}}getActiveConversationId(){return this.#v}#ee(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#te(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#T;e&&await e.catch(()=>{});let t=this.#D;t&&await t.catch(()=>{})}#ne(){if(this.streaming||this.status===`paused`||this.status===`resuming`)throw new ol(`conversation_busy`,`Finish or stop the current turn before switching conversations`)}listConversations(e){return this.#Q().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit===void 0?{}:{limit:e.limit},...e?.targetId===void 0?{}:{targetId:e.targetId},context:this.#$(e?.scope)})}async openConversation(e,t){let n=this.#Q();this.#ne();let r=this.#$(t?.scope);await this.awaitHistorySettled();let i=++this.#x,a=await n.getPage(e,{context:r});if(i!==this.#x)throw new ol(`superseded`,`A later selection won`);let o=await n.prepareOpen(e,{context:r});if(i!==this.#x)throw o.discard(),new ol(`superseded`,`A later selection won`);this.#S=!0;try{await this.#le(o)}finally{this.#S=!1}this.#v=o.conversationId||e,this.#y=o.conversationRevision||a.conversationRevision||null,this.#b=a.nextCursor,this.#C=null,this.#w=!1,this.#de();for(let e of a.messages)this.#O.set(e.id,e.content);return this.#ue(),this.hydrateMessages(a.messages),this.#ee(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,t,n){let r=this.#Q(),i=this.#$(n?.scope),a=t??this.#b;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let o=`${e} ${a}`,s=this.#E.get(o);if(s)return s;let c=this.#re(r,e,a,i).finally(()=>{this.#E.delete(o)});return this.#E.set(o,c),c}async#re(e,t,n,r){let i=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:n,...i?{beforeCreatedAt:i}:{},context:r});if(this.#v&&this.#v!==t)return{messages:[],nextMessageCursor:a.nextCursor};let o=this.#ie(a.messages),s=Lo(this.messages,o);this.messages=this.#ht(s.map(e=>this.#pt(e))),this.#b=a.nextCursor;for(let e of a.messages)this.#O.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#ee(),{messages:o,nextMessageCursor:a.nextCursor}}#ie(e){let t=new Map(this.messages.map(e=>[e.id,e]));return e.map(e=>{let n=t.get(e.id);if(n){if(this.webMcpApprovalResolvers.has(n.id)||n.approval&&rs(n.approval)&&n.approval.id===e.approval?.id&&n.approval.status!==`pending`&&e.approval?.status===`pending`)return n;let t=n.agentMetadata?.executionId,r=[...n.toolCall?[n.toolCall]:[],...n.tools??[]];if(t&&r.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return n}return is(e)})}async startNewConversation(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=++this.#x,i=await t.prepareStartNew({context:n});if(r!==this.#x)throw i.discard(),new ol(`superseded`,`A later action won`);await this.#ae(i)}async#ae(e){this.#fe(),await this.#le(e),this.#v=e.conversationId||null,this.#y=e.conversationRevision||null,this.#b=null,this.#C=null,this.#w=!1,this.#ue(),this.#ee()}async deleteConversation(e,t){let n=this.#Q(),r=this.#$(t?.scope);await this.awaitHistorySettled(),await n.delete(e,{context:r}),e===this.#v&&await this.#oe(r)}async updateConversation(e,t,n){let r=this.#Q();if(!r.update)throw new ol(`history_unavailable`,`This history provider cannot update conversations`);let i=this.#$(n?.scope);return await this.awaitHistorySettled(),r.update(e,t,{context:i})}canUpdateConversations(){return typeof this.#Z?.update==`function`}async clearConversationHistory(e){let t=this.#Q(),n=this.#$(e?.scope);await this.awaitHistorySettled();let r=await t.deleteAll({...e?.targetId===void 0?{}:{targetId:e.targetId},context:n});return await this.#oe(n),r}async resetHistoryDevice(){let e=this.#Q();if(!e.resetDevice)throw new ol(`history_unavailable`,`This history provider cannot reset the device`);this.#x+=1,this.#D=null;try{return await e.resetDevice()}finally{this.#fe(),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#w=!1,this.#ee()}}async#oe(e){this.#x+=1,this.#D=null,this.#fe(),this.#v=null,this.#y=null,this.#b=null,this.#w=!0,this.#C=null,this.#ee(),await this.#se(e)}async#se(e){let t=this.#Z;if(!t)this.#w=!1,this.#ee();else try{let n=await t.prepareStartNew({context:e});await this.#ae(n)}catch{this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`)}}async#ce(){if(this.#C===`new_conversation_required`&&this.#Z&&(this.#C=null,await this.#se(this.#$()),this.#C===`new_conversation_required`))throw new ol(`new_conversation_required`,`A new conversation is required before sending`)}async#le(e){await e.commit();let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#v=e.conversationId,this.#y=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#S||this.#Y(e)}#ue(){this.#v?this.config.setStoredConversationId?.(this.#v):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#y),this.historyInternals.setStoredMessageCursor?.(this.#b)}#de(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Ge(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#O.clear(),this.#be(null)}#fe(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.messages=[],this.#de(),this.#E.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#ct(!1),this.#st(`idle`),this.callbacks.onMessagesChanged([...this.messages])}#pe(e){this.#x+=1,this.#D=null,this.#w=!0,this.#fe(),this.#v=e.conversationId,this.#y=null,this.#b=null,this.#C=null,this.#ee(),this.#te(`history_continuity_reset`,`This browser was reconnected to a different conversation, so the previous messages were cleared.`),this.#T=Promise.resolve().then(()=>{this.#w=!1,this.#T=null,this.#ee()})}#me(){let e=this.historyInternals.visitorStore??null;e!==this.#N&&(this.#M?.(),this.#M=null,this.#N=e,e&&(this.#M=e.subscribe(e=>this.#he(e))))}#he(e){if(e.source!==`external`||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#x+=1,this.#D=null,this.#P=!0,this.#F=null;let t=this.messages.length>0;t||this.#v!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#fe():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#E.clear(),this.#be(null)),this.#v=null,this.#y=null,this.#b=null,this.#C=null,this.#ee(),t&&this.#te(`history_continuity_reset`,`This browser's conversation history was reset in another tab, so the previous messages were cleared.`)}#ge(){return this.#P?(this.#F||=this.#_e().finally(()=>{this.#F=null}),this.#F):Promise.resolve()}async#_e(){if(!this.isClientTokenMode())this.#P=!1;else try{this.bindActivatedSession(await this.client.initSession()),this.#P=!1}catch{}}reconcileBootConversation(e){let t=this.#Z,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#v;if(!t||!n)return Promise.resolve();let r=this.#$(e?.scope);this.#w=!0,this.#ee();let i=this.#ve(t,n,r).finally(()=>{this.#w=this.#C!==null,this.#T===i&&(this.#T=null),this.#ee()});return this.#T=i,i}async#ve(e,t,n){this.#v=t;let r=this.clientSession?.conversationRevision??this.#y??null,i=this.#j?this.#A:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#j=!1,this.#b=this.historyInternals.getStoredMessageCursor?.()??this.#b,await this.replayPendingProjections(),r&&i&&r===i){this.#y=r;return}let a=await e.getPage(t,{context:n}),o=this.#ie(a.messages),s=new Set(a.messages.map(e=>e.id)),c=this.messages.some(e=>s.has(e.id)),l=a.messages[0]?.createdAt,u;if(!c)u=o.map(e=>this.#pt(e));else{let e=this.#r?this.#i:null;u=Lo(this.messages.filter(t=>s.has(t.id)||t.id===e?!0:l!==void 0&&t.createdAt<l),o).map(e=>this.#pt(e))}this.#b=a.nextCursor,this.#y=a.conversationRevision||r||null,this.#O.clear();for(let e of a.messages)this.#O.set(e.id,e.content);this.#ue(),this.messages=this.#ht(u),this.callbacks.onMessagesChanged([...this.messages])}#ye(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#be(e){this.#k=e,this.historyInternals.setPendingDisplayProjections?.(e)}#xe(){return this.historyInternals.getPendingDisplayProjections?.()??this.#k}#Se(e){if(this.#ye())for(let t of e){let e=Io(t);e!==void 0&&this.#O.set(t.id,e)}}#Ce(){if(!this.#ye())return;let e=this.#v;if(!e)return;let t=[];for(let e of this.messages){if(e.role!==`assistant`||e.streaming)continue;let n=Io(e);n!==void 0&&this.#O.get(e.id)!==n&&t.push({id:e.id,displayContent:n})}t.length!==0&&(this.#be({conversationId:e,messageIds:t.map(e=>e.id)}),this.#we(e,t))}#we(e,t){let n=(this.#D??Promise.resolve()).catch(()=>{}).then(()=>this.#Te(e,t,!1)).finally(()=>{this.#D===n&&(this.#D=null)});this.#D=n}async#Te(e,t,n){if(this.#v!==e)return;let r=t.filter(e=>this.#O.get(e.id)!==e.displayContent);if(r.length===0)this.#De(e,t);else try{let{conversationRevision:n}=await this.client.finalizeDisplayProjections(e,r);for(let e of r)this.#O.set(e.id,e.displayContent);this.#v===e&&n&&(this.#y=n),this.#De(e,t)}catch(i){if(!n&&this.#Ee(i)){await this.#Te(e,r,!0);return}if(i instanceof uc&&(i.code===`not_found`||i.code===`conversation_deleted`)){this.#De(e,t);return}this.#te(`projection_finalization_failed`,`Some message formatting could not be saved for history; it will be retried.`)}}#Ee(e){return e instanceof uc?e.code===`request_failed`:e instanceof Error}#De(e,t){let n=this.#xe();if(!n||n.conversationId!==e)return;let r=new Set(t.map(e=>e.id)),i=n.messageIds.filter(e=>!r.has(e));this.#be(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#ye())return;let e=this.#xe();if(!e)return;if(this.#v&&e.conversationId!==this.#v){this.#be(null);return}let t=[];for(let n of e.messageIds){let e=this.messages.find(e=>e.id===n);e&&typeof e.content==`string`&&t.push({id:n,displayContent:e.content})}t.length===0?this.#be(null):(this.#we(e.conversationId,t),await this.#D?.catch(()=>{}))}#Oe(){this.#v&&(this.#y=null,this.historyInternals.setStoredConversationRevision?.(null))}async#ke(){await this.awaitHistorySettled(),await this.#ge(),this.#C===`new_conversation_required`&&await this.#ce()}static#Ae(e){return e instanceof uc&&e.code===`conversation_deleted`}async#je(t,n,r,i,a){this.#Se(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},this.handleEvent);return}catch(t){if(!e.#Ae(t))throw t;let o=await this.#Me(i);if(!o)throw t;this.#Se([o]),await this.client.dispatch({messages:[o],signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},this.handleEvent)}}async#Me(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let n={...t};this.#x+=1,this.#D=null,this.#fe(),this.#v=null,this.#y=null,this.#b=null,this.#S=!0;try{let e=this.#Z;if(e){let t=await e.prepareStartNew({context:this.#$()});await this.#ae(t)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#w=!0,this.#C=`new_conversation_required`,this.#ee(),this.#te(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`),null}finally{this.#S=!1}return this.#ft(n),this.#ct(!0),this.#te(`conversation_deleted_recovered`,`That conversation was deleted. Started a new conversation.`),this.messages.find(e=>e.id===n.id)??n}updateConfig(e){let t=this.config.features?.artifacts?.display,n={...this.config,...e},r=bs(this.config,n),i=al(this.config,n);this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&xs(n.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(n.features?.artifacts?.display);if(!i){this.client.updateConfig(n),a&&this.#We();return}this.#He(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.client=new _c(this.config,this.historyInternals),a&&this.#We(),this.#Fe(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:n,llmContent:r,contentParts:i,id:a,createdAt:o,sequence:s,streaming:c=!1,voiceProcessing:l,voiceCaption:u,rawContent:d}=e,f={id:a??(t===`user`?Ra():t===`assistant`?za():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:n,createdAt:o??(/* @__PURE__ */ new Date()).toISOString(),sequence:s??this.#mt(),streaming:c,...r!==void 0&&{llmContent:r},...i!==void 0&&{contentParts:i},...l!==void 0&&{voiceProcessing:l},...u&&{voiceCaption:u},...d!==void 0&&{rawContent:d}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:`assistant`})}injectUserMessage(e){return this.injectMessage({...e,role:`user`})}injectSystemMessage(e){return this.injectMessage({...e,role:`system`})}injectMessageBatch(e){let t=[];for(let n of e){let{role:e,content:r,llmContent:i,contentParts:a,id:o,createdAt:s,sequence:c,streaming:l=!1,voiceProcessing:u,rawContent:d}=n,f={id:o??(e===`user`?Ra():e===`assistant`?za():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:e,content:r,createdAt:s??(/* @__PURE__ */ new Date()).toISOString(),sequence:c??this.#mt(),streaming:l,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a},...u!==void 0&&{voiceProcessing:u},...d!==void 0&&{rawContent:d}};t.push(f)}return this.messages=this.#ht([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:r=``,llmContent:i,id:a,createdAt:o,sequence:s}=e,c={text:r,component:t,props:n};return this.injectMessage({role:`assistant`,content:r,rawContent:JSON.stringify(c),...i!==void 0&&{llmContent:i},...a!==void 0&&{id:a},...o!==void 0&&{createdAt:o},...s!==void 0&&{sequence:s}})}async#Ne(e,t,n){let r;try{r=await n()}catch{return}let i=r.blocks.join(`
19
19
 
20
20
  `),a=[i,t].filter(Boolean).join(`
21
21
 
22
- `),o=Array.isArray(e.contentParts)&&e.contentParts.length>0,s=r.contentParts.length>0;if(o){let t=[];i&&t.push(ki(i)),t.push(...r.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(s){let t=[];a&&t.push(ki(a)),t.push(...r.contentParts),e.contentParts=t}else i&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,t){let n=e.trim(),r=!!t?.replayFields&&(t.replayFields.llmContent!==void 0||t.replayFields.rawContent!==void 0||(t.replayFields.contextMentions?.length??0)>0);if(!n&&(!t?.contentParts||t.contentParts.length===0)&&(!t?.mentions||t.mentions.refs.length===0)&&!r)return;this.#U&&!t?.voiceTurn&&(this.#U.failed=!0,this.#U=null),(this.#T||this.#D||this.#w||this.#P)&&await this.#Oe(),this.stopSpeaking(),this.abortController?.abort(),this.#Ve(),this.#Ie++,this.#et();let i=t?.voiceTurn?.userMessageId,a=i?this.messages.find(e=>e.id===i&&e.role===`user`):void 0,o=a?.id??$s(),s=ec();this.#i=null;let c=t?.contentParts&&Di(t.contentParts)?zi:``,l={id:o,role:`user`,content:n||c,createdAt:(/* @__PURE__ */ new Date()).toISOString(),sequence:this.#ut(),viaVoice:t?.viaVoice||!1,...t?.contentParts&&t.contentParts.length>0&&{contentParts:t.contentParts},...t?.mentions&&t.mentions.refs.length>0&&{contextMentions:t.mentions.refs},...t?.contentSegments&&t.contentSegments.length>0&&{contentSegments:t.contentSegments},...t?.composerOptions&&{composerOptions:t.composerOptions},...t?.replayFields??{}};a?(a.viaVoice=!0,delete a.voiceCaption,a.content.trim()!==n&&(a.llmContent=n),this.callbacks.onMessagesChanged([...this.messages])):this.#ct(l),this.#it(!0);let u=new AbortController;if(this.abortController=u,t?.mentions){let e=this.messages.find(e=>e.id===o)??l;if(await this.#Me(e,n,t.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(t?.quote&&!t.replayFields){let e=this.messages.find(e=>e.id===o)??l,n=bc({quote:t.quote,text:e.llmContent??e.content,contentParts:e.contentParts});n.contentParts&&(e.contentParts=n.contentParts),n.llmContent!==void 0&&(e.llmContent=n.llmContent),(n.contentParts||n.llmContent!==void 0)&&(e.quote={...t.quote},this.callbacks.onMessagesChanged([...this.messages]))}let d=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:(/* @__PURE__ */ new Date()).toISOString()}]:[...this.messages];try{await this.#Ae(d,u,s,o,{composerOptions:t?.composerOptions,interrupt:t?.interrupt,voiceSpoken:!!t?.voiceTurn})}catch(e){if(this.status===`resuming`||this.#a)return;this.#U&&(this.#U.failed=!0);let t=e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`abort`));if(!t){let t=tl(e,this.config.errorMessage);if(t){let e={id:s,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:t,sequence:this.#ut()};this.#ct(e)}}this.#rt(`idle`),this.#it(!1),this.abortController=null,t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(Error(String(e))))}}resubmitFrom(e,t){let n=Sc(this.messages,e);if(!n)return!1;let r=this.messages[n.start],i=t.replacement,a=i?i.text:r.content,o=i?i.contentParts:r.contentParts;if(!(a?.trim()||(o?.length??0)>0||!i&&(r.llmContent?.trim()?.length??0)>0))return!1;let s=i?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},c=i?this.#Ne(i.options):r.composerOptions,l=i?i.contentSegments:r.contentSegments,u=i?i.options?.quote:void 0,d=i?i.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(a??``,{...o?.length?{contentParts:[...o]}:{},...l?.length?{contentSegments:[...l]}:{},...c?{composerOptions:c}:{},...u?{quote:u}:{},...s&&Object.keys(s).length>0?{replayFields:s}:{},viaVoice:d===!0}),!0}#Ne(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}async continueConversation(){if(this.streaming)return;(this.#T||this.#D||this.#w||this.#P)&&await this.#Oe(),this.abortController?.abort(),this.#et();let e=ec();this.#i=null,this.#it(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(t){if(this.status===`resuming`||this.#a)return;let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));if(!n){let n=tl(t,this.config.errorMessage);if(n){let t={id:e,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:n,sequence:this.#ut()};this.#ct(t)}}this.#rt(`idle`),this.#it(!1),this.abortController=null,n||(t instanceof Error?this.callbacks.onError?.(t):this.callbacks.onError?.(Error(String(t))))}}async connectStream(e,t){if(this.streaming&&!t?.allowReentry)return;t?.allowReentry||this.abortController?.abort(),t?.preserveAssistantId&&t.assistantMessageId&&(this.#i=t.assistantMessageId);let n=t?.preserveAssistantId?t.assistantMessageId:void 0,r=!1;for(let e of this.messages)e.streaming&&e.id!==n&&(e.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#it(!0);let i={};try{await this.client.processStream(e,e=>{let t=this.#t;this.#t=i;try{this.handleEvent(e)}finally{this.#t=t}},t?.assistantMessageId,t?.seedContent),this.#at(i)}catch(e){if(this.status===`resuming`||this.#a){this.#ot(i);return}this.#at(i),this.#rt(`error`),this.webMcpResolveControllers.size===0&&(this.#it(!1),this.abortController=null),this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))}}#Pe(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}if(e.signal?.aborted)return Promise.resolve(!1);let t={id:`webmcp-${++this.#d}`,status:`pending`,agentId:``,executionId:``,toolName:e.toolName,toolType:`webmcp`,description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},n=`approval-${t.id}`;return this.upsertMessage({id:n,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,approval:t}),new Promise(t=>{this.webMcpApprovalResolvers.set(n,t),e.signal?.addEventListener(`abort`,()=>this.resolveWebMcpApproval(n,`timeout`),{once:!0})})}resolveWebMcpApproval(e,t){let n=this.webMcpApprovalResolvers.get(e);if(!n)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(t=>t.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:t,resolvedAt:Date.now()}}),n(t===`approved`)}#Fe;#Ie;#Le(e){let t=this.#Fe??={s:this,setStreaming:e=>this.#it(e),appendMessage:e=>this.#ct(e),nextSequence:()=>this.#ut(),settleApprovalPausedToolCall:e=>this.#st(e),resumeAfter:e=>this.#r?.executionId===e?this.#r.lastEventId:void 0},n=to();if(n)return e(n,t);let r=this.#Ie;return $a().then(n=>r===this.#Ie?e(n,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))})}resolveApproval(e,t,n){return this.#Le((r,i)=>r.resolveApproval(i,e,t,n))}resolveAskUserQuestion(e,t){return this.#Le((n,r)=>n.resolveAskUserQuestion(r,e,t))}resolveWebMcpToolCall(e){return this.#Le((t,n)=>t.resolveWebMcpToolCall(n,e))}persistAskUserQuestionProgress(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}#Re(e){let t=e.agentMetadata?.executionId,n=e.toolCall?.id;if(!t||!n){let t=this.#u;queueMicrotask(()=>{t===this.#u&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(t);r||(r={snapshots:[],seen:/* @__PURE__ */ new Set},this.webMcpAwaitBatches.set(t,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(e))}#ze(){if(this.webMcpAwaitBatches.size===0)return;let e=this.#u;queueMicrotask(()=>{if(e===this.#u)for(let e of[...this.webMcpAwaitBatches.keys()])this.#Be(e)})}#Be(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:n}=t;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.#Le((t,r)=>t.resolveWebMcpToolCallBatch(r,e,n))}#Ve(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,`denied`);this.webMcpAwaitBatches.clear(),this.#u++}cancel(){this.abortController?.abort(),this.abortController=null,this.#et(),this.#Ve(),this.#Ie++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#it(!1),this.#rt(`idle`)}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#et(),this.#Ve(),this.#Ie++,this.messages=[],this.agentExecution=null,this.#We(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#it(!1),this.#rt(`idle`),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#l}selectArtifact(e){this.#l=e,this.#Ge()}clearArtifacts(){this.#We()}upsertArtifact(e){let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=e.artifactType===`markdown`?{id:t,artifactType:`markdown`,title:e.title,status:`complete`,markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:t,artifactType:`component`,title:e.title,status:`complete`,component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(t,n),this.#l=t,this.#Ge(),e.transcript!==!1&&this.#He(n),n}#He(e){let t=`artifact-ref-${e.id}`,n=ke(Oe(this.config.features?.artifacts,e),{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:`complete`,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown===void 0?{}:{markdown:e.markdown}}),r=this.messages.find(e=>e.id===t);r?(r.rawContent=n,r.streaming=!1,this.callbacks.onMessagesChanged([...this.messages])):this.injectAssistantMessage({id:t,content:``,rawContent:n})}#Ue(){let e=!1;for(let t of this.artifacts.values()){let n=this.messages.find(e=>e.id===`artifact-ref-${t.id}`);if(!n)continue;let r=ke(Oe(this.config.features?.artifacts,t),{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown===void 0?{}:{markdown:t.markdown}});n.rawContent!==r&&(n.rawContent=r,n.streaming=t.status===`streaming`,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#We(){(this.artifacts.size!==0||this.#l!==null)&&(this.artifacts.clear(),this.#l=null,this.#Ge())}#Ge(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#l})}#Ke(e){switch(e.type){case`artifact_start`:e.artifactType===`markdown`?this.artifacts.set(e.id,{id:e.id,artifactType:`markdown`,title:e.title,status:`streaming`,markdown:``,...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:`component`,title:e.title,status:`streaming`,component:e.component??``,props:{}}),this.#l=e.id;break;case`artifact_delta`:{let t=this.artifacts.get(e.id);t?.artifactType===`markdown`&&(t.markdown=(t.markdown??``)+e.artDelta);break}case`artifact_update`:{let t=this.artifacts.get(e.id);t?.artifactType===`component`&&(t.props={...t.props,...e.props},e.component&&(t.component=e.component));break}case`artifact_complete`:{let t=this.artifacts.get(e.id);t&&(t.status=`complete`);break}default:return}this.#Ge()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#et(),this.#Ve(),this.#Ie++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#dt(e.map(e=>({...e,streaming:!1,sequence:e.sequence??this.#ut()}))),this.#it(!1),this.#rt(`idle`),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let t of e)this.artifacts.set(t.id,{...t,status:`complete`});this.#l=t,this.#Ge()}#qe(e){let t=this.agentExecution?.executionId;if(!t||!this.#i||this.agentExecution?.status!==`running`)return;let n=this.#r===null;this.#r={executionId:t,lastEventId:e,assistantMessageId:this.#i,status:`running`},this.#nt(n)}#Je(){return this.#r!==null&&typeof this.config.reconnectStream==`function`&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#Ye()}#Ye(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant===`approval`&&e.approval?.status===`pending`)}#Xe(){this.#a||this.#r&&typeof this.config.reconnectStream==`function`&&(this.#a=!0,this.callbacks.onReconnect?.({phase:`paused`,handle:this.#r}),this.#it(!0),this.#rt(`resuming`),this.#Ze().then(e=>{this.#a&&this.#r&&e.begin()}))}#Ze(){return this.#o?Promise.resolve(this.#o):(this.#s||(this.#s=Zc().then(({createReconnectController:e})=>{let t=e(this.#Qe());return this.#o=t,t}),this.#s.catch(()=>{this.#s=null})),this.#s)}#Qe(){let e=this;return{get config(){return e.config},getResumable:()=>e.#r,clearResumable:()=>e.#tt(),getStatus:()=>e.status,setStatus:t=>e.#rt(t),setStreaming:t=>e.#it(t),setReconnecting:t=>{e.#a=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,n,r)=>e.connectStream(t,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:t=>e.#ct(t),nextSequence:()=>e.#ut(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>tl(Error(t),e.config.errorMessage),onError:t=>e.callbacks.onError?.(t)}}reconnectNow(){this.#a?this.#o?.wake():this.#Xe()}resumeFromHandle(e){if(typeof this.config.reconnectStream!=`function`||this.#a)return;let t=this.#$e();t||(t=ec(),this.#ct({id:t,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:this.#ut()})),this.#i=t,this.agentExecution||={executionId:e.executionId,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0},this.#r={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:`running`},this.#Xe()}#$e(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role===`assistant`&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role===`user`)break}return null}#et(){this.#a=!1,this.#o?.teardown(),this.#tt()}#tt(){this.#c&&=(clearTimeout(this.#c),null);let e=this.#r!==null;this.#r=null,e&&this.config.onExecutionState?.(null)}#nt(e){let t=this.config.onExecutionState;t&&(e?(this.#c&&=(clearTimeout(this.#c),null),t(this.#r)):this.#c||=setTimeout(()=>{this.#c=null,this.config.onExecutionState?.(this.#r)},500))}getResumableHandle(){return this.#r}#rt(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#it(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&(this.#at(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(e){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider===`browser`||t.provider===`runtype`&&t.browserFallback))return;let n=[...this.messages].reverse().find(e=>e.role===`assistant`&&e.content&&!e.voiceProcessing);if(!n||e&&!e.includes(n.id))return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=Fc(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return Ec(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||t.role!==`assistant`)return;let n=Fc(t.content||``);if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<`u`&&`speechSynthesis`in window&&window.speechSynthesis.cancel()}#at(e){for(let[t,n]of[...this.#e])n===e&&(this.#e.delete(t),this.#st(t))}#ot(e){for(let[t,n]of this.#e)n===e&&this.#e.set(t,void 0)}#st(e){let t=this.messages.find(t=>t.id===e)?.approval,n=t?.toolCallId,r=n&&this.messages.find(e=>e.toolCall?.id===n),i=r&&r.toolCall;if(!i||i.status===`complete`||t.status===`pending`)return;let a={...i,status:`complete`,approvalStatus:t.status,completedAt:Date.now(),...t.status===`approved`?{superseded:!0}:{success:!1,error:t.status===`denied`?`Denied`:`Approval timed out`}};this.upsertMessage({...r,streaming:!1,toolCall:a})}#ct(e){let t=this.#lt(e);this.messages=this.#dt([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#lt(e),n=this.messages.findIndex(e=>e.id===t.id);n===-1?this.#ct(t):(this.messages=this.messages.map((e,r)=>{if(r!==n)return e;let i={...e,...t};e.agentMetadata?.askUserQuestionAnswered===!0&&t.agentMetadata&&(i.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),e.agentMetadata?.suggestRepliesResolved===!0&&t.agentMetadata&&(i.agentMetadata={...i.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let n=e.approval,r=t.approval;i.approval={...n,...r,executionId:r.executionId||n.executionId,toolName:r.toolName||n.toolName,description:r.description||n.description,toolType:r.toolType??n.toolType,reason:r.reason??n.reason,parameters:r.parameters??n.parameters,toolCallId:r.toolCallId??n.toolCallId}}let o=t.toolCall?.name,s=t.agentMetadata?.executionId,c=t.toolCall?.id;if(o&&nl(o)&&s&&c&&t.agentMetadata?.awaitingLocalTool===!0){let t=`${s}:${c}`,n=this.webMcpInflightKeys.has(t),r=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,o=e.agentMetadata?.executionId===s&&e.toolCall?.id===c&&a!==void 0&&nl(a)&&e.toolCall?.status===`complete`;(n||r||o)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=e.toolCall,i.streaming=e.streaming)}return i}),this.messages=this.#dt(this.messages),this.callbacks.onMessagesChanged([...this.messages]))}#lt(e){return e.sequence===void 0?{...e,sequence:this.#ut()}:{...e}}#ut(){return this.#n++}#dt(e){return[...e].sort((e,t)=>{let n=new Date(e.createdAt).getTime(),r=new Date(t.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(r)&&n!==r)return n-r;let i=e.sequence??0,a=t.sequence??0;return i===a?e.id.localeCompare(t.id):i-a})}};H(),A(),I(),Ui();const il={add:e=>Fi(e)},al=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,ol={allowedTypes:Hi,maxFileSize:10485760,maxFiles:4};function sl(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function cl(e){return e===`application/pdf`||e.startsWith(`text/`)||e.includes(`word`)?f.FileText:e.includes(`excel`)||e.includes(`spreadsheet`)?f.FileSpreadsheet:e===`application/json`?f.FileCode:f.File}var ll=class e{#e;#t;#n;constructor(e={}){this.attachments=[],this.#e=null,this.#t=/* @__PURE__ */ new Map,this.#n=!1,this.config={allowedTypes:e.allowedTypes??ol.allowedTypes,maxFileSize:e.maxFileSize??ol.maxFileSize,maxFiles:e.maxFiles??ol.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#r(){return typeof this.config.adapter?.add==`function`}#i(){return this.#r()?this.config.adapter:il}setPreviewsContainer(e){this.#e=e}remountPreviews(e){if(this.#e=e,e){e.innerHTML=``;for(let e of this.attachments)this.#l(e)}this.#f()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:ol.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status===`ready`)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){e&&e.length!==0&&await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#n)return;let t=[];for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,`count`);continue}let e=Ii(n,this.config.allowedTypes,this.config.maxFileSize);if(!e.valid){let t=e.error?.includes(`type`)?`type`:`size`;this.config.onFileRejected?.(n,t);continue}let r={id:sl(),file:n,previewUrl:Pi(n)?URL.createObjectURL(n):null,contentPart:null,status:this.#r()?`uploading`:`processing`,progress:this.#r()?0:void 0};this.attachments.push(r),this.#l(r),t.push(r)}this.#f(),this.#c(),await Promise.all(t.map(e=>this.#a(e)))}async#a(e){let t=new AbortController;this.#t.set(e.id,t);let n=()=>this.#n||t.signal.aborted||this.#t.get(e.id)!==t||!this.attachments.includes(e);try{let r=await this.#i().add(e.file,{signal:t.signal,onProgress:t=>{n()||e.status!==`uploading`||(e.progress=al(t),this.#u(e),this.#c())}});if(n())return;e.contentPart=r,e.status=`ready`,e.progress=void 0,e.error=void 0}catch(t){if(n())return;e.status=`error`,e.progress=void 0,e.error=t instanceof Error?t.message:String(t??`Upload failed`)}finally{this.#t.get(e.id)===t&&this.#t.delete(e.id)}this.#u(e),this.#c()}retryAttachment(e){let t=this.attachments.find(t=>t.id===e);!t||t.status!==`error`||this.#n||(t.status=this.#r()?`uploading`:`processing`,t.progress=this.#r()?0:void 0,t.error=void 0,this.#u(t),this.#c(),this.#a(t))}#o(e){let t=this.#t.get(e);t&&(this.#t.delete(e),t.abort())}removeAttachment(e){let t=this.attachments.findIndex(t=>t.id===e);if(t===-1)return;let n=this.attachments[t];this.#o(e),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let r=this.#e?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),n.status===`ready`&&n.contentPart&&this.#s(n.contentPart),this.#f(),this.#c()}#s(e){let t=this.config.adapter?.remove;if(t)try{let n=t(e,{signal:new AbortController().signal});n&&typeof n.catch==`function`&&n.catch(e=>{console.error(`[AttachmentManager] adapter.remove failed:`,e)})}catch(e){console.error(`[AttachmentManager] adapter.remove failed:`,e)}}clearAttachments(){for(let e of this.attachments)this.#o(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=``),this.#f(),this.#c()}destroy(){if(!this.#n){this.#n=!0;for(let e of this.#t.values())e.abort();this.#t.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#e=null}}#c(){this.#n||this.config.onAttachmentsChange?.(this.getAttachments())}#l(e){if(!this.#e)return;let t=Pi(e.file),n=B(`div`,`persona-attachment-preview persona-relative persona-inline-block`);if(n.setAttribute(`data-attachment-id`,e.id),n.style.width=`48px`,n.style.height=`48px`,t&&e.previewUrl){let t=B(`img`);t.src=e.previewUrl,t.alt=e.file.name,t.className=`persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200`,t.style.width=`48px`,t.style.height=`48px`,t.style.objectFit=`cover`,t.style.borderRadius=`8px`,n.appendChild(t)}else{let t=B(`div`);t.style.width=`48px`,t.style.height=`48px`,t.style.borderRadius=`8px`,t.style.backgroundColor=`var(--persona-container, #f3f4f6)`,t.style.border=`1px solid var(--persona-border, #e5e7eb)`,t.style.display=`flex`,t.style.flexDirection=`column`,t.style.alignItems=`center`,t.style.justifyContent=`center`,t.style.gap=`2px`,t.style.overflow=`hidden`;let r=cl(e.file.type),i=k(r,20,`var(--persona-muted, #6b7280)`,1.5);i&&t.appendChild(i);let a=B(`span`);a.textContent=Ri(e.file.type,e.file.name),a.style.fontSize=`8px`,a.style.fontWeight=`600`,a.style.color=`var(--persona-muted, #6b7280)`,a.style.textTransform=`uppercase`,a.style.lineHeight=`1`,t.appendChild(a),n.appendChild(t)}let r=V(`div`,{className:`persona-attachment-status`,attrs:{"data-persona-attachment-status":``}}),i=B(`div`,`persona-attachment-progress`);i.appendChild(B(`div`,`persona-attachment-progress__bar`));let a=V(`button`,{className:`persona-attachment-retry`,attrs:{type:`button`,"aria-label":`Retry upload`}}),o=F(`rotate-cw`,12,`var(--persona-text-inverse, #ffffff)`,2);o?a.appendChild(o):a.textContent=`↻`,a.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.retryAttachment(e.id)}),r.append(i,a),n.appendChild(r);let s=B(`button`,`persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center`);s.type=`button`,s.setAttribute(`aria-label`,`Remove attachment`),s.style.position=`absolute`,s.style.top=`-4px`,s.style.insetInlineEnd=`-4px`,s.style.width=`18px`,s.style.height=`18px`,s.style.borderRadius=`50%`,s.style.backgroundColor=`var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))`,s.style.border=`none`,s.style.cursor=`pointer`,s.style.display=`flex`,s.style.alignItems=`center`,s.style.justifyContent=`center`,s.style.padding=`0`;let c=k(f.X,10,`var(--persona-text-inverse, #ffffff)`,2);c?s.appendChild(c):(s.textContent=`×`,s.style.color=`var(--persona-text-inverse, #ffffff)`,s.style.fontSize=`14px`,s.style.lineHeight=`1`),s.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.removeAttachment(e.id)}),n.appendChild(s),this.#e.appendChild(n),this.#d(n,e)}#u(e){let t=this.#e?.querySelector(`[data-attachment-id="${e.id}"]`);t&&this.#d(t,e)}#d(e,t){e.dataset.status=t.status;let n=t.status!==`ready`&&t.status!==`error`;e.setAttribute(`aria-busy`,n?`true`:`false`),e.title=t.status===`error`?`${t.file.name}: ${t.error??`Upload failed`}`:t.file.name;let r=e.querySelector(`.persona-attachment-progress__bar`);if(r){let e=t.progress;r.style.width=typeof e==`number`?`${Math.round(e*100)}%`:``}}#f(){this.#e&&(this.#e.style.display=this.attachments.length>0?`flex`:`none`)}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n,adapter:t?.adapter})}};const ul=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),dl=(e,t)=>e.length===t.length&&e.every((e,n)=>{let r=t[n];return e.id===r.id&&e.name===r.name&&e.mimeType===r.mimeType&&e.size===r.size&&e.status===r.status&&e.progress===r.progress&&e.error===r.error});function fl(){let e={text:``,attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=/* @__PURE__ */ new Set,n=null,r=!1,i=!1,a=()=>e.preparing?`preparing`:e.streaming?`streaming`:`idle`,o=()=>{let t=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(e=>Object.freeze({...e}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:t,inputDisabled:e.inputDisabled,sendDisabled:t!==`idle`||e.sendDisabled||e.inputDisabled})},s=()=>(n||=o(),n),c=()=>{if(r=!1,i||t.size===0)return;let e=s();for(let n of[...t])try{n(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] composer state listener failed:`,e)}},l=()=>{n=null,!(i||r)&&(r=!0,queueMicrotask(c))};return{getState:s,subscribe:e=>(t.add(e),()=>t.delete(e)),setText:t=>{e.text!==t&&(e.text=t,l())},setAttachments:t=>{dl(e.attachments,t)||(e.attachments=[...t],l())},setMentionRefs:t=>{ul(e.mentionRefs,t)||(e.mentionRefs=[...t],l())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,l())},setActiveModeIds:t=>{ul(e.activeModeIds,t)||(e.activeModeIds=[...t],l())},setQuote:t=>{let n=e.quote;(n?.text!==t?.text||n?.messageId!==t?.messageId||n?.sourceLabel!==t?.sourceLabel)&&(e.quote=t?{...t}:void 0,l())},setPendingSubmission:t=>{e.pendingSubmission!==t&&(e.pendingSubmission=t,l())},setPreparing:t=>{e.preparing!==t&&(e.preparing=t,l())},setStreaming:t=>{e.streaming!==t&&(e.streaming=t,l())},setInputDisabled:t=>{e.inputDisabled!==t&&(e.inputDisabled=t,l())},setSendDisabled:t=>{e.sendDisabled!==t&&(e.sendDisabled=t,l())},flush:()=>{r&&c()},destroy:()=>{i=!0,r=!1,t.clear()}}}H();const pl=(e,...t)=>{for(let n of t){let t=e.querySelector(n);if(t)return t}return null},ml=(e,t)=>{let n=B(`div`,e);return n.setAttribute(t,``),n.setAttribute(`data-persona-composer-synthesized`,``),n.style.display=`contents`,n};function hl(e,t={}){let n=pl(e,`[data-persona-composer-form]`),r=pl(e,`[data-persona-composer-input]`);if(!n||!r){let e=`[Persona] composer surface is missing required element(s): ${[!n&&`form`,!r&&`input`].filter(Boolean).join(`, `)}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||r))throw Error(e);return typeof console<`u`&&console.warn(e),null}let i={header:pl(e,`[data-persona-composer-header]`),body:pl(e,`[data-persona-composer-body]`),actionsStart:pl(e,`[data-persona-composer-actions-start]`,`.persona-widget-composer__left-actions`),actionsEnd:pl(e,`[data-persona-composer-actions-end]`,`.persona-widget-composer__right-actions`),actionsRow:pl(e,`[data-persona-composer-actions]`,`.persona-widget-composer .persona-flex.persona-items-center.persona-justify-between`),suggestions:pl(e,`[data-persona-composer-suggestions]`,`.persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2`),status:pl(e,`[data-persona-composer-status]`)},a=/* @__PURE__ */ new Set,o=i.header;o||(a.add(`header`),o=ml(`persona-widget-composer__header`,`data-persona-composer-header`),n.parentNode?n.parentNode.insertBefore(o,n):e.appendChild(o));let s=i.body??r.parentElement??n,c=(e,t,n,r,i)=>{if(t)return t;a.add(e);let o=ml(n,r);return i.appendChild(o),o},l=c(`actionsStart`,i.actionsStart,`persona-widget-composer__left-actions`,`data-persona-composer-actions-start`,n),u=c(`actionsEnd`,i.actionsEnd,`persona-widget-composer__right-actions`,`data-persona-composer-actions-end`,n),d=c(`suggestions`,i.suggestions,`persona-widget-composer__suggestions`,`data-persona-composer-suggestions`,e),f=c(`status`,i.status,`persona-widget-composer__status`,`data-persona-composer-status`,e),p=[],m=(e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler,h=pl(e,`[data-persona-composer-attachment-input]`,`input[type="file"]`)??void 0;return{footer:e,form:n,input:r,header:o,body:s,actionsStart:l,actionsEnd:u,suggestions:d,status:f,attachmentInput:h,attachmentPreviews:pl(e,`[data-persona-composer-attachment-previews]`,`.persona-attachment-previews`)??void 0,attachmentButton:pl(e,`[data-persona-composer-attachment-button]`,`.persona-attachment-button`)??void 0,sendButton:pl(e,`[data-persona-composer-submit]`)??void 0,micButton:pl(e,`[data-persona-composer-mic]`)??void 0,synthesized:a,found:i,addListener:(e,t,n,r)=>{e.addEventListener(t,n,r),p.push({target:e,type:t,handler:n,options:r})},removeListener:(e,t,n,r)=>{e.removeEventListener(t,n,r),p=p.filter(r=>!m(r,{target:e,type:t,handler:n}))},destroy:()=>{for(let e of p)e.target.removeEventListener(e.type,e.handler,e.options);p=[]}}}function gl(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function _l(e){let{anchor:t,content:n,placement:r=`bottom-start`,offset:i=6,matchAnchorWidth:a=!1,horizontalOffset:o,verticalOffset:s,zIndex:c=2147483e3,onOpen:l,onDismiss:u}=e,d=e.container??gl(t),f=!1,p=null,m=()=>{if(!f)return;let e=t.getBoundingClientRect();n.style.position=`fixed`,a&&(n.style.minWidth=`${e.width}px`),o&&(n.style.maxWidth=`${e.width}px`);let c=n.getBoundingClientRect(),l=s?.()??null,u=l==null?e.top:e.top+l,d=r===`top-start`||r===`top-end`?u-i-c.height:e.bottom+i,p=r===`bottom-end`||r===`top-end`?e.right-c.width:e.left,m=o?.()??null;if(m!=null){let t=Math.max(e.left,e.right-c.width);p=Math.min(Math.max(e.left+m,e.left),t)}n.style.top=`${d}px`,n.style.left=`${p}px`},h=()=>{f&&(f=!1,p&&=(p(),null),n.remove())},g=()=>{if(f)return;f=!0,c!=null&&(n.style.zIndex=String(c)),d.appendChild(n),m();let e=(t.ownerDocument??document).defaultView??window,r=t.ownerDocument??document,i=()=>{t.isConnected?m():(h(),u?.(`anchor-removed`))},a=e=>{let r=typeof e.composedPath==`function`?e.composedPath():[];r.includes(n)||r.includes(t)||(h(),u?.(`outside`))},o=e.setTimeout(()=>{r.addEventListener(`pointerdown`,a,!0)},0);e.addEventListener(`scroll`,i,!0),e.addEventListener(`resize`,i),p=()=>{e.clearTimeout(o),r.removeEventListener(`pointerdown`,a,!0),e.removeEventListener(`scroll`,i,!0),e.removeEventListener(`resize`,i)},l?.()};return{get isOpen(){return f},open:g,close:h,toggle:()=>f?h():g(),reposition:m,destroy:h}}H(),I(),da();const vl=[`--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`],yl=`data-persona-menu-focus`,bl=/* @__PURE__ */ new Set([`ArrowDown`,`ArrowUp`,`Home`,`End`]);function xl(e){return e.getAttribute(`role`)===`menuitem`?e:e.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`)??e}const Sl=e=>e.disabled===!0||e.getAttribute(`aria-disabled`)===`true`;function Cl(e){let t=e.label,n=!1,r=B(`div`,`persona-send-button-wrapper`),i=V(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${ta} ${na}`,attrs:{type:`button`,"aria-haspopup":`menu`,"aria-expanded":`false`,"data-persona-composer-overflow-trigger":``}});r.appendChild(i);let a=V(`div`,{className:`persona-composer-overflow-menu`,attrs:{role:`menu`,tabindex:`-1`,"data-persona-composer-overflow-menu":``}}),o=()=>{let t=e.getButtonSize?.()??``;i.style.width=t,i.style.height=t,i.style.minWidth=t,i.style.minHeight=t,i.style.lineHeight=`1`,i.replaceChildren();let n=F(`plus`,24,`currentColor`,1.5);n?i.appendChild(n):i.textContent=`+`},s=()=>{i.setAttribute(`aria-label`,t),i.setAttribute(`title`,t),a.setAttribute(`aria-label`,t)};s(),o();let c=[],l=-1,u=!1,d=()=>{let e=a.getRootNode().activeElement;return e instanceof HTMLElement?e:null},f=()=>{let e=d();for(let t of c){let n=!!e&&xl(t)===e;t.toggleAttribute(yl,n&&u)}},p=()=>c.filter(e=>e.isConnected||a.contains(e)).map(xl).filter(e=>!Sl(e)),m=(e,t)=>{e.forEach((e,n)=>{e.setAttribute(`tabindex`,n===t?`0`:`-1`)})},h=e=>{let t=p();if(t.length===0)return;let n=(e%t.length+t.length)%t.length;l=n,m(t,n),t[n].focus(),f()},g=()=>r.ownerDocument??document,_=null,v=null,y=null,b=()=>{_&&=(g().removeEventListener(`focusin`,_,!0),null)},x=()=>{v&&=(a.removeEventListener(`focusin`,v),null),y&&=(a.removeEventListener(`pointerdown`,y,!0),null)},S=null,C=()=>(S||=_l({anchor:i,content:a,placement:`top-start`,offset:6,onDismiss:()=>{i.setAttribute(`aria-expanded`,`false`),b()}}),S),w=()=>S?.isOpen===!0,T=(e=!1)=>{if(w()){S?.close(),i.setAttribute(`aria-expanded`,`false`),b(),x(),l=-1,u=!1;for(let e of c)e.removeAttribute(yl);e&&i.focus()}},E=(e=0,t=!1)=>{if(n||w())return;u=t,ra(i,a,vl),C().open(),i.setAttribute(`aria-expanded`,`true`);let o=p();m(o,-1),h(e<0?o.length-1:e),_=e=>{let t=typeof e.composedPath==`function`?e.composedPath():[];t.includes(a)||t.includes(r)||T()},g().addEventListener(`focusin`,_,!0),v=()=>f(),a.addEventListener(`focusin`,v),y=()=>{u=!1},a.addEventListener(`pointerdown`,y,!0)},D=e=>{e.preventDefault(),e.stopPropagation(),w()?T(!0):E(0)},O=e=>{e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),u=!0,w()?h(0):E(0,!0)):e.key===`ArrowUp`&&(e.preventDefault(),u=!0,w()?h(-1):E(-1,!0))},ee=e=>{switch(bl.has(e.key)&&(u=!0),e.key){case`ArrowDown`:e.preventDefault(),h(l+1);return;case`ArrowUp`:e.preventDefault(),h(l-1);return;case`Home`:e.preventDefault(),h(0);return;case`End`:e.preventDefault(),h(p().length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),T(!0);return;case`Tab`:T(!0);return}};return i.addEventListener(`click`,D),i.addEventListener(`keydown`,O),a.addEventListener(`keydown`,ee),{trigger:r,triggerButton:i,panel:a,setItems:e=>{for(let t of c)e.includes(t)||t.removeAttribute(yl);if(c=[...e],!w())return;let t=p();m(t,Math.min(l,t.length-1)),f()},isOpen:w,open:()=>E(0),close:T,setLabel:e=>{e!==t&&(t=e,s())},applyButtonSize:o,destroy:()=>{n=!0,b(),x(),i.removeEventListener(`click`,D),i.removeEventListener(`keydown`,O),a.removeEventListener(`keydown`,ee),S?.destroy(),S=null,r.remove(),a.remove(),c=[]}}}H(),I(),Ir(),da();const wl={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Tl=`data-persona-composer-action`,El=`data-persona-composer-disable-when-streaming`,Dl=e=>e===`core:attachment`?`attachments`:e.startsWith(`core:mention`)?`mentions`:null;function Ol(e,t){if(e===void 0)return null;if(typeof e==`number`)return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let r=B(`div`);r.style.position=`absolute`,r.style.visibility=`hidden`,r.style.pointerEvents=`none`,r.style.height=`0`,r.style.width=e,t.appendChild(r);let i=r.getBoundingClientRect().width;return r.remove(),Number.isFinite(i)&&i>0?i:Number.isFinite(n)?n:null}function kl(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let r=n.getComputedStyle(e),i=(Number.parseFloat(r.paddingLeft)||0)+(Number.parseFloat(r.paddingRight)||0);return Math.max(0,t-i)}const Al=(e,t)=>{e&&typeof console<`u`&&console.warn(t)},jl=(e,t)=>t.includes(`:`)?t:`${e}:${t}`;function Ml(e){let{debug:t}=e,n=[],r=/* @__PURE__ */ new Map,i=0,a=e=>{let i=r.get(e.id);i?Al(t,`[Persona] composer action "${e.id}" is already contributed by ${Nl(i)}; the ${Nl(e)} copy is ignored.`):(r.set(e.id,e),n.push(e))};for(let t of e.builtIns)a({id:t.id,placement:t.placement,presentation:`bar`,order:t.order,sequence:i++,source:`core`,builtIn:t});let o=(e,n,r)=>{let o=r?jl(r,e.id):e.id,s=e.order??wl.custom;e.placement===`end`&&s>=wl.send&&(Al(t,`[Persona] composer action "${o}" ordered at ${s} would render after send; clamped to ${wl.send-1}.`),s=wl.send-1),a({id:o,placement:e.placement,presentation:e.presentation??`bar`,order:s,sequence:i++,source:n,pluginId:r,action:e})};for(let t of e.configActions??[])o(t,`config`);for(let t of e.plugins){if(!t.contributeComposerActions)continue;let n;try{n=t.contributeComposerActions(e.contributionContext)}catch(e){typeof console<`u`&&console.error(`[Persona] plugin "${t.id}" contributeComposerActions failed:`,e);continue}for(let e of n??[])o(e,`plugin`,t.id)}return n.sort((e,t)=>e.order===t.order?e.sequence-t.sequence:e.order-t.order)}const Nl=e=>e.source===`plugin`?`plugin "${e.pluginId}"`:e.source===`config`?`composer.actions`:`a core built-in`,Pl=(e,t,n)=>e===void 0?n:typeof e==`function`?e(t)===!0:e===!0,Fl=e=>e.phase===`streaming`||e.text.trim().length>0||e.attachments.length>0;function Il(e,t){if(!e||e===`always`)return!0;let n=Fl(t);return e===`when-text`?n:!n}const Ll=e=>e.kind===`custom`,Rl=e=>e instanceof HTMLButtonElement?e:e.querySelector(`button`)??e,zl=e=>{let t=Rl(e);return t.getAttribute(`aria-label`)?.trim()||t.getAttribute(`title`)?.trim()||``};function Bl(e){let t=``,n=e=>{if(e.nodeType===Node.TEXT_NODE){t+=e.nodeValue??``;return}if(e.nodeType!==Node.ELEMENT_NODE)return;let r=e;typeof r.matches==`function`&&r.matches(`.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]`)||e.childNodes.forEach(n)};return n(e),t.trim()}const Vl=e=>Bl(e).length===0;function Hl(e){let t=/* @__PURE__ */ new Map,n=[],r=!1,i=()=>e.getButtonSize?.(),a=(e,t)=>{let n=e.button;if(!n)return;n.setAttribute(`role`,`menuitem`),n.setAttribute(`tabindex`,`-1`),n.className=`persona-composer-overflow-menu__item`;for(let e of[`width`,`height`,`minWidth`,`minHeight`,`fontSize`,`color`,`backgroundColor`])n.style[e]=``;n.style.lineHeight=`1`,t.tooltipText?n.setAttribute(`title`,t.tooltipText):n.removeAttribute(`title`),n.replaceChildren();let r=B(`span`,`persona-composer-overflow-menu__icon`);if(t.iconName){let e=F(t.iconName,16,`currentColor`,1.5);e&&r.appendChild(e)}let i=B(`span`,`persona-composer-overflow-menu__label`);i.textContent=t.shortLabel??t.label,n.append(r,i)},o=(e,t)=>{let n=e.button;if(!n)return;if(n.setAttribute(`aria-label`,t.label),t.pressed===void 0?n.removeAttribute(`aria-pressed`):n.setAttribute(`aria-pressed`,t.pressed?`true`:`false`),n.toggleAttribute(El,t.disableWhenStreaming===!0),e.mode===`menu`){e.tooltip?.destroy(),e.tooltip=void 0,a(e,t);return}n.removeAttribute(`role`),n.removeAttribute(`tabindex`),n.removeAttribute(`title`);let r=i(),o=!!t.shortLabel;if(n.className=Qe(`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button`,ta,na,o&&`persona-composer-action-button--text persona-gap-1 persona-text-sm`),n.style.width=r&&!o?r:``,n.style.height=r??``,n.style.minWidth=r&&!o?r:``,n.style.minHeight=r??``,n.style.fontSize=o?``:`18px`,n.style.lineHeight=`1`,n.style.color=t.iconColor??``,n.style.backgroundColor=t.backgroundColor??``,n.replaceChildren(),t.iconName){let e=F(t.iconName,24,`currentColor`,1.5);e&&n.appendChild(e)}if(o){let e=B(`span`,`persona-composer-action-button__label`);e.textContent=t.shortLabel,n.appendChild(e)}else n.firstChild||(n.textContent=t.label);e.tooltip?.destroy(),e.tooltip=yr({anchor:n,trigger:e.element,text:()=>t.tooltipText??t.label,enabled:!!t.tooltipText})},s=(t,n)=>{let r=t.action,i=V(`button`,{attrs:{type:`button`}}),a=i;if(n===`bar`){let e=B(`div`,`persona-send-button-wrapper`);e.appendChild(i),a=e}a.setAttribute(Tl,t.id);let s={resolved:t,element:a,button:i,owned:!0,managed:!0,busy:!1,visible:!0,mode:n},c=t=>{if(t.preventDefault(),t.stopPropagation(),s.busy||i.disabled)return;let n=s.resolved.action;s.mode===`menu`&&p?.close(!0);let r;try{r=n.onSelect(e.actionContext,t)}catch(t){e.reportError(t,{actionId:s.resolved.id});return}r&&typeof r.then==`function`&&(s.busy=!0,i.setAttribute(`aria-busy`,`true`),r.catch(t=>{e.reportError(t,{actionId:s.resolved.id})}).finally(()=>{s.busy=!1,i.removeAttribute(`aria-busy`)}))};return i.addEventListener(`click`,c),s.detach=()=>i.removeEventListener(`click`,c),o(s,r),s},c=t=>{let n=t.action,r;try{r=n.render({...e.actionContext,id:t.id,action:n})}catch(n){return e.reportError(n,{actionId:t.id}),null}return r?.element?(r.element.setAttribute(Tl,t.id),r.element.toggleAttribute(El,n.disableWhenStreaming===!0),{resolved:t,element:r.element,owned:!0,managed:!0,destroy:r.destroy,busy:!1,visible:!0,mode:`bar`}):null},l=(e,t)=>{if(e.builtIn){let t=e.builtIn.element;return t?{resolved:e,element:t,owned:!1,managed:e.builtIn.managed===!0,busy:!1,visible:!0,mode:`bar`}:null}let n=e.action;return n?Ll(n)?c(e):s(e,t):null},u=t=>{if(t.detach?.(),t.tooltip?.destroy(),t.detachMenuSlot?.(),t.detachMenuSlot=void 0,t.menuLabel?.remove(),t.menuLabel=void 0,t.menuSlot?.remove(),t.menuSlot=void 0,t.owned){try{t.destroy?.()}catch(n){e.reportError(n,{actionId:t.resolved.id})}t.element.remove()}},d=(e,t)=>{for(let n=0;n<t.length;n++){let r=t[n];if(!r.managed)continue;let i=null;for(let r=n+1;r<t.length;r++){let n=t[r];if(!n.managed&&n.element.parentElement===e){i=n.element;break}}i?(r.element.parentElement!==e||r.element.nextSibling!==i)&&e.insertBefore(r.element,i):e.lastChild!==r.element&&e.appendChild(r.element)}},f=(e,t)=>{if(e.button){e.button.disabled=t;return}if(!e.owned)return;let n=e.element;n.toggleAttribute(`data-disabled`,t),n.setAttribute(`aria-disabled`,t?`true`:`false`);let r=n instanceof HTMLButtonElement||n instanceof HTMLSelectElement||n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?n:n.querySelector(`button, select, input, textarea`);r&&(r.disabled=t)},p=null,m=null,h=null,g=0,_=()=>{let t=e.getOverflow?.();return t?.enabled===!0?t:void 0},v=()=>(p?p.setLabel(e.getOverflowLabel?.()??`More actions`):p=Cl({label:e.getOverflowLabel?.()??`More actions`,getButtonSize:i}),p),y=e=>{m!==e&&(h?.disconnect(),m=e,g=kl(e),typeof ResizeObserver<`u`&&(h=new ResizeObserver(t=>{let n=t[t.length-1]?.contentRect?.width??kl(e);n!==g&&(g=n,T())}),h.observe(e)))},b=(e,t)=>{let n=Ol(e.collapseAutoActionsBelow,t);if(n===null)return!1;let r=g||kl(t);return r>0&&r<n},x=(e,t,n)=>{if(!t)return`bar`;if(e.resolved.builtIn){let n=Dl(e.resolved.id);return n&&t.includeBuiltIns?.includes(n)?`menu`:`bar`}let r=e.resolved.presentation;return r===`overflow`||r===`auto`&&n?`menu`:`bar`},S=e=>{let t=e.menuSlot;if(!t)return;if(!Vl(e.element)){e.menuLabel?.remove(),e.menuLabel=void 0;return}let n=zl(e.element);n?(e.menuLabel||=B(`span`,`persona-composer-overflow-menu__label`),e.menuLabel.textContent!==n&&(e.menuLabel.textContent=n),e.menuLabel.parentElement!==t&&t.appendChild(e.menuLabel)):(e.menuLabel?.remove(),e.menuLabel=void 0)},C=(e,n)=>{if(e.mode===n)return e;let r=e.resolved.action;if(r&&!Ll(r)){u(e),t.delete(e.resolved.id);let r=s(e.resolved,n);return t.set(e.resolved.id,r),r}if(n===`menu`){let t=V(`div`,{className:`persona-composer-overflow-menu__slot`,attrs:{role:`none`,[Ar]:``}});t.appendChild(e.element),vr(Rl(e.element)),e.menuSlot=t;let n=t=>{let n=Rl(e.element);if(n.disabled)return;let r=t.target===n||n.contains(t.target);p?.close(!0),r||n.click()};t.addEventListener(`click`,n,!0),e.detachMenuSlot=()=>t.removeEventListener(`click`,n,!0),e.managed=!0,S(e)}else e.detachMenuSlot?.(),e.detachMenuSlot=void 0,e.menuLabel?.remove(),e.menuLabel=void 0,e.menuSlot?.remove(),e.menuSlot=void 0;return e.mode=n,e},w=(e,t)=>{let n=t.map(e=>e.menuSlot??e.element);for(n.forEach((t,n)=>{let r=e.children[n];r!==t&&(r?e.insertBefore(t,r):e.appendChild(t))});e.children.length>n.length;)e.lastElementChild?.remove()},T=()=>{if(r)return;let i=e.getBindings();if(!i)return;let a=e.getState(),o=a.phase===`streaming`,s=_();s&&y(i.footer);let c=s?b(s,i.footer):!1,l={start:[],end:[]},u=[];for(let e of n){let n=t.get(e.id);if(!n)continue;let r=e.action,i=!r||Pl(r.visible,a,!0)&&Il(r.visibility,a);if(n.visible!==i&&(n.visible=i,!i&&n.managed&&(n.menuSlot??n.element).remove()),i){if(n=C(n,x(n,s,c)),r){let e=Pl(r.disabled,a,!1)||r.disableWhenStreaming===!0&&o;f(n,e),!Ll(r)&&r.pressed!==void 0&&n.button?.setAttribute(`aria-pressed`,r.pressed?`true`:`false`)}n.mode===`menu`?(S(n),u.push(n)):l[e.placement].push(n)}}if(u.length>0){let e=v();w(e.panel,u),e.setItems(u.map(e=>e.menuSlot??e.element)),e.applyButtonSize();let t=Number.isFinite(s?.order)?s?.order:wl.overflow,n=l.start.findIndex(e=>e.resolved.order>t),r={resolved:{id:`core:overflow`,placement:`start`,presentation:`bar`,order:t,sequence:-1,source:`core`},element:e.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:`bar`};l.start.splice(n<0?l.start.length:n,0,r)}else p&&(p.close(),p.trigger.remove(),p.setItems([]));d(i.actionsStart,l.start),d(i.actionsEnd,l.end)};return{resolve:()=>{if(r)return;let i=Ml(e.collect()),a=new Set(i.map(e=>e.id));for(let[e,n]of t)a.has(e)||(u(n),t.delete(e));for(let e of i){let n=t.get(e.id);if(!n){let n=l(e,`bar`);n&&t.set(e.id,n);continue}let r=n.resolved.action,i=e.action;if(!!r!=!!i||r&&i&&Ll(r)!==Ll(i)||r&&i&&Ll(r)&&Ll(i)&&r.render!==i.render){u(n),t.delete(e.id);let r=l(e,n.mode);r&&t.set(e.id,r)}else n.resolved=e,e.builtIn?(n.managed=e.builtIn.managed===!0||n.mode===`menu`,e.builtIn.element&&n.mode===`bar`&&(n.element=e.builtIn.element)):i&&!Ll(i)?o(n,i):i&&n.element.toggleAttribute(El,i.disableWhenStreaming===!0)}n=i,T()},sync:T,getResolved:()=>n,getOverflowMenu:()=>p,destroy:()=>{if(!r){r=!0,h?.disconnect(),h=null,m=null;for(let e of t.values())u(e);t.clear(),p?.destroy(),p=null,n=[]}}}}H(),I(),da();const Ul=[`--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`],Wl=()=>({wrapper:V(`span`,{className:`persona-composer-model-picker-wrapper`,attrs:{"data-persona-composer-model-picker-wrapper":``}}),chevron:V(`span`,{className:`persona-composer-model-picker-chevron`,attrs:{"aria-hidden":`true`}})});function Gl(e){let t=e.label??`Model`,n=e.presentation??`native`,r=null,i=t=>{let n=e.getSelectedModelId();return t.find(e=>e.id===n)??t[0]},a=()=>{let n=V(`select`,{className:`persona-composer-model-picker`,attrs:{"aria-label":t,"data-persona-composer-model-picker":``}}),a=``,o=()=>{let t=e.getModels(),r=t.map(e=>`${e.id}:${e.label}`).join(`|`);r!==a&&(a=r,n.replaceChildren(...t.map(e=>{let t=V(`option`,{attrs:{value:e.id}});return t.textContent=e.label,t}))),n.value=i(t)?.id??``};o(),r=o;let s=()=>{n.value&&e.onSelect(n.value)};n.addEventListener(`change`,s);let c=e=>e.stopPropagation();n.addEventListener(`click`,c);let{wrapper:l,chevron:u}=Wl();return l.append(n,u),{element:l,destroy:()=>{r===o&&(r=null),n.removeEventListener(`change`,s),n.removeEventListener(`click`,c)}}},o=()=>{let n=V(`button`,{className:`persona-composer-model-picker persona-composer-model-picker-trigger`,attrs:{type:`button`,"aria-haspopup":`listbox`,"aria-expanded":`false`,"data-persona-composer-model-picker":`popover`}}),a=B(`span`,`persona-composer-model-picker-label`),o=B(`span`,`persona-composer-model-picker-suffix`);n.append(a,o);let s=V(`div`,{className:`persona-composer-model-menu`,attrs:{role:`listbox`,tabindex:`-1`,"aria-label":t,"data-persona-composer-model-menu":``}}),c=/* @__PURE__ */ new Map,l=``,u=null,d=()=>u?.isOpen===!0,f=(e=!1)=>{d()&&(u?.close(),n.setAttribute(`aria-expanded`,`false`),e&&n.focus())},p=e=>{let t=[...c.values()];t.length!==0&&t[(e%t.length+t.length)%t.length].focus()},m=t=>{if(d())return;u||=_l({anchor:n,content:s,placement:`top-start`,offset:6,onDismiss:()=>n.setAttribute(`aria-expanded`,`false`)}),ra(n,s,Ul),u.open(),n.setAttribute(`aria-expanded`,`true`);let r=[...c.keys()].indexOf(i(e.getModels())?.id??``);p(t??(r>=0?r:0))},h=t=>{f(!0),e.onSelect(t)},g=e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getAttribute(`data-persona-model-option`);t&&h(t)},_=e=>{let t=V(`button`,{className:`persona-composer-model-option`,attrs:{type:`button`,role:`option`,tabindex:`-1`,"aria-selected":`false`,"data-persona-model-option":e.id}});if(e.icon){let n=F(e.icon,16,`currentColor`,1.5);if(n){let e=B(`span`,`persona-composer-model-option-icon`);e.appendChild(n),t.appendChild(e)}}let n=B(`span`,`persona-composer-model-option-body`),r=B(`span`,`persona-composer-model-option-label`);if(r.textContent=e.label,n.appendChild(r),e.description){let t=B(`span`,`persona-composer-model-option-description`);t.textContent=e.description,n.appendChild(t)}t.appendChild(n);let i=B(`span`,`persona-composer-model-option-check`);i.setAttribute(`aria-hidden`,`true`);let a=F(`check`,16,`currentColor`,2);return a&&i.appendChild(a),t.appendChild(i),t.addEventListener(`click`,g),t},v=()=>{let r=e.getModels(),u=r.map(e=>`${e.id}:${e.label}:${e.icon??``}:${e.description??``}`).join(`|`);if(u!==l){l=u;for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),s.replaceChildren(...r.map(e=>{let t=_(e);return c.set(e.id,t),t}))}let d=i(r);for(let[e,t]of c)t.setAttribute(`aria-selected`,String(e===d?.id));a.textContent=d?.label??``;let f=e.getSuffix?.()??``;o.textContent=f,n.setAttribute(`aria-label`,[t,[d?.label,f].filter(Boolean).join(` `)].filter(Boolean).join(`: `))};v(),r=v;let y=e=>{e.preventDefault(),e.stopPropagation(),d()?f(!0):m()},b=e=>{e.key===`ArrowDown`?(e.preventDefault(),d()?p(0):m(0)):e.key===`ArrowUp`&&(e.preventDefault(),d()?p(-1):m(-1))},x=e=>{let t=[...c.values()],n=t.indexOf(e.target?.closest?.(`.persona-composer-model-option`));switch(e.key){case`ArrowDown`:e.preventDefault(),p(n+1);return;case`ArrowUp`:e.preventDefault(),p(n-1);return;case`Home`:e.preventDefault(),p(0);return;case`End`:e.preventDefault(),p(t.length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),f(!0);return;case`Tab`:f(!0);return}};n.addEventListener(`click`,y),n.addEventListener(`keydown`,b),s.addEventListener(`keydown`,x);let{wrapper:S,chevron:C}=Wl();return S.append(n,C),{element:S,destroy:()=>{r===v&&(r=null),n.removeEventListener(`click`,y),n.removeEventListener(`keydown`,b),s.removeEventListener(`keydown`,x);for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),u?.destroy(),u=null,s.remove()}}};return{action:{id:`core:model`,kind:`custom`,placement:`end`,order:700,presentation:n===`popover`?`bar`:`auto`,label:t,render:()=>n===`popover`?o():a()},repaint:()=>r?.()}}H();const Kl=`[data-persona-composer-chip-row]`;function ql(e){e.style.display=e.childElementCount>0?`flex`:`none`}function Jl(e){let t=e.querySelector(Kl);if(t)return t;let n=V(`div`,{className:`persona-composer-chip-row`,attrs:{"data-persona-composer-chip-row":``}});n.style.display=`none`;let r=e.querySelector(`[data-persona-composer-quote], [data-persona-composer-pending]`);return r?.parentElement===e?e.insertBefore(n,r):e.appendChild(n),n}H(),I();function Yl(e){let t=e.row,n=``,r=!1,i=new Set(e.initialIds??[]),a=t=>{let n=V(`span`,{className:`persona-mention-chip persona-composer-mode-chip`,attrs:{"data-persona-composer-mode":t.id}});if(t.iconName){let e=B(`span`,`persona-mention-chip-icon`),r=F(t.iconName,12,`currentColor`,1.5);r&&e.appendChild(r),n.appendChild(e)}let r=B(`span`,`persona-mention-chip-label`);r.textContent=t.shortLabel??t.label,n.appendChild(r);let i=V(`button`,{className:`persona-mention-chip-remove`,attrs:{type:`button`,"aria-label":`Remove ${t.label}`}}),a=F(`x`,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=`×`,i.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation(),e.onRemove(t.id)}),n.appendChild(i),n},o=()=>Array.from(t.querySelectorAll(`:scope > [data-persona-composer-mode]`)),s=e=>{e.setAttribute(`data-persona-chip-exit`,``),e.setAttribute(`aria-hidden`,`true`),e.style.pointerEvents=`none`;let n=()=>{e.remove(),ql(t)},r=t.ownerDocument.defaultView,i=typeof r?.getComputedStyle==`function`?r.getComputedStyle(e).animationName:``;!i||i===`none`?n():(e.addEventListener(`animationend`,n,{once:!0}),e.addEventListener(`animationcancel`,n,{once:!0}))},c=()=>{for(let e of o())e.remove()};return{element:t,render:(e,c)=>{if(r)return;let l=c.filter(t=>e.includes(t.id)),u=l.map(e=>`${e.id}:${e.shortLabel??e.label}`).join(`|`);if(u===n)return;n=u;let d=/* @__PURE__ */ new Map;for(let e of o()){let t=e.getAttribute(`data-persona-composer-mode`);t&&l.some(e=>e.id===t)&&!e.hasAttribute(`data-persona-chip-exit`)?d.set(t,e):e.hasAttribute(`data-persona-chip-exit`)||s(e)}let f=t.firstChild;for(let e of l){let n=d.get(e.id);n||(n=a(e),i.has(e.id)||(n.setAttribute(`data-persona-chip-enter`,``),n.addEventListener(`animationend`,()=>n?.removeAttribute(`data-persona-chip-enter`),{once:!0}))),i.delete(e.id),n!==f&&t.insertBefore(n,f),f=n.nextSibling}ql(t)},destroy:()=>{r=!0,c(),ql(t)}}}const Xl=e=>`core:mode:${e}`,Zl=e=>Math.min(300+e,499),Ql=e=>`core:mode-group:${e}`;function $l(e,t){return e?t?.find(t=>t.id===e)?.presentation===`segmented`:!1}function eu(e,t){return e?t?.find(t=>t.id===e)?.chipVisibility===`hidden`:!1}function tu(e,t){return e?.length?e.filter(e=>!$l(e.groupId,t)&&!eu(e.groupId,t)):[]}const nu=(e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null;function ru(e,t,n,r){let i=n.find(e=>e.id===t);if(!i)return[...e];let a=e.includes(t),o=new Set(e);if(a)o.delete(t);else{if(nu(i,r)===`single`){let e=n.filter(e=>e.groupId===i.groupId).map(e=>e.id);o=new Set([...o].filter(t=>!e.includes(t)))}o.add(t)}return n.filter(e=>o.has(e.id)).map(e=>e.id)}function iu(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function au(e,t){return t?.length?t.filter(t=>e.includes(t.id)&&(t.persistence??`sticky`)!==`once`).map(e=>e.id):[]}function ou(e,t){if(t?.length&&e.length!==0)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}H(),I();function su(e){let t=null;return{action:{id:Ql(e.groupId),kind:`custom`,placement:`start`,presentation:`bar`,label:e.getGroup()?.label??e.groupId,render:()=>{let n=V(`div`,{className:`persona-composer-segmented`,attrs:{"data-persona-composer-mode-group":e.groupId}}),r=/* @__PURE__ */ new Map,i=``,a=t=>{t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getAttribute(`data-persona-composer-mode`);n&&(e.getActiveIds().includes(n)&&e.getGroup()?.selection===`single`||e.onSelect(n))},o=e=>{let t=V(`button`,{className:`persona-composer-segmented-item`,attrs:{type:`button`,"data-persona-composer-mode":e.id,"aria-label":e.label}});if(e.iconName){let n=F(e.iconName,16,`currentColor`,1.5);n&&t.appendChild(n)}let n=B(`span`,`persona-composer-segmented-label`);return n.textContent=e.shortLabel??e.label,t.appendChild(n),t.addEventListener(`click`,a),t},s=()=>{let t=e.getGroup();t?.label?(n.setAttribute(`role`,`group`),n.setAttribute(`aria-label`,t.label)):(n.removeAttribute(`role`),n.removeAttribute(`aria-label`));let s=e.getModes(),c=s.map(e=>`${e.id}:${e.shortLabel??e.label}:${e.iconName??``}`).join(`|`);if(c!==i){i=c;for(let e of r.values())e.removeEventListener(`click`,a);r.clear();let e=s.map(e=>{let t=o(e);return r.set(e.id,t),t});n.replaceChildren(...e)}let l=e.getActiveIds();for(let[e,t]of r)t.setAttribute(`aria-pressed`,String(l.includes(e)))};return s(),t=s,{element:n,destroy:()=>{t===s&&(t=null);for(let e of r.values())e.removeEventListener(`click`,a);r.clear()}}}},repaint:()=>t?.()}}H(),I();function cu(e){let t=V(`div`,{className:`persona-composer-quote`,attrs:{"data-persona-composer-quote":``}});t.style.display=`none`;let n=``,r=!1,i=n=>{let r=B(`span`,`persona-composer-quote-bar`),i=B(`div`,`persona-composer-quote-content`);if(n.sourceLabel){let e=B(`div`,`persona-composer-quote-source`);e.textContent=n.sourceLabel,i.appendChild(e)}let a=V(`div`,{className:`persona-composer-quote-text`,attrs:{"data-persona-composer-quote-text":``}});a.textContent=xc(n.text),i.appendChild(a);let o=V(`button`,{className:`persona-composer-quote-dismiss`,attrs:{type:`button`,"aria-label":e.dismissLabel??`Remove quote`,"data-persona-composer-quote-dismiss":``}}),s=F(`x`,12,`currentColor`,2);s?o.appendChild(s):o.textContent=`×`,o.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(r,i,o)};return{element:t,render:e=>{if(r)return;let a=e?`${e.sourceLabel??``}${e.text}`:``;a!==n&&(n=a,e?(i(e),t.style.display=`flex`):(t.replaceChildren(),t.style.display=`none`))},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}H(),I();function lu(e){let t=V(`div`,{className:`persona-composer-pending`,attrs:{"data-persona-composer-pending":``}});t.style.display=`none`;let n,r=!1,i=(e,t,n,r)=>{let i=V(`button`,{className:`persona-composer-pending-action`,attrs:{type:`button`,"aria-label":t,[n]:``}}),a=F(e,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=t,i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},a=e=>{let t=xc(e.text??``,90);if(t)return t;let n=e.contentParts?.length??0;return n>0?n===1?`1 attachment`:`${n} attachments`:(e.mentionRefs?.length??0)>0?e.mentionRefs.map(e=>e.label).join(`, `):`Queued message`};return{element:t,render:o=>{if(r||o===n)return;if(n=o,!o){t.replaceChildren(),t.style.display=`none`;return}let s=B(`span`,`persona-composer-pending-badge`);s.textContent=e.label??`Sends next`;let c=V(`div`,{className:`persona-composer-pending-text`,attrs:{"data-persona-composer-pending-text":``}});c.textContent=a(o),t.replaceChildren(s,c,i(`pencil`,e.editLabel??`Edit queued message`,`data-persona-composer-pending-edit`,e.onEdit),i(`x`,e.removeLabel??`Remove queued message`,`data-persona-composer-pending-remove`,e.onRemove)),t.style.display=`flex`},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}H();function uu(e){let t=V(`div`,{className:`persona-message-edit`,attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":``}}),n=V(`textarea`,{className:`persona-message-edit-input`,attrs:{rows:`1`,dir:`auto`,"aria-label":`Edit message`,"data-persona-message-edit-input":``}});n.value=e.initialText;let r=()=>{n.style.height=`auto`,n.style.height=`${n.scrollHeight}px`};n.addEventListener(`input`,r);let i=B(`div`,`persona-message-edit-actions`),a=(e,t,n,r)=>{let i=V(`button`,{className:`persona-message-edit-button ${t}`,attrs:{type:`button`,[n]:``},text:e});return i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},o=()=>{let t=n.value.trim();t&&e.onSave(t)};return i.append(a(e.cancelLabel??`Cancel`,`persona-message-edit-cancel`,`data-persona-message-edit-cancel`,e.onCancel),a(e.saveLabel??`Send`,`persona-message-edit-save`,`data-persona-message-edit-save`,o)),n.addEventListener(`keydown`,t=>{t.key===`Escape`?(t.preventDefault(),t.stopPropagation(),e.onCancel()):t.key===`Enter`&&!t.shiftKey&&(t.preventDefault(),o())}),t.append(n,i),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let e=n.value.length;n.setSelectionRange(e,e),r()},destroy:()=>{t.replaceChildren(),t.remove()}}}function du(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 fu(e,t){if(!e||typeof e.text!=`string`)return;let n=new Set(t.mentionSourceIds),r=(e.mentionRefs??[]).filter(e=>n.has(e.sourceId)),i=r.length===(e.mentionRefs?.length??0)&&r.length>0,a=new Set(t.modes.map(e=>e.id)),o=(e.activeModeIds??[]).filter(e=>a.has(e)),s=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...i?{mentionRefs:r}:{},...i&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...s?{selectedModelId:s}:{},...o.length?{activeModeIds:o}:{},...e.quote?.text?{quote:e.quote}:{}}}function pu(e){let t=e.delay??500,n=null,r=!1,i=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{r||(i(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{r||n===null||(i(),e.write())},cancel:i,destroy:()=>{r=!0,i()}}}function mu(e){return e.wrapped||e.text.includes(`
23
- `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function hu(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function gu(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),r=Number.parseFloat(n.lineHeight),i=Number.parseFloat(n.fontSize),a=Number.isFinite(r)&&r>0?r:Number.isFinite(i)&&i>0?i*1.4:0;if(!a)return!1;let o=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-o>a*1.5}function _u(e){e&&(typeof e.requestSubmit==`function`?e.requestSubmit():e.dispatchEvent(new Event(`submit`,{bubbles:!0,cancelable:!0})))}function vu(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 yu(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}const bu=e=>typeof e?.then==`function`;function xu(e,t){return t===!1?{status:`canceled`}:(!t||typeof t!=`object`||(typeof t.text==`string`&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options})),{status:`proceed`})}function Su(e,t,n){let r;try{r=e(vu(t),{signal:n})}catch(e){return{status:`error`,error:e}}return bu(r)?Promise.resolve(r).then(e=>n.aborted?{status:`aborted`}:xu(t,e),e=>n.aborted?{status:`aborted`}:{status:`error`,error:e}):xu(t,r)}const Cu=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?`circle`:`pill`),wu={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`};wi();const Tu=`16px`,Eu=`transparent`,Du={colors:{primary:{50:`#ffffff`,100:`#f5f5f5`,200:`#d4d4d4`,300:`#a3a3a3`,400:`#737373`,500:`#171717`,600:`#0f0f0f`,700:`#0a0a0a`,800:`#050505`,900:`#030303`,950:`#000000`},secondary:{50:`#f5f3ff`,100:`#ede9fe`,200:`#ddd6fe`,300:`#c4b5fd`,400:`#a78bfa`,500:`#8b5cf6`,600:`#7c3aed`,700:`#6d28d9`,800:`#5b21b6`,900:`#4c1d95`,950:`#2e1065`},accent:{50:`#ecfeff`,100:`#cffafe`,200:`#a5f3fc`,300:`#67e8f9`,400:`#22d3ee`,500:`#06b6d4`,600:`#0891b2`,700:`#0e7490`,800:`#155e75`,900:`#164e63`,950:`#083344`},gray:{50:`#f9fafb`,100:`#f3f4f6`,200:`#e5e7eb`,300:`#d1d5db`,400:`#9ca3af`,500:`#6b7280`,600:`#4b5563`,700:`#374151`,800:`#1f2937`,900:`#111827`,950:`#030712`},success:{50:`#f0fdf4`,100:`#dcfce7`,200:`#bbf7d0`,300:`#86efac`,400:`#4ade80`,500:`#22c55e`,600:`#16a34a`,700:`#15803d`,800:`#166534`,900:`#14532d`},warning:{50:`#fefce8`,100:`#fef9c3`,200:`#fef08a`,300:`#fde047`,400:`#facc15`,500:`#eab308`,600:`#ca8a04`,700:`#a16207`,800:`#854d0e`,900:`#713f12`},error:{50:`#fef2f2`,100:`#fee2e2`,200:`#fecaca`,300:`#fca5a5`,400:`#f87171`,500:`#ef4444`,600:`#dc2626`,700:`#b91c1c`,800:`#991b1b`,900:`#7f1d1d`},info:{50:`#eff6ff`,100:`#dbeafe`,200:`#bfdbfe`,300:`#93c5fd`,400:`#60a5fa`,500:`#3b82f6`,600:`#2563eb`,700:`#1d4ed8`,800:`#1e40af`,900:`#1e3a8a`,950:`#172554`},purple:{50:`#faf5ff`,100:`#f3e8ff`,200:`#e9d5ff`,300:`#d8b4fe`,400:`#c084fc`,500:`#a855f7`,600:`#9333ea`,700:`#7e22ce`,800:`#6b21a8`,900:`#581c87`,950:`#3b0764`},teal:{50:`#f0fdfa`,100:`#ccfbf1`,200:`#99f6e4`,300:`#5eead4`,400:`#2dd4bf`,500:`#14b8a6`,600:`#0d9488`,700:`#0f766e`,800:`#115e59`,900:`#134e4a`,950:`#042f2e`}},spacing:(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?`0px`:`${t/4}rem`;return e})(),typography:{fontFamily:{sans:`system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`,serif:`Georgia, Cambria, "Times New Roman", Times, serif`,mono:`ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace`},fontSize:{xs:`0.75rem`,sm:`0.875rem`,base:`1rem`,lg:`1.125rem`,xl:`1.25rem`,"2xl":`1.5rem`,"3xl":`1.875rem`,"4xl":`2.25rem`},fontWeight:{normal:`400`,medium:`500`,semibold:`600`,bold:`700`},lineHeight:{tight:`1.25`,normal:`1.5`,relaxed:`1.625`}},shadows:{none:`none`,sm:`0 1px 2px 0 rgb(0 0 0 / 0.05)`,md:`0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)`,lg:`0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)`,xl:`0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)`,"2xl":`0 25px 50px -12px rgb(0 0 0 / 0.25)`},borders:{none:`none`,sm:`1px solid`,md:`2px solid`,lg:`4px solid`},radius:{none:`0px`,sm:`0.125rem`,md:`0.375rem`,lg:`0.5rem`,xl:`0.75rem`,"2xl":`1rem`,full:`9999px`}},Ou={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`}},ku={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:pi,maxWidth:`none`,height:`min(640px, max(200px, calc(100vh - 64px)))`,maxHeight:`none`,borderRadius:`palette.radius.xl`,shadow:`palette.shadows.xl`,inset:Tu,canvasBackground:Eu,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`}}},Au=Du.colors.gray,ju={50:`#fafafa`,100:`#f5f5f5`,200:`#e5e5e5`,300:`#d4d4d4`,400:`#a3a3a3`,500:`#737373`,600:`#525252`,700:`#404040`,800:`#262626`,900:`#171717`,950:`#0a0a0a`},Mu={...Du,colors:{...Du.colors,gray:Au}},Nu={...Du,colors:{...Du.colors,gray:ju},radius:{none:`0px`,sm:`4px`,md:`8px`,lg:`12px`,xl:`16px`,"2xl":`24px`,full:`9999px`}},Pu=Mu,Fu=Ou,Iu={...Ou,colors:{...Ou.colors,surface:`#ffffff`,background:`#ffffff`,container:`semantic.colors.surface`,textInverse:`#ffffff`},typography:{...Ou.typography,fontSize:`14px`,lineHeight:`1.5`}},Lu=Fu,Ru=ku,zu={...ku,launcher:wu,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:{...ku.input,borderRadius:`palette.radius.full`},introCard:{...ku.introCard,title:{fontSize:`22px`,fontWeight:`500`}},suggestion:{chip:{...ku.suggestion.chip,fontWeight:`400`},card:{...ku.suggestion.card,fontWeight:`400`},list:{...ku.suggestion.list,fontWeight:`400`}},panel:{...ku.panel,width:`min(400px, calc(100vw - 24px))`,height:`min(704px, calc(100dvh - 104px))`,borderRadius:`palette.radius.xl`},header:{...ku.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:{...ku.message,gap:`20px`,fullscreenGap:`28px`,topFadeHeight:`18px`,user:{...ku.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:{...ku.message.assistant,background:`transparent`,border:`transparent`,borderWidth:`0px`,borderRadius:`0px`,shadow:`none`,padding:`0px`,fontSize:`14px`,lineHeight:`1.55`}},composer:{...ku.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)`}},Bu=Ru,Vu=e=>li({future:e}),Hu=e=>Vu(e)===`v5`?{palette:Nu,semantic:Iu,components:zu}:{palette:Mu,semantic:Fu,components:Ru};function Uu(e,t){if(!t.startsWith(`palette.`)&&!t.startsWith(`semantic.`)&&!t.startsWith(`components.`))return t;let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return typeof r==`string`&&(r.startsWith(`palette.`)||r.startsWith(`semantic.`)||r.startsWith(`components.`))?Uu(e,r):r}function Wu(e){let t={};function n(r,i){for(let[a,o]of Object.entries(r)){let r=`${i}.${a}`;if(typeof o==`string`){let n=Uu(e,o);n!==void 0&&(t[r]={path:r,value:n,type:i.includes(`color`)?`color`:i.includes(`spacing`)?`spacing`:i.includes(`typography`)?`typography`:i.includes(`shadow`)?`shadow`:i.includes(`border`)?`border`:`color`})}else typeof o==`object`&&o&&n(o,r)}}return n(e.palette,`palette`),n(e.semantic,`semantic`),n(e.components,`components`),t}function Gu(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 Ku(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t&&typeof t==`object`&&!Array.isArray(t)&&r&&typeof r==`object`&&!Array.isArray(r)?Ku(t,r):r}return n}function qu(e,t){return t?Ku(e,t):e}function Ju(e,t={}){let n=Hu(t.future),r={palette:n.palette,semantic:n.semantic,components:n.components},i={palette:{...r.palette,...e?.palette,colors:{...r.palette.colors,...e?.palette?.colors},spacing:{...r.palette.spacing,...e?.palette?.spacing},typography:{...r.palette.typography,...e?.palette?.typography},shadows:{...r.palette.shadows,...e?.palette?.shadows},borders:{...r.palette.borders,...e?.palette?.borders},radius:{...r.palette.radius,...e?.palette?.radius}},semantic:{...r.semantic,...e?.semantic,colors:{...r.semantic.colors,...e?.semantic?.colors,interactive:{...r.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...r.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...r.semantic.spacing,...e?.semantic?.spacing},typography:{...r.semantic.typography,...e?.semantic?.typography}},components:qu(r.components,e?.components)},a=e?.components?.activity;for(let e of[`toolBubble`,`reasoningBubble`])for(let t of[`rowHeight`,`labelSize`,`iconSize`,`indent`,`bodySurface`])a?.[t]!==void 0&&(i.components[e][t]=a[t]);let o=e?.components?.collapsibleWidget?.surface;o!==void 0&&a?.bodySurface===void 0&&(i.components.activity={...i.components.activity,bodySurface:o});let s=e?.components?.header;s?.padding!==void 0&&s.minimalPadding===void 0&&(i.components.header.minimalPadding=i.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(i.components.message.fullscreenGap=i.components.message.gap),t.validate!==!1){let e=Gu(i);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(`, `)}`)}if(t.plugins)for(let e of t.plugins)i=e.transform(i);return i}const Yu=e=>e.trim()===`0`?`0px`:e,Xu=`--persona-`,Zu=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let e=t.slice(1);if(!/^[0-9a-f]+$/.test(e))return;e.length===3||e.length===4?n=[0,1,2].map(t=>parseInt(e[t]+e[t],16)):(e.length===6||e.length===8)&&(n=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16)))}else{let e=t.match(/^rgba?\(([^)]+)\)$/);if(e){let t=e[1].split(/[,/\s]+/).filter(Boolean);t.length>=3&&(n=t.slice(0,3).map(e=>{let t=e.endsWith(`%`),n=parseFloat(t?e.slice(0,-1):e);return t?n/100*255:n}))}}if(!n||n.some(e=>!Number.isFinite(e)))return;let[r,i,a]=n.map(e=>{let t=Math.max(0,Math.min(255,e))/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a},Qu=(e,t)=>{for(let[n,...r]of t){let t;for(let n of r)if(t=n.charCodeAt(0)===61?n.slice(1):e[Xu+n],t!==void 0)break;t!==void 0&&(e[Xu+n]=t)}};function $u(e){let t=Wu(e),n={};for(let[e,r]of Object.entries(t)){let t=e.replace(/\./g,`-`);n[`--persona-${t}`]=r.value}Qu(n,[[`primary`,`semantic-colors-primary`,`palette-colors-primary-500`],[`secondary`,`semantic-colors-secondary`,`palette-colors-secondary-500`],[`accent`,`semantic-colors-accent`,`palette-colors-accent-500`],[`surface`,`semantic-colors-surface`,`palette-colors-gray-50`],[`background`,`semantic-colors-background`,`palette-colors-gray-50`],[`container`,`semantic-colors-container`,`palette-colors-gray-100`],[`text`,`semantic-colors-text`,`palette-colors-gray-900`],[`text-muted`,`semantic-colors-text-muted`,`palette-colors-gray-500`],[`text-inverse`,`semantic-colors-text-inverse`,`palette-colors-gray-50`],[`border`,`semantic-colors-border`,`palette-colors-gray-200`],[`divider`,`semantic-colors-divider`,`palette-colors-gray-200`],[`muted`,`text-muted`],[`voice-recording-indicator`,`components-voice-recording-indicator`,`palette-colors-error-500`],[`voice-recording-bg`,`components-voice-recording-background`,`palette-colors-error-50`],[`voice-processing-icon`,`components-voice-processing-icon`,`palette-colors-primary-500`],[`voice-speaking-icon`,`components-voice-speaking-icon`,`palette-colors-success-500`],[`approval-bg`,`components-approval-requested-background`,`surface`],[`approval-border`,`components-approval-requested-border`,`border`],[`approval-text`,`components-approval-requested-text`,`palette-colors-gray-900`],[`approval-shadow`,`components-approval-requested-shadow`,`=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)`],[`approval-approve-bg`,`components-approval-approve-background`,`button-primary-bg`],[`approval-deny-bg`,`components-approval-deny-background`,`container`],[`attachment-image-bg`,`components-attachment-image-background`,`palette-colors-gray-100`],[`attachment-image-border`,`components-attachment-image-border`,`palette-colors-gray-200`],[`font-family`,`semantic-typography-fontFamily`,`palette-typography-fontFamily-sans`],[`font-size`,`semantic-typography-fontSize`,`palette-typography-fontSize-base`],[`font-weight`,`semantic-typography-fontWeight`,`palette-typography-fontWeight-normal`],[`line-height`,`semantic-typography-lineHeight`,`palette-typography-lineHeight-normal`],[`input-font-family`,`font-family`],[`input-font-weight`,`font-weight`],[`radius-sm`,`palette-radius-sm`,`=0.125rem`],[`radius-md`,`palette-radius-md`,`=0.375rem`],[`radius-lg`,`palette-radius-lg`,`=0.5rem`],[`radius-xl`,`palette-radius-xl`,`=0.75rem`],[`radius-full`,`palette-radius-full`,`=9999px`],[`launcher-radius`,`components-launcher-borderRadius`,`palette-radius-full`,`=9999px`],[`launcher-bg`,`components-launcher-background`,`surface`],[`launcher-fg`,`components-launcher-foreground`,`primary`]]);let r=n[`--persona-components-launcher-foreground`];n[`--persona-launcher-fg-muted`]=r&&r!==n[`--persona-primary`]?`color-mix(in srgb, ${r} 70%, transparent)`:n[`--persona-muted`],Qu(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`]]),Qu(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`]}`,Qu(n,[[`panel-shadow`,`components-panel-shadow`,`palette-shadows-xl`,`=0 25px 50px -12px rgba(0, 0, 0, 0.25)`]]),n[`--persona-panel-inset`]=n[`--persona-components-panel-inset`]??`16px`,n[`--persona-panel-canvas-bg`]=n[`--persona-components-panel-canvasBackground`]??`transparent`,Qu(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`]]),Qu(n,[[`header-bg`,`components-header-background`,`surface`]]);let i=n[`--persona-header-bg`],a=n[`--persona-components-header-foreground`],o=a?`color-mix(in srgb, ${a} 72%, ${i})`:void 0;n[`--persona-header-border`]=n[`--persona-components-header-border`]??(a?`color-mix(in srgb, ${a} 14%, ${i})`:void 0)??n[`--persona-divider`],Qu(n,[[`header-icon-bg`,`components-header-iconBackground`,`primary`],[`header-icon-fg`,`components-header-iconForeground`,`text-inverse`]]),n[`--persona-header-title-fg`]=n[`--persona-components-header-title-color`]??n[`--persona-components-header-titleForeground`]??a??n[`--persona-primary`],n[`--persona-header-subtitle-fg`]=n[`--persona-components-header-subtitle-color`]??n[`--persona-components-header-subtitleForeground`]??o??n[`--persona-text-muted`],n[`--persona-header-action-icon-fg`]=n[`--persona-components-header-actionIconForeground`]??o??n[`--persona-muted`],Qu(n,[[`header-control-size`,`components-header-controlSize`,`=32px`],[`header-control-icon-size`,`components-header-controlIconSize`,`=20px`]]);let s=e.components?.header;s?.shadow&&(n[`--persona-header-shadow`]=s.shadow),s?.borderBottom&&(n[`--persona-header-border-bottom`]=s.borderBottom),s?.minHeight&&(n[`--persona-header-min-height`]=s.minHeight);let c=n[`--persona-components-history-railHeader-background`];c&&(n[`--persona-history-rail-header-bg`]=c);let l=n[`--persona-components-history-railHeader-border`];l&&(n[`--persona-history-rail-header-border`]=l);let u=n[`--persona-components-history-railHeader-minHeight`];u&&(n[`--persona-history-rail-header-min-height`]=u);for(let[e,t]of[[`margin`,`margin`],[`borderRadius`,`radius`],[`shadow`,`shadow`],[`background`,`bg`]]){let r=n[`--persona-components-history-overlay-${e}`];r&&(n[`--persona-history-overlay-${t}`]=r)}for(let[e,t]of[[`background`,`bg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-history-menu-${e}`];r&&(n[`--persona-history-menu-${t}`]=r)}let d=e.components?.history?.motion;if(d){let e=e=>{if(e===void 0)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},t=e(d.enterDurationMs);t!==void 0&&(n[`--persona-history-enter-ms`]=t);let r=e(d.exitDurationMs);r!==void 0&&(n[`--persona-history-exit-ms`]=r),d.enterEasing&&(n[`--persona-history-enter-easing`]=d.enterEasing),d.exitEasing&&(n[`--persona-history-exit-easing`]=d.exitEasing)}let f=n[`--persona-components-history-dangerForeground`];f&&(n[`--persona-history-danger-fg`]=f),n[`--persona-danger`]=n[`--persona-components-history-confirm-dangerBackground`]??n[`--persona-palette-colors-error-700`]??`#b42318`,n[`--persona-danger-fg`]=n[`--persona-components-history-confirm-dangerForeground`]??`#ffffff`;for(let e of[`scrim`,`shadow`]){let t=n[`--persona-components-history-confirm-${e}`];t&&(n[`--persona-history-confirm-${e}`]=t)}for(let[e,t]of[[`background`,`background`],[`foreground`,`foreground`],[`hintForeground`,`hint-fg`],[`borderRadius`,`radius`],[`fontSize`,`font-size`],[`padding`,`padding`],[`maxWidth`,`max-width`],[`shadow`,`shadow`]]){let r=n[`--persona-components-tooltip-${e}`];r&&(n[`--persona-tooltip-${t}`]=r)}e.components?.tooltip?.arrow===!1&&(n[`--persona-tooltip-arrow-display`]=`none`);for(let[e,t]of[[`background`,`bg`],[`border`,`border`],[`hoverBackground`,`hover-bg`],[`hoverForeground`,`hover-fg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-messageActions-${e}`];r&&(n[`--persona-message-action-${t}`]=r)}Qu(n,[[`intro-card-bg`,`components-introCard-background`,`=transparent`],[`intro-card-radius`,`components-introCard-borderRadius`,`=1rem`]]);let p=n[`--persona-components-introCard-background`],m=n[`--persona-components-introCard-shadow`],h=(!p||p===`transparent`||p===`none`)&&(!m||m===`none`),g=n[`--persona-components-introCard-padding`]??`1.5rem`;n[`--persona-intro-card-padding`]=h&&g===`1.5rem`?`1.5rem 0`:g,Qu(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`]]),Qu(n,[[`composer-padding`,`components-composer-padding`,`=0.75rem 1rem`],[`composer-gap`,`components-composer-gap`,`=0.5rem`],[`composer-font-size`,`components-composer-fontSize`,`=0.875rem`],[`composer-line-height`,`components-composer-lineHeight`,`=1.25rem`],[`composer-control-size`,`components-composer-controlSize`,`=40px`],[`composer-control-icon-size`,`components-composer-controlIconSize`,`=24px`],[`motion-duration-fast`,`components-motion-durationFast`,`=120ms`],[`motion-duration-base`,`components-motion-durationBase`,`=200ms`],[`motion-easing`,`components-motion-easing`,`=cubic-bezier(0.2, 0, 0, 1)`],[`composer-border-color`,`components-composer-borderColor`,`border`,`=#e5e7eb`],[`composer-overlay-band`,`components-composer-overlayBand`,`=transparent`],[`scrollbar-thumb`,`components-scrollbar-thumb`,`border`,`=#e5e7eb`],[`scrollbar-track`,`components-scrollbar-track`,`=transparent`],[`md-inline-code-bg`,`components-markdown-inlineCode-background`,`container`],[`md-inline-code-color`,`components-markdown-inlineCode-foreground`,`text`],[`md-link-color`,`components-markdown-link-foreground`,`accent`,`=#0f0f0f`]]);let _=n[`--persona-components-markdown-heading-h1-fontSize`];_&&(n[`--persona-md-h1-size`]=_);let v=n[`--persona-components-markdown-heading-h1-fontWeight`];v&&(n[`--persona-md-h1-weight`]=v);let y=n[`--persona-components-markdown-heading-h2-fontSize`];y&&(n[`--persona-md-h2-size`]=y);let b=n[`--persona-components-markdown-heading-h2-fontWeight`];b&&(n[`--persona-md-h2-weight`]=b);let x=n[`--persona-components-markdown-prose-fontFamily`];x&&x!==`inherit`&&(n[`--persona-md-prose-font-family`]=x),Qu(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`]]),Qu(n,[[`md-code-block-border-radius`,`components-markdown-codeBlock-borderRadius`,`radius-md`,`=0.375rem`]]),Qu(n,[[`md-table-header-bg`,`components-markdown-table-headerBackground`,`container`],[`md-table-border-color`,`components-markdown-table-borderColor`,`border`]]),Qu(n,[[`md-hr-color`,`components-markdown-hr-color`,`divider`]]),Qu(n,[[`md-blockquote-border-color`,`components-markdown-blockquote-borderColor`,`palette-colors-gray-900`],[`md-blockquote-bg`,`components-markdown-blockquote-background`,`=transparent`],[`md-blockquote-text-color`,`components-markdown-blockquote-textColor`,`palette-colors-gray-500`]]);for(let[e,t]of[[`container`,`surface`],[`surface`,`surface`],[`border`,`border`]]){let r=n[`--persona-components-collapsibleWidget-${e}`]??n[`--persona-${t}`];r!==void 0&&(n[`--persona-cw-${e}`]=r,n[`--cw-${e}`]=r)}Qu(n,[[`message-border`,`components-message-border`,`border`]]),Qu(n,[[`message-user-padding`,`components-message-user-padding`],[`message-user-max-width`,`components-message-user-maxWidth`],[`message-user-font-size`,`components-message-user-fontSize`],[`message-user-font-family`,`components-message-user-fontFamily`],[`message-user-line-height`,`components-message-user-lineHeight`],[`message-assistant-padding`,`components-message-assistant-padding`],[`message-assistant-border-width`,`components-message-assistant-borderWidth`],[`message-assistant-max-width`,`components-message-assistant-maxWidth`],[`message-assistant-font-size`,`components-message-assistant-fontSize`],[`message-assistant-font-family`,`components-message-assistant-fontFamily`],[`message-assistant-line-height`,`components-message-assistant-lineHeight`]]);let S=e.components,C=S?.iconButton;C&&(C.background&&(n[`--persona-icon-btn-bg`]=C.background),C.border&&(n[`--persona-icon-btn-border`]=C.border),C.color&&(n[`--persona-icon-btn-color`]=C.color),C.padding&&(n[`--persona-icon-btn-padding`]=C.padding),C.borderRadius&&(n[`--persona-icon-btn-radius`]=C.borderRadius),C.hoverBackground&&(n[`--persona-icon-btn-hover-bg`]=C.hoverBackground),C.hoverColor&&(n[`--persona-icon-btn-hover-color`]=C.hoverColor),C.activeBackground&&(n[`--persona-icon-btn-active-bg`]=C.activeBackground),C.activeBorder&&(n[`--persona-icon-btn-active-border`]=C.activeBorder));let w=S?.labelButton;w&&(w.background&&(n[`--persona-label-btn-bg`]=w.background),w.border&&(n[`--persona-label-btn-border`]=w.border),w.color&&(n[`--persona-label-btn-color`]=w.color),w.padding&&(n[`--persona-label-btn-padding`]=w.padding),w.borderRadius&&(n[`--persona-label-btn-radius`]=w.borderRadius),w.hoverBackground&&(n[`--persona-label-btn-hover-bg`]=w.hoverBackground),w.fontSize&&(n[`--persona-label-btn-font-size`]=w.fontSize),w.gap&&(n[`--persona-label-btn-gap`]=w.gap));let T=S?.toggleGroup;T&&(T.gap&&(n[`--persona-toggle-group-gap`]=T.gap),T.borderRadius&&(n[`--persona-toggle-group-radius`]=T.borderRadius));let E=S?.artifact;if(E?.toolbar){let t=E.toolbar;t.iconHoverColor&&(n[`--persona-artifact-toolbar-icon-hover-color`]=t.iconHoverColor),t.iconHoverBackground&&(n[`--persona-artifact-toolbar-icon-hover-bg`]=t.iconHoverBackground),t.iconPadding&&(n[`--persona-artifact-toolbar-icon-padding`]=t.iconPadding),t.iconBorderRadius&&(n[`--persona-artifact-toolbar-icon-radius`]=t.iconBorderRadius),t.iconBorder&&(n[`--persona-artifact-toolbar-icon-border`]=t.iconBorder),t.toggleGroupGap&&(n[`--persona-artifact-toolbar-toggle-group-gap`]=Yu(t.toggleGroupGap)),t.toggleBorderRadius&&(n[`--persona-artifact-toolbar-toggle-radius`]=t.toggleBorderRadius),t.toggleGroupPadding&&(n[`--persona-artifact-toolbar-toggle-group-padding`]=Yu(t.toggleGroupPadding)),t.toggleGroupBorder&&(n[`--persona-artifact-toolbar-toggle-group-border`]=t.toggleGroupBorder),t.toggleGroupBorderRadius&&(n[`--persona-artifact-toolbar-toggle-group-radius`]=t.toggleGroupBorderRadius),t.toggleGroupBackground&&(n[`--persona-artifact-toolbar-toggle-group-bg`]=Uu(e,t.toggleGroupBackground)??t.toggleGroupBackground),t.copyBackground&&(n[`--persona-artifact-toolbar-copy-bg`]=t.copyBackground),t.copyBorder&&(n[`--persona-artifact-toolbar-copy-border`]=t.copyBorder),t.copyColor&&(n[`--persona-artifact-toolbar-copy-color`]=t.copyColor),t.copyBorderRadius&&(n[`--persona-artifact-toolbar-copy-radius`]=Yu(t.copyBorderRadius)),t.copyPadding&&(n[`--persona-artifact-toolbar-copy-padding`]=t.copyPadding),t.copyMenuBackground&&(n[`--persona-artifact-toolbar-copy-menu-bg`]=t.copyMenuBackground,n[`--persona-dropdown-bg`]=n[`--persona-dropdown-bg`]??t.copyMenuBackground),t.copyMenuBorder&&(n[`--persona-artifact-toolbar-copy-menu-border`]=t.copyMenuBorder,n[`--persona-dropdown-border`]=n[`--persona-dropdown-border`]??t.copyMenuBorder),t.copyMenuShadow&&(n[`--persona-artifact-toolbar-copy-menu-shadow`]=t.copyMenuShadow,n[`--persona-dropdown-shadow`]=n[`--persona-dropdown-shadow`]??t.copyMenuShadow),t.copyMenuBorderRadius&&(n[`--persona-artifact-toolbar-copy-menu-radius`]=t.copyMenuBorderRadius,n[`--persona-dropdown-radius`]=n[`--persona-dropdown-radius`]??t.copyMenuBorderRadius),t.copyMenuItemHoverBackground&&(n[`--persona-artifact-toolbar-copy-menu-item-hover-bg`]=t.copyMenuItemHoverBackground,n[`--persona-dropdown-item-hover-bg`]=n[`--persona-dropdown-item-hover-bg`]??t.copyMenuItemHoverBackground),t.iconBackground&&(n[`--persona-artifact-toolbar-icon-bg`]=t.iconBackground),t.toolbarBorder&&(n[`--persona-artifact-toolbar-border`]=t.toolbarBorder)}if(E?.tab){let e=E.tab;e.background&&(n[`--persona-artifact-tab-bg`]=e.background),e.activeBackground&&(n[`--persona-artifact-tab-active-bg`]=e.activeBackground),e.activeBorder&&(n[`--persona-artifact-tab-active-border`]=e.activeBorder),e.borderRadius&&(n[`--persona-artifact-tab-radius`]=e.borderRadius),e.textColor&&(n[`--persona-artifact-tab-color`]=e.textColor),e.hoverBackground&&(n[`--persona-artifact-tab-hover-bg`]=e.hoverBackground),e.listBackground&&(n[`--persona-artifact-tab-list-bg`]=e.listBackground),e.listBorderColor&&(n[`--persona-artifact-tab-list-border-color`]=e.listBorderColor),e.listPadding&&(n[`--persona-artifact-tab-list-padding`]=e.listPadding)}if(E?.pane){let t=E.pane;t.toolbarBackground&&(n[`--persona-artifact-toolbar-bg`]=Uu(e,t.toolbarBackground)??t.toolbarBackground)}if(E?.card){let e=E.card;e.background&&(n[`--persona-artifact-card-bg`]=e.background),e.border&&(n[`--persona-artifact-card-border`]=e.border),e.borderRadius&&(n[`--persona-artifact-card-radius`]=e.borderRadius),e.hoverBackground&&(n[`--persona-artifact-card-hover-bg`]=e.hoverBackground),e.hoverBorderColor&&(n[`--persona-artifact-card-hover-border`]=e.hoverBorderColor)}if(E?.inline){let t=E.inline;t.background&&(n[`--persona-artifact-inline-bg`]=Uu(e,t.background)??t.background),t.border&&(n[`--persona-artifact-inline-border`]=t.border),t.borderRadius&&(n[`--persona-artifact-inline-radius`]=t.borderRadius),t.chromeBackground&&(n[`--persona-artifact-inline-chrome-bg`]=Uu(e,t.chromeBackground)??t.chromeBackground),t.chromeBorder&&(n[`--persona-artifact-inline-chrome-border`]=Uu(e,t.chromeBorder)??t.chromeBorder),t.titleColor&&(n[`--persona-artifact-inline-title-color`]=Uu(e,t.titleColor)??t.titleColor),t.mutedColor&&(n[`--persona-artifact-inline-muted-color`]=Uu(e,t.mutedColor)??t.mutedColor),t.frameHeight&&(n[`--persona-artifact-inline-frame-height`]=t.frameHeight)}let D=S?.code;D&&(D.keywordColor&&(n[`--persona-code-keyword-color`]=D.keywordColor),D.stringColor&&(n[`--persona-code-string-color`]=D.stringColor),D.commentColor&&(n[`--persona-code-comment-color`]=D.commentColor),D.numberColor&&(n[`--persona-code-number-color`]=D.numberColor),D.tagColor&&(n[`--persona-code-tag-color`]=D.tagColor),D.attrColor&&(n[`--persona-code-attr-color`]=D.attrColor),D.propertyColor&&(n[`--persona-code-property-color`]=D.propertyColor),D.lineNumberColor&&(n[`--persona-code-line-number-color`]=D.lineNumberColor),D.gutterBorderColor&&(n[`--persona-code-gutter-border-color`]=D.gutterBorderColor),D.background&&(n[`--persona-code-bg`]=Uu(e,D.background)??D.background));let O=n[`--persona-surface`],ee=n[`--persona-container`],k=n[`--persona-palette-colors-gray-100`]??`#f3f4f6`,A=n[`--persona-palette-colors-gray-200`]??`#e5e7eb`,j=n[`--persona-palette-colors-gray-300`]??`#d1d5db`,te=!ee||ee===O,ne=Zu(O??n[`--persona-background`]),re=te&&ne!==void 0&&ne<.179,ie=re?`rgba(255, 255, 255, 0.08)`:k,M=re?`rgba(255, 255, 255, 0.12)`:A,N=re?`rgba(255, 255, 255, 0.16)`:j,P=te?ie:ee,ae=te?M:ee;return n[`--persona-icon-btn-hover-bg`]=n[`--persona-icon-btn-hover-bg`]??P,n[`--persona-icon-btn-active-bg`]=n[`--persona-icon-btn-active-bg`]??ae,te&&(n[`--persona-icon-btn-active-border`]=n[`--persona-icon-btn-active-border`]??N),n[`--persona-label-btn-hover-bg`]=n[`--persona-label-btn-hover-bg`]??P,n[`--persona-artifact-tab-hover-bg`]=n[`--persona-artifact-tab-hover-bg`]??P,n[`--persona-artifact-card-hover-bg`]=n[`--persona-artifact-card-hover-bg`]??P,n}const ed={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`};wi(),Ur();const td=e=>!!e&&`launcher`in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode===`docked`),nd=(e,t)=>{if(!t||!td(t))return e;let n=t.theme?.components?.panel?.width,r=t.darkTheme?.components?.panel?.width;return(pd(t)===`dark`?r??n:n)==null?{...e,components:{...e.components,panel:{...e.components.panel,width:li(t)===`v5`?`400px`:`420px`}}}:e},rd={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`}}},id={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)`}}}},ad=rd,od={...ad,colors:{...ad.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`}}},sd=id,cd={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:{...id.components,button:{...id.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:{...id.components?.eventStream,badge:{...id.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`}}}}},ld=e=>li({future:e})===`v5`?{palette:od,components:cd}:{palette:ad,components:sd},ud=e=>{if(e&&typeof e==`object`&&!Array.isArray(e))return e},dd=()=>typeof document<`u`&&document.documentElement.classList.contains(`dark`)||typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`,fd=e=>{let t=e?.colorScheme??`light`;return t===`light`?`light`:t===`dark`?`dark`:dd()},pd=e=>fd(e),md=(e,t={})=>Ju(e,t),hd=(e,t={})=>{let n=ld(t.future),r=Vr(n.components,e??{})??{};return Ju({...r,palette:{...r.palette,colors:li(t)===`v5`?Vr(n.palette.colors,r.palette?.colors):{...n.palette.colors,...r.palette?.colors}}},{validate:!1,future:t.future})},gd=e=>{let t=pd(e),n=ud(e?.theme),r=Vr({components:{launcher:Cu(e)===`circle`?wu:{...Ru.launcher,...e?.future?.v5Defaults?{offset:`1.5rem`}:{}}}},n),i=ud(e?.darkTheme);return nd(t===`dark`?hd(Vr(r??{},i??{}),{future:e?.future}):md(r,{future:e?.future}),e)},_d=e=>$u(e),vd=(e,t)=>{let n=gd(t),r=_d(n);for(let[t,n]of Object.entries(r))e.style.setProperty(t,n);e.setAttribute(`data-persona-color-scheme`,pd(t)),e.setAttribute(`data-persona-defaults`,li(t))},yd=e=>{let t=[];if(typeof document<`u`&&typeof MutationObserver<`u`){let n=new MutationObserver(()=>{e(dd())});n.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),t.push(()=>n.disconnect())}if(typeof window<`u`&&window.matchMedia){let n=window.matchMedia(`(prefers-color-scheme: dark)`),r=()=>e(dd());n.addEventListener?(n.addEventListener(`change`,r),t.push(()=>n.removeEventListener(`change`,r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(e=>e())}},bd=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??`720px`:`768px`),xd=(e,t)=>t||e?.composer?.placement!==`overlay`?`block`:`overlay`,Sd=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},Cd=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight),wd=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;m.Idiomorph.morph(e,t.innerHTML,{morphStyle:`innerHTML`,callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement&&r){if(e.classList.contains(`persona-animate-typing`)||e.hasAttribute(`data-preserve-runtime`))return!1;if(e.hasAttribute(`data-tool-elapsed`))return t instanceof HTMLElement&&t.getAttribute(`data-tool-elapsed`)===e.getAttribute(`data-tool-elapsed`)?!1:void 0;if(e.hasAttribute(`data-preserve-animation`))return t instanceof HTMLElement&&!t.hasAttribute(`data-preserve-animation`)||t instanceof HTMLElement&&t.hasAttribute(`data-preserve-animation`)&&(e.textContent??``)!==(t.textContent??``)?void 0:!1}}}})},Td=e=>e.replace(/^\n+/,``).replace(/\s+$/,``),Ed={index:-1,draft:``};function Dd(e){let{direction:t,history:n,currentValue:r,atStart:i,state:a}=e,o=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t===`up`){if(!o&&!i)return{handled:!1,state:a};if(!o){let e=n.length-1;return{handled:!0,value:n[e],state:{index:e,draft:r}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!o)return{handled:!1,state:a};if(a.index<n.length-1){let e=a.index+1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function Od(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 kd(){return/* @__PURE__ */ new Map}function Ad(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function jd(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Md(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Nd(e){return e.role!==`assistant`||e.variant===`tool`||e.variant===`reasoning`?!1:e.variant===`approval`||!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function Pd(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>!t&&(t=!0,!0)}}function Fd(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Id(e,t){return Fd(e)-e.scrollTop<=t}function Ld(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:i,userScrollThreshold:a,isAutoScrolling:o=!1,pauseOnUpwardScroll:s=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:l=!1}=e,u=n-r;return o||Math.abs(u)<a?{action:`none`,delta:u,nextLastScrollTop:n}:!t&&i&&(!l||u>0)?{action:`resume`,delta:u,nextLastScrollTop:n}:t&&s&&u<0||t&&c&&!i?{action:`pause`,delta:u,nextLastScrollTop:n}:{action:`none`,delta:u,nextLastScrollTop:n}}function Rd(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:i=!1}=e;return t&&n<0?`pause`:!t&&i&&n>0&&r?`resume`:`none`}function zd(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Bd(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset);return{targetScrollTop:t,spacerHeight:Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0))}}function Vd(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}const Hd={type:`none`,placeholder:`none`,speed:120,duration:1800,buffer:`none`},Ud=[`pre`,`code`,`a`,`script`,`style`],Wd=e=>({type:e?.type??Hd.type,placeholder:e?.placeholder??Hd.placeholder,speed:e?.speed??Hd.speed,duration:e?.duration??Hd.duration,buffer:e?.buffer??Hd.buffer}),Gd=[{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`}],Kd=/* @__PURE__ */ new Map;for(let e of Gd)Kd.set(e.name,e);const qd=[`wipe`,`glyph-cycle`],Jd=e=>{Kd.set(e.name,e)},Yd=e=>{Gd.some(t=>t.name===e)||Kd.delete(e)},Xd=()=>Array.from(Kd.keys()),Zd=(e,t)=>e===`none`?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Kd.get(e)??null,Qd=(e,t,n,r,i)=>{if(!i)return e;if(n?.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t===`word`){let t=e.search(/\s(?=\S*$)/);return t<0?``:e.slice(0,t)}if(t===`line`){let t=e.lastIndexOf(`
24
- `);return t<0?``:e.slice(0,t)}return e},$d=(e,t,n,r)=>{let i=e.createElement(`span`);return i.className=`persona-stream-char`,i.id=`stream-c-${n}-${r}`,i.style.setProperty(`--char-index`,String(r)),i.textContent=t,i},ef=(e,t,n,r)=>{let i=e.createElement(`span`);return i.className=`persona-stream-word`,i.id=`stream-w-${n}-${r}`,i.style.setProperty(`--word-index`,String(r)),i.textContent=t,i},tf=/\s/,nf=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let e=n;if(t.has(e.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},rf=(e,t,n)=>{let r=e.ownerDocument,i=e.parentNode;if(!r||!i)return;let a=e.nodeValue??``;if(!a)return;let o=r.createDocumentFragment(),s=0;for(;s<a.length;)if(tf.test(a[s])){let e=s;for(;e<a.length&&tf.test(a[e]);)e+=1;o.appendChild(r.createTextNode(a.slice(s,e))),s=e}else{let e=r.createElement(`span`);e.className=`persona-stream-word-group`;let i=s;for(;i<a.length&&!tf.test(a[i]);)e.appendChild($d(r,a[i],t,n.value)),n.value+=1,i+=1;o.appendChild(e),s=i}i.replaceChild(o,e)},af=(e,t,n)=>{let r=e.ownerDocument,i=e.parentNode;if(!r||!i)return;let a=e.nodeValue??``;if(!a)return;let o=r.createDocumentFragment(),s=a.split(/(\s+)/);for(let e of s)e&&(/^\s+$/.test(e)?o.appendChild(r.createTextNode(e)):(o.appendChild(ef(r,e,t,n.value)),n.value+=1));i.replaceChild(o,e)},of=(e,t,n,r)=>{if(!e||typeof document>`u`)return e;let i=document.createElement(`div`);i.innerHTML=e;let a=new Set((r?.skipTags??Ud).map(e=>e.toLowerCase())),o=document.createTreeWalker(i,NodeFilter.SHOW_TEXT,null),s=[],c=o.nextNode();for(;c;)nf(c,a)||s.push(c),c=o.nextNode();let l={value:r?.startIndex??0},u=t===`char`?rf:af;for(let e of s)u(e,n,l);return i.innerHTML},sf=(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},cf=(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},lf=/* @__PURE__ */ new WeakMap,uf=(e,t)=>{if(!e.styles)return;let n=lf.get(t);if(n||(n=/* @__PURE__ */ new Set,lf.set(t,n)),n.has(e.name)){let r=e.name.replace(/["\\]/g,`\\$&`);if(t.querySelector(`style[data-persona-animation="${r}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement(`style`);r.setAttribute(`data-persona-animation`,e.name),r.textContent=e.styles,t.appendChild(r)},df=/* @__PURE__ */ new WeakMap,ff=(e,t)=>{if(!e.onAttach)return;let n=df.get(t);if(n||(n=/* @__PURE__ */ new Map,df.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},pf=e=>{let t=df.get(e);if(t){for(let e of t.values())typeof e==`function`&&e();t.clear()}},mf=(e,t)=>{uf(e,t),ff(e,t)};g();const{setLoader:hf,load:gf}=h({fallbackImport:()=>import(`@runtypelabs/persona/animations-extra`)}),_f=gf;dn();function vf(e,t=ln){let n=e.style.position,r=e.style.zIndex,i=e.style.isolation,a=getComputedStyle(e),o=a.position===`static`||a.position===``;return o&&(e.style.position=`relative`),e.style.zIndex=String(t),e.style.isolation=`isolate`,()=>{o&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=i}}let yf=0,bf=null;function xf(e=document){if(yf++,yf===1){let t=e.body,n=(e.defaultView??window).scrollY||e.documentElement.scrollTop;bf={originalOverflow:t.style.overflow,originalPosition:t.style.position,originalTop:t.style.top,originalWidth:t.style.width,scrollY:n},t.style.overflow=`hidden`,t.style.position=`fixed`,t.style.top=`-${n}px`,t.style.width=`100%`}let t=!1;return()=>{if(!t&&(t=!0,yf=Math.max(0,yf-1),yf===0&&bf)){let t=e.body,n=e.defaultView??window;t.style.overflow=bf.originalOverflow,t.style.position=bf.originalPosition,t.style.top=bf.originalTop,t.style.width=bf.originalWidth,n.scrollTo(0,bf.scrollY),bf=null}}}ci();const Sf={side:`right`,width:`420px`,animate:!0,reveal:`resize`,maxHeight:`100dvh`},Cf=e=>(e?.launcher?.mountMode??`floating`)===`docked`,wf=e=>(e?.launcher?.mountMode??`floating`)===`composer-bar`,Tf=e=>{let t=e?.launcher?.dock,n=ii(e).dockWidth?t?.width:Uu(gd(e),`components.panel.width`);return{side:t?.side??Sf.side,width:n??Sf.width,animate:t?.animate??Sf.animate,reveal:t?.reveal??Sf.reveal,maxHeight:t?.maxHeight??Sf.maxHeight}};H(),I(),A();const Ef=e=>e===`followUp`?`follow-up`:e,Df=(e,t=0)=>{if(typeof e==`string`){let t=e.trim();return t?{id:t,label:t,prompt:t,emphasis:`default`}:null}let n=e.label.trim();if(!n)return null;let r=e.prompt?.trim()||n;return{id:e.id?.trim()||r||`suggestion-${t}`,label:n,prompt:r,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??`default`}},Of=/* @__PURE__ */ new WeakSet,kf=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,Af=e=>{kf()||e.forEach((e,t)=>{typeof e.animate==`function`&&e.animate([{opacity:`0`,transform:`translateY(4px)`},{opacity:`1`,transform:`none`}],{duration:250,delay:t*60,easing:`ease-out`,fill:`backwards`})})},jf=e=>{let{item:t,index:n,surface:r,source:i,variant:a,streaming:o,config:s,plugins:c,chipsConfig:l,session:u,getTextarea:d,eventTarget:p,submitPrompt:m}=e,h=r===`followUp`,g=t.behavior,_=()=>{if(u.isStreaming())return;let e={suggestion:{...t},surface:r,source:i,behavior:g},n=p.dispatchEvent(new CustomEvent(`persona:suggestion:selected`,{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(h&&p.dispatchEvent(new CustomEvent(`persona:suggestReplies:selected`,{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!n)return;for(let e of c)if(e.onSuggestionSelect?.({suggestion:{...t},surface:r,source:i,variant:a,config:s})===!1)return;let o=d();g===`fill`?(o.value=t.prompt,o.dispatchEvent(new Event(`input`,{bubbles:!0,composed:!0})),o.focus()):m?m(t.prompt):(o.value=``,u.sendMessage(t.prompt))},v=()=>{let e=B(`button`,`persona-suggestion persona-suggestion--${a}`);if(e.type=`button`,e.disabled=o,e.dataset.suggestionId=t.id,e.dataset.emphasis=t.emphasis,e.dataset.behavior=g,a===`chip`&&(l?.fontWeight&&(e.style.fontWeight=l.fontWeight),l?.paddingX&&(e.style.paddingLeft=l.paddingX,e.style.paddingRight=l.paddingX),l?.paddingY&&(e.style.paddingTop=l.paddingY,e.style.paddingBottom=l.paddingY)),t.icon){let n=F(t.icon,`var(--persona-suggestion-icon-size)`,`currentColor`,1.8);n&&(n.classList.add(`persona-suggestion__icon`),t.iconColor&&(n.style.color=t.iconColor),e.appendChild(n))}let n=B(`span`,`persona-suggestion__copy`);if(n.appendChild(V(`span`,{className:`persona-suggestion__label`,text:t.label})),t.description&&a!==`chip`&&n.appendChild(V(`span`,{className:`persona-suggestion__description`,text:t.description})),e.appendChild(n),a!==`chip`){let t=k(f.ArrowRight,16,`currentColor`,1.8);t&&(t.classList.add(`persona-suggestion__arrow`),e.appendChild(t))}return e.addEventListener(`click`,_),e},y=null;for(let e of c)if(e.renderSuggestion&&(y=e.renderSuggestion({suggestion:{...t},index:n,surface:r,source:i,variant:a,streaming:o,config:s,defaultRenderer:v,select:_}),y))break;return y??=v(),y.dataset.suggestionId||=t.id,y.dataset.behavior||=g,y.dataset.emphasis||=t.emphasis,y instanceof HTMLButtonElement||y.setAttribute(`aria-disabled`,o?`true`:`false`),y},Mf=e=>{let t=[],n=[],r=null,i=null,a=()=>{e.removeAttribute(`data-scroll-left`),e.removeAttribute(`data-scroll-right`)},o=()=>{if(i=null,e.hidden||e.dataset.variant!==`chip`||e.dataset.overflow!==`scroll`){a();return}let t=Math.max(0,e.scrollWidth-e.clientWidth);if(t<=1){a();return}let n=getComputedStyle(e).direction===`rtl`,r=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),o=r<=4,s=r>=t-4,c=n?!s:!o,l=n?!o:!s;e.toggleAttribute(`data-scroll-left`,c),e.toggleAttribute(`data-scroll-right`,l)},s=()=>{i!==null||typeof requestAnimationFrame!=`function`?typeof requestAnimationFrame!=`function`&&o():i=requestAnimationFrame(o)};e.addEventListener(`scroll`,s,{passive:!0});let c=typeof ResizeObserver==`function`?new ResizeObserver(s):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener(`scroll`,s),c?.disconnect(),i!==null&&typeof cancelAnimationFrame==`function`&&cancelAnimationFrame(i),i=null},render:(i,c,l,u,d,f)=>{e.replaceChildren(),t.length=0,n.length=0;let p=f?.source??`config`,m=f?.surface??(p===`config`?`starter`:`followUp`),h=m===`followUp`,g=f?.variant??`chip`,_=f?.behavior??`send`,v=f?.overflow??`wrap`,y=f?.config??{},b=f?.plugins??[],x=typeof f?.maxItems==`number`?Math.max(0,Math.floor(f.maxItems)):void 0,S=h?`followUps`:`starters`;!Of.has(y)&&y.debug===!0&&g!==`chip`&&y.suggestions?.[S]?.overflow!==void 0&&(Of.add(y),console.info(`[persona] suggestions.${S}.overflow applies to the "chip" variant only; the "${g}" variant manages its own stacking.`));let C=e=>e.map(Df).filter(e=>e!==null).map(e=>({...e,behavior:e.behavior??_})),w=C(i??[]);b.forEach(e=>{e.transformSuggestions&&(w=C(e.transformSuggestions({suggestions:w.map(e=>({...e})),surface:m,source:p,config:y})))});let T=x===void 0?w:w.slice(0,x);if(!T.length){e.hidden=!0,r=null,a();return}if(!h&&(u??c.getMessages()).some(e=>e.role===`user`)){e.hidden=!0,r=null;return}e.hidden=!1,e.classList.add(`persona-suggestions`),e.dataset.personaSuggestionSurface=Ef(m),e.dataset.variant=g,e.dataset.overflow=v;let E=document.createDocumentFragment(),D=c.isStreaming();T.forEach((r,i)=>{let a=jf({item:r,index:i,surface:m,source:p,variant:g,streaming:D,config:y,plugins:b,chipsConfig:d,session:c,getTextarea:()=>l,eventTarget:e,submitPrompt:f?.submitPrompt});E.appendChild(a),n.push(a),[...a instanceof HTMLButtonElement?[a]:[],...Array.from(a.querySelectorAll(`button`))].forEach(e=>{t.includes(e)||(e.disabled=D,t.push(e))})}),e.appendChild(E),o(),s();let O=JSON.stringify({normalized:T,surface:m,variant:g,source:p});O!==r&&(r=O,Af(n),e.dispatchEvent(new CustomEvent(`persona:suggestion:shown`,{detail:{suggestions:T.map(e=>({...e})),surface:m,source:p,variant:g},bubbles:!0,composed:!0})),h&&e.dispatchEvent(new CustomEvent(`persona:suggestReplies:shown`,{detail:{suggestions:T.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},Nf={"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`};H(),I(),Ir();const Pf={x:[1.4,1.05]},Ff=`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`,If=(e,t,n={})=>{let{iconSize:r,iconText:i}=n,[a,o]=Pf[t]??[1,1.5],s=!r;e.classList.toggle(`persona-header-control--glyph`,s),e.classList.toggle(`persona-header-control--sparse`,s&&a!==1);let c=F(t,`${Math.round((parseFloat(r??``)||20)*a)}px`,`currentColor`,o);c?(c.style.display=`block`,s||(c.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((o/1.5).toFixed(4))})`),e.replaceChildren(c)):i&&(e.textContent=i)},Lf=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:r,iconName:i,iconText:a,wrapperClassName:o=Ff,size:s,iconSize:c,color:l,backgroundColor:u,borderWidth:d,borderColor:f,borderRadius:p,paddingX:m,paddingY:h,hidden:g,extraClassName:_,attrs:v}=e,y=B(`div`,o),b=!!(d||f),x=V(`button`,{className:Qe(`persona-header-control`,`persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer`,!u&&`persona-bg-transparent hover:persona-bg-gray-100`,!b&&`persona-border-none`,!p&&`persona-rounded-full`,_),attrs:{type:`button`,"aria-label":t,...v},style:{width:s,height:s,minWidth:s,minHeight:s,display:g?`none`:void 0,color:l||Bf.actionIconColor,backgroundColor:u,border:b?`${d||`0px`} solid ${f||`transparent`}`:void 0,borderRadius:p,paddingLeft:m,paddingRight:m,paddingTop:h,paddingBottom:h}});return i?If(x,i,{iconSize:c,iconText:a}):a&&(x.textContent=a),y.appendChild(x),yr({anchor:x,trigger:y,text:()=>x.getAttribute(`aria-label`)??t,hint:r,enabled:n}),{button:x,wrapper:y}},Rf=(e,t={})=>{let{showClose:n=!0,wrapperClassName:r=Ff,buttonSize:i,iconSize:a}=t,o=e?.launcher??{},s=o.closeButtonTooltipText??`Close chat`,c=o.closeButtonShowTooltip??!0,{button:l,wrapper:u}=Lf({ariaLabel:s,tooltip:c,iconName:o.closeButtonIconName??`x`,iconText:o.closeButtonIconText??`×`,wrapperClassName:r,size:i??o.closeButtonSize,iconSize:a,color:o.closeButtonColor,backgroundColor:o.closeButtonBackgroundColor,borderWidth:o.closeButtonBorderWidth,borderColor:o.closeButtonBorderColor,borderRadius:o.closeButtonBorderRadius,paddingX:o.closeButtonPaddingX,paddingY:o.closeButtonPaddingY,hidden:!n});return{button:l,wrapper:u}},zf=(e,t={})=>{let{wrapperClassName:n=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,buttonSize:r,iconSize:i}=t,a=(e?.launcher??{}).clearChat??{},o=a.tooltipText??`Clear chat`,s=a.showTooltip??!0,{button:c,wrapper:l}=Lf({ariaLabel:o,tooltip:s,iconName:a.iconName??`refresh-cw`,wrapperClassName:n,size:r??a.size,iconSize:i,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:c,wrapper:l}};H(),I(),wi();const Bf={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)`},Vf={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)`},Hf={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)`},Uf=e=>{let{config:t,showClose:n=!0}=e,r=V(`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:Bf.minHeight,backgroundColor:`var(--persona-header-bg, var(--persona-surface, #ffffff))`,borderBottomColor:`var(--persona-header-border, var(--persona-divider, #f1f5f9))`,boxShadow:`var(--persona-header-shadow, none)`,borderBottom:`var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))`}}),i=t?.launcher??{},a=i.headerIconSize??`40px`,o=i.closeButtonPlacement??`inline`,s=i.headerIconHidden??!1,c=i.headerIconName,l=V(`div`,{className:`persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl`,style:{height:a,width:a,backgroundColor:`var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))`,color:`var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))`}});if(!s){if(c){let e=parseFloat(a)||24,n=F(c,e*.6,`currentColor`,1);n?(n.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,n.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,l.replaceChildren(n)):l.textContent=t?.launcher?.agentIconText??`💬`}else if(t?.launcher?.iconUrl){let e=B(`img`);e.src=t.launcher.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=a,e.style.width=a,l.replaceChildren(e)}else l.textContent=t?.launcher?.agentIconText??`💬`}let u=B(`div`,`persona-flex persona-flex-col persona-flex-1 persona-min-w-0`),d=V(`span`,{className:`persona-text-base persona-font-semibold`,text:t?.launcher?.title??`Chat Assistant`,style:{color:Bf.titleColor,...Vf}}),f=V(`span`,{className:`persona-text-xs`,text:t?.launcher?.subtitle??`Here to help you get answers fast`,style:{color:Bf.subtitleColor,...Hf}});u.append(d,f),s?r.append(u):r.append(l,u);let p=i.clearChat??{},m=p.enabled??!0,h=p.placement??`inline`,g=null,_=null;if(m){let e=zf(t,{wrapperClassName:h===`top-right`?`persona-absolute persona-top-4 persona-z-50`:`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`});g=e.button,_=e.wrapper,h===`top-right`&&(_.style.right=`48px`),h===`inline`&&r.appendChild(_)}let{button:v,wrapper:y}=Rf(t,{showClose:n,wrapperClassName:o===`top-right`?`persona-absolute persona-top-4 persona-right-4 persona-z-50`:m&&h===`inline`?`persona-relative persona-inline-flex persona-items-center persona-justify-center`:`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`});return o!==`top-right`&&r.appendChild(y),{header:r,iconHolder:l,headerTitle:d,headerSubtitle:f,closeButton:v,closeButtonWrapper:y,clearChatButton:g,clearChatButtonWrapper:_}},Wf=(e,t,n)=>{let r=n?.launcher??{},i=r.closeButtonPlacement??`inline`,a=r.clearChat?.placement??`inline`;e.appendChild(t.header),i===`top-right`&&(e.style.position=`relative`,e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a===`top-right`&&(e.style.position=`relative`,e.appendChild(t.clearChatButtonWrapper))};H(),I(),dn();function Gf(e){let{items:t,onSelect:n,anchor:r,position:i=`bottom-left`,portal:a,onOpenChange:o}=e,s=B(`div`,`persona-dropdown-menu persona-hidden`);s.setAttribute(`role`,`menu`),s.setAttribute(`data-persona-theme-zone`,`dropdown`),a?(s.style.position=`fixed`,s.style.zIndex=String(un)):(s.style.position=`absolute`,s.style.top=`100%`,s.style.marginTop=`4px`,i===`bottom-right`?s.style.right=`0`:s.style.left=`0`);for(let e of t){if(e.dividerBefore){let e=document.createElement(`hr`);s.appendChild(e)}let t=document.createElement(`button`);if(t.type=`button`,t.setAttribute(`role`,`menuitem`),t.setAttribute(`data-dropdown-item-id`,e.id),e.destructive&&t.setAttribute(`data-destructive`,``),e.icon){let n=F(e.icon,16,`currentColor`,1.5);n&&t.appendChild(n)}let r=document.createElement(`span`);r.textContent=e.label,t.appendChild(r),t.addEventListener(`click`,t=>{t.stopPropagation(),d(),n(e.id)}),s.appendChild(t)}let c=null;function l(){if(!a)return;let e=r.getBoundingClientRect();s.style.top=`${e.bottom+4}px`,i===`bottom-right`?(s.style.right=`${window.innerWidth-e.right}px`,s.style.left=`auto`):(s.style.left=`${e.left}px`,s.style.right=`auto`)}function u(){let e=s.classList.contains(`persona-hidden`);l(),s.classList.remove(`persona-hidden`),e&&o?.(!0),requestAnimationFrame(()=>{let e=e=>{!s.contains(e.target)&&!r.contains(e.target)&&d()};document.addEventListener(`click`,e,!0),c=()=>document.removeEventListener(`click`,e,!0)})}function d(){let e=!s.classList.contains(`persona-hidden`);s.classList.add(`persona-hidden`),c?.(),c=null,e&&o?.(!1)}function f(){s.classList.contains(`persona-hidden`)?u():d()}function p(){d(),s.remove()}return a&&a.appendChild(s),{element:s,show:u,hide:d,toggle:f,destroy:p}}H(),I();function Kf(e){let{icon:t,label:n,size:r,strokeWidth:i,className:a,chromeless:o,onClick:s,aria:c}=e,l=B(`button`,Qe(!o&&`persona-icon-btn`,a));l.type=`button`,l.setAttribute(`aria-label`,n),l.title=n;let u=F(t,r??16,`currentColor`,i??2);if(u&&l.appendChild(u),s&&l.addEventListener(`click`,s),c)for(let[e,t]of Object.entries(c))l.setAttribute(e,t);return l}function qf(e){let{icon:t,label:n,variant:r=`default`,size:i=`sm`,iconSize:a,className:o,onClick:s,aria:c}=e,l=`persona-label-btn`;r!=="default"&&(l+=` persona-label-btn--`+r),l+=` persona-label-btn--`+i,o&&(l+=` `+o);let u=B(`button`,l);if(u.type=`button`,u.setAttribute(`aria-label`,n),t){let e=F(t,a??14,`currentColor`,2);e&&u.appendChild(e)}let d=B(`span`);if(d.textContent=n,u.appendChild(d),s&&u.addEventListener(`click`,s),c)for(let[e,t]of Object.entries(c))u.setAttribute(e,t);return u}function Jf(e){let{items:t,selectedId:n,onSelect:r,className:i}=e,a=B(`div`,`persona-toggle-group`+(i?` `+i:``));a.setAttribute(`role`,`group`);let o=n,s=[];function c(){for(let e of s)e.btn.setAttribute(`aria-pressed`,e.id===o?`true`:`false`)}for(let e of t){let t;e.icon?t=Kf({icon:e.icon,label:e.label,className:e.className,onClick:()=>{o=e.id,c(),r(e.id)}}):(t=B(`button`,`persona-icon-btn`+(e.className?` `+e.className:``)),t.type=`button`,t.setAttribute(`aria-label`,e.label),t.title=e.label,t.textContent=e.label,t.addEventListener(`click`,()=>{o=e.id,c(),r(e.id)})),t.setAttribute(`aria-pressed`,e.id===o?`true`:`false`),s.push({id:e.id,btn:t}),a.appendChild(t)}function l(e){o=e,c()}return{element:a,setSelected:l}}function Yf(e){let{label:t,icon:n,iconSize:r,iconOnly:i,menuItems:a,onSelect:o,onPrimary:s,position:c=`bottom-left`,portal:l,chevronLabel:u=`More options`,chevronIconSize:d,className:f,primaryClassName:p,chevronClassName:m}=e,h=B(`div`,`persona-split-btn`+(f?` `+f:``)),g={label:t,className:`persona-split-btn-primary`+(p?` `+p:``),onClick:s},_=i&&n?Kf({...g,icon:n,size:r??14}):qf({...g,icon:n,iconSize:r??14}),v=Kf({icon:`chevron-down`,label:u,size:d??14,className:`persona-split-btn-chevron`+(m?` `+m:``),aria:{"aria-haspopup":`true`,"aria-expanded":`false`}});h.append(_,v);let y=null,b=()=>{if(y)return y;let e=(typeof l==`function`?l():l)??void 0;return y=Gf({items:a,onSelect:o,anchor:h,position:c,portal:e,onOpenChange:e=>{v.setAttribute(`aria-expanded`,e?`true`:`false`)}}),e||h.appendChild(y.element),y};return h.isConnected?b():requestAnimationFrame(()=>{y||b()}),v.addEventListener(`click`,e=>{e.stopPropagation(),b().toggle()}),{element:h,primaryButton:_,chevronButton:v,openMenu:()=>b().show(),closeMenu:()=>y?.hide(),toggleMenu:()=>b().toggle(),destroy:()=>{y?.destroy(),h.remove()}}}function Xf(e){let{label:t,icon:n=`chevron-down`,menuItems:r,onSelect:i,position:a=`bottom-left`,portal:o,className:s,hover:c}=e,l=B(`div`,`persona-combo-btn`+(s?` `+s:``));l.style.position=`relative`,l.style.display=`inline-flex`,l.style.alignItems=`center`,l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`),l.setAttribute(`aria-haspopup`,`true`),l.setAttribute(`aria-expanded`,`false`),l.setAttribute(`aria-label`,t);let u=B(`span`,`persona-combo-btn-label`);u.textContent=t,l.appendChild(u);let d=F(n,14,`currentColor`,2);d&&(d.style.marginLeft=`4px`,d.style.opacity=`0.6`,l.appendChild(d)),c&&(l.style.borderRadius=c.borderRadius??`10px`,l.style.padding=c.padding??`6px 4px 6px 12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=c.background??``,l.style.borderColor=c.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}));let f=Gf({items:r,onSelect:e=>{l.setAttribute(`aria-expanded`,`false`),i(e)},anchor:l,position:a,portal:o});o||l.appendChild(f.element);let p=()=>l.getAttribute(`data-persona-menu-locked`)===`true`;return l.addEventListener(`click`,e=>{if(e.stopPropagation(),p())return;let t=!f.element.classList.contains(`persona-hidden`);l.setAttribute(`aria-expanded`,t?`false`:`true`),f.toggle()}),l.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),l.click())}),{element:l,setLabel:e=>{u.textContent=e,l.setAttribute(`aria-label`,e)},open:()=>{l.setAttribute(`aria-expanded`,`true`),f.show()},close:()=>{l.setAttribute(`aria-expanded`,`false`),f.hide()},toggle:()=>{let e=!f.element.classList.contains(`persona-hidden`);l.setAttribute(`aria-expanded`,e?`false`:`true`),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}H(),To();const Zf=e=>{let t=Uf({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let e=t.headerTitle.parentElement;e&&(e.style.cursor=`pointer`,e.setAttribute(`role`,`button`),e.setAttribute(`tabindex`,`0`),e.addEventListener(`click`,()=>n()),e.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n())}))}return t};function Qf(e,t,n){if(t?.length)for(let r of t){let{button:t,wrapper:i}=Lf({ariaLabel:r.ariaLabel??r.label??r.id,iconName:r.icon,iconText:r.icon?void 0:r.label,tooltipHint:r.shortcut?bo(r.shortcut):void 0,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`});if(t.setAttribute(`data-persona-header-action`,r.id),r.shortcut){let e=xo(r.shortcut);e&&t.setAttribute(`aria-keyshortcuts`,e)}if(r.menuItems?.length){let e=Gf({items:r.menuItems,onSelect:e=>n?.(e),anchor:i,position:`bottom-right`});i.appendChild(e.element),t.addEventListener(`click`,t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener(`click`,()=>n?.(r.id));e.appendChild(i)}}const $f=e=>{let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:i,onHeaderAction:a}=e,o=t?.launcher??{},s=B(`div`,`persona-flex persona-items-center persona-justify-between`);s.setAttribute(`data-persona-theme-zone`,`header`),s.style.minHeight=Bf.minHeight,s.style.padding=`var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))`,s.style.backgroundColor=`var(--persona-header-bg, var(--persona-surface, #ffffff))`,s.style.borderBottomColor=`var(--persona-header-border, var(--persona-divider, #f1f5f9))`,s.style.boxShadow=`var(--persona-header-shadow, none)`,s.style.borderBottom=`var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))`;let c=i?.titleMenu,l,u;if(c){let e=Xf({label:o.title??`Chat Assistant`,menuItems:c.menuItems,onSelect:t=>{let n=n=>{n===!1&&e.element.dispatchEvent(new CustomEvent(`persona:title-menu-builtin`,{bubbles:!0,composed:!0,detail:{actionId:t}}))},r=c.onSelect(t);r instanceof Promise?r.then(n,()=>{}):n(r)},hover:c.hover,className:``});l=e.element,l.style.color=Bf.titleColor,u=l.querySelector(`.persona-combo-btn-label`)??l}else{if(l=B(`div`,`persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1`),u=B(`span`,`persona-text-base persona-font-semibold persona-truncate`),u.style.color=Bf.titleColor,Object.assign(u.style,Vf),u.textContent=o.title??`Chat Assistant`,l.appendChild(u),i?.onTitleClick){l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`);let e=i.onTitleClick;l.addEventListener(`click`,t=>{t.target.closest(`button`)||e()}),l.addEventListener(`keydown`,t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e())})}let e=i?.titleRowHover;e&&(l.style.borderRadius=e.borderRadius??`10px`,l.style.padding=e.padding??`6px 4px 6px 12px`,l.style.margin=`-6px 0 -6px -12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.style.width=`fit-content`,l.style.flex=`none`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=e.background??``,l.style.borderColor=e.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}))}s.appendChild(l);let d=`persona-relative persona-inline-flex persona-items-center persona-justify-center`,{button:f,wrapper:p}=Rf(t,{showClose:n,wrapperClassName:d});r&&f.addEventListener(`click`,r);let m=B(`div`,`persona-flex persona-items-center persona-gap-1`);c||Qf(m,i?.trailingActions,i?.onAction??a);let h=o.clearChat??{},g=null,_=null;if(h.enabled??!0){let e=h.placement??`inline`,n=zf(t,{wrapperClassName:e===`top-right`?`persona-absolute persona-top-4 persona-z-50`:d});g=n.button,_=n.wrapper,e===`top-right`?_.style.right=`48px`:m.appendChild(_)}m.appendChild(p),s.appendChild(m);let v=B(`div`);v.style.display=`none`;let y=B(`span`);return y.style.display=`none`,{header:s,iconHolder:v,headerTitle:u,headerSubtitle:y,closeButton:f,closeButtonWrapper:p,clearChatButton:g,clearChatButtonWrapper:_}},ep={default:Zf,minimal:$f},tp=e=>ep[e]??ep.default,np=(e,t,n)=>{if(t?.render){let r=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=B(`div`);i.style.display=`none`;let a=B(`span`),o=B(`span`),s=B(`button`);s.style.display=`none`;let c=B(`div`);return c.style.display=`none`,{header:r,iconHolder:i,headerTitle:a,headerSubtitle:o,closeButton:s,closeButtonWrapper:c,clearChatButton:null,clearChatButtonWrapper:null}}let r=t?.layout??`default`,i=tp(r)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(i.iconHolder.style.display=`none`),t.showTitle===!1&&(i.headerTitle.style.display=`none`),t.showSubtitle===!1&&(i.headerSubtitle.style.display=`none`),t.showCloseButton===!1&&(i.closeButton.style.display=`none`),t.showClearChat===!1&&i.clearChatButtonWrapper&&(i.clearChatButtonWrapper.style.display=`none`)),i};H(),da();const rp=e=>{let{config:t}=e,n=V(`div`,{className:`persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4`,attrs:{"data-persona-theme-zone":`composer`}}),r=ua(),i=V(`form`,{className:`persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3`,attrs:{"data-persona-composer-form":``}}),{textarea:a,attachAutoResize:o}=ia(t);o();let s=oa(t),c=sa(t),l=ca(t),u=la(t),d=V(`div`,{className:`persona-widget-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});i.append(d),l&&(l.previewsContainer.style.gap=`8px`,d.append(l.previewsContainer),i.append(l.input)),i.append(a);let f=V(`div`,{className:`persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full`,attrs:{"data-persona-composer-actions":``}}),p=V(`div`,{className:`persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-start":``}}),m=V(`div`,{className:`persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-end":``}});return l&&p.append(l.wrapper),c&&m.append(c.wrapper),m.append(s.wrapper),f.append(p,m),i.append(f),i.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),t?.statusIndicator?.mode===`transient`?n.append(r,u,i):n.append(r,i,u),{footer:n,suggestions:r,composerForm:i,header:d,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:u,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:f,leftActions:p,rightActions:m,setSendButtonMode:s.setMode}};H(),A(),da(),ea();const ip=()=>{let e=V(`button`,{className:`persona-pill-peek`,attrs:{type:`button`,"data-persona-pill-peek":``,"aria-label":`Show conversation`,tabindex:`-1`}}),t=B(`span`,`persona-pill-peek__icon`),n=k(f.MessageSquare,16,`currentColor`,1.5);n&&t.appendChild(n);let r=B(`span`,`persona-pill-peek__text`),i=B(`span`,`persona-pill-peek__caret`),a=k(f.ChevronUp,16,`currentColor`,1.5);return a&&i.appendChild(a),e.append(t,r,i),{root:e,textNode:r}},ap=e=>{let{config:t}=e,n=V(`div`,{className:`persona-widget-footer persona-widget-footer--pill`,attrs:{"data-persona-theme-zone":`composer`}}),r=ua(),i=la(t);i.style.display=`none`;let{textarea:a,attachAutoResize:o}=ia(t,{defaultMaxLines:5});o();let s=oa(t),c=sa(t),l=ca(t);l&&l.previewsContainer.classList.add(`persona-pill-composer__previews`);let u=V(`form`,{className:`persona-widget-composer persona-pill-composer`,attrs:{"data-persona-composer-form":``}}),d=V(`div`,{className:`persona-widget-composer__left-actions persona-pill-composer__left`,attrs:{"data-persona-composer-actions-start":``}});l&&d.append(l.wrapper);let f=V(`div`,{className:`persona-widget-composer__right-actions persona-pill-composer__right`,attrs:{"data-persona-composer-actions-end":``}});c&&f.append(c.wrapper),f.append(s.wrapper),u.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),l&&u.append(l.input),u.append(d,a,f);let p=V(`div`,{className:`persona-pill-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});n.append(p),l&&p.append(l.previewsContainer),n.append(r,u,i);let m=u;return{footer:n,suggestions:r,composerForm:u,header:p,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:i,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:m,leftActions:d,rightActions:f,setSendButtonMode:s.setMode}};H(),Ca(),I(),Ui();const op=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}},sp=(e,t)=>{if(!e)return null;let n=op(e);if(n===null)return null;let r=t?.[e];return(r===void 0?n:r)||null},cp=(e,t)=>{let n=B(`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},lp=e=>{let t=e.toLowerCase();return!t.startsWith(`data:image/svg+xml`)&&!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:image/`)||!e.includes(`:`))},up=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(`:`))},dp=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`image`&&typeof e.image==`string`&&e.image.trim().length>0),fp=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`audio`&&typeof e.audio==`string`&&e.audio.trim().length>0),pp=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`video`&&typeof e.video==`string`&&e.video.trim().length>0),mp=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`file`&&typeof e.data==`string`&&e.data.trim().length>0),hp=e=>{if(!e||e.length===0)return null;let t=V(`div`,{className:`persona-mention-context-row persona-message-mentions`,attrs:{"data-message-mentions":``}});t.style.display=`flex`;for(let n of e){let e=V(`div`,{className:`persona-mention-chip persona-mention-chip-readonly`,attrs:{"data-status":`ready`,title:n.label}}),r=B(`span`,`persona-mention-chip-icon`),i=F(n.iconName??`at-sign`,13,`currentColor`,2);i&&r.appendChild(i),e.appendChild(r),e.appendChild(V(`span`,{className:`persona-mention-chip-label`,text:n.label})),t.appendChild(e)}return t},gp=(e,t)=>{let n=document.createDocumentFragment();for(let r of e)r.kind===`text`?n.appendChild(document.createTextNode(r.text)):n.appendChild(Sa(r.ref,{readonly:!0,render:t}));return n},_p=(e,t,n,r)=>{let i=Math.random().toString(36).slice(2,8),a=e=>`${i}:${e}`,o=n(t.map((e,t)=>e.kind===`text`?e.text:a(t)).join(``));if(!t.every((e,t)=>e.kind===`text`||o.includes(a(t)))){e.replaceChildren(gp(t,r));return}e.innerHTML=o;let s=RegExp(`${i}:(\\d+)`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),l=[];for(let e=c.nextNode();e;e=c.nextNode())l.push(e);for(let e of l){let n=e;for(let e=s.exec(n.data);e;e=s.exec(n.data)){let i=t[Number(e[1])],a=n.splitText(e.index);a.data=a.data.slice(e[0].length),i?.kind===`mention`&&a.parentNode?.insertBefore(Sa(i.ref,{readonly:!0,render:r}),a),n=a}}},vp=(e,t,n)=>{if(e.length===0)return null;try{let r=B(`div`,`persona-flex persona-flex-col persona-gap-2`);r.setAttribute(`data-message-attachments`,`images`),t&&(r.style.marginBottom=`8px`);let i=0,a=!1,o=()=>{a||(a=!0,r.remove(),n?.())};return e.forEach((e,t)=>{let n=B(`img`);n.alt=e.alt?.trim()||`Attached image ${t+1}`,n.loading=`lazy`,n.decoding=`async`,n.referrerPolicy=`no-referrer`,n.style.display=`block`,n.style.width=`100%`,n.style.maxWidth=`320px`,n.style.maxHeight=`320px`,n.style.height=`auto`,n.style.objectFit=`contain`,n.style.borderRadius=`10px`,n.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,n.style.border=`1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))`;let a=!1;i+=1,n.addEventListener(`error`,()=>{a||(a=!0,i=Math.max(0,i-1),n.remove(),i===0&&o())}),n.addEventListener(`load`,()=>{a=!0}),lp(e.image)?(n.src=e.image,r.appendChild(n)):(a=!0,i=Math.max(0,i-1),n.remove())}),i===0?(o(),null):r}catch{return n?.(),null}},yp=e=>{if(e.length===0)return null;try{let t=B(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`audio`);let n=0;return e.forEach(e=>{if(!up(e.audio))return;let r=B(`audio`);r.controls=!0,r.preload=`metadata`,r.src=e.audio,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},bp=e=>{if(e.length===0)return null;try{let t=B(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`video`);let n=0;return e.forEach(e=>{if(!up(e.video))return;let r=B(`video`);r.controls=!0,r.preload=`metadata`,r.src=e.video,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,r.style.maxHeight=`320px`,r.style.borderRadius=`10px`,r.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},xp=e=>{if(e.length===0)return null;try{let t=B(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`files`);let n=0;return e.forEach(e=>{if(!up(e.data))return;let r=B(`a`);r.href=e.data,r.download=e.filename,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=e.filename,r.className=`persona-message-file-attachment`,r.style.display=`inline-flex`,r.style.alignItems=`center`,r.style.gap=`6px`,r.style.padding=`6px 10px`,r.style.borderRadius=`8px`,r.style.fontSize=`0.875rem`,r.style.textDecoration=`underline`,r.style.backgroundColor=`var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))`,r.style.border=`1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))`,r.style.color=`inherit`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Sp=()=>{let e=document.createElement(`div`);e.className=`persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2`;let t=document.createElement(`div`);t.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,t.style.backgroundColor=`currentColor`,t.style.opacity=`0.4`,t.style.animationDelay=`0ms`;let n=document.createElement(`div`);n.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,n.style.backgroundColor=`currentColor`,n.style.opacity=`0.4`,n.style.animationDelay=`250ms`;let r=document.createElement(`div`);r.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,r.style.backgroundColor=`currentColor`,r.style.opacity=`0.4`,r.style.animationDelay=`500ms`;let i=document.createElement(`span`);return i.className=`persona-sr-only`,i.textContent=`Loading`,e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(i),e},Cp=(e,t,n)=>{let r={config:n??{},streaming:!0,location:e,defaultRenderer:Sp};if(t){let e=t(r);if(e!==null)return e}return Sp()},wp=(e,t)=>{let n=B(`div`,`persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm`),r=t===`user`?e.userAvatar:e.assistantAvatar;if(r){if(r.startsWith(`http`)||r.startsWith(`/`)||r.startsWith(`data:`)){let e=B(`img`);e.src=r,e.alt=t===`user`?`User`:`Assistant`,e.className=`persona-w-full persona-h-full persona-rounded-full persona-object-cover`,n.appendChild(e)}else n.textContent=r,n.classList.add(t===`user`?`persona-bg-persona-accent`:`persona-bg-persona-primary`,`persona-text-white`)}else n.textContent=t===`user`?`U`:`A`,n.classList.add(t===`user`?`persona-bg-persona-accent`:`persona-bg-persona-primary`,`persona-text-white`);return n},Tp=(e,t,n=`div`)=>{let r=B(n,`persona-text-xs persona-text-persona-muted`),i=new Date(e.createdAt);return r.textContent=t.format?t.format(i):i.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`}),r},Ep=(e,t=`bubble`)=>{let n=[`persona-message-bubble`];switch(t){case`flat`:e===`user`?n.push(`persona-message-user-bubble`,`persona-ml-auto`,`persona-text-persona-primary`,`persona-py-2`):n.push(`persona-message-assistant-bubble`,`persona-text-persona-text`,`persona-py-2`);break;case`minimal`:n.push(`persona-text-sm`,`persona-leading-relaxed`),e===`user`?n.push(`persona-message-user-bubble`,`persona-ml-auto`,`persona-bg-persona-accent`,`persona-text-white`,`persona-px-3`,`persona-py-2`,`persona-rounded-lg`):n.push(`persona-message-assistant-bubble`,`persona-bg-persona-container`,`persona-text-persona-text`,`persona-px-3`,`persona-py-2`,`persona-rounded-lg`);break;default:n.push(`persona-rounded-2xl`,`persona-text-sm`,`persona-leading-relaxed`,`persona-shadow-sm`),e===`user`?n.push(`persona-message-user-bubble`,`persona-ml-auto`,`persona-bg-persona-accent`,`persona-text-white`,`persona-px-5`,`persona-py-3`):n.push(`persona-message-assistant-bubble`,`persona-bg-persona-container`,`persona-border`,`persona-border-persona-message-border`,`persona-text-persona-text`,`persona-px-5`,`persona-py-3`)}return n},Dp={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`}},Op=(e,t,n=`bubble`,r)=>{if(!r)return;let i=t===`user`?`user`:`assistant`,a=Dp[n??`bubble`]??Dp.bubble;r.padding&&(e.style.padding=`var(--persona-message-${i}-padding, ${a.padding})`),r.fontSize&&(e.style.fontSize=`var(--persona-message-${i}-font-size, ${a.fontSize})`),r.lineHeight&&(e.style.lineHeight=`var(--persona-message-${i}-line-height, ${a.lineHeight})`),r.fontFamily&&(e.style.fontFamily=`var(--persona-message-${i}-font-family, inherit)`)},kp=e=>`custom:${e}`,Ap=(e,t)=>t!==`user`&&t!==`assistant`?[]:(e?.custom??[]).filter(e=>(e.roles??[`assistant`]).includes(t)),jp=(e,t,n,r)=>{let i=t.showCopy??!0,a=t.showUpvote??!1,o=t.showDownvote??!1,s=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&r?.canRegenerate===!0,l=(t.showEdit??!1)&&r?.canEdit===!0,u=(t.showQuote??!1)&&r?.canQuote!==!1,d=Ap(t,e.role);if(!i&&!a&&!o&&!s&&!c&&!l&&!u&&d.length===0){let t=B(`div`);return t.style.display=`none`,t.id=`actions-${e.id}`,t.setAttribute(`data-actions-for`,e.id),t}let f=t.visibility??`hover`,p=t.align??`right`,m=t.layout??`pill-inside`,h={left:`persona-message-actions-left`,center:`persona-message-actions-center`,right:`persona-message-actions-right`}[p],g={"pill-inside":`persona-message-actions-pill`,"row-inside":`persona-message-actions-row`}[m],_=B(`div`,`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${h} ${g} ${f===`hover`?`persona-message-actions-hover`:``}`);_.id=`actions-${e.id}`,_.setAttribute(`data-actions-for`,e.id);let v=(e,t,n)=>{let r=Kf({icon:e,label:t,size:14,className:`persona-message-action-btn`,chromeless:!0});return r.setAttribute(`data-action`,n),r};i&&_.appendChild(v(`copy`,`Copy message`,`copy`)),s&&_.appendChild(v(`volume-2`,`Read aloud`,`read-aloud`)),a&&_.appendChild(v(`thumbs-up`,`Upvote`,`upvote`)),o&&_.appendChild(v(`thumbs-down`,`Downvote`,`downvote`)),c&&_.appendChild(v(`refresh-cw`,`Regenerate response`,`regenerate`)),l&&_.appendChild(v(`pencil`,`Edit message`,`edit`)),u&&_.appendChild(v(`quote`,`Quote message`,`quote`));for(let e of d)_.appendChild(v(e.iconName??`ellipsis`,e.label,kp(e.id)));return _},Mp=(e,t,n,r,i,a)=>{let o=n??{},s=o.layout??`bubble`,c=o.avatar,l=o.timestamp,u=c?.show??!1,d=l?.show??!1,f=c?.position??`left`,p=l?.position??`below`,m=Ep(e.role,s),h=B(`div`,m.join(` `));h.id=`bubble-${e.id}`,h.setAttribute(`data-message-id`,e.id),h.setAttribute(`data-persona-theme-zone`,e.role===`user`?`user-message`:`assistant-message`);let g=Hu(a?.widgetConfig?.future).components.message,_=a?.widgetConfig?.theme?.components?.message;Op(h,e.role,s,e.role===`user`?{...g.user,..._?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...g.assistant,..._?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),s===`flat`?(h.style.backgroundColor=`transparent`,h.style.color=e.role===`user`?`var(--persona-primary, var(--persona-text))`:`var(--persona-message-assistant-text, var(--persona-text))`):e.role===`user`?(h.style.backgroundColor=`var(--persona-message-user-bg, var(--persona-accent))`,h.style.color=`var(--persona-message-user-text, white)`):e.role===`assistant`&&(h.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,h.style.color=`var(--persona-message-assistant-text, var(--persona-text))`);let v=dp(e),y=e.content?.trim()??``,b=v.length>0&&y===`[Image]`,x=Wd(a?.widgetConfig?.features?.streamAnimation),S=a?.widgetConfig?.features?.streamAnimation?.plugins,C=e.role===`assistant`&&x.type!==`none`?Zd(x.type,S):null,w=e.role===`assistant`&&C?.isAnimating?.(e)===!0,T=e.role===`assistant`&&C!==null&&(!!e.streaming||w);T&&C?.bubbleClass&&h.classList.add(C.bubbleClass);let E=document.createElement(`div`);E.classList.add(`persona-message-content`),e.streaming&&E.classList.add(`persona-content-streaming`),T&&C&&(C.containerClass&&E.classList.add(C.containerClass),E.style.setProperty(`--persona-stream-step`,`${x.speed}ms`),E.style.setProperty(`--persona-stream-duration`,`${x.duration}ms`));let D=T?Qd(e.content??``,x.buffer,C,e,!!e.streaming):e.content??``,O=()=>{let n=t({text:D,message:e,streaming:!!e.streaming,raw:e.rawContent});return T&&C?.wrap===`char`?of(n,`char`,e.id,{skipTags:C.skipTags}):T&&C?.wrap===`word`?of(n,`word`,e.id,{skipTags:C.skipTags}):n},ee=null;if(b?(ee=document.createElement(`div`),ee.innerHTML=O(),ee.style.display=`none`,E.appendChild(ee)):e.contentSegments?.length?_p(E,e.contentSegments,n=>t({text:n,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):E.innerHTML=O(),T&&C?.useCaret&&!b&&y){let e=sf(),t=E.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];if(n?.parentNode)n.parentNode.insertBefore(e,n.nextSibling);else{let t=E.lastElementChild;t?t.appendChild(e):E.appendChild(e)}}if(d&&p===`inline`&&e.createdAt){let t=Tp(e,l,`span`);t.classList.add(`persona-timestamp-inline`);let n=E.lastElementChild;n?n.appendChild(t):E.appendChild(t)}if(v.length>0){let e=vp(v,!b&&!!y,()=>{b&&ee&&(ee.style.display=``)});e?h.appendChild(e):b&&ee&&(ee.style.display=``)}let k=fp(e);if(k.length>0){let e=yp(k);e&&h.appendChild(e)}let A=pp(e);if(A.length>0){let e=bp(A);e&&h.appendChild(e)}let j=mp(e);if(j.length>0){let e=xp(j);e&&h.appendChild(e)}let te=e.contentSegments?.length?null:hp(e.contextMentions);if(te&&h.appendChild(te),h.appendChild(E),d&&p===`below`&&e.createdAt){let t=Tp(e,l);t.classList.add(`persona-mt-1`),h.appendChild(t)}let ne=e.role===`assistant`?sp(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role===`assistant`){let e=!!(D&&D.trim()),t=x.placeholder===`skeleton`,n=t&&x.buffer===`line`&&e;if(e)n&&h.appendChild(cf());else if(t)h.appendChild(cf());else{let e=Cp(`inline`,a?.loadingIndicatorRenderer,a?.widgetConfig);e&&h.appendChild(e)}}ne&&e.stopReason&&!e.streaming&&(y||(E.style.display=`none`),h.appendChild(cp(e.stopReason,ne)));let re=e.role===`assistant`&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&r?.enabled!==!1,ie=a?.actionEligibility,M=e.role===`user`&&!e.streaming&&r?.enabled!==!1&&(r?.showEdit===!0&&ie?.canEdit===!0||r?.showQuote===!0&&ie?.canQuote===!0||Ap(r,`user`).length>0);if((re||M)&&r){let t=jp(e,M?{...r,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:r,i,ie);h.appendChild(t)}if(!u||e.role===`system`)return h;let N=B(`div`,`persona-message-with-avatar persona-flex persona-gap-2 ${e.role===`user`?`persona-flex-row-reverse`:``}`),P=wp(c,e.role);return f===`right`||f===`left`&&e.role===`user`?N.append(h,P):N.append(P,h),N},Np=(e,t,n,r,i,a)=>{let o=n??{};return e.role===`user`&&o.renderUserMessage?o.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role===`assistant`&&o.renderAssistantMessage?o.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Mp(e,t,n,r,i,a)};H(),I();const Pp=(e,t)=>{if(e.replaceChildren(),!t)e.hidden=!0;else if(typeof t==`function`){let n=null;try{n=t()}catch(e){console.warn(`[persona] welcome.icon renderer threw`,e)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1}else{if(t.type===`lucide`){let n=F(t.name,40);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type===`image`?e.appendChild(V(`img`,{className:`persona-welcome-icon-image`,attrs:{src:t.url,alt:t.alt}})):e.appendChild(V(`span`,{className:`persona-welcome-icon-text`,text:t.text}));e.hidden=!1}},Fp=(e,t,n={})=>{let r=V(`div`,{className:`persona-welcome-icon`,attrs:{"data-persona-welcome-icon":``}});r.hidden=!0;let i=B(`p`,`persona-welcome-kicker`);i.hidden=!0;let a=B(`h2`,`persona-welcome-title`),o=B(`p`,`persona-welcome-subtitle`),s=V(`div`,{className:`persona-welcome-head-text`},i,a),c=V(`div`,{className:`persona-welcome-title-row`},r,s);return{host:V(`div`,{className:`persona-welcome persona-rounded-2xl`,attrs:{"data-persona-welcome":``,"data-persona-intro-card":``,"data-persona-welcome-variant":`card`},style:{background:`var(--persona-intro-card-bg, transparent)`,boxShadow:n.flatShadow?`none`:`var(--persona-intro-card-shadow, none)`,border:`var(--persona-intro-card-border, none)`}},c,o,t),iconHolder:r,kicker:i,title:a,subtitle:o,starterSuggestions:t}},Ip=(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)},Lp=(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===``,Pp(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`)},Rp=`data-persona-welcome-overlay`,zp=`persona-welcome-overlay-active`,Bp=/* @__PURE__ */ new WeakMap,Vp=(e,t,n)=>{n.setAttribute(`data-persona-welcome-plugin`,``),t.appendChild(n),t.setAttribute(`data-persona-welcome-content`,`plugin`),t.setAttribute(Rp,``),e.classList.contains(zp)||(Bp.set(e,e.scrollTop),e.classList.add(zp),e.scrollTop=0)},Hp=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute(`data-persona-welcome-content`),t.removeAttribute(Rp),e.classList.contains(zp)&&(e.classList.remove(zp),e.scrollTop=Bp.get(e)??e.scrollTop,Bp.delete(e))},Up=()=>{let e=V(`div`,{className:`persona-welcome-greeting persona-flex persona-flex-col`,attrs:{"data-persona-welcome-greeting":``}});return e.hidden=!0,e},Wp=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let r=n?.layout?.messages?.layout??`bubble`,i=V(`div`,{className:Ep(`assistant`,r).join(` `),attrs:{"data-persona-theme-zone":`assistant-message`},text:t,style:r===`flat`?{backgroundColor:`transparent`,color:`var(--persona-message-assistant-text, var(--persona-text))`}:{backgroundColor:`var(--persona-message-assistant-bg, var(--persona-container))`,color:`var(--persona-message-assistant-text, var(--persona-text))`}});e.appendChild(V(`div`,{className:`persona-flex`},i)),e.hidden=!1},Gp=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,Kp=(e,t)=>{if(Gp()||typeof e.animate!=`function`||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),r=e.parentElement,i=0,a=0,o=0;if(r){let t=getComputedStyle(r);i=parseFloat(t.rowGap)||0;let s=e.previousElementSibling,c=e.nextElementSibling,l=r.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-r.scrollTop;a=Math.max(0,s?n.top-s.getBoundingClientRect().bottom-i:n.top-l),o=Math.max(0,c?c.getBoundingClientRect().top-n.bottom-i:0)}let s=e.style.overflow;e.style.overflow=`hidden`;let c=getComputedStyle(e),l=parseFloat(c.paddingTop)||0,u=parseFloat(c.paddingBottom)||0,d=e.animate([{opacity:`1`,transform:`none`,height:`${n.height}px`,minHeight:`0px`,paddingTop:`${l}px`,paddingBottom:`${u}px`,marginTop:`${a}px`,marginBottom:`${o}px`},{opacity:`0`,transform:`translateY(-4px)`,height:`0px`,minHeight:`0px`,paddingTop:`0px`,paddingBottom:`0px`,marginTop:`0px`,marginBottom:`${-i}px`}],{duration:180,easing:`ease-out`,fill:`forwards`}),f=!1,p=()=>{f||(f=!0,e.style.overflow=s,t(d))};return d.finished.then(p).catch(p),d},qp=(e,t,n,r=260)=>{if(t<=1||Gp()||typeof e.animate!=`function`||!e.isConnected)return null;let i=n===`drop`?-t:t;return e.animate([{transform:`translateY(${i}px)`},{transform:`none`}],{duration:r,easing:`cubic-bezier(0.2, 0, 0, 1)`,fill:`none`})},Jp=/* @__PURE__ */ new WeakSet,Yp=(e,t)=>!!e&&e[t]!==void 0,Xp=(e,t)=>{e&&e.debug===!0&&t.length&&(Jp.has(e)||(Jp.add(e),t.forEach(e=>console.warn(`[persona] ${e}`))))},Zp=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!==`docked`)=>{let n=e?.welcome,r=e?.copy,i=e?.future?.v5Defaults===!0,a=n?.layout??(i?`centered`:`top`),o=Yp(n,`variant`)?n.variant:r?.showWelcomeCard===!1?`none`:`card`,s=o===`hero`&&!i&&n?.layout===void 0?`on-first-message`:Yp(n,`dismiss`)?n.dismiss:i||o===`hero`?`on-first-message`:`never`,c=[];Yp(n,`title`)&&Yp(r,`welcomeTitle`)&&c.push(`welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated.`),Yp(n,`subtitle`)&&Yp(r,`welcomeSubtitle`)&&c.push(`welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated.`),Yp(n,`variant`)&&Yp(r,`showWelcomeCard`)&&c.push(`welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated.`),o===`hero`&&Yp(n,`message`)&&c.push(`welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.`),!i&&n?.layout===void 0&&o===`hero`&&Yp(n,`dismiss`)&&n.dismiss!==`on-first-message`&&c.push(`welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".`);let l=n?.anchor??(a===`centered`&&t?`center`:`bottom`),u=Sd(n?.anchorComposerTop)!==null;return Yp(n,`anchorComposerTop`)&&!u&&c.push(`welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".`),l!==`center`&&(Yp(n,`anchorComposerTop`)||Yp(n,`composerGap`))&&c.push(`welcome.anchorComposerTop is ignored unless welcome.anchor is "center".`),Xp(e,c),{title:Yp(n,`title`)?n.title:r?.welcomeTitle??(i?`What can I help with?`:`Hello 👋`),kicker:n?.kicker??``,subtitle:Yp(n,`subtitle`)?n.subtitle:r?.welcomeSubtitle??(i?``:`I can answer questions and help you get things done here.`),icon:n?.icon,align:n?.align===`start`||n?.align===`center`?n.align:a===`centered`?`center`:void 0,iconPlacement:n?.icon&&typeof n.icon!=`function`&&n.icon.placement===`inline`?`inline`:`above`,variant:o,dismiss:s,message:o===`hero`?void 0:n?.message,layout:a,anchor:l,anchorComposerTop:u?n.anchorComposerTop:`44%`,composerGap:n?.composerGap?.trim()||`24px`}},Qp=e=>(e??[]).some(e=>e.role===`user`)?`active`:`empty`,$p=(e,t)=>e.variant===`none`?!1:e.dismiss===`never`||!(t??[]).some(e=>e.role===`user`);H(),dn(),ci();const em=`var(--persona-components-panel-height)`,tm=e=>{let t=ii(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,r=e?.launcher?.heightOffset??0,i=r===0?`max(200px, ${em})`:`max(200px, calc(${em} - ${r}px))`;return{width:n??`var(--persona-components-panel-width)`,maxWidth:n??`var(--persona-components-panel-maxWidth)`,height:i,maxHeight:`var(--persona-components-panel-maxHeight)`}},nm=`16px`,rm=`10px`,im=`14px`,am=e=>{let t=e?.launcher?.enabled??!0,n=Cf(e);if(wf(e)){let t=e?.launcher?.composerBar??{},n=B(`div`,`persona-widget-wrapper persona-fixed persona-transition`);n.setAttribute(`data-persona-composer-bar`,``),n.dataset.state=`collapsed`,n.dataset.expandedSize=t.expandedSize??`anchored`,n.style.zIndex=String(e?.launcher?.zIndex??1e5);let r=B(`div`,`persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);r.style.width=`100%`,n.appendChild(r);let i=B(`div`,`persona-widget-pill-root`);return i.setAttribute(`data-persona-composer-bar`,``),i.dataset.state=`collapsed`,i.dataset.expandedSize=t.expandedSize??`anchored`,i.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:n,panel:r,pillRoot:i}}if(n){let e=B(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`),t=B(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);return e.appendChild(t),{wrapper:e,panel:t}}if(!t){let t=B(`div`,`persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0`),n=B(`div`,`persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0`),r=ii(e),i=r.launcherWidth||r.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?tm(e).width:`100%`;return t.style.width=i,n.style.width=`100%`,t.appendChild(n),{wrapper:t,panel:n}}let r=e?.launcher??{},i=r.position&&Nf[r.position]?Nf[r.position]:Nf[`bottom-right`],a=B(`div`,`persona-widget-wrapper persona-fixed ${i} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let o=B(`div`,`persona-widget-panel persona-relative persona-min-h-[320px]`),s=tm(e);return o.style.width=s.width,o.style.maxWidth=s.maxWidth,a.appendChild(o),{wrapper:a,panel:o}},om=e=>{let t=V(`div`,{className:`persona-suggestions`,attrs:{"data-persona-suggestions":Ef(e)}});return t.hidden=!0,t},sm=(e,t)=>{let n=om(`starter`),r=Fp(e,n,{flatShadow:Cf(e)}),i=Zp(e);Lp(r,i),Ip(t,r.host,$p(i,e?.initialMessages));let a=Up();return Wp(a,i.message,e),{welcome:r,greetingHost:a}},cm=(e,t)=>{let n=B(`div`,`persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary`);n.setAttribute(`data-persona-theme-zone`,`container`);let{button:r,wrapper:i}=Rf(e,{showClose:t,wrapperClassName:`persona-composer-bar-close`,buttonSize:nm,iconSize:rm});i.style.position=`absolute`,i.style.top=`8px`,i.style.right=`8px`,i.style.zIndex=`10`;let a=e?.launcher?.clearChat?.enabled??!0,o=null,s=null;if(a){let t=zf(e,{wrapperClassName:`persona-composer-bar-clear-chat`,buttonSize:nm,iconSize:im});o=t.button,s=t.wrapper,s.style.position=`absolute`,s.style.top=`8px`,s.style.right=`32px`,s.style.zIndex=`10`}let c=V(`span`,{className:`persona-widget-header`,attrs:{"data-persona-theme-zone":`header`},style:{display:`none`}}),l=V(`div`,{className:`persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6`,attrs:{id:`persona-scroll-container`,"data-persona-theme-zone":`messages`},style:{paddingTop:`48px`}});l.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:u,greetingHost:d}=sm(e,l),{host:f,title:p,subtitle:m}=u,h=u.starterSuggestions,g=B(`div`,`persona-widget-messages persona-flex persona-flex-col`);g.style.gap=`var(--persona-components-message-gap, 12px)`;let _=om(`followUp`),v=bd(e,!0);v&&(g.style.maxWidth=v,g.style.marginLeft=`auto`,g.style.marginRight=`auto`,g.style.width=`100%`),l.append(f,d,g,_);let y=V(`div`,{className:`persona-composer-overlay persona-pointer-events-none`,attrs:{"data-persona-composer-overlay":``},style:{position:`absolute`,left:`0`,right:`0`,bottom:`calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))`,zIndex:`20`}}),b=ap({config:e}),{root:x,textNode:S}=ip();return n.append(c,i,l,y),s&&n.appendChild(s),{container:n,body:l,messagesWrapper:g,starterSuggestions:h,transcriptSuggestions:_,composerOverlay:y,suggestions:b.suggestions,textarea:b.textarea,sendButton:b.sendButton,sendButtonWrapper:b.sendButtonWrapper,micButton:b.micButton,micButtonWrapper:b.micButtonWrapper,composerForm:b.composerForm,statusText:b.statusText,welcomeHost:f,welcomeIconHolder:u.iconHolder,greetingHost:d,introKicker:u.kicker,introTitle:p,introSubtitle:m,closeButton:r,closeButtonWrapper:i,clearChatButton:o,clearChatButtonWrapper:s,iconHolder:B(`span`),headerTitle:B(`span`),headerSubtitle:B(`span`),header:c,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:x,peekTextNode:S}},lm=(e,t=!0)=>{if(wf(e))return cm(e,t);let n=V(`div`,{className:`persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border`,attrs:{"data-persona-theme-zone":`container`}}),r=e?.layout?.header,i=e?.layout?.showHeader!==!1,a=r?np(e,r,{showClose:t}):Uf({config:e,showClose:t}),o=V(`div`,{className:`persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6`,attrs:{id:`persona-scroll-container`,"data-persona-theme-zone":`messages`}});o.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:s,greetingHost:c}=sm(e,o),{host:l,title:u,subtitle:d}=s,f=s.starterSuggestions,p=B(`div`,`persona-widget-messages persona-flex persona-flex-col`);p.style.gap=`var(--persona-components-message-gap, 12px)`;let m=om(`followUp`),h=bd(e,!1);h&&(p.style.maxWidth=h,p.style.marginLeft=`auto`,p.style.marginRight=`auto`,p.style.width=`100%`),o.append(l,c,p,m);let g=rp({config:e}),_=e?.layout?.showFooter!==!1;i||(a.header.style.display=`none`),Wf(n,a,e),n.append(o);let v=V(`div`,{className:`persona-composer-overlay persona-pointer-events-none`,attrs:{"data-persona-composer-overlay":``},style:{position:`absolute`,left:`0`,right:`0`,bottom:`calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))`,zIndex:`20`}});return _||(g.footer.style.display=`none`),n.append(g.footer),n.append(v),{container:n,body:o,messagesWrapper:p,starterSuggestions:f,transcriptSuggestions:m,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,welcomeHost:l,welcomeIconHolder:s.iconHolder,greetingHost:c,introKicker:s.kicker,introTitle:u,introSubtitle:d,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};H(),I(),dn();const um=(e,t)=>{let n=B(`button`);n.type=`button`,n.innerHTML=`
22
+ `),o=Array.isArray(e.contentParts)&&e.contentParts.length>0,s=r.contentParts.length>0;if(o){let t=[];i&&t.push(Ai(i)),t.push(...r.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(s){let t=[];a&&t.push(Ai(a)),t.push(...r.contentParts),e.contentParts=t}else i&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,t){let n=e.trim(),r=!!t?.replayFields&&(t.replayFields.llmContent!==void 0||t.replayFields.rawContent!==void 0||(t.replayFields.contextMentions?.length??0)>0);if(!n&&(!t?.contentParts||t.contentParts.length===0)&&(!t?.mentions||t.mentions.refs.length===0)&&!r)return;this.#U&&!t?.voiceTurn&&(this.#U.failed=!0,this.#U=null),(this.#T||this.#D||this.#w||this.#P)&&await this.#ke(),this.stopSpeaking(),this.abortController?.abort(),this.#He(),this.#Le++,this.#it();let i=t?.voiceTurn?.userMessageId,a=i?this.messages.find(e=>e.id===i&&e.role===`user`):void 0,o=a?.id??Ra(),s=za();this.#i=null;let c=t?.contentParts&&Oi(t.contentParts)?Bi:``,l={id:o,role:`user`,content:n||c,createdAt:(/* @__PURE__ */ new Date()).toISOString(),sequence:this.#mt(),viaVoice:t?.viaVoice||!1,...t?.contentParts&&t.contentParts.length>0&&{contentParts:t.contentParts},...t?.mentions&&t.mentions.refs.length>0&&{contextMentions:t.mentions.refs},...t?.contentSegments&&t.contentSegments.length>0&&{contentSegments:t.contentSegments},...t?.composerOptions&&{composerOptions:t.composerOptions},...t?.replayFields??{}};a?(a.viaVoice=!0,delete a.voiceCaption,a.content.trim()!==n&&(a.llmContent=n),this.callbacks.onMessagesChanged([...this.messages])):this.#ft(l),this.#ct(!0);let u=new AbortController;if(this.abortController=u,t?.mentions){let e=this.messages.find(e=>e.id===o)??l;if(await this.#Ne(e,n,t.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(t?.quote&&!t.replayFields){let e=this.messages.find(e=>e.id===o)??l,n=Ec({quote:t.quote,text:e.llmContent??e.content,contentParts:e.contentParts});n.contentParts&&(e.contentParts=n.contentParts),n.llmContent!==void 0&&(e.llmContent=n.llmContent),(n.contentParts||n.llmContent!==void 0)&&(e.quote={...t.quote},this.callbacks.onMessagesChanged([...this.messages]))}let d=(/* @__PURE__ */ new Date()).toISOString(),f=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:d}]:[...this.messages],p=(a??this.messages.find(e=>e.id===o))?.createdAt??d,m=xc(t?.voiceTurn?.priorToolResults,p);for(let e of m)this.messages.some(t=>t.id===e.id)||(this.#ft(e),f.push({...e,createdAt:d}));let h=m.map(({agentMetadata:e})=>{let{toolCallId:t,toolName:n,args:r,result:i}=e.clientToolAnswer;return{toolCallId:t,name:n,arguments:r,result:i}});try{await this.#je(f,u,s,o,{composerOptions:t?.composerOptions,interrupt:t?.interrupt,voiceSpoken:!!t?.voiceTurn,...h.length>0&&{voicePriorToolResults:h}})}catch(e){if(this.status===`resuming`||this.#a)return;this.#U&&(this.#U.failed=!0);let t=e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`abort`));if(!t){let t=sl(e,this.config.errorMessage);if(t){let e={id:s,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:t,localOnly:!0,sequence:this.#mt()};this.#ft(e)}}this.#st(`idle`),this.#ct(!1),this.abortController=null,t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(Error(String(e))))}}resubmitFrom(e,t){let n=Oc(this.messages,e);if(!n)return!1;let r=this.messages[n.start],i=t.replacement,a=i?i.text:r.content,o=i?i.contentParts:r.contentParts;if(!(a?.trim()||(o?.length??0)>0||!i&&(r.llmContent?.trim()?.length??0)>0))return!1;let s=i?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},c=i?this.#Pe(i.options):r.composerOptions,l=i?i.contentSegments:r.contentSegments,u=i?i.options?.quote:void 0,d=i?i.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(a??``,{...o?.length?{contentParts:[...o]}:{},...l?.length?{contentSegments:[...l]}:{},...c?{composerOptions:c}:{},...u?{quote:u}:{},...s&&Object.keys(s).length>0?{replayFields:s}:{},viaVoice:d===!0}),!0}#Pe(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}async continueConversation(){if(this.streaming)return;(this.#T||this.#D||this.#w||this.#P)&&await this.#ke(),this.abortController?.abort(),this.#it();let e=za();this.#i=null,this.#ct(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(t){if(this.status===`resuming`||this.#a)return;let n=t instanceof Error&&(t.name===`AbortError`||t.message.includes(`aborted`)||t.message.includes(`abort`));if(!n){let n=sl(t,this.config.errorMessage);if(n){let t={id:e,role:`assistant`,createdAt:(/* @__PURE__ */ new Date()).toISOString(),content:n,localOnly:!0,sequence:this.#mt()};this.#ft(t)}}this.#st(`idle`),this.#ct(!1),this.abortController=null,n||(t instanceof Error?this.callbacks.onError?.(t):this.callbacks.onError?.(Error(String(t))))}}async connectStream(e,t){if(this.streaming&&!t?.allowReentry)return;t?.allowReentry||this.abortController?.abort(),t?.preserveAssistantId&&t.assistantMessageId&&(this.#i=t.assistantMessageId);let n=t?.preserveAssistantId?t.assistantMessageId:void 0,r=!1;for(let e of this.messages)e.streaming&&e.id!==n&&(e.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#ct(!0);let i={};try{await this.client.processStream(e,e=>{let t=this.#t;this.#t=i;try{this.handleEvent(e)}finally{this.#t=t}},t?.assistantMessageId,t?.seedContent),this.#lt(i)}catch(e){if(this.status===`resuming`||this.#a){this.#ut(i);return}this.#lt(i),this.#st(`error`),this.webMcpResolveControllers.size===0&&(this.#ct(!1),this.abortController=null),this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))}}#Fe(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}if(e.signal?.aborted)return Promise.resolve(!1);let t;do t=`webmcp-${++this.#d}`;while(this.messages.some(e=>e.id===`approval-${t}`||e.approval?.id===t));let n={id:t,status:`pending`,agentId:``,executionId:``,toolName:e.toolName,toolType:`webmcp`,description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,approval:n}),new Promise(t=>{this.webMcpApprovalResolvers.set(r,t),e.signal?.addEventListener(`abort`,()=>this.resolveWebMcpApproval(r,`timeout`),{once:!0})})}resolveWebMcpApproval(e,t){let n=this.webMcpApprovalResolvers.get(e);if(!n)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(t=>t.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:t,resolvedAt:Date.now()}}),n(t===`approved`)}#Ie;#Le;#Re(e){let t=this.#Ie??={s:this,setStreaming:e=>this.#ct(e),appendMessage:e=>this.#ft(e),nextSequence:()=>this.#mt(),settleApprovalPausedToolCall:e=>this.#dt(e),resumeAfter:e=>this.#r?.executionId===e?this.#r.lastEventId:void 0},n=oo();if(n)return e(n,t);let r=this.#Le;return io().then(n=>r===this.#Le?e(n,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))})}resolveApproval(e,t,n){return this.#Re((r,i)=>r.resolveApproval(i,e,t,n))}resolveAskUserQuestion(e,t){return this.#Re((n,r)=>n.resolveAskUserQuestion(r,e,t))}resolveWebMcpToolCall(e){return this.#Re((t,n)=>t.resolveWebMcpToolCall(n,e))}persistAskUserQuestionProgress(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}#ze(e){let t=e.agentMetadata?.executionId,n=e.toolCall?.id;if(!t||!n){let t=this.#u;queueMicrotask(()=>{t===this.#u&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(t);r||(r={snapshots:[],seen:/* @__PURE__ */ new Set},this.webMcpAwaitBatches.set(t,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(e))}#Be(){if(this.webMcpAwaitBatches.size===0)return;let e=this.#u;queueMicrotask(()=>{if(e===this.#u)for(let e of[...this.webMcpAwaitBatches.keys()])this.#Ve(e)})}#Ve(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:n}=t;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.#Re((t,r)=>t.resolveWebMcpToolCallBatch(r,e,n))}#He(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,`denied`);this.webMcpAwaitBatches.clear(),this.#u++}cancel(){this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#ct(!1),this.#st(`idle`)}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.messages=[],this.agentExecution=null,this.#Ge(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#ct(!1),this.#st(`idle`),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#l}selectArtifact(e){this.#l=e,this.#Ke()}clearArtifacts(){this.#Ge()}upsertArtifact(e){let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=e.artifactType===`markdown`?{id:t,artifactType:`markdown`,title:e.title,status:`complete`,markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:t,artifactType:`component`,title:e.title,status:`complete`,component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(t,n),this.#l=t,this.#Ke(),e.transcript!==!1&&this.#Ue(n),n}#Ue(e){let t=`artifact-ref-${e.id}`,n=Ae(ke(this.config.features?.artifacts,e),{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:`complete`,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown===void 0?{}:{markdown:e.markdown}}),r=this.messages.find(e=>e.id===t);r?(r.rawContent=n,r.streaming=!1,this.callbacks.onMessagesChanged([...this.messages])):this.injectAssistantMessage({id:t,content:``,rawContent:n})}#We(){let e=!1;for(let t of this.artifacts.values()){let n=this.messages.find(e=>e.id===`artifact-ref-${t.id}`);if(!n)continue;let r=Ae(ke(this.config.features?.artifacts,t),{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown===void 0?{}:{markdown:t.markdown}});n.rawContent!==r&&(n.rawContent=r,n.streaming=t.status===`streaming`,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#Ge(){(this.artifacts.size!==0||this.#l!==null)&&(this.artifacts.clear(),this.#l=null,this.#Ke())}#Ke(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#l})}#qe(e){switch(e.type){case`artifact_start`:e.artifactType===`markdown`?this.artifacts.set(e.id,{id:e.id,artifactType:`markdown`,title:e.title,status:`streaming`,markdown:``,...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:`component`,title:e.title,status:`streaming`,component:e.component??``,props:{}}),this.#l=e.id;break;case`artifact_delta`:{let t=this.artifacts.get(e.id);t?.artifactType===`markdown`&&(t.markdown=(t.markdown??``)+e.artDelta);break}case`artifact_update`:{let t=this.artifacts.get(e.id);t?.artifactType===`component`&&(t.props={...t.props,...e.props},e.component&&(t.component=e.component));break}case`artifact_complete`:{let t=this.artifacts.get(e.id);t&&(t.status=`complete`);break}default:return}this.#Ke()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.#it(),this.#He(),this.#Le++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#ht(e.map(e=>({...is(e),streaming:!1,sequence:e.sequence??this.#mt()}))),this.#ct(!1),this.#st(`idle`),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let t of e)this.artifacts.set(t.id,{...t,status:`complete`});this.#l=t,this.#Ke()}#Je(e){let t=this.agentExecution?.executionId;if(!t||!this.#i||this.agentExecution?.status!==`running`)return;let n=this.#r===null;this.#r={executionId:t,lastEventId:e,assistantMessageId:this.#i,status:`running`},this.#ot(n)}#Ye(){return this.#r!==null&&typeof this.config.reconnectStream==`function`&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#Xe()}#Xe(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant===`approval`&&e.approval?.status===`pending`)}#Ze(){this.#a||this.#r&&typeof this.config.reconnectStream==`function`&&(this.#a=!0,this.callbacks.onReconnect?.({phase:`paused`,handle:this.#r}),this.#ct(!0),this.#st(`resuming`),this.#Qe().then(e=>{this.#a&&this.#r&&e.begin()}))}#Qe(){return this.#o?Promise.resolve(this.#o):(this.#s||(this.#s=rl().then(({createReconnectController:e})=>{let t=e(this.#$e());return this.#o=t,t}),this.#s.catch(()=>{this.#s=null})),this.#s)}#$e(){let e=this;return{get config(){return e.config},getResumable:()=>e.#r,clearResumable:()=>e.#at(),getStatus:()=>e.status,setStatus:t=>e.#st(t),setStreaming:t=>e.#ct(t),setReconnecting:t=>{e.#a=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,n,r)=>e.connectStream(t,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:t=>e.#ft(t),settleParked:t=>e.#et(t),nextSequence:()=>e.#mt(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>sl(Error(t),e.config.errorMessage),onError:t=>e.callbacks.onError?.(t)}}reconnectNow(){this.#a?this.#o?.wake():this.#Ze()}resumeFromHandle(e){if(typeof this.config.reconnectStream!=`function`||this.#a)return;if(this.#Xe()){this.#tt(e.executionId),this.#r={executionId:e.executionId,lastEventId:e.after,assistantMessageId:this.#i??``,status:`running`};return}let t=this.#nt(e.executionId)?za():this.#rt();t||(t=za(),this.#ft({id:t,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:this.#mt()})),this.#i=t,this.#tt(e.executionId),this.#r={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:`running`},this.#Ze()}#et(e){let t=this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0;if(!t&&!this.#Xe()){if(!this.#nt(e))return!1;this.#at()}if(this.#a=!1,!t){let e=!1;for(let t of this.messages)t.streaming&&(t.streaming=!1,e=!0);e&&this.callbacks.onMessagesChanged([...this.messages]),this.#ct(!1),this.abortController=null}return this.#st(`idle`),!0}#tt(e){this.agentExecution||={executionId:e,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0}}#nt(e){return this.messages.some(t=>t.agentMetadata?.executionId===e&&[t.toolCall,...t.tools??[]].some(e=>e?.interrupted===!0))}#rt(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role===`assistant`&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role===`user`)break}return null}#it(){this.#a=!1,this.#o?.teardown(),this.#at()}#at(){this.#c&&=(clearTimeout(this.#c),null);let e=this.#r!==null;this.#r=null,e&&this.config.onExecutionState?.(null)}#ot(e){let t=this.config.onExecutionState;t&&(e?(this.#c&&=(clearTimeout(this.#c),null),t(this.#r)):this.#c||=setTimeout(()=>{this.#c=null,this.config.onExecutionState?.(this.#r)},500))}getResumableHandle(){return this.#r}#st(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#ct(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&(this.#lt(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(e){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider===`browser`||t.provider===`runtype`&&t.browserFallback))return;let n=[...this.messages].reverse().find(e=>e.role===`assistant`&&e.content&&!e.voiceProcessing);if(!n||e&&!e.includes(n.id))return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=Vc(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return Mc(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||t.role!==`assistant`)return;let n=Vc(t.content||``);if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<`u`&&`speechSynthesis`in window&&window.speechSynthesis.cancel()}#lt(e){for(let[t,n]of[...this.#e])n===e&&(this.#e.delete(t),this.#dt(t))}#ut(e){for(let[t,n]of this.#e)n===e&&this.#e.set(t,void 0)}#dt(e){let t=this.messages.find(t=>t.id===e)?.approval,n=t?.toolCallId,r=n&&this.messages.find(e=>e.toolCall?.id===n),i=r&&r.toolCall;if(!i||i.status===`complete`||t.status===`pending`)return;let a={...i,status:`complete`,approvalStatus:t.status,completedAt:Date.now(),...t.status===`approved`?{superseded:!0}:{success:!1,error:t.status===`denied`?`Denied`:`Approval timed out`}};this.upsertMessage({...r,streaming:!1,toolCall:a})}#ft(e){let t=this.#pt(e);this.messages=this.#ht([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#pt(e),n=this.messages.findIndex(e=>e.id===t.id);n===-1?this.#ft(t):(this.messages=this.messages.map((e,r)=>{if(r!==n||e.toolCall?.name&&Se(e.toolCall.name)&&e.toolCall.status===`complete`&&t.toolCall?.id===e.toolCall.id&&t.toolCall.status!==`complete`&&(t.toolCall.status===`pending`&&!t.toolCall.name||!e.toolCall.interrupted&&(e.toolCall.result!==void 0||e.toolCall.success!==void 0)&&(!t.agentMetadata?.executionId||t.agentMetadata.executionId===e.agentMetadata?.executionId)))return e;let i={...e,...t};e.agentMetadata?.askUserQuestionAnswered===!0&&t.agentMetadata&&(i.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),e.agentMetadata?.suggestRepliesResolved===!0&&t.agentMetadata&&(i.agentMetadata={...i.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let n=e.approval,r=t.approval;i.approval={...n,...r,executionId:r.executionId||n.executionId,toolName:r.toolName||n.toolName,description:r.description||n.description,toolType:r.toolType??n.toolType,reason:r.reason??n.reason,parameters:r.parameters??n.parameters,toolCallId:r.toolCallId??n.toolCallId}}let o=t.toolCall?.name,s=t.agentMetadata?.executionId,c=t.toolCall?.id;if(o&&cl(o)&&s&&c&&t.agentMetadata?.awaitingLocalTool===!0){let t=`${s}:${c}`,n=this.webMcpInflightKeys.has(t),r=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,o=e.agentMetadata?.executionId===s&&e.toolCall?.id===c&&a!==void 0&&cl(a)&&e.toolCall?.status===`complete`&&!e.toolCall.interrupted;(n||r||o)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=e.toolCall,i.streaming=e.streaming)}return i}),this.messages=this.#ht(this.messages),this.callbacks.onMessagesChanged([...this.messages]))}#pt(e){return e.sequence===void 0?{...e,sequence:this.#mt()}:{...e}}#mt(){return this.#n++}#ht(e){return[...e].sort((e,t)=>{let n=new Date(e.createdAt).getTime(),r=new Date(t.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(r)&&n!==r)return n-r;let i=e.sequence??0,a=t.sequence??0;return i===a?e.id.localeCompare(t.id):i-a})}};V(),A(),F(),Wi();const ul={add:e=>Ii(e)},dl=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,fl={allowedTypes:Ui,maxFileSize:10485760,maxFiles:4};function pl(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ml(e){return e===`application/pdf`||e.startsWith(`text/`)||e.includes(`word`)?f.FileText:e.includes(`excel`)||e.includes(`spreadsheet`)?f.FileSpreadsheet:e===`application/json`?f.FileCode:f.File}var hl=class e{#e;#t;#n;constructor(e={}){this.attachments=[],this.#e=null,this.#t=/* @__PURE__ */ new Map,this.#n=!1,this.config={allowedTypes:e.allowedTypes??fl.allowedTypes,maxFileSize:e.maxFileSize??fl.maxFileSize,maxFiles:e.maxFiles??fl.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,adapter:e.adapter}}#r(){return typeof this.config.adapter?.add==`function`}#i(){return this.#r()?this.config.adapter:ul}setPreviewsContainer(e){this.#e=e}remountPreviews(e){if(this.#e=e,e){e.innerHTML=``;for(let e of this.attachments)this.#l(e)}this.#f()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:fl.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange),e.adapter!==void 0&&(this.config.adapter=e.adapter)}isReady(){return this.attachments.every(e=>e.status===`ready`)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){e&&e.length!==0&&await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#n)return;let t=[];for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,`count`);continue}let e=Li(n,this.config.allowedTypes,this.config.maxFileSize);if(!e.valid){let t=e.error?.includes(`type`)?`type`:`size`;this.config.onFileRejected?.(n,t);continue}let r={id:pl(),file:n,previewUrl:Fi(n)?URL.createObjectURL(n):null,contentPart:null,status:this.#r()?`uploading`:`processing`,progress:this.#r()?0:void 0};this.attachments.push(r),this.#l(r),t.push(r)}this.#f(),this.#c(),await Promise.all(t.map(e=>this.#a(e)))}async#a(e){let t=new AbortController;this.#t.set(e.id,t);let n=()=>this.#n||t.signal.aborted||this.#t.get(e.id)!==t||!this.attachments.includes(e);try{let r=await this.#i().add(e.file,{signal:t.signal,onProgress:t=>{n()||e.status!==`uploading`||(e.progress=dl(t),this.#u(e),this.#c())}});if(n())return;e.contentPart=r,e.status=`ready`,e.progress=void 0,e.error=void 0}catch(t){if(n())return;e.status=`error`,e.progress=void 0,e.error=t instanceof Error?t.message:String(t??`Upload failed`)}finally{this.#t.get(e.id)===t&&this.#t.delete(e.id)}this.#u(e),this.#c()}retryAttachment(e){let t=this.attachments.find(t=>t.id===e);!t||t.status!==`error`||this.#n||(t.status=this.#r()?`uploading`:`processing`,t.progress=this.#r()?0:void 0,t.error=void 0,this.#u(t),this.#c(),this.#a(t))}#o(e){let t=this.#t.get(e);t&&(this.#t.delete(e),t.abort())}removeAttachment(e){let t=this.attachments.findIndex(t=>t.id===e);if(t===-1)return;let n=this.attachments[t];this.#o(e),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let r=this.#e?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),n.status===`ready`&&n.contentPart&&this.#s(n.contentPart),this.#f(),this.#c()}#s(e){let t=this.config.adapter?.remove;if(t)try{let n=t(e,{signal:new AbortController().signal});n&&typeof n.catch==`function`&&n.catch(e=>{console.error(`[AttachmentManager] adapter.remove failed:`,e)})}catch(e){console.error(`[AttachmentManager] adapter.remove failed:`,e)}}clearAttachments(){for(let e of this.attachments)this.#o(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=``),this.#f(),this.#c()}destroy(){if(!this.#n){this.#n=!0;for(let e of this.#t.values())e.abort();this.#t.clear();for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.#e=null}}#c(){this.#n||this.config.onAttachmentsChange?.(this.getAttachments())}#l(e){if(!this.#e)return;let t=Fi(e.file),n=z(`div`,`persona-attachment-preview persona-relative persona-inline-block`);if(n.setAttribute(`data-attachment-id`,e.id),n.style.width=`48px`,n.style.height=`48px`,t&&e.previewUrl){let t=z(`img`);t.src=e.previewUrl,t.alt=e.file.name,t.className=`persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200`,t.style.width=`48px`,t.style.height=`48px`,t.style.objectFit=`cover`,t.style.borderRadius=`8px`,n.appendChild(t)}else{let t=z(`div`);t.style.width=`48px`,t.style.height=`48px`,t.style.borderRadius=`8px`,t.style.backgroundColor=`var(--persona-container, #f3f4f6)`,t.style.border=`1px solid var(--persona-border, #e5e7eb)`,t.style.display=`flex`,t.style.flexDirection=`column`,t.style.alignItems=`center`,t.style.justifyContent=`center`,t.style.gap=`2px`,t.style.overflow=`hidden`;let r=ml(e.file.type),i=k(r,20,`var(--persona-muted, #6b7280)`,1.5);i&&t.appendChild(i);let a=z(`span`);a.textContent=zi(e.file.type,e.file.name),a.style.fontSize=`8px`,a.style.fontWeight=`600`,a.style.color=`var(--persona-muted, #6b7280)`,a.style.textTransform=`uppercase`,a.style.lineHeight=`1`,t.appendChild(a),n.appendChild(t)}let r=B(`div`,{className:`persona-attachment-status`,attrs:{"data-persona-attachment-status":``}}),i=z(`div`,`persona-attachment-progress`);i.appendChild(z(`div`,`persona-attachment-progress__bar`));let a=B(`button`,{className:`persona-attachment-retry`,attrs:{type:`button`,"aria-label":`Retry upload`}}),o=P(`rotate-cw`,12,`var(--persona-text-inverse, #ffffff)`,2);o?a.appendChild(o):a.textContent=`↻`,a.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.retryAttachment(e.id)}),r.append(i,a),n.appendChild(r);let s=z(`button`,`persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center`);s.type=`button`,s.setAttribute(`aria-label`,`Remove attachment`),s.style.position=`absolute`,s.style.top=`-4px`,s.style.insetInlineEnd=`-4px`,s.style.width=`18px`,s.style.height=`18px`,s.style.borderRadius=`50%`,s.style.backgroundColor=`var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))`,s.style.border=`none`,s.style.cursor=`pointer`,s.style.display=`flex`,s.style.alignItems=`center`,s.style.justifyContent=`center`,s.style.padding=`0`;let c=k(f.X,10,`var(--persona-text-inverse, #ffffff)`,2);c?s.appendChild(c):(s.textContent=`×`,s.style.color=`var(--persona-text-inverse, #ffffff)`,s.style.fontSize=`14px`,s.style.lineHeight=`1`),s.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),this.removeAttachment(e.id)}),n.appendChild(s),this.#e.appendChild(n),this.#d(n,e)}#u(e){let t=this.#e?.querySelector(`[data-attachment-id="${e.id}"]`);t&&this.#d(t,e)}#d(e,t){e.dataset.status=t.status;let n=t.status!==`ready`&&t.status!==`error`;e.setAttribute(`aria-busy`,n?`true`:`false`),e.title=t.status===`error`?`${t.file.name}: ${t.error??`Upload failed`}`:t.file.name;let r=e.querySelector(`.persona-attachment-progress__bar`);if(r){let e=t.progress;r.style.width=typeof e==`number`?`${Math.round(e*100)}%`:``}}#f(){this.#e&&(this.#e.style.display=this.attachments.length>0?`flex`:`none`)}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n,adapter:t?.adapter})}};const gl=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),_l=(e,t)=>e.length===t.length&&e.every((e,n)=>{let r=t[n];return e.id===r.id&&e.name===r.name&&e.mimeType===r.mimeType&&e.size===r.size&&e.status===r.status&&e.progress===r.progress&&e.error===r.error});function vl(){let e={text:``,attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=/* @__PURE__ */ new Set,n=null,r=!1,i=!1,a=()=>e.preparing?`preparing`:e.streaming?`streaming`:`idle`,o=()=>{let t=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(e=>Object.freeze({...e}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:t,inputDisabled:e.inputDisabled,sendDisabled:t!==`idle`||e.sendDisabled||e.inputDisabled})},s=()=>(n||=o(),n),c=()=>{if(r=!1,i||t.size===0)return;let e=s();for(let n of[...t])try{n(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] composer state listener failed:`,e)}},l=()=>{n=null,!(i||r)&&(r=!0,queueMicrotask(c))};return{getState:s,subscribe:e=>(t.add(e),()=>t.delete(e)),setText:t=>{e.text!==t&&(e.text=t,l())},setAttachments:t=>{_l(e.attachments,t)||(e.attachments=[...t],l())},setMentionRefs:t=>{gl(e.mentionRefs,t)||(e.mentionRefs=[...t],l())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,l())},setActiveModeIds:t=>{gl(e.activeModeIds,t)||(e.activeModeIds=[...t],l())},setQuote:t=>{let n=e.quote;(n?.text!==t?.text||n?.messageId!==t?.messageId||n?.sourceLabel!==t?.sourceLabel)&&(e.quote=t?{...t}:void 0,l())},setPendingSubmission:t=>{e.pendingSubmission!==t&&(e.pendingSubmission=t,l())},setPreparing:t=>{e.preparing!==t&&(e.preparing=t,l())},setStreaming:t=>{e.streaming!==t&&(e.streaming=t,l())},setInputDisabled:t=>{e.inputDisabled!==t&&(e.inputDisabled=t,l())},setSendDisabled:t=>{e.sendDisabled!==t&&(e.sendDisabled=t,l())},flush:()=>{r&&c()},destroy:()=>{i=!0,r=!1,t.clear()}}}V();const yl=(e,...t)=>{for(let n of t){let t=e.querySelector(n);if(t)return t}return null},bl=(e,t)=>{let n=z(`div`,e);return n.setAttribute(t,``),n.setAttribute(`data-persona-composer-synthesized`,``),n.style.display=`contents`,n};function xl(e,t={}){let n=yl(e,`[data-persona-composer-form]`),r=yl(e,`[data-persona-composer-input]`);if(!n||!r){let e=`[Persona] composer surface is missing required element(s): ${[!n&&`form`,!r&&`input`].filter(Boolean).join(`, `)}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||r))throw Error(e);return typeof console<`u`&&console.warn(e),null}let i={header:yl(e,`[data-persona-composer-header]`),body:yl(e,`[data-persona-composer-body]`),actionsStart:yl(e,`[data-persona-composer-actions-start]`,`.persona-widget-composer__left-actions`),actionsEnd:yl(e,`[data-persona-composer-actions-end]`,`.persona-widget-composer__right-actions`),actionsRow:yl(e,`[data-persona-composer-actions]`,`.persona-widget-composer .persona-flex.persona-items-center.persona-justify-between`),suggestions:yl(e,`[data-persona-composer-suggestions]`,`.persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2`),status:yl(e,`[data-persona-composer-status]`)},a=/* @__PURE__ */ new Set,o=i.header;o||(a.add(`header`),o=bl(`persona-widget-composer__header`,`data-persona-composer-header`),n.parentNode?n.parentNode.insertBefore(o,n):e.appendChild(o));let s=i.body??r.parentElement??n,c=(e,t,n,r,i)=>{if(t)return t;a.add(e);let o=bl(n,r);return i.appendChild(o),o},l=c(`actionsStart`,i.actionsStart,`persona-widget-composer__left-actions`,`data-persona-composer-actions-start`,n),u=c(`actionsEnd`,i.actionsEnd,`persona-widget-composer__right-actions`,`data-persona-composer-actions-end`,n),d=c(`suggestions`,i.suggestions,`persona-widget-composer__suggestions`,`data-persona-composer-suggestions`,e),f=c(`status`,i.status,`persona-widget-composer__status`,`data-persona-composer-status`,e),p=[],m=(e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler,h=yl(e,`[data-persona-composer-attachment-input]`,`input[type="file"]`)??void 0;return{footer:e,form:n,input:r,header:o,body:s,actionsStart:l,actionsEnd:u,suggestions:d,status:f,attachmentInput:h,attachmentPreviews:yl(e,`[data-persona-composer-attachment-previews]`,`.persona-attachment-previews`)??void 0,attachmentButton:yl(e,`[data-persona-composer-attachment-button]`,`.persona-attachment-button`)??void 0,sendButton:yl(e,`[data-persona-composer-submit]`)??void 0,micButton:yl(e,`[data-persona-composer-mic]`)??void 0,synthesized:a,found:i,addListener:(e,t,n,r)=>{e.addEventListener(t,n,r),p.push({target:e,type:t,handler:n,options:r})},removeListener:(e,t,n,r)=>{e.removeEventListener(t,n,r),p=p.filter(r=>!m(r,{target:e,type:t,handler:n}))},destroy:()=>{for(let e of p)e.target.removeEventListener(e.type,e.handler,e.options);p=[]}}}function Sl(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Cl(e){let{anchor:t,content:n,placement:r=`bottom-start`,offset:i=6,matchAnchorWidth:a=!1,horizontalOffset:o,verticalOffset:s,zIndex:c=2147483e3,onOpen:l,onDismiss:u}=e,d=e.container??Sl(t),f=!1,p=null,m=()=>{if(!f)return;let e=t.getBoundingClientRect();n.style.position=`fixed`,a&&(n.style.minWidth=`${e.width}px`),o&&(n.style.maxWidth=`${e.width}px`);let c=n.getBoundingClientRect(),l=s?.()??null,u=l==null?e.top:e.top+l,d=r===`top-start`||r===`top-end`?u-i-c.height:e.bottom+i,p=r===`bottom-end`||r===`top-end`?e.right-c.width:e.left,m=o?.()??null;if(m!=null){let t=Math.max(e.left,e.right-c.width);p=Math.min(Math.max(e.left+m,e.left),t)}n.style.top=`${d}px`,n.style.left=`${p}px`},h=()=>{f&&(f=!1,p&&=(p(),null),n.remove())},g=()=>{if(f)return;f=!0,c!=null&&(n.style.zIndex=String(c)),d.appendChild(n),m();let e=(t.ownerDocument??document).defaultView??window,r=t.ownerDocument??document,i=()=>{t.isConnected?m():(h(),u?.(`anchor-removed`))},a=e=>{let r=typeof e.composedPath==`function`?e.composedPath():[];r.includes(n)||r.includes(t)||(h(),u?.(`outside`))},o=e.setTimeout(()=>{r.addEventListener(`pointerdown`,a,!0)},0);e.addEventListener(`scroll`,i,!0),e.addEventListener(`resize`,i),p=()=>{e.clearTimeout(o),r.removeEventListener(`pointerdown`,a,!0),e.removeEventListener(`scroll`,i,!0),e.removeEventListener(`resize`,i)},l?.()};return{get isOpen(){return f},open:g,close:h,toggle:()=>f?h():g(),reposition:m,destroy:h}}V(),F(),fa();const wl=[`--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`],Tl=`data-persona-menu-focus`,El=/* @__PURE__ */ new Set([`ArrowDown`,`ArrowUp`,`Home`,`End`]);function Dl(e){return e.getAttribute(`role`)===`menuitem`?e:e.querySelector(`button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])`)??e}const Ol=e=>e.disabled===!0||e.getAttribute(`aria-disabled`)===`true`;function kl(e){let t=e.label,n=!1,r=z(`div`,`persona-send-button-wrapper`),i=B(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${na} ${ra}`,attrs:{type:`button`,"aria-haspopup":`menu`,"aria-expanded":`false`,"data-persona-composer-overflow-trigger":``}});r.appendChild(i);let a=B(`div`,{className:`persona-composer-overflow-menu`,attrs:{role:`menu`,tabindex:`-1`,"data-persona-composer-overflow-menu":``}}),o=()=>{let t=e.getButtonSize?.()??``;i.style.width=t,i.style.height=t,i.style.minWidth=t,i.style.minHeight=t,i.style.lineHeight=`1`,i.replaceChildren();let n=P(`plus`,24,`currentColor`,1.5);n?i.appendChild(n):i.textContent=`+`},s=()=>{i.setAttribute(`aria-label`,t),i.setAttribute(`title`,t),a.setAttribute(`aria-label`,t)};s(),o();let c=[],l=-1,u=!1,d=()=>{let e=a.getRootNode().activeElement;return e instanceof HTMLElement?e:null},f=()=>{let e=d();for(let t of c){let n=!!e&&Dl(t)===e;t.toggleAttribute(Tl,n&&u)}},p=()=>c.filter(e=>e.isConnected||a.contains(e)).map(Dl).filter(e=>!Ol(e)),m=(e,t)=>{e.forEach((e,n)=>{e.setAttribute(`tabindex`,n===t?`0`:`-1`)})},h=e=>{let t=p();if(t.length===0)return;let n=(e%t.length+t.length)%t.length;l=n,m(t,n),t[n].focus(),f()},g=()=>r.ownerDocument??document,_=null,v=null,y=null,b=()=>{_&&=(g().removeEventListener(`focusin`,_,!0),null)},x=()=>{v&&=(a.removeEventListener(`focusin`,v),null),y&&=(a.removeEventListener(`pointerdown`,y,!0),null)},S=null,C=()=>(S||=Cl({anchor:i,content:a,placement:`top-start`,offset:6,onDismiss:()=>{i.setAttribute(`aria-expanded`,`false`),b()}}),S),w=()=>S?.isOpen===!0,T=(e=!1)=>{if(w()){S?.close(),i.setAttribute(`aria-expanded`,`false`),b(),x(),l=-1,u=!1;for(let e of c)e.removeAttribute(Tl);e&&i.focus()}},E=(e=0,t=!1)=>{if(n||w())return;u=t,ia(i,a,wl),C().open(),i.setAttribute(`aria-expanded`,`true`);let o=p();m(o,-1),h(e<0?o.length-1:e),_=e=>{let t=typeof e.composedPath==`function`?e.composedPath():[];t.includes(a)||t.includes(r)||T()},g().addEventListener(`focusin`,_,!0),v=()=>f(),a.addEventListener(`focusin`,v),y=()=>{u=!1},a.addEventListener(`pointerdown`,y,!0)},D=e=>{e.preventDefault(),e.stopPropagation(),w()?T(!0):E(0)},O=e=>{e.key===`ArrowDown`||e.key===`Enter`||e.key===` `?(e.preventDefault(),u=!0,w()?h(0):E(0,!0)):e.key===`ArrowUp`&&(e.preventDefault(),u=!0,w()?h(-1):E(-1,!0))},ee=e=>{switch(El.has(e.key)&&(u=!0),e.key){case`ArrowDown`:e.preventDefault(),h(l+1);return;case`ArrowUp`:e.preventDefault(),h(l-1);return;case`Home`:e.preventDefault(),h(0);return;case`End`:e.preventDefault(),h(p().length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),T(!0);return;case`Tab`:T(!0);return}};return i.addEventListener(`click`,D),i.addEventListener(`keydown`,O),a.addEventListener(`keydown`,ee),{trigger:r,triggerButton:i,panel:a,setItems:e=>{for(let t of c)e.includes(t)||t.removeAttribute(Tl);if(c=[...e],!w())return;let t=p();m(t,Math.min(l,t.length-1)),f()},isOpen:w,open:()=>E(0),close:T,setLabel:e=>{e!==t&&(t=e,s())},applyButtonSize:o,destroy:()=>{n=!0,b(),x(),i.removeEventListener(`click`,D),i.removeEventListener(`keydown`,O),a.removeEventListener(`keydown`,ee),S?.destroy(),S=null,r.remove(),a.remove(),c=[]}}}V(),F(),Lr(),fa();const Al={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},jl=`data-persona-composer-action`,Ml=`data-persona-composer-disable-when-streaming`,Nl=e=>e===`core:attachment`?`attachments`:e.startsWith(`core:mention`)?`mentions`:null;function Pl(e,t){if(e===void 0)return null;if(typeof e==`number`)return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let r=z(`div`);r.style.position=`absolute`,r.style.visibility=`hidden`,r.style.pointerEvents=`none`,r.style.height=`0`,r.style.width=e,t.appendChild(r);let i=r.getBoundingClientRect().width;return r.remove(),Number.isFinite(i)&&i>0?i:Number.isFinite(n)?n:null}function Fl(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let r=n.getComputedStyle(e),i=(Number.parseFloat(r.paddingLeft)||0)+(Number.parseFloat(r.paddingRight)||0);return Math.max(0,t-i)}const Il=(e,t)=>{e&&typeof console<`u`&&console.warn(t)},Ll=(e,t)=>t.includes(`:`)?t:`${e}:${t}`;function Rl(e){let{debug:t}=e,n=[],r=/* @__PURE__ */ new Map,i=0,a=e=>{let i=r.get(e.id);i?Il(t,`[Persona] composer action "${e.id}" is already contributed by ${zl(i)}; the ${zl(e)} copy is ignored.`):(r.set(e.id,e),n.push(e))};for(let t of e.builtIns)a({id:t.id,placement:t.placement,presentation:`bar`,order:t.order,sequence:i++,source:`core`,builtIn:t});let o=(e,n,r)=>{let o=r?Ll(r,e.id):e.id,s=e.order??Al.custom;e.placement===`end`&&s>=Al.send&&(Il(t,`[Persona] composer action "${o}" ordered at ${s} would render after send; clamped to ${Al.send-1}.`),s=Al.send-1),a({id:o,placement:e.placement,presentation:e.presentation??`bar`,order:s,sequence:i++,source:n,pluginId:r,action:e})};for(let t of e.configActions??[])o(t,`config`);for(let t of e.plugins){if(!t.contributeComposerActions)continue;let n;try{n=t.contributeComposerActions(e.contributionContext)}catch(e){typeof console<`u`&&console.error(`[Persona] plugin "${t.id}" contributeComposerActions failed:`,e);continue}for(let e of n??[])o(e,`plugin`,t.id)}return n.sort((e,t)=>e.order===t.order?e.sequence-t.sequence:e.order-t.order)}const zl=e=>e.source===`plugin`?`plugin "${e.pluginId}"`:e.source===`config`?`composer.actions`:`a core built-in`,Bl=(e,t,n)=>e===void 0?n:typeof e==`function`?e(t)===!0:e===!0,Vl=e=>e.phase===`streaming`||e.text.trim().length>0||e.attachments.length>0;function Hl(e,t){if(!e||e===`always`)return!0;let n=Vl(t);return e===`when-text`?n:!n}const Ul=e=>e.kind===`custom`,Wl=e=>e instanceof HTMLButtonElement?e:e.querySelector(`button`)??e,Gl=e=>{let t=Wl(e);return t.getAttribute(`aria-label`)?.trim()||t.getAttribute(`title`)?.trim()||``};function Kl(e){let t=``,n=e=>{if(e.nodeType===Node.TEXT_NODE){t+=e.nodeValue??``;return}if(e.nodeType!==Node.ELEMENT_NODE)return;let r=e;typeof r.matches==`function`&&r.matches(`.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]`)||e.childNodes.forEach(n)};return n(e),t.trim()}const ql=e=>Kl(e).length===0;function Jl(e){let t=/* @__PURE__ */ new Map,n=[],r=!1,i=()=>e.getButtonSize?.(),a=(e,t)=>{let n=e.button;if(!n)return;n.setAttribute(`role`,`menuitem`),n.setAttribute(`tabindex`,`-1`),n.className=`persona-composer-overflow-menu__item`;for(let e of[`width`,`height`,`minWidth`,`minHeight`,`fontSize`,`color`,`backgroundColor`])n.style[e]=``;n.style.lineHeight=`1`,t.tooltipText?n.setAttribute(`title`,t.tooltipText):n.removeAttribute(`title`),n.replaceChildren();let r=z(`span`,`persona-composer-overflow-menu__icon`);if(t.iconName){let e=P(t.iconName,16,`currentColor`,1.5);e&&r.appendChild(e)}let i=z(`span`,`persona-composer-overflow-menu__label`);i.textContent=t.shortLabel??t.label,n.append(r,i)},o=(e,t)=>{let n=e.button;if(!n)return;if(n.setAttribute(`aria-label`,t.label),t.pressed===void 0?n.removeAttribute(`aria-pressed`):n.setAttribute(`aria-pressed`,t.pressed?`true`:`false`),n.toggleAttribute(Ml,t.disableWhenStreaming===!0),e.mode===`menu`){e.tooltip?.destroy(),e.tooltip=void 0,a(e,t);return}n.removeAttribute(`role`),n.removeAttribute(`tabindex`),n.removeAttribute(`title`);let r=i(),o=!!t.shortLabel;if(n.className=$e(`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button`,na,ra,o&&`persona-composer-action-button--text persona-gap-1 persona-text-sm`),n.style.width=r&&!o?r:``,n.style.height=r??``,n.style.minWidth=r&&!o?r:``,n.style.minHeight=r??``,n.style.fontSize=o?``:`18px`,n.style.lineHeight=`1`,n.style.color=t.iconColor??``,n.style.backgroundColor=t.backgroundColor??``,n.replaceChildren(),t.iconName){let e=P(t.iconName,24,`currentColor`,1.5);e&&n.appendChild(e)}if(o){let e=z(`span`,`persona-composer-action-button__label`);e.textContent=t.shortLabel,n.appendChild(e)}else n.firstChild||(n.textContent=t.label);e.tooltip?.destroy(),e.tooltip=br({anchor:n,trigger:e.element,text:()=>t.tooltipText??t.label,enabled:!!t.tooltipText})},s=(t,n)=>{let r=t.action,i=B(`button`,{attrs:{type:`button`}}),a=i;if(n===`bar`){let e=z(`div`,`persona-send-button-wrapper`);e.appendChild(i),a=e}a.setAttribute(jl,t.id);let s={resolved:t,element:a,button:i,owned:!0,managed:!0,busy:!1,visible:!0,mode:n},c=t=>{if(t.preventDefault(),t.stopPropagation(),s.busy||i.disabled)return;let n=s.resolved.action;s.mode===`menu`&&p?.close(!0);let r;try{r=n.onSelect(e.actionContext,t)}catch(t){e.reportError(t,{actionId:s.resolved.id});return}r&&typeof r.then==`function`&&(s.busy=!0,i.setAttribute(`aria-busy`,`true`),r.catch(t=>{e.reportError(t,{actionId:s.resolved.id})}).finally(()=>{s.busy=!1,i.removeAttribute(`aria-busy`)}))};return i.addEventListener(`click`,c),s.detach=()=>i.removeEventListener(`click`,c),o(s,r),s},c=t=>{let n=t.action,r;try{r=n.render({...e.actionContext,id:t.id,action:n})}catch(n){return e.reportError(n,{actionId:t.id}),null}return r?.element?(r.element.setAttribute(jl,t.id),r.element.toggleAttribute(Ml,n.disableWhenStreaming===!0),{resolved:t,element:r.element,owned:!0,managed:!0,destroy:r.destroy,busy:!1,visible:!0,mode:`bar`}):null},l=(e,t)=>{if(e.builtIn){let t=e.builtIn.element;return t?{resolved:e,element:t,owned:!1,managed:e.builtIn.managed===!0,busy:!1,visible:!0,mode:`bar`}:null}let n=e.action;return n?Ul(n)?c(e):s(e,t):null},u=t=>{if(t.detach?.(),t.tooltip?.destroy(),t.detachMenuSlot?.(),t.detachMenuSlot=void 0,t.menuLabel?.remove(),t.menuLabel=void 0,t.menuSlot?.remove(),t.menuSlot=void 0,t.owned){try{t.destroy?.()}catch(n){e.reportError(n,{actionId:t.resolved.id})}t.element.remove()}},d=(e,t)=>{for(let n=0;n<t.length;n++){let r=t[n];if(!r.managed)continue;let i=null;for(let r=n+1;r<t.length;r++){let n=t[r];if(!n.managed&&n.element.parentElement===e){i=n.element;break}}i?(r.element.parentElement!==e||r.element.nextSibling!==i)&&e.insertBefore(r.element,i):e.lastChild!==r.element&&e.appendChild(r.element)}},f=(e,t)=>{if(e.button){e.button.disabled=t;return}if(!e.owned)return;let n=e.element;n.toggleAttribute(`data-disabled`,t),n.setAttribute(`aria-disabled`,t?`true`:`false`);let r=n instanceof HTMLButtonElement||n instanceof HTMLSelectElement||n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?n:n.querySelector(`button, select, input, textarea`);r&&(r.disabled=t)},p=null,m=null,h=null,g=0,_=()=>{let t=e.getOverflow?.();return t?.enabled===!0?t:void 0},v=()=>(p?p.setLabel(e.getOverflowLabel?.()??`More actions`):p=kl({label:e.getOverflowLabel?.()??`More actions`,getButtonSize:i}),p),y=e=>{m!==e&&(h?.disconnect(),m=e,g=Fl(e),typeof ResizeObserver<`u`&&(h=new ResizeObserver(t=>{let n=t[t.length-1]?.contentRect?.width??Fl(e);n!==g&&(g=n,T())}),h.observe(e)))},b=(e,t)=>{let n=Pl(e.collapseAutoActionsBelow,t);if(n===null)return!1;let r=g||Fl(t);return r>0&&r<n},x=(e,t,n)=>{if(!t)return`bar`;if(e.resolved.builtIn){let n=Nl(e.resolved.id);return n&&t.includeBuiltIns?.includes(n)?`menu`:`bar`}let r=e.resolved.presentation;return r===`overflow`||r===`auto`&&n?`menu`:`bar`},S=e=>{let t=e.menuSlot;if(!t)return;if(!ql(e.element)){e.menuLabel?.remove(),e.menuLabel=void 0;return}let n=Gl(e.element);n?(e.menuLabel||=z(`span`,`persona-composer-overflow-menu__label`),e.menuLabel.textContent!==n&&(e.menuLabel.textContent=n),e.menuLabel.parentElement!==t&&t.appendChild(e.menuLabel)):(e.menuLabel?.remove(),e.menuLabel=void 0)},C=(e,n)=>{if(e.mode===n)return e;let r=e.resolved.action;if(r&&!Ul(r)){u(e),t.delete(e.resolved.id);let r=s(e.resolved,n);return t.set(e.resolved.id,r),r}if(n===`menu`){let t=B(`div`,{className:`persona-composer-overflow-menu__slot`,attrs:{role:`none`,[jr]:``}});t.appendChild(e.element),yr(Wl(e.element)),e.menuSlot=t;let n=t=>{let n=Wl(e.element);if(n.disabled)return;let r=t.target===n||n.contains(t.target);p?.close(!0),r||n.click()};t.addEventListener(`click`,n,!0),e.detachMenuSlot=()=>t.removeEventListener(`click`,n,!0),e.managed=!0,S(e)}else e.detachMenuSlot?.(),e.detachMenuSlot=void 0,e.menuLabel?.remove(),e.menuLabel=void 0,e.menuSlot?.remove(),e.menuSlot=void 0;return e.mode=n,e},w=(e,t)=>{let n=t.map(e=>e.menuSlot??e.element);for(n.forEach((t,n)=>{let r=e.children[n];r!==t&&(r?e.insertBefore(t,r):e.appendChild(t))});e.children.length>n.length;)e.lastElementChild?.remove()},T=()=>{if(r)return;let i=e.getBindings();if(!i)return;let a=e.getState(),o=a.phase===`streaming`,s=_();s&&y(i.footer);let c=s?b(s,i.footer):!1,l={start:[],end:[]},u=[];for(let e of n){let n=t.get(e.id);if(!n)continue;let r=e.action,i=!r||Bl(r.visible,a,!0)&&Hl(r.visibility,a);if(n.visible!==i&&(n.visible=i,!i&&n.managed&&(n.menuSlot??n.element).remove()),i){if(n=C(n,x(n,s,c)),r){let e=Bl(r.disabled,a,!1)||r.disableWhenStreaming===!0&&o;f(n,e),!Ul(r)&&r.pressed!==void 0&&n.button?.setAttribute(`aria-pressed`,r.pressed?`true`:`false`)}n.mode===`menu`?(S(n),u.push(n)):l[e.placement].push(n)}}if(u.length>0){let e=v();w(e.panel,u),e.setItems(u.map(e=>e.menuSlot??e.element)),e.applyButtonSize();let t=Number.isFinite(s?.order)?s?.order:Al.overflow,n=l.start.findIndex(e=>e.resolved.order>t),r={resolved:{id:`core:overflow`,placement:`start`,presentation:`bar`,order:t,sequence:-1,source:`core`},element:e.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:`bar`};l.start.splice(n<0?l.start.length:n,0,r)}else p&&(p.close(),p.trigger.remove(),p.setItems([]));d(i.actionsStart,l.start),d(i.actionsEnd,l.end)};return{resolve:()=>{if(r)return;let i=Rl(e.collect()),a=new Set(i.map(e=>e.id));for(let[e,n]of t)a.has(e)||(u(n),t.delete(e));for(let e of i){let n=t.get(e.id);if(!n){let n=l(e,`bar`);n&&t.set(e.id,n);continue}let r=n.resolved.action,i=e.action;if(!!r!=!!i||r&&i&&Ul(r)!==Ul(i)||r&&i&&Ul(r)&&Ul(i)&&r.render!==i.render){u(n),t.delete(e.id);let r=l(e,n.mode);r&&t.set(e.id,r)}else n.resolved=e,e.builtIn?(n.managed=e.builtIn.managed===!0||n.mode===`menu`,e.builtIn.element&&n.mode===`bar`&&(n.element=e.builtIn.element)):i&&!Ul(i)?o(n,i):i&&n.element.toggleAttribute(Ml,i.disableWhenStreaming===!0)}n=i,T()},sync:T,getResolved:()=>n,getOverflowMenu:()=>p,destroy:()=>{if(!r){r=!0,h?.disconnect(),h=null,m=null;for(let e of t.values())u(e);t.clear(),p?.destroy(),p=null,n=[]}}}}V(),F(),fa();const Yl=[`--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`],Xl=()=>({wrapper:B(`span`,{className:`persona-composer-model-picker-wrapper`,attrs:{"data-persona-composer-model-picker-wrapper":``}}),chevron:B(`span`,{className:`persona-composer-model-picker-chevron`,attrs:{"aria-hidden":`true`}})});function Zl(e){let t=e.label??`Model`,n=e.presentation??`native`,r=null,i=t=>{let n=e.getSelectedModelId();return t.find(e=>e.id===n)??t[0]},a=()=>{let n=B(`select`,{className:`persona-composer-model-picker`,attrs:{"aria-label":t,"data-persona-composer-model-picker":``}}),a=``,o=()=>{let t=e.getModels(),r=t.map(e=>`${e.id}:${e.label}`).join(`|`);r!==a&&(a=r,n.replaceChildren(...t.map(e=>{let t=B(`option`,{attrs:{value:e.id}});return t.textContent=e.label,t}))),n.value=i(t)?.id??``};o(),r=o;let s=()=>{n.value&&e.onSelect(n.value)};n.addEventListener(`change`,s);let c=e=>e.stopPropagation();n.addEventListener(`click`,c);let{wrapper:l,chevron:u}=Xl();return l.append(n,u),{element:l,destroy:()=>{r===o&&(r=null),n.removeEventListener(`change`,s),n.removeEventListener(`click`,c)}}},o=()=>{let n=B(`button`,{className:`persona-composer-model-picker persona-composer-model-picker-trigger`,attrs:{type:`button`,"aria-haspopup":`listbox`,"aria-expanded":`false`,"data-persona-composer-model-picker":`popover`}}),a=z(`span`,`persona-composer-model-picker-label`),o=z(`span`,`persona-composer-model-picker-suffix`);n.append(a,o);let s=B(`div`,{className:`persona-composer-model-menu`,attrs:{role:`listbox`,tabindex:`-1`,"aria-label":t,"data-persona-composer-model-menu":``}}),c=/* @__PURE__ */ new Map,l=``,u=null,d=()=>u?.isOpen===!0,f=(e=!1)=>{d()&&(u?.close(),n.setAttribute(`aria-expanded`,`false`),e&&n.focus())},p=e=>{let t=[...c.values()];t.length!==0&&t[(e%t.length+t.length)%t.length].focus()},m=t=>{if(d())return;u||=Cl({anchor:n,content:s,placement:`top-start`,offset:6,onDismiss:()=>n.setAttribute(`aria-expanded`,`false`)}),ia(n,s,Yl),u.open(),n.setAttribute(`aria-expanded`,`true`);let r=[...c.keys()].indexOf(i(e.getModels())?.id??``);p(t??(r>=0?r:0))},h=t=>{f(!0),e.onSelect(t)},g=e=>{e.preventDefault(),e.stopPropagation();let t=e.currentTarget.getAttribute(`data-persona-model-option`);t&&h(t)},_=e=>{let t=B(`button`,{className:`persona-composer-model-option`,attrs:{type:`button`,role:`option`,tabindex:`-1`,"aria-selected":`false`,"data-persona-model-option":e.id}});if(e.icon){let n=P(e.icon,16,`currentColor`,1.5);if(n){let e=z(`span`,`persona-composer-model-option-icon`);e.appendChild(n),t.appendChild(e)}}let n=z(`span`,`persona-composer-model-option-body`),r=z(`span`,`persona-composer-model-option-label`);if(r.textContent=e.label,n.appendChild(r),e.description){let t=z(`span`,`persona-composer-model-option-description`);t.textContent=e.description,n.appendChild(t)}t.appendChild(n);let i=z(`span`,`persona-composer-model-option-check`);i.setAttribute(`aria-hidden`,`true`);let a=P(`check`,16,`currentColor`,2);return a&&i.appendChild(a),t.appendChild(i),t.addEventListener(`click`,g),t},v=()=>{let r=e.getModels(),u=r.map(e=>`${e.id}:${e.label}:${e.icon??``}:${e.description??``}`).join(`|`);if(u!==l){l=u;for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),s.replaceChildren(...r.map(e=>{let t=_(e);return c.set(e.id,t),t}))}let d=i(r);for(let[e,t]of c)t.setAttribute(`aria-selected`,String(e===d?.id));a.textContent=d?.label??``;let f=e.getSuffix?.()??``;o.textContent=f,n.setAttribute(`aria-label`,[t,[d?.label,f].filter(Boolean).join(` `)].filter(Boolean).join(`: `))};v(),r=v;let y=e=>{e.preventDefault(),e.stopPropagation(),d()?f(!0):m()},b=e=>{e.key===`ArrowDown`?(e.preventDefault(),d()?p(0):m(0)):e.key===`ArrowUp`&&(e.preventDefault(),d()?p(-1):m(-1))},x=e=>{let t=[...c.values()],n=t.indexOf(e.target?.closest?.(`.persona-composer-model-option`));switch(e.key){case`ArrowDown`:e.preventDefault(),p(n+1);return;case`ArrowUp`:e.preventDefault(),p(n-1);return;case`Home`:e.preventDefault(),p(0);return;case`End`:e.preventDefault(),p(t.length-1);return;case`Escape`:e.preventDefault(),e.stopPropagation(),f(!0);return;case`Tab`:f(!0);return}};n.addEventListener(`click`,y),n.addEventListener(`keydown`,b),s.addEventListener(`keydown`,x);let{wrapper:S,chevron:C}=Xl();return S.append(n,C),{element:S,destroy:()=>{r===v&&(r=null),n.removeEventListener(`click`,y),n.removeEventListener(`keydown`,b),s.removeEventListener(`keydown`,x);for(let e of c.values())e.removeEventListener(`click`,g);c.clear(),u?.destroy(),u=null,s.remove()}}};return{action:{id:`core:model`,kind:`custom`,placement:`end`,order:700,presentation:n===`popover`?`bar`:`auto`,label:t,render:()=>n===`popover`?o():a()},repaint:()=>r?.()}}V();const Ql=`[data-persona-composer-chip-row]`;function $l(e){e.style.display=e.childElementCount>0?`flex`:`none`}function eu(e){let t=e.querySelector(Ql);if(t)return t;let n=B(`div`,{className:`persona-composer-chip-row`,attrs:{"data-persona-composer-chip-row":``}});n.style.display=`none`;let r=e.querySelector(`[data-persona-composer-quote], [data-persona-composer-pending]`);return r?.parentElement===e?e.insertBefore(n,r):e.appendChild(n),n}V(),F();function tu(e){let t=e.row,n=``,r=!1,i=new Set(e.initialIds??[]),a=t=>{let n=B(`span`,{className:`persona-mention-chip persona-composer-mode-chip`,attrs:{"data-persona-composer-mode":t.id}});if(t.iconName){let e=z(`span`,`persona-mention-chip-icon`),r=P(t.iconName,12,`currentColor`,1.5);r&&e.appendChild(r),n.appendChild(e)}let r=z(`span`,`persona-mention-chip-label`);r.textContent=t.shortLabel??t.label,n.appendChild(r);let i=B(`button`,{className:`persona-mention-chip-remove`,attrs:{type:`button`,"aria-label":`Remove ${t.label}`}}),a=P(`x`,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=`×`,i.addEventListener(`click`,n=>{n.preventDefault(),n.stopPropagation(),e.onRemove(t.id)}),n.appendChild(i),n},o=()=>Array.from(t.querySelectorAll(`:scope > [data-persona-composer-mode]`)),s=e=>{e.setAttribute(`data-persona-chip-exit`,``),e.setAttribute(`aria-hidden`,`true`),e.style.pointerEvents=`none`;let n=()=>{e.remove(),$l(t)},r=t.ownerDocument.defaultView,i=typeof r?.getComputedStyle==`function`?r.getComputedStyle(e).animationName:``;!i||i===`none`?n():(e.addEventListener(`animationend`,n,{once:!0}),e.addEventListener(`animationcancel`,n,{once:!0}))},c=()=>{for(let e of o())e.remove()};return{element:t,render:(e,c)=>{if(r)return;let l=c.filter(t=>e.includes(t.id)),u=l.map(e=>`${e.id}:${e.shortLabel??e.label}`).join(`|`);if(u===n)return;n=u;let d=/* @__PURE__ */ new Map;for(let e of o()){let t=e.getAttribute(`data-persona-composer-mode`);t&&l.some(e=>e.id===t)&&!e.hasAttribute(`data-persona-chip-exit`)?d.set(t,e):e.hasAttribute(`data-persona-chip-exit`)||s(e)}let f=t.firstChild;for(let e of l){let n=d.get(e.id);n||(n=a(e),i.has(e.id)||(n.setAttribute(`data-persona-chip-enter`,``),n.addEventListener(`animationend`,()=>n?.removeAttribute(`data-persona-chip-enter`),{once:!0}))),i.delete(e.id),n!==f&&t.insertBefore(n,f),f=n.nextSibling}$l(t)},destroy:()=>{r=!0,c(),$l(t)}}}const nu=e=>`core:mode:${e}`,ru=e=>Math.min(300+e,499),iu=e=>`core:mode-group:${e}`;function au(e,t){return e?t?.find(t=>t.id===e)?.presentation===`segmented`:!1}function ou(e,t){return e?t?.find(t=>t.id===e)?.chipVisibility===`hidden`:!1}function su(e,t){return e?.length?e.filter(e=>!au(e.groupId,t)&&!ou(e.groupId,t)):[]}const cu=(e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null;function lu(e,t,n,r){let i=n.find(e=>e.id===t);if(!i)return[...e];let a=e.includes(t),o=new Set(e);if(a)o.delete(t);else{if(cu(i,r)===`single`){let e=n.filter(e=>e.groupId===i.groupId).map(e=>e.id);o=new Set([...o].filter(t=>!e.includes(t)))}o.add(t)}return n.filter(e=>o.has(e.id)).map(e=>e.id)}function uu(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function du(e,t){return t?.length?t.filter(t=>e.includes(t.id)&&(t.persistence??`sticky`)!==`once`).map(e=>e.id):[]}function fu(e,t){if(t?.length&&e.length!==0)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}V(),F();function pu(e){let t=null;return{action:{id:iu(e.groupId),kind:`custom`,placement:`start`,presentation:`bar`,label:e.getGroup()?.label??e.groupId,render:()=>{let n=B(`div`,{className:`persona-composer-segmented`,attrs:{"data-persona-composer-mode-group":e.groupId}}),r=/* @__PURE__ */ new Map,i=``,a=t=>{t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getAttribute(`data-persona-composer-mode`);n&&(e.getActiveIds().includes(n)&&e.getGroup()?.selection===`single`||e.onSelect(n))},o=e=>{let t=B(`button`,{className:`persona-composer-segmented-item`,attrs:{type:`button`,"data-persona-composer-mode":e.id,"aria-label":e.label}});if(e.iconName){let n=P(e.iconName,16,`currentColor`,1.5);n&&t.appendChild(n)}let n=z(`span`,`persona-composer-segmented-label`);return n.textContent=e.shortLabel??e.label,t.appendChild(n),t.addEventListener(`click`,a),t},s=()=>{let t=e.getGroup();t?.label?(n.setAttribute(`role`,`group`),n.setAttribute(`aria-label`,t.label)):(n.removeAttribute(`role`),n.removeAttribute(`aria-label`));let s=e.getModes(),c=s.map(e=>`${e.id}:${e.shortLabel??e.label}:${e.iconName??``}`).join(`|`);if(c!==i){i=c;for(let e of r.values())e.removeEventListener(`click`,a);r.clear();let e=s.map(e=>{let t=o(e);return r.set(e.id,t),t});n.replaceChildren(...e)}let l=e.getActiveIds();for(let[e,t]of r)t.setAttribute(`aria-pressed`,String(l.includes(e)))};return s(),t=s,{element:n,destroy:()=>{t===s&&(t=null);for(let e of r.values())e.removeEventListener(`click`,a);r.clear()}}}},repaint:()=>t?.()}}V(),F();function mu(e){let t=B(`div`,{className:`persona-composer-quote`,attrs:{"data-persona-composer-quote":``}});t.style.display=`none`;let n=``,r=!1,i=n=>{let r=z(`span`,`persona-composer-quote-bar`),i=z(`div`,`persona-composer-quote-content`);if(n.sourceLabel){let e=z(`div`,`persona-composer-quote-source`);e.textContent=n.sourceLabel,i.appendChild(e)}let a=B(`div`,{className:`persona-composer-quote-text`,attrs:{"data-persona-composer-quote-text":``}});a.textContent=Dc(n.text),i.appendChild(a);let o=B(`button`,{className:`persona-composer-quote-dismiss`,attrs:{type:`button`,"aria-label":e.dismissLabel??`Remove quote`,"data-persona-composer-quote-dismiss":``}}),s=P(`x`,12,`currentColor`,2);s?o.appendChild(s):o.textContent=`×`,o.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(r,i,o)};return{element:t,render:e=>{if(r)return;let a=e?`${e.sourceLabel??``}${e.text}`:``;a!==n&&(n=a,e?(i(e),t.style.display=`flex`):(t.replaceChildren(),t.style.display=`none`))},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}V(),F();function hu(e){let t=B(`div`,{className:`persona-composer-pending`,attrs:{"data-persona-composer-pending":``}});t.style.display=`none`;let n,r=!1,i=(e,t,n,r)=>{let i=B(`button`,{className:`persona-composer-pending-action`,attrs:{type:`button`,"aria-label":t,[n]:``}}),a=P(e,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=t,i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},a=e=>{let t=Dc(e.text??``,90);if(t)return t;let n=e.contentParts?.length??0;return n>0?n===1?`1 attachment`:`${n} attachments`:(e.mentionRefs?.length??0)>0?e.mentionRefs.map(e=>e.label).join(`, `):`Queued message`};return{element:t,render:o=>{if(r||o===n)return;if(n=o,!o){t.replaceChildren(),t.style.display=`none`;return}let s=z(`span`,`persona-composer-pending-badge`);s.textContent=e.label??`Sends next`;let c=B(`div`,{className:`persona-composer-pending-text`,attrs:{"data-persona-composer-pending-text":``}});c.textContent=a(o),t.replaceChildren(s,c,i(`pencil`,e.editLabel??`Edit queued message`,`data-persona-composer-pending-edit`,e.onEdit),i(`x`,e.removeLabel??`Remove queued message`,`data-persona-composer-pending-remove`,e.onRemove)),t.style.display=`flex`},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}V();function gu(e){let t=B(`div`,{className:`persona-message-edit`,attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":``}}),n=B(`textarea`,{className:`persona-message-edit-input`,attrs:{rows:`1`,dir:`auto`,"aria-label":`Edit message`,"data-persona-message-edit-input":``}});n.value=e.initialText;let r=()=>{n.style.height=`auto`,n.style.height=`${n.scrollHeight}px`};n.addEventListener(`input`,r);let i=z(`div`,`persona-message-edit-actions`),a=(e,t,n,r)=>{let i=B(`button`,{className:`persona-message-edit-button ${t}`,attrs:{type:`button`,[n]:``},text:e});return i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},o=()=>{let t=n.value.trim();t&&e.onSave(t)};return i.append(a(e.cancelLabel??`Cancel`,`persona-message-edit-cancel`,`data-persona-message-edit-cancel`,e.onCancel),a(e.saveLabel??`Send`,`persona-message-edit-save`,`data-persona-message-edit-save`,o)),n.addEventListener(`keydown`,t=>{t.key===`Escape`?(t.preventDefault(),t.stopPropagation(),e.onCancel()):t.key===`Enter`&&!t.shiftKey&&(t.preventDefault(),o())}),t.append(n,i),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let e=n.value.length;n.setSelectionRange(e,e),r()},destroy:()=>{t.replaceChildren(),t.remove()}}}function _u(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 vu(e,t){if(!e||typeof e.text!=`string`)return;let n=new Set(t.mentionSourceIds),r=(e.mentionRefs??[]).filter(e=>n.has(e.sourceId)),i=r.length===(e.mentionRefs?.length??0)&&r.length>0,a=new Set(t.modes.map(e=>e.id)),o=(e.activeModeIds??[]).filter(e=>a.has(e)),s=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...i?{mentionRefs:r}:{},...i&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...s?{selectedModelId:s}:{},...o.length?{activeModeIds:o}:{},...e.quote?.text?{quote:e.quote}:{}}}function yu(e){let t=e.delay??500,n=null,r=!1,i=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{r||(i(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{r||n===null||(i(),e.write())},cancel:i,destroy:()=>{r=!0,i()}}}function bu(e){return e.wrapped||e.text.includes(`
23
+ `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function xu(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function Su(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),r=Number.parseFloat(n.lineHeight),i=Number.parseFloat(n.fontSize),a=Number.isFinite(r)&&r>0?r:Number.isFinite(i)&&i>0?i*1.4:0;if(!a)return!1;let o=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-o>a*1.5}function Cu(e){e&&(typeof e.requestSubmit==`function`?e.requestSubmit():e.dispatchEvent(new Event(`submit`,{bubbles:!0,cancelable:!0})))}function wu(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 Tu(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}const Eu=e=>typeof e?.then==`function`;function Du(e,t){return t===!1?{status:`canceled`}:(!t||typeof t!=`object`||(typeof t.text==`string`&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options})),{status:`proceed`})}function Ou(e,t,n){let r;try{r=e(wu(t),{signal:n})}catch(e){return{status:`error`,error:e}}return Eu(r)?Promise.resolve(r).then(e=>n.aborted?{status:`aborted`}:Du(t,e),e=>n.aborted?{status:`aborted`}:{status:`error`,error:e}):Du(t,r)}const ku=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?`circle`:`pill`),Au={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`};Ti();const ju=`16px`,Mu=`transparent`,Nu={colors:{primary:{50:`#ffffff`,100:`#f5f5f5`,200:`#d4d4d4`,300:`#a3a3a3`,400:`#737373`,500:`#171717`,600:`#0f0f0f`,700:`#0a0a0a`,800:`#050505`,900:`#030303`,950:`#000000`},secondary:{50:`#f5f3ff`,100:`#ede9fe`,200:`#ddd6fe`,300:`#c4b5fd`,400:`#a78bfa`,500:`#8b5cf6`,600:`#7c3aed`,700:`#6d28d9`,800:`#5b21b6`,900:`#4c1d95`,950:`#2e1065`},accent:{50:`#ecfeff`,100:`#cffafe`,200:`#a5f3fc`,300:`#67e8f9`,400:`#22d3ee`,500:`#06b6d4`,600:`#0891b2`,700:`#0e7490`,800:`#155e75`,900:`#164e63`,950:`#083344`},gray:{50:`#f9fafb`,100:`#f3f4f6`,200:`#e5e7eb`,300:`#d1d5db`,400:`#9ca3af`,500:`#6b7280`,600:`#4b5563`,700:`#374151`,800:`#1f2937`,900:`#111827`,950:`#030712`},success:{50:`#f0fdf4`,100:`#dcfce7`,200:`#bbf7d0`,300:`#86efac`,400:`#4ade80`,500:`#22c55e`,600:`#16a34a`,700:`#15803d`,800:`#166534`,900:`#14532d`},warning:{50:`#fefce8`,100:`#fef9c3`,200:`#fef08a`,300:`#fde047`,400:`#facc15`,500:`#eab308`,600:`#ca8a04`,700:`#a16207`,800:`#854d0e`,900:`#713f12`},error:{50:`#fef2f2`,100:`#fee2e2`,200:`#fecaca`,300:`#fca5a5`,400:`#f87171`,500:`#ef4444`,600:`#dc2626`,700:`#b91c1c`,800:`#991b1b`,900:`#7f1d1d`},info:{50:`#eff6ff`,100:`#dbeafe`,200:`#bfdbfe`,300:`#93c5fd`,400:`#60a5fa`,500:`#3b82f6`,600:`#2563eb`,700:`#1d4ed8`,800:`#1e40af`,900:`#1e3a8a`,950:`#172554`},purple:{50:`#faf5ff`,100:`#f3e8ff`,200:`#e9d5ff`,300:`#d8b4fe`,400:`#c084fc`,500:`#a855f7`,600:`#9333ea`,700:`#7e22ce`,800:`#6b21a8`,900:`#581c87`,950:`#3b0764`},teal:{50:`#f0fdfa`,100:`#ccfbf1`,200:`#99f6e4`,300:`#5eead4`,400:`#2dd4bf`,500:`#14b8a6`,600:`#0d9488`,700:`#0f766e`,800:`#115e59`,900:`#134e4a`,950:`#042f2e`}},spacing:(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?`0px`:`${t/4}rem`;return e})(),typography:{fontFamily:{sans:`system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`,serif:`Georgia, Cambria, "Times New Roman", Times, serif`,mono:`ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace`},fontSize:{xs:`0.75rem`,sm:`0.875rem`,base:`1rem`,lg:`1.125rem`,xl:`1.25rem`,"2xl":`1.5rem`,"3xl":`1.875rem`,"4xl":`2.25rem`},fontWeight:{normal:`400`,medium:`500`,semibold:`600`,bold:`700`},lineHeight:{tight:`1.25`,normal:`1.5`,relaxed:`1.625`}},shadows:{none:`none`,sm:`0 1px 2px 0 rgb(0 0 0 / 0.05)`,md:`0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)`,lg:`0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)`,xl:`0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)`,"2xl":`0 25px 50px -12px rgb(0 0 0 / 0.25)`},borders:{none:`none`,sm:`1px solid`,md:`2px solid`,lg:`4px solid`},radius:{none:`0px`,sm:`0.125rem`,md:`0.375rem`,lg:`0.5rem`,xl:`0.75rem`,"2xl":`1rem`,full:`9999px`}},Pu={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`}},Fu={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:mi,maxWidth:`none`,height:`min(640px, max(200px, calc(100vh - 64px)))`,maxHeight:`none`,borderRadius:`palette.radius.xl`,shadow:`palette.shadows.xl`,inset:ju,canvasBackground:Mu,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`}}},Iu=Nu.colors.gray,Lu={50:`#fafafa`,100:`#f5f5f5`,200:`#e5e5e5`,300:`#d4d4d4`,400:`#a3a3a3`,500:`#737373`,600:`#525252`,700:`#404040`,800:`#262626`,900:`#171717`,950:`#0a0a0a`},Ru={...Nu,colors:{...Nu.colors,gray:Iu}},zu={...Nu,colors:{...Nu.colors,gray:Lu},radius:{none:`0px`,sm:`4px`,md:`8px`,lg:`12px`,xl:`16px`,"2xl":`24px`,full:`9999px`}},Bu=Ru,Vu=Pu,Hu={...Pu,colors:{...Pu.colors,surface:`#ffffff`,background:`#ffffff`,container:`semantic.colors.surface`,textInverse:`#ffffff`},typography:{...Pu.typography,fontSize:`14px`,lineHeight:`1.5`}},Uu=Vu,Wu=Fu,Gu={...Fu,launcher:Au,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:{...Fu.input,borderRadius:`palette.radius.full`},introCard:{...Fu.introCard,title:{fontSize:`22px`,fontWeight:`500`}},suggestion:{chip:{...Fu.suggestion.chip,fontWeight:`400`},card:{...Fu.suggestion.card,fontWeight:`400`},list:{...Fu.suggestion.list,fontWeight:`400`}},panel:{...Fu.panel,width:`min(400px, calc(100vw - 24px))`,height:`min(704px, calc(100dvh - 104px))`,borderRadius:`palette.radius.xl`},header:{...Fu.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:{...Fu.message,gap:`20px`,fullscreenGap:`28px`,topFadeHeight:`18px`,user:{...Fu.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:{...Fu.message.assistant,background:`transparent`,border:`transparent`,borderWidth:`0px`,borderRadius:`0px`,shadow:`none`,padding:`0px`,fontSize:`14px`,lineHeight:`1.55`}},composer:{...Fu.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)`}},Ku=Wu,qu=e=>ui({future:e}),Ju=e=>qu(e)===`v5`?{palette:zu,semantic:Hu,components:Gu}:{palette:Ru,semantic:Vu,components:Wu};function Yu(e,t){if(!t.startsWith(`palette.`)&&!t.startsWith(`semantic.`)&&!t.startsWith(`components.`))return t;let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return typeof r==`string`&&(r.startsWith(`palette.`)||r.startsWith(`semantic.`)||r.startsWith(`components.`))?Yu(e,r):r}function Xu(e){let t={};function n(r,i){for(let[a,o]of Object.entries(r)){let r=`${i}.${a}`;if(typeof o==`string`){let n=Yu(e,o);n!==void 0&&(t[r]={path:r,value:n,type:i.includes(`color`)?`color`:i.includes(`spacing`)?`spacing`:i.includes(`typography`)?`typography`:i.includes(`shadow`)?`shadow`:i.includes(`border`)?`border`:`color`})}else typeof o==`object`&&o&&n(o,r)}}return n(e.palette,`palette`),n(e.semantic,`semantic`),n(e.components,`components`),t}function Zu(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 Qu(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t&&typeof t==`object`&&!Array.isArray(t)&&r&&typeof r==`object`&&!Array.isArray(r)?Qu(t,r):r}return n}function $u(e,t){return t?Qu(e,t):e}function ed(e,t={}){let n=Ju(t.future),r={palette:n.palette,semantic:n.semantic,components:n.components},i={palette:{...r.palette,...e?.palette,colors:{...r.palette.colors,...e?.palette?.colors},spacing:{...r.palette.spacing,...e?.palette?.spacing},typography:{...r.palette.typography,...e?.palette?.typography},shadows:{...r.palette.shadows,...e?.palette?.shadows},borders:{...r.palette.borders,...e?.palette?.borders},radius:{...r.palette.radius,...e?.palette?.radius}},semantic:{...r.semantic,...e?.semantic,colors:{...r.semantic.colors,...e?.semantic?.colors,interactive:{...r.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...r.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...r.semantic.spacing,...e?.semantic?.spacing},typography:{...r.semantic.typography,...e?.semantic?.typography}},components:$u(r.components,e?.components)},a=e?.components?.activity;for(let e of[`toolBubble`,`reasoningBubble`])for(let t of[`rowHeight`,`labelSize`,`iconSize`,`indent`,`bodySurface`])a?.[t]!==void 0&&(i.components[e][t]=a[t]);let o=e?.components?.collapsibleWidget?.surface;o!==void 0&&a?.bodySurface===void 0&&(i.components.activity={...i.components.activity,bodySurface:o});let s=e?.components?.header;s?.padding!==void 0&&s.minimalPadding===void 0&&(i.components.header.minimalPadding=i.components.header.padding);let c=e?.components?.message;if(c?.gap!==void 0&&c.fullscreenGap===void 0&&(i.components.message.fullscreenGap=i.components.message.gap),t.validate!==!1){let e=Zu(i);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(`, `)}`)}if(t.plugins)for(let e of t.plugins)i=e.transform(i);return i}const td=e=>e.trim()===`0`?`0px`:e,nd=`--persona-`,rd=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let e=t.slice(1);if(!/^[0-9a-f]+$/.test(e))return;e.length===3||e.length===4?n=[0,1,2].map(t=>parseInt(e[t]+e[t],16)):(e.length===6||e.length===8)&&(n=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16)))}else{let e=t.match(/^rgba?\(([^)]+)\)$/);if(e){let t=e[1].split(/[,/\s]+/).filter(Boolean);t.length>=3&&(n=t.slice(0,3).map(e=>{let t=e.endsWith(`%`),n=parseFloat(t?e.slice(0,-1):e);return t?n/100*255:n}))}}if(!n||n.some(e=>!Number.isFinite(e)))return;let[r,i,a]=n.map(e=>{let t=Math.max(0,Math.min(255,e))/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a},id=(e,t)=>{for(let[n,...r]of t){let t;for(let n of r)if(t=n.charCodeAt(0)===61?n.slice(1):e[nd+n],t!==void 0)break;t!==void 0&&(e[nd+n]=t)}};function ad(e){let t=Xu(e),n={};for(let[e,r]of Object.entries(t)){let t=e.replace(/\./g,`-`);n[`--persona-${t}`]=r.value}id(n,[[`primary`,`semantic-colors-primary`,`palette-colors-primary-500`],[`secondary`,`semantic-colors-secondary`,`palette-colors-secondary-500`],[`accent`,`semantic-colors-accent`,`palette-colors-accent-500`],[`surface`,`semantic-colors-surface`,`palette-colors-gray-50`],[`background`,`semantic-colors-background`,`palette-colors-gray-50`],[`container`,`semantic-colors-container`,`palette-colors-gray-100`],[`text`,`semantic-colors-text`,`palette-colors-gray-900`],[`text-muted`,`semantic-colors-text-muted`,`palette-colors-gray-500`],[`text-inverse`,`semantic-colors-text-inverse`,`palette-colors-gray-50`],[`border`,`semantic-colors-border`,`palette-colors-gray-200`],[`divider`,`semantic-colors-divider`,`palette-colors-gray-200`],[`muted`,`text-muted`],[`voice-recording-indicator`,`components-voice-recording-indicator`,`palette-colors-error-500`],[`voice-recording-bg`,`components-voice-recording-background`,`palette-colors-error-50`],[`voice-processing-icon`,`components-voice-processing-icon`,`palette-colors-primary-500`],[`voice-speaking-icon`,`components-voice-speaking-icon`,`palette-colors-success-500`],[`approval-bg`,`components-approval-requested-background`,`surface`],[`approval-border`,`components-approval-requested-border`,`border`],[`approval-text`,`components-approval-requested-text`,`palette-colors-gray-900`],[`approval-shadow`,`components-approval-requested-shadow`,`=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)`],[`approval-approve-bg`,`components-approval-approve-background`,`button-primary-bg`],[`approval-deny-bg`,`components-approval-deny-background`,`container`],[`attachment-image-bg`,`components-attachment-image-background`,`palette-colors-gray-100`],[`attachment-image-border`,`components-attachment-image-border`,`palette-colors-gray-200`],[`font-family`,`semantic-typography-fontFamily`,`palette-typography-fontFamily-sans`],[`font-size`,`semantic-typography-fontSize`,`palette-typography-fontSize-base`],[`font-weight`,`semantic-typography-fontWeight`,`palette-typography-fontWeight-normal`],[`line-height`,`semantic-typography-lineHeight`,`palette-typography-lineHeight-normal`],[`input-font-family`,`font-family`],[`input-font-weight`,`font-weight`],[`radius-sm`,`palette-radius-sm`,`=0.125rem`],[`radius-md`,`palette-radius-md`,`=0.375rem`],[`radius-lg`,`palette-radius-lg`,`=0.5rem`],[`radius-xl`,`palette-radius-xl`,`=0.75rem`],[`radius-full`,`palette-radius-full`,`=9999px`],[`launcher-radius`,`components-launcher-borderRadius`,`palette-radius-full`,`=9999px`],[`launcher-bg`,`components-launcher-background`,`surface`],[`launcher-fg`,`components-launcher-foreground`,`primary`]]);let r=n[`--persona-components-launcher-foreground`];n[`--persona-launcher-fg-muted`]=r&&r!==n[`--persona-primary`]?`color-mix(in srgb, ${r} 70%, transparent)`:n[`--persona-muted`],id(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`]]),id(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`]}`,id(n,[[`panel-shadow`,`components-panel-shadow`,`palette-shadows-xl`,`=0 25px 50px -12px rgba(0, 0, 0, 0.25)`]]),n[`--persona-panel-inset`]=n[`--persona-components-panel-inset`]??`16px`,n[`--persona-panel-canvas-bg`]=n[`--persona-components-panel-canvasBackground`]??`transparent`,id(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`]]),id(n,[[`header-bg`,`components-header-background`,`surface`]]);let i=n[`--persona-header-bg`],a=n[`--persona-components-header-foreground`],o=a?`color-mix(in srgb, ${a} 72%, ${i})`:void 0;n[`--persona-header-border`]=n[`--persona-components-header-border`]??(a?`color-mix(in srgb, ${a} 14%, ${i})`:void 0)??n[`--persona-divider`],id(n,[[`header-icon-bg`,`components-header-iconBackground`,`primary`],[`header-icon-fg`,`components-header-iconForeground`,`text-inverse`]]),n[`--persona-header-title-fg`]=n[`--persona-components-header-title-color`]??n[`--persona-components-header-titleForeground`]??a??n[`--persona-primary`],n[`--persona-header-subtitle-fg`]=n[`--persona-components-header-subtitle-color`]??n[`--persona-components-header-subtitleForeground`]??o??n[`--persona-text-muted`],n[`--persona-header-action-icon-fg`]=n[`--persona-components-header-actionIconForeground`]??o??n[`--persona-muted`],id(n,[[`header-control-size`,`components-header-controlSize`,`=32px`],[`header-control-icon-size`,`components-header-controlIconSize`,`=20px`]]);let s=e.components?.header;s?.shadow&&(n[`--persona-header-shadow`]=s.shadow),s?.borderBottom&&(n[`--persona-header-border-bottom`]=s.borderBottom),s?.minHeight&&(n[`--persona-header-min-height`]=s.minHeight);let c=n[`--persona-components-history-railHeader-background`];c&&(n[`--persona-history-rail-header-bg`]=c);let l=n[`--persona-components-history-railHeader-border`];l&&(n[`--persona-history-rail-header-border`]=l);let u=n[`--persona-components-history-railHeader-minHeight`];u&&(n[`--persona-history-rail-header-min-height`]=u);for(let[e,t]of[[`margin`,`margin`],[`borderRadius`,`radius`],[`shadow`,`shadow`],[`background`,`bg`]]){let r=n[`--persona-components-history-overlay-${e}`];r&&(n[`--persona-history-overlay-${t}`]=r)}for(let[e,t]of[[`background`,`bg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-history-menu-${e}`];r&&(n[`--persona-history-menu-${t}`]=r)}let d=e.components?.history?.motion;if(d){let e=e=>{if(e===void 0)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},t=e(d.enterDurationMs);t!==void 0&&(n[`--persona-history-enter-ms`]=t);let r=e(d.exitDurationMs);r!==void 0&&(n[`--persona-history-exit-ms`]=r),d.enterEasing&&(n[`--persona-history-enter-easing`]=d.enterEasing),d.exitEasing&&(n[`--persona-history-exit-easing`]=d.exitEasing)}let f=n[`--persona-components-history-dangerForeground`];f&&(n[`--persona-history-danger-fg`]=f),n[`--persona-danger`]=n[`--persona-components-history-confirm-dangerBackground`]??n[`--persona-palette-colors-error-700`]??`#b42318`,n[`--persona-danger-fg`]=n[`--persona-components-history-confirm-dangerForeground`]??`#ffffff`;for(let e of[`scrim`,`shadow`]){let t=n[`--persona-components-history-confirm-${e}`];t&&(n[`--persona-history-confirm-${e}`]=t)}for(let[e,t]of[[`background`,`background`],[`foreground`,`foreground`],[`hintForeground`,`hint-fg`],[`borderRadius`,`radius`],[`fontSize`,`font-size`],[`padding`,`padding`],[`maxWidth`,`max-width`],[`shadow`,`shadow`]]){let r=n[`--persona-components-tooltip-${e}`];r&&(n[`--persona-tooltip-${t}`]=r)}e.components?.tooltip?.arrow===!1&&(n[`--persona-tooltip-arrow-display`]=`none`);for(let[e,t]of[[`background`,`bg`],[`border`,`border`],[`hoverBackground`,`hover-bg`],[`hoverForeground`,`hover-fg`],[`borderRadius`,`radius`]]){let r=n[`--persona-components-messageActions-${e}`];r&&(n[`--persona-message-action-${t}`]=r)}id(n,[[`intro-card-bg`,`components-introCard-background`,`=transparent`],[`intro-card-radius`,`components-introCard-borderRadius`,`=1rem`]]);let p=n[`--persona-components-introCard-background`],m=n[`--persona-components-introCard-shadow`],h=(!p||p===`transparent`||p===`none`)&&(!m||m===`none`),g=n[`--persona-components-introCard-padding`]??`1.5rem`;n[`--persona-intro-card-padding`]=h&&g===`1.5rem`?`1.5rem 0`:g,id(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`]]),id(n,[[`composer-padding`,`components-composer-padding`,`=0.75rem 1rem`],[`composer-gap`,`components-composer-gap`,`=0.5rem`],[`composer-font-size`,`components-composer-fontSize`,`=0.875rem`],[`composer-line-height`,`components-composer-lineHeight`,`=1.25rem`],[`composer-control-size`,`components-composer-controlSize`,`=40px`],[`composer-control-icon-size`,`components-composer-controlIconSize`,`=24px`],[`motion-duration-fast`,`components-motion-durationFast`,`=120ms`],[`motion-duration-base`,`components-motion-durationBase`,`=200ms`],[`motion-easing`,`components-motion-easing`,`=cubic-bezier(0.2, 0, 0, 1)`],[`composer-border-color`,`components-composer-borderColor`,`border`,`=#e5e7eb`],[`composer-overlay-band`,`components-composer-overlayBand`,`=transparent`],[`scrollbar-thumb`,`components-scrollbar-thumb`,`border`,`=#e5e7eb`],[`scrollbar-track`,`components-scrollbar-track`,`=transparent`],[`md-inline-code-bg`,`components-markdown-inlineCode-background`,`container`],[`md-inline-code-color`,`components-markdown-inlineCode-foreground`,`text`],[`md-link-color`,`components-markdown-link-foreground`,`accent`,`=#0f0f0f`]]);let _=n[`--persona-components-markdown-heading-h1-fontSize`];_&&(n[`--persona-md-h1-size`]=_);let v=n[`--persona-components-markdown-heading-h1-fontWeight`];v&&(n[`--persona-md-h1-weight`]=v);let y=n[`--persona-components-markdown-heading-h2-fontSize`];y&&(n[`--persona-md-h2-size`]=y);let b=n[`--persona-components-markdown-heading-h2-fontWeight`];b&&(n[`--persona-md-h2-weight`]=b);let x=n[`--persona-components-markdown-prose-fontFamily`];x&&x!==`inherit`&&(n[`--persona-md-prose-font-family`]=x),id(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`]]),id(n,[[`md-code-block-border-radius`,`components-markdown-codeBlock-borderRadius`,`radius-md`,`=0.375rem`]]),id(n,[[`md-table-header-bg`,`components-markdown-table-headerBackground`,`container`],[`md-table-border-color`,`components-markdown-table-borderColor`,`border`]]),id(n,[[`md-hr-color`,`components-markdown-hr-color`,`divider`]]),id(n,[[`md-blockquote-border-color`,`components-markdown-blockquote-borderColor`,`palette-colors-gray-900`],[`md-blockquote-bg`,`components-markdown-blockquote-background`,`=transparent`],[`md-blockquote-text-color`,`components-markdown-blockquote-textColor`,`palette-colors-gray-500`]]);for(let[e,t]of[[`container`,`surface`],[`surface`,`surface`],[`border`,`border`]]){let r=n[`--persona-components-collapsibleWidget-${e}`]??n[`--persona-${t}`];r!==void 0&&(n[`--persona-cw-${e}`]=r,n[`--cw-${e}`]=r)}id(n,[[`message-border`,`components-message-border`,`border`]]),id(n,[[`message-user-padding`,`components-message-user-padding`],[`message-user-max-width`,`components-message-user-maxWidth`],[`message-user-font-size`,`components-message-user-fontSize`],[`message-user-font-family`,`components-message-user-fontFamily`],[`message-user-line-height`,`components-message-user-lineHeight`],[`message-assistant-padding`,`components-message-assistant-padding`],[`message-assistant-border-width`,`components-message-assistant-borderWidth`],[`message-assistant-max-width`,`components-message-assistant-maxWidth`],[`message-assistant-font-size`,`components-message-assistant-fontSize`],[`message-assistant-font-family`,`components-message-assistant-fontFamily`],[`message-assistant-line-height`,`components-message-assistant-lineHeight`]]);let S=e.components,C=S?.iconButton;C&&(C.background&&(n[`--persona-icon-btn-bg`]=C.background),C.border&&(n[`--persona-icon-btn-border`]=C.border),C.color&&(n[`--persona-icon-btn-color`]=C.color),C.padding&&(n[`--persona-icon-btn-padding`]=C.padding),C.borderRadius&&(n[`--persona-icon-btn-radius`]=C.borderRadius),C.hoverBackground&&(n[`--persona-icon-btn-hover-bg`]=C.hoverBackground),C.hoverColor&&(n[`--persona-icon-btn-hover-color`]=C.hoverColor),C.activeBackground&&(n[`--persona-icon-btn-active-bg`]=C.activeBackground),C.activeBorder&&(n[`--persona-icon-btn-active-border`]=C.activeBorder));let w=S?.labelButton;w&&(w.background&&(n[`--persona-label-btn-bg`]=w.background),w.border&&(n[`--persona-label-btn-border`]=w.border),w.color&&(n[`--persona-label-btn-color`]=w.color),w.padding&&(n[`--persona-label-btn-padding`]=w.padding),w.borderRadius&&(n[`--persona-label-btn-radius`]=w.borderRadius),w.hoverBackground&&(n[`--persona-label-btn-hover-bg`]=w.hoverBackground),w.fontSize&&(n[`--persona-label-btn-font-size`]=w.fontSize),w.gap&&(n[`--persona-label-btn-gap`]=w.gap));let T=S?.toggleGroup;T&&(T.gap&&(n[`--persona-toggle-group-gap`]=T.gap),T.borderRadius&&(n[`--persona-toggle-group-radius`]=T.borderRadius));let E=S?.artifact;if(E?.toolbar){let t=E.toolbar;t.iconHoverColor&&(n[`--persona-artifact-toolbar-icon-hover-color`]=t.iconHoverColor),t.iconHoverBackground&&(n[`--persona-artifact-toolbar-icon-hover-bg`]=t.iconHoverBackground),t.iconPadding&&(n[`--persona-artifact-toolbar-icon-padding`]=t.iconPadding),t.iconBorderRadius&&(n[`--persona-artifact-toolbar-icon-radius`]=t.iconBorderRadius),t.iconBorder&&(n[`--persona-artifact-toolbar-icon-border`]=t.iconBorder),t.toggleGroupGap&&(n[`--persona-artifact-toolbar-toggle-group-gap`]=td(t.toggleGroupGap)),t.toggleBorderRadius&&(n[`--persona-artifact-toolbar-toggle-radius`]=t.toggleBorderRadius),t.toggleGroupPadding&&(n[`--persona-artifact-toolbar-toggle-group-padding`]=td(t.toggleGroupPadding)),t.toggleGroupBorder&&(n[`--persona-artifact-toolbar-toggle-group-border`]=t.toggleGroupBorder),t.toggleGroupBorderRadius&&(n[`--persona-artifact-toolbar-toggle-group-radius`]=t.toggleGroupBorderRadius),t.toggleGroupBackground&&(n[`--persona-artifact-toolbar-toggle-group-bg`]=Yu(e,t.toggleGroupBackground)??t.toggleGroupBackground),t.copyBackground&&(n[`--persona-artifact-toolbar-copy-bg`]=t.copyBackground),t.copyBorder&&(n[`--persona-artifact-toolbar-copy-border`]=t.copyBorder),t.copyColor&&(n[`--persona-artifact-toolbar-copy-color`]=t.copyColor),t.copyBorderRadius&&(n[`--persona-artifact-toolbar-copy-radius`]=td(t.copyBorderRadius)),t.copyPadding&&(n[`--persona-artifact-toolbar-copy-padding`]=t.copyPadding),t.copyMenuBackground&&(n[`--persona-artifact-toolbar-copy-menu-bg`]=t.copyMenuBackground,n[`--persona-dropdown-bg`]=n[`--persona-dropdown-bg`]??t.copyMenuBackground),t.copyMenuBorder&&(n[`--persona-artifact-toolbar-copy-menu-border`]=t.copyMenuBorder,n[`--persona-dropdown-border`]=n[`--persona-dropdown-border`]??t.copyMenuBorder),t.copyMenuShadow&&(n[`--persona-artifact-toolbar-copy-menu-shadow`]=t.copyMenuShadow,n[`--persona-dropdown-shadow`]=n[`--persona-dropdown-shadow`]??t.copyMenuShadow),t.copyMenuBorderRadius&&(n[`--persona-artifact-toolbar-copy-menu-radius`]=t.copyMenuBorderRadius,n[`--persona-dropdown-radius`]=n[`--persona-dropdown-radius`]??t.copyMenuBorderRadius),t.copyMenuItemHoverBackground&&(n[`--persona-artifact-toolbar-copy-menu-item-hover-bg`]=t.copyMenuItemHoverBackground,n[`--persona-dropdown-item-hover-bg`]=n[`--persona-dropdown-item-hover-bg`]??t.copyMenuItemHoverBackground),t.iconBackground&&(n[`--persona-artifact-toolbar-icon-bg`]=t.iconBackground),t.toolbarBorder&&(n[`--persona-artifact-toolbar-border`]=t.toolbarBorder)}if(E?.tab){let e=E.tab;e.background&&(n[`--persona-artifact-tab-bg`]=e.background),e.activeBackground&&(n[`--persona-artifact-tab-active-bg`]=e.activeBackground),e.activeBorder&&(n[`--persona-artifact-tab-active-border`]=e.activeBorder),e.borderRadius&&(n[`--persona-artifact-tab-radius`]=e.borderRadius),e.textColor&&(n[`--persona-artifact-tab-color`]=e.textColor),e.hoverBackground&&(n[`--persona-artifact-tab-hover-bg`]=e.hoverBackground),e.listBackground&&(n[`--persona-artifact-tab-list-bg`]=e.listBackground),e.listBorderColor&&(n[`--persona-artifact-tab-list-border-color`]=e.listBorderColor),e.listPadding&&(n[`--persona-artifact-tab-list-padding`]=e.listPadding)}if(E?.pane){let t=E.pane;t.toolbarBackground&&(n[`--persona-artifact-toolbar-bg`]=Yu(e,t.toolbarBackground)??t.toolbarBackground)}if(E?.card){let e=E.card;e.background&&(n[`--persona-artifact-card-bg`]=e.background),e.border&&(n[`--persona-artifact-card-border`]=e.border),e.borderRadius&&(n[`--persona-artifact-card-radius`]=e.borderRadius),e.hoverBackground&&(n[`--persona-artifact-card-hover-bg`]=e.hoverBackground),e.hoverBorderColor&&(n[`--persona-artifact-card-hover-border`]=e.hoverBorderColor)}if(E?.inline){let t=E.inline;t.background&&(n[`--persona-artifact-inline-bg`]=Yu(e,t.background)??t.background),t.border&&(n[`--persona-artifact-inline-border`]=t.border),t.borderRadius&&(n[`--persona-artifact-inline-radius`]=t.borderRadius),t.chromeBackground&&(n[`--persona-artifact-inline-chrome-bg`]=Yu(e,t.chromeBackground)??t.chromeBackground),t.chromeBorder&&(n[`--persona-artifact-inline-chrome-border`]=Yu(e,t.chromeBorder)??t.chromeBorder),t.titleColor&&(n[`--persona-artifact-inline-title-color`]=Yu(e,t.titleColor)??t.titleColor),t.mutedColor&&(n[`--persona-artifact-inline-muted-color`]=Yu(e,t.mutedColor)??t.mutedColor),t.frameHeight&&(n[`--persona-artifact-inline-frame-height`]=t.frameHeight)}let D=S?.code;D&&(D.keywordColor&&(n[`--persona-code-keyword-color`]=D.keywordColor),D.stringColor&&(n[`--persona-code-string-color`]=D.stringColor),D.commentColor&&(n[`--persona-code-comment-color`]=D.commentColor),D.numberColor&&(n[`--persona-code-number-color`]=D.numberColor),D.tagColor&&(n[`--persona-code-tag-color`]=D.tagColor),D.attrColor&&(n[`--persona-code-attr-color`]=D.attrColor),D.propertyColor&&(n[`--persona-code-property-color`]=D.propertyColor),D.lineNumberColor&&(n[`--persona-code-line-number-color`]=D.lineNumberColor),D.gutterBorderColor&&(n[`--persona-code-gutter-border-color`]=D.gutterBorderColor),D.background&&(n[`--persona-code-bg`]=Yu(e,D.background)??D.background));let O=n[`--persona-surface`],ee=n[`--persona-container`],k=n[`--persona-palette-colors-gray-100`]??`#f3f4f6`,A=n[`--persona-palette-colors-gray-200`]??`#e5e7eb`,te=n[`--persona-palette-colors-gray-300`]??`#d1d5db`,ne=!ee||ee===O,re=rd(O??n[`--persona-background`]),ie=ne&&re!==void 0&&re<.179,ae=ie?`rgba(255, 255, 255, 0.08)`:k,j=ie?`rgba(255, 255, 255, 0.12)`:A,M=ie?`rgba(255, 255, 255, 0.16)`:te,N=ne?ae:ee,oe=ne?j:ee;return n[`--persona-icon-btn-hover-bg`]=n[`--persona-icon-btn-hover-bg`]??N,n[`--persona-icon-btn-active-bg`]=n[`--persona-icon-btn-active-bg`]??oe,ne&&(n[`--persona-icon-btn-active-border`]=n[`--persona-icon-btn-active-border`]??M),n[`--persona-label-btn-hover-bg`]=n[`--persona-label-btn-hover-bg`]??N,n[`--persona-artifact-tab-hover-bg`]=n[`--persona-artifact-tab-hover-bg`]??N,n[`--persona-artifact-card-hover-bg`]=n[`--persona-artifact-card-hover-bg`]??N,n}const od={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`};Ti(),Wr();const sd=e=>!!e&&`launcher`in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode===`docked`),cd=(e,t)=>{if(!t||!sd(t))return e;let n=t.theme?.components?.panel?.width,r=t.darkTheme?.components?.panel?.width;return(yd(t)===`dark`?r??n:n)==null?{...e,components:{...e.components,panel:{...e.components.panel,width:ui(t)===`v5`?`400px`:`420px`}}}:e},ld={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`}}},ud={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)`}}}},dd=ld,fd={...dd,colors:{...dd.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`}}},pd=ud,md={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:{...ud.components,button:{...ud.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:{...ud.components?.eventStream,badge:{...ud.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`}}}}},hd=e=>ui({future:e})===`v5`?{palette:fd,components:md}:{palette:dd,components:pd},gd=e=>{if(e&&typeof e==`object`&&!Array.isArray(e))return e},_d=()=>typeof document<`u`&&document.documentElement.classList.contains(`dark`)||typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`,vd=e=>{let t=e?.colorScheme??`light`;return t===`light`?`light`:t===`dark`?`dark`:_d()},yd=e=>vd(e),bd=(e,t={})=>ed(e,t),xd=(e,t={})=>{let n=hd(t.future),r=Hr(n.components,e??{})??{};return ed({...r,palette:{...r.palette,colors:ui(t)===`v5`?Hr(n.palette.colors,r.palette?.colors):{...n.palette.colors,...r.palette?.colors}}},{validate:!1,future:t.future})},Sd=e=>{let t=yd(e),n=gd(e?.theme),r=Hr({components:{launcher:ku(e)===`circle`?Au:{...Wu.launcher,...e?.future?.v5Defaults?{offset:`1.5rem`}:{}}}},n),i=gd(e?.darkTheme);return cd(t===`dark`?xd(Hr(r??{},i??{}),{future:e?.future}):bd(r,{future:e?.future}),e)},Cd=e=>ad(e),wd=(e,t)=>{let n=Sd(t),r=Cd(n);for(let[t,n]of Object.entries(r))e.style.setProperty(t,n);e.setAttribute(`data-persona-color-scheme`,yd(t)),e.setAttribute(`data-persona-defaults`,ui(t))},Td=e=>{let t=[];if(typeof document<`u`&&typeof MutationObserver<`u`){let n=new MutationObserver(()=>{e(_d())});n.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),t.push(()=>n.disconnect())}if(typeof window<`u`&&window.matchMedia){let n=window.matchMedia(`(prefers-color-scheme: dark)`),r=()=>e(_d());n.addEventListener?(n.addEventListener(`change`,r),t.push(()=>n.removeEventListener(`change`,r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(e=>e())}},Ed=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??`720px`:`768px`),Dd=(e,t)=>t||e?.composer?.placement!==`overlay`?`block`:`overlay`,Od=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},kd=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight),Ad=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;m.Idiomorph.morph(e,t.innerHTML,{morphStyle:`innerHTML`,callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement&&r){if(e.classList.contains(`persona-animate-typing`)||e.hasAttribute(`data-preserve-runtime`))return!1;if(e.hasAttribute(`data-tool-elapsed`))return t instanceof HTMLElement&&t.getAttribute(`data-tool-elapsed`)===e.getAttribute(`data-tool-elapsed`)?!1:void 0;if(e.hasAttribute(`data-preserve-animation`))return t instanceof HTMLElement&&!t.hasAttribute(`data-preserve-animation`)||t instanceof HTMLElement&&t.hasAttribute(`data-preserve-animation`)&&(e.textContent??``)!==(t.textContent??``)?void 0:!1}}}})},jd=e=>e.replace(/^\n+/,``).replace(/\s+$/,``),Md={index:-1,draft:``};function Nd(e){let{direction:t,history:n,currentValue:r,atStart:i,state:a}=e,o=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t===`up`){if(!o&&!i)return{handled:!1,state:a};if(!o){let e=n.length-1;return{handled:!0,value:n[e],state:{index:e,draft:r}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!o)return{handled:!1,state:a};if(a.index<n.length-1){let e=a.index+1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function Pd(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 Fd(){return/* @__PURE__ */ new Map}function Id(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Ld(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Rd(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function zd(e){return e.role!==`assistant`||e.variant===`tool`||e.variant===`reasoning`?!1:e.variant===`approval`||!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function Bd(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>!t&&(t=!0,!0)}}function Vd(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Hd(e,t){return Vd(e)-e.scrollTop<=t}function Ud(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:i,userScrollThreshold:a,isAutoScrolling:o=!1,pauseOnUpwardScroll:s=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:l=!1}=e,u=n-r;return o||Math.abs(u)<a?{action:`none`,delta:u,nextLastScrollTop:n}:!t&&i&&(!l||u>0)?{action:`resume`,delta:u,nextLastScrollTop:n}:t&&s&&u<0||t&&c&&!i?{action:`pause`,delta:u,nextLastScrollTop:n}:{action:`none`,delta:u,nextLastScrollTop:n}}function Wd(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:i=!1}=e;return t&&n<0?`pause`:!t&&i&&n>0&&r?`resume`:`none`}function Gd(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Kd(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset);return{targetScrollTop:t,spacerHeight:Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0))}}function qd(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}const Jd={type:`none`,placeholder:`none`,speed:120,duration:1800,buffer:`none`},Yd=[`pre`,`code`,`a`,`script`,`style`],Xd=e=>({type:e?.type??Jd.type,placeholder:e?.placeholder??Jd.placeholder,speed:e?.speed??Jd.speed,duration:e?.duration??Jd.duration,buffer:e?.buffer??Jd.buffer}),Zd=[{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`}],Qd=/* @__PURE__ */ new Map;for(let e of Zd)Qd.set(e.name,e);const $d=[`wipe`,`glyph-cycle`],ef=e=>{Qd.set(e.name,e)},tf=e=>{Zd.some(t=>t.name===e)||Qd.delete(e)},nf=()=>Array.from(Qd.keys()),rf=(e,t)=>e===`none`?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Qd.get(e)??null,af=(e,t,n,r,i)=>{if(!i)return e;if(n?.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t===`word`){let t=e.search(/\s(?=\S*$)/);return t<0?``:e.slice(0,t)}if(t===`line`){let t=e.lastIndexOf(`
24
+ `);return t<0?``:e.slice(0,t)}return e},of=(e,t,n,r)=>{let i=e.createElement(`span`);return i.className=`persona-stream-char`,i.id=`stream-c-${n}-${r}`,i.style.setProperty(`--char-index`,String(r)),i.textContent=t,i},sf=(e,t,n,r)=>{let i=e.createElement(`span`);return i.className=`persona-stream-word`,i.id=`stream-w-${n}-${r}`,i.style.setProperty(`--word-index`,String(r)),i.textContent=t,i},cf=/\s/,lf=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let e=n;if(t.has(e.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},uf=(e,t,n)=>{let r=e.ownerDocument,i=e.parentNode;if(!r||!i)return;let a=e.nodeValue??``;if(!a)return;let o=r.createDocumentFragment(),s=0;for(;s<a.length;)if(cf.test(a[s])){let e=s;for(;e<a.length&&cf.test(a[e]);)e+=1;o.appendChild(r.createTextNode(a.slice(s,e))),s=e}else{let e=r.createElement(`span`);e.className=`persona-stream-word-group`;let i=s;for(;i<a.length&&!cf.test(a[i]);)e.appendChild(of(r,a[i],t,n.value)),n.value+=1,i+=1;o.appendChild(e),s=i}i.replaceChild(o,e)},df=(e,t,n)=>{let r=e.ownerDocument,i=e.parentNode;if(!r||!i)return;let a=e.nodeValue??``;if(!a)return;let o=r.createDocumentFragment(),s=a.split(/(\s+)/);for(let e of s)e&&(/^\s+$/.test(e)?o.appendChild(r.createTextNode(e)):(o.appendChild(sf(r,e,t,n.value)),n.value+=1));i.replaceChild(o,e)},ff=(e,t,n,r)=>{if(!e||typeof document>`u`)return e;let i=document.createElement(`div`);i.innerHTML=e;let a=new Set((r?.skipTags??Yd).map(e=>e.toLowerCase())),o=document.createTreeWalker(i,NodeFilter.SHOW_TEXT,null),s=[],c=o.nextNode();for(;c;)lf(c,a)||s.push(c),c=o.nextNode();let l={value:r?.startIndex??0},u=t===`char`?uf:df;for(let e of s)u(e,n,l);return i.innerHTML},pf=(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},mf=(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},hf=/* @__PURE__ */ new WeakMap,gf=(e,t)=>{if(!e.styles)return;let n=hf.get(t);if(n||(n=/* @__PURE__ */ new Set,hf.set(t,n)),n.has(e.name)){let r=e.name.replace(/["\\]/g,`\\$&`);if(t.querySelector(`style[data-persona-animation="${r}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement(`style`);r.setAttribute(`data-persona-animation`,e.name),r.textContent=e.styles,t.appendChild(r)},_f=/* @__PURE__ */ new WeakMap,vf=(e,t)=>{if(!e.onAttach)return;let n=_f.get(t);if(n||(n=/* @__PURE__ */ new Map,_f.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},yf=e=>{let t=_f.get(e);if(t){for(let e of t.values())typeof e==`function`&&e();t.clear()}},bf=(e,t)=>{gf(e,t),vf(e,t)};g();const{setLoader:xf,load:Sf}=h({fallbackImport:()=>import(`@runtypelabs/persona/animations-extra`)}),Cf=Sf;fn();function wf(e,t=un){let n=e.style.position,r=e.style.zIndex,i=e.style.isolation,a=getComputedStyle(e),o=a.position===`static`||a.position===``;return o&&(e.style.position=`relative`),e.style.zIndex=String(t),e.style.isolation=`isolate`,()=>{o&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=i}}let Tf=0,Ef=null;function Df(e=document){if(Tf++,Tf===1){let t=e.body,n=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Ef={originalOverflow:t.style.overflow,originalPosition:t.style.position,originalTop:t.style.top,originalWidth:t.style.width,scrollY:n},t.style.overflow=`hidden`,t.style.position=`fixed`,t.style.top=`-${n}px`,t.style.width=`100%`}let t=!1;return()=>{if(!t&&(t=!0,Tf=Math.max(0,Tf-1),Tf===0&&Ef)){let t=e.body,n=e.defaultView??window;t.style.overflow=Ef.originalOverflow,t.style.position=Ef.originalPosition,t.style.top=Ef.originalTop,t.style.width=Ef.originalWidth,n.scrollTo(0,Ef.scrollY),Ef=null}}}li();const Of={side:`right`,width:`420px`,animate:!0,reveal:`resize`,maxHeight:`100dvh`},kf=e=>(e?.launcher?.mountMode??`floating`)===`docked`,Af=e=>(e?.launcher?.mountMode??`floating`)===`composer-bar`,jf=e=>{let t=e?.launcher?.dock,n=ai(e).dockWidth?t?.width:Yu(Sd(e),`components.panel.width`);return{side:t?.side??Of.side,width:n??Of.width,animate:t?.animate??Of.animate,reveal:t?.reveal??Of.reveal,maxHeight:t?.maxHeight??Of.maxHeight}};V(),F(),A();const Mf=e=>e===`followUp`?`follow-up`:e,Nf=(e,t=0)=>{if(typeof e==`string`){let t=e.trim();return t?{id:t,label:t,prompt:t,emphasis:`default`}:null}let n=e.label.trim();if(!n)return null;let r=e.prompt?.trim()||n;return{id:e.id?.trim()||r||`suggestion-${t}`,label:n,prompt:r,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??`default`}},Pf=/* @__PURE__ */ new WeakSet,Ff=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,If=e=>{Ff()||e.forEach((e,t)=>{typeof e.animate==`function`&&e.animate([{opacity:`0`,transform:`translateY(4px)`},{opacity:`1`,transform:`none`}],{duration:250,delay:t*60,easing:`ease-out`,fill:`backwards`})})},Lf=e=>{let{item:t,index:n,surface:r,source:i,variant:a,streaming:o,config:s,plugins:c,chipsConfig:l,session:u,getTextarea:d,eventTarget:p,submitPrompt:m}=e,h=r===`followUp`,g=t.behavior,_=()=>{if(u.isStreaming())return;let e={suggestion:{...t},surface:r,source:i,behavior:g},n=p.dispatchEvent(new CustomEvent(`persona:suggestion:selected`,{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(h&&p.dispatchEvent(new CustomEvent(`persona:suggestReplies:selected`,{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!n)return;for(let e of c)if(e.onSuggestionSelect?.({suggestion:{...t},surface:r,source:i,variant:a,config:s})===!1)return;let o=d();g===`fill`?(o.value=t.prompt,o.dispatchEvent(new Event(`input`,{bubbles:!0,composed:!0})),o.focus()):m?m(t.prompt):(o.value=``,u.sendMessage(t.prompt))},v=()=>{let e=z(`button`,`persona-suggestion persona-suggestion--${a}`);if(e.type=`button`,e.disabled=o,e.dataset.suggestionId=t.id,e.dataset.emphasis=t.emphasis,e.dataset.behavior=g,a===`chip`&&(l?.fontWeight&&(e.style.fontWeight=l.fontWeight),l?.paddingX&&(e.style.paddingLeft=l.paddingX,e.style.paddingRight=l.paddingX),l?.paddingY&&(e.style.paddingTop=l.paddingY,e.style.paddingBottom=l.paddingY)),t.icon){let n=P(t.icon,`var(--persona-suggestion-icon-size)`,`currentColor`,1.8);n&&(n.classList.add(`persona-suggestion__icon`),t.iconColor&&(n.style.color=t.iconColor),e.appendChild(n))}let n=z(`span`,`persona-suggestion__copy`);if(n.appendChild(B(`span`,{className:`persona-suggestion__label`,text:t.label})),t.description&&a!==`chip`&&n.appendChild(B(`span`,{className:`persona-suggestion__description`,text:t.description})),e.appendChild(n),a!==`chip`){let t=k(f.ArrowRight,16,`currentColor`,1.8);t&&(t.classList.add(`persona-suggestion__arrow`),e.appendChild(t))}return e.addEventListener(`click`,_),e},y=null;for(let e of c)if(e.renderSuggestion&&(y=e.renderSuggestion({suggestion:{...t},index:n,surface:r,source:i,variant:a,streaming:o,config:s,defaultRenderer:v,select:_}),y))break;return y??=v(),y.dataset.suggestionId||=t.id,y.dataset.behavior||=g,y.dataset.emphasis||=t.emphasis,y instanceof HTMLButtonElement||y.setAttribute(`aria-disabled`,o?`true`:`false`),y},Rf=e=>{let t=[],n=[],r=null,i=null,a=()=>{e.removeAttribute(`data-scroll-left`),e.removeAttribute(`data-scroll-right`)},o=()=>{if(i=null,e.hidden||e.dataset.variant!==`chip`||e.dataset.overflow!==`scroll`){a();return}let t=Math.max(0,e.scrollWidth-e.clientWidth);if(t<=1){a();return}let n=getComputedStyle(e).direction===`rtl`,r=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),o=r<=4,s=r>=t-4,c=n?!s:!o,l=n?!o:!s;e.toggleAttribute(`data-scroll-left`,c),e.toggleAttribute(`data-scroll-right`,l)},s=()=>{i!==null||typeof requestAnimationFrame!=`function`?typeof requestAnimationFrame!=`function`&&o():i=requestAnimationFrame(o)};e.addEventListener(`scroll`,s,{passive:!0});let c=typeof ResizeObserver==`function`?new ResizeObserver(s):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener(`scroll`,s),c?.disconnect(),i!==null&&typeof cancelAnimationFrame==`function`&&cancelAnimationFrame(i),i=null},render:(i,c,l,u,d,f)=>{e.replaceChildren(),t.length=0,n.length=0;let p=f?.source??`config`,m=f?.surface??(p===`config`?`starter`:`followUp`),h=m===`followUp`,g=f?.variant??`chip`,_=f?.behavior??`send`,v=f?.overflow??`wrap`,y=f?.config??{},b=f?.plugins??[],x=typeof f?.maxItems==`number`?Math.max(0,Math.floor(f.maxItems)):void 0,S=h?`followUps`:`starters`;!Pf.has(y)&&y.debug===!0&&g!==`chip`&&y.suggestions?.[S]?.overflow!==void 0&&(Pf.add(y),console.info(`[persona] suggestions.${S}.overflow applies to the "chip" variant only; the "${g}" variant manages its own stacking.`));let C=e=>e.map(Nf).filter(e=>e!==null).map(e=>({...e,behavior:e.behavior??_})),w=C(i??[]);b.forEach(e=>{e.transformSuggestions&&(w=C(e.transformSuggestions({suggestions:w.map(e=>({...e})),surface:m,source:p,config:y})))});let T=x===void 0?w:w.slice(0,x);if(!T.length){e.hidden=!0,r=null,a();return}if(!h&&(u??c.getMessages()).some(e=>e.role===`user`)){e.hidden=!0,r=null;return}e.hidden=!1,e.classList.add(`persona-suggestions`),e.dataset.personaSuggestionSurface=Mf(m),e.dataset.variant=g,e.dataset.overflow=v;let E=document.createDocumentFragment(),D=c.isStreaming();T.forEach((r,i)=>{let a=Lf({item:r,index:i,surface:m,source:p,variant:g,streaming:D,config:y,plugins:b,chipsConfig:d,session:c,getTextarea:()=>l,eventTarget:e,submitPrompt:f?.submitPrompt});E.appendChild(a),n.push(a),[...a instanceof HTMLButtonElement?[a]:[],...Array.from(a.querySelectorAll(`button`))].forEach(e=>{t.includes(e)||(e.disabled=D,t.push(e))})}),e.appendChild(E),o(),s();let O=JSON.stringify({normalized:T,surface:m,variant:g,source:p});O!==r&&(r=O,If(n),e.dispatchEvent(new CustomEvent(`persona:suggestion:shown`,{detail:{suggestions:T.map(e=>({...e})),surface:m,source:p,variant:g},bubbles:!0,composed:!0})),h&&e.dispatchEvent(new CustomEvent(`persona:suggestReplies:shown`,{detail:{suggestions:T.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},zf={"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`};V(),F(),Lr();const Bf={x:[1.4,1.05]},Vf=`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`,Hf=(e,t,n={})=>{let{iconSize:r,iconText:i}=n,[a,o]=Bf[t]??[1,1.5],s=!r;e.classList.toggle(`persona-header-control--glyph`,s),e.classList.toggle(`persona-header-control--sparse`,s&&a!==1);let c=P(t,`${Math.round((parseFloat(r??``)||20)*a)}px`,`currentColor`,o);c?(c.style.display=`block`,s||(c.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((o/1.5).toFixed(4))})`),e.replaceChildren(c)):i&&(e.textContent=i)},Uf=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:r,iconName:i,iconText:a,wrapperClassName:o=Vf,size:s,iconSize:c,color:l,backgroundColor:u,borderWidth:d,borderColor:f,borderRadius:p,paddingX:m,paddingY:h,hidden:g,extraClassName:_,attrs:v}=e,y=z(`div`,o),b=!!(d||f),x=B(`button`,{className:$e(`persona-header-control`,`persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer`,!u&&`persona-bg-transparent hover:persona-bg-gray-100`,!b&&`persona-border-none`,!p&&`persona-rounded-full`,_),attrs:{type:`button`,"aria-label":t,...v},style:{width:s,height:s,minWidth:s,minHeight:s,display:g?`none`:void 0,color:l||Kf.actionIconColor,backgroundColor:u,border:b?`${d||`0px`} solid ${f||`transparent`}`:void 0,borderRadius:p,paddingLeft:m,paddingRight:m,paddingTop:h,paddingBottom:h}});return i?Hf(x,i,{iconSize:c,iconText:a}):a&&(x.textContent=a),y.appendChild(x),br({anchor:x,trigger:y,text:()=>x.getAttribute(`aria-label`)??t,hint:r,enabled:n}),{button:x,wrapper:y}},Wf=(e,t={})=>{let{showClose:n=!0,wrapperClassName:r=Vf,buttonSize:i,iconSize:a}=t,o=e?.launcher??{},s=o.closeButtonTooltipText??`Close chat`,c=o.closeButtonShowTooltip??!0,{button:l,wrapper:u}=Uf({ariaLabel:s,tooltip:c,iconName:o.closeButtonIconName??`x`,iconText:o.closeButtonIconText??`×`,wrapperClassName:r,size:i??o.closeButtonSize,iconSize:a,color:o.closeButtonColor,backgroundColor:o.closeButtonBackgroundColor,borderWidth:o.closeButtonBorderWidth,borderColor:o.closeButtonBorderColor,borderRadius:o.closeButtonBorderRadius,paddingX:o.closeButtonPaddingX,paddingY:o.closeButtonPaddingY,hidden:!n});return{button:l,wrapper:u}},Gf=(e,t={})=>{let{wrapperClassName:n=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,buttonSize:r,iconSize:i}=t,a=(e?.launcher??{}).clearChat??{},o=a.tooltipText??`Clear chat`,s=a.showTooltip??!0,{button:c,wrapper:l}=Uf({ariaLabel:o,tooltip:s,iconName:a.iconName??`refresh-cw`,wrapperClassName:n,size:r??a.size,iconSize:i,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:c,wrapper:l}};V(),F(),Ti();const Kf={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)`},qf={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)`},Jf={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)`},Yf=e=>{let{config:t,showClose:n=!0}=e,r=B(`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:Kf.minHeight,backgroundColor:`var(--persona-header-bg, var(--persona-surface, #ffffff))`,borderBottomColor:`var(--persona-header-border, var(--persona-divider, #f1f5f9))`,boxShadow:`var(--persona-header-shadow, none)`,borderBottom:`var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))`}}),i=t?.launcher??{},a=i.headerIconSize??`40px`,o=i.closeButtonPlacement??`inline`,s=i.headerIconHidden??!1,c=i.headerIconName,l=B(`div`,{className:`persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl`,style:{height:a,width:a,backgroundColor:`var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))`,color:`var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))`}});if(!s){if(c){let e=parseFloat(a)||24,n=P(c,e*.6,`currentColor`,1);n?(n.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,n.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,l.replaceChildren(n)):l.textContent=t?.launcher?.agentIconText??`💬`}else if(t?.launcher?.iconUrl){let e=z(`img`);e.src=t.launcher.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=a,e.style.width=a,l.replaceChildren(e)}else l.textContent=t?.launcher?.agentIconText??`💬`}let u=z(`div`,`persona-flex persona-flex-col persona-flex-1 persona-min-w-0`),d=B(`span`,{className:`persona-text-base persona-font-semibold`,text:t?.launcher?.title??`Chat Assistant`,style:{color:Kf.titleColor,...qf}}),f=B(`span`,{className:`persona-text-xs`,text:t?.launcher?.subtitle??`Here to help you get answers fast`,style:{color:Kf.subtitleColor,...Jf}});u.append(d,f),s?r.append(u):r.append(l,u);let p=i.clearChat??{},m=p.enabled??!0,h=p.placement??`inline`,g=null,_=null;if(m){let e=Gf(t,{wrapperClassName:h===`top-right`?`persona-absolute persona-top-4 persona-z-50`:`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`});g=e.button,_=e.wrapper,h===`top-right`&&(_.style.right=`48px`),h===`inline`&&r.appendChild(_)}let{button:v,wrapper:y}=Wf(t,{showClose:n,wrapperClassName:o===`top-right`?`persona-absolute persona-top-4 persona-right-4 persona-z-50`:m&&h===`inline`?`persona-relative persona-inline-flex persona-items-center persona-justify-center`:`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`});return o!==`top-right`&&r.appendChild(y),{header:r,iconHolder:l,headerTitle:d,headerSubtitle:f,closeButton:v,closeButtonWrapper:y,clearChatButton:g,clearChatButtonWrapper:_}},Xf=(e,t,n)=>{let r=n?.launcher??{},i=r.closeButtonPlacement??`inline`,a=r.clearChat?.placement??`inline`;e.appendChild(t.header),i===`top-right`&&(e.style.position=`relative`,e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a===`top-right`&&(e.style.position=`relative`,e.appendChild(t.clearChatButtonWrapper))};V(),F(),fn();function Zf(e){let{items:t,onSelect:n,anchor:r,position:i=`bottom-left`,portal:a,onOpenChange:o}=e,s=z(`div`,`persona-dropdown-menu persona-hidden`);s.setAttribute(`role`,`menu`),s.setAttribute(`data-persona-theme-zone`,`dropdown`),a?(s.style.position=`fixed`,s.style.zIndex=String(dn)):(s.style.position=`absolute`,s.style.top=`100%`,s.style.marginTop=`4px`,i===`bottom-right`?s.style.right=`0`:s.style.left=`0`);for(let e of t){if(e.dividerBefore){let e=document.createElement(`hr`);s.appendChild(e)}let t=document.createElement(`button`);if(t.type=`button`,t.setAttribute(`role`,`menuitem`),t.setAttribute(`data-dropdown-item-id`,e.id),e.destructive&&t.setAttribute(`data-destructive`,``),e.icon){let n=P(e.icon,16,`currentColor`,1.5);n&&t.appendChild(n)}let r=document.createElement(`span`);r.textContent=e.label,t.appendChild(r),t.addEventListener(`click`,t=>{t.stopPropagation(),d(),n(e.id)}),s.appendChild(t)}let c=null;function l(){if(!a)return;let e=r.getBoundingClientRect();s.style.top=`${e.bottom+4}px`,i===`bottom-right`?(s.style.right=`${window.innerWidth-e.right}px`,s.style.left=`auto`):(s.style.left=`${e.left}px`,s.style.right=`auto`)}function u(){let e=s.classList.contains(`persona-hidden`);l(),s.classList.remove(`persona-hidden`),e&&o?.(!0),requestAnimationFrame(()=>{let e=e=>{!s.contains(e.target)&&!r.contains(e.target)&&d()};document.addEventListener(`click`,e,!0),c=()=>document.removeEventListener(`click`,e,!0)})}function d(){let e=!s.classList.contains(`persona-hidden`);s.classList.add(`persona-hidden`),c?.(),c=null,e&&o?.(!1)}function f(){s.classList.contains(`persona-hidden`)?u():d()}function p(){d(),s.remove()}return a&&a.appendChild(s),{element:s,show:u,hide:d,toggle:f,destroy:p}}V(),F();function Qf(e){let{icon:t,label:n,size:r,strokeWidth:i,className:a,chromeless:o,onClick:s,aria:c}=e,l=z(`button`,$e(!o&&`persona-icon-btn`,a));l.type=`button`,l.setAttribute(`aria-label`,n),l.title=n;let u=P(t,r??16,`currentColor`,i??2);if(u&&l.appendChild(u),s&&l.addEventListener(`click`,s),c)for(let[e,t]of Object.entries(c))l.setAttribute(e,t);return l}function $f(e){let{icon:t,label:n,variant:r=`default`,size:i=`sm`,iconSize:a,className:o,onClick:s,aria:c}=e,l=`persona-label-btn`;r!=="default"&&(l+=` persona-label-btn--`+r),l+=` persona-label-btn--`+i,o&&(l+=` `+o);let u=z(`button`,l);if(u.type=`button`,u.setAttribute(`aria-label`,n),t){let e=P(t,a??14,`currentColor`,2);e&&u.appendChild(e)}let d=z(`span`);if(d.textContent=n,u.appendChild(d),s&&u.addEventListener(`click`,s),c)for(let[e,t]of Object.entries(c))u.setAttribute(e,t);return u}function ep(e){let{items:t,selectedId:n,onSelect:r,className:i}=e,a=z(`div`,`persona-toggle-group`+(i?` `+i:``));a.setAttribute(`role`,`group`);let o=n,s=[];function c(){for(let e of s)e.btn.setAttribute(`aria-pressed`,e.id===o?`true`:`false`)}for(let e of t){let t;e.icon?t=Qf({icon:e.icon,label:e.label,className:e.className,onClick:()=>{o=e.id,c(),r(e.id)}}):(t=z(`button`,`persona-icon-btn`+(e.className?` `+e.className:``)),t.type=`button`,t.setAttribute(`aria-label`,e.label),t.title=e.label,t.textContent=e.label,t.addEventListener(`click`,()=>{o=e.id,c(),r(e.id)})),t.setAttribute(`aria-pressed`,e.id===o?`true`:`false`),s.push({id:e.id,btn:t}),a.appendChild(t)}function l(e){o=e,c()}return{element:a,setSelected:l}}function tp(e){let{label:t,icon:n,iconSize:r,iconOnly:i,menuItems:a,onSelect:o,onPrimary:s,position:c=`bottom-left`,portal:l,chevronLabel:u=`More options`,chevronIconSize:d,className:f,primaryClassName:p,chevronClassName:m}=e,h=z(`div`,`persona-split-btn`+(f?` `+f:``)),g={label:t,className:`persona-split-btn-primary`+(p?` `+p:``),onClick:s},_=i&&n?Qf({...g,icon:n,size:r??14}):$f({...g,icon:n,iconSize:r??14}),v=Qf({icon:`chevron-down`,label:u,size:d??14,className:`persona-split-btn-chevron`+(m?` `+m:``),aria:{"aria-haspopup":`true`,"aria-expanded":`false`}});h.append(_,v);let y=null,b=()=>{if(y)return y;let e=(typeof l==`function`?l():l)??void 0;return y=Zf({items:a,onSelect:o,anchor:h,position:c,portal:e,onOpenChange:e=>{v.setAttribute(`aria-expanded`,e?`true`:`false`)}}),e||h.appendChild(y.element),y};return h.isConnected?b():requestAnimationFrame(()=>{y||b()}),v.addEventListener(`click`,e=>{e.stopPropagation(),b().toggle()}),{element:h,primaryButton:_,chevronButton:v,openMenu:()=>b().show(),closeMenu:()=>y?.hide(),toggleMenu:()=>b().toggle(),destroy:()=>{y?.destroy(),h.remove()}}}function np(e){let{label:t,icon:n=`chevron-down`,menuItems:r,onSelect:i,position:a=`bottom-left`,portal:o,className:s,hover:c}=e,l=z(`div`,`persona-combo-btn`+(s?` `+s:``));l.style.position=`relative`,l.style.display=`inline-flex`,l.style.alignItems=`center`,l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`),l.setAttribute(`aria-haspopup`,`true`),l.setAttribute(`aria-expanded`,`false`),l.setAttribute(`aria-label`,t);let u=z(`span`,`persona-combo-btn-label`);u.textContent=t,l.appendChild(u);let d=P(n,14,`currentColor`,2);d&&(d.style.marginLeft=`4px`,d.style.opacity=`0.6`,l.appendChild(d)),c&&(l.style.borderRadius=c.borderRadius??`10px`,l.style.padding=c.padding??`6px 4px 6px 12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=c.background??``,l.style.borderColor=c.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}));let f=Zf({items:r,onSelect:e=>{l.setAttribute(`aria-expanded`,`false`),i(e)},anchor:l,position:a,portal:o});o||l.appendChild(f.element);let p=()=>l.getAttribute(`data-persona-menu-locked`)===`true`;return l.addEventListener(`click`,e=>{if(e.stopPropagation(),p())return;let t=!f.element.classList.contains(`persona-hidden`);l.setAttribute(`aria-expanded`,t?`false`:`true`),f.toggle()}),l.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),l.click())}),{element:l,setLabel:e=>{u.textContent=e,l.setAttribute(`aria-label`,e)},open:()=>{l.setAttribute(`aria-expanded`,`true`),f.show()},close:()=>{l.setAttribute(`aria-expanded`,`false`),f.hide()},toggle:()=>{let e=!f.element.classList.contains(`persona-hidden`);l.setAttribute(`aria-expanded`,e?`false`:`true`),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}V(),Ao();const rp=e=>{let t=Yf({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let e=t.headerTitle.parentElement;e&&(e.style.cursor=`pointer`,e.setAttribute(`role`,`button`),e.setAttribute(`tabindex`,`0`),e.addEventListener(`click`,()=>n()),e.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n())}))}return t};function ip(e,t,n){if(t?.length)for(let r of t){let{button:t,wrapper:i}=Uf({ariaLabel:r.ariaLabel??r.label??r.id,iconName:r.icon,iconText:r.icon?void 0:r.label,tooltipHint:r.shortcut?To(r.shortcut):void 0,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`});if(t.setAttribute(`data-persona-header-action`,r.id),r.shortcut){let e=Eo(r.shortcut);e&&t.setAttribute(`aria-keyshortcuts`,e)}if(r.menuItems?.length){let e=Zf({items:r.menuItems,onSelect:e=>n?.(e),anchor:i,position:`bottom-right`});i.appendChild(e.element),t.addEventListener(`click`,t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener(`click`,()=>n?.(r.id));e.appendChild(i)}}const ap=e=>{let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:i,onHeaderAction:a}=e,o=t?.launcher??{},s=z(`div`,`persona-flex persona-items-center persona-justify-between`);s.setAttribute(`data-persona-theme-zone`,`header`),s.style.minHeight=Kf.minHeight,s.style.padding=`var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))`,s.style.backgroundColor=`var(--persona-header-bg, var(--persona-surface, #ffffff))`,s.style.borderBottomColor=`var(--persona-header-border, var(--persona-divider, #f1f5f9))`,s.style.boxShadow=`var(--persona-header-shadow, none)`,s.style.borderBottom=`var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))`;let c=i?.titleMenu,l,u;if(c){let e=np({label:o.title??`Chat Assistant`,menuItems:c.menuItems,onSelect:t=>{let n=n=>{n===!1&&e.element.dispatchEvent(new CustomEvent(`persona:title-menu-builtin`,{bubbles:!0,composed:!0,detail:{actionId:t}}))},r=c.onSelect(t);r instanceof Promise?r.then(n,()=>{}):n(r)},hover:c.hover,className:``});l=e.element,l.style.color=Kf.titleColor,u=l.querySelector(`.persona-combo-btn-label`)??l}else{if(l=z(`div`,`persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1`),u=z(`span`,`persona-text-base persona-font-semibold persona-truncate`),u.style.color=Kf.titleColor,Object.assign(u.style,qf),u.textContent=o.title??`Chat Assistant`,l.appendChild(u),i?.onTitleClick){l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`);let e=i.onTitleClick;l.addEventListener(`click`,t=>{t.target.closest(`button`)||e()}),l.addEventListener(`keydown`,t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e())})}let e=i?.titleRowHover;e&&(l.style.borderRadius=e.borderRadius??`10px`,l.style.padding=e.padding??`6px 4px 6px 12px`,l.style.margin=`-6px 0 -6px -12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.style.width=`fit-content`,l.style.flex=`none`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=e.background??``,l.style.borderColor=e.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}))}s.appendChild(l);let d=`persona-relative persona-inline-flex persona-items-center persona-justify-center`,{button:f,wrapper:p}=Wf(t,{showClose:n,wrapperClassName:d});r&&f.addEventListener(`click`,r);let m=z(`div`,`persona-flex persona-items-center persona-gap-1`);c||ip(m,i?.trailingActions,i?.onAction??a);let h=o.clearChat??{},g=null,_=null;if(h.enabled??!0){let e=h.placement??`inline`,n=Gf(t,{wrapperClassName:e===`top-right`?`persona-absolute persona-top-4 persona-z-50`:d});g=n.button,_=n.wrapper,e===`top-right`?_.style.right=`48px`:m.appendChild(_)}m.appendChild(p),s.appendChild(m);let v=z(`div`);v.style.display=`none`;let y=z(`span`);return y.style.display=`none`,{header:s,iconHolder:v,headerTitle:u,headerSubtitle:y,closeButton:f,closeButtonWrapper:p,clearChatButton:g,clearChatButtonWrapper:_}},op={default:rp,minimal:ap},sp=e=>op[e]??op.default,cp=(e,t,n)=>{if(t?.render){let r=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=z(`div`);i.style.display=`none`;let a=z(`span`),o=z(`span`),s=z(`button`);s.style.display=`none`;let c=z(`div`);return c.style.display=`none`,{header:r,iconHolder:i,headerTitle:a,headerSubtitle:o,closeButton:s,closeButtonWrapper:c,clearChatButton:null,clearChatButtonWrapper:null}}let r=t?.layout??`default`,i=sp(r)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(i.iconHolder.style.display=`none`),t.showTitle===!1&&(i.headerTitle.style.display=`none`),t.showSubtitle===!1&&(i.headerSubtitle.style.display=`none`),t.showCloseButton===!1&&(i.closeButton.style.display=`none`),t.showClearChat===!1&&i.clearChatButtonWrapper&&(i.clearChatButtonWrapper.style.display=`none`)),i};V(),fa();const lp=e=>{let{config:t}=e,n=B(`div`,{className:`persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4`,attrs:{"data-persona-theme-zone":`composer`}}),r=da(),i=B(`form`,{className:`persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3`,attrs:{"data-persona-composer-form":``}}),{textarea:a,attachAutoResize:o}=aa(t);o();let s=sa(t),c=ca(t),l=la(t),u=ua(t),d=B(`div`,{className:`persona-widget-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});i.append(d),l&&(l.previewsContainer.style.gap=`8px`,d.append(l.previewsContainer),i.append(l.input)),i.append(a);let f=B(`div`,{className:`persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full`,attrs:{"data-persona-composer-actions":``}}),p=B(`div`,{className:`persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-start":``}}),m=B(`div`,{className:`persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-end":``}});return l&&p.append(l.wrapper),c&&m.append(c.wrapper),m.append(s.wrapper),f.append(p,m),i.append(f),i.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),t?.statusIndicator?.mode===`transient`?n.append(r,u,i):n.append(r,i,u),{footer:n,suggestions:r,composerForm:i,header:d,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:u,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:f,leftActions:p,rightActions:m,setSendButtonMode:s.setMode}};V(),A(),fa(),ta();const up=()=>{let e=B(`button`,{className:`persona-pill-peek`,attrs:{type:`button`,"data-persona-pill-peek":``,"aria-label":`Show conversation`,tabindex:`-1`}}),t=z(`span`,`persona-pill-peek__icon`),n=k(f.MessageSquare,16,`currentColor`,1.5);n&&t.appendChild(n);let r=z(`span`,`persona-pill-peek__text`),i=z(`span`,`persona-pill-peek__caret`),a=k(f.ChevronUp,16,`currentColor`,1.5);return a&&i.appendChild(a),e.append(t,r,i),{root:e,textNode:r}},dp=e=>{let{config:t}=e,n=B(`div`,{className:`persona-widget-footer persona-widget-footer--pill`,attrs:{"data-persona-theme-zone":`composer`}}),r=da(),i=ua(t);i.style.display=`none`;let{textarea:a,attachAutoResize:o}=aa(t,{defaultMaxLines:5});o();let s=sa(t),c=ca(t),l=la(t);l&&l.previewsContainer.classList.add(`persona-pill-composer__previews`);let u=B(`form`,{className:`persona-widget-composer persona-pill-composer`,attrs:{"data-persona-composer-form":``}}),d=B(`div`,{className:`persona-widget-composer__left-actions persona-pill-composer__left`,attrs:{"data-persona-composer-actions-start":``}});l&&d.append(l.wrapper);let f=B(`div`,{className:`persona-widget-composer__right-actions persona-pill-composer__right`,attrs:{"data-persona-composer-actions-end":``}});c&&f.append(c.wrapper),f.append(s.wrapper),u.addEventListener(`click`,e=>{e.target!==s.button&&e.target!==s.wrapper&&e.target!==c?.button&&e.target!==c?.wrapper&&e.target!==l?.button&&e.target!==l?.wrapper&&a.focus()}),l&&u.append(l.input),u.append(d,a,f);let p=B(`div`,{className:`persona-pill-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});n.append(p),l&&p.append(l.previewsContainer),n.append(r,u,i);let m=u;return{footer:n,suggestions:r,composerForm:u,header:p,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:i,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:m,leftActions:d,rightActions:f,setSendButtonMode:s.setMode}};V(),wa(),F(),Wi();const fp=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}},pp=(e,t)=>{if(!e)return null;let n=fp(e);if(n===null)return null;let r=t?.[e];return(r===void 0?n:r)||null},mp=(e,t)=>{let n=z(`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},hp=e=>{let t=e.toLowerCase();return!t.startsWith(`data:image/svg+xml`)&&!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:image/`)||!e.includes(`:`))},gp=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(`:`))},_p=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`image`&&typeof e.image==`string`&&e.image.trim().length>0),vp=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`audio`&&typeof e.audio==`string`&&e.audio.trim().length>0),yp=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`video`&&typeof e.video==`string`&&e.video.trim().length>0),bp=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`file`&&typeof e.data==`string`&&e.data.trim().length>0),xp=e=>{if(!e||e.length===0)return null;let t=B(`div`,{className:`persona-mention-context-row persona-message-mentions`,attrs:{"data-message-mentions":``}});t.style.display=`flex`;for(let n of e){let e=B(`div`,{className:`persona-mention-chip persona-mention-chip-readonly`,attrs:{"data-status":`ready`,title:n.label}}),r=z(`span`,`persona-mention-chip-icon`),i=P(n.iconName??`at-sign`,13,`currentColor`,2);i&&r.appendChild(i),e.appendChild(r),e.appendChild(B(`span`,{className:`persona-mention-chip-label`,text:n.label})),t.appendChild(e)}return t},Sp=(e,t)=>{let n=document.createDocumentFragment();for(let r of e)r.kind===`text`?n.appendChild(document.createTextNode(r.text)):n.appendChild(Ca(r.ref,{readonly:!0,render:t}));return n},Cp=(e,t,n,r)=>{let i=Math.random().toString(36).slice(2,8),a=e=>`${i}:${e}`,o=n(t.map((e,t)=>e.kind===`text`?e.text:a(t)).join(``));if(!t.every((e,t)=>e.kind===`text`||o.includes(a(t)))){e.replaceChildren(Sp(t,r));return}e.innerHTML=o;let s=RegExp(`${i}:(\\d+)`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),l=[];for(let e=c.nextNode();e;e=c.nextNode())l.push(e);for(let e of l){let n=e;for(let e=s.exec(n.data);e;e=s.exec(n.data)){let i=t[Number(e[1])],a=n.splitText(e.index);a.data=a.data.slice(e[0].length),i?.kind===`mention`&&a.parentNode?.insertBefore(Ca(i.ref,{readonly:!0,render:r}),a),n=a}}},wp=(e,t,n)=>{if(e.length===0)return null;try{let r=z(`div`,`persona-flex persona-flex-col persona-gap-2`);r.setAttribute(`data-message-attachments`,`images`),t&&(r.style.marginBottom=`8px`);let i=0,a=!1,o=()=>{a||(a=!0,r.remove(),n?.())};return e.forEach((e,t)=>{let n=z(`img`);n.alt=e.alt?.trim()||`Attached image ${t+1}`,n.loading=`lazy`,n.decoding=`async`,n.referrerPolicy=`no-referrer`,n.style.display=`block`,n.style.width=`100%`,n.style.maxWidth=`320px`,n.style.maxHeight=`320px`,n.style.height=`auto`,n.style.objectFit=`contain`,n.style.borderRadius=`10px`,n.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,n.style.border=`1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))`;let a=!1;i+=1,n.addEventListener(`error`,()=>{a||(a=!0,i=Math.max(0,i-1),n.remove(),i===0&&o())}),n.addEventListener(`load`,()=>{a=!0}),hp(e.image)?(n.src=e.image,r.appendChild(n)):(a=!0,i=Math.max(0,i-1),n.remove())}),i===0?(o(),null):r}catch{return n?.(),null}},Tp=e=>{if(e.length===0)return null;try{let t=z(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`audio`);let n=0;return e.forEach(e=>{if(!gp(e.audio))return;let r=z(`audio`);r.controls=!0,r.preload=`metadata`,r.src=e.audio,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ep=e=>{if(e.length===0)return null;try{let t=z(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`video`);let n=0;return e.forEach(e=>{if(!gp(e.video))return;let r=z(`video`);r.controls=!0,r.preload=`metadata`,r.src=e.video,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,r.style.maxHeight=`320px`,r.style.borderRadius=`10px`,r.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Dp=e=>{if(e.length===0)return null;try{let t=z(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`files`);let n=0;return e.forEach(e=>{if(!gp(e.data))return;let r=z(`a`);r.href=e.data,r.download=e.filename,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=e.filename,r.className=`persona-message-file-attachment`,r.style.display=`inline-flex`,r.style.alignItems=`center`,r.style.gap=`6px`,r.style.padding=`6px 10px`,r.style.borderRadius=`8px`,r.style.fontSize=`0.875rem`,r.style.textDecoration=`underline`,r.style.backgroundColor=`var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))`,r.style.border=`1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))`,r.style.color=`inherit`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Op=()=>{let e=document.createElement(`div`);e.className=`persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2`;let t=document.createElement(`div`);t.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,t.style.backgroundColor=`currentColor`,t.style.opacity=`0.4`,t.style.animationDelay=`0ms`;let n=document.createElement(`div`);n.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,n.style.backgroundColor=`currentColor`,n.style.opacity=`0.4`,n.style.animationDelay=`250ms`;let r=document.createElement(`div`);r.className=`persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5`,r.style.backgroundColor=`currentColor`,r.style.opacity=`0.4`,r.style.animationDelay=`500ms`;let i=document.createElement(`span`);return i.className=`persona-sr-only`,i.textContent=`Loading`,e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(i),e},kp=(e,t,n)=>{let r={config:n??{},streaming:!0,location:e,defaultRenderer:Op};if(t){let e=t(r);if(e!==null)return e}return Op()},Ap=(e,t)=>{let n=z(`div`,`persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm`),r=t===`user`?e.userAvatar:e.assistantAvatar;if(r){if(r.startsWith(`http`)||r.startsWith(`/`)||r.startsWith(`data:`)){let e=z(`img`);e.src=r,e.alt=t===`user`?`User`:`Assistant`,e.className=`persona-w-full persona-h-full persona-rounded-full persona-object-cover`,n.appendChild(e)}else n.textContent=r,n.classList.add(t===`user`?`persona-bg-persona-accent`:`persona-bg-persona-primary`,`persona-text-white`)}else n.textContent=t===`user`?`U`:`A`,n.classList.add(t===`user`?`persona-bg-persona-accent`:`persona-bg-persona-primary`,`persona-text-white`);return n},jp=(e,t,n=`div`)=>{let r=z(n,`persona-text-xs persona-text-persona-muted`),i=new Date(e.createdAt);return r.textContent=t.format?t.format(i):i.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`}),r},Mp=(e,t=`bubble`)=>{let n=[`persona-message-bubble`];switch(t){case`flat`:e===`user`?n.push(`persona-message-user-bubble`,`persona-ml-auto`,`persona-text-persona-primary`,`persona-py-2`):n.push(`persona-message-assistant-bubble`,`persona-text-persona-text`,`persona-py-2`);break;case`minimal`:n.push(`persona-text-sm`,`persona-leading-relaxed`),e===`user`?n.push(`persona-message-user-bubble`,`persona-ml-auto`,`persona-bg-persona-accent`,`persona-text-white`,`persona-px-3`,`persona-py-2`,`persona-rounded-lg`):n.push(`persona-message-assistant-bubble`,`persona-bg-persona-container`,`persona-text-persona-text`,`persona-px-3`,`persona-py-2`,`persona-rounded-lg`);break;default:n.push(`persona-rounded-2xl`,`persona-text-sm`,`persona-leading-relaxed`,`persona-shadow-sm`),e===`user`?n.push(`persona-message-user-bubble`,`persona-ml-auto`,`persona-bg-persona-accent`,`persona-text-white`,`persona-px-5`,`persona-py-3`):n.push(`persona-message-assistant-bubble`,`persona-bg-persona-container`,`persona-border`,`persona-border-persona-message-border`,`persona-text-persona-text`,`persona-px-5`,`persona-py-3`)}return n},Np={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`}},Pp=(e,t,n=`bubble`,r)=>{if(!r)return;let i=t===`user`?`user`:`assistant`,a=Np[n??`bubble`]??Np.bubble;r.padding&&(e.style.padding=`var(--persona-message-${i}-padding, ${a.padding})`),r.fontSize&&(e.style.fontSize=`var(--persona-message-${i}-font-size, ${a.fontSize})`),r.lineHeight&&(e.style.lineHeight=`var(--persona-message-${i}-line-height, ${a.lineHeight})`),r.fontFamily&&(e.style.fontFamily=`var(--persona-message-${i}-font-family, inherit)`)},Fp=e=>`custom:${e}`,Ip=(e,t)=>t!==`user`&&t!==`assistant`?[]:(e?.custom??[]).filter(e=>(e.roles??[`assistant`]).includes(t)),Lp=(e,t,n,r)=>{let i=t.showCopy??!0,a=t.showUpvote??!1,o=t.showDownvote??!1,s=t.showReadAloud??!1,c=(t.showRegenerate??!1)&&r?.canRegenerate===!0,l=(t.showEdit??!1)&&r?.canEdit===!0,u=(t.showQuote??!1)&&r?.canQuote!==!1,d=Ip(t,e.role);if(!i&&!a&&!o&&!s&&!c&&!l&&!u&&d.length===0){let t=z(`div`);return t.style.display=`none`,t.id=`actions-${e.id}`,t.setAttribute(`data-actions-for`,e.id),t}let f=t.visibility??`hover`,p=t.align??`right`,m=t.layout??`pill-inside`,h={left:`persona-message-actions-left`,center:`persona-message-actions-center`,right:`persona-message-actions-right`}[p],g={"pill-inside":`persona-message-actions-pill`,"row-inside":`persona-message-actions-row`}[m],_=z(`div`,`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${h} ${g} ${f===`hover`?`persona-message-actions-hover`:``}`);_.id=`actions-${e.id}`,_.setAttribute(`data-actions-for`,e.id);let v=(e,t,n)=>{let r=Qf({icon:e,label:t,size:14,className:`persona-message-action-btn`,chromeless:!0});return r.setAttribute(`data-action`,n),r};i&&_.appendChild(v(`copy`,`Copy message`,`copy`)),s&&_.appendChild(v(`volume-2`,`Read aloud`,`read-aloud`)),a&&_.appendChild(v(`thumbs-up`,`Upvote`,`upvote`)),o&&_.appendChild(v(`thumbs-down`,`Downvote`,`downvote`)),c&&_.appendChild(v(`refresh-cw`,`Regenerate response`,`regenerate`)),l&&_.appendChild(v(`pencil`,`Edit message`,`edit`)),u&&_.appendChild(v(`quote`,`Quote message`,`quote`));for(let e of d)_.appendChild(v(e.iconName??`ellipsis`,e.label,Fp(e.id)));return _},Rp=(e,t,n,r,i,a)=>{let o=n??{},s=o.layout??`bubble`,c=o.avatar,l=o.timestamp,u=c?.show??!1,d=l?.show??!1,f=c?.position??`left`,p=l?.position??`below`,m=Mp(e.role,s),h=z(`div`,m.join(` `));h.id=`bubble-${e.id}`,h.setAttribute(`data-message-id`,e.id),h.setAttribute(`data-persona-theme-zone`,e.role===`user`?`user-message`:`assistant-message`);let g=Ju(a?.widgetConfig?.future).components.message,_=a?.widgetConfig?.theme?.components?.message;Pp(h,e.role,s,e.role===`user`?{...g.user,..._?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...g.assistant,..._?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),s===`flat`?(h.style.backgroundColor=`transparent`,h.style.color=e.role===`user`?`var(--persona-primary, var(--persona-text))`:`var(--persona-message-assistant-text, var(--persona-text))`):e.role===`user`?(h.style.backgroundColor=`var(--persona-message-user-bg, var(--persona-accent))`,h.style.color=`var(--persona-message-user-text, white)`):e.role===`assistant`&&(h.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,h.style.color=`var(--persona-message-assistant-text, var(--persona-text))`);let v=_p(e),y=e.content?.trim()??``,b=v.length>0&&y===`[Image]`,x=Xd(a?.widgetConfig?.features?.streamAnimation),S=a?.widgetConfig?.features?.streamAnimation?.plugins,C=e.role===`assistant`&&x.type!==`none`?rf(x.type,S):null,w=e.role===`assistant`&&C?.isAnimating?.(e)===!0,T=e.role===`assistant`&&C!==null&&(!!e.streaming||w);T&&C?.bubbleClass&&h.classList.add(C.bubbleClass);let E=document.createElement(`div`);E.classList.add(`persona-message-content`),e.streaming&&E.classList.add(`persona-content-streaming`),T&&C&&(C.containerClass&&E.classList.add(C.containerClass),E.style.setProperty(`--persona-stream-step`,`${x.speed}ms`),E.style.setProperty(`--persona-stream-duration`,`${x.duration}ms`));let D=T?af(e.content??``,x.buffer,C,e,!!e.streaming):e.content??``,O=()=>{let n=t({text:D,message:e,streaming:!!e.streaming,raw:e.rawContent});return T&&C?.wrap===`char`?ff(n,`char`,e.id,{skipTags:C.skipTags}):T&&C?.wrap===`word`?ff(n,`word`,e.id,{skipTags:C.skipTags}):n},ee=null;if(b?(ee=document.createElement(`div`),ee.innerHTML=O(),ee.style.display=`none`,E.appendChild(ee)):e.contentSegments?.length?Cp(E,e.contentSegments,n=>t({text:n,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):E.innerHTML=O(),T&&C?.useCaret&&!b&&y){let e=pf(),t=E.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];if(n?.parentNode)n.parentNode.insertBefore(e,n.nextSibling);else{let t=E.lastElementChild;t?t.appendChild(e):E.appendChild(e)}}if(d&&p===`inline`&&e.createdAt){let t=jp(e,l,`span`);t.classList.add(`persona-timestamp-inline`);let n=E.lastElementChild;n?n.appendChild(t):E.appendChild(t)}if(v.length>0){let e=wp(v,!b&&!!y,()=>{b&&ee&&(ee.style.display=``)});e?h.appendChild(e):b&&ee&&(ee.style.display=``)}let k=vp(e);if(k.length>0){let e=Tp(k);e&&h.appendChild(e)}let A=yp(e);if(A.length>0){let e=Ep(A);e&&h.appendChild(e)}let te=bp(e);if(te.length>0){let e=Dp(te);e&&h.appendChild(e)}let ne=e.contentSegments?.length?null:xp(e.contextMentions);if(ne&&h.appendChild(ne),h.appendChild(E),d&&p===`below`&&e.createdAt){let t=jp(e,l);t.classList.add(`persona-mt-1`),h.appendChild(t)}let re=e.role===`assistant`?pp(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role===`assistant`){let e=!!(D&&D.trim()),t=x.placeholder===`skeleton`,n=t&&x.buffer===`line`&&e;if(e)n&&h.appendChild(mf());else if(t)h.appendChild(mf());else{let e=kp(`inline`,a?.loadingIndicatorRenderer,a?.widgetConfig);e&&h.appendChild(e)}}re&&e.stopReason&&!e.streaming&&(y||(E.style.display=`none`),h.appendChild(mp(e.stopReason,re)));let ie=e.role===`assistant`&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&r?.enabled!==!1,ae=a?.actionEligibility,j=e.role===`user`&&!e.streaming&&r?.enabled!==!1&&(r?.showEdit===!0&&ae?.canEdit===!0||r?.showQuote===!0&&ae?.canQuote===!0||Ip(r,`user`).length>0);if((ie||j)&&r){let t=Lp(e,j?{...r,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:r,i,ae);h.appendChild(t)}if(!u||e.role===`system`)return h;let M=z(`div`,`persona-message-with-avatar persona-flex persona-gap-2 ${e.role===`user`?`persona-flex-row-reverse`:``}`),N=Ap(c,e.role);return f===`right`||f===`left`&&e.role===`user`?M.append(h,N):M.append(N,h),M},zp=(e,t,n,r,i,a)=>{let o=n??{};return e.role===`user`&&o.renderUserMessage?o.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role===`assistant`&&o.renderAssistantMessage?o.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Rp(e,t,n,r,i,a)};V(),F();const Bp=(e,t)=>{if(e.replaceChildren(),!t)e.hidden=!0;else if(typeof t==`function`){let n=null;try{n=t()}catch(e){console.warn(`[persona] welcome.icon renderer threw`,e)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1}else{if(t.type===`lucide`){let n=P(t.name,40);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type===`image`?e.appendChild(B(`img`,{className:`persona-welcome-icon-image`,attrs:{src:t.url,alt:t.alt}})):e.appendChild(B(`span`,{className:`persona-welcome-icon-text`,text:t.text}));e.hidden=!1}},Vp=(e,t,n={})=>{let r=B(`div`,{className:`persona-welcome-icon`,attrs:{"data-persona-welcome-icon":``}});r.hidden=!0;let i=z(`p`,`persona-welcome-kicker`);i.hidden=!0;let a=z(`h2`,`persona-welcome-title`),o=z(`p`,`persona-welcome-subtitle`),s=B(`div`,{className:`persona-welcome-head-text`},i,a),c=B(`div`,{className:`persona-welcome-title-row`},r,s);return{host:B(`div`,{className:`persona-welcome persona-rounded-2xl`,attrs:{"data-persona-welcome":``,"data-persona-intro-card":``,"data-persona-welcome-variant":`card`},style:{background:`var(--persona-intro-card-bg, transparent)`,boxShadow:n.flatShadow?`none`:`var(--persona-intro-card-shadow, none)`,border:`var(--persona-intro-card-border, none)`}},c,o,t),iconHolder:r,kicker:i,title:a,subtitle:o,starterSuggestions:t}},Hp=(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)},Up=(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===``,Bp(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`)},Wp=`data-persona-welcome-overlay`,Gp=`persona-welcome-overlay-active`,Kp=/* @__PURE__ */ new WeakMap,qp=(e,t,n)=>{n.setAttribute(`data-persona-welcome-plugin`,``),t.appendChild(n),t.setAttribute(`data-persona-welcome-content`,`plugin`),t.setAttribute(Wp,``),e.classList.contains(Gp)||(Kp.set(e,e.scrollTop),e.classList.add(Gp),e.scrollTop=0)},Jp=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute(`data-persona-welcome-content`),t.removeAttribute(Wp),e.classList.contains(Gp)&&(e.classList.remove(Gp),e.scrollTop=Kp.get(e)??e.scrollTop,Kp.delete(e))},Yp=()=>{let e=B(`div`,{className:`persona-welcome-greeting persona-flex persona-flex-col`,attrs:{"data-persona-welcome-greeting":``}});return e.hidden=!0,e},Xp=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let r=n?.layout?.messages?.layout??`bubble`,i=B(`div`,{className:Mp(`assistant`,r).join(` `),attrs:{"data-persona-theme-zone":`assistant-message`},text:t,style:r===`flat`?{backgroundColor:`transparent`,color:`var(--persona-message-assistant-text, var(--persona-text))`}:{backgroundColor:`var(--persona-message-assistant-bg, var(--persona-container))`,color:`var(--persona-message-assistant-text, var(--persona-text))`}});e.appendChild(B(`div`,{className:`persona-flex`},i)),e.hidden=!1},Zp=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,Qp=(e,t)=>{if(Zp()||typeof e.animate!=`function`||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),r=e.parentElement,i=0,a=0,o=0;if(r){let t=getComputedStyle(r);i=parseFloat(t.rowGap)||0;let s=e.previousElementSibling,c=e.nextElementSibling,l=r.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-r.scrollTop;a=Math.max(0,s?n.top-s.getBoundingClientRect().bottom-i:n.top-l),o=Math.max(0,c?c.getBoundingClientRect().top-n.bottom-i:0)}let s=e.style.overflow;e.style.overflow=`hidden`;let c=getComputedStyle(e),l=parseFloat(c.paddingTop)||0,u=parseFloat(c.paddingBottom)||0,d=e.animate([{opacity:`1`,transform:`none`,height:`${n.height}px`,minHeight:`0px`,paddingTop:`${l}px`,paddingBottom:`${u}px`,marginTop:`${a}px`,marginBottom:`${o}px`},{opacity:`0`,transform:`translateY(-4px)`,height:`0px`,minHeight:`0px`,paddingTop:`0px`,paddingBottom:`0px`,marginTop:`0px`,marginBottom:`${-i}px`}],{duration:180,easing:`ease-out`,fill:`forwards`}),f=!1,p=()=>{f||(f=!0,e.style.overflow=s,t(d))};return d.finished.then(p).catch(p),d},$p=(e,t,n,r=260)=>{if(t<=1||Zp()||typeof e.animate!=`function`||!e.isConnected)return null;let i=n===`drop`?-t:t;return e.animate([{transform:`translateY(${i}px)`},{transform:`none`}],{duration:r,easing:`cubic-bezier(0.2, 0, 0, 1)`,fill:`none`})},em=/* @__PURE__ */ new WeakSet,tm=(e,t)=>!!e&&e[t]!==void 0,nm=(e,t)=>{e&&e.debug===!0&&t.length&&(em.has(e)||(em.add(e),t.forEach(e=>console.warn(`[persona] ${e}`))))},rm=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!==`docked`)=>{let n=e?.welcome,r=e?.copy,i=e?.future?.v5Defaults===!0,a=n?.layout??(i?`centered`:`top`),o=tm(n,`variant`)?n.variant:r?.showWelcomeCard===!1?`none`:`card`,s=o===`hero`&&!i&&n?.layout===void 0?`on-first-message`:tm(n,`dismiss`)?n.dismiss:i||o===`hero`?`on-first-message`:`never`,c=[];tm(n,`title`)&&tm(r,`welcomeTitle`)&&c.push(`welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated.`),tm(n,`subtitle`)&&tm(r,`welcomeSubtitle`)&&c.push(`welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated.`),tm(n,`variant`)&&tm(r,`showWelcomeCard`)&&c.push(`welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated.`),o===`hero`&&tm(n,`message`)&&c.push(`welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.`),!i&&n?.layout===void 0&&o===`hero`&&tm(n,`dismiss`)&&n.dismiss!==`on-first-message`&&c.push(`welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".`);let l=n?.anchor??(a===`centered`&&t?`center`:`bottom`),u=Od(n?.anchorComposerTop)!==null;return tm(n,`anchorComposerTop`)&&!u&&c.push(`welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".`),l!==`center`&&(tm(n,`anchorComposerTop`)||tm(n,`composerGap`))&&c.push(`welcome.anchorComposerTop is ignored unless welcome.anchor is "center".`),nm(e,c),{title:tm(n,`title`)?n.title:r?.welcomeTitle??(i?`What can I help with?`:`Hello 👋`),kicker:n?.kicker??``,subtitle:tm(n,`subtitle`)?n.subtitle:r?.welcomeSubtitle??(i?``:`I can answer questions and help you get things done here.`),icon:n?.icon,align:n?.align===`start`||n?.align===`center`?n.align:a===`centered`?`center`:void 0,iconPlacement:n?.icon&&typeof n.icon!=`function`&&n.icon.placement===`inline`?`inline`:`above`,variant:o,dismiss:s,message:o===`hero`?void 0:n?.message,layout:a,anchor:l,anchorComposerTop:u?n.anchorComposerTop:`44%`,composerGap:n?.composerGap?.trim()||`24px`}},im=e=>(e??[]).some(e=>e.role===`user`)?`active`:`empty`,am=(e,t)=>e.variant===`none`?!1:e.dismiss===`never`||!(t??[]).some(e=>e.role===`user`);V(),fn(),li();const om=`var(--persona-components-panel-height)`,sm=e=>{let t=ai(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,r=e?.launcher?.heightOffset??0,i=r===0?`max(200px, ${om})`:`max(200px, calc(${om} - ${r}px))`;return{width:n??`var(--persona-components-panel-width)`,maxWidth:n??`var(--persona-components-panel-maxWidth)`,height:i,maxHeight:`var(--persona-components-panel-maxHeight)`}},cm=`16px`,lm=`10px`,um=`14px`,dm=e=>{let t=e?.launcher?.enabled??!0,n=kf(e);if(Af(e)){let t=e?.launcher?.composerBar??{},n=z(`div`,`persona-widget-wrapper persona-fixed persona-transition`);n.setAttribute(`data-persona-composer-bar`,``),n.dataset.state=`collapsed`,n.dataset.expandedSize=t.expandedSize??`anchored`,n.style.zIndex=String(e?.launcher?.zIndex??1e5);let r=z(`div`,`persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);r.style.width=`100%`,n.appendChild(r);let i=z(`div`,`persona-widget-pill-root`);return i.setAttribute(`data-persona-composer-bar`,``),i.dataset.state=`collapsed`,i.dataset.expandedSize=t.expandedSize??`anchored`,i.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:n,panel:r,pillRoot:i}}if(n){let e=z(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`),t=z(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);return e.appendChild(t),{wrapper:e,panel:t}}if(!t){let t=z(`div`,`persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0`),n=z(`div`,`persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0`),r=ai(e),i=r.launcherWidth||r.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?sm(e).width:`100%`;return t.style.width=i,n.style.width=`100%`,t.appendChild(n),{wrapper:t,panel:n}}let r=e?.launcher??{},i=r.position&&zf[r.position]?zf[r.position]:zf[`bottom-right`],a=z(`div`,`persona-widget-wrapper persona-fixed ${i} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let o=z(`div`,`persona-widget-panel persona-relative persona-min-h-[320px]`),s=sm(e);return o.style.width=s.width,o.style.maxWidth=s.maxWidth,a.appendChild(o),{wrapper:a,panel:o}},fm=e=>{let t=B(`div`,{className:`persona-suggestions`,attrs:{"data-persona-suggestions":Mf(e)}});return t.hidden=!0,t},pm=(e,t)=>{let n=fm(`starter`),r=Vp(e,n,{flatShadow:kf(e)}),i=rm(e);Up(r,i),Hp(t,r.host,am(i,e?.initialMessages));let a=Yp();return Xp(a,i.message,e),{welcome:r,greetingHost:a}},mm=(e,t)=>{let n=z(`div`,`persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary`);n.setAttribute(`data-persona-theme-zone`,`container`);let{button:r,wrapper:i}=Wf(e,{showClose:t,wrapperClassName:`persona-composer-bar-close`,buttonSize:cm,iconSize:lm});i.style.position=`absolute`,i.style.top=`8px`,i.style.right=`8px`,i.style.zIndex=`10`;let a=e?.launcher?.clearChat?.enabled??!0,o=null,s=null;if(a){let t=Gf(e,{wrapperClassName:`persona-composer-bar-clear-chat`,buttonSize:cm,iconSize:um});o=t.button,s=t.wrapper,s.style.position=`absolute`,s.style.top=`8px`,s.style.right=`32px`,s.style.zIndex=`10`}let c=B(`span`,{className:`persona-widget-header`,attrs:{"data-persona-theme-zone":`header`},style:{display:`none`}}),l=B(`div`,{className:`persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6`,attrs:{id:`persona-scroll-container`,"data-persona-theme-zone":`messages`},style:{paddingTop:`48px`}});l.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:u,greetingHost:d}=pm(e,l),{host:f,title:p,subtitle:m}=u,h=u.starterSuggestions,g=z(`div`,`persona-widget-messages persona-flex persona-flex-col`);g.style.gap=`var(--persona-components-message-gap, 12px)`;let _=fm(`followUp`),v=Ed(e,!0);v&&(g.style.maxWidth=v,g.style.marginLeft=`auto`,g.style.marginRight=`auto`,g.style.width=`100%`),l.append(f,d,g,_);let y=B(`div`,{className:`persona-composer-overlay persona-pointer-events-none`,attrs:{"data-persona-composer-overlay":``},style:{position:`absolute`,left:`0`,right:`0`,bottom:`calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))`,zIndex:`20`}}),b=dp({config:e}),{root:x,textNode:S}=up();return n.append(c,i,l,y),s&&n.appendChild(s),{container:n,body:l,messagesWrapper:g,starterSuggestions:h,transcriptSuggestions:_,composerOverlay:y,suggestions:b.suggestions,textarea:b.textarea,sendButton:b.sendButton,sendButtonWrapper:b.sendButtonWrapper,micButton:b.micButton,micButtonWrapper:b.micButtonWrapper,composerForm:b.composerForm,statusText:b.statusText,welcomeHost:f,welcomeIconHolder:u.iconHolder,greetingHost:d,introKicker:u.kicker,introTitle:p,introSubtitle:m,closeButton:r,closeButtonWrapper:i,clearChatButton:o,clearChatButtonWrapper:s,iconHolder:z(`span`),headerTitle:z(`span`),headerSubtitle:z(`span`),header:c,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:x,peekTextNode:S}},hm=(e,t=!0)=>{if(Af(e))return mm(e,t);let n=B(`div`,{className:`persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border`,attrs:{"data-persona-theme-zone":`container`}}),r=e?.layout?.header,i=e?.layout?.showHeader!==!1,a=r?cp(e,r,{showClose:t}):Yf({config:e,showClose:t}),o=B(`div`,{className:`persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6`,attrs:{id:`persona-scroll-container`,"data-persona-theme-zone":`messages`}});o.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:s,greetingHost:c}=pm(e,o),{host:l,title:u,subtitle:d}=s,f=s.starterSuggestions,p=z(`div`,`persona-widget-messages persona-flex persona-flex-col`);p.style.gap=`var(--persona-components-message-gap, 12px)`;let m=fm(`followUp`),h=Ed(e,!1);h&&(p.style.maxWidth=h,p.style.marginLeft=`auto`,p.style.marginRight=`auto`,p.style.width=`100%`),o.append(l,c,p,m);let g=lp({config:e}),_=e?.layout?.showFooter!==!1;i||(a.header.style.display=`none`),Xf(n,a,e),n.append(o);let v=B(`div`,{className:`persona-composer-overlay persona-pointer-events-none`,attrs:{"data-persona-composer-overlay":``},style:{position:`absolute`,left:`0`,right:`0`,bottom:`calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))`,zIndex:`20`}});return _||(g.footer.style.display=`none`),n.append(g.footer),n.append(v),{container:n,body:o,messagesWrapper:p,starterSuggestions:f,transcriptSuggestions:m,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,welcomeHost:l,welcomeIconHolder:s.iconHolder,greetingHost:c,introKicker:s.kicker,introTitle:u,introSubtitle:d,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};V(),F(),fn();const gm=(e,t)=>{let n=z(`button`);n.type=`button`,n.innerHTML=`
25
25
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">💬</span>
26
26
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
27
27
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -29,15 +29,15 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
29
29
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
30
30
  </span>
31
31
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">↗</span>
32
- `,n.addEventListener(`click`,t);let r=e=>{let t=e.launcher??{},r=Cf(e),i=Cu(e)===`circle`;i?(n.dataset.personaLauncherVariant=`circle`,n.setAttribute(`aria-label`,t.title??`Open chat`)):(n.removeAttribute(`data-persona-launcher-variant`),n.removeAttribute(`aria-label`));let a=n.querySelector(`[data-role='launcher-title']`);if(a){let e=t.title??`Chat Assistant`;a.textContent=e,a.setAttribute(`title`,e)}let o=n.querySelector(`[data-role='launcher-subtitle']`);if(o){let e=t.subtitle??`Here to help you get answers fast`;o.textContent=e,o.setAttribute(`title`,e)}let s=n.querySelector(`.persona-flex-col`);s&&(t.textHidden||r||i?s.style.display=`none`:s.style.display=``);let c=n.querySelector(`[data-role='launcher-icon']`);if(c){if(t.agentIconHidden)c.style.display=`none`;else{let e=t.agentIconSize??`40px`;if(c.style.height=e,c.style.width=e,t.agentIconBackgroundColor?(c.style.backgroundColor=t.agentIconBackgroundColor,c.classList.remove(`persona-bg-persona-primary`)):(c.style.backgroundColor=``,c.classList.add(`persona-bg-persona-primary`)),c.innerHTML=``,t.agentIconName){let n=parseFloat(e)||24,r=F(t.agentIconName,n*.6,`var(--persona-text-inverse, #ffffff)`,1.5);r?(c.appendChild(r),c.style.display=``):(c.textContent=t.agentIconText??`💬`,c.style.display=``)}else t.iconUrl?c.style.display=`none`:(c.textContent=t.agentIconText??`💬`,c.style.display=``)}}let l=n.querySelector(`[data-role='launcher-image']`);if(l){let e=t.agentIconSize??`40px`;l.style.height=e,l.style.width=e,t.iconUrl&&!t.agentIconName&&!t.agentIconHidden?(l.src=t.iconUrl,l.style.display=`block`):l.style.display=`none`}let u=n.querySelector(`[data-role='launcher-call-to-action-icon']`);if(u){let e=t.callToActionIconSize??`32px`;u.style.height=e,u.style.width=e,t.callToActionIconBackgroundColor?(u.style.backgroundColor=t.callToActionIconBackgroundColor,u.classList.remove(`persona-bg-persona-primary`)):(u.style.backgroundColor=``,u.classList.add(`persona-bg-persona-primary`)),t.callToActionIconColor?(u.style.color=t.callToActionIconColor,u.classList.remove(`persona-text-persona-call-to-action`)):(u.style.color=``,u.classList.add(`persona-text-persona-call-to-action`));let n=0;if(t.callToActionIconPadding?(u.style.boxSizing=`border-box`,u.style.padding=t.callToActionIconPadding,n=(parseFloat(t.callToActionIconPadding)||0)*2):(u.style.boxSizing=``,u.style.padding=``),t.callToActionIconHidden||i)u.style.display=`none`;else if(u.style.display=r?`none`:``,u.innerHTML=``,t.callToActionIconName){let r=Math.max((parseFloat(e)||24)-n,8),i=F(t.callToActionIconName,r,`currentColor`,1.5);i?u.appendChild(i):u.textContent=t.callToActionIconText??`↗`}else u.textContent=t.callToActionIconText??`↗`}let d=t.position&&Nf[t.position]?Nf[t.position]:Nf[`bottom-right`];n.className=r?`persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer`:`persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer ${d}`,r||(n.style.zIndex=String(t.zIndex??1e5)),n.style.border=t.border??`1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))`,n.style.boxShadow=t.shadow===void 0?`var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))`:t.shadow.trim()===``?`none`:t.shadow,r?(n.style.width=`0`,n.style.minWidth=`0`,n.style.maxWidth=`0`,n.style.padding=`0`,n.style.overflow=`hidden`,n.style.border=`none`,n.style.boxShadow=`none`):(n.style.width=``,n.style.minWidth=``,n.style.maxWidth=t.collapsedMaxWidth??``,n.style.justifyContent=``,n.style.padding=``,n.style.overflow=``)};return e&&r(e),{element:n,update:r,destroy:()=>{n.removeEventListener(`click`,t),n.remove()}}},dm=/* @__PURE__ */ new Set,fm=e=>{let t=e?.persistState;return`${(typeof t==`object`?t?.keyPrefix:void 0)??`persona-`}teaser-dismissed`},pm=(e,t)=>{if(dm.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)===`1`}catch{return!1}},mm=(e,t)=>{if(dm.add(e),t)try{window.localStorage.setItem(e,`1`)}catch{}},hm=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,gm=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Cf(e??{})?null:t},_m=(e,t)=>{let n=B(`div`,`persona-launcher-surface`);n.setAttribute(`data-persona-launcher-surface`,`true`);let r=e??{},i=null,a=null,o=null,s=null,c=null,l=!1,u=!1,d=!1,f=!1,p=()=>(i?.frequency??`once`)===`once`&&r.persistState!==!1,m=()=>{c!==null&&(clearTimeout(c),c=null)},h=()=>{a&&l&&(l=!1,a.hidden=!0)},g=e=>{m(),d=!0,h(),mm(fm(r),e&&p())},_=e=>{i&&!d&&g(e===`user`&&l)},v=()=>{c=null,!(!a||d||f)&&(u=!0,l=!0,a.hidden=!1,!(hm()||typeof a.animate!=`function`)&&a.animate([{opacity:`0`,transform:`translateY(6px)`},{opacity:`1`,transform:`none`}],{duration:220,easing:`ease-out`,fill:`backwards`}))},y=()=>{i&&a&&(d||u||f||pm(fm(r),p())||(m(),c=setTimeout(v,Math.max(0,i.delayMs??0))))},b=()=>{g(p()),t()},x=e=>{e.stopPropagation(),g(p())},S=um(e,()=>{_(`user`),t()}),C=()=>{m(),s?.removeEventListener(`click`,b),o?.removeEventListener(`click`,x),a?.remove(),a=null,s=null,o=null,l=!1},w=()=>{s=V(`button`,{className:`persona-launcher-teaser-text`,attrs:{type:`button`}}),s.addEventListener(`click`,b),o=V(`button`,{className:`persona-launcher-teaser-dismiss`,attrs:{type:`button`},text:`×`}),o.addEventListener(`click`,x),a=V(`div`,{className:`persona-launcher-teaser`,attrs:{"data-persona-launcher-teaser":`true`,role:`status`,"aria-live":`polite`,hidden:``}},s,o),n.insertBefore(a,S.element)},T=()=>{let e=r.launcher?.position??`bottom-right`,t=Nf[e]??Nf[`bottom-right`];a?(n.className=Qe(`persona-launcher-surface`,t),n.setAttribute(`data-teaser`,e),n.style.zIndex=String(r.launcher?.zIndex??1e5),S.element.style.position=`static`):(n.className=`persona-launcher-surface`,n.removeAttribute(`data-teaser`),n.style.zIndex=``,S.element.style.position=``)},E=e=>{let t=gm(e);i=t,t?(a||w(),s.textContent=t.text,o.hidden=t.dismissible===!1,o.setAttribute(`aria-label`,t.dismissLabel??`Dismiss message`),y()):C()};return n.appendChild(S.element),e&&(E(e),T()),{element:n,launcher:S,get teaser(){return a?{element:a,show:v,dismiss:g}:null},setPanelOpen:(e,t=`user`)=>{f=e,e&&_(t)},update:e=>{r=e,S.update(e),E(e),T()},destroy:()=>{C(),S.destroy(),n.remove()}}},vm=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:i}=am(e),a=lm(e,t),o={wrapper:n,panel:r,pillRoot:i},s={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},l={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:o,panelElements:a,transcript:s,header:c,composer:l,replaceHeader:e=>(c.element.replaceWith(e.header),c.element=e.header,c.iconHolder=e.iconHolder,c.headerTitle=e.headerTitle,c.headerSubtitle=e.headerSubtitle,c.closeButton=e.closeButton,c.closeButtonWrapper=e.closeButtonWrapper,c.clearChatButton=e.clearChatButton,c.clearChatButtonWrapper=e.clearChatButtonWrapper,e),replaceComposer:e=>{l.footer.replaceWith(e),l.footer=e}}},ym=({config:e,plugins:t,onToggle:n})=>{let r=t.find(e=>e.renderLauncher);if(r?.renderLauncher){let t=r.renderLauncher({config:e,defaultRenderer:()=>um(e,n).element,onToggle:n});if(t)return{instance:null,element:t}}let i=_m(e,n);return{instance:i,element:i.element}},bm=e=>{let t=e?.persistState;return(typeof t==`object`?t?.keyPrefix:void 0)??`persona-`},xm=(e,t,n)=>`${bm(e)}plugin:${t}:${n}`,Sm=e=>{let t=/* @__PURE__ */ new Map,n=!1,r=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>`u`||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return i=>{let a=t=>xm(e(),i,t);return{get:e=>{let i=a(e),o=r();if(o)try{return o.getItem(i)}catch{n=!0}return t.get(i)??null},set:(e,i)=>{let o=a(e),s=r();if(s)try{s.setItem(o,i);return}catch{n=!0}t.set(o,i)},remove:e=>{let i=a(e);t.delete(i);let o=r();if(o)try{o.removeItem(i)}catch{n=!0}}}}};H();const Cm=(e,t,n)=>{let r=n;for(let n of t){let t=B(`span`,`persona-tool-char`);t.style.setProperty(`--char-index`,String(r)),t.textContent=n===` `?`\xA0`:n,e.appendChild(t),r++}return r};H(),I(),wi(),Ze();const wm=(e,t)=>{let n=e.reasoning?.chunks.join(``).trim()??``;return n?n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join(`
33
- `):``},Tm=(e,t,n)=>{os(e,t,{stateSet:n,previewKind:`reasoning`,iconColor:`currentColor`})},Em=(e,t,n=/* @__PURE__ */ new Set)=>{t=ss(t,`reasoning`);let r=e.reasoning,i=es(`persona-reasoning-bubble`,e.id);if(!r)return us(i,e,t,`reasoning`);let a=t?.features?.reasoningDisplay??{},o=a.expandable??vi.expandable,s=o&&n.has(e.id),c=r.status!==`complete`,l=wm(e,a.previewMaxLines??vi.previewMaxLines),u=ts({expandable:o,expanded:s,bubbleType:`reasoning`}),d=B(`div`,`persona-flex persona-flex-col persona-text-left`),f=B(`span`,`persona-text-xs persona-text-persona-primary`),p=cs(t,`reasoning`)===`row`,m=p&&!c?`Thought for ${ls(r.durationMs??(r.completedAt!==void 0&&r.startedAt!==void 0?r.completedAt-r.startedAt:void 0))}`:`Thinking...`,h=t?.reasoning??{},g=String(r.startedAt??Date.now()),_=()=>{let e=B(`span`,``);return e.setAttribute(`data-tool-elapsed`,g),e.textContent=Be(r),e},v=h.renderCollapsedSummary?.({message:e,reasoning:r,defaultSummary:m,previewText:l,isActive:c,config:t??{},elapsed:Be(r),createElapsedElement:_});typeof v==`string`&&v.trim()?(f.textContent=v,d.appendChild(f)):v instanceof HTMLElement?d.appendChild(v):(f.textContent=m,d.appendChild(f));let y=B(`span`,`persona-text-xs persona-text-persona-primary`);y.textContent=Pe(r),p||d.appendChild(y);let b=a.loadingAnimation??vi.loadingAnimation,x=h.activeTextTemplate,S=h.completeTextTemplate,C=c?x:S,w=v instanceof HTMLElement,T=(e,t)=>{f.textContent=``;let n=He(e,``),i=0;for(let e of n){let n=e.styles.length>0?(()=>{let t=B(`span`,e.styles.map(e=>`persona-tool-text-${e}`).join(` `));return f.appendChild(t),t})():f;if(e.isDuration&&c)n.appendChild(_());else{let a=e.isDuration?Be(r):e.text;t?i=Cm(n,a,i):n.appendChild(document.createTextNode(a))}}};if(!w&&C){if(y.style.display=`none`,f.style.display=``,c&&b!==`none`){let e=h.loadingAnimationDuration??2e3;f.setAttribute(`data-preserve-animation`,`true`),b===`pulse`?(f.classList.add(`persona-tool-loading-pulse`),f.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),T(C,!1)):(f.classList.add(`persona-tool-loading-${b}`),f.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),b===`shimmer-color`&&(h.loadingAnimationColor&&f.style.setProperty(`--persona-tool-anim-color`,h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&f.style.setProperty(`--persona-tool-anim-secondary-color`,h.loadingAnimationSecondaryColor)),T(C,!0))}else T(C,!1)}else if(!w&&c&&b!==`none`){f.style.display=``;let e=h.loadingAnimationDuration??2e3;if(f.setAttribute(`data-preserve-animation`,`true`),b===`pulse`)f.classList.add(`persona-tool-loading-pulse`),f.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`);else{f.classList.add(`persona-tool-loading-${b}`),f.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),b===`shimmer-color`&&(h.loadingAnimationColor&&f.style.setProperty(`--persona-tool-anim-color`,h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&f.style.setProperty(`--persona-tool-anim-secondary-color`,h.loadingAnimationSecondaryColor));let t=f.textContent||m;f.textContent=``,Cm(f,t,0)}r.status===`complete`&&!p&&(f.style.display=`none`)}else w||(r.status===`complete`&&!p?f.style.display=`none`:f.style.display=``);if(a.iconName&&!w){let e=B(`span`,`persona-reasoning-header-icon`),t=F(a.iconName,16,`currentColor`,2);t&&(e.appendChild(t),u.appendChild(e))}let E=`currentColor`,D=rs(u,d,{expandable:o,expanded:s,iconColor:E,metaGap:!1}),O=is({bubble:i,previewKind:`reasoning`,expanded:s,isActive:c,previewText:l,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:r,defaultPreview:l,isActive:c,config:t??{}})});if(!o)return i.append(u,O),us(i,e,t,`reasoning`);let ee=B(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3`);ee.style.display=s?``:`none`;let k=r.chunks.join(``),A=B(`div`,`persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted`);return A.textContent=k||(r.status===`complete`?`No additional context was shared.`:`Waiting for details…`),ee.appendChild(A),as({expanded:s,header:u,toggleIcon:D,content:ee,collapsedPreview:O,iconColor:E}),i.append(u,O,ee),us(i,e,t,`reasoning`)};H(),Ze(),I();const Dm=e=>{if(e==null)return!0;if(typeof e==`string`){if(!e.trim())return!0;try{return Dm(JSON.parse(e))}catch{return!1}}return typeof e==`object`&&Object.keys(e).length===0},Om=e=>{if(typeof e==`object`&&e)return!0;if(typeof e!=`string`)return!1;try{let t=JSON.parse(e);return typeof t==`object`&&!!t}catch{return!1}};function km(e,t,n){let r=t.toolCall;if(!r)return;let i=n.toolCall??{},a=(t,n)=>{let r=V(`section`,{className:`persona-tool-detail`,attrs:{"data-persona-tool-detail":t.toLowerCase()},style:{backgroundColor:i.codeBlockBackgroundColor,borderColor:i.codeBlockBorderColor,borderWidth:i.codeBlockBorderColor?`1px`:void 0}}),a=V(`div`,{className:`persona-tool-detail-label`,text:t,style:{color:i.labelTextColor}}),o=Me(n),s=V(`pre`,{className:`persona-tool-detail-value${Om(n)?` persona-tool-detail-code`:``}`,text:o,attrs:o.length>420||o.split(`
34
- `).length>7?{tabindex:`0`,"aria-label":`${t} content`}:{},style:{color:i.codeBlockTextColor??i.contentTextColor}}),c=V(`button`,{className:`persona-tool-detail-copy`,attrs:{type:`button`,"data-persona-copy-tool-detail":``,"aria-label":`Copy ${t.toLowerCase()}`,title:`Copy ${t.toLowerCase()}`}}),l=F(`copy`,14,`currentColor`,1.7);l&&c.appendChild(l),r.append(a,s,c),e.appendChild(r)};Dm(r.args)||a(`Request`,r.args);let o=r.status===`complete`&&r.result!==void 0?r.result:r.chunks?.join(``);o!==void 0&&(typeof o!=`string`||o.trim())&&a(`Response`,o),r.success===!1&&e.appendChild(V(`div`,{className:`persona-text-sm persona-whitespace-pre-wrap`,text:r.error||`Tool failed`,attrs:{"data-persona-tool-error":``,role:`status`}}))}const Am=/* @__PURE__ */ new WeakMap;async function jm(e){let t=e.closest(`[data-persona-tool-detail]`),n=t?.querySelector(`pre`);if(!n)return;let r=`Copy ${t?.getAttribute(`data-persona-tool-detail`)}`;clearTimeout(Am.get(e));try{await navigator.clipboard.writeText(n.textContent??``),e.dataset.copied=`true`,e.setAttribute(`aria-label`,`Copied`),e.title=`Copied`;let t=F(`check`,14,`currentColor`,2);t&&e.replaceChildren(t)}catch{e.setAttribute(`aria-label`,`Copy failed — try again`),e.title=`Copy failed — try again`}Am.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute(`aria-label`,r),e.title=r;let t=F(`copy`,14,`currentColor`,1.7);t&&e.replaceChildren(t),Am.delete(e)},1800))}H(),wi(),Ze();const Mm=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?`currentColor`:`var(--persona-primary, #171717)`),Nm=(e,t)=>{let n=e.toolCall;if(!n)return``;let r=(n.chunks??[]).join(``).trim();if(r)return r.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(-t).join(`
35
- `);let i=Me(n.args).trim();return i?i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join(`
36
- `):``},Pm=(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)`},Fm=(e,t)=>{let n=e.toolCall,r=t?.features?.toolCallDisplay,i=r?.collapsedMode??_i.collapsedMode,a=n?.success===!1?n.error||`Tool failed`:Nm(e,r?.previewMaxLines??_i.previewMaxLines),o=n?cs(t,`tool`)===`row`?`${n.status===`complete`?`Used`:`Using`} ${n.name?.trim()||`tool`}`:Le(n):``;if(!n)return{summary:o,previewText:a,isActive:!1};let s=n.status!==`complete`,c=t?.toolCall??{},l=o;return i===`tool-name`?l=n.name?.trim()||o:i===`tool-preview`&&a&&(l=a),s&&c.activeTextTemplate?l=Ve(n,c.activeTextTemplate,l):!s&&c.completeTextTemplate&&(l=Ve(n,c.completeTextTemplate,l)),n.success===!1?l+=` · Failed`:n.superseded&&(l+=` · Approved, ran again below`),{summary:l,previewText:a,isActive:s}},Im=(e,t,n,r)=>{os(e,t,{stateSet:n,previewKind:`tool`,iconColor:Mm(r?.toolCall??{},t.classList.contains(`persona-activity-row`))})},Lm=(e,t,n=/* @__PURE__ */ new Set)=>{t=ss(t,`tool`);let r=e.toolCall,i=t?.toolCall??{},a=es(`persona-tool-bubble`,e.id);if(i.backgroundColor&&(a.style.backgroundColor=i.backgroundColor),i.borderColor&&(a.style.borderColor=i.borderColor),i.borderWidth&&(a.style.borderWidth=i.borderWidth),i.borderRadius&&(a.style.borderRadius=i.borderRadius),a.style.boxShadow=i.shadow===void 0?`var(--persona-tool-bubble-shadow)`:i.shadow.trim()===``?`none`:i.shadow,!r)return us(a,e,t,`tool`);let o=t?.features?.toolCallDisplay??{},s=o.expandable??_i.expandable,c=s&&n.has(e.id),{summary:l,previewText:u,isActive:d}=Fm(e,t),f=ts({expandable:s,expanded:c,bubbleType:`tool`});i.headerBackgroundColor&&(f.style.backgroundColor=i.headerBackgroundColor),i.headerPaddingX&&(f.style.paddingLeft=i.headerPaddingX,f.style.paddingRight=i.headerPaddingX),i.headerPaddingY&&(f.style.paddingTop=i.headerPaddingY,f.style.paddingBottom=i.headerPaddingY);let p=B(`div`,`persona-flex persona-flex-col persona-text-left`),m=B(`span`,`persona-text-xs persona-text-persona-primary`);i.headerTextColor&&(m.style.color=i.headerTextColor);let h=String(r.startedAt??Date.now()),g=()=>{let e=B(`span`,``);return e.setAttribute(`data-tool-elapsed`,h),e.textContent=ze(r),e},_=i.renderCollapsedSummary?.({message:e,toolCall:r,defaultSummary:l,previewText:u,collapsedMode:o.collapsedMode??_i.collapsedMode,isActive:d,config:t??{},elapsed:ze(r),createElapsedElement:g});typeof _==`string`&&_.trim()?(m.textContent=_,p.appendChild(m)):_ instanceof HTMLElement?p.appendChild(_):(m.textContent=l,p.appendChild(m));let v=o.loadingAnimation??_i.loadingAnimation,y=i.activeTextTemplate,b=i.completeTextTemplate,x=d?y:b,S=_ instanceof HTMLElement,C=(e,t)=>{m.textContent=``;let n=r.name?.trim()||`tool`,i=He(e,n),a=0;for(let e of i){let n=e.styles.length>0?(()=>{let t=B(`span`,e.styles.map(e=>`persona-tool-text-${e}`).join(` `));return m.appendChild(t),t})():m;if(e.isDuration&&d)n.appendChild(g());else{let i=e.isDuration?ze(r):e.text;t?a=Cm(n,i,a):n.appendChild(document.createTextNode(i))}}};if(!S){if(d&&v!==`none`){let e=i.loadingAnimationDuration??2e3;if(m.setAttribute(`data-preserve-animation`,`true`),v===`pulse`)m.classList.add(`persona-tool-loading-pulse`),m.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),x&&C(x,!1);else if(m.classList.add(`persona-tool-loading-${v}`),m.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),v===`shimmer-color`&&(i.loadingAnimationColor&&m.style.setProperty(`--persona-tool-anim-color`,i.loadingAnimationColor),i.loadingAnimationSecondaryColor&&m.style.setProperty(`--persona-tool-anim-secondary-color`,i.loadingAnimationSecondaryColor)),x)C(x,!0);else{let e=m.textContent||l;m.textContent=``,Cm(m,e,0)}}else x&&C(x,!1)}let w=Mm(i,cs(t,`tool`)===`row`),T=rs(f,p,{expandable:s,expanded:c,iconColor:w,metaGap:!0}),E=is({bubble:a,previewKind:`tool`,expanded:c,isActive:d,previewText:u,activePreview:o.activePreview,activeMinHeight:o.activeMinHeight,renderPreview:()=>i.renderCollapsedPreview?.({message:e,toolCall:r,defaultPreview:u,isActive:d,config:t??{}})});if(!s)return a.append(f,E),us(a,e,t,`tool`);let D=B(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3`);if(D.style.display=c?``:`none`,i.contentBackgroundColor&&(D.style.backgroundColor=i.contentBackgroundColor),i.contentTextColor&&(D.style.color=i.contentTextColor),i.contentPaddingX&&(D.style.paddingLeft=i.contentPaddingX,D.style.paddingRight=i.contentPaddingX),i.contentPaddingY&&(D.style.paddingTop=i.contentPaddingY,D.style.paddingBottom=i.contentPaddingY),t.future?.v5Defaults===!0)km(D,e,t);else{if(r.name){let e=B(`div`,`persona-text-xs persona-text-persona-muted persona-italic`);i.contentTextColor?e.style.color=i.contentTextColor:i.headerTextColor&&(e.style.color=i.headerTextColor),e.textContent=r.name,D.appendChild(e)}if(r.args!==void 0){let e=B(`div`,`persona-space-y-1`),t=B(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Arguments`;let n=B(`pre`,`persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,Pm(n,i),n.textContent=Me(r.args),e.append(t,n),D.appendChild(e)}if(r.chunks&&r.chunks.length){let e=B(`div`,`persona-space-y-1`),t=B(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Activity`;let n=B(`pre`,`persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,Pm(n,i),n.textContent=r.chunks.join(``),e.append(t,n),D.appendChild(e)}if(r.success===!1&&D.appendChild(V(`div`,{className:`persona-text-sm persona-whitespace-pre-wrap`,text:r.error||`Tool failed`,attrs:{"data-persona-tool-error":``}})),r.status===`complete`&&r.result!==void 0){let e=B(`div`,`persona-space-y-1`),t=B(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Result`;let n=B(`pre`,`persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,Pm(n,i),n.textContent=Me(r.result),e.append(t,n),D.appendChild(e)}if(r.status===`complete`&&typeof r.duration==`number`){let e=B(`div`,`persona-text-xs persona-text-persona-muted`);i.contentTextColor&&(e.style.color=i.contentTextColor),e.textContent=`Duration: ${r.duration}ms`,D.appendChild(e)}}return as({expanded:c,header:f,toggleIcon:T,content:D,collapsedPreview:E,iconColor:w}),a.append(f,E,D),us(a,e,t,`tool`)};g();const{setLoader:Rm,load:zm,provide:Bm,getSync:Vm}=h({fallbackImport:()=>import(`@runtypelabs/persona/approval-ui`)}),Hm=zm,Um=Vm;g();const{setLoader:Wm,load:Gm}=h({fallbackImport:()=>import(`@runtypelabs/persona/event-stream-view`)}),Km=Gm,qm=new class{constructor(){this.components=/* @__PURE__ */ new Map,this.#e=/* @__PURE__ */ new Map}#e;register(e,t,n){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t),n?this.#e.set(e,n):this.#e.delete(e)}unregister(e){this.components.delete(e),this.#e.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.#e.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.#e.clear()}registerAll(e){Object.entries(e).forEach(([e,t])=>{this.register(e,t)})}};g(),re();const Jm=[`PersonaArtifactCard`,`PersonaArtifactInline`],{setLoader:Ym,load:Xm,provide:Zm,getSync:Qm}=h({fallbackImport:()=>import(`@runtypelabs/persona/artifacts-ui`)});let $m=null;const eh=/* @__PURE__ */ new Set,th=e=>{if($m)return $m;$m=e,e.initArtifactsUi({componentRegistry:qm});for(let t of Jm)qm.has(t)||qm.register(t,t===`PersonaArtifactCard`?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=O();t?e.__provideMarkdownParsers(t):E(()=>{let t=O();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader(()=>ne());let n=[...eh];eh.clear();for(let e of n)try{e()}catch{}return e},nh=()=>Xm().then(th),rh=()=>{if($m)return $m;let e=Qm();return e?th(e):null},ih=e=>$m?()=>{}:(eh.add(e),()=>{eh.delete(e)});function ah(e){return e?.features?.artifacts?.enabled===!0}function oh(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`),!ah(t))return;let n=t.features?.artifacts?.layout,r=n?.paneBorder?.trim(),i=n?.paneBorderLeft?.trim();r?(e.classList.add(`persona-artifact-border-full`),e.style.setProperty(`--persona-artifact-pane-border`,r)):i&&(e.classList.add(`persona-artifact-border-left`),e.style.setProperty(`--persona-artifact-pane-border-left`,i))}function sh(e){e.style.removeProperty(`--persona-artifact-doc-toolbar-icon-color`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-bg`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-border`)}const ch=[`panel`,`seamless`,`detached`];function lh(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&ch.includes(t)?t:t?`panel`:e.launcher?.detachedPanel?`detached`:`panel`}function uh(e){return!e||!ah(e)?!1:lh(e)===`detached`}function dh(e,t){if(!ah(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`),sh(e),oh(e,t);return}let n=t.features?.artifacts?.layout,r=lh(t)===`detached`?`var(--persona-panel-inset)`:`0`;e.style.setProperty(`--persona-artifact-split-gap`,n?.splitGap??r),e.style.setProperty(`--persona-artifact-pane-width`,n?.paneWidth??`40%`),e.style.setProperty(`--persona-artifact-pane-max-width`,n?.paneMaxWidth??`28rem`),n?.drawerWidth?e.style.setProperty(`--persona-artifact-drawer-width`,n.drawerWidth):e.style.removeProperty(`--persona-artifact-drawer-width`),n?.paneMinWidth?e.style.setProperty(`--persona-artifact-pane-min-width`,n.paneMinWidth):e.style.removeProperty(`--persona-artifact-pane-min-width`);let i=n?.paneBackground?.trim();i?e.style.setProperty(`--persona-artifact-pane-bg`,i):e.style.removeProperty(`--persona-artifact-pane-bg`);let a=n?.panePadding?.trim();a?e.style.setProperty(`--persona-artifact-pane-padding`,a):e.style.removeProperty(`--persona-artifact-pane-padding`);let o=[[n?.documentToolbarIconColor,`--persona-artifact-doc-toolbar-icon-color`],[n?.documentToolbarToggleActiveBackground,`--persona-artifact-doc-toggle-active-bg`],[n?.documentToolbarToggleActiveBorderColor,`--persona-artifact-doc-toggle-active-border`],[n?.documentToolbarToggleActiveColor,`--persona-artifact-doc-toggle-active-color`]];for(let[t,n]of o){let r=t?.trim();r?e.style.setProperty(n,r):e.style.removeProperty(n)}oh(e,t)}function fh(e,t){for(let t of ch)e.classList.remove(`persona-artifact-appearance-${t}`);if(e.style.removeProperty(`--persona-artifact-pane-radius`),e.style.removeProperty(`--persona-artifact-pane-shadow`),e.style.removeProperty(`--persona-artifact-chat-shadow`),!ah(t))return;let n=t.features?.artifacts?.layout,r=lh(t);e.classList.add(`persona-artifact-appearance-${r}`);let i=n?.paneBorderRadius?.trim();i&&e.style.setProperty(`--persona-artifact-pane-radius`,i);let a=n?.paneShadow?.trim();a&&e.style.setProperty(`--persona-artifact-pane-shadow`,a);let o=n?.chatShadow?.trim();o&&e.style.setProperty(`--persona-artifact-chat-shadow`,o)}function ph(e,t){return!t||!ah(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}Ae();const mh=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`]),hh=/* @__PURE__ */ new Set([`collapsed`,`card`,`panel`,`inline`]),gh=/* @__PURE__ */ new Set([`markdown`,`component`]),_h=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,vh=e=>typeof e==`object`&&!!e&&!Array.isArray(e),yh=e=>!mh.has(e),bh=e=>typeof e==`string`&&hh.has(e),xh=e=>Object.keys(e).length>0;function Sh(e,t,n,r){e.push({path:t,code:n,message:r})}const Ch=`Ignored an unsupported value.`,wh={kind:`mode`,message:Ch},Th={kind:`string`,message:`Expected a CSS length string.`},Eh={kind:`boolean`},Dh={kind:`object`,message:`Expected a preference object.`,children:{showToolCalls:Eh,showReasoning:Eh,toolCallDisplay:{kind:`object`,children:{collapsedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`tool-call`,`tool-name`,`tool-preview`]),message:Ch},groupedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`stack`,`summary`]),message:Ch},loadingAnimation:{kind:`enum`,values:/* @__PURE__ */ new Set([`none`,`pulse`,`shimmer`,`shimmer-color`,`rainbow`]),message:Ch},expandable:Eh,grouped:Eh}},reasoningDisplay:{kind:`object`,children:{expandable:Eh,activePreview:Eh}},artifacts:{kind:`object`,children:{display:{kind:`object`,bareMode:!0,message:`Expected an artifact display rules object.`,children:{default:wh,files:{kind:`object`,bareMode:!0,message:`Expected collapsed, panel, inline, or a file display rules object.`,children:{default:wh,byMediaType:{kind:`modeMap`,keys:`mediaType`}}},byType:{kind:`modeMap`,keys:gh,alias:`byKind`,deprecated:`Use byKind. The legacy selector was normalized automatically.`},byKind:{kind:`modeMap`,keys:gh}}},filePreview:{kind:`object`,children:{enabled:Eh}},layout:{kind:`object`,children:{paneWidth:Th,paneMaxWidth:Th,paneMinWidth:Th,expandedPanelWidth:Th,resizableMinWidth:Th,resizableMaxWidth:Th,expandLauncherPanelWhenOpen:Eh,resizable:Eh}}}}}};function Oh(e,t,n,r){if(e!==void 0)switch(t.kind){case`boolean`:return typeof e==`boolean`?e:Sh(r,n,`invalid_type`,`Expected a boolean.`);case`string`:return typeof e==`string`?e:Sh(r,n,`invalid_type`,t.message);case`enum`:return typeof e==`string`&&t.values.has(e)?e:Sh(r,n,`invalid_value`,t.message);case`mode`:return bh(e)?we(e):Sh(r,n,`invalid_value`,t.message);case`modeMap`:{if(!vh(e))return Sh(r,n,`invalid_type`,`Expected an object.`);let i=t.keys===`mediaType`?void 0:t.keys,a={};for(let[t,o]of Object.entries(e)){let e=i?t:Te(t);yh(t)&&(i?i.has(t):_h.test(e))?bh(o)?a[e]=we(o):Sh(r,`${n}.${t}`,`invalid_value`,`Expected collapsed, panel, or inline.`):Sh(r,`${n}.${t}`,i?`unknown_key`:`invalid_value`,i?`Ignored an unsupported selector.`:`Expected a MIME type such as "text/html" or a wildcard such as "image/*".`)}return xh(a)?a:void 0}case`object`:{if(t.bareMode&&bh(e))return we(e);if(!vh(e))return Sh(r,n,`invalid_type`,t.message??`Expected an object.`);let i=Object.keys(t.children),a=e=>n?`${n}.${e}`:e;for(let t of Object.keys(e))(!yh(t)||!i.includes(t))&&Sh(r,a(t),`unknown_key`,`Ignored because this key is not part of the persisted preference schema.`);let o={};for(let n of i){let i=t.children[n],s=Oh(e[n],i,a(n),r);if(i.deprecated&&e[n]!==void 0&&Sh(r,a(n),`deprecated_key`,i.deprecated),s===void 0)continue;let c=i.alias??n,l=o[c];o[c]=vh(l)&&vh(s)?{...l,...s}:s}return xh(o)?o:void 0}}}function kh(e){let t=[];return{preferences:(e===null?void 0:Oh(e,Dh,``,t))??{},issues:t}}function Ah(e){if(Array.isArray(e))return e.map(Ah);if(!vh(e))return e;let t={};for(let[n,r]of Object.entries(e))yh(n)&&r!==void 0&&(t[n]=Ah(r));return t}function jh(e,t){let n=Ah(e);for(let[e,r]of Object.entries(t)){if(!yh(e)||r===void 0)continue;let t=n[e];n[e]=vh(t)&&vh(r)?jh(t,r):Ah(r)}return n}function Mh(e){let t={},n;for(let r of e){let e=kh(r).preferences;n=Ph(n,e.artifacts?.display),t=jh(t,e)}let r=t;return r.artifacts&&(n===void 0?delete r.artifacts.display:r.artifacts.display=n),r}function Nh(e,t){if(t===void 0)return e===void 0?void 0:Ah(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byMediaType,...t.byMediaType},a={...r?{default:r}:{},...xh(i)?{byMediaType:i}:{}};return xh(a)?a:void 0}function Ph(e,t){if(t===void 0)return e===void 0?void 0:Ah(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byType,...n.byKind,...t.byType,...t.byKind},a=Nh(n.files,t.files),o={...r?{default:r}:{},...xh(i)?{byKind:i}:{},...a===void 0?{}:{files:a}};return xh(o)?o:void 0}function Fh(e={},t){let n=Mh(t),r={...e};if(n.showToolCalls!==void 0&&(r.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(r.showReasoning=n.showReasoning),n.toolCallDisplay&&(r.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(r.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let t=e.artifacts??{},i={...t};if(n.artifacts.display!==void 0){let e=Ph(t.display,n.artifacts.display);e!==void 0&&(i.display=e)}n.artifacts.filePreview&&(i.filePreview={...t.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...t.layout,...n.artifacts.layout}),r.artifacts=i}return r}function Ih(e){let t=e.preferences;return!t||!xh(t)?e:{...e,features:Fh(e.features??{},[t])}}function Lh(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 Rh(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 zh(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Bh(e,t,n,r){let i=e-r-2*t-n;return Math.max(0,i)}function Vh(e,t){let n=(t.getComputedStyle(e).gap||`0px`).trim().split(/\s+/)[0]??`0px`,r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let i=/^([\d.]+)/.exec(n);return i?Number(i[1]):8}function Hh(e,t,n,r,i,a,o=200){let s=Lh(i,200),c=Bh(t,n,r,o);c=Math.max(s,c);let l=Rh(a);return l!==null&&(c=Math.min(c,l)),zh(e,s,c)}g();const{setLoader:Uh,load:Wh,provide:Gh,getSync:Kh}=h({fallbackImport:()=>import(`@runtypelabs/persona/forms-ui`)}),qh=Wh,Jh=Kh,Yh=new class{#e=/* @__PURE__ */ new Map;register(e){this.#e.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.#e.set(e.id,e),e.onRegister?.()}unregister(e){let t=this.#e.get(e);t&&(t.onUnregister?.(),this.#e.delete(e))}getAll(){return Array.from(this.#e.values()).sort((e,t)=>(t.priority??0)-(e.priority??0))}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let n=new Set(e.map(e=>e.id));return[...t.filter(e=>!n.has(e.id)),...e].sort((e,t)=>(t.priority??0)-(e.priority??0))}clear(){this.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}};wi(),ci(),$r();const Xh=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Zh=/* @__PURE__ */ new Set([`headers`,`agent`,`storageAdapter`,`components`,`targetProviders`,`voiceRecognition.provider.custom`,`features.artifacts.display`,`features.streamAnimation.plugins`,`preferences`,`welcome.icon`]),Qh=(e,t,n)=>{if(!Xh(e)||!Xh(t)||Zh.has(n))return t;let r={...e};for(let i of Object.keys(t)){if(t[i]===void 0){delete r[i];continue}let a=n?`${n}.${i}`:i;r[i]=Qh(e[i],t[i],a)}return r};function $h(e,t){let n=Wr(Si),r=Yr(e,t,n),i=qr(Xr(Qh(e,t,``),n,r),r);return ai(fi(i),si(e,t))}const eg=()=>{let e=/* @__PURE__ */ new Map,t=(t,r)=>(e.has(t)||e.set(t,/* @__PURE__ */ new Set),e.get(t).add(r),()=>n(t,r)),n=(t,n)=>{e.get(t)?.delete(n)};return{on:t,off:n,emit:(t,n)=>{e.get(t)?.forEach(e=>{try{e(n)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Event handler error:`,e)}})}}},tg=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},ng=e=>{let t=e.trim(),n=t.indexOf(`{`);if(n===-1)return null;let r=0;for(let e=n;e<t.length;e+=1){let i=t[e];if(i===`{`&&(r+=1),i===`}`&&(--r,r===0))return t.slice(n,e+1)}return null},rg=({text:e})=>{if(!e||!e.includes(`{`))return null;try{let t=tg(e),n=ng(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!=`object`||!r.action)return null;let{action:i,...a}=r;return{type:String(i),payload:a,raw:r}}catch{return null}},ig=e=>typeof e==`string`?e:e==null?``:String(e),ag={message:e=>{if(e.type===`message`)return{handled:!0,displayText:ig(e.payload.text)}},messageAndClick:(e,t)=>{if(e.type!==`message_and_click`)return;let n=e.payload,r=ig(n.element);if(r&&t.document?.querySelector){let e=t.document.querySelector(r);e?setTimeout(()=>{e.click()},400):typeof console<`u`&&console.warn(`[AgentWidget] Element not found for selector:`,r)}return{handled:!0,displayText:ig(n.text)}}},og=e=>Array.isArray(e)?e.map(e=>String(e)):[],sg=e=>{let t=new Set(og(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(og(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let n=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:n}))};return{process:n=>{if(n.streaming||n.message.role!==`assistant`||!n.text||t.has(n.message.id))return null;let i=typeof n.raw==`string`&&n.raw||typeof n.message.rawContent==`string`&&n.message.rawContent||typeof n.text==`string`&&n.text||null;!i&&typeof n.text==`string`&&n.text.trim().startsWith(`{`)&&typeof console<`u`&&console.warn(`[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.`);let a=i?e.parsers.reduce((e,t)=>e||t?.({text:i,message:n.message})||null,null):null;if(!a)return null;t.add(n.message.id),r();let o={action:a,message:n.message};e.emit(`action:detected`,o);for(let t of e.handlers)if(t)try{let r=t(a,{message:n.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{e.emit(`action:resubmit`,o)}});if(!r)continue;if(r.handled){let e=r.persistMessage!==!1;return{text:r.displayText===void 0?``:r.displayText,persist:e,resubmit:r.resubmit}}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Action handler error:`,e)}return{text:``,persist:!0}},syncFromMetadata:n}},cg=e=>{if(!e)return null;try{return JSON.parse(e)}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] Failed to parse stored state:`,e),null}},lg=e=>e.map(e=>({...e,streaming:!1})),ug=e=>e.map(e=>({...e,status:`complete`})),dg=(e=`persona-state`)=>{let t=()=>typeof window>`u`||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?cg(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let t={...n,messages:n.messages?lg(n.messages):void 0,artifacts:n.artifacts?ug(n.artifacts):void 0};r.setItem(e,JSON.stringify(t))}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to persist state:`,e)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to clear stored state:`,e)}}}},fg=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`)},pg=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let n=await t.digest(`SHA-256`,new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}catch{}return fg(e)},mg=async(e,t)=>{let n=await pg(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await pg(`${e}\0${t}`)}`}},hg=(e,t,n)=>{let r=``,i=``,a=``,o=!1,s=!1,c=0,l=null,u=null,d=/* @__PURE__ */ new Set,f=()=>{if(n||o)return null;try{return typeof window>`u`||!window.localStorage?null:window.localStorage}catch{return o=!0,null}},p=()=>{let e=f();if(!e)return l;try{return e.getItem(r)}catch{return o=!0,l}},m=(e,t)=>{if(s||e===l)return;let n=l;l=e,c+=1;let r={previousToken:n,token:e,source:t,revision:c};for(let e of d)e(r)},h=e=>{s||(e.key===null||e.key===r)&&m(e.key===null?null:e.newValue??null,`external`)},g=(async()=>{let o=await mg(e,t);r=o.storageKey,i=o.leaseKey,a=o.lockName,l=p(),!n&&typeof window<`u`&&window.addEventListener(`storage`,h)})(),_=e=>new Promise(t=>setTimeout(t,e)),v=()=>{let e=f();if(!e)return null;try{let t=e.getItem(i);if(!t)return null;let n=JSON.parse(t);return typeof n?.expiresAt==`number`&&typeof n?.ownerNonce==`string`?n:null}catch{return null}},y=e=>{let t=f();if(t)try{v()?.ownerNonce===e&&t.removeItem(i)}catch{}},b=/* @__PURE__ */ new Set,x=e=>s?Promise.reject(/* @__PURE__ */ Error(`Visitor store destroyed before its first init could start`)):e(),S=e=>new Promise(t=>{let n=setTimeout(r,e);function r(){clearTimeout(n),b.delete(r),window.removeEventListener(`storage`,a),t()}function a(e){(e.key===null||e.key===i)&&r()}b.add(r),window.addEventListener(`storage`,a)}),C=async e=>{let t=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,n=Date.now()+15e3;for(;!s&&Date.now()<n;){let n=f();if(!n)break;let r=Date.now(),a=v();if(a&&a.expiresAt>r&&a.ownerNonce!==t)await S(Math.min(a.expiresAt-r,500));else{try{n.setItem(i,JSON.stringify({ownerNonce:t,expiresAt:r+1e4}))}catch{o=!0;break}if(await _(20+Math.random()*40),v()?.ownerNonce!==t)await S(500);else{u=t;try{return await x(e)}finally{u=null,y(t)}}}}return x(e)};return{ready:g,async get(){return await g,m(p(),`external`),l},async set(e){await g;let t=f();if(t)try{t.setItem(r,e)}catch{o=!0}m(e,`local`)},async clear(){await g;let e=f();if(e)try{e.removeItem(r)}catch{o=!0}m(null,`local`)},revision(){return c},subscribe(e){return d.add(e),()=>{d.delete(e)}},async withFirstInitLock(e){await g;let t=globalThis.navigator?.locks;return t?.request?t.request(a,()=>x(e)):f()?C(e):x(e)},matches(r,i,a){return r===e&&i===t&&a===n},destroy(){s=!0,d.clear(),typeof window<`u`&&window.removeEventListener(`storage`,h),u&&y(u);for(let e of[...b])e()}}};g();const{setLoader:gg,load:_g}=h({fallbackImport:()=>import(`@runtypelabs/persona/history-view`)}),vg=_g;function yg(){return null}function bg(e){if(!e||typeof e!=`object`||!(`component`in e))return!1;let t=e.component;return typeof t==`string`&&t.length>0}function xg(e,t){if(!bg(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 Sg(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith(`{`)&&!r.startsWith(`[`))return null;if(n.length<=t)return e;try{let t=xg((0,p.parse)(n,p.STR|p.OBJ),n);t&&(e=t)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Cg(e){return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`&&`props`in e&&typeof e.props==`object`}H();function wg(e,t){let{config:n,message:r,onPropsUpdate:i}=t,a=qm.get(e.component);if(!a){if(Jm.includes(e.component)){nh().catch(()=>{});let e=B(`div`,`persona-w-full`);return e.setAttribute(`data-persona-artifact-pending`,`true`),e}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let o={message:r,config:n,updateProps:e=>{i&&i(e)}};try{return a(e.props,o)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function Tg(){let e=Sg();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Eg(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 Dg(e){let t=Eg(e);if(!t)return!1;try{let e=JSON.parse(t);return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`}catch{return!1}}function Og(e){let t=Eg(e);if(!t)return null;try{let e=JSON.parse(t);if(typeof e==`object`&&e&&`component`in e&&typeof e.component==`string`){let n=e;return{component:n.component,props:n.props&&typeof n.props==`object`&&n.props!==null?n.props:{},raw:t}}}catch{}return null}const kg=[`Very dissatisfied`,`Dissatisfied`,`Neutral`,`Satisfied`,`Very satisfied`];function Ag(e){let{onSubmit:t,onDismiss:n,title:r=`How satisfied are you?`,subtitle:i=`Please rate your experience`,commentPlaceholder:a=`Share your thoughts (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,ratingLabels:l=kg}=e,u=document.createElement(`div`);u.className=`persona-feedback-container persona-feedback-csat`,u.setAttribute(`role`,`dialog`),u.setAttribute(`aria-label`,`Customer satisfaction feedback`);let d=null,f=document.createElement(`div`);f.className=`persona-feedback-content`;let p=document.createElement(`div`);p.className=`persona-feedback-header`;let m=document.createElement(`h3`);m.className=`persona-feedback-title`,m.textContent=r,p.appendChild(m);let h=document.createElement(`p`);h.className=`persona-feedback-subtitle`,h.textContent=i,p.appendChild(h),f.appendChild(p);let g=document.createElement(`div`);g.className=`persona-feedback-rating persona-feedback-rating-csat`,g.setAttribute(`role`,`radiogroup`),g.setAttribute(`aria-label`,`Satisfaction rating from 1 to 5`);let _=[];for(let e=1;e<=5;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-star-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`${e} star${e>1?`s`:``}: ${l[e-1]}`),t.title=l[e-1],t.dataset.rating=String(e),t.innerHTML=`
32
+ `,n.addEventListener(`click`,t);let r=e=>{let t=e.launcher??{},r=kf(e),i=ku(e)===`circle`;i?(n.dataset.personaLauncherVariant=`circle`,n.setAttribute(`aria-label`,t.title??`Open chat`)):(n.removeAttribute(`data-persona-launcher-variant`),n.removeAttribute(`aria-label`));let a=n.querySelector(`[data-role='launcher-title']`);if(a){let e=t.title??`Chat Assistant`;a.textContent=e,a.setAttribute(`title`,e)}let o=n.querySelector(`[data-role='launcher-subtitle']`);if(o){let e=t.subtitle??`Here to help you get answers fast`;o.textContent=e,o.setAttribute(`title`,e)}let s=n.querySelector(`.persona-flex-col`);s&&(t.textHidden||r||i?s.style.display=`none`:s.style.display=``);let c=n.querySelector(`[data-role='launcher-icon']`);if(c){if(t.agentIconHidden)c.style.display=`none`;else{let e=t.agentIconSize??`40px`;if(c.style.height=e,c.style.width=e,t.agentIconBackgroundColor?(c.style.backgroundColor=t.agentIconBackgroundColor,c.classList.remove(`persona-bg-persona-primary`)):(c.style.backgroundColor=``,c.classList.add(`persona-bg-persona-primary`)),c.innerHTML=``,t.agentIconName){let n=parseFloat(e)||24,r=P(t.agentIconName,n*.6,`var(--persona-text-inverse, #ffffff)`,1.5);r?(c.appendChild(r),c.style.display=``):(c.textContent=t.agentIconText??`💬`,c.style.display=``)}else t.iconUrl?c.style.display=`none`:(c.textContent=t.agentIconText??`💬`,c.style.display=``)}}let l=n.querySelector(`[data-role='launcher-image']`);if(l){let e=t.agentIconSize??`40px`;l.style.height=e,l.style.width=e,t.iconUrl&&!t.agentIconName&&!t.agentIconHidden?(l.src=t.iconUrl,l.style.display=`block`):l.style.display=`none`}let u=n.querySelector(`[data-role='launcher-call-to-action-icon']`);if(u){let e=t.callToActionIconSize??`32px`;u.style.height=e,u.style.width=e,t.callToActionIconBackgroundColor?(u.style.backgroundColor=t.callToActionIconBackgroundColor,u.classList.remove(`persona-bg-persona-primary`)):(u.style.backgroundColor=``,u.classList.add(`persona-bg-persona-primary`)),t.callToActionIconColor?(u.style.color=t.callToActionIconColor,u.classList.remove(`persona-text-persona-call-to-action`)):(u.style.color=``,u.classList.add(`persona-text-persona-call-to-action`));let n=0;if(t.callToActionIconPadding?(u.style.boxSizing=`border-box`,u.style.padding=t.callToActionIconPadding,n=(parseFloat(t.callToActionIconPadding)||0)*2):(u.style.boxSizing=``,u.style.padding=``),t.callToActionIconHidden||i)u.style.display=`none`;else if(u.style.display=r?`none`:``,u.innerHTML=``,t.callToActionIconName){let r=Math.max((parseFloat(e)||24)-n,8),i=P(t.callToActionIconName,r,`currentColor`,1.5);i?u.appendChild(i):u.textContent=t.callToActionIconText??`↗`}else u.textContent=t.callToActionIconText??`↗`}let d=t.position&&zf[t.position]?zf[t.position]:zf[`bottom-right`];n.className=r?`persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer`:`persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer ${d}`,r||(n.style.zIndex=String(t.zIndex??1e5)),n.style.border=t.border??`1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))`,n.style.boxShadow=t.shadow===void 0?`var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))`:t.shadow.trim()===``?`none`:t.shadow,r?(n.style.width=`0`,n.style.minWidth=`0`,n.style.maxWidth=`0`,n.style.padding=`0`,n.style.overflow=`hidden`,n.style.border=`none`,n.style.boxShadow=`none`):(n.style.width=``,n.style.minWidth=``,n.style.maxWidth=t.collapsedMaxWidth??``,n.style.justifyContent=``,n.style.padding=``,n.style.overflow=``)};return e&&r(e),{element:n,update:r,destroy:()=>{n.removeEventListener(`click`,t),n.remove()}}},_m=/* @__PURE__ */ new Set,vm=e=>{let t=e?.persistState;return`${(typeof t==`object`?t?.keyPrefix:void 0)??`persona-`}teaser-dismissed`},ym=(e,t)=>{if(_m.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)===`1`}catch{return!1}},bm=(e,t)=>{if(_m.add(e),t)try{window.localStorage.setItem(e,`1`)}catch{}},xm=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,Sm=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||kf(e??{})?null:t},Cm=(e,t)=>{let n=z(`div`,`persona-launcher-surface`);n.setAttribute(`data-persona-launcher-surface`,`true`);let r=e??{},i=null,a=null,o=null,s=null,c=null,l=!1,u=!1,d=!1,f=!1,p=()=>(i?.frequency??`once`)===`once`&&r.persistState!==!1,m=()=>{c!==null&&(clearTimeout(c),c=null)},h=()=>{a&&l&&(l=!1,a.hidden=!0)},g=e=>{m(),d=!0,h(),bm(vm(r),e&&p())},_=e=>{i&&!d&&g(e===`user`&&l)},v=()=>{c=null,!(!a||d||f)&&(u=!0,l=!0,a.hidden=!1,!(xm()||typeof a.animate!=`function`)&&a.animate([{opacity:`0`,transform:`translateY(6px)`},{opacity:`1`,transform:`none`}],{duration:220,easing:`ease-out`,fill:`backwards`}))},y=()=>{i&&a&&(d||u||f||ym(vm(r),p())||(m(),c=setTimeout(v,Math.max(0,i.delayMs??0))))},b=()=>{g(p()),t()},x=e=>{e.stopPropagation(),g(p())},S=gm(e,()=>{_(`user`),t()}),C=()=>{m(),s?.removeEventListener(`click`,b),o?.removeEventListener(`click`,x),a?.remove(),a=null,s=null,o=null,l=!1},w=()=>{s=B(`button`,{className:`persona-launcher-teaser-text`,attrs:{type:`button`}}),s.addEventListener(`click`,b),o=B(`button`,{className:`persona-launcher-teaser-dismiss`,attrs:{type:`button`},text:`×`}),o.addEventListener(`click`,x),a=B(`div`,{className:`persona-launcher-teaser`,attrs:{"data-persona-launcher-teaser":`true`,role:`status`,"aria-live":`polite`,hidden:``}},s,o),n.insertBefore(a,S.element)},T=()=>{let e=r.launcher?.position??`bottom-right`,t=zf[e]??zf[`bottom-right`];a?(n.className=$e(`persona-launcher-surface`,t),n.setAttribute(`data-teaser`,e),n.style.zIndex=String(r.launcher?.zIndex??1e5),S.element.style.position=`static`):(n.className=`persona-launcher-surface`,n.removeAttribute(`data-teaser`),n.style.zIndex=``,S.element.style.position=``)},E=e=>{let t=Sm(e);i=t,t?(a||w(),s.textContent=t.text,o.hidden=t.dismissible===!1,o.setAttribute(`aria-label`,t.dismissLabel??`Dismiss message`),y()):C()};return n.appendChild(S.element),e&&(E(e),T()),{element:n,launcher:S,get teaser(){return a?{element:a,show:v,dismiss:g}:null},setPanelOpen:(e,t=`user`)=>{f=e,e&&_(t)},update:e=>{r=e,S.update(e),E(e),T()},destroy:()=>{C(),S.destroy(),n.remove()}}},wm=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:i}=dm(e),a=hm(e,t),o={wrapper:n,panel:r,pillRoot:i},s={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},l={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:o,panelElements:a,transcript:s,header:c,composer:l,replaceHeader:e=>(c.element.replaceWith(e.header),c.element=e.header,c.iconHolder=e.iconHolder,c.headerTitle=e.headerTitle,c.headerSubtitle=e.headerSubtitle,c.closeButton=e.closeButton,c.closeButtonWrapper=e.closeButtonWrapper,c.clearChatButton=e.clearChatButton,c.clearChatButtonWrapper=e.clearChatButtonWrapper,e),replaceComposer:e=>{l.footer.replaceWith(e),l.footer=e}}},Tm=({config:e,plugins:t,onToggle:n})=>{let r=t.find(e=>e.renderLauncher);if(r?.renderLauncher){let t=r.renderLauncher({config:e,defaultRenderer:()=>gm(e,n).element,onToggle:n});if(t)return{instance:null,element:t}}let i=Cm(e,n);return{instance:i,element:i.element}},Em=e=>{let t=e?.persistState;return(typeof t==`object`?t?.keyPrefix:void 0)??`persona-`},Dm=(e,t,n)=>`${Em(e)}plugin:${t}:${n}`,Om=e=>{let t=/* @__PURE__ */ new Map,n=!1,r=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>`u`||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return i=>{let a=t=>Dm(e(),i,t);return{get:e=>{let i=a(e),o=r();if(o)try{return o.getItem(i)}catch{n=!0}return t.get(i)??null},set:(e,i)=>{let o=a(e),s=r();if(s)try{s.setItem(o,i);return}catch{n=!0}t.set(o,i)},remove:e=>{let i=a(e);t.delete(i);let o=r();if(o)try{o.removeItem(i)}catch{n=!0}}}}};V();const km=(e,t,n)=>{let r=n;for(let n of t){let t=z(`span`,`persona-tool-char`);t.style.setProperty(`--char-index`,String(r)),t.textContent=n===` `?`\xA0`:n,e.appendChild(t),r++}return r};V(),F(),Ti(),Qe();const Am=(e,t)=>{let n=e.reasoning?.chunks.join(``).trim()??``;return n?n.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join(`
33
+ `):``},jm=(e,t,n)=>{ps(e,t,{stateSet:n,previewKind:`reasoning`,iconColor:`currentColor`})},Mm=(e,t,n=/* @__PURE__ */ new Set)=>{t=ms(t,`reasoning`);let r=e.reasoning,i=ss(`persona-reasoning-bubble`,e.id);if(!r)return _s(i,e,t,`reasoning`);let a=t?.features?.reasoningDisplay??{},o=a.expandable??yi.expandable,s=o&&n.has(e.id),c=r.status!==`complete`,l=Am(e,a.previewMaxLines??yi.previewMaxLines),u=cs({expandable:o,expanded:s,bubbleType:`reasoning`}),d=z(`div`,`persona-flex persona-flex-col persona-text-left`),f=z(`span`,`persona-text-xs persona-text-persona-primary`),p=hs(t,`reasoning`)===`row`,m=p&&!c?`Thought for ${gs(r.durationMs??(r.completedAt!==void 0&&r.startedAt!==void 0?r.completedAt-r.startedAt:void 0))}`:`Thinking...`,h=t?.reasoning??{},g=String(r.startedAt??Date.now()),_=()=>{let e=z(`span`,``);return e.setAttribute(`data-tool-elapsed`,g),e.textContent=Ve(r),e},v=h.renderCollapsedSummary?.({message:e,reasoning:r,defaultSummary:m,previewText:l,isActive:c,config:t??{},elapsed:Ve(r),createElapsedElement:_});typeof v==`string`&&v.trim()?(f.textContent=v,d.appendChild(f)):v instanceof HTMLElement?d.appendChild(v):(f.textContent=m,d.appendChild(f));let y=z(`span`,`persona-text-xs persona-text-persona-primary`);y.textContent=Fe(r),p||d.appendChild(y);let b=a.loadingAnimation??yi.loadingAnimation,x=h.activeTextTemplate,S=h.completeTextTemplate,C=c?x:S,w=v instanceof HTMLElement,T=(e,t)=>{f.textContent=``;let n=Ue(e,``),i=0;for(let e of n){let n=e.styles.length>0?(()=>{let t=z(`span`,e.styles.map(e=>`persona-tool-text-${e}`).join(` `));return f.appendChild(t),t})():f;if(e.isDuration&&c)n.appendChild(_());else{let a=e.isDuration?Ve(r):e.text;t?i=km(n,a,i):n.appendChild(document.createTextNode(a))}}};if(!w&&C){if(y.style.display=`none`,f.style.display=``,c&&b!==`none`){let e=h.loadingAnimationDuration??2e3;f.setAttribute(`data-preserve-animation`,`true`),b===`pulse`?(f.classList.add(`persona-tool-loading-pulse`),f.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),T(C,!1)):(f.classList.add(`persona-tool-loading-${b}`),f.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),b===`shimmer-color`&&(h.loadingAnimationColor&&f.style.setProperty(`--persona-tool-anim-color`,h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&f.style.setProperty(`--persona-tool-anim-secondary-color`,h.loadingAnimationSecondaryColor)),T(C,!0))}else T(C,!1)}else if(!w&&c&&b!==`none`){f.style.display=``;let e=h.loadingAnimationDuration??2e3;if(f.setAttribute(`data-preserve-animation`,`true`),b===`pulse`)f.classList.add(`persona-tool-loading-pulse`),f.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`);else{f.classList.add(`persona-tool-loading-${b}`),f.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),b===`shimmer-color`&&(h.loadingAnimationColor&&f.style.setProperty(`--persona-tool-anim-color`,h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&f.style.setProperty(`--persona-tool-anim-secondary-color`,h.loadingAnimationSecondaryColor));let t=f.textContent||m;f.textContent=``,km(f,t,0)}r.status===`complete`&&!p&&(f.style.display=`none`)}else w||(r.status===`complete`&&!p?f.style.display=`none`:f.style.display=``);if(a.iconName&&!w){let e=z(`span`,`persona-reasoning-header-icon`),t=P(a.iconName,16,`currentColor`,2);t&&(e.appendChild(t),u.appendChild(e))}let E=`currentColor`,D=us(u,d,{expandable:o,expanded:s,iconColor:E,metaGap:!1}),O=ds({bubble:i,previewKind:`reasoning`,expanded:s,isActive:c,previewText:l,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:r,defaultPreview:l,isActive:c,config:t??{}})});if(!o)return i.append(u,O),_s(i,e,t,`reasoning`);let ee=z(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3`);ee.style.display=s?``:`none`;let k=r.chunks.join(``),A=z(`div`,`persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted`);return A.textContent=k||(r.status===`complete`?`No additional context was shared.`:`Waiting for details…`),ee.appendChild(A),fs({expanded:s,header:u,toggleIcon:D,content:ee,collapsedPreview:O,iconColor:E}),i.append(u,O,ee),_s(i,e,t,`reasoning`)};V(),Qe(),F();const Nm=e=>{if(e==null)return!0;if(typeof e==`string`){if(!e.trim())return!0;try{return Nm(JSON.parse(e))}catch{return!1}}return typeof e==`object`&&Object.keys(e).length===0},Pm=e=>{if(typeof e==`object`&&e)return!0;if(typeof e!=`string`)return!1;try{let t=JSON.parse(e);return typeof t==`object`&&!!t}catch{return!1}};function Fm(e,t,n){let r=t.toolCall;if(!r)return;let i=n.toolCall??{},a=(t,n)=>{let r=B(`section`,{className:`persona-tool-detail`,attrs:{"data-persona-tool-detail":t.toLowerCase()},style:{backgroundColor:i.codeBlockBackgroundColor,borderColor:i.codeBlockBorderColor,borderWidth:i.codeBlockBorderColor?`1px`:void 0}}),a=B(`div`,{className:`persona-tool-detail-label`,text:t,style:{color:i.labelTextColor}}),o=Ne(n),s=B(`pre`,{className:`persona-tool-detail-value${Pm(n)?` persona-tool-detail-code`:``}`,text:o,attrs:o.length>420||o.split(`
34
+ `).length>7?{tabindex:`0`,"aria-label":`${t} content`}:{},style:{color:i.codeBlockTextColor??i.contentTextColor}}),c=B(`button`,{className:`persona-tool-detail-copy`,attrs:{type:`button`,"data-persona-copy-tool-detail":``,"aria-label":`Copy ${t.toLowerCase()}`,title:`Copy ${t.toLowerCase()}`}}),l=P(`copy`,14,`currentColor`,1.7);l&&c.appendChild(l),r.append(a,s,c),e.appendChild(r)};Nm(r.args)||a(`Request`,r.args);let o=r.status===`complete`&&r.result!==void 0?r.result:r.chunks?.join(``);o!==void 0&&(typeof o!=`string`||o.trim())&&a(`Response`,o),r.success===!1&&e.appendChild(B(`div`,{className:`persona-text-sm persona-whitespace-pre-wrap`,text:r.error||`Tool failed`,attrs:{"data-persona-tool-error":``,role:`status`}}))}const Im=/* @__PURE__ */ new WeakMap;async function Lm(e){let t=e.closest(`[data-persona-tool-detail]`),n=t?.querySelector(`pre`);if(!n)return;let r=`Copy ${t?.getAttribute(`data-persona-tool-detail`)}`;clearTimeout(Im.get(e));try{await navigator.clipboard.writeText(n.textContent??``),e.dataset.copied=`true`,e.setAttribute(`aria-label`,`Copied`),e.title=`Copied`;let t=P(`check`,14,`currentColor`,2);t&&e.replaceChildren(t)}catch{e.setAttribute(`aria-label`,`Copy failed — try again`),e.title=`Copy failed — try again`}Im.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute(`aria-label`,r),e.title=r;let t=P(`copy`,14,`currentColor`,1.7);t&&e.replaceChildren(t),Im.delete(e)},1800))}V(),Ti(),Qe();const Rm=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?`currentColor`:`var(--persona-primary, #171717)`),zm=(e,t)=>{let n=e.toolCall;if(!n)return``;let r=(n.chunks??[]).join(``).trim();if(r)return r.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(-t).join(`
35
+ `);let i=Ne(n.args).trim();return i?i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,t).join(`
36
+ `):``},Bm=(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)`},Vm=(e,t)=>{let n=e.toolCall,r=t?.features?.toolCallDisplay,i=r?.collapsedMode??vi.collapsedMode,a=n?.success===!1?n.error||`Tool failed`:zm(e,r?.previewMaxLines??vi.previewMaxLines),o=n?.interrupted?`${n.name?.trim()||`Tool`} · Interrupted`:n?hs(t,`tool`)===`row`?`${n.status===`complete`?`Used`:`Using`} ${n.name?.trim()||`tool`}`:Re(n):``;if(!n)return{summary:o,previewText:a,isActive:!1};let s=n.status!==`complete`,c=t?.toolCall??{},l=o;return i===`tool-name`?l=n.name?.trim()||o:i===`tool-preview`&&a&&(l=a),s&&c.activeTextTemplate?l=He(n,c.activeTextTemplate,l):!s&&!n.interrupted&&c.completeTextTemplate&&(l=He(n,c.completeTextTemplate,l)),n.interrupted?l.includes(` · Interrupted`)||(l+=` · Interrupted`):n.success===!1?l+=` · Failed`:n.superseded&&(l+=` · Approved, ran again below`),{summary:l,previewText:a,isActive:s}},Hm=(e,t,n,r)=>{ps(e,t,{stateSet:n,previewKind:`tool`,iconColor:Rm(r?.toolCall??{},t.classList.contains(`persona-activity-row`))})},Um=(e,t,n=/* @__PURE__ */ new Set)=>{t=ms(t,`tool`);let r=e.toolCall,i=t?.toolCall??{},a=ss(`persona-tool-bubble`,e.id);if(i.backgroundColor&&(a.style.backgroundColor=i.backgroundColor),i.borderColor&&(a.style.borderColor=i.borderColor),i.borderWidth&&(a.style.borderWidth=i.borderWidth),i.borderRadius&&(a.style.borderRadius=i.borderRadius),a.style.boxShadow=i.shadow===void 0?`var(--persona-tool-bubble-shadow)`:i.shadow.trim()===``?`none`:i.shadow,!r)return _s(a,e,t,`tool`);let o=t?.features?.toolCallDisplay??{},s=o.expandable??vi.expandable,c=s&&n.has(e.id),{summary:l,previewText:u,isActive:d}=Vm(e,t),f=cs({expandable:s,expanded:c,bubbleType:`tool`});i.headerBackgroundColor&&(f.style.backgroundColor=i.headerBackgroundColor),i.headerPaddingX&&(f.style.paddingLeft=i.headerPaddingX,f.style.paddingRight=i.headerPaddingX),i.headerPaddingY&&(f.style.paddingTop=i.headerPaddingY,f.style.paddingBottom=i.headerPaddingY);let p=z(`div`,`persona-flex persona-flex-col persona-text-left`),m=z(`span`,`persona-text-xs persona-text-persona-primary`);i.headerTextColor&&(m.style.color=i.headerTextColor);let h=String(r.startedAt??Date.now()),g=()=>{let e=z(`span`,``);return d&&e.setAttribute(`data-tool-elapsed`,h),e.textContent=Be(r),e},_=i.renderCollapsedSummary?.({message:e,toolCall:r,defaultSummary:l,previewText:u,collapsedMode:o.collapsedMode??vi.collapsedMode,isActive:d,config:t??{},elapsed:Be(r),createElapsedElement:g});typeof _==`string`&&_.trim()?(m.textContent=_,p.appendChild(m)):_ instanceof HTMLElement?p.appendChild(_):(m.textContent=l,p.appendChild(m));let v=o.loadingAnimation??vi.loadingAnimation,y=i.activeTextTemplate,b=r.interrupted?void 0:i.completeTextTemplate,x=d?y:b,S=_ instanceof HTMLElement,C=(e,t)=>{m.textContent=``;let n=r.name?.trim()||`tool`,i=Ue(e,n),a=0;for(let e of i){let n=e.styles.length>0?(()=>{let t=z(`span`,e.styles.map(e=>`persona-tool-text-${e}`).join(` `));return m.appendChild(t),t})():m;if(e.isDuration&&d)n.appendChild(g());else{let i=e.isDuration?Be(r):e.text;t?a=km(n,i,a):n.appendChild(document.createTextNode(i))}}};if(!S){if(d&&v!==`none`){let e=i.loadingAnimationDuration??2e3;if(m.setAttribute(`data-preserve-animation`,`true`),v===`pulse`)m.classList.add(`persona-tool-loading-pulse`),m.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),x&&C(x,!1);else if(m.classList.add(`persona-tool-loading-${v}`),m.style.setProperty(`--persona-tool-anim-duration`,`${e}ms`),v===`shimmer-color`&&(i.loadingAnimationColor&&m.style.setProperty(`--persona-tool-anim-color`,i.loadingAnimationColor),i.loadingAnimationSecondaryColor&&m.style.setProperty(`--persona-tool-anim-secondary-color`,i.loadingAnimationSecondaryColor)),x)C(x,!0);else{let e=m.textContent||l;m.textContent=``,km(m,e,0)}}else x&&C(x,!1)}let w=Rm(i,hs(t,`tool`)===`row`),T=us(f,p,{expandable:s,expanded:c,iconColor:w,metaGap:!0}),E=ds({bubble:a,previewKind:`tool`,expanded:c,isActive:d,previewText:u,activePreview:o.activePreview,activeMinHeight:o.activeMinHeight,renderPreview:()=>i.renderCollapsedPreview?.({message:e,toolCall:r,defaultPreview:u,isActive:d,config:t??{}})});if(!s)return a.append(f,E),_s(a,e,t,`tool`);let D=z(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3`);if(D.style.display=c?``:`none`,i.contentBackgroundColor&&(D.style.backgroundColor=i.contentBackgroundColor),i.contentTextColor&&(D.style.color=i.contentTextColor),i.contentPaddingX&&(D.style.paddingLeft=i.contentPaddingX,D.style.paddingRight=i.contentPaddingX),i.contentPaddingY&&(D.style.paddingTop=i.contentPaddingY,D.style.paddingBottom=i.contentPaddingY),t.future?.v5Defaults===!0)Fm(D,e,t);else{if(r.name){let e=z(`div`,`persona-text-xs persona-text-persona-muted persona-italic`);i.contentTextColor?e.style.color=i.contentTextColor:i.headerTextColor&&(e.style.color=i.headerTextColor),e.textContent=r.name,D.appendChild(e)}if(r.args!==void 0){let e=z(`div`,`persona-space-y-1`),t=z(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Arguments`;let n=z(`pre`,`persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,Bm(n,i),n.textContent=Ne(r.args),e.append(t,n),D.appendChild(e)}if(r.chunks&&r.chunks.length){let e=z(`div`,`persona-space-y-1`),t=z(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Activity`;let n=z(`pre`,`persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,Bm(n,i),n.textContent=r.chunks.join(``),e.append(t,n),D.appendChild(e)}if(r.success===!1&&D.appendChild(B(`div`,{className:`persona-text-sm persona-whitespace-pre-wrap`,text:r.error||`Tool failed`,attrs:{"data-persona-tool-error":``}})),r.status===`complete`&&r.result!==void 0){let e=z(`div`,`persona-space-y-1`),t=z(`div`,`persona-text-xs persona-text-persona-muted`);i.labelTextColor&&(t.style.color=i.labelTextColor),t.textContent=`Result`;let n=z(`pre`,`persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs`);n.style.fontSize=`0.75rem`,n.style.lineHeight=`1rem`,Bm(n,i),n.textContent=Ne(r.result),e.append(t,n),D.appendChild(e)}if(r.status===`complete`&&typeof r.duration==`number`){let e=z(`div`,`persona-text-xs persona-text-persona-muted`);i.contentTextColor&&(e.style.color=i.contentTextColor),e.textContent=`Duration: ${r.duration}ms`,D.appendChild(e)}}return fs({expanded:c,header:f,toggleIcon:T,content:D,collapsedPreview:E,iconColor:w}),a.append(f,E,D),_s(a,e,t,`tool`)};g();const{setLoader:Wm,load:Gm,provide:Km,getSync:qm}=h({fallbackImport:()=>import(`@runtypelabs/persona/approval-ui`)}),Jm=Gm,Ym=qm;g();const{setLoader:Xm,load:Zm}=h({fallbackImport:()=>import(`@runtypelabs/persona/event-stream-view`)}),Qm=Zm,$m=new class{constructor(){this.components=/* @__PURE__ */ new Map,this.#e=/* @__PURE__ */ new Map}#e;register(e,t,n){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t),n?this.#e.set(e,n):this.#e.delete(e)}unregister(e){this.components.delete(e),this.#e.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.#e.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.#e.clear()}registerAll(e){Object.entries(e).forEach(([e,t])=>{this.register(e,t)})}};g(),ie();const eh=[`PersonaArtifactCard`,`PersonaArtifactInline`],{setLoader:th,load:nh,provide:rh,getSync:ih}=h({fallbackImport:()=>import(`@runtypelabs/persona/artifacts-ui`)});let ah=null;const oh=/* @__PURE__ */ new Set,sh=e=>{if(ah)return ah;ah=e,e.initArtifactsUi({componentRegistry:$m});for(let t of eh)$m.has(t)||$m.register(t,t===`PersonaArtifactCard`?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=O();t?e.__provideMarkdownParsers(t):E(()=>{let t=O();t&&e.__provideMarkdownParsers(t)}),e.__setIconsExtraLoader(()=>re());let n=[...oh];oh.clear();for(let e of n)try{e()}catch{}return e},ch=()=>nh().then(sh),lh=()=>{if(ah)return ah;let e=ih();return e?sh(e):null},uh=e=>ah?()=>{}:(oh.add(e),()=>{oh.delete(e)});function dh(e){return e?.features?.artifacts?.enabled===!0}function fh(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`),!dh(t))return;let n=t.features?.artifacts?.layout,r=n?.paneBorder?.trim(),i=n?.paneBorderLeft?.trim();r?(e.classList.add(`persona-artifact-border-full`),e.style.setProperty(`--persona-artifact-pane-border`,r)):i&&(e.classList.add(`persona-artifact-border-left`),e.style.setProperty(`--persona-artifact-pane-border-left`,i))}function ph(e){e.style.removeProperty(`--persona-artifact-doc-toolbar-icon-color`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-bg`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-border`)}const mh=[`panel`,`seamless`,`detached`];function hh(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&mh.includes(t)?t:t?`panel`:e.launcher?.detachedPanel?`detached`:`panel`}function gh(e){return!e||!dh(e)?!1:hh(e)===`detached`}function _h(e,t){if(!dh(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`),ph(e),fh(e,t);return}let n=t.features?.artifacts?.layout,r=hh(t)===`detached`?`var(--persona-panel-inset)`:`0`;e.style.setProperty(`--persona-artifact-split-gap`,n?.splitGap??r),e.style.setProperty(`--persona-artifact-pane-width`,n?.paneWidth??`40%`),e.style.setProperty(`--persona-artifact-pane-max-width`,n?.paneMaxWidth??`28rem`),n?.drawerWidth?e.style.setProperty(`--persona-artifact-drawer-width`,n.drawerWidth):e.style.removeProperty(`--persona-artifact-drawer-width`),n?.paneMinWidth?e.style.setProperty(`--persona-artifact-pane-min-width`,n.paneMinWidth):e.style.removeProperty(`--persona-artifact-pane-min-width`);let i=n?.paneBackground?.trim();i?e.style.setProperty(`--persona-artifact-pane-bg`,i):e.style.removeProperty(`--persona-artifact-pane-bg`);let a=n?.panePadding?.trim();a?e.style.setProperty(`--persona-artifact-pane-padding`,a):e.style.removeProperty(`--persona-artifact-pane-padding`);let o=[[n?.documentToolbarIconColor,`--persona-artifact-doc-toolbar-icon-color`],[n?.documentToolbarToggleActiveBackground,`--persona-artifact-doc-toggle-active-bg`],[n?.documentToolbarToggleActiveBorderColor,`--persona-artifact-doc-toggle-active-border`],[n?.documentToolbarToggleActiveColor,`--persona-artifact-doc-toggle-active-color`]];for(let[t,n]of o){let r=t?.trim();r?e.style.setProperty(n,r):e.style.removeProperty(n)}fh(e,t)}function vh(e,t){for(let t of mh)e.classList.remove(`persona-artifact-appearance-${t}`);if(e.style.removeProperty(`--persona-artifact-pane-radius`),e.style.removeProperty(`--persona-artifact-pane-shadow`),e.style.removeProperty(`--persona-artifact-chat-shadow`),!dh(t))return;let n=t.features?.artifacts?.layout,r=hh(t);e.classList.add(`persona-artifact-appearance-${r}`);let i=n?.paneBorderRadius?.trim();i&&e.style.setProperty(`--persona-artifact-pane-radius`,i);let a=n?.paneShadow?.trim();a&&e.style.setProperty(`--persona-artifact-pane-shadow`,a);let o=n?.chatShadow?.trim();o&&e.style.setProperty(`--persona-artifact-chat-shadow`,o)}function yh(e,t){return!t||!dh(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}je();const bh=/* @__PURE__ */ new Set([`__proto__`,`prototype`,`constructor`]),xh=/* @__PURE__ */ new Set([`collapsed`,`card`,`panel`,`inline`]),Sh=/* @__PURE__ */ new Set([`markdown`,`component`]),Ch=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,wh=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Th=e=>!bh.has(e),Eh=e=>typeof e==`string`&&xh.has(e),Dh=e=>Object.keys(e).length>0;function Oh(e,t,n,r){e.push({path:t,code:n,message:r})}const kh=`Ignored an unsupported value.`,Ah={kind:`mode`,message:kh},jh={kind:`string`,message:`Expected a CSS length string.`},Mh={kind:`boolean`},Nh={kind:`object`,message:`Expected a preference object.`,children:{showToolCalls:Mh,showReasoning:Mh,toolCallDisplay:{kind:`object`,children:{collapsedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`tool-call`,`tool-name`,`tool-preview`]),message:kh},groupedMode:{kind:`enum`,values:/* @__PURE__ */ new Set([`stack`,`summary`]),message:kh},loadingAnimation:{kind:`enum`,values:/* @__PURE__ */ new Set([`none`,`pulse`,`shimmer`,`shimmer-color`,`rainbow`]),message:kh},expandable:Mh,grouped:Mh}},reasoningDisplay:{kind:`object`,children:{expandable:Mh,activePreview:Mh}},artifacts:{kind:`object`,children:{display:{kind:`object`,bareMode:!0,message:`Expected an artifact display rules object.`,children:{default:Ah,files:{kind:`object`,bareMode:!0,message:`Expected collapsed, panel, inline, or a file display rules object.`,children:{default:Ah,byMediaType:{kind:`modeMap`,keys:`mediaType`}}},byType:{kind:`modeMap`,keys:Sh,alias:`byKind`,deprecated:`Use byKind. The legacy selector was normalized automatically.`},byKind:{kind:`modeMap`,keys:Sh}}},filePreview:{kind:`object`,children:{enabled:Mh}},layout:{kind:`object`,children:{paneWidth:jh,paneMaxWidth:jh,paneMinWidth:jh,expandedPanelWidth:jh,resizableMinWidth:jh,resizableMaxWidth:jh,expandLauncherPanelWhenOpen:Mh,resizable:Mh}}}}}};function Ph(e,t,n,r){if(e!==void 0)switch(t.kind){case`boolean`:return typeof e==`boolean`?e:Oh(r,n,`invalid_type`,`Expected a boolean.`);case`string`:return typeof e==`string`?e:Oh(r,n,`invalid_type`,t.message);case`enum`:return typeof e==`string`&&t.values.has(e)?e:Oh(r,n,`invalid_value`,t.message);case`mode`:return Eh(e)?Te(e):Oh(r,n,`invalid_value`,t.message);case`modeMap`:{if(!wh(e))return Oh(r,n,`invalid_type`,`Expected an object.`);let i=t.keys===`mediaType`?void 0:t.keys,a={};for(let[t,o]of Object.entries(e)){let e=i?t:Ee(t);Th(t)&&(i?i.has(t):Ch.test(e))?Eh(o)?a[e]=Te(o):Oh(r,`${n}.${t}`,`invalid_value`,`Expected collapsed, panel, or inline.`):Oh(r,`${n}.${t}`,i?`unknown_key`:`invalid_value`,i?`Ignored an unsupported selector.`:`Expected a MIME type such as "text/html" or a wildcard such as "image/*".`)}return Dh(a)?a:void 0}case`object`:{if(t.bareMode&&Eh(e))return Te(e);if(!wh(e))return Oh(r,n,`invalid_type`,t.message??`Expected an object.`);let i=Object.keys(t.children),a=e=>n?`${n}.${e}`:e;for(let t of Object.keys(e))(!Th(t)||!i.includes(t))&&Oh(r,a(t),`unknown_key`,`Ignored because this key is not part of the persisted preference schema.`);let o={};for(let n of i){let i=t.children[n],s=Ph(e[n],i,a(n),r);if(i.deprecated&&e[n]!==void 0&&Oh(r,a(n),`deprecated_key`,i.deprecated),s===void 0)continue;let c=i.alias??n,l=o[c];o[c]=wh(l)&&wh(s)?{...l,...s}:s}return Dh(o)?o:void 0}}}function Fh(e){let t=[];return{preferences:(e===null?void 0:Ph(e,Nh,``,t))??{},issues:t}}function Ih(e){if(Array.isArray(e))return e.map(Ih);if(!wh(e))return e;let t={};for(let[n,r]of Object.entries(e))Th(n)&&r!==void 0&&(t[n]=Ih(r));return t}function Lh(e,t){let n=Ih(e);for(let[e,r]of Object.entries(t)){if(!Th(e)||r===void 0)continue;let t=n[e];n[e]=wh(t)&&wh(r)?Lh(t,r):Ih(r)}return n}function Rh(e){let t={},n;for(let r of e){let e=Fh(r).preferences;n=Bh(n,e.artifacts?.display),t=Lh(t,e)}let r=t;return r.artifacts&&(n===void 0?delete r.artifacts.display:r.artifacts.display=n),r}function zh(e,t){if(t===void 0)return e===void 0?void 0:Ih(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byMediaType,...t.byMediaType},a={...r?{default:r}:{},...Dh(i)?{byMediaType:i}:{}};return Dh(a)?a:void 0}function Bh(e,t){if(t===void 0)return e===void 0?void 0:Ih(e);if(typeof t==`string`)return t;let n=typeof e==`string`?{default:e}:e??{},r=t.default??n.default,i={...n.byType,...n.byKind,...t.byType,...t.byKind},a=zh(n.files,t.files),o={...r?{default:r}:{},...Dh(i)?{byKind:i}:{},...a===void 0?{}:{files:a}};return Dh(o)?o:void 0}function Vh(e={},t){let n=Rh(t),r={...e};if(n.showToolCalls!==void 0&&(r.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(r.showReasoning=n.showReasoning),n.toolCallDisplay&&(r.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(r.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let t=e.artifacts??{},i={...t};if(n.artifacts.display!==void 0){let e=Bh(t.display,n.artifacts.display);e!==void 0&&(i.display=e)}n.artifacts.filePreview&&(i.filePreview={...t.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...t.layout,...n.artifacts.layout}),r.artifacts=i}return r}function Hh(e){let t=e.preferences;return!t||!Dh(t)?e:{...e,features:Vh(e.features??{},[t])}}function Uh(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 Wh(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 Gh(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Kh(e,t,n,r){let i=e-r-2*t-n;return Math.max(0,i)}function qh(e,t){let n=(t.getComputedStyle(e).gap||`0px`).trim().split(/\s+/)[0]??`0px`,r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let i=/^([\d.]+)/.exec(n);return i?Number(i[1]):8}function Jh(e,t,n,r,i,a,o=200){let s=Uh(i,200),c=Kh(t,n,r,o);c=Math.max(s,c);let l=Wh(a);return l!==null&&(c=Math.min(c,l)),Gh(e,s,c)}g();const{setLoader:Yh,load:Xh,provide:Zh,getSync:Qh}=h({fallbackImport:()=>import(`@runtypelabs/persona/forms-ui`)}),$h=Xh,eg=Qh,tg=new class{#e=/* @__PURE__ */ new Map;register(e){this.#e.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.#e.set(e.id,e),e.onRegister?.()}unregister(e){let t=this.#e.get(e);t&&(t.onUnregister?.(),this.#e.delete(e))}getAll(){return Array.from(this.#e.values()).sort((e,t)=>(t.priority??0)-(e.priority??0))}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let n=new Set(e.map(e=>e.id));return[...t.filter(e=>!n.has(e.id)),...e].sort((e,t)=>(t.priority??0)-(e.priority??0))}clear(){this.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}};Ti(),li(),ei();const ng=e=>typeof e==`object`&&!!e&&!Array.isArray(e),rg=/* @__PURE__ */ new Set([`headers`,`agent`,`storageAdapter`,`components`,`targetProviders`,`voiceRecognition.provider.custom`,`features.artifacts.display`,`features.streamAnimation.plugins`,`preferences`,`welcome.icon`]),ig=(e,t,n)=>{if(!ng(e)||!ng(t)||rg.has(n))return t;let r={...e};for(let i of Object.keys(t)){if(t[i]===void 0){delete r[i];continue}let a=n?`${n}.${i}`:i;r[i]=ig(e[i],t[i],a)}return r};function ag(e,t){let n=Gr(Ci),r=Xr(e,t,n),i=Jr(Zr(ig(e,t,``),n,r),r);return oi(pi(i),ci(e,t))}const og=()=>{let e=/* @__PURE__ */ new Map,t=(t,r)=>(e.has(t)||e.set(t,/* @__PURE__ */ new Set),e.get(t).add(r),()=>n(t,r)),n=(t,n)=>{e.get(t)?.delete(n)};return{on:t,off:n,emit:(t,n)=>{e.get(t)?.forEach(e=>{try{e(n)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Event handler error:`,e)}})}}},sg=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},cg=e=>{let t=e.trim(),n=t.indexOf(`{`);if(n===-1)return null;let r=0;for(let e=n;e<t.length;e+=1){let i=t[e];if(i===`{`&&(r+=1),i===`}`&&(--r,r===0))return t.slice(n,e+1)}return null},lg=({text:e})=>{if(!e||!e.includes(`{`))return null;try{let t=sg(e),n=cg(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!=`object`||!r.action)return null;let{action:i,...a}=r;return{type:String(i),payload:a,raw:r}}catch{return null}},ug=e=>typeof e==`string`?e:e==null?``:String(e),dg={message:e=>{if(e.type===`message`)return{handled:!0,displayText:ug(e.payload.text)}},messageAndClick:(e,t)=>{if(e.type!==`message_and_click`)return;let n=e.payload,r=ug(n.element);if(r&&t.document?.querySelector){let e=t.document.querySelector(r);e?setTimeout(()=>{e.click()},400):typeof console<`u`&&console.warn(`[AgentWidget] Element not found for selector:`,r)}return{handled:!0,displayText:ug(n.text)}}},fg=e=>Array.isArray(e)?e.map(e=>String(e)):[],pg=e=>{let t=new Set(fg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(fg(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let n=Array.from(t);e.updateSessionMetadata(e=>({...e,processedActionMessageIds:n}))};return{process:n=>{if(n.streaming||n.message.role!==`assistant`||!n.text||t.has(n.message.id))return null;let i=typeof n.raw==`string`&&n.raw||typeof n.message.rawContent==`string`&&n.message.rawContent||typeof n.text==`string`&&n.text||null;!i&&typeof n.text==`string`&&n.text.trim().startsWith(`{`)&&typeof console<`u`&&console.warn(`[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.`);let a=i?e.parsers.reduce((e,t)=>e||t?.({text:i,message:n.message})||null,null):null;if(!a)return null;t.add(n.message.id),r();let o={action:a,message:n.message};e.emit(`action:detected`,o);for(let t of e.handlers)if(t)try{let r=t(a,{message:n.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:()=>{e.emit(`action:resubmit`,o)}});if(!r)continue;if(r.handled){let e=r.persistMessage!==!1;return{text:r.displayText===void 0?``:r.displayText,persist:e,resubmit:r.resubmit}}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Action handler error:`,e)}return{text:``,persist:!0}},syncFromMetadata:n}},mg=e=>{if(!e)return null;try{return JSON.parse(e)}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] Failed to parse stored state:`,e),null}},hg=e=>e.map(e=>({...e,streaming:!1})),gg=e=>e.map(e=>({...e,status:`complete`})),_g=e=>`${e??`persona-`}state`,vg=(e=_g())=>{let t=()=>typeof window>`u`||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?mg(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let t={...n,messages:n.messages?hg(n.messages):void 0,artifacts:n.artifacts?gg(n.artifacts):void 0};r.setItem(e,JSON.stringify(t))}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to persist state:`,e)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to clear stored state:`,e)}}}},yg=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`)},bg=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let n=await t.digest(`SHA-256`,new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}catch{}return yg(e)},xg=async(e,t)=>{let n=await bg(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await bg(`${e}\0${t}`)}`}},Sg=(e,t,n)=>{let r=``,i=``,a=``,o=!1,s=!1,c=0,l=null,u=null,d=/* @__PURE__ */ new Set,f=()=>{if(n||o)return null;try{return typeof window>`u`||!window.localStorage?null:window.localStorage}catch{return o=!0,null}},p=()=>{let e=f();if(!e)return l;try{return e.getItem(r)}catch{return o=!0,l}},m=(e,t)=>{if(s||e===l)return;let n=l;l=e,c+=1;let r={previousToken:n,token:e,source:t,revision:c};for(let e of d)e(r)},h=e=>{s||(e.key===null||e.key===r)&&m(e.key===null?null:e.newValue??null,`external`)},g=(async()=>{let o=await xg(e,t);r=o.storageKey,i=o.leaseKey,a=o.lockName,l=p(),!n&&typeof window<`u`&&window.addEventListener(`storage`,h)})(),_=e=>new Promise(t=>setTimeout(t,e)),v=()=>{let e=f();if(!e)return null;try{let t=e.getItem(i);if(!t)return null;let n=JSON.parse(t);return typeof n?.expiresAt==`number`&&typeof n?.ownerNonce==`string`?n:null}catch{return null}},y=e=>{let t=f();if(t)try{v()?.ownerNonce===e&&t.removeItem(i)}catch{}},b=/* @__PURE__ */ new Set,x=e=>s?Promise.reject(/* @__PURE__ */ Error(`Visitor store destroyed before its first init could start`)):e(),S=e=>new Promise(t=>{let n=setTimeout(r,e);function r(){clearTimeout(n),b.delete(r),window.removeEventListener(`storage`,a),t()}function a(e){(e.key===null||e.key===i)&&r()}b.add(r),window.addEventListener(`storage`,a)}),C=async e=>{let t=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,n=Date.now()+15e3;for(;!s&&Date.now()<n;){let n=f();if(!n)break;let r=Date.now(),a=v();if(a&&a.expiresAt>r&&a.ownerNonce!==t)await S(Math.min(a.expiresAt-r,500));else{try{n.setItem(i,JSON.stringify({ownerNonce:t,expiresAt:r+1e4}))}catch{o=!0;break}if(await _(20+Math.random()*40),v()?.ownerNonce!==t)await S(500);else{u=t;try{return await x(e)}finally{u=null,y(t)}}}}return x(e)};return{ready:g,async get(){return await g,m(p(),`external`),l},async set(e){await g;let t=f();if(t)try{t.setItem(r,e)}catch{o=!0}m(e,`local`)},async clear(){await g;let e=f();if(e)try{e.removeItem(r)}catch{o=!0}m(null,`local`)},revision(){return c},subscribe(e){return d.add(e),()=>{d.delete(e)}},async withFirstInitLock(e){await g;let t=globalThis.navigator?.locks;return t?.request?t.request(a,()=>x(e)):f()?C(e):x(e)},matches(r,i,a){return r===e&&i===t&&a===n},destroy(){s=!0,d.clear(),typeof window<`u`&&window.removeEventListener(`storage`,h),u&&y(u);for(let e of[...b])e()}}};g();const{setLoader:Cg,load:wg}=h({fallbackImport:()=>import(`@runtypelabs/persona/history-view`)}),Tg=wg;function Eg(){return null}function Dg(e){if(!e||typeof e!=`object`||!(`component`in e))return!1;let t=e.component;return typeof t==`string`&&t.length>0}function Og(e,t){if(!Dg(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 kg(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith(`{`)&&!r.startsWith(`[`))return null;if(n.length<=t)return e;try{let t=Og((0,p.parse)(n,p.STR|p.OBJ),n);t&&(e=t)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Ag(e){return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`&&`props`in e&&typeof e.props==`object`}V();function jg(e,t){let{config:n,message:r,onPropsUpdate:i}=t,a=$m.get(e.component);if(!a){if(eh.includes(e.component)){ch().catch(()=>{});let e=z(`div`,`persona-w-full`);return e.setAttribute(`data-persona-artifact-pending`,`true`),e}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let o={message:r,config:n,updateProps:e=>{i&&i(e)}};try{return a(e.props,o)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function Mg(){let e=kg();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ng(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 Pg(e){let t=Ng(e);if(!t)return!1;try{let e=JSON.parse(t);return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`}catch{return!1}}function Fg(e){let t=Ng(e);if(!t)return null;try{let e=JSON.parse(t);if(typeof e==`object`&&e&&`component`in e&&typeof e.component==`string`){let n=e;return{component:n.component,props:n.props&&typeof n.props==`object`&&n.props!==null?n.props:{},raw:t}}}catch{}return null}const Ig=[`Very dissatisfied`,`Dissatisfied`,`Neutral`,`Satisfied`,`Very satisfied`];function Lg(e){let{onSubmit:t,onDismiss:n,title:r=`How satisfied are you?`,subtitle:i=`Please rate your experience`,commentPlaceholder:a=`Share your thoughts (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,ratingLabels:l=Ig}=e,u=document.createElement(`div`);u.className=`persona-feedback-container persona-feedback-csat`,u.setAttribute(`role`,`dialog`),u.setAttribute(`aria-label`,`Customer satisfaction feedback`);let d=null,f=document.createElement(`div`);f.className=`persona-feedback-content`;let p=document.createElement(`div`);p.className=`persona-feedback-header`;let m=document.createElement(`h3`);m.className=`persona-feedback-title`,m.textContent=r,p.appendChild(m);let h=document.createElement(`p`);h.className=`persona-feedback-subtitle`,h.textContent=i,p.appendChild(h),f.appendChild(p);let g=document.createElement(`div`);g.className=`persona-feedback-rating persona-feedback-rating-csat`,g.setAttribute(`role`,`radiogroup`),g.setAttribute(`aria-label`,`Satisfaction rating from 1 to 5`);let _=[];for(let e=1;e<=5;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-star-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`${e} star${e>1?`s`:``}: ${l[e-1]}`),t.title=l[e-1],t.dataset.rating=String(e),t.innerHTML=`
37
37
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
38
38
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
39
39
  </svg>
40
- `,t.addEventListener(`click`,()=>{d=e,_.forEach((t,n)=>{let r=n<e;t.classList.toggle(`selected`,r),t.setAttribute(`aria-checked`,n===e-1?`true`:`false`)})}),_.push(t),g.appendChild(t)}f.appendChild(g);let v=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,v=document.createElement(`textarea`),v.className=`persona-feedback-comment`,v.placeholder=a,v.rows=3,v.setAttribute(`aria-label`,`Additional comments`),e.appendChild(v),f.appendChild(e)}let y=document.createElement(`div`);y.className=`persona-feedback-actions`;let b=document.createElement(`button`);b.type=`button`,b.className=`persona-feedback-btn persona-feedback-btn-skip`,b.textContent=s,b.addEventListener(`click`,()=>{n?.(),u.remove()});let x=document.createElement(`button`);return x.type=`button`,x.className=`persona-feedback-btn persona-feedback-btn-submit`,x.textContent=o,x.addEventListener(`click`,async()=>{if(d===null)g.classList.add(`persona-feedback-shake`),setTimeout(()=>g.classList.remove(`persona-feedback-shake`),500);else{x.disabled=!0,x.textContent=`Submitting...`;try{let e=v?.value.trim()||void 0;await t(d,e),u.remove()}catch(e){x.disabled=!1,x.textContent=o,console.error(`[CSAT Feedback] Failed to submit:`,e)}}}),y.appendChild(b),y.appendChild(x),f.appendChild(y),u.appendChild(f),u}function jg(e){let{onSubmit:t,onDismiss:n,title:r=`How likely are you to recommend us?`,subtitle:i=`On a scale of 0 to 10`,commentPlaceholder:a=`What could we do better? (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,lowLabel:l=`Not likely`,highLabel:u=`Very likely`}=e,d=document.createElement(`div`);d.className=`persona-feedback-container persona-feedback-nps`,d.setAttribute(`role`,`dialog`),d.setAttribute(`aria-label`,`Net Promoter Score feedback`);let f=null,p=document.createElement(`div`);p.className=`persona-feedback-content`;let m=document.createElement(`div`);m.className=`persona-feedback-header`;let h=document.createElement(`h3`);h.className=`persona-feedback-title`,h.textContent=r,m.appendChild(h);let g=document.createElement(`p`);g.className=`persona-feedback-subtitle`,g.textContent=i,m.appendChild(g),p.appendChild(m);let _=document.createElement(`div`);_.className=`persona-feedback-rating persona-feedback-rating-nps`,_.setAttribute(`role`,`radiogroup`),_.setAttribute(`aria-label`,`Likelihood rating from 0 to 10`);let v=document.createElement(`div`);v.className=`persona-feedback-labels`;let y=document.createElement(`span`);y.className=`persona-feedback-label-low`,y.textContent=l;let b=document.createElement(`span`);b.className=`persona-feedback-label-high`,b.textContent=u,v.appendChild(y),v.appendChild(b);let x=document.createElement(`div`);x.className=`persona-feedback-numbers`;let S=[];for(let e=0;e<=10;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-number-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`Rating ${e} out of 10`),t.textContent=String(e),t.dataset.rating=String(e),e<=6?t.classList.add(`persona-feedback-detractor`):e<=8?t.classList.add(`persona-feedback-passive`):t.classList.add(`persona-feedback-promoter`),t.addEventListener(`click`,()=>{f=e,S.forEach((t,n)=>{t.classList.toggle(`selected`,n===e),t.setAttribute(`aria-checked`,n===e?`true`:`false`)})}),S.push(t),x.appendChild(t)}_.appendChild(v),_.appendChild(x),p.appendChild(_);let C=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,C=document.createElement(`textarea`),C.className=`persona-feedback-comment`,C.placeholder=a,C.rows=3,C.setAttribute(`aria-label`,`Additional comments`),e.appendChild(C),p.appendChild(e)}let w=document.createElement(`div`);w.className=`persona-feedback-actions`;let T=document.createElement(`button`);T.type=`button`,T.className=`persona-feedback-btn persona-feedback-btn-skip`,T.textContent=s,T.addEventListener(`click`,()=>{n?.(),d.remove()});let E=document.createElement(`button`);return E.type=`button`,E.className=`persona-feedback-btn persona-feedback-btn-submit`,E.textContent=o,E.addEventListener(`click`,async()=>{if(f===null)x.classList.add(`persona-feedback-shake`),setTimeout(()=>x.classList.remove(`persona-feedback-shake`),500);else{E.disabled=!0,E.textContent=`Submitting...`;try{let e=C?.value.trim()||void 0;await t(f,e),d.remove()}catch(e){E.disabled=!1,E.textContent=o,console.error(`[NPS Feedback] Failed to submit:`,e)}}}),w.appendChild(T),w.appendChild(E),p.appendChild(w),d.appendChild(p),d}Br(),ea(),_a(),xa(),pa(),Ui(),Ur(),I(),A(),H(),Ir(),gr(),To(),dn(),da(),Gt(),nn(),Ze(),Ce(),Ae(),wi(),ci();const Mg=`persona-chat-history`,Ng=`data-persona-composer-reason`,Pg=`data-persona-composer-notice`,Fg={"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 Ig(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let e of n){if(e.kind!==`file`||!e.type.startsWith(`image/`))continue;let n=e.getAsFile();if(!n)continue;if(n.name){t.push(n);continue}let r=Fg[n.type]??`png`;t.push(new File([n],`clipboard-image-${Date.now()}.${r}`,{type:n.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let n of Array.from(e.files??[]))n.type.startsWith(`image/`)&&t.push(n);return t}function Lg(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 Rg(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 zg(e){try{let t=e===`local`?localStorage:sessionStorage,n=`__persist_test__`;return t.setItem(n,`1`),t.removeItem(n),t}catch{return null}}const Bg=e=>!e||typeof e!=`object`?{}:{...e},Vg=e=>e.map(e=>({...e,streaming:!1})),Hg=(e,t,n)=>{let r=e?.markdown?ys(e.markdown):null,i=js(e?.sanitize);e?.postprocessMessage&&i&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let a=!1,o=a=>{let o=a.text??``,s=a.message.rawContent??null;if(t){let e=t.process({text:o,raw:s??o,message:a.message,streaming:a.streaming});e!==null&&(o=e.text,e.persist||(a.message.__skipPersist=!0),e.resubmit&&!a.streaming&&n&&n())}let c=O()!==null,l;if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:o,raw:s??a.text??``});l=i?i(t):t}else if(r){let e=a.streaming?Rs(o):o,t=r(e);l=i&&c?i(t):t}else l=Ss(o);return l};return e=>{try{return o(e)}catch(t){return a||(a=!0,console.error(`[Persona] markdown rendering failed; falling back to plain text:`,t)),Ss(e.text??``)}}};function Ug(e){let t=B(`div`,`persona-attachment-drop-overlay`);e?.background&&t.style.setProperty(`--persona-drop-overlay-bg`,e.background),e?.backdropBlur!==void 0&&t.style.setProperty(`--persona-drop-overlay-blur`,e.backdropBlur),e?.border&&t.style.setProperty(`--persona-drop-overlay-border`,e.border),e?.borderRadius&&t.style.setProperty(`--persona-drop-overlay-radius`,e.borderRadius),e?.inset&&t.style.setProperty(`--persona-drop-overlay-inset`,e.inset),e?.labelSize&&t.style.setProperty(`--persona-drop-overlay-label-size`,e.labelSize),e?.labelColor&&t.style.setProperty(`--persona-drop-overlay-label-color`,e.labelColor);let n=e?.iconName??`upload`,r=e?.iconSize??`48px`,i=e?.iconColor??`rgba(59, 130, 246, 0.6)`,a=e?.iconStrokeWidth??.5,o=F(n,r,i,a);if(o&&t.appendChild(o),e?.label){let n=B(`span`,`persona-drop-overlay-label`);n.textContent=e.label,t.appendChild(n)}return t}const Wg=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t?{...t,...r}:r}return n},Gg=e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:Wg(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}),Kg=(e,t,n)=>{if(e==null)throw Error(`createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).`);e.id&&!e.getAttribute(`data-persona-instance`)&&e.setAttribute(`data-persona-instance`,e.id),e.hasAttribute(`data-persona-root`)||e.setAttribute(`data-persona-root`,`true`);let r=fi(t),i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=ds((e,t)=>{ca.delete(e);let n=Array.from(K.querySelectorAll(`[data-message-id]`)).find(t=>t.dataset.messageId===e);n&&(t===`tool`?Im(e,n,i,r):Tm(e,n,a))}),s=/* @__PURE__ */ new Map,c=()=>{_r({delayMs:r.tooltip?.delayMs??200,skipDelayMs:r.tooltip?.skipDelayMs??300})};c();let l=r.features;r=Ih(r);let u=Yh.getForInstance(r.plugins),d=wo(e),p=[],m=!1,h=Sm(()=>r),g=null,_=null,v=null,y=!1,b=null,x=e=>{g=e,e.initApprovalUi({webMcpToolTitle:be});let t=e.createBuiltInApprovalPlugin(s);_=t.plugin,v=t.teardown},S=()=>{if(g)return g;let e=Um();return e?(x(e),e):(Hm().then(e=>{y||g||(x(e),b?.())}).catch(()=>{}),null)},C=!1,w=!1,D=null,ee=(e,t,n,r)=>{if(!e.querySelector(`[data-tv-form]`))return;let i=Jh();i?i.enhanceWithForms(e,t,n,r):qh().then(()=>{C||w||!D||(w=!0,D())}).catch(()=>{})};r.components&&qm.registerAll(r.components);let A=eg(),j=r.persistState===!1?null:r.storageAdapter??dg(),te=!!r.clientToken&&typeof r.reconnectStream!=`function`,ne={},re=null,ie,M=new Promise(e=>{ie=e}),N=()=>{},P=new Promise(e=>{N=e}),ae,oe=!1,se=e=>{if(r.onStateLoaded)try{let t=r.onStateLoaded(e);if(t&&typeof t==`object`&&`state`in t){let{state:e,open:n}=t;return n&&(oe=!0),e}return t}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}return e};if(j?.load)try{let e=j.load();if(e&&typeof e.then==`function`)re=e.then(e=>se(e??{messages:[],metadata:{}}));else{let t=se(e??{messages:[],metadata:{}});t.metadata&&(ne=Bg(t.metadata)),t.messages?.length&&(r={...r,initialMessages:t.messages}),t.artifacts?.length&&(r={...r,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),ae=t.draft}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to load stored state:`,e)}else if(r.onStateLoaded)try{let e=se({messages:[],metadata:{}});e.messages?.length&&(r={...r,initialMessages:e.messages})}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}re||ie();let le=()=>ne,ue=e=>{ne=e({...ne})??{},ro()},de=r.actionParsers&&r.actionParsers.length?r.actionParsers:[rg],fe=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ag.message,ag.messageAndClick],pe=sg({parsers:de,handlers:fe,getSessionMetadata:le,updateSessionMetadata:ue,emit:A.emit,documentRef:typeof document<`u`?document:null});pe.syncFromMetadata();let me=r.launcher?.enabled??!0,I=r.launcher?.autoExpand??!1,he=r.autoFocusInput??!1,ge=I,_e=me,ve=r.layout?.header?.layout,ye=!1,L=()=>wf(r),R=()=>me||L(),z=L()?!1:!me||I,xe=!1,Se=null,Ce=()=>{xe=!0,Se&&clearTimeout(Se),Se=setTimeout(()=>{xe&&=(typeof console<`u`&&console.warn(`[AgentWidget] Resubmit requested but no injection occurred within 10s`),!1)},1e4)},we=Hg(r,pe,Ce),Te=r.features?.showReasoning??!0,Ee=r.features?.showToolCalls??!0,De=r.features?.showEventStreamToggle??!1,ke=r.features?.scrollToBottom??{},Ae=r.features?.scrollBehavior??{},je=()=>(typeof r.persistState==`object`?r.persistState?.keyPrefix:void 0)??`persona-`,Me=`${je()}event-stream`,Ne=null,Pe=r.features?.eventStream?.maxEvents??2e3,Ie=null,Le=null,ze=null,Be=!1,Ve=null,He=!1,Ue=null,We=0,Ge=(e,t)=>{Ie?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},Ke=(e,t)=>{Le?.processEvent(e,t),Ie?Ge(e,t):ze&&(ze.length>=Pe&&ze.shift(),ze.push({type:e,payload:t}))},qe=()=>{!Ie&&De&&(ze??=[],Km().then(e=>{if(Be||Ie||!De)return;Ne=new e.EventStreamStore(Me),Ie=new e.EventStreamBuffer(Pe,Ne),Le??=new e.ThroughputTracker,Ne.open().then(()=>Ie?.restore()).catch(e=>{r.debug&&console.warn(`[AgentWidget] IndexedDB not available for event stream:`,e)});let t=ze??[];ze=null;for(let e of t)Le?.processEvent(e.type,e.payload),Ge(e.type,e.payload)}).catch(()=>{}))};De&&qe();let Je=!1,Ye=null,Xe=()=>{},Ze=()=>{},V=()=>{},Qe=()=>{},H=()=>{},$e=()=>He||Je&&Ye===`panel`,et={onCopy:e=>{A.emit(`message:copy`,e),$?.isClientTokenMode()&&$.submitMessageFeedback(e.id,`copy`).catch(e=>{r.debug&&console.error(`[AgentWidget] Failed to submit copy feedback:`,e)}),r.messageActions?.onCopy?.(e)},onFeedback:e=>{A.emit(`message:feedback`,e),$?.isClientTokenMode()&&$.submitMessageFeedback(e.messageId,e.type).catch(e=>{r.debug&&console.error(`[AgentWidget] Failed to submit feedback:`,e)}),r.messageActions?.onFeedback?.(e)}};r.statusIndicator;let tt=(e,t=r.statusIndicator??{})=>e===`idle`?t.idleText??cn.idle:e===`connecting`?t.connectingText??cn.connecting:e===`connected`?t.connectedText??cn.connected:e===`error`?t.errorText??cn.error:e===`paused`?t.pausedText??cn.paused:e===`resuming`?t.resumingText??cn.resuming:cn[e];function nt(e,t,n,r){if(!L()&&(n.mode===`transient`||e.classList.contains(`persona-mb-2`))&&(zr(e,ut,n),Rr(e,n,r)),!(e.hasAttribute(Ng)||e.hasAttribute(Pg))){if(r===`idle`&&n.idleLink){e.textContent=``;let r=document.createElement(`a`);r.href=n.idleLink,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=t,r.style.color=`inherit`,r.style.textDecoration=`none`,e.appendChild(r)}else e.textContent=t}}let rt=vm({config:r,showClose:R()}),{wrapper:it,panel:U,pillRoot:at}=rt.shell,ot=rt.panelElements,{container:W,body:G,messagesWrapper:K,starterSuggestions:st,transcriptSuggestions:ct,suggestions:lt,textarea:q,sendButton:J,composerForm:ut,statusText:dt,welcomeHost:ft,welcomeIconHolder:mt,greetingHost:gt,introKicker:_t,introTitle:vt,introSubtitle:yt,closeButton:Y,iconHolder:bt,headerTitle:xt,headerSubtitle:St,header:Ct,footer:wt,actionsRow:Tt}=ot,Et=ot.leftActions,Dt=ot.rightActions,Ot=ot.sendButtonWrapper,kt=ot.setSendButtonMode,X=ot.micButton,At=ot.micButtonWrapper,jt=ot.attachmentButton,Mt=ot.attachmentButtonWrapper,Nt=ot.attachmentInput,Pt=ot.attachmentPreviewsContainer;W.classList.add(`persona-relative`),G.classList.add(`persona-relative`);let Ft=()=>ke.label??``,It=()=>ke.iconName??`arrow-down`,Lt=()=>ke.enabled!==!1,Rt=()=>Ae.mode??`anchor-top`,zt=()=>Rt()===`follow`||Rt()===`anchor-top`&&ja,Ht=()=>Ae.anchorTopOffset??16,Ut=()=>Ae.restorePosition??`bottom`,Wt=()=>Ae.pauseOnInteraction===!0,Gt=()=>Ae.showActivityWhilePinned!==!1,Kt=()=>Ae.announce===!0,qt=()=>Ae.scrollbar??`on-scroll`,Jt=B(`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`);Jt.type=`button`,Jt.style.display=`none`,Jt.setAttribute(`data-persona-scroll-to-bottom`,`true`);let Yt=B(`span`,`persona-flex persona-items-center`),Zt=B(`span`,``),$t=B(`span`,``);$t.setAttribute(`data-persona-scroll-to-bottom-count`,``),$t.style.display=`none`,Jt.append(Yt,Zt,$t),W.appendChild(Jt);let en=B(`div`,`persona-stream-anchor-spacer`);en.setAttribute(`aria-hidden`,`true`),en.setAttribute(`data-persona-anchor-spacer`,``),en.style.flexShrink=`0`,en.style.pointerEvents=`none`,en.style.height=`0px`,en.style.display=`none`,G.appendChild(en);let nn=B(`div`,`persona-sr-only`);nn.setAttribute(`aria-live`,`polite`),nn.setAttribute(`aria-atomic`,`true`),nn.setAttribute(`role`,`status`),nn.setAttribute(`data-persona-live-region`,``),Object.assign(nn.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`}),W.appendChild(nn);let rn=null,an=null,on=e=>{Kt()&&e&&(an=e,rn===null&&(rn=setTimeout(()=>{rn=null,an&&Kt()&&(nn.textContent=an),an=null},400)))},sn=()=>{let t=e.ownerDocument.defaultView??window;return(r.launcher?.mobileFullscreen??!0)&&t.innerWidth<=(r.launcher?.mobileBreakpoint??640)&&(me||Cf(r))||r.launcher?.fullHeight===!0&&!r.launcher.sidebarMode&&!Cf(r)},ln=()=>Zp(r,sn()),un=`empty`,dn=0,fn=()=>dn||parseFloat(e.style.getPropertyValue(`--persona-composer-lift`))||0,pn=()=>{let e=wt.style.display===`none`?0:wt.offsetHeight;Jt.style.bottom=`${e+fn()+12}px`};pn();let mn=()=>{Jn||(wt.style.marginBottom=dn>0?`${dn}px`:``)},hn=()=>{let t=xd(r,L()),n=ln();e.setAttribute(`data-persona-welcome-fullscreen`,String(sn())),e.setAttribute(`data-persona-welcome-layout`,n.layout??`top`),e.setAttribute(`data-persona-welcome-layout-explicit`,r.welcome?.layout??``),e.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`);let i=wt.style.display===`none`?0:wt.offsetHeight,a=n.anchor===`center`&&un===`empty`?Sd(n.anchorComposerTop)??Sd(`44%`):null,o=a!==null&&n.layout===`centered`&&r.welcome?.anchor===void 0&&r.welcome?.anchorComposerTop===void 0,s=o?getComputedStyle(G):null,c=parseFloat(e.style.getPropertyValue(`--persona-composer-overlay-height`))||0,l=parseFloat(e.style.getPropertyValue(`--persona-composer-lift`))||0,u=Math.max(0,(parseFloat(s?.paddingBottom??``)||0)-(t===`overlay`?c+l:0)),d=o?G.getBoundingClientRect().top-W.getBoundingClientRect().top:0,f=!o||ft.hidden?0:(ft.querySelector(`[data-persona-welcome-plugin]`)??ft).offsetHeight,p=a===null||L()?0:o?Math.max(0,Math.round((W.clientHeight-d-f-u-i)/2)):Cd({columnHeight:W.clientHeight,footerHeight:i,fraction:a});e.style.setProperty(`--persona-composer-overlay-height`,`${i}px`),e.style.setProperty(`--persona-composer-lift`,`${t===`overlay`?p:0}px`),dn=t===`block`?p:0,mn(),pn()},gn=()=>{let e=!!Ft();Jt.setAttribute(`aria-label`,Ft()||`Jump to latest`),Jt.title=Ft(),Jt.setAttribute(`data-persona-scroll-to-bottom-has-label`,e?`true`:`false`),Yt.innerHTML=``;let t=F(It(),`14px`,`currentColor`,2);t?(Yt.appendChild(t),Yt.style.display=``):Yt.style.display=`none`,Zt.textContent=Ft(),Zt.style.display=e?``:`none`};gn();let _n=null,vn=null,Z=fl();Z.subscribe(e=>{try{W.dispatchEvent(new CustomEvent(`persona:composer:state`,{detail:e,bubbles:!0,composed:!0}))}catch{}});let yn=()=>{Z.setText(q?.value??``)},bn=()=>{Z.setMentionRefs(vn?.getMentionRefs()??[])},xn=e=>({id:e.id,name:e.file.name,mimeType:e.file.type,size:e.file.size,status:e.status,progress:e.progress,error:e.error}),Sn=e=>{let t=Object.freeze(e.map(xn));Z.setAttachments(t);try{r.attachments?.onChange?.(t)}catch(e){console.error(`[AgentWidget] attachments.onChange failed:`,e)}Es()};Z.setSelectedModelId(r.composer?.selectedModelId);let Cn=()=>r.composer?.modes??[],wn=()=>tu(Cn(),r.composer?.modeGroups);{let e=iu(r.composer?.defaultActiveModeIds??[],Cn());e.length&&Z.setActiveModeIds(e)}function En(e){if(Z.getState().selectedModelId!==e){Z.setSelectedModelId(e),kn?.repaint();try{r.composer?.onModelChange?.(e)}catch(e){console.error(`[AgentWidget] composer.onModelChange failed:`,e)}}}function Dn(e){Z.setActiveModeIds(e),jn?.render(e,wn()),Mn.forEach(e=>e.repaint()),or?.resolve(),nc(),mr()}function On(e){Dn(ru(Z.getState().activeModeIds,e,Cn(),r.composer?.modeGroups))}let kn=null,An=null,jn=null,Mn=/* @__PURE__ */ new Map,Nn=null;function Pn(e){Z.setQuote(e),Nn?.render(Z.getState().quote),mr(),so()}let Fn=!1;function In(){let e=r.composer?.streamingSubmitBehavior??`block`;return e===`interrupt`?r.clientToken?`interrupt`:(!Fn&&r.debug===!0&&(Fn=!0,typeof console<`u`&&console.warn(`[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".`)),`block`):e}let Ln=null;function Rn(e){Z.setPendingSubmission(e),Ln?.render(Z.getState().pendingSubmission),mr()}let zn=e=>{let t=Mn.get(e);if(t)return t;let n=su({groupId:e,getGroup:()=>r.composer?.modeGroups?.find(t=>t.id===e),getModes:()=>Cn().filter(t=>t.groupId===e),getActiveIds:()=>Z.getState().activeModeIds,onSelect:e=>On(e)});return Mn.set(e,n),n},Bn=()=>{let e=[],t=Z.getState().activeModeIds,n=/* @__PURE__ */ new Set;if(Cn().forEach((i,a)=>{if($l(i.groupId,r.composer?.modeGroups)){let t=i.groupId;if(n.has(t))return;n.add(t);let o=zn(t);o.action.order=Zl(a),o.action.label=r.composer?.modeGroups?.find(e=>e.id===t)?.label??t,e.push(o.action)}else e.push({id:Xl(i.id),kind:`button`,placement:`start`,order:Zl(a),presentation:i.presentation??`auto`,label:i.label,shortLabel:i.shortLabel,iconName:i.iconName,pressed:t.includes(i.id),onSelect:()=>On(i.id)})}),r.composer?.models?.length&&!u.some(e=>e.renderComposer)){let t=r.composer?.modelPicker?.presentation??`native`;(!kn||An!==t)&&(An=t,kn=Gl({getModels:()=>r.composer?.models??[],getSelectedModelId:()=>Z.getState().selectedModelId,onSelect:e=>En(e),presentation:t,getSuffix:()=>r.composer?.modelPicker?.suffix})),e.push(kn.action)}return e},Vn=null,Hn=u.find(e=>e.renderHeader);if(Hn?.renderHeader){let e=Hn.renderHeader({config:r,defaultRenderer:()=>{let e=Uf({config:r,showClose:R()});return Wf(W,e,r),e.header},onClose:()=>ys(!1,`user`)});if(e){let t=Ct;t&&(t.replaceWith(e),Ct=e,rt.header.element=e)}}let Un=()=>{Ve&&(G.style.display=`none`,wt.parentNode?.insertBefore(Ve.element,wt),Ve.update())},Wn=()=>{if(!Ie){qe();return}if(He=!0,Ve?Un():Km().then(e=>{!Ve&&He&&Ie&&(Ve=e.createEventStreamView({buffer:Ie,getFullHistory:()=>Ie.getAllFromStore(),onClose:()=>Gn(),config:r,plugins:u,getThroughput:()=>Le?.getMetric()??{status:`idle`},renderIconByName:F}),Un())}).catch(()=>{Gn()}),Kn){Kn.style.boxShadow=`inset 0 0 0 1.5px ${Bf.actionIconColor}`;let e=r.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&Kn.classList.add(e))}let e=()=>{if(!He)return;let t=Date.now();t-We>=200&&(Ve?.update(),We=t),Ue=requestAnimationFrame(e)};We=0,Ue=requestAnimationFrame(e),So(),A.emit(`eventStream:opened`,{timestamp:Date.now()})},Gn=()=>{if(He){if(He=!1,Ve&&Ve.element.remove(),G.style.display=``,Kn){Kn.style.boxShadow=``;let e=r.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&Kn.classList.remove(e))}Ue!==null&&(cancelAnimationFrame(Ue),Ue=null),So(),A.emit(`eventStream:closed`,{timestamp:Date.now()})}},Kn=null;if(De){let e=r.features?.eventStream?.classNames,t=`persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1`+(e?.toggleButton?` `+e.toggleButton:``);Kn=B(`button`,t),Kn.style.width=`28px`,Kn.style.height=`28px`,Kn.style.color=Bf.actionIconColor,Kn.type=`button`,Kn.setAttribute(`aria-label`,`Event Stream`),Kn.title=`Event Stream`;let n=k(f.Activity,`18px`,`currentColor`,1.5);n&&Kn.appendChild(n);let i=ot.clearChatButtonWrapper,a=ot.closeButtonWrapper,o=i||a;o&&o.parentNode===Ct?Ct.insertBefore(Kn,o):Ct.appendChild(Kn),Kn.addEventListener(`click`,()=>{He?Gn():Wn()})}let qn=e=>{let t=r.attachments;if(!t?.enabled)return;let n=e.querySelector(`[data-persona-composer-attachment-previews]`)??e.querySelector(`.persona-attachment-previews`);if(!n){n=B(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),n.setAttribute(`data-persona-composer-attachment-previews`,``),n.style.display=`none`;let t=e.querySelector(`[data-persona-composer-form]`);t?.parentNode?t.parentNode.insertBefore(n,t):e.insertBefore(n,e.firstChild)}if(!(e.querySelector(`[data-persona-composer-attachment-input]`)??e.querySelector(`input[type="file"]`))){let n=B(`input`);n.type=`file`,n.setAttribute(`data-persona-composer-attachment-input`,``),n.accept=(t.allowedTypes??Hi).join(`,`),n.multiple=(t.maxFiles??4)>1,n.style.display=`none`,n.setAttribute(`aria-label`,t.buttonTooltipText??`Attach files`),e.appendChild(n)}},Jn=!1,Yn=e=>{let t=u.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let n=r.composer,i=m?$.isStreaming():!1;return t.renderComposer({config:r,defaultRenderer:e,requestRender:()=>af(),storage:h(t.id),onSubmit:e=>{$&&!$.isStreaming()&&Nl(e.trim(),{consumeDraft:!1})},streaming:i,disabled:i,openAttachmentPicker:()=>{xs()||Nt?.click()},models:n?.models,selectedModelId:Z.getState().selectedModelId??n?.selectedModelId,onModelChange:e=>En(e),onVoiceToggle:r.voiceRecognition?.enabled===!0?()=>{Vn?.()}:void 0})},Xn=Yn(()=>rp({config:r}).footer);Xn&&(rt.replaceComposer(Xn),wt=rt.composer.footer,Jn=!0);let Zn=null,Qn=e=>{ut=e.form,q=e.input,Ot=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(J=e.sendButton),e.micButton&&(X=e.micButton,At=e.micButton.parentElement),e.found.status&&(dt=e.found.status),e.found.suggestions&&(lt=e.found.suggestions),e.attachmentButton&&(jt=e.attachmentButton,Mt=e.attachmentButton.parentElement),Nt=e.attachmentInput??null,Pt=e.attachmentPreviews??null,e.found.actionsRow&&(Tt=e.found.actionsRow),Et=e.found.actionsStart,Dt=e.found.actionsEnd};function $n(){let e=q;if(!e)return;let t=r.composer?.inputAttributes,n=!t?.ariaLabel&&!(e instanceof HTMLTextAreaElement)?e.getAttribute(`aria-label`):null;Qi(e,t),n&&e.setAttribute(`aria-label`,n),Zi(e,{submitKey:r.composer?.submitKey,insertNewlineOnTouchEnter:r.composer?.insertNewlineOnTouchEnter,coarsePointer:qi(e)}),Ki(e,Gi(r.composer?.maxLines,L()?5:3))}let er=e=>{Zn=hl(e,{debug:r.debug===!0}),Zn&&Qn(Zn),$n()};qn(wt),er(wt),yn();let tr=bd(r,L());tr&&(K.style.maxWidth=tr,K.style.marginLeft=`auto`,K.style.marginRight=`auto`,K.style.width=`100%`,gt.style.maxWidth=tr,gt.style.marginLeft=`auto`,gt.style.marginRight=`auto`,gt.style.width=`100%`,st.style.maxWidth=tr,ct.style.maxWidth=tr,ct.style.marginLeft=`auto`,ct.style.marginRight=`auto`,ct.style.width=`100%`);let nr=()=>{let e=bd(r,L());if(e&&!L())for(let t of[ut,lt,Pt,dt])t&&(t.style.maxWidth=e,t.style.marginLeft=`auto`,t.style.marginRight=`auto`,t.style.width=`100%`)};nr();let rr=()=>{r.attachments?.enabled&&Nt&&Pt&&(_n?_n.remountPreviews(Pt):(_n=ll.fromConfig(r.attachments,Sn),_n.setPreviewsContainer(Pt)),Zn?.addListener(Nt,`change`,e=>{let t=e.target;_n?.handleFileSelect(t.files),t.value=``}),W.querySelector(`.persona-attachment-drop-overlay`)||W.appendChild(Ug(r.attachments.dropOverlay)))};rr();let ir=()=>vn?.prefetch(),ar=()=>{if(!r.contextMentions?.enabled||!q)return;let e=Fa();if(!e){let e=q;Na().then(()=>{!vn&&q===e&&e.isConnected&&(ar(),or?.resolve())},()=>{});return}let t=Zn?.header??null,n=t?Jl(t):void 0;if(vn=e.createContextMentionOrchestrator({deps:{loadContextMentions:ga,loadContextMentionsInline:ba,renderLucideIcon:F,createMentionButton:fa},config:r,textarea:q,anchor:ut??q,getMessages:()=>$.getMessages(),liveRegionHost:W,chipRow:n}),vn&&!n){let e=q;e.parentElement?.insertBefore(vn.contextRow,e)}};ar();let or=null,sr={getState:()=>Z.getState(),getValue:()=>q?.value??``,setValue:e=>{q&&(q.value=e,q.dispatchEvent(new Event(`input`,{bubbles:!0})),yn())},submit:()=>{_u(Zn?.form??null)},openAttachmentPicker:()=>{xs()||Nt?.click()},toggleVoice:()=>{Vn?.()},requestRender:()=>or?.resolve()},cr=()=>{let e=[];return(vn?.affordanceButtons??[]).forEach((t,n)=>{e.push({id:`core:mention-${n}`,placement:`start`,order:wl.mention+n,element:t,managed:!0})}),Mt&&e.push({id:`core:attachment`,placement:`start`,order:wl.attachment,element:Mt}),At&&e.push({id:`core:mic`,placement:`end`,order:wl.mic,element:At}),Ot&&e.push({id:`core:send`,placement:`end`,order:wl.send,element:Ot}),e},lr=()=>{or?.destroy(),or=Hl({getBindings:()=>Zn,collect:()=>({builtIns:cr(),configActions:[...Bn(),...r.composer?.actions??[]],plugins:u,contributionContext:{config:r,getState:()=>Z.getState(),requestRender:()=>or?.resolve()},debug:r.debug===!0}),actionContext:sr,getState:()=>Z.getState(),getOverflow:()=>r.composer?.actionOverflow,reportError:(e,t)=>{typeof console<`u`&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),or.resolve()};lr();let ur=()=>{if(jn?.destroy(),jn=null,!wn().length)return;let e=Zn?.header;e&&(jn=Yl({row:Jl(e),onRemove:e=>On(e),initialIds:Z.getState().activeModeIds}),jn.render(Z.getState().activeModeIds,wn()))};ur();let dr=()=>{Nn?.destroy(),Nn=null,Ln?.destroy(),Ln=null;let e=Zn?.header;e&&(Nn=cu({onDismiss:()=>Pn(void 0)}),e.appendChild(Nn.element),Nn.render(Z.getState().quote),In()===`defer-one`&&(Ln=lu({onEdit:()=>xl(),onRemove:()=>Rn(void 0)}),e.appendChild(Ln.element),Ln.render(Z.getState().pendingSubmission)))};dr();let fr=hu(),pr=()=>{let e=Zn?.header?.querySelector(Kl);if(e)return e.childElementCount>0;let t=Z.getState();return t.mentionRefs.length>0||iu(t.activeModeIds,wn()).length>0};function mr(){let e=Z.getState(),t=fr.observe(gu(q),e.text);wt.toggleAttribute(`data-persona-composer-compact`,mu({text:e.text,wrapped:t,hasAttachments:e.attachments.length>0,hasChips:pr(),hasQuote:e.quote!==void 0,hasPendingSubmission:e.pendingSubmission!==void 0}))}function hr(){r.composer?.layout===`single-row`&&!L()?wt.setAttribute(`data-persona-composer-layout`,`single-row`):wt.removeAttribute(`data-persona-composer-layout`)}hr(),Z.subscribe(()=>{or?.sync(),Es(),Ds(),mr(),so()}),Ds();let gr=!1,vr=e=>{if(gr||r.debug!==!0)return;let t=[`messages`,`composer`].filter(t=>e[t]);t.length&&(gr=!0,console.warn(`[persona] layout.slots.${t.join(` and layout.slots.`)} ${t.length>1?`are`:`is`} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let e=r.layout?.slots??{};vr(e);let t=e=>{switch(e){case`body-top`:return G.querySelector(`[data-persona-intro-card]`);case`messages`:return K;case`footer-top`:return lt;case`composer`:return ut;case`footer-bottom`:return dt;default:return null}},n=(e,t)=>{switch(e){case`header-left`:case`header-center`:case`header-right`:if(e===`header-left`)Ct.insertBefore(t,Ct.firstChild);else if(e===`header-right`)Ct.appendChild(t);else{let e=Ct.querySelector(`.persona-flex-col`);e?e.parentNode?.insertBefore(t,e.nextSibling):Ct.appendChild(t)}break;case`body-top`:{let e=G.querySelector(`[data-persona-intro-card]`);e?e.replaceWith(t):G.insertBefore(t,G.firstChild);break}case`body-bottom`:G.appendChild(t);break;case`footer-top`:lt.replaceWith(t);break;case`footer-bottom`:dt.replaceWith(t)}};for(let[i,a]of Object.entries(e))if(a)try{let e=a({config:r,defaultContent:()=>t(i)});e&&n(i,e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Error rendering slot "${i}":`,e)}})(),K.addEventListener(`click`,e=>{let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`button[data-persona-copy-tool-detail]`);n&&(e.preventDefault(),e.stopPropagation(),jm(n))});let br=e=>{let t=e.target.closest(`button[data-expand-header="true"]`);if(!t)return;let n=t.closest(`.persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble`);if(!n)return;let c=n.getAttribute(`data-message-id`);if(!c)return;La(),Co();let l=t.getAttribute(`data-bubble-type`);if(n.classList.contains(`persona-activity-row`)){o.manual(c);let e=n.parentElement?.closest(`[data-persona-tool-group]`);e?.dataset.messageId&&o.manual(e.dataset.messageId)}if(l===`reasoning`)a.has(c)?a.delete(c):a.add(c),Tm(c,n,a);else if(l===`tool`)i.has(c)?i.delete(c):i.add(c),Im(c,n,i,r);else if(l===`approval`&&g){let e=((r.approval===!1?void 0:r.approval)?.detailsDisplay??`collapsed`)===`expanded`,t=s.get(c)??e;s.set(c,!t),g.updateApprovalDetailsUI(c,n,r,s)}ca.delete(c)};K.addEventListener(`pointerdown`,e=>{e.target.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),br(e))}),K.addEventListener(`click`,e=>{e.detail===0&&e.target.closest(`.persona-activity-row`)&&br(e)}),K.addEventListener(`keydown`,e=>{let t=e.target;(e.key===`Enter`||e.key===` `)&&t.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),br(e))}),K.addEventListener(`copy`,e=>{let{clipboardData:t}=e;if(!t)return;let n=K.getRootNode(),r=typeof n.getSelection==`function`?n.getSelection():window.getSelection();if(!r||r.isCollapsed)return;let i=r.toString(),a=Td(i);a&&a!==i&&(t.setData(`text/plain`,a),e.preventDefault())});let xr=/* @__PURE__ */ new Map,Sr=null,Cr=`idle`,wr={idle:{icon:`volume-2`,label:`Read aloud`},loading:{icon:`loader-circle`,label:`Loading…`},playing:{icon:`pause`,label:`Pause`},paused:{icon:`play`,label:`Resume`}},Tr=(e,t)=>{let{icon:n,label:r}=wr[t];e.setAttribute(`aria-label`,r),e.title=r,e.setAttribute(`aria-pressed`,t===`idle`?`false`:`true`),e.classList.toggle(`persona-message-action-active`,t!==`idle`),e.classList.toggle(`persona-message-action-loading`,t===`loading`);let i=F(n,14,`currentColor`,2);i&&(e.innerHTML=``,e.appendChild(i))},Er=()=>{K.querySelectorAll(`[data-action="read-aloud"]`).forEach(e=>{let t=e.closest(`[data-actions-for]`)?.getAttribute(`data-actions-for`)??null;Tr(e,t&&t===Sr?Cr:`idle`)})};K.addEventListener(`click`,e=>{let t=e.target.closest(`.persona-message-action-btn[data-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`[data-actions-for]`);if(!n)return;let i=n.getAttribute(`data-actions-for`);if(!i)return;let a=t.getAttribute(`data-action`);if(a===`copy`){let e=$.getMessages().find(e=>e.id===i);if(e&&et.onCopy){let n=e.content||``;navigator.clipboard.writeText(n).then(()=>{t.classList.add(`persona-message-action-success`);let e=k(f.Check,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e)),setTimeout(()=>{t.classList.remove(`persona-message-action-success`);let e=k(f.Copy,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))},2e3)}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to copy message:`,e)}),et.onCopy(e)}}else if(a===`read-aloud`)$.toggleReadAloud(i);else if(a===`upvote`||a===`downvote`){let e=(xr.get(i)??null)===a,r=a===`upvote`?`thumbs-up`:`thumbs-down`;if(e){xr.delete(i),t.classList.remove(`persona-message-action-active`);let e=F(r,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))}else{let e=a===`upvote`?`downvote`:`upvote`,o=n.querySelector(`[data-action="${e}"]`);if(o){o.classList.remove(`persona-message-action-active`);let t=F(e===`upvote`?`thumbs-up`:`thumbs-down`,14,`currentColor`,2);t&&(o.innerHTML=``,o.appendChild(t))}xr.set(i,a),t.classList.add(`persona-message-action-active`);let s=F(r,14,`currentColor`,2);s&&(s.setAttribute(`fill`,`currentColor`),t.innerHTML=``,t.appendChild(s)),t.classList.remove(`persona-message-action-pop`),t.offsetWidth,t.classList.add(`persona-message-action-pop`);let c=$.getMessages().find(e=>e.id===i);c&&et.onFeedback&&et.onFeedback({type:a,messageId:c.id,message:c})}}else if(a===`regenerate`)Dr?.regenerate(i);else if(a===`edit`)Dr?.edit(i);else if(a===`quote`)Dr?.quote(i);else if(a?.startsWith(`custom:`)){let e=a.slice(7),t=r.messageActions?.custom?.find(t=>t.id===e),n=$.getMessages().find(e=>e.id===i);if(!t||!n)return;try{t.onSelect(n)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let Dr=null;K.addEventListener(`click`,e=>{let t=e.target.closest(`button[data-approval-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`.persona-approval-bubble`);if(!n)return;let r=n.getAttribute(`data-message-id`);if(!r)return;let i=t.getAttribute(`data-approval-action`);if(!i)return;let a=i===`approve`?`approved`:`denied`,o=$.getMessages().find(e=>e.id===r);if(!o?.approval)return;let s=n.querySelector(`[data-approval-buttons]`);s&&s.querySelectorAll(`button`).forEach(e=>{e.disabled=!0,e.style.opacity=`0.5`,e.style.cursor=`not-allowed`}),o.approval.toolType===`webmcp`?$.resolveWebMcpApproval(r,a):$.resolveApproval(o.approval,a)});let Or=null,kr=!1,Ar=null,jr=()=>{},Mr=`none`,Nr=null,Pr={artifacts:[],selectedId:null},Fr=!1,Ir=!1,Lr=!1,Br=!1,Hr=()=>Br||Pr.artifacts.some(e=>Oe(r.features?.artifacts,e)===`panel`),Ur=()=>Pr.artifacts.length>0&&!Fr&&Hr(),Wr={current:null},Gr=(e,t)=>{let n=$.getArtifactById(t),r=n?.markdown,i=n?.title||`artifact`,a=n?.file,o=n?.artifactType??`markdown`;if(!r){let t=(e.closest(`[data-open-artifact], [data-artifact-inline]`)?.closest(`[data-message-id]`))?.getAttribute(`data-message-id`);if(t){let e=$.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);r=t?.props?.markdown,i=t?.props?.title||i,t?.props?.file&&typeof t.props.file==`object`&&(a=t.props.file),!n&&typeof t?.props?.artifactType==`string`&&(o=t.props.artifactType)}catch{}}}return{markdown:r,title:i,file:a,artifactType:o}};K.addEventListener(`click`,e=>{let t=e.target.closest(`[data-download-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-download-artifact`);if(!n||r.features?.artifacts?.onArtifactAction?.({type:`download`,artifactId:n})===!0)return;let{markdown:i,title:a,file:o}=Gr(t,n);if(!i)return;let s=rh();s&&s.triggerArtifactDownload(s.downloadInfoFor({title:a,markdown:i,file:o}))}),K.addEventListener(`click`,e=>{let t=e.target.closest(`[data-artifact-custom-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-artifact-custom-action`);if(!n)return;let i=t.closest(`[data-artifact-inline]`),a=i?null:t.closest(`[data-open-artifact]`),o=i?i.getAttribute(`data-artifact-inline`):a?.getAttribute(`data-open-artifact`)??null,s=(i?r.features?.artifacts?.inlineActions:r.features?.artifacts?.cardActions)?.find(e=>e.id===n);if(!s)return;let{markdown:c,title:l,file:u,artifactType:d}=Gr(t,o??``),f={artifactId:o,title:l,artifactType:d,markdown:c,file:u};try{Promise.resolve(s.onClick(f)).catch(()=>{})}catch{}}),K.addEventListener(`click`,e=>{let t=e.target.closest(`[data-copy-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-copy-artifact`);if(!n)return;let r=$.getArtifactById(n),i=rh();if(!i)return;let a=``;if(r)a=i.artifactCopyText(r);else{let{markdown:e,file:r,artifactType:o}=Gr(t,n);o===`markdown`&&(a=i.artifactCopyText({id:n,artifactType:`markdown`,status:`complete`,markdown:e??``,...r?{file:r}:{}}))}a&&navigator.clipboard.writeText(a).then(()=>{let e=k(f.Check,16,`currentColor`,2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=k(f.Copy,16,`currentColor`,2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),K.addEventListener(`click`,e=>{let t=e.target.closest(`[data-expand-artifact-inline]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-expand-artifact-inline`);n&&r.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:n})!==!0&&(Fr=!1,Br=!0,Ir=!0,Lr=!0,$.selectArtifact(n),hi())}),K.addEventListener(`click`,e=>{let t=e.target;if(t.closest(`[data-download-artifact]`)||t.closest(`[data-artifact-custom-action]`))return;let n=t.closest(`[data-open-artifact]`);if(!n)return;let i=n.getAttribute(`data-open-artifact`);i&&r.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:i})!==!0&&(e.preventDefault(),e.stopPropagation(),Fr=!1,Br=!0,$.selectArtifact(i),hi())}),K.addEventListener(`keydown`,e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target;(t.hasAttribute(`data-open-artifact`)||t.hasAttribute(`data-expand-artifact-inline`))&&(e.preventDefault(),t.click())});let Kr=ot.composerOverlay,qr=e=>{Na().catch(()=>{}),Bt(e,r,Kr)},Jr=null,Yr={mount:e,overlay:Kr,sessionRef:Wr,config:()=>r},Xr=!1,Zr=e=>t=>{let n=t.target,r=n?.closest?.(`[data-persona-ask-sheet-for]`);if(!r||!(e===`click`?n?.closest(`[data-ask-user-action]`):t.key===`Enter`&&n?.matches?.(`[data-ask-free-text-input="true"]`)))return;let i=n=>{Jr??=n.createAskUserSheetHandlers(Yr),Jr[e](t)},a=Fa();a?i(a):Xr||(Xr=!0,Na().then(e=>{Xr=!1,r.isConnected&&i(e)},()=>{Xr=!1}))};Kr.addEventListener(`click`,Zr(`click`)),Kr.addEventListener(`keydown`,Zr(`keydown`));let Qr=e=>{if(!/^[1-9]$/.test(e.key)||e.metaKey||e.ctrlKey||e.altKey)return;let t=e.target;if(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable)return;let n=Kr.querySelector(`[data-persona-ask-sheet-for]`);if(!n||n.getAttribute(`data-ask-layout`)!==`rows`||n.getAttribute(`data-multi-select`)===`true`)return;let r=Number(e.key),i=n.querySelectorAll(`[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]`)[r-1];i&&(e.preventDefault(),i.click())};document.addEventListener(`keydown`,Qr);let $r=null,ei=null,ti=null,ni=null,ri=()=>{},ai=!1,oi=``,si=``;function ci(){ni?.(),ni=null}let li=()=>{let e=Rc?.railShell?Rc.railHost:null,t=e?.isConnected?e:null,n=t?t.getBoundingClientRect().width:0;return n<=0?200:n+360},ui=()=>{if(!$r||!ei)return;let t=e.classList.contains(`persona-artifact-welded-split`),n=e.ownerDocument.defaultView??window,r=n.innerWidth<=640;if(!t||e.classList.contains(`persona-artifact-narrow-host`)||r){ei.style.removeProperty(`position`),ei.style.removeProperty(`left`),ei.style.removeProperty(`top`),ei.style.removeProperty(`bottom`),ei.style.removeProperty(`width`),ei.style.removeProperty(`z-index`);return}let i=$r.firstElementChild;if(!i||i===ei)return;ei.style.position=`absolute`,ei.style.top=`0`,ei.style.bottom=`0`,ei.style.width=`10px`,ei.style.zIndex=`5`;let a=Vh($r,n),o=i.offsetWidth+a/2-5;ei.style.left=`${Math.max(0,o)}px`},di=()=>{},pi=()=>{let t=e.ownerDocument.defaultView??window,n=r.launcher?.mobileFullscreen??!0,i=r.launcher?.mobileBreakpoint??640;return!n||t.innerWidth>i?!1:me||Cf(r)},mi=()=>!ah(r)||!Ur()||e.classList.contains(`persona-artifact-narrow-host`)||pi()||(e.ownerDocument.defaultView??window).innerWidth<641?`none`:uh(r)?`detached`:`welded`,hi=()=>{if(!Or||!ah(r))return;dh(e,r),fh(e,r),di();let t=r.features?.artifacts?.layout?.narrowHostMaxWidth??520,n=U.getBoundingClientRect().width||0;e.classList.toggle(`persona-artifact-narrow-host`,n>0&&n<=t);let i=Ur();Or.setVisible(i),Or.update(Pr),Fr?(Or.setMobileOpen(!1),Or.element.classList.add(`persona-hidden`),Or.backdrop?.classList.add(`persona-hidden`),Ir=!1,Lr=!1):Pr.artifacts.length>0&&Hr()?(Or.element.classList.remove(`persona-hidden`),Or.setMobileOpen(!0)):(Or.setMobileOpen(!1),Or.element.classList.add(`persona-hidden`),Or.backdrop?.classList.add(`persona-hidden`),Ir=!1,Lr=!1);let a=r.features?.artifacts?.layout?.showExpandToggle===!0;if(Or.setExpandToggleVisible(a),Or.setCopyButtonVisible(r.features?.artifacts?.layout?.showCopyButton===!0),Or.setRefreshButtonVisible(typeof r.features?.artifacts?.layout?.onDocumentToolbarRefresh==`function`),Or.setCustomActions(r.features?.artifacts?.toolbarActions??[]),Or.setTabFade(r.features?.artifacts?.layout?.tabFade),Or.setRenderTabBar(r.features?.artifacts?.renderTabBar),!a&&!Lr&&(Ir=!1),Ir!==ai){let e=Or.element;Ir?(oi=e.style.width,si=e.style.maxWidth,e.style.removeProperty(`width`),e.style.removeProperty(`max-width`)):(oi&&(e.style.width=oi),si&&(e.style.maxWidth=si),oi=``,si=``),ai=Ir}e.classList.toggle(`persona-artifact-expanded`,Ir),Or.setExpanded(Ir);let o=mi();o!==Mr&&(Mr=o,jr()),ri()};if(ah(r)){U.style.position=`relative`;let t=B(`div`,`persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0`),n=B(`div`,`persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root`);t.appendChild(W),$r=n,n.appendChild(t),U.appendChild(n);let i=e=>{kr||Or||(Or=e.createArtifactPane(r,{onSelect:e=>Wr.current?.selectArtifact(e),onDismiss:()=>{Fr=!0,hi()},onToggleExpand:()=>{let e=!Ir,t=Pr.selectedId??Pr.artifacts[Pr.artifacts.length-1]?.id??null;r.features?.artifacts?.onArtifactAction?.({type:`expand`,artifactId:t,expanded:e})!==!0&&(Ir=e,e||(Lr=!1),hi())}}),Or.element.classList.add(`persona-hidden`),n.appendChild(Or.element),Or.backdrop&&U.appendChild(Or.backdrop),ri(),hi())},a=rh();a?i(a):(ih(()=>{let e=rh();e&&i(e)}),nh().catch(()=>{})),ri=()=>{if($r&&Or){if(r.features?.artifacts?.layout?.resizable!==!0)ti?.(),ti=null,ci(),ei&&=(ei.remove(),null),Or.element.style.removeProperty(`width`),Or.element.style.removeProperty(`maxWidth`);else{if(!ei){let t=B(`div`,`persona-artifact-split-handle persona-shrink-0 persona-h-full`);t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-label`,`Resize artifacts panel`),t.tabIndex=0;let n=e.ownerDocument,i=n.defaultView??window,a=a=>{if(!Or||a.button!==0||e.classList.contains(`persona-artifact-narrow-host`)||e.classList.contains(`persona-artifact-expanded`)||i.innerWidth<=640)return;a.preventDefault(),ci();let o=a.clientX,s=Or.element.getBoundingClientRect().width,c=r.features?.artifacts?.layout,l=n=>{let r=$r.getBoundingClientRect().width,a=e.classList.contains(`persona-artifact-welded-split`),l=Vh($r,i),u=a?0:t.getBoundingClientRect().width||6,d=Hh(s-(n.clientX-o),r,l,u,c?.resizableMinWidth,c?.resizableMaxWidth,li());Or.element.style.width=`${d}px`,Or.element.style.maxWidth=`none`,ui()},u=()=>{n.removeEventListener(`pointermove`,l),n.removeEventListener(`pointerup`,u),n.removeEventListener(`pointercancel`,u),ni=null;try{t.releasePointerCapture(a.pointerId)}catch{}};ni=u,n.addEventListener(`pointermove`,l),n.addEventListener(`pointerup`,u),n.addEventListener(`pointercancel`,u);try{t.setPointerCapture(a.pointerId)}catch{}};t.addEventListener(`pointerdown`,a),ei=t,$r.insertBefore(t,Or.element),ti=()=>{t.removeEventListener(`pointerdown`,a)}}if(ei){let e=Ur();ei.classList.toggle(`persona-hidden`,!e),ui()}}}},di=()=>{if(!me||!Or||(r.launcher?.sidebarMode??!1)||Cf(r)&&Tf(r).reveal===`emerge`)return;let t=e.ownerDocument.defaultView??window,n=r.launcher?.mobileFullscreen??!0,i=r.launcher?.mobileBreakpoint??640;if(n&&t.innerWidth<=i||!ph(r,me))return;let a=tm(r).width,o=r.features?.artifacts?.layout?.expandedPanelWidth??`min(720px, calc(100vw - 24px))`;Ur()?(U.style.width=o,U.style.maxWidth=o):(U.style.width=a,U.style.maxWidth=a)},typeof ResizeObserver<`u`&&(Ar=new ResizeObserver(()=>{hi()}),Ar.observe(U))}else U.appendChild(W);L()&&at&&(ot.peekBanner&&at.appendChild(ot.peekBanner),at.appendChild(wt)),e.appendChild(it),at&&e.appendChild(at);let gi=()=>{let t=pi()||L()&&r.launcher?.composerBar?.expandedSize===`fullscreen`||r.launcher?.fullHeight===!0&&!r.launcher?.sidebarMode&&!Cf(r);if(K.style.gap=t?`var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))`:`var(--persona-components-message-gap, 12px)`,K.style.setProperty(`--persona-transcript-gap`,K.style.gap),L()){U.style.width=`100%`,U.style.maxWidth=`100%`;let e=r.launcher?.composerBar??{},t=it.dataset.state===`expanded`,n=e.expandedSize??`anchored`;if(!(t&&n!==`fullscreen`)){W.style.background=``,W.style.border=``,W.style.borderRadius=``,W.style.overflow=``,W.style.boxShadow=``;return}let i=r.theme?.components?.panel,a=gd(r),o=(e,t)=>e==null||e===``?t:Uu(a,e)??e;W.style.background=`var(--persona-surface, #ffffff)`,W.style.border=o(i?.border,`1px solid var(--persona-border)`),W.style.borderRadius=o(i?.borderRadius,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`),W.style.boxShadow=o(i?.shadow,`var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))`),W.style.overflow=`hidden`;return}let n=Cf(r),i=r.launcher?.sidebarMode??!1,a=n||i||(r.launcher?.fullHeight??!1),o=r.launcher?.enabled===!1,s=r.launcher?.detachedPanel===!0,c=r.theme?.components?.panel,l=r.darkTheme?.components?.panel,u=pd(r)===`dark`?Vr(c??{},l??{}):c,d=gd(r),f=(e,t)=>e==null||e===``?t:Uu(d,e)??e,p=e.ownerDocument.defaultView??window,m=r.launcher?.mobileFullscreen??!0,h=r.launcher?.mobileBreakpoint??640,g=p.innerWidth<=h,_=m&&g&&me,v=n&&m&&g,y=r.launcher?.position??`bottom-left`,b=y===`bottom-left`||y===`top-left`,x=r.launcher?.zIndex??1e5,S=(e,t,n)=>`var(--persona-components-panel-modes-${e}-${t}, ${n})`,C=u?.modes?.floating,w=f(C?.border??u?.border,S(`floating`,`border`,`var(--persona-panel-border, 1px solid var(--persona-border))`)),T=f(C?.shadow??u?.shadow,S(`floating`,`shadow`,`var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))`)),E=f(C?.borderRadius??u?.borderRadius,S(`floating`,`borderRadius`,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`)),D=s&&!_&&!v,O=_||v?`mobile`:D?`floating`:n?`docked`:i?`sidebar`:o?`inline`:`floating`,ee=u?.modes?.[O];D?e.setAttribute(`data-persona-panel-detached`,`true`):e.removeAttribute(`data-persona-panel-detached`);let k=D?w:i||_?`none`:w,A=D?T:_?`none`:i?b?`2px 0 12px rgba(0, 0, 0, 0.08)`:`-2px 0 12px rgba(0, 0, 0, 0.08)`:o?`none`:T;n&&!_&&!D&&(A=`none`,k=`none`);let j=D?E:i||_?`0`:E,te=f(ee?.border??u?.border,S(O,`border`,k)),ne=f(ee?.shadow??u?.shadow,S(O,`shadow`,A)),re=f(ee?.borderRadius??u?.borderRadius,S(O,`borderRadius`,j)),ie=mi(),M=ie===`detached`,N=ie===`welded`;e.classList.toggle(`persona-artifact-detached-split`,M),e.classList.toggle(`persona-artifact-welded-split`,N);let P=`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)))))`,ae=(r.features?.artifacts?.layout?.chatSurface===`flush`?`flush`:`card`)==`flush`&&ah(r)&&uh(r)&&o&&!n;e.classList.toggle(`persona-artifact-chat-flush`,ae);let oe=M||ae?`none`:ne,se=M?w:N?`none`:te,ce=M?E:re;ae&&(se=`none`,ce=`0`);let le=ee?.borderRadius!=null&&ee.borderRadius!==``||u?.borderRadius!=null&&u.borderRadius!==``,ue=ae&&!le?`0`:re,de=G.scrollTop;e.style.cssText=``,it.style.cssText=``,U.style.cssText=``,W.style.cssText=``,G.style.cssText=``,Jn||(wt.style.cssText=``),He&&(G.style.display=`none`),(a||o)&&(e.style.minWidth=`0`);let fe=()=>{de<=0||(G.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(G.scrollTop===de)return;let e=G.scrollHeight-G.clientHeight;e<=0||(G.scrollTop=Math.min(de,e))})};if(_){it.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`),it.style.cssText=`
40
+ `,t.addEventListener(`click`,()=>{d=e,_.forEach((t,n)=>{let r=n<e;t.classList.toggle(`selected`,r),t.setAttribute(`aria-checked`,n===e-1?`true`:`false`)})}),_.push(t),g.appendChild(t)}f.appendChild(g);let v=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,v=document.createElement(`textarea`),v.className=`persona-feedback-comment`,v.placeholder=a,v.rows=3,v.setAttribute(`aria-label`,`Additional comments`),e.appendChild(v),f.appendChild(e)}let y=document.createElement(`div`);y.className=`persona-feedback-actions`;let b=document.createElement(`button`);b.type=`button`,b.className=`persona-feedback-btn persona-feedback-btn-skip`,b.textContent=s,b.addEventListener(`click`,()=>{n?.(),u.remove()});let x=document.createElement(`button`);return x.type=`button`,x.className=`persona-feedback-btn persona-feedback-btn-submit`,x.textContent=o,x.addEventListener(`click`,async()=>{if(d===null)g.classList.add(`persona-feedback-shake`),setTimeout(()=>g.classList.remove(`persona-feedback-shake`),500);else{x.disabled=!0,x.textContent=`Submitting...`;try{let e=v?.value.trim()||void 0;await t(d,e),u.remove()}catch(e){x.disabled=!1,x.textContent=o,console.error(`[CSAT Feedback] Failed to submit:`,e)}}}),y.appendChild(b),y.appendChild(x),f.appendChild(y),u.appendChild(f),u}function Rg(e){let{onSubmit:t,onDismiss:n,title:r=`How likely are you to recommend us?`,subtitle:i=`On a scale of 0 to 10`,commentPlaceholder:a=`What could we do better? (optional)...`,submitText:o=`Submit`,skipText:s=`Skip`,showComment:c=!0,lowLabel:l=`Not likely`,highLabel:u=`Very likely`}=e,d=document.createElement(`div`);d.className=`persona-feedback-container persona-feedback-nps`,d.setAttribute(`role`,`dialog`),d.setAttribute(`aria-label`,`Net Promoter Score feedback`);let f=null,p=document.createElement(`div`);p.className=`persona-feedback-content`;let m=document.createElement(`div`);m.className=`persona-feedback-header`;let h=document.createElement(`h3`);h.className=`persona-feedback-title`,h.textContent=r,m.appendChild(h);let g=document.createElement(`p`);g.className=`persona-feedback-subtitle`,g.textContent=i,m.appendChild(g),p.appendChild(m);let _=document.createElement(`div`);_.className=`persona-feedback-rating persona-feedback-rating-nps`,_.setAttribute(`role`,`radiogroup`),_.setAttribute(`aria-label`,`Likelihood rating from 0 to 10`);let v=document.createElement(`div`);v.className=`persona-feedback-labels`;let y=document.createElement(`span`);y.className=`persona-feedback-label-low`,y.textContent=l;let b=document.createElement(`span`);b.className=`persona-feedback-label-high`,b.textContent=u,v.appendChild(y),v.appendChild(b);let x=document.createElement(`div`);x.className=`persona-feedback-numbers`;let S=[];for(let e=0;e<=10;e++){let t=document.createElement(`button`);t.type=`button`,t.className=`persona-feedback-rating-btn persona-feedback-number-btn`,t.setAttribute(`role`,`radio`),t.setAttribute(`aria-checked`,`false`),t.setAttribute(`aria-label`,`Rating ${e} out of 10`),t.textContent=String(e),t.dataset.rating=String(e),e<=6?t.classList.add(`persona-feedback-detractor`):e<=8?t.classList.add(`persona-feedback-passive`):t.classList.add(`persona-feedback-promoter`),t.addEventListener(`click`,()=>{f=e,S.forEach((t,n)=>{t.classList.toggle(`selected`,n===e),t.setAttribute(`aria-checked`,n===e?`true`:`false`)})}),S.push(t),x.appendChild(t)}_.appendChild(v),_.appendChild(x),p.appendChild(_);let C=null;if(c){let e=document.createElement(`div`);e.className=`persona-feedback-comment-container`,C=document.createElement(`textarea`),C.className=`persona-feedback-comment`,C.placeholder=a,C.rows=3,C.setAttribute(`aria-label`,`Additional comments`),e.appendChild(C),p.appendChild(e)}let w=document.createElement(`div`);w.className=`persona-feedback-actions`;let T=document.createElement(`button`);T.type=`button`,T.className=`persona-feedback-btn persona-feedback-btn-skip`,T.textContent=s,T.addEventListener(`click`,()=>{n?.(),d.remove()});let E=document.createElement(`button`);return E.type=`button`,E.className=`persona-feedback-btn persona-feedback-btn-submit`,E.textContent=o,E.addEventListener(`click`,async()=>{if(f===null)x.classList.add(`persona-feedback-shake`),setTimeout(()=>x.classList.remove(`persona-feedback-shake`),500);else{E.disabled=!0,E.textContent=`Submitting...`;try{let e=C?.value.trim()||void 0;await t(f,e),d.remove()}catch(e){E.disabled=!1,E.textContent=o,console.error(`[NPS Feedback] Failed to submit:`,e)}}}),w.appendChild(T),w.appendChild(E),p.appendChild(w),d.appendChild(p),d}Vr(),ta(),va(),Sa(),ma(),Wi(),Wr(),F(),A(),V(),Lr(),_r(),Ao(),fn(),fa(),Kt(),rn(),Qe(),we(),je(),Ti(),li();const zg=`persona-chat-history`,Bg=`data-persona-composer-reason`,Vg=`data-persona-composer-notice`,Hg={"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 Ug(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let e of n){if(e.kind!==`file`||!e.type.startsWith(`image/`))continue;let n=e.getAsFile();if(!n)continue;if(n.name){t.push(n);continue}let r=Hg[n.type]??`png`;t.push(new File([n],`clipboard-image-${Date.now()}.${r}`,{type:n.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let n of Array.from(e.files??[]))n.type.startsWith(`image/`)&&t.push(n);return t}function Wg(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 Gg(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 Kg(e){try{let t=e===`local`?localStorage:sessionStorage,n=`__persist_test__`;return t.setItem(n,`1`),t.removeItem(n),t}catch{return null}}const qg=e=>!e||typeof e!=`object`?{}:{...e},Jg=e=>e.filter(e=>!lc(e)).map(e=>({...e,streaming:!1})),Yg=(e,t,n)=>{let r=e?.markdown?Es(e.markdown):null,i=Rs(e?.sanitize);e?.postprocessMessage&&i&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let a=!1,o=a=>{let o=a.text??``,s=a.message.rawContent??null;if(t){let e=t.process({text:o,raw:s??o,message:a.message,streaming:a.streaming});e!==null&&(o=e.text,e.persist||(a.message.__skipPersist=!0),e.resubmit&&!a.streaming&&n&&n())}let c=O()!==null,l;if(e?.postprocessMessage){let t=e.postprocessMessage({...a,text:o,raw:s??a.text??``});l=i?i(t):t}else if(r){let e=a.streaming?Gs(o):o,t=r(e);l=i&&c?i(t):t}else l=ks(o);return l};return e=>{try{return o(e)}catch(t){return a||(a=!0,console.error(`[Persona] markdown rendering failed; falling back to plain text:`,t)),ks(e.text??``)}}};function Xg(e){let t=z(`div`,`persona-attachment-drop-overlay`);e?.background&&t.style.setProperty(`--persona-drop-overlay-bg`,e.background),e?.backdropBlur!==void 0&&t.style.setProperty(`--persona-drop-overlay-blur`,e.backdropBlur),e?.border&&t.style.setProperty(`--persona-drop-overlay-border`,e.border),e?.borderRadius&&t.style.setProperty(`--persona-drop-overlay-radius`,e.borderRadius),e?.inset&&t.style.setProperty(`--persona-drop-overlay-inset`,e.inset),e?.labelSize&&t.style.setProperty(`--persona-drop-overlay-label-size`,e.labelSize),e?.labelColor&&t.style.setProperty(`--persona-drop-overlay-label-color`,e.labelColor);let n=e?.iconName??`upload`,r=e?.iconSize??`48px`,i=e?.iconColor??`rgba(59, 130, 246, 0.6)`,a=e?.iconStrokeWidth??.5,o=P(n,r,i,a);if(o&&t.appendChild(o),e?.label){let n=z(`span`,`persona-drop-overlay-label`);n.textContent=e.label,t.appendChild(n)}return t}const Zg=(e,t)=>{let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t?{...t,...r}:r}return n},Qg=e=>e.reduce((e,t)=>({blocks:[...e.blocks,...t.blocks],contentParts:[...e.contentParts,...t.contentParts],context:Zg(e.context,t.context)}),{blocks:[],contentParts:[],context:{}}),$g=(e,t,n)=>{if(e==null)throw Error(`createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).`);e.id&&!e.getAttribute(`data-persona-instance`)&&e.setAttribute(`data-persona-instance`,e.id),e.hasAttribute(`data-persona-root`)||e.setAttribute(`data-persona-root`,`true`);let r=pi(t),i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=vs((e,t)=>{la.delete(e);let n=Array.from(G.querySelectorAll(`[data-message-id]`)).find(t=>t.dataset.messageId===e);n&&(t===`tool`?Hm(e,n,i,r):jm(e,n,a))}),s=/* @__PURE__ */ new Map,c=()=>{vr({delayMs:r.tooltip?.delayMs??200,skipDelayMs:r.tooltip?.skipDelayMs??300})};c();let l=r.features;r=Hh(r);let u=tg.getForInstance(r.plugins),d=ko(e),p=[],m=!1,h=Om(()=>r),g=null,_=null,v=null,y=!1,b=null,x=e=>{g=e,e.initApprovalUi({webMcpToolTitle:xe});let t=e.createBuiltInApprovalPlugin(s);_=t.plugin,v=t.teardown},S=()=>{if(g)return g;let e=Ym();return e?(x(e),e):(Jm().then(e=>{y||g||(x(e),b?.())}).catch(()=>{}),null)},C=!1,w=!1,D=null,ee=(e,t,n,r)=>{if(!e.querySelector(`[data-tv-form]`))return;let i=eg();i?i.enhanceWithForms(e,t,n,r):$h().then(()=>{C||w||!D||(w=!0,D())}).catch(()=>{})};r.components&&$m.registerAll(r.components);let A=og(),te=r.persistState===!1?null:r.storageAdapter??vg(_g(typeof r.persistState==`object`?r.persistState.keyPrefix:void 0)),ne=!!r.clientToken&&typeof r.reconnectStream!=`function`,re={},ie=null,ae,j=new Promise(e=>{ae=e}),M=()=>{},N=new Promise(e=>{M=e}),oe,se=!1,ce=e=>{if(r.onStateLoaded)try{let t=r.onStateLoaded(e);if(t&&typeof t==`object`&&`state`in t){let{state:e,open:n}=t;return n&&(se=!0),e}return t}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}return e};if(te?.load)try{let e=te.load();if(e&&typeof e.then==`function`)ie=e.then(e=>ce(e??{messages:[],metadata:{}}));else{let t=ce(e??{messages:[],metadata:{}});t.metadata&&(re=qg(t.metadata)),t.messages?.length&&(r={...r,initialMessages:t.messages}),t.artifacts?.length&&(r={...r,initialArtifacts:t.artifacts,initialSelectedArtifactId:t.selectedArtifactId??null}),oe=t.draft}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Failed to load stored state:`,e)}else if(r.onStateLoaded)try{let e=ce({messages:[],metadata:{}});e.messages?.length&&(r={...r,initialMessages:e.messages})}catch(e){typeof console<`u`&&console.error(`[AgentWidget] onStateLoaded hook failed:`,e)}ie||ae();let ue=()=>re,de=e=>{re=e({...re})??{},ro()},fe=r.actionParsers&&r.actionParsers.length?r.actionParsers:[lg],pe=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[dg.message,dg.messageAndClick],me=pg({parsers:fe,handlers:pe,getSessionMetadata:ue,updateSessionMetadata:de,emit:A.emit,documentRef:typeof document<`u`?document:null});me.syncFromMetadata();let he=r.launcher?.enabled??!0,F=r.launcher?.autoExpand??!1,ge=r.autoFocusInput??!1,_e=F,ve=he,ye=r.layout?.header?.layout,be=!1,I=()=>Af(r),L=()=>he||I(),R=I()?!1:!he||F,Se=!1,Ce=null,we=()=>{Se=!0,Ce&&clearTimeout(Ce),Ce=setTimeout(()=>{Se&&=(typeof console<`u`&&console.warn(`[AgentWidget] Resubmit requested but no injection occurred within 10s`),!1)},1e4)},Te=Yg(r,me,we),Ee=r.features?.showReasoning??!0,De=r.features?.showToolCalls??!0,Oe=r.features?.showEventStreamToggle??!1,Ae=r.features?.scrollToBottom??{},je=r.features?.scrollBehavior??{},Me=()=>(typeof r.persistState==`object`?r.persistState?.keyPrefix:void 0)??`persona-`,Ne=`${Me()}event-stream`,Pe=null,Fe=r.features?.eventStream?.maxEvents??2e3,Le=null,Re=null,Be=null,Ve=!1,He=null,Ue=!1,We=null,Ge=0,Ke=(e,t)=>{Le?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:e,timestamp:Date.now(),payload:JSON.stringify(t)})},qe=(e,t)=>{Re?.processEvent(e,t),Le?Ke(e,t):Be&&(Be.length>=Fe&&Be.shift(),Be.push({type:e,payload:t}))},Je=()=>{!Le&&Oe&&(Be??=[],Qm().then(e=>{if(Ve||Le||!Oe)return;Pe=new e.EventStreamStore(Ne),Le=new e.EventStreamBuffer(Fe,Pe),Re??=new e.ThroughputTracker,Pe.open().then(()=>Le?.restore()).catch(e=>{r.debug&&console.warn(`[AgentWidget] IndexedDB not available for event stream:`,e)});let t=Be??[];Be=null;for(let e of t)Re?.processEvent(e.type,e.payload),Ke(e.type,e.payload)}).catch(()=>{}))};Oe&&Je();let Ye=!1,Xe=null,Ze=()=>{},Qe=()=>{},B=()=>{},$e=()=>{},V=()=>{},et=()=>Ue||Ye&&Xe===`panel`,tt={onCopy:e=>{A.emit(`message:copy`,e),Q?.isClientTokenMode()&&Q.submitMessageFeedback(e.id,`copy`).catch(e=>{r.debug&&console.error(`[AgentWidget] Failed to submit copy feedback:`,e)}),r.messageActions?.onCopy?.(e)},onFeedback:e=>{A.emit(`message:feedback`,e),Q?.isClientTokenMode()&&Q.submitMessageFeedback(e.messageId,e.type).catch(e=>{r.debug&&console.error(`[AgentWidget] Failed to submit feedback:`,e)}),r.messageActions?.onFeedback?.(e)}};r.statusIndicator;let nt=(e,t=r.statusIndicator??{})=>e===`idle`?t.idleText??ln.idle:e===`connecting`?t.connectingText??ln.connecting:e===`connected`?t.connectedText??ln.connected:e===`error`?t.errorText??ln.error:e===`paused`?t.pausedText??ln.paused:e===`resuming`?t.resumingText??ln.resuming:ln[e];function rt(e,t,n,r){if(!I()&&(n.mode===`transient`||e.classList.contains(`persona-mb-2`))&&(Br(e,dt,n),zr(e,n,r)),!(e.hasAttribute(Bg)||e.hasAttribute(Vg))){if(r===`idle`&&n.idleLink){e.textContent=``;let r=document.createElement(`a`);r.href=n.idleLink,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=t,r.style.color=`inherit`,r.style.textDecoration=`none`,e.appendChild(r)}else e.textContent=t}}let it=wm({config:r,showClose:L()}),{wrapper:at,panel:H,pillRoot:ot}=it.shell,st=it.panelElements,{container:U,body:W,messagesWrapper:G,starterSuggestions:ct,transcriptSuggestions:lt,suggestions:ut,textarea:K,sendButton:q,composerForm:dt,statusText:ft,welcomeHost:pt,welcomeIconHolder:ht,greetingHost:_t,introKicker:vt,introTitle:yt,introSubtitle:bt,closeButton:J,iconHolder:xt,headerTitle:St,headerSubtitle:Ct,header:wt,footer:Tt,actionsRow:Et}=st,Dt=st.leftActions,Ot=st.rightActions,kt=st.sendButtonWrapper,At=st.setSendButtonMode,Y=st.micButton,jt=st.micButtonWrapper,Mt=st.attachmentButton,Nt=st.attachmentButtonWrapper,Pt=st.attachmentInput,Ft=st.attachmentPreviewsContainer;U.classList.add(`persona-relative`),W.classList.add(`persona-relative`);let It=()=>Ae.label??``,Lt=()=>Ae.iconName??`arrow-down`,Rt=()=>Ae.enabled!==!1,zt=()=>je.mode??`anchor-top`,Bt=()=>zt()===`follow`||zt()===`anchor-top`&&Ma,Ut=()=>je.anchorTopOffset??16,Wt=()=>je.restorePosition??`bottom`,Gt=()=>je.pauseOnInteraction===!0,Kt=()=>je.showActivityWhilePinned!==!1,qt=()=>je.announce===!0,Jt=()=>je.scrollbar??`on-scroll`,Yt=z(`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`);Yt.type=`button`,Yt.style.display=`none`,Yt.setAttribute(`data-persona-scroll-to-bottom`,`true`);let Xt=z(`span`,`persona-flex persona-items-center`),Qt=z(`span`,``),en=z(`span`,``);en.setAttribute(`data-persona-scroll-to-bottom-count`,``),en.style.display=`none`,Yt.append(Xt,Qt,en),U.appendChild(Yt);let tn=z(`div`,`persona-stream-anchor-spacer`);tn.setAttribute(`aria-hidden`,`true`),tn.setAttribute(`data-persona-anchor-spacer`,``),tn.style.flexShrink=`0`,tn.style.pointerEvents=`none`,tn.style.height=`0px`,tn.style.display=`none`,W.appendChild(tn);let rn=z(`div`,`persona-sr-only`);rn.setAttribute(`aria-live`,`polite`),rn.setAttribute(`aria-atomic`,`true`),rn.setAttribute(`role`,`status`),rn.setAttribute(`data-persona-live-region`,``),Object.assign(rn.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`}),U.appendChild(rn);let an=null,on=null,sn=e=>{qt()&&e&&(on=e,an===null&&(an=setTimeout(()=>{an=null,on&&qt()&&(rn.textContent=on),on=null},400)))},cn=()=>{let t=e.ownerDocument.defaultView??window;return(r.launcher?.mobileFullscreen??!0)&&t.innerWidth<=(r.launcher?.mobileBreakpoint??640)&&(he||kf(r))||r.launcher?.fullHeight===!0&&!r.launcher.sidebarMode&&!kf(r)},un=()=>rm(r,cn()),dn=`empty`,fn=0,pn=()=>fn||parseFloat(e.style.getPropertyValue(`--persona-composer-lift`))||0,mn=()=>{let e=Tt.style.display===`none`?0:Tt.offsetHeight;Yt.style.bottom=`${e+pn()+12}px`};mn();let hn=()=>{Yn||(Tt.style.marginBottom=fn>0?`${fn}px`:``)},gn=()=>{let t=Dd(r,I()),n=un();e.setAttribute(`data-persona-welcome-fullscreen`,String(cn())),e.setAttribute(`data-persona-welcome-layout`,n.layout??`top`),e.setAttribute(`data-persona-welcome-layout-explicit`,r.welcome?.layout??``),e.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`);let i=Tt.style.display===`none`?0:Tt.offsetHeight,a=n.anchor===`center`&&dn===`empty`?Od(n.anchorComposerTop)??Od(`44%`):null,o=a!==null&&n.layout===`centered`&&r.welcome?.anchor===void 0&&r.welcome?.anchorComposerTop===void 0,s=o?getComputedStyle(W):null,c=parseFloat(e.style.getPropertyValue(`--persona-composer-overlay-height`))||0,l=parseFloat(e.style.getPropertyValue(`--persona-composer-lift`))||0,u=Math.max(0,(parseFloat(s?.paddingBottom??``)||0)-(t===`overlay`?c+l:0)),d=o?W.getBoundingClientRect().top-U.getBoundingClientRect().top:0,f=!o||pt.hidden?0:(pt.querySelector(`[data-persona-welcome-plugin]`)??pt).offsetHeight,p=a===null||I()?0:o?Math.max(0,Math.round((U.clientHeight-d-f-u-i)/2)):kd({columnHeight:U.clientHeight,footerHeight:i,fraction:a});e.style.setProperty(`--persona-composer-overlay-height`,`${i}px`),e.style.setProperty(`--persona-composer-lift`,`${t===`overlay`?p:0}px`),fn=t===`block`?p:0,hn(),mn()},_n=()=>{let e=!!It();Yt.setAttribute(`aria-label`,It()||`Jump to latest`),Yt.title=It(),Yt.setAttribute(`data-persona-scroll-to-bottom-has-label`,e?`true`:`false`),Xt.innerHTML=``;let t=P(Lt(),`14px`,`currentColor`,2);t?(Xt.appendChild(t),Xt.style.display=``):Xt.style.display=`none`,Qt.textContent=It(),Qt.style.display=e?``:`none`};_n();let vn=null,yn=null,X=vl();X.subscribe(e=>{try{U.dispatchEvent(new CustomEvent(`persona:composer:state`,{detail:e,bubbles:!0,composed:!0}))}catch{}});let bn=()=>{X.setText(K?.value??``)},xn=()=>{X.setMentionRefs(yn?.getMentionRefs()??[])},Sn=e=>({id:e.id,name:e.file.name,mimeType:e.file.type,size:e.file.size,status:e.status,progress:e.progress,error:e.error}),Cn=e=>{let t=Object.freeze(e.map(Sn));X.setAttachments(t);try{r.attachments?.onChange?.(t)}catch(e){console.error(`[AgentWidget] attachments.onChange failed:`,e)}Es()};X.setSelectedModelId(r.composer?.selectedModelId);let wn=()=>r.composer?.modes??[],Tn=()=>su(wn(),r.composer?.modeGroups);{let e=uu(r.composer?.defaultActiveModeIds??[],wn());e.length&&X.setActiveModeIds(e)}function Dn(e){if(X.getState().selectedModelId!==e){X.setSelectedModelId(e),An?.repaint();try{r.composer?.onModelChange?.(e)}catch(e){console.error(`[AgentWidget] composer.onModelChange failed:`,e)}}}function On(e){X.setActiveModeIds(e),Mn?.render(e,Tn()),Nn.forEach(e=>e.repaint()),sr?.resolve(),rc(),hr()}function kn(e){On(lu(X.getState().activeModeIds,e,wn(),r.composer?.modeGroups))}let An=null,jn=null,Mn=null,Nn=/* @__PURE__ */ new Map,Pn=null;function Fn(e){X.setQuote(e),Pn?.render(X.getState().quote),hr(),so()}let In=!1;function Ln(){let e=r.composer?.streamingSubmitBehavior??`block`;return e===`interrupt`?r.clientToken?`interrupt`:(!In&&r.debug===!0&&(In=!0,typeof console<`u`&&console.warn(`[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".`)),`block`):e}let Rn=null;function zn(e){X.setPendingSubmission(e),Rn?.render(X.getState().pendingSubmission),hr()}let Bn=e=>{let t=Nn.get(e);if(t)return t;let n=pu({groupId:e,getGroup:()=>r.composer?.modeGroups?.find(t=>t.id===e),getModes:()=>wn().filter(t=>t.groupId===e),getActiveIds:()=>X.getState().activeModeIds,onSelect:e=>kn(e)});return Nn.set(e,n),n},Vn=()=>{let e=[],t=X.getState().activeModeIds,n=/* @__PURE__ */ new Set;if(wn().forEach((i,a)=>{if(au(i.groupId,r.composer?.modeGroups)){let t=i.groupId;if(n.has(t))return;n.add(t);let o=Bn(t);o.action.order=ru(a),o.action.label=r.composer?.modeGroups?.find(e=>e.id===t)?.label??t,e.push(o.action)}else e.push({id:nu(i.id),kind:`button`,placement:`start`,order:ru(a),presentation:i.presentation??`auto`,label:i.label,shortLabel:i.shortLabel,iconName:i.iconName,pressed:t.includes(i.id),onSelect:()=>kn(i.id)})}),r.composer?.models?.length&&!u.some(e=>e.renderComposer)){let t=r.composer?.modelPicker?.presentation??`native`;(!An||jn!==t)&&(jn=t,An=Zl({getModels:()=>r.composer?.models??[],getSelectedModelId:()=>X.getState().selectedModelId,onSelect:e=>Dn(e),presentation:t,getSuffix:()=>r.composer?.modelPicker?.suffix})),e.push(An.action)}return e},Hn=null,Un=u.find(e=>e.renderHeader);if(Un?.renderHeader){let e=Un.renderHeader({config:r,defaultRenderer:()=>{let e=Yf({config:r,showClose:L()});return Xf(U,e,r),e.header},onClose:()=>_s(!1,`user`)});if(e){let t=wt;t&&(t.replaceWith(e),wt=e,it.header.element=e)}}let Wn=()=>{He&&(W.style.display=`none`,Tt.parentNode?.insertBefore(He.element,Tt),He.update())},Gn=()=>{if(!Le){Je();return}if(Ue=!0,He?Wn():Qm().then(e=>{!He&&Ue&&Le&&(He=e.createEventStreamView({buffer:Le,getFullHistory:()=>Le.getAllFromStore(),onClose:()=>Kn(),config:r,plugins:u,getThroughput:()=>Re?.getMetric()??{status:`idle`},renderIconByName:P}),Wn())}).catch(()=>{Kn()}),qn){qn.style.boxShadow=`inset 0 0 0 1.5px ${Kf.actionIconColor}`;let e=r.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&qn.classList.add(e))}let e=()=>{if(!Ue)return;let t=Date.now();t-Ge>=200&&(He?.update(),Ge=t),We=requestAnimationFrame(e)};Ge=0,We=requestAnimationFrame(e),So(),A.emit(`eventStream:opened`,{timestamp:Date.now()})},Kn=()=>{if(Ue){if(Ue=!1,He&&He.element.remove(),W.style.display=``,qn){qn.style.boxShadow=``;let e=r.features?.eventStream?.classNames?.toggleButtonActive;e&&e.split(/\s+/).forEach(e=>e&&qn.classList.remove(e))}We!==null&&(cancelAnimationFrame(We),We=null),So(),A.emit(`eventStream:closed`,{timestamp:Date.now()})}},qn=null;if(Oe){let e=r.features?.eventStream?.classNames,t=`persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1`+(e?.toggleButton?` `+e.toggleButton:``);qn=z(`button`,t),qn.style.width=`28px`,qn.style.height=`28px`,qn.style.color=Kf.actionIconColor,qn.type=`button`,qn.setAttribute(`aria-label`,`Event Stream`),qn.title=`Event Stream`;let n=k(f.Activity,`18px`,`currentColor`,1.5);n&&qn.appendChild(n);let i=st.clearChatButtonWrapper,a=st.closeButtonWrapper,o=i||a;o&&o.parentNode===wt?wt.insertBefore(qn,o):wt.appendChild(qn),qn.addEventListener(`click`,()=>{Ue?Kn():Gn()})}let Jn=e=>{let t=r.attachments;if(!t?.enabled)return;let n=e.querySelector(`[data-persona-composer-attachment-previews]`)??e.querySelector(`.persona-attachment-previews`);if(!n){n=z(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),n.setAttribute(`data-persona-composer-attachment-previews`,``),n.style.display=`none`;let t=e.querySelector(`[data-persona-composer-form]`);t?.parentNode?t.parentNode.insertBefore(n,t):e.insertBefore(n,e.firstChild)}if(!(e.querySelector(`[data-persona-composer-attachment-input]`)??e.querySelector(`input[type="file"]`))){let n=z(`input`);n.type=`file`,n.setAttribute(`data-persona-composer-attachment-input`,``),n.accept=(t.allowedTypes??Ui).join(`,`),n.multiple=(t.maxFiles??4)>1,n.style.display=`none`,n.setAttribute(`aria-label`,t.buttonTooltipText??`Attach files`),e.appendChild(n)}},Yn=!1,Xn=e=>{let t=u.find(e=>e.renderComposer);if(!t?.renderComposer)return null;let n=r.composer,i=m?Q.isStreaming():!1;return t.renderComposer({config:r,defaultRenderer:e,requestRender:()=>of(),storage:h(t.id),onSubmit:e=>{Q&&!Q.isStreaming()&&Pl(e.trim(),{consumeDraft:!1})},streaming:i,disabled:i,openAttachmentPicker:()=>{Ss()||Pt?.click()},models:n?.models,selectedModelId:X.getState().selectedModelId??n?.selectedModelId,onModelChange:e=>Dn(e),onVoiceToggle:r.voiceRecognition?.enabled===!0?()=>{Hn?.()}:void 0})},Zn=Xn(()=>lp({config:r}).footer);Zn&&(it.replaceComposer(Zn),Tt=it.composer.footer,Yn=!0);let Qn=null,$n=e=>{dt=e.form,K=e.input,kt=e.sendButton?e.sendButton.parentElement:null,e.sendButton&&(q=e.sendButton),e.micButton&&(Y=e.micButton,jt=e.micButton.parentElement),e.found.status&&(ft=e.found.status),e.found.suggestions&&(ut=e.found.suggestions),e.attachmentButton&&(Mt=e.attachmentButton,Nt=e.attachmentButton.parentElement),Pt=e.attachmentInput??null,Ft=e.attachmentPreviews??null,e.found.actionsRow&&(Et=e.found.actionsRow),Dt=e.found.actionsStart,Ot=e.found.actionsEnd};function er(){let e=K;if(!e)return;let t=r.composer?.inputAttributes,n=!t?.ariaLabel&&!(e instanceof HTMLTextAreaElement)?e.getAttribute(`aria-label`):null;$i(e,t),n&&e.setAttribute(`aria-label`,n),Qi(e,{submitKey:r.composer?.submitKey,insertNewlineOnTouchEnter:r.composer?.insertNewlineOnTouchEnter,coarsePointer:Ji(e)}),qi(e,Ki(r.composer?.maxLines,I()?5:3))}let tr=e=>{Qn=xl(e,{debug:r.debug===!0}),Qn&&$n(Qn),er()};Jn(Tt),tr(Tt),bn();let nr=Ed(r,I());nr&&(G.style.maxWidth=nr,G.style.marginLeft=`auto`,G.style.marginRight=`auto`,G.style.width=`100%`,_t.style.maxWidth=nr,_t.style.marginLeft=`auto`,_t.style.marginRight=`auto`,_t.style.width=`100%`,ct.style.maxWidth=nr,lt.style.maxWidth=nr,lt.style.marginLeft=`auto`,lt.style.marginRight=`auto`,lt.style.width=`100%`);let rr=()=>{let e=Ed(r,I());if(e&&!I())for(let t of[dt,ut,Ft,ft])t&&(t.style.maxWidth=e,t.style.marginLeft=`auto`,t.style.marginRight=`auto`,t.style.width=`100%`)};rr();let ir=()=>{r.attachments?.enabled&&Pt&&Ft&&(vn?vn.remountPreviews(Ft):(vn=hl.fromConfig(r.attachments,Cn),vn.setPreviewsContainer(Ft)),Qn?.addListener(Pt,`change`,e=>{let t=e.target;vn?.handleFileSelect(t.files),t.value=``}),U.querySelector(`.persona-attachment-drop-overlay`)||U.appendChild(Xg(r.attachments.dropOverlay)))};ir();let ar=()=>yn?.prefetch(),or=()=>{if(!r.contextMentions?.enabled||!K)return;let e=Ia();if(!e){let e=K;Pa().then(()=>{!yn&&K===e&&e.isConnected&&(or(),sr?.resolve())},()=>{});return}let t=Qn?.header??null,n=t?eu(t):void 0;if(yn=e.createContextMentionOrchestrator({deps:{loadContextMentions:_a,loadContextMentionsInline:xa,renderLucideIcon:P,createMentionButton:pa},config:r,textarea:K,anchor:dt??K,getMessages:()=>Q.getMessages(),liveRegionHost:U,chipRow:n}),yn&&!n){let e=K;e.parentElement?.insertBefore(yn.contextRow,e)}};or();let sr=null,cr={getState:()=>X.getState(),getValue:()=>K?.value??``,setValue:e=>{K&&(K.value=e,K.dispatchEvent(new Event(`input`,{bubbles:!0})),bn())},submit:()=>{Cu(Qn?.form??null)},openAttachmentPicker:()=>{Ss()||Pt?.click()},toggleVoice:()=>{Hn?.()},requestRender:()=>sr?.resolve()},lr=()=>{let e=[];return(yn?.affordanceButtons??[]).forEach((t,n)=>{e.push({id:`core:mention-${n}`,placement:`start`,order:Al.mention+n,element:t,managed:!0})}),Nt&&e.push({id:`core:attachment`,placement:`start`,order:Al.attachment,element:Nt}),jt&&e.push({id:`core:mic`,placement:`end`,order:Al.mic,element:jt}),kt&&e.push({id:`core:send`,placement:`end`,order:Al.send,element:kt}),e},ur=()=>{sr?.destroy(),sr=Jl({getBindings:()=>Qn,collect:()=>({builtIns:lr(),configActions:[...Vn(),...r.composer?.actions??[]],plugins:u,contributionContext:{config:r,getState:()=>X.getState(),requestRender:()=>sr?.resolve()},debug:r.debug===!0}),actionContext:cr,getState:()=>X.getState(),getOverflow:()=>r.composer?.actionOverflow,reportError:(e,t)=>{typeof console<`u`&&console.error(`[AgentWidget] composer action "${t.actionId}" failed:`,e)}}),sr.resolve()};ur();let dr=()=>{if(Mn?.destroy(),Mn=null,!Tn().length)return;let e=Qn?.header;e&&(Mn=tu({row:eu(e),onRemove:e=>kn(e),initialIds:X.getState().activeModeIds}),Mn.render(X.getState().activeModeIds,Tn()))};dr();let fr=()=>{Pn?.destroy(),Pn=null,Rn?.destroy(),Rn=null;let e=Qn?.header;e&&(Pn=mu({onDismiss:()=>Fn(void 0)}),e.appendChild(Pn.element),Pn.render(X.getState().quote),Ln()===`defer-one`&&(Rn=hu({onEdit:()=>Sl(),onRemove:()=>zn(void 0)}),e.appendChild(Rn.element),Rn.render(X.getState().pendingSubmission)))};fr();let pr=xu(),mr=()=>{let e=Qn?.header?.querySelector(Ql);if(e)return e.childElementCount>0;let t=X.getState();return t.mentionRefs.length>0||uu(t.activeModeIds,Tn()).length>0};function hr(){let e=X.getState(),t=pr.observe(Su(K),e.text);Tt.toggleAttribute(`data-persona-composer-compact`,bu({text:e.text,wrapped:t,hasAttachments:e.attachments.length>0,hasChips:mr(),hasQuote:e.quote!==void 0,hasPendingSubmission:e.pendingSubmission!==void 0}))}function gr(){r.composer?.layout===`single-row`&&!I()?Tt.setAttribute(`data-persona-composer-layout`,`single-row`):Tt.removeAttribute(`data-persona-composer-layout`)}gr(),X.subscribe(()=>{sr?.sync(),Es(),Ds(),hr(),so()}),Ds();let _r=!1,yr=e=>{if(_r||r.debug!==!0)return;let t=[`messages`,`composer`].filter(t=>e[t]);t.length&&(_r=!0,console.warn(`[persona] layout.slots.${t.join(` and layout.slots.`)} ${t.length>1?`are`:`is`} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let e=r.layout?.slots??{};yr(e);let t=e=>{switch(e){case`body-top`:return W.querySelector(`[data-persona-intro-card]`);case`messages`:return G;case`footer-top`:return ut;case`composer`:return dt;case`footer-bottom`:return ft;default:return null}},n=(e,t)=>{switch(e){case`header-left`:case`header-center`:case`header-right`:if(e===`header-left`)wt.insertBefore(t,wt.firstChild);else if(e===`header-right`)wt.appendChild(t);else{let e=wt.querySelector(`.persona-flex-col`);e?e.parentNode?.insertBefore(t,e.nextSibling):wt.appendChild(t)}break;case`body-top`:{let e=W.querySelector(`[data-persona-intro-card]`);e?e.replaceWith(t):W.insertBefore(t,W.firstChild);break}case`body-bottom`:W.appendChild(t);break;case`footer-top`:ut.replaceWith(t);break;case`footer-bottom`:ft.replaceWith(t)}};for(let[i,a]of Object.entries(e))if(a)try{let e=a({config:r,defaultContent:()=>t(i)});e&&n(i,e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Error rendering slot "${i}":`,e)}})(),G.addEventListener(`click`,e=>{let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`button[data-persona-copy-tool-detail]`);n&&(e.preventDefault(),e.stopPropagation(),Lm(n))});let xr=e=>{let t=e.target.closest(`button[data-expand-header="true"]`);if(!t)return;let n=t.closest(`.persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble`);if(!n)return;let c=n.getAttribute(`data-message-id`);if(!c)return;Ra(),Co();let l=t.getAttribute(`data-bubble-type`);if(n.classList.contains(`persona-activity-row`)){o.manual(c);let e=n.parentElement?.closest(`[data-persona-tool-group]`);e?.dataset.messageId&&o.manual(e.dataset.messageId)}if(l===`reasoning`)a.has(c)?a.delete(c):a.add(c),jm(c,n,a);else if(l===`tool`)i.has(c)?i.delete(c):i.add(c),Hm(c,n,i,r);else if(l===`approval`&&g){let e=((r.approval===!1?void 0:r.approval)?.detailsDisplay??`collapsed`)===`expanded`,t=s.get(c)??e;s.set(c,!t),g.updateApprovalDetailsUI(c,n,r,s)}la.delete(c)};G.addEventListener(`pointerdown`,e=>{e.target.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),xr(e))}),G.addEventListener(`click`,e=>{e.detail===0&&e.target.closest(`.persona-activity-row`)&&xr(e)}),G.addEventListener(`keydown`,e=>{let t=e.target;(e.key===`Enter`||e.key===` `)&&t.closest(`button[data-expand-header="true"]`)&&(e.preventDefault(),xr(e))}),G.addEventListener(`copy`,e=>{let{clipboardData:t}=e;if(!t)return;let n=G.getRootNode(),r=typeof n.getSelection==`function`?n.getSelection():window.getSelection();if(!r||r.isCollapsed)return;let i=r.toString(),a=jd(i);a&&a!==i&&(t.setData(`text/plain`,a),e.preventDefault())});let Sr=/* @__PURE__ */ new Map,Cr=null,wr=`idle`,Tr={idle:{icon:`volume-2`,label:`Read aloud`},loading:{icon:`loader-circle`,label:`Loading…`},playing:{icon:`pause`,label:`Pause`},paused:{icon:`play`,label:`Resume`}},Er=(e,t)=>{let{icon:n,label:r}=Tr[t];e.setAttribute(`aria-label`,r),e.title=r,e.setAttribute(`aria-pressed`,t===`idle`?`false`:`true`),e.classList.toggle(`persona-message-action-active`,t!==`idle`),e.classList.toggle(`persona-message-action-loading`,t===`loading`);let i=P(n,14,`currentColor`,2);i&&(e.innerHTML=``,e.appendChild(i))},Dr=()=>{G.querySelectorAll(`[data-action="read-aloud"]`).forEach(e=>{let t=e.closest(`[data-actions-for]`)?.getAttribute(`data-actions-for`)??null;Er(e,t&&t===Cr?wr:`idle`)})};G.addEventListener(`click`,e=>{let t=e.target.closest(`.persona-message-action-btn[data-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`[data-actions-for]`);if(!n)return;let i=n.getAttribute(`data-actions-for`);if(!i)return;let a=t.getAttribute(`data-action`);if(a===`copy`){let e=Q.getMessages().find(e=>e.id===i);if(e&&tt.onCopy){let n=e.content||``;navigator.clipboard.writeText(n).then(()=>{t.classList.add(`persona-message-action-success`);let e=k(f.Check,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e)),setTimeout(()=>{t.classList.remove(`persona-message-action-success`);let e=k(f.Copy,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))},2e3)}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to copy message:`,e)}),tt.onCopy(e)}}else if(a===`read-aloud`)Q.toggleReadAloud(i);else if(a===`upvote`||a===`downvote`){let e=(Sr.get(i)??null)===a,r=a===`upvote`?`thumbs-up`:`thumbs-down`;if(e){Sr.delete(i),t.classList.remove(`persona-message-action-active`);let e=P(r,14,`currentColor`,2);e&&(t.innerHTML=``,t.appendChild(e))}else{let e=a===`upvote`?`downvote`:`upvote`,o=n.querySelector(`[data-action="${e}"]`);if(o){o.classList.remove(`persona-message-action-active`);let t=P(e===`upvote`?`thumbs-up`:`thumbs-down`,14,`currentColor`,2);t&&(o.innerHTML=``,o.appendChild(t))}Sr.set(i,a),t.classList.add(`persona-message-action-active`);let s=P(r,14,`currentColor`,2);s&&(s.setAttribute(`fill`,`currentColor`),t.innerHTML=``,t.appendChild(s)),t.classList.remove(`persona-message-action-pop`),t.offsetWidth,t.classList.add(`persona-message-action-pop`);let c=Q.getMessages().find(e=>e.id===i);c&&tt.onFeedback&&tt.onFeedback({type:a,messageId:c.id,message:c})}}else if(a===`regenerate`)Or?.regenerate(i);else if(a===`edit`)Or?.edit(i);else if(a===`quote`)Or?.quote(i);else if(a?.startsWith(`custom:`)){let e=a.slice(7),t=r.messageActions?.custom?.find(t=>t.id===e),n=Q.getMessages().find(e=>e.id===i);if(!t||!n)return;try{t.onSelect(n)}catch(t){console.error(`[AgentWidget] messageActions.custom "${e}" onSelect failed:`,t)}}});let Or=null;G.addEventListener(`click`,e=>{let t=e.target.closest(`button[data-approval-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.closest(`.persona-approval-bubble`);if(!n)return;let r=n.getAttribute(`data-message-id`);if(!r)return;let i=t.getAttribute(`data-approval-action`);if(!i)return;let a=i===`approve`?`approved`:`denied`,o=Q.getMessages().find(e=>e.id===r);if(!o?.approval)return;let s=n.querySelector(`[data-approval-buttons]`);s&&s.querySelectorAll(`button`).forEach(e=>{e.disabled=!0,e.style.opacity=`0.5`,e.style.cursor=`not-allowed`}),rs(o.approval)?Q.resolveWebMcpApproval(r,a):Q.resolveApproval(o.approval,a)});let kr=null,Ar=!1,jr=null,Mr=()=>{},Nr=`none`,Pr=null,Fr={artifacts:[],selectedId:null},Ir=!1,Lr=!1,Rr=!1,Vr=!1,Ur=()=>Vr||Fr.artifacts.some(e=>ke(r.features?.artifacts,e)===`panel`),Wr=()=>Fr.artifacts.length>0&&!Ir&&Ur(),Gr={current:null},Kr=(e,t)=>{let n=Q.getArtifactById(t),r=n?.markdown,i=n?.title||`artifact`,a=n?.file,o=n?.artifactType??`markdown`;if(!r){let t=(e.closest(`[data-open-artifact], [data-artifact-inline]`)?.closest(`[data-message-id]`))?.getAttribute(`data-message-id`);if(t){let e=Q.getMessages().find(e=>e.id===t);if(e?.rawContent)try{let t=JSON.parse(e.rawContent);r=t?.props?.markdown,i=t?.props?.title||i,t?.props?.file&&typeof t.props.file==`object`&&(a=t.props.file),!n&&typeof t?.props?.artifactType==`string`&&(o=t.props.artifactType)}catch{}}}return{markdown:r,title:i,file:a,artifactType:o}};G.addEventListener(`click`,e=>{let t=e.target.closest(`[data-download-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-download-artifact`);if(!n||r.features?.artifacts?.onArtifactAction?.({type:`download`,artifactId:n})===!0)return;let{markdown:i,title:a,file:o}=Kr(t,n);if(!i)return;let s=lh();s&&s.triggerArtifactDownload(s.downloadInfoFor({title:a,markdown:i,file:o}))}),G.addEventListener(`click`,e=>{let t=e.target.closest(`[data-artifact-custom-action]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-artifact-custom-action`);if(!n)return;let i=t.closest(`[data-artifact-inline]`),a=i?null:t.closest(`[data-open-artifact]`),o=i?i.getAttribute(`data-artifact-inline`):a?.getAttribute(`data-open-artifact`)??null,s=(i?r.features?.artifacts?.inlineActions:r.features?.artifacts?.cardActions)?.find(e=>e.id===n);if(!s)return;let{markdown:c,title:l,file:u,artifactType:d}=Kr(t,o??``),f={artifactId:o,title:l,artifactType:d,markdown:c,file:u};try{Promise.resolve(s.onClick(f)).catch(()=>{})}catch{}}),G.addEventListener(`click`,e=>{let t=e.target.closest(`[data-copy-artifact]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-copy-artifact`);if(!n)return;let r=Q.getArtifactById(n),i=lh();if(!i)return;let a=``;if(r)a=i.artifactCopyText(r);else{let{markdown:e,file:r,artifactType:o}=Kr(t,n);o===`markdown`&&(a=i.artifactCopyText({id:n,artifactType:`markdown`,status:`complete`,markdown:e??``,...r?{file:r}:{}}))}a&&navigator.clipboard.writeText(a).then(()=>{let e=k(f.Check,16,`currentColor`,2);e&&(t.replaceChildren(e),setTimeout(()=>{let e=k(f.Copy,16,`currentColor`,2);e&&t.replaceChildren(e)},1500))}).catch(()=>{})}),G.addEventListener(`click`,e=>{let t=e.target.closest(`[data-expand-artifact-inline]`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.getAttribute(`data-expand-artifact-inline`);n&&r.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:n})!==!0&&(Ir=!1,Vr=!0,Lr=!0,Rr=!0,Q.selectArtifact(n),gi())}),G.addEventListener(`click`,e=>{let t=e.target;if(t.closest(`[data-download-artifact]`)||t.closest(`[data-artifact-custom-action]`))return;let n=t.closest(`[data-open-artifact]`);if(!n)return;let i=n.getAttribute(`data-open-artifact`);i&&r.features?.artifacts?.onArtifactAction?.({type:`open`,artifactId:i})!==!0&&(e.preventDefault(),e.stopPropagation(),Ir=!1,Vr=!0,Q.selectArtifact(i),gi())}),G.addEventListener(`keydown`,e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target;(t.hasAttribute(`data-open-artifact`)||t.hasAttribute(`data-expand-artifact-inline`))&&(e.preventDefault(),t.click())});let qr=st.composerOverlay,Jr=e=>{Pa().catch(()=>{}),Vt(e,r,qr)},Yr=null,Xr={mount:e,overlay:qr,sessionRef:Gr,config:()=>r},Zr=!1,Qr=e=>t=>{let n=t.target,r=n?.closest?.(`[data-persona-ask-sheet-for]`);if(!r||!(e===`click`?n?.closest(`[data-ask-user-action]`):t.key===`Enter`&&n?.matches?.(`[data-ask-free-text-input="true"]`)))return;let i=n=>{Yr??=n.createAskUserSheetHandlers(Xr),Yr[e](t)},a=Ia();a?i(a):Zr||(Zr=!0,Pa().then(e=>{Zr=!1,r.isConnected&&i(e)},()=>{Zr=!1}))};qr.addEventListener(`click`,Qr(`click`)),qr.addEventListener(`keydown`,Qr(`keydown`));let $r=e=>{if(!/^[1-9]$/.test(e.key)||e.metaKey||e.ctrlKey||e.altKey)return;let t=e.target;if(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable)return;let n=qr.querySelector(`[data-persona-ask-sheet-for]`);if(!n||n.getAttribute(`data-ask-layout`)!==`rows`||n.getAttribute(`data-multi-select`)===`true`)return;let r=Number(e.key),i=n.querySelectorAll(`[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]`)[r-1];i&&(e.preventDefault(),i.click())};document.addEventListener(`keydown`,$r);let ei=null,ti=null,ni=null,ri=null,ii=()=>{},oi=!1,si=``,ci=``;function li(){ri?.(),ri=null}let ui=()=>{let e=Lc?.railShell?Lc.railHost:null,t=e?.isConnected?e:null,n=t?t.getBoundingClientRect().width:0;return n<=0?200:n+360},di=()=>{if(!ei||!ti)return;let t=e.classList.contains(`persona-artifact-welded-split`),n=e.ownerDocument.defaultView??window,r=n.innerWidth<=640;if(!t||e.classList.contains(`persona-artifact-narrow-host`)||r){ti.style.removeProperty(`position`),ti.style.removeProperty(`left`),ti.style.removeProperty(`top`),ti.style.removeProperty(`bottom`),ti.style.removeProperty(`width`),ti.style.removeProperty(`z-index`);return}let i=ei.firstElementChild;if(!i||i===ti)return;ti.style.position=`absolute`,ti.style.top=`0`,ti.style.bottom=`0`,ti.style.width=`10px`,ti.style.zIndex=`5`;let a=qh(ei,n),o=i.offsetWidth+a/2-5;ti.style.left=`${Math.max(0,o)}px`},fi=()=>{},mi=()=>{let t=e.ownerDocument.defaultView??window,n=r.launcher?.mobileFullscreen??!0,i=r.launcher?.mobileBreakpoint??640;return!n||t.innerWidth>i?!1:he||kf(r)},hi=()=>!dh(r)||!Wr()||e.classList.contains(`persona-artifact-narrow-host`)||mi()||(e.ownerDocument.defaultView??window).innerWidth<641?`none`:gh(r)?`detached`:`welded`,gi=()=>{if(!kr||!dh(r))return;_h(e,r),vh(e,r),fi();let t=r.features?.artifacts?.layout?.narrowHostMaxWidth??520,n=H.getBoundingClientRect().width||0;e.classList.toggle(`persona-artifact-narrow-host`,n>0&&n<=t);let i=Wr();kr.setVisible(i),kr.update(Fr),Ir?(kr.setMobileOpen(!1),kr.element.classList.add(`persona-hidden`),kr.backdrop?.classList.add(`persona-hidden`),Lr=!1,Rr=!1):Fr.artifacts.length>0&&Ur()?(kr.element.classList.remove(`persona-hidden`),kr.setMobileOpen(!0)):(kr.setMobileOpen(!1),kr.element.classList.add(`persona-hidden`),kr.backdrop?.classList.add(`persona-hidden`),Lr=!1,Rr=!1);let a=r.features?.artifacts?.layout?.showExpandToggle===!0;if(kr.setExpandToggleVisible(a),kr.setCopyButtonVisible(r.features?.artifacts?.layout?.showCopyButton===!0),kr.setRefreshButtonVisible(typeof r.features?.artifacts?.layout?.onDocumentToolbarRefresh==`function`),kr.setCustomActions(r.features?.artifacts?.toolbarActions??[]),kr.setTabFade(r.features?.artifacts?.layout?.tabFade),kr.setRenderTabBar(r.features?.artifacts?.renderTabBar),!a&&!Rr&&(Lr=!1),Lr!==oi){let e=kr.element;Lr?(si=e.style.width,ci=e.style.maxWidth,e.style.removeProperty(`width`),e.style.removeProperty(`max-width`)):(si&&(e.style.width=si),ci&&(e.style.maxWidth=ci),si=``,ci=``),oi=Lr}e.classList.toggle(`persona-artifact-expanded`,Lr),kr.setExpanded(Lr);let o=hi();o!==Nr&&(Nr=o,Mr()),ii()};if(dh(r)){H.style.position=`relative`;let t=z(`div`,`persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0`),n=z(`div`,`persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root`);t.appendChild(U),ei=n,n.appendChild(t),H.appendChild(n);let i=e=>{Ar||kr||(kr=e.createArtifactPane(r,{onSelect:e=>Gr.current?.selectArtifact(e),onDismiss:()=>{Ir=!0,gi()},onToggleExpand:()=>{let e=!Lr,t=Fr.selectedId??Fr.artifacts[Fr.artifacts.length-1]?.id??null;r.features?.artifacts?.onArtifactAction?.({type:`expand`,artifactId:t,expanded:e})!==!0&&(Lr=e,e||(Rr=!1),gi())}}),kr.element.classList.add(`persona-hidden`),n.appendChild(kr.element),kr.backdrop&&H.appendChild(kr.backdrop),ii(),gi())},a=lh();a?i(a):(uh(()=>{let e=lh();e&&i(e)}),ch().catch(()=>{})),ii=()=>{if(ei&&kr){if(r.features?.artifacts?.layout?.resizable!==!0)ni?.(),ni=null,li(),ti&&=(ti.remove(),null),kr.element.style.removeProperty(`width`),kr.element.style.removeProperty(`maxWidth`);else{if(!ti){let t=z(`div`,`persona-artifact-split-handle persona-shrink-0 persona-h-full`);t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`aria-label`,`Resize artifacts panel`),t.tabIndex=0;let n=e.ownerDocument,i=n.defaultView??window,a=a=>{if(!kr||a.button!==0||e.classList.contains(`persona-artifact-narrow-host`)||e.classList.contains(`persona-artifact-expanded`)||i.innerWidth<=640)return;a.preventDefault(),li();let o=a.clientX,s=kr.element.getBoundingClientRect().width,c=r.features?.artifacts?.layout,l=n=>{let r=ei.getBoundingClientRect().width,a=e.classList.contains(`persona-artifact-welded-split`),l=qh(ei,i),u=a?0:t.getBoundingClientRect().width||6,d=Jh(s-(n.clientX-o),r,l,u,c?.resizableMinWidth,c?.resizableMaxWidth,ui());kr.element.style.width=`${d}px`,kr.element.style.maxWidth=`none`,di()},u=()=>{n.removeEventListener(`pointermove`,l),n.removeEventListener(`pointerup`,u),n.removeEventListener(`pointercancel`,u),ri=null;try{t.releasePointerCapture(a.pointerId)}catch{}};ri=u,n.addEventListener(`pointermove`,l),n.addEventListener(`pointerup`,u),n.addEventListener(`pointercancel`,u);try{t.setPointerCapture(a.pointerId)}catch{}};t.addEventListener(`pointerdown`,a),ti=t,ei.insertBefore(t,kr.element),ni=()=>{t.removeEventListener(`pointerdown`,a)}}if(ti){let e=Wr();ti.classList.toggle(`persona-hidden`,!e),di()}}}},fi=()=>{if(!he||!kr||(r.launcher?.sidebarMode??!1)||kf(r)&&jf(r).reveal===`emerge`)return;let t=e.ownerDocument.defaultView??window,n=r.launcher?.mobileFullscreen??!0,i=r.launcher?.mobileBreakpoint??640;if(n&&t.innerWidth<=i||!yh(r,he))return;let a=sm(r).width,o=r.features?.artifacts?.layout?.expandedPanelWidth??`min(720px, calc(100vw - 24px))`;Wr()?(H.style.width=o,H.style.maxWidth=o):(H.style.width=a,H.style.maxWidth=a)},typeof ResizeObserver<`u`&&(jr=new ResizeObserver(()=>{gi()}),jr.observe(H))}else H.appendChild(U);I()&&ot&&(st.peekBanner&&ot.appendChild(st.peekBanner),ot.appendChild(Tt)),e.appendChild(at),ot&&e.appendChild(ot);let _i=()=>{let t=mi()||I()&&r.launcher?.composerBar?.expandedSize===`fullscreen`||r.launcher?.fullHeight===!0&&!r.launcher?.sidebarMode&&!kf(r);if(G.style.gap=t?`var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))`:`var(--persona-components-message-gap, 12px)`,G.style.setProperty(`--persona-transcript-gap`,G.style.gap),I()){H.style.width=`100%`,H.style.maxWidth=`100%`;let e=r.launcher?.composerBar??{},t=at.dataset.state===`expanded`,n=e.expandedSize??`anchored`;if(!(t&&n!==`fullscreen`)){U.style.background=``,U.style.border=``,U.style.borderRadius=``,U.style.overflow=``,U.style.boxShadow=``;return}let i=r.theme?.components?.panel,a=Sd(r),o=(e,t)=>e==null||e===``?t:Yu(a,e)??e;U.style.background=`var(--persona-surface, #ffffff)`,U.style.border=o(i?.border,`1px solid var(--persona-border)`),U.style.borderRadius=o(i?.borderRadius,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`),U.style.boxShadow=o(i?.shadow,`var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))`),U.style.overflow=`hidden`;return}let n=kf(r),i=r.launcher?.sidebarMode??!1,a=n||i||(r.launcher?.fullHeight??!1),o=r.launcher?.enabled===!1,s=r.launcher?.detachedPanel===!0,c=r.theme?.components?.panel,l=r.darkTheme?.components?.panel,u=yd(r)===`dark`?Hr(c??{},l??{}):c,d=Sd(r),f=(e,t)=>e==null||e===``?t:Yu(d,e)??e,p=e.ownerDocument.defaultView??window,m=r.launcher?.mobileFullscreen??!0,h=r.launcher?.mobileBreakpoint??640,g=p.innerWidth<=h,_=m&&g&&he,v=n&&m&&g,y=r.launcher?.position??`bottom-left`,b=y===`bottom-left`||y===`top-left`,x=r.launcher?.zIndex??1e5,S=(e,t,n)=>`var(--persona-components-panel-modes-${e}-${t}, ${n})`,C=u?.modes?.floating,w=f(C?.border??u?.border,S(`floating`,`border`,`var(--persona-panel-border, 1px solid var(--persona-border))`)),T=f(C?.shadow??u?.shadow,S(`floating`,`shadow`,`var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))`)),E=f(C?.borderRadius??u?.borderRadius,S(`floating`,`borderRadius`,`var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))`)),D=s&&!_&&!v,O=_||v?`mobile`:D?`floating`:n?`docked`:i?`sidebar`:o?`inline`:`floating`,ee=u?.modes?.[O];D?e.setAttribute(`data-persona-panel-detached`,`true`):e.removeAttribute(`data-persona-panel-detached`);let k=D?w:i||_?`none`:w,A=D?T:_?`none`:i?b?`2px 0 12px rgba(0, 0, 0, 0.08)`:`-2px 0 12px rgba(0, 0, 0, 0.08)`:o?`none`:T;n&&!_&&!D&&(A=`none`,k=`none`);let te=D?E:i||_?`0`:E,ne=f(ee?.border??u?.border,S(O,`border`,k)),re=f(ee?.shadow??u?.shadow,S(O,`shadow`,A)),ie=f(ee?.borderRadius??u?.borderRadius,S(O,`borderRadius`,te)),ae=hi(),j=ae===`detached`,M=ae===`welded`;e.classList.toggle(`persona-artifact-detached-split`,j),e.classList.toggle(`persona-artifact-welded-split`,M);let N=`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)))))`,oe=(r.features?.artifacts?.layout?.chatSurface===`flush`?`flush`:`card`)==`flush`&&dh(r)&&gh(r)&&o&&!n;e.classList.toggle(`persona-artifact-chat-flush`,oe);let se=j||oe?`none`:re,ce=j?w:M?`none`:ne,le=j?E:ie;oe&&(ce=`none`,le=`0`);let ue=ee?.borderRadius!=null&&ee.borderRadius!==``||u?.borderRadius!=null&&u.borderRadius!==``,de=oe&&!ue?`0`:ie,fe=W.scrollTop;e.style.cssText=``,at.style.cssText=``,H.style.cssText=``,U.style.cssText=``,W.style.cssText=``,Yn||(Tt.style.cssText=``),Ue&&(W.style.display=`none`),(a||o)&&(e.style.minWidth=`0`);let pe=()=>{fe<=0||(W.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(W.scrollTop===fe)return;let e=W.scrollHeight-W.clientHeight;e<=0||(W.scrollTop=Math.min(fe,e))})};if(_){at.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`),at.style.cssText=`
41
41
  position: fixed !important;
42
42
  inset: 0 !important;
43
43
  width: 100% !important;
@@ -49,7 +49,7 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
49
49
  flex-direction: column !important;
50
50
  z-index: ${x} !important;
51
51
  background-color: var(--persona-surface, #ffffff) !important;
52
- `,U.style.cssText=`
52
+ `,H.style.cssText=`
53
53
  position: relative !important;
54
54
  display: flex !important;
55
55
  flex-direction: column !important;
@@ -62,7 +62,7 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
62
62
  padding: 0 !important;
63
63
  box-shadow: none !important;
64
64
  border-radius: 0 !important;
65
- `,W.style.cssText=`
65
+ `,U.style.cssText=`
66
66
  display: flex !important;
67
67
  flex-direction: column !important;
68
68
  flex: 1 1 0% !important;
@@ -73,7 +73,7 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
73
73
  overflow: hidden !important;
74
74
  border-radius: 0 !important;
75
75
  border: none !important;
76
- `,G.style.flex=`1 1 0%`,G.style.minHeight=`0`,G.style.overflowY=`auto`,wt.style.flexShrink=`0`,mn(),ye=!0,fe();return}let pe=tm(r);if(!i&&!n)o&&a?(U.style.width=`100%`,U.style.maxWidth=`100%`):(U.style.width=pe.width,U.style.maxWidth=pe.maxWidth);else if(n){if(Tf(r).reveal===`emerge`&&!s){let e=Tf(r).width;U.style.width=e,U.style.maxWidth=e}else U.style.width=`100%`,U.style.maxWidth=`100%`}if(di(),U.style.boxShadow=oe,U.style.borderRadius=ue,M?U.style.border=`none`:N&&(U.style.border=te),W.style.border=se,W.style.borderRadius=ce,W.style.boxShadow=M&&!ae?P:``,ae&&(W.style.background=`transparent`,G.style.background=`transparent`,wt.style.background=`transparent`,wt.style.borderTop=`none`),N){let e=r.features?.artifacts?.layout;Nr=e?.unifiedSplitOuterRadius?.trim()||e?.paneBorderRadius?.trim()||re}else Nr=null;let F=ee?.border!=null||u?.border!=null;if(n&&!_&&!D&&!M&&!N&&!F&&(W.style.border=`none`,Tf(r).side===`right`?W.style.borderLeft=`1px solid var(--persona-border)`:W.style.borderRight=`1px solid var(--persona-border)`),n&&!_&&N&&!F&&(Tf(r).side===`right`?U.style.borderLeft=`1px solid var(--persona-border)`:U.style.borderRight=`1px solid var(--persona-border)`),a&&(e.style.display=`flex`,e.style.flexDirection=`column`,e.style.height=`100%`,e.style.minHeight=`0`,o&&(e.style.width=`100%`),it.style.display=`flex`,it.style.flexDirection=`column`,it.style.flex=`1 1 0%`,it.style.minHeight=`0`,it.style.maxHeight=`100%`,it.style.height=`100%`,o&&(it.style.overflow=`hidden`),U.style.display=`flex`,U.style.flexDirection=`column`,U.style.flex=`1 1 0%`,U.style.minHeight=`0`,U.style.maxHeight=`100%`,U.style.height=`100%`,M||(U.style.overflow=`hidden`),W.style.display=`flex`,W.style.flexDirection=`column`,W.style.flex=`1 1 0%`,W.style.minHeight=`0`,W.style.maxHeight=`100%`,W.style.overflow=`hidden`,G.style.flex=`1 1 0%`,G.style.minHeight=`0`,G.style.overflowY=`auto`,wt.style.flexShrink=`0`),o&&(D||M||ae)&&!n&&(ae||(it.style.padding=`var(--persona-panel-inset)`),it.style.background=`var(--persona-panel-canvas-bg)`),it.classList.remove(`persona-bottom-6`,`persona-right-6`,`persona-left-6`,`persona-top-6`,`persona-bottom-4`,`persona-right-4`,`persona-left-4`,`persona-top-4`),!i&&!o&&!n&&(Nf[y]??Nf[`bottom-right`]).split(` `).forEach(e=>it.classList.add(e)),i){let e=ii(r).sidebarWidth?r.launcher?.sidebarWidth??`420px`:Uu(gd(r),`components.panel.width`)??`420px`;s?it.style.cssText=`
76
+ `,W.style.flex=`1 1 0%`,W.style.minHeight=`0`,W.style.overflowY=`auto`,Tt.style.flexShrink=`0`,hn(),be=!0,pe();return}let me=sm(r);if(!i&&!n)o&&a?(H.style.width=`100%`,H.style.maxWidth=`100%`):(H.style.width=me.width,H.style.maxWidth=me.maxWidth);else if(n){if(jf(r).reveal===`emerge`&&!s){let e=jf(r).width;H.style.width=e,H.style.maxWidth=e}else H.style.width=`100%`,H.style.maxWidth=`100%`}if(fi(),H.style.boxShadow=se,H.style.borderRadius=de,j?H.style.border=`none`:M&&(H.style.border=ne),U.style.border=ce,U.style.borderRadius=le,U.style.boxShadow=j&&!oe?N:``,oe&&(U.style.background=`transparent`,W.style.background=`transparent`,Tt.style.background=`transparent`,Tt.style.borderTop=`none`),M){let e=r.features?.artifacts?.layout;Pr=e?.unifiedSplitOuterRadius?.trim()||e?.paneBorderRadius?.trim()||ie}else Pr=null;let P=ee?.border!=null||u?.border!=null;if(n&&!_&&!D&&!j&&!M&&!P&&(U.style.border=`none`,jf(r).side===`right`?U.style.borderLeft=`1px solid var(--persona-border)`:U.style.borderRight=`1px solid var(--persona-border)`),n&&!_&&M&&!P&&(jf(r).side===`right`?H.style.borderLeft=`1px solid var(--persona-border)`:H.style.borderRight=`1px solid var(--persona-border)`),a&&(e.style.display=`flex`,e.style.flexDirection=`column`,e.style.height=`100%`,e.style.minHeight=`0`,o&&(e.style.width=`100%`),at.style.display=`flex`,at.style.flexDirection=`column`,at.style.flex=`1 1 0%`,at.style.minHeight=`0`,at.style.maxHeight=`100%`,at.style.height=`100%`,o&&(at.style.overflow=`hidden`),H.style.display=`flex`,H.style.flexDirection=`column`,H.style.flex=`1 1 0%`,H.style.minHeight=`0`,H.style.maxHeight=`100%`,H.style.height=`100%`,j||(H.style.overflow=`hidden`),U.style.display=`flex`,U.style.flexDirection=`column`,U.style.flex=`1 1 0%`,U.style.minHeight=`0`,U.style.maxHeight=`100%`,U.style.overflow=`hidden`,W.style.flex=`1 1 0%`,W.style.minHeight=`0`,W.style.overflowY=`auto`,Tt.style.flexShrink=`0`),o&&(D||j||oe)&&!n&&(oe||(at.style.padding=`var(--persona-panel-inset)`),at.style.background=`var(--persona-panel-canvas-bg)`),at.classList.remove(`persona-bottom-6`,`persona-right-6`,`persona-left-6`,`persona-top-6`,`persona-bottom-4`,`persona-right-4`,`persona-left-4`,`persona-top-4`),!i&&!o&&!n&&(zf[y]??zf[`bottom-right`]).split(` `).forEach(e=>at.classList.add(e)),i){let e=ai(r).sidebarWidth?r.launcher?.sidebarWidth??`420px`:Yu(Sd(r),`components.panel.width`)??`420px`;s?at.style.cssText=`
77
77
  position: fixed !important;
78
78
  top: var(--persona-panel-inset) !important;
79
79
  bottom: var(--persona-panel-inset) !important;
@@ -86,7 +86,7 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
86
86
  flex-direction: column !important;
87
87
  z-index: ${x} !important;
88
88
  ${b?`left: var(--persona-panel-inset) !important; right: auto !important;`:`left: auto !important; right: var(--persona-panel-inset) !important;`}
89
- `:it.style.cssText=`
89
+ `:at.style.cssText=`
90
90
  position: fixed !important;
91
91
  top: 0 !important;
92
92
  bottom: 0 !important;
@@ -99,7 +99,7 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
99
99
  flex-direction: column !important;
100
100
  z-index: ${x} !important;
101
101
  ${b?`left: 0 !important; right: auto !important;`:`left: auto !important; right: 0 !important;`}
102
- `,U.style.cssText=`
102
+ `,H.style.cssText=`
103
103
  position: relative !important;
104
104
  display: flex !important;
105
105
  flex-direction: column !important;
@@ -110,10 +110,10 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
110
110
  min-height: 0 !important;
111
111
  margin: 0 !important;
112
112
  padding: 0 !important;
113
- box-shadow: ${oe} !important;
114
- border-radius: ${ue} !important;
115
- ${M?`border: none !important;`:N?`border: ${te} !important;`:``}
116
- `,U.style.setProperty(`width`,`100%`,`important`),U.style.setProperty(`max-width`,`100%`,`important`),W.style.cssText=`
113
+ box-shadow: ${se} !important;
114
+ border-radius: ${de} !important;
115
+ ${j?`border: none !important;`:M?`border: ${ne} !important;`:``}
116
+ `,H.style.setProperty(`width`,`100%`,`important`),H.style.setProperty(`max-width`,`100%`,`important`),U.style.cssText=`
117
117
  display: flex !important;
118
118
  flex-direction: column !important;
119
119
  flex: 1 1 0% !important;
@@ -122,18 +122,18 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
122
122
  min-height: 0 !important;
123
123
  max-height: 100% !important;
124
124
  overflow: hidden !important;
125
- border-radius: ${ce} !important;
126
- border: ${se} !important;
127
- ${M&&!ae?`box-shadow: ${P} !important;`:``}
128
- ${ae?`background: transparent !important;`:``}
129
- `,Jn||(wt.style.cssText=`
125
+ border-radius: ${le} !important;
126
+ border: ${ce} !important;
127
+ ${j&&!oe?`box-shadow: ${N} !important;`:``}
128
+ ${oe?`background: transparent !important;`:``}
129
+ `,Yn||(Tt.style.cssText=`
130
130
  flex-shrink: 0 !important;
131
131
  border-top: none !important;
132
132
  padding: 8px 16px 12px 16px !important;
133
- ${ae?`background: transparent !important;`:``}
134
- `)}if(!o&&!n){let e=i?``:`padding-top: 1.25em !important;`,t=i?``:`z-index: ${r.launcher?.zIndex??1e5} !important;`;it.style.cssText+=`max-height: -moz-available !important; max-height: stretch !important;`+e+t}mn(),fe()},_i=()=>{e.style.setProperty(`--persona-content-max-width`,bd(r,L()))},vi=!1;function yi(){r.layout?.topFade&&G.scrollTop>1?G.setAttribute(`data-persona-top-fade`,`true`):G.removeAttribute(`data-persona-top-fade`)}let bi=()=>{yi();let t=xd(r,L());L()&&r.composer?.placement&&r.debug===!0&&!vi&&(vi=!0,console.warn(`[persona] composer.placement is ignored in composer-bar mount mode.`));let n=ln();e.setAttribute(`data-persona-composer-placement`,t),e.setAttribute(`data-persona-conversation-state`,un),e.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`),e.style.setProperty(`--persona-composer-anchor-gap`,n.composerGap??`24px`),hn()},xi=()=>{if(L())return;let t=Cf(r),n=r.launcher?.sidebarMode??!1;if(t||n||(r.launcher?.fullHeight??!1)||!me)return;let i=e.ownerDocument.defaultView??window,a=r.launcher?.mobileFullscreen??!0,o=r.launcher?.mobileBreakpoint??640;if(a&&i.innerWidth<=o)return;let s=tm(r);U.style.height=s.height,U.style.maxHeight=s.maxHeight};gi(),vd(e,r),dh(e,r),fh(e,r),_i(),bi(),jr=()=>{gi(),xi(),vd(e,r),dh(e,r),fh(e,r),_i(),bi(),Nr?e.style.setProperty(`--persona-artifact-welded-outer-radius`,Nr):e.style.removeProperty(`--persona-artifact-welded-outer-radius`),Ze(),Xe()};let Q=[];Q.push(()=>{kr=!0}),Q.push(()=>{p.forEach(e=>e()),d.destroy()}),Q.push(()=>{document.removeEventListener(`keydown`,Qr)}),Q.push(()=>{rn!==null&&clearTimeout(rn)});let Si=null,Ci=null;Q.push(()=>{Si?.(),Si=null,Ci?.(),Ci=null}),Ar&&Q.push(()=>{Ar?.disconnect(),Ar=null}),Q.push(()=>{ti?.(),ti=null,ci(),ei&&=(ei.remove(),null),Or?.element.style.removeProperty(`width`),Or?.element.style.removeProperty(`maxWidth`),Or?.destroy()}),De&&Q.push(()=>{Be=!0,ze=null,Ue!==null&&(cancelAnimationFrame(Ue),Ue=null),Ve?.destroy(),Ve=null,Ie?.destroy(),Ie=null,Ne=null});let wi=null,Ti=()=>{wi&&=(wi(),null),r.colorScheme===`auto`&&(wi=yd(()=>{vd(e,r)}))};Ti(),Q.push(()=>{wi&&=(wi(),null)}),Q.push(()=>{y=!0,v?.()}),Q.push(()=>{C=!0});let Ei=!1;Q.push(()=>{Ei=!0});let Di=(t,n)=>{let r=Zd(t,n);return r||!qd.includes(t)?r:(_f().then(r=>{if(Ei)return;Jd(r.wipe),Jd(r.glyphCycle);let i=Zd(t,n);i&&mf(i,e)}).catch(()=>{}),null)},Oi=r.features?.streamAnimation;if(Oi?.type&&Oi.type!==`none`){let t=Di(Oi.type,Oi.plugins);t&&mf(t,e),Q.push(()=>pf(e))}let Ai=Mf(lt),ji=Mf(st),Mi=Mf(ct),Ni=[Ai,ji,Mi];Q.push(()=>{Ni.forEach(e=>e.destroy())});let Pi=null,$,Fi=null,Ii=!1,Li=0,Ri=null,zi=e=>e.reduce((e,t)=>t.role===`user`?e+1:e,0),Bi=e=>{for(let t=e.length-1;t>=0;t--)if(Xt(e[t]))return e[t].id??null;return null},Vi=!1,Ui=()=>{Vi||r.debug!==!0||(Vi=!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".`))},Wi=!1,Ji=!1,Xi=(e,t)=>{Wi||r.debug!==!0||t.enabled&&!t.expose&&(Ii||Ji&&($.isStreaming()||e.some(Xt)||(Wi=!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.`))))},ea=e=>{if(!$)return;let t=e??$.getMessages(),n=e=>{e.render([],$,q,t)},i=e=>{Ni.forEach(t=>{t!==e&&n(t)})};Fi&&(zi(t)>Li||Bi(t)!==Ri)&&(Fi=null);let a=tn(r);Xi(t,a);let o=a.enabled?Qt(t):null,s=Fi??o,c=Fi?`host`:`agent`;if(s){let e=r.suggestions?.followUps,n=e?.placement??(e?`auto`:`composer`),a=(n===`auto`?L()?`composer`:`after-message`:n)===`after-message`?Mi:Ai;i(a),a.render(s,$,q,t,r.suggestionChipsConfig,{source:c,surface:`followUp`,variant:e?.variant??`chip`,behavior:e?.behavior??`send`,overflow:e?.overflow??`wrap`,maxItems:e?.maxItems??4,config:r,plugins:u,submitPrompt:Ml});return}if(t.some(e=>e.role===`user`)){Ni.forEach(n);return}let l=r.future?.v5Defaults===!0,d=sn(),f=r.suggestions?.starters??(l?{}:void 0);if(f){let e=$p(ln(),t),a=f.placement??`auto`,o=a===`auto`?e?`welcome`:`composer`:a;if(o===`welcome`&&!e){Ui(),Ni.forEach(n);return}let s=o===`welcome`?ji:Ai;i(s),s.render(f.items??r.suggestionChips,$,q,t,r.suggestionChipsConfig,{surface:`starter`,variant:f.variant??(l&&!d?`chip`:`card`),behavior:f.behavior??`send`,overflow:f.overflow??`wrap`,maxItems:f.maxItems??(l&&!d?3:4),config:r,plugins:u,submitPrompt:Ml})}else i(Ai),Ai.render(r.suggestionChips,$,q,t,r.suggestionChipsConfig,{surface:`starter`,variant:`chip`,behavior:`send`,overflow:`wrap`,maxItems:4,config:r,plugins:u,submitPrompt:Ml})},ra=()=>{Fi&&(Fi=null,ea())},ia=e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length){ra();return}let n=$?$.getMessages():[];Fi=t,Ii=!0,Li=zi(n),Ri=Bi(n),ea(n)},oa=!1,ca=kd(),la=/* @__PURE__ */ new Map,ua=/* @__PURE__ */ new Map,da=/* @__PURE__ */ new Map,pa=null,ma=null;function ha(){if(!pa)return;let e=pa;pa=null,ma?.destroy(),ma=null,ca.delete(e),W.querySelector(`#wrapper-${e}`)?.removeAttribute(`data-preserve-runtime`),$&&ts(K,$.getMessages(),we)}let _a=0,va=O()!==null,ya=Pd(),xa=0,Sa=null,Ca=!1,wa=!1,Ta=0,Ea=null,Da=null,Oa=!1,ka=!1,Aa=null,ja=!0,Ma=!1,Pa=null,Ia=!1,La=()=>{Ia=!0,Va()},Ra=null,za=null,Ba=()=>{e.setAttribute(`data-persona-scrollbar`,qt()),qt()!==`on-scroll`&&(za!==null&&clearTimeout(za),za=null,G.removeAttribute(`data-persona-scrollbar-visible`))},Va=()=>{qt()===`on-scroll`&&(G.setAttribute(`data-persona-scrollbar-visible`,``),za!==null&&clearTimeout(za),za=setTimeout(()=>{za=null,Id(G,24)&&G.removeAttribute(`data-persona-scrollbar-visible`)},1e3))};Ba(),Q.push(()=>{za!==null&&clearTimeout(za)});let Ha=/* @__PURE__ */ new Map,Ua=!1,Wa=null,Ga={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};mr();let Ka=r.voiceRecognition?.autoResume??!1,qa=()=>$.isVoiceActive()||$.isBargeInActive(),Ja=!1,Ya=e=>{A.emit(`voice:state`,{active:Ga.active,source:e,timestamp:Date.now()})},Xa=()=>{ue(e=>({...e,voiceState:{active:Ga.active,timestamp:Date.now(),manuallyDeactivated:Ga.manuallyDeactivated}}))},Za=()=>{if(r.voiceRecognition?.enabled===!1)return;let e=Bg(ne.voiceState),t=!!e.active,n=Number(e.timestamp??0);Ga.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-n<3e4&&setTimeout(()=>{Ga.active||(Ga.manuallyDeactivated=!1,ms(r.voiceRecognition?.provider)?$.toggleVoice().then(()=>{Ga.active=qa(),Ya(`restore`),Ga.active?Bu():(Xa(),bl(`Tap the mic to resume your voice call`,1e4))}):Iu(`restore`))},ms(r.voiceRecognition?.provider)?0:1e3)},Qa=e=>{Ja=!e.persisted,Ga.active&&Xa()};typeof window<`u`&&(window.addEventListener(`pagehide`,Qa),Q.push(()=>window.removeEventListener(`pagehide`,Qa)));let $a=()=>$?Vg($.getMessages()).filter(e=>!e.__skipPersist):[],eo=null,to=(e,t)=>{typeof console<`u`&&console.error(e,t)},no=(e,t)=>{let n=()=>{try{let n=e();return!n||typeof n.then!=`function`?null:Promise.resolve(n).catch(e=>{to(t,e)})}catch(e){return to(t,e),null}},r=eo,i=r?r.then(()=>n()??void 0):n();if(!i)return;let a=i.finally(()=>{eo===a&&(eo=null)});eo=a};function ro(e){if(!j?.save)return;let t=e?Vg(e):$?$a():[],n=te&&$?.getResumableHandle();n&&(ne={...ne,durableResume:{executionId:n.executionId,after:n.lastEventId}});let r={messages:t,metadata:ne,artifacts:Pr.artifacts,selectedArtifactId:Pr.selectedId,...io?{draft:io}:{}};no(()=>j.save(r),`[AgentWidget] Failed to persist state:`)}let io,ao=()=>!j?.save||r.persistState===!1?!1:typeof r.persistState!=`object`||r.persistState.persist?.draft!==!1,oo=pu({write:()=>{if(!ao())return;let e=Z.getState(),t=du({text:e.text,mentionRefs:e.mentionRefs,contentSegments:ml(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(io)&&(io=t,ro())}});function so(){ao()&&oo.schedule()}function co(){oo.flush()}function lo(e){if(!ao())return;let t=fu(e,{mentionSourceIds:(r.contextMentions?.sources??[]).map(e=>e.id),modelIds:(r.composer?.models??[]).map(e=>e.id),modes:r.composer?.modes??[]});t&&(io=e,q&&!q.value&&(q.value=t.text,q.dispatchEvent(new Event(`input`,{bubbles:!0})),yn()),t.selectedModelId&&(Z.setSelectedModelId(t.selectedModelId),kn?.repaint()),Dn(t.activeModeIds??[]),t.quote&&Pn(t.quote),oo.cancel())}function uo(){oo.cancel(),io&&(io=void 0,ao()&&ro())}let fo=null,po=()=>it.querySelector(`#persona-scroll-container`)||G,mo=()=>{fo!==null&&(cancelAnimationFrame(fo),fo=null),Ca=!1},ho=()=>{Sa!==null&&(cancelAnimationFrame(Sa),Sa=null),wa=!1,mo()},go=()=>oa&&bo()&&(Rt()!==`anchor-top`||Gt()),_o=()=>{let e=Ft()||`Jump to latest`,t=go();Jt.toggleAttribute(`data-persona-scroll-to-bottom-streaming`,t),Ta>0?($t.textContent=String(Ta),$t.style.display=``,Jt.setAttribute(`aria-label`,`${e} (${Ta} new)`)):($t.textContent=``,$t.style.display=`none`,Jt.setAttribute(`aria-label`,t?`${e} (response streaming below)`:e))},vo=()=>{Ta!==0&&(Ta=0,_o())},yo=()=>{let e=Ea?.spacerHeight??0;return e<=0?Id(G,24):Fo(e)-G.scrollTop-G.clientHeight<=24},bo=()=>zt()?!ya.isFollowing():!yo(),xo=()=>!!$&&$.getMessages().length>0,So=()=>{if(!Lt()||$e()){Jt.parentNode&&Jt.remove(),Jt.style.display=`none`;return}Jt.parentNode!==W&&W.appendChild(Jt),pn();let e=Fd(G)>0&&bo()&&xo();e?_o():vo(),Jt.style.display=e?``:`none`},Co=()=>{ya.pause()&&(ho(),So())},To=()=>{ya.resume(),vo(),So()},Eo=(e=!1)=>{zt()&&xo()&&ya.isFollowing()&&(e||oa)&&(Sa!==null&&(cancelAnimationFrame(Sa),Sa=null),wa=!0,Sa=requestAnimationFrame(()=>{Sa=null,wa=!1,ya.isFollowing()&&Oo(po(),e?220:140)}))},Do=(e,t,n,r=()=>!0)=>{let i=e.scrollTop,a=t(),o=a-i;if(mo(),Math.abs(o)<1){Ca=!0,e.scrollTop=a,xa=e.scrollTop,Ca=!1;return}let s=performance.now();Ca=!0;let c=e=>1-(1-e)**3,l=u=>{if(!r()){mo();return}let d=t();d!==a&&(a=d,o=a-i);let f=u-s,p=Math.min(f/n,1),m=c(p);e.scrollTop=i+o*m,xa=e.scrollTop,p<1?fo=requestAnimationFrame(l):(e.scrollTop=a,xa=e.scrollTop,fo=null,Ca=!1)};fo=requestAnimationFrame(l)},Oo=(e,t=500)=>{let n=Fd(e)-e.scrollTop;Math.abs(n)<1?xa=e.scrollTop:Math.abs(n)>=80?(mo(),Ca=!0,e.scrollTop=Fd(e),xa=e.scrollTop,Ca=!1):Do(e,()=>Fd(e),t,()=>ya.isFollowing())},ko=()=>{if(!xo()){So();return}let e=po();Ca=!0,e.scrollTop=Fd(e),xa=e.scrollTop,Ca=!1,So()},Ao=e=>{let t=0,n=e;for(;n&&n!==G;)t+=n.offsetTop,n=n.offsetParent;return t},jo=()=>{let e=G.getRootNode();return(typeof e.getSelection==`function`?e.getSelection():null)??G.ownerDocument.getSelection()},Mo=()=>zd(jo(),G),No=()=>{if(Ut()!==`last-user-turn`)return!1;let e=$?.getMessages()??[];if(e.length<2)return!1;let t=[...e].reverse().find(e=>e.role===`user`);if(!t)return!1;let n=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(t.id):t.id.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),r=G.querySelector(`[data-message-id="${n}"]`);if(!r)return!1;let i=Math.min(Math.max(0,Ao(r)-Ht()),Fd(G));return Ca=!0,G.scrollTop=i,xa=G.scrollTop,Ca=!1,Rt()===`follow`&&!Id(G,24)&&ya.pause(),So(),!0},Po=e=>{let t=Math.max(0,Math.round(e));en.style.height=`${t}px`,en.style.display=t>0?``:`none`,Ea&&(Ea.spacerHeight=Math.max(0,e))},Fo=e=>{let t=parseFloat(getComputedStyle(G).paddingBottom)||0,n=0;for(let e of Array.from(G.children)){if(e===en||e.offsetHeight===0)continue;let t=Ao(e)+e.offsetHeight;t>n&&(n=t)}let r=G.scrollHeight-e;return n>0?Math.min(n+t,r):r},Io=()=>{if(!Ea||Ea.spacerHeight<=0)return;let e=Fo(Ea.spacerHeight),t=Math.max(0,Math.round(G.scrollTop)+G.clientHeight-e+24);t<Ea.spacerHeight&&(Po(t),So())},Lo=()=>{Da!==null&&(cancelAnimationFrame(Da),Da=null),mo(),Ea=null,en.style.height=`0px`,en.style.display=`none`},Ro=e=>typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),zo=e=>G.querySelector(`[data-message-id="${Ro(e)}"]`),Bo=e=>{Da!==null&&cancelAnimationFrame(Da),Da=requestAnimationFrame(()=>{Da=null;let t=Ro(e),n=G.querySelector(`[data-message-id="${t}"]`);if(!n)return;let r=Ao(n),i=Ea?.spacerHeight??0,a=Fo(i),{targetScrollTop:o,spacerHeight:s}=Bd({anchorOffsetTop:r,topOffset:Ht(),viewportHeight:G.clientHeight,contentHeight:a,slack:24});Ea={initialSpacerHeight:s,contentHeightAtAnchor:a,spacerHeight:s},Po(s),Do(G,()=>n.isConnected?Math.max(0,Ao(n)-Ht()):o,220)})},Vo=()=>{if(Rt()!==`anchor-top`||!Ea||!Pa)return;let e=zo(Pa);if(!e)return;mo();let t=Ea.spacerHeight,n=Fo(t),{targetScrollTop:r,spacerHeight:i}=Bd({anchorOffsetTop:Ao(e),topOffset:Ht(),viewportHeight:G.clientHeight,contentHeight:n,slack:24});Ea={initialSpacerHeight:i,contentHeightAtAnchor:n,spacerHeight:i},Po(i),Ca=!0,G.scrollTop=r,xa=G.scrollTop,Ca=!1,So()},Ho=()=>{if(zt()){if(!ya.isFollowing()||Id(G,1))return;Eo(!oa)}else{if(Ea&&Ea.initialSpacerHeight>0){let e=G.scrollHeight-Ea.spacerHeight,t=Vd({initialSpacerHeight:Ea.initialSpacerHeight,contentHeightAtAnchor:Ea.contentHeightAtAnchor,currentContentHeight:e});t!==Ea.spacerHeight&&Po(t)}So()}},Uo=e=>{let t=Rt();t===`follow`?(To(),Eo(!0)):t===`anchor-top`&&(ja=!1,Ma=!0,Ia=!1,Pa=e,Bo(e))},Wo=()=>{Rt()===`anchor-top`&&(Ma?ja=!1:(ja=!0,Lo(),To(),Eo(!0)))},Go=e=>{if(Aa===null)return!0;let t=zo(Aa),n=zo(e);if(!t||!n)return!0;let r=Ao(n)-Ao(t);return Ht()+r>G.clientHeight-96},Ko=e=>{if(Rt()!==`anchor-top`||!Ma||Ia||Mo())return;let t=Aa===null;for(let n of e)if(!t)n.id===Aa&&(t=!0);else if(Nd(n)){if(n.id===Pa||!Go(n.id))return;Pa=n.id,Bo(n.id);return}},qo=e=>{let t=/* @__PURE__ */ new Map;e.forEach(e=>{let n=Ha.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!n&&e.role===`assistant`&&(A.emit(`assistant:message`,e),!ka&&(Rt()!==`anchor-top`||Gt())&&bo()&&(Ta+=1,_o(),So(),on(Ta===1?`1 new message below.`:`${Ta} new messages below.`))),e.role===`assistant`&&n?.streaming&&e.streaming===!1&&A.emit(`assistant:complete`,e),e.variant===`approval`&&e.approval&&(n?e.approval.status!==`pending`&&A.emit(`approval:resolved`,{approval:e.approval,decision:e.approval.status}):A.emit(`approval:requested`,{approval:e.approval,message:e}))}),Ha.clear(),t.forEach((e,t)=>{Ha.set(t,e)})},Jo=(e,t)=>{let n=t===`user`?`user`:`assistant`,i=r.layout?.messages?.[n],a=i?.width??`content`,o=i?.maxWidth??(a===`full`?`var(--persona-message-${n}-max-width, 100%)`:void 0);e.classList.add(`persona-message-row`),e.classList.remove(`persona-message-row-user`,`persona-message-row-assistant`,`persona-message-row-system`,`persona-message-width-content`,`persona-message-width-full`),e.classList.add(`persona-message-row-${t}`,`persona-message-width-${a}`),e.classList.toggle(`persona-justify-end`,t===`user`),e.setAttribute(`data-message-role`,t),e.setAttribute(`data-message-width`,a),o?e.style.setProperty(`--persona-message-row-max-width`,o):e.style.removeProperty(`--persona-message-row-max-width`)},Xo=(e,t)=>{let n=document.createElement(`div`);return n.className=`persona-flex`,n.id=`wrapper-${e}`,n.setAttribute(`data-wrapper-id`,e),Jo(n,t),n},Qo=(e,t,n)=>{let c=/* @__PURE__ */ new Set;for(let e of t){let t=e.variant===`tool`?`tool`:e.variant===`reasoning`?`reasoning`:null;if(!t||cs(r,t)!==`row`)continue;let n=t===`tool`?r.features?.toolCallDisplay:r.features?.reasoningDisplay;n?.expandable!==!1&&(c.add(e.id),o.observe(e,t,t===`tool`?i:a,n))}let l=document.createElement(`div`),d=(()=>{let e=u.find(e=>e.renderLoadingIndicator);if(e?.renderLoadingIndicator)return e.renderLoadingIndicator;if(r.loadingIndicator?.render)return r.loadingIndicator.render})(),f=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),p=/* @__PURE__ */ new Set,m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Set,g=u.some(e=>e.renderAskUserQuestion),v=[],y=[],b=r.enableComponentStreaming!==!1,x=r.approval!==!1,C=[],w=r.messageActions,T=w?.showRegenerate===!0&&w.enabled!==!1&&Wr.current?.isStreaming()!==!0?wc(t):null,E=w?.showEdit===!0&&w.enabled!==!1,D=w?.showQuote===!0&&w.enabled!==!1,O=null,k=r.features?.reasoningDisplay?.completedVisibility,A=e=>k===`removed`||k===`removed-when-short`&&Fe(e,r.features?.reasoningDisplay?.shortThinkThreshold),j=r.features?.toolCallDisplay?.completedVisibility===`removed`,te=e=>e.variant===`reasoning`&&e.reasoning?.status===`complete`?A(e.reasoning):j&&e.variant===`tool`&&e.toolCall?.status===`complete`;if(t.forEach(t=>{if(te(t))return;if(p.add(t.id),m.set(t.id,t.role),pa===t.id&&ma){let e=Xo(t.id,t.role);e.setAttribute(`data-persona-message-edit-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),O={messageId:t.id,element:ma.element};return}let o=g&&pt(t),c=x&&t.variant===`approval`&&!!t.approval,f=!o&&t.role===`assistant`&&!t.variant&&b&&Dg(t);!c&&da.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),da.delete(t.id)),!f&&ua.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),ua.delete(t.id));let w=pt(t)?`:${t.agentMetadata?.askUserQuestionAnswered?`a`:`u`}:${t.agentMetadata?.askUserQuestionAnswers?Object.keys(t.agentMetadata.askUserQuestionAnswers).length:0}`:``,k={canRegenerate:T===t.id,canEdit:E&&Tc(t),canQuote:D&&!t.variant&&(t.content?.trim().length??0)>0},A=`${k.canRegenerate?`r`:``}${k.canEdit?`e`:``}${k.canQuote?`q`:``}`,j=Od(t,_a)+w+`:${A}`,ne=o||c||f?null:Ad(ca,t.id,j);if(ne){l.appendChild(ne.cloneNode(!0)),pt(t)&&t.toolCall?.id&&t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(h.add(t.toolCall.id),qr(t));return}let re=null,ie=u.find(e=>!!(t.variant===`reasoning`&&e.renderReasoning||t.variant===`tool`&&e.renderToolCall||!t.variant&&e.renderMessage)),M=r.layout?.messages;if(pt(t)&&t.agentMetadata?.askUserQuestionAnswered===!0){la.delete(t.id),e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`);return}if(Xt(t)&&tn(r).enabled)return;if(pt(t)&&r.features?.askUserQuestion?.enabled!==!1){let e=u.find(e=>typeof e.renderAskUserQuestion==`function`);if(e&&Wr.current){let n=la.get(t.id),i=n!==j,a=null;if(i){let{payload:n,complete:i}=ht(t),o=t.id,s=()=>Wr.current?.getMessages().find(e=>e.id===o);a=e.renderAskUserQuestion({message:t,payload:n,complete:i,resolve:e=>{let t=s();t&&Wr.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=s();e?.agentMetadata?.awaitingLocalTool&&(Wr.current?.markAskUserQuestionResolved(e),Wr.current?.resolveAskUserQuestion(e,`(dismissed)`))},config:r})}if(i&&a===null&&n==null){t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(h.add(t.toolCall.id),qr(t));return}let o=Xo(t.id,t.role);o.setAttribute(`data-ask-plugin-stub`,`true`),o.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(o),v.push({messageId:t.id,fingerprint:j,bubble:a});return}t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(h.add(t.toolCall.id),qr(t));return}if(c){let n=S();if(!n){l.appendChild(Xo(t.id,t.role));return}let i=u.find(e=>typeof e.renderApproval==`function`)??_,a=da.get(t.id)!==j,o=null;if(a&&i?.renderApproval){let e=t.id,a=(t,n)=>{let r=Wr.current?.getMessages().find(t=>t.id===e);r?.approval&&(r.approval.toolType===`webmcp`?Wr.current?.resolveWebMcpApproval(r.id,t):Wr.current?.resolveApproval(r.approval,t,n))};o=i.renderApproval({message:t,defaultRenderer:()=>n.createApprovalBubble(t,r,s),config:r,approve:e=>a(`approved`,e),deny:e=>a(`denied`,e)})}if(a&&o===null)e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),da.delete(t.id),re=n.createApprovalBubble(t,r,s);else{let e=Xo(t.id,t.role);e.setAttribute(`data-approval-plugin-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),C.push({messageId:t.id,fingerprint:j,bubble:o});return}}else if(ie){if(t.variant===`reasoning`&&t.reasoning&&ie.renderReasoning){if(!Te)return;re=ie.renderReasoning({message:t,defaultRenderer:()=>Em(t,r,a),config:r})}else if(t.variant===`tool`&&t.toolCall&&ie.renderToolCall){if(!Ee)return;re=ie.renderToolCall({message:t,defaultRenderer:()=>Lm(t,r,i),config:r})}else ie.renderMessage&&(re=ie.renderMessage({message:t,defaultRenderer:()=>{let e=Mp(t,n,M,r.messageActions,et,{loadingIndicatorRenderer:d,widgetConfig:r,actionEligibility:k});return t.role!==`user`&&ee(e,t,r,$),e},config:r}))}if(!re&&f){let i=Og(t);if(i){let a=ua.get(t.id),o=a!==j,s=r.wrapComponentDirectiveInBubble!==!1&&qm.getOptions(i.component)?.bubbleChrome!==!1,c=null;if(o){let a=wg(i,{config:r,message:t,transform:n});if(a&&i.component===`PersonaArtifactInline`){let n=a.hasAttribute(`data-artifact-inline`)?a:a.querySelector(`[data-artifact-inline]`),r=n?.getAttribute(`data-artifact-inline`)??``,i=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(r):r,o=r?e.querySelector(`#wrapper-${t.id}`)?.querySelector(`[data-artifact-inline="${i}"]`)??null:null;n&&o&&o!==n&&rh()?.hasLiveInlineArtifactBlock(o)&&(n===a?a=o:n.replaceWith(o))}if(a){if(s){let e=document.createElement(`div`);if(e.className=[`persona-message-bubble`,`persona-rounded-2xl`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-p-4`].join(` `),e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-mb-3 persona-text-sm persona-leading-relaxed`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(a),c=e}else{let e=document.createElement(`div`);if(e.className=`persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch`,e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),e.setAttribute(`data-persona-component-directive`,`true`),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(a),c=e}}}if(c||a!=null){let e=Xo(t.id,t.role);e.setAttribute(`data-component-directive-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),y.push({messageId:t.id,fingerprint:j,bubble:c});return}}}if(!re){if(t.variant===`reasoning`&&t.reasoning){if(!Te)return;re=Em(t,r,a)}else if(t.variant===`tool`&&t.toolCall){if(!Ee)return;re=Lm(t,r,i)}else if(t.variant===`approval`&&t.approval){if(r.approval===!1)return;let e=S();if(!e)return;re=e.createApprovalBubble(t,r,s)}else{let e=r.layout?.messages;re=e?.renderUserMessage&&t.role===`user`?e.renderUserMessage({message:t,config:r,streaming:!!t.streaming}):e?.renderAssistantMessage&&t.role===`assistant`?e.renderAssistantMessage({message:t,config:r,streaming:!!t.streaming}):Mp(t,n,e,r.messageActions,et,{loadingIndicatorRenderer:d,widgetConfig:r,actionEligibility:k}),t.role!==`user`&&re&&ee(re,t,r,$)}}let N=Xo(t.id,t.role);N.appendChild(re),jd(ca,t.id,j,N),l.appendChild(N)}),ot.composerOverlay&&ot.composerOverlay.querySelectorAll(`[data-persona-ask-sheet-for]`).forEach(e=>{let t=e.getAttribute(`data-persona-ask-sheet-for`);t&&!h.has(t)&&Vt(ot.composerOverlay,t)}),r.features?.toolCallDisplay?.grouped){let e=[],n=[],a=r.features.toolCallDisplay.groupedMode===`summary`;t.forEach(t=>{if(t.variant===`tool`&&t.toolCall&&Ee){if(j&&t.toolCall.status===`complete`)return;n.push(t)}else(t.variant!==`reasoning`||Te&&(t.reasoning?.status!==`complete`||!A(t.reasoning)))&&((n.length>1||a&&n.length>0)&&e.push(n),n=[])}),(n.length>1||a&&n.length>0)&&e.push(n),e.forEach(e=>{let t=e.map(e=>Array.from(l.children).find(t=>t instanceof HTMLElement&&t.getAttribute(`data-wrapper-id`)===e.id)).filter(e=>!!e);if(t.length<(a?1:2))return;let n=Xo(`tool-group-${e[0].id}`,`assistant`);if(n.setAttribute(`data-persona-tool-group-row`,`true`),r.features?.toolCallDisplay?.groupedMode===`collapsible`){let a=`tool-group-${e[0].id}`,s=e.some(e=>e.toolCall?.status!==`complete`),l={...e[0],id:a,toolCall:{id:a,name:`${e.length} tools`,status:s?`running`:`complete`,chunks:e.flatMap(e=>e.toolCall?.chunks??[]),success:!e.some(e=>e.toolCall?.success===!1)}};c.add(a),o.observe(l,`tool`,i,r.features.toolCallDisplay);let u=`${s?`Using`:`Used`} ${e.length} tools`,d=r.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall),defaultSummary:u,config:r}),f=fs(l,r,i.has(a),d??u);f.bubble.classList.add(`persona-tool-group`),f.body.dataset.personaToolGroupStack=`true`,t[0].before(n),n.appendChild(f.bubble),t.forEach((e,t)=>{e.style.setProperty(`--persona-message-row-max-width`,`100%`),e.style.setProperty(`--persona-activity-stagger`,`${t*40}ms`),e.classList.add(`persona-activity-group-child`),f.body.appendChild(e)});return}let s=document.createElement(`div`);s.className=`persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2`,s.setAttribute(`data-persona-tool-group`,`true`);let u=document.createElement(`div`);u.className=`persona-tool-group-summary persona-text-xs persona-text-persona-muted`,u.id=`tool-group-summary-${e[0].id}`;let d=`Called ${e.length} ${e.length===1?`tool`:`tools`}`,p=r.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall).filter(e=>!!e),defaultSummary:d,config:r});f(u,p)||(u.textContent=d);let m=document.createElement(`div`);m.className=`persona-tool-group-stack persona-flex persona-flex-col`,m.id=`tool-group-stack-${e[0].id}`,m.setAttribute(`data-persona-tool-group-stack`,`true`),s.appendChild(u),a||s.appendChild(m),n.appendChild(s),t[0].before(n),t.forEach((e,n)=>{if(a){e.remove();return}e.style.setProperty(`--persona-message-row-max-width`,`100%`);let r=document.createElement(`div`);r.className=`persona-tool-group-item persona-relative`,r.setAttribute(`data-persona-tool-group-item`,`true`),n<t.length-1&&r.setAttribute(`data-persona-tool-group-connector`,`true`),r.appendChild(e),m.appendChild(r)})})}o.prune(c),Md(ca,p);let ne=e=>e.variant===`tool`&&!Ee||e.variant===`reasoning`&&!Te||te(e),re=t.some(e=>e.role===`assistant`&&e.streaming&&!ne(e)),ie=t.length-1;for(;ie>=0&&ne(t[ie]);)ie--;let M=ie>=0?t[ie]:void 0,N=ie<t.length-1,P=M?.role===`assistant`&&!M.streaming&&M.variant!==`approval`&&!N;if(oa&&t.some(e=>e.role===`user`)&&!re&&!P){let e={config:r,streaming:!0,location:`standalone`,defaultRenderer:Sp},t=u.find(e=>e.renderLoadingIndicator),n=null;if(t?.renderLoadingIndicator&&(n=t.renderLoadingIndicator(e)),n===null&&r.loadingIndicator?.render&&(n=r.loadingIndicator.render(e)),n===null&&(n=Sp()),n){let e=document.createElement(`div`),t=r.loadingIndicator?.showBubble!==!1,i=r.layout?.messages?.layout??`bubble`;e.className=t?Ep(`assistant`,i).join(` `):[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-text`].join(` `),e.setAttribute(`data-typing-indicator`,`true`),t&&(e.style.color=`var(--persona-message-assistant-text, var(--persona-text))`,i!==`flat`&&(e.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,e.style.borderColor=`var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))`)),e.appendChild(n);let a=Xo(`typing-indicator`,`assistant`);a.appendChild(e),l.appendChild(a)}}if(!oa&&t.length>0){let e=t[t.length-1],n={config:r,lastMessage:e,messageCount:t.length},i=u.find(e=>e.renderIdleIndicator),a=null;if(i?.renderIdleIndicator&&(a=i.renderIdleIndicator(n)),a===null&&r.loadingIndicator?.renderIdle&&(a=r.loadingIndicator.renderIdle(n)),a){let e=document.createElement(`div`);e.className=r.loadingIndicator?.showBubble===!1?[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-primary`].join(` `):[`persona-rounded-2xl`,`persona-text-sm`,`persona-leading-relaxed`,`persona-shadow-sm`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-text-persona-primary`,`persona-px-5`,`persona-py-3`].join(` `),e.setAttribute(`data-idle-indicator`,`true`),e.appendChild(a);let t=Xo(`idle-indicator`,`assistant`);t.appendChild(e),l.appendChild(t)}}if(Vs(l),wd(e,l),Us(e),O){let{messageId:t,element:n}=O,r=e.querySelector(`#wrapper-${t}`);r&&n.parentElement!==r&&(Jo(r,m.get(t)??`user`),r.replaceChildren(n))}if(v.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of v){let i=e.querySelector(`#wrapper-${t}`);i&&(Jo(i,m.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),la.set(t,n)))}if(la.size>0)for(let e of la.keys())p.has(e)||la.delete(e);if(y.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of y){let i=e.querySelector(`#wrapper-${t}`);i&&(Jo(i,m.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),ua.set(t,n)))}if(ua.size>0)for(let e of ua.keys())p.has(e)||ua.delete(e);if(C.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of C){let i=e.querySelector(`#wrapper-${t}`);i&&(Jo(i,m.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),da.set(t,n)))}if(da.size>0)for(let e of da.keys())p.has(e)||da.delete(e)},$o=!1,es=()=>{$o||($o=!0,Tn().catch(()=>{}),T().catch(()=>{$o=!1}))},ts=(e,t,n)=>{t.length>0&&es(),Qo(e,t,n),Er()},ns=null,rs=()=>{if(ns)return;let t=e=>{let t=e.composedPath();t.includes(it)||at&&t.includes(at)||ys(!1,`user`)};ns=t,(e.ownerDocument??document).addEventListener(`pointerdown`,t,!0)},is=()=>{ns&&=((e.ownerDocument??document).removeEventListener(`pointerdown`,ns,!0),null)};Q.push(()=>is());let as=null,os=()=>{if(as)return;let t=e=>{e.key===`Escape`&&(e.isComposing||ys(!1,`user`))};as=t,(e.ownerDocument??document).addEventListener(`keydown`,t,!0)},ss=()=>{as&&=((e.ownerDocument??document).removeEventListener(`keydown`,as,!0),null)};Q.push(()=>ss());let us=!1,ps=/* @__PURE__ */ new Set,hs=()=>r.launcher?.composerBar?.peek?.streamAnimation||r.features?.streamAnimation,gs=()=>{if(!L())return;let t=ot.peekBanner,n=ot.peekTextNode;if(!t||!n)return;if(z){t.classList.remove(`persona-pill-peek--visible`);return}let r=$?.getMessages()??[],i;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.role===`assistant`&&t.content){i=t;break}}if(!i){t.classList.remove(`persona-pill-peek--visible`);return}let a=i.content,o=!!i.streaming,s=hs(),c=Wd(s),l=c.type===`none`?null:Di(c.type,s?.plugins),u=l?.isAnimating?.(i)===!0,d=l!==null&&(o||u);d&&l&&!ps.has(l.name)&&(mf(l,e),ps.add(l.name));let f=d&&l?.containerClass?l.containerClass:null,p=n.dataset.personaPeekStreamClass??null;p&&p!==f&&(n.classList.remove(p),delete n.dataset.personaPeekStreamClass),f&&p!==f&&(n.classList.add(f),n.dataset.personaPeekStreamClass=f),d?(n.style.setProperty(`--persona-stream-step`,`${c.speed}ms`),n.style.setProperty(`--persona-stream-duration`,`${c.duration}ms`)):(n.style.removeProperty(`--persona-stream-step`),n.style.removeProperty(`--persona-stream-duration`));let m=d?Qd(a,c.buffer,l,i,o):a;if(d&&c.placeholder===`skeleton`&&o&&(!m||!m.trim())){let e=document.createElement(`div`),t=cf();t.classList.add(`persona-pill-peek__skeleton`),e.appendChild(t),wd(n,e)}else{let e=Math.max(0,m.length-100),r=m.length>100?m.slice(-100):m,a=Ss(r);if(!d||!l){let e=m.length>100?`…${r}`:r;n.textContent!==e&&(n.textContent=e)}else{let o=a;(l.wrap===`char`||l.wrap===`word`)&&(o=of(a,l.wrap,`peek-${i.id}`,{skipTags:l.skipTags,startIndex:e}));let s=document.createElement(`div`);if(s.innerHTML=o,l.useCaret&&r.length>0){let e=sf(),t=s.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];n?.parentNode?n.parentNode.insertBefore(e,n.nextSibling):s.appendChild(e)}wd(n,s),l.onAfterRender?.({container:n,bubble:t,messageId:i.id,message:i,speed:c.speed,duration:c.duration})}}let h=oa||us;t.classList.toggle(`persona-pill-peek--visible`,h)};if(L()){let e=ot.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),ys(!0,`user`)};e.addEventListener(`pointerdown`,t),Q.push(()=>{e.removeEventListener(`pointerdown`,t)})}let t=()=>{us||(us=!0,gs())},n=()=>{us&&(us=!1,gs())};U.addEventListener(`pointerenter`,t),U.addEventListener(`pointerleave`,n),Q.push(()=>{U.removeEventListener(`pointerenter`,t),U.removeEventListener(`pointerleave`,n)}),at&&(at.addEventListener(`pointerenter`,t),at.addEventListener(`pointerleave`,n),Q.push(()=>{at.removeEventListener(`pointerenter`,t),at.removeEventListener(`pointerleave`,n)}))}let _s=e=>{let t=r.launcher?.composerBar??{},n=t.expandedSize??`anchored`,i=t.bottomOffset??`16px`,a=t.collapsedMaxWidth,o=t.expandedMaxWidth??`880px`,s=t.expandedTopOffset??`5vh`,c=t.modalMaxWidth??`880px`,l=t.modalMaxHeight??`min(90vh, 800px)`,u=`calc(100vw - 32px)`,d=it.style;if(d.left=``,d.right=``,d.top=``,d.bottom=``,d.transform=``,d.width=``,d.maxWidth=``,d.height=``,d.maxHeight=``,at){let e=at.style;e.bottom=i,e.width=a??``}e&&n!==`fullscreen`&&(n===`modal`?(d.top=`50%`,d.left=`50%`,d.transform=`translate(-50%, -50%)`,d.bottom=`auto`,d.right=`auto`,d.width=c,d.maxWidth=u,d.maxHeight=l,d.height=l):(d.left=`50%`,d.transform=`translateX(-50%)`,d.bottom=`calc(${i} + var(--persona-pill-area-height, 80px))`,d.top=s,d.width=o,d.maxWidth=u))},vs=()=>{if(z&&es(),!R())return;if(L()){let e=(r.launcher?.composerBar??{}).expandedSize??`anchored`,t=z?`expanded`:`collapsed`;it.dataset.state=t,it.dataset.expandedSize=e,at&&(at.dataset.state=t,at.dataset.expandedSize=e),it.style.removeProperty(`display`),it.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),U.classList.remove(`persona-scale-95`,`persona-opacity-0`,`persona-scale-100`,`persona-opacity-100`),_s(z),W.style.display=z?`flex`:`none`,jr(),z?(rs(),os()):(is(),ss()),gs();return}let t=Cf(r),n=e.ownerDocument.defaultView??window,i=r.launcher?.mobileBreakpoint??640,a=r.launcher?.mobileFullscreen??!0,o=n.innerWidth<=i,s=a&&o&&me,c=Tf(r).reveal;z?(it.style.removeProperty(`display`),it.style.display=t?`flex`:``,it.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),U.classList.remove(`persona-scale-95`,`persona-opacity-0`),U.classList.add(`persona-scale-100`,`persona-opacity-100`),ad?(ad.setPanelOpen(!0),ad.element.style.display=`none`):od&&(od.style.display=`none`)):(t?t&&(c===`overlay`||c===`push`)&&!s?(it.style.removeProperty(`display`),it.style.display=`flex`,it.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),U.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(it.style.setProperty(`display`,`none`,`important`),it.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),U.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(it.style.display=``,it.classList.add(`persona-pointer-events-none`,`persona-opacity-0`),U.classList.remove(`persona-scale-100`,`persona-opacity-100`),U.classList.add(`persona-scale-95`,`persona-opacity-0`)),ad?(ad.setPanelOpen(!1),ad.element.style.display=t?`none`:``):od&&(od.style.display=t?`none`:``))},ys=(t,n=`user`)=>{if(!R()||z===t)return;let i=z;z=t,vs();let a=(()=>{let t=r.launcher?.sidebarMode??!1,n=e.ownerDocument.defaultView??window,i=r.launcher?.mobileFullscreen??!0,a=r.launcher?.mobileBreakpoint??640,o=n.innerWidth<=a,s=Cf(r)&&i&&o,c=L()&&(r.launcher?.composerBar?.expandedSize??`fullscreen`)===`fullscreen`;return t||i&&o&&me||s||c})();if(z&&a){if(!Si){let t=e.getRootNode(),n=t instanceof ShadowRoot?t.host:e.closest(`.persona-host`);n&&(Si=vf(n,r.launcher?.zIndex??1e5))}Ci||=xf(e.ownerDocument)}else z||(Si?.(),Si=null,Ci?.(),Ci=null);z&&(ud(),No()||(Rt()===`follow`?Eo(!0):ko()));let o={open:z,source:n,timestamp:Date.now()};z&&!i?A.emit(`widget:opened`,o):!z&&i&&A.emit(`widget:closed`,o),A.emit(`widget:state`,{open:z,launcherEnabled:me,voiceActive:Ga.active,streaming:$.isStreaming()})},bs={inputDisabled:!1,sendDisabled:!1},xs=()=>bs.inputDisabled,Cs=()=>ms(r.voiceRecognition?.provider)&&!!$&&($.isBargeInActive()||[`listening`,`processing`,`speaking`].includes($.getVoiceStatus())),ws=()=>bs.inputDisabled||bs.sendDisabled,Ts=()=>(bs.inputDisabled?bs.inputReason:void 0)??(bs.sendDisabled?bs.sendReason:void 0);function Es(){if(!J)return;if(Z.getState().phase===`streaming`){J.disabled=!1;return}let e=_n?!_n.isReady():!1;J.disabled=ws()||e}function Ds(){if(!Ot)return;let e=Z.getState(),t=r.sendButton?.visibility===`when-text`&&e.phase!==`streaming`&&e.text.trim().length===0&&e.attachments.length===0;Ot.toggleAttribute(`data-persona-send-hidden`,t)}function Os(){let e=Ts();if(L()){let t=ut??wt;e?t.setAttribute(`title`,e):t.removeAttribute(`title`),wt.toggleAttribute(Ng,!!e)}else if(e)dt.setAttribute(`role`,`status`),dt.setAttribute(`aria-live`,`polite`),dt.setAttribute(Ng,``),dt.removeAttribute(Pg),dt.textContent=e,Rr(dt,r.statusIndicator??{},`idle`);else if(dt.hasAttribute(Ng)&&(dt.removeAttribute(`role`),dt.removeAttribute(`aria-live`),dt.removeAttribute(Ng),m)){let e=$.getStatus();nt(dt,tt(e),r.statusIndicator??{},e)}}function ks(){let e=$i(r.composer?.inputDisabled),t=$i(r.composer?.sendDisabled);bs={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},Z.setInputDisabled(e.disabled),Z.setSendDisabled(t.disabled);let n=Z.getState().phase===`streaming`,i=e.disabled,a=n||i;q&&(q instanceof HTMLTextAreaElement?q.disabled=i:q.setAttribute(`contenteditable`,i?`false`:`true`),q.setAttribute(`aria-disabled`,i?`true`:`false`)),jt&&(jt.disabled=i),Nt&&(Nt.disabled=i);for(let e of vn?.affordanceButtons??[])e.querySelectorAll(`button`).forEach(e=>{e.disabled=i});X&&(X.disabled=i||n&&!Cs()),Ni.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute(`data-disabled`,a),e instanceof HTMLButtonElement||e.setAttribute(`aria-disabled`,a?`true`:`false`)}),e.buttons.forEach(e=>{e.disabled=a})}),Js.forEach(e=>{e.toggleAttribute(`data-disabled`,a),e instanceof HTMLButtonElement?e.disabled=a:e.setAttribute(`aria-disabled`,a?`true`:`false`),e.querySelectorAll(`button`).forEach(e=>{e.disabled=a})}),wt.dataset.personaComposerStreaming=n?`true`:`false`,wt.dataset.personaComposerInputDisabled=i?`true`:`false`,wt.dataset.personaComposerSendDisabled=ws()?`true`:`false`,wt.querySelectorAll(`[data-persona-composer-disable-when-streaming]`).forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=n)}),Es(),Os()}let As=e=>{Z.setStreaming(e),kt(e?`stop`:`send`),ks()},js=()=>{Ga.active||q&&q.focus()};A.on(`widget:opened`,()=>{r.autoFocusInput&&setTimeout(()=>js(),200)});let Ms=null,Ns=!1,Ps=!ft.hidden,Fs=null,Is=!re,Ls=null;Q.push(()=>{Ls?.cancel(),Ls=null});let Rs=t=>{let n=Qp(t);if(n===un)return;un=n,e.setAttribute(`data-persona-conversation-state`,n);let r=fn();hn(),Is&&(Ls?.cancel(),Ls=qp(wt,n===`active`?r:fn(),n===`active`?`drop`:`rise`,ln().layout===`centered`?320:260)),Vo()},zs=null,Bs,Hs=null,Ws=null,Gs=!1,Ks=e=>{let t=ln(),n=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??`bottom`}|${t.align??``}|${t.iconPlacement}|${t.kicker??``}|${t.title}|${t.subtitle}`;(n!==zs||t.icon!==Bs)&&(zs=n,Bs=t.icon,Lp({host:ft,iconHolder:mt,kicker:_t,title:vt,subtitle:yt,starterSuggestions:st},t));let i=t.message===void 0?null:`${r.layout?.messages?.layout??`bubble`}|${t.message}`;i!==Hs&&(Hs=i,Wp(gt,t.message,r));let a=e??($?$.getMessages():r.initialMessages);Rs(a);let o=Ns,s=!o&&$p(t,a),c=s!==Ps;if(Ps=s,Ws){Fs?.cancel(),Fs=null,o!==Gs&&(Gs=o,o?Hp(G,ft,null):Vp(G,ft,Ws)),Ip(G,ft,!o);return}if(c&&!s&&!o&&t.dismiss===`on-first-message`&&Is){Fs=Kp(ft,e=>{Fs===e&&(Fs=null),!Ps&&!Ws&&(Ip(G,ft,!1),Vo()),e?.cancel()});return}if(Fs){if(!s&&!o)return;Fs.cancel(),Fs=null}let l=!ft.hidden;Ip(G,ft,s),!s&&l&&Vo()},qs=[],Js=[],Ys=!1,Xs=null,Zs,Qs=()=>{Js.length=0;let e=qs.splice(0,qs.length);for(let t of e)try{t()}catch(e){console.warn(`[persona] renderWelcome cleanup threw`,e)}};Q.push(Qs);let $s=(e,t)=>{let n=Df(e,t);if(!n)return r.debug===!0&&console.warn(`[persona] renderStarter received a suggestion with no label`),B(`span`);let i=r.suggestions?.starters,a=jf({item:{...n,behavior:n.behavior??i?.behavior??`send`},index:t,surface:`starter`,source:`config`,variant:i?.variant??`card`,streaming:m?$.isStreaming():!1,config:r,plugins:u,chipsConfig:r.suggestionChipsConfig,session:$,getTextarea:()=>q,eventTarget:ft,submitPrompt:Ml});return Js.push(a),a},ec=()=>{if(Ys)return;Ys=!0;let e=ln();Xs=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`,Zs=e.icon;try{Qs(),Hp(G,ft,Ws),Ws=null,Gs=!1;let t=$?$.getMessages():r.initialMessages,n=$p(e,t),i=0,a=null;for(let t of u)if(t.renderWelcome&&(a=t.renderWelcome({config:e,variant:e.variant,visible:n,defaultRenderer:()=>ft,sendMessage:e=>{if(!$||$.isStreaming())return;let t=e.trim();t&&$.sendMessage(t)},requestRender:()=>ec(),renderStarter:e=>$s(e,i++),storage:h(t.id),onCleanup:e=>{qs.push(e)}}),a))break;a&&a!==ft&&(Ws=a,Vp(G,ft,a))}finally{Ys=!1}Ks()},tc=()=>{let e=ln();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`!==Xs||e.icon!==Zs)&&ec()},nc=()=>{Ks(),Jn||(q.placeholder=ou(Z.getState().activeModeIds,r.composer?.modes)??r.copy?.inputPlaceholder??`How can I help...`,!(r.sendButton?.useIcon??!1)&&!$?.isStreaming()&&(J.textContent=r.copy?.sendButtonLabel??`Send`)),q.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,q.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`},rc=!!r.setStoredConversationId,ic=e=>ue(t=>{let n={...t};return delete n[e],n}),ac=e=>{let t=ne[e];return typeof t==`string`?t:null},sc=()=>{let e=ne.durableResume;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.executionId==`string`&&t.executionId.length>0&&typeof t.after==`string`&&t.after.length>0?{executionId:t.executionId,after:t.after}:null};r.clientToken&&(r={...r,getStoredSessionId:()=>ac(`sessionId`),setStoredSessionId:e=>{ue(t=>({...t,sessionId:e}))},clearStoredSessionId:r.clearStoredSessionId??(()=>ic(`sessionId`)),getStoredConversationId:r.getStoredConversationId??(()=>ac(`conversationId`)),setStoredConversationId:r.setStoredConversationId??(e=>{ue(t=>({...t,conversationId:e}))}),clearStoredConversationId:r.clearStoredConversationId??(()=>ic(`conversationId`))});let cc=()=>r.clientToken??null,lc=e=>hg(e,je(),r.persistState===!1),uc=cc(),dc=uc?lc(uc):null,fc=()=>{let e=ne.pendingDisplayProjections;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.conversationId!=`string`||!Array.isArray(t.messageIds)?null:{conversationId:t.conversationId,messageIds:t.messageIds.filter(e=>typeof e==`string`)}},pc={...dc?{visitorStore:dc}:{},historyBootstrapReady:r.features?.history?.enabled===!0&&!Zo()?Promise.all([M,P]).then(()=>{}):M,getStoredMessageCursor:()=>ac(`historyMessageCursor`),setStoredMessageCursor:e=>{e===null?ic(`historyMessageCursor`):ue(t=>({...t,historyMessageCursor:e}))},getPendingDisplayProjections:fc,setPendingDisplayProjections:e=>{e?ue(t=>({...t,pendingDisplayProjections:e})):ic(`pendingDisplayProjections`)},getStoredResumableHandle:sc,setStoredResumableHandle:e=>{e?ue(t=>({...t,durableResume:e})):ic(`durableResume`)},shouldResumeDurableConversation:()=>te&&sc()!==null,...rc?{}:{getStoredConversationRevision:()=>ac(`conversationRevision`),setStoredConversationRevision:e=>{e===null?ic(`conversationRevision`):ue(t=>({...t,conversationRevision:e}))}}};if(te){let t=r.onExecutionState,n=e.ownerDocument.defaultView,i=!1,a=()=>i=!0,o=()=>i=!1;n?.addEventListener(`pagehide`,a),n?.addEventListener(`pageshow`,o),Q.push(()=>{n?.removeEventListener(`pagehide`,a),n?.removeEventListener(`pageshow`,o)}),r={...r,reconnectStream:r.reconnectStream??(e=>$.getClient().reconnectClientTokenStream(e)),onExecutionState:e=>{(e||!i)&&pc.setStoredResumableHandle?.(e?{executionId:e.executionId,after:e.lastEventId}:null),t?.(e)}}}let hc=()=>{let e=cc();if(e&&dc?.matches(e,je(),r.persistState===!1)||!e&&!dc)return;dc?.destroy(),dc=e?lc(e):null;let t={...pc};dc?t.visitorStore=dc:delete t.visitorStore,pc=t,$.setHistoryInternals(pc)},gc=null,_c=()=>{gc??=setInterval(()=>{let e=K.querySelectorAll(`[data-tool-elapsed]`);if(e.length===0){clearInterval(gc),gc=null;return}let t=Date.now();e.forEach(e=>{let n=Number(e.getAttribute(`data-tool-elapsed`));n&&(e.textContent=e.closest(`.persona-activity-row`)?ls(t-n):Re(t-n))})},100)},vc=(e,t)=>{if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>vc(e,t[n]));let n=e,r=t,i=Object.keys(n),a=Object.keys(r);return i.length===a.length&&i.every(e=>Object.prototype.hasOwnProperty.call(r,e)&&vc(n[e],r[e]))},yc=e=>{let{content:t,rawContent:n,llmContent:r,...i}=e;return i},bc=e=>e.role===`assistant`&&e.streaming===!0&&!e.variant&&!e.toolCall&&!e.tools&&!e.approval&&!e.reasoning&&!e.contentParts&&!e.stopReason&&!Dg(e),xc=(e,t,n)=>{if(e.length!==t.length)return!1;let r=e[n.index],i=t[n.index];return!r||!i||r.id!==n.id||i.id!==n.id?!1:(!Object.is(r.content,i.content)||!Object.is(r.rawContent,i.rawContent)||!Object.is(r.llmContent,i.llmContent))&&bc(r)&&bc(i)&&vc(yc(r),yc(i))},Sc=null,Ec=null,Dc=null,Oc=null,kc=null,Ac=e=>{if(!te)return ro(e);kc=e,queueMicrotask(()=>{kc===e&&(kc=null,ro(e))})},jc=e=>{Sc=e;let t,n;Ec=null;for(let r=e.length-1;r>=0;--r){let i=e[r];if(!t&&i.role===`user`&&(t=i),!n&&i.role===`assistant`&&(n=i),!Ec&&bc(i)&&(Ec={index:r,id:i.id}),t&&n&&Ec)break}ts(K,e,we),rh()?.updateInlineArtifactBlocks(K,Pr.artifacts,{suppressTransition:oa}),_c(),Ks(e),ea(e),Eo(!oa),qo(e),e.length===0&&(Lo(),ja=!0,Ma=!1,Pa=null,Ia=!1),!Oa||ka?(Oa=!0,Aa=t?.id??null,Ra=n?.id??null):t&&t.id!==Aa?(Aa=t.id,Uo(t.id)):n&&n.id!==Ra&&Wo(),n&&(Ra=n.id),Ko(e);let r=Ga.lastUserMessageId;t&&t.id!==r&&(Ga.lastUserMessageId=t.id,A.emit(`user:message`,t)),Ga.lastUserMessageWasVoice=!!t?.viaVoice,Ac(e),gs()},Mc=()=>{Oc!==null&&(cancelAnimationFrame(Oc),Oc=null);let e=Dc;Dc=null,e&&jc(e)},Fc=()=>{Oc!==null&&cancelAnimationFrame(Oc),Oc=null,Dc=null},Ic=e=>{let t=Dc??Sc;oa&&t&&Ec&&xc(t,e,Ec)?(Dc=e,Oc===null&&(Oc=requestAnimationFrame(()=>{Oc=null;let e=Dc;Dc=null,e&&jc(e)}))):e.length===0?(Fc(),jc(e)):(Mc(),jc(e))};$=new rl(r,{onMessagesChanged(e){Ic(e)},onStatusChanged(e){let t=r.statusIndicator??{};nt(dt,(e=>e===`idle`?t.idleText??cn.idle:e===`connecting`?t.connectingText??cn.connecting:e===`connected`?t.connectedText??cn.connected:e===`error`?t.errorText??cn.error:e===`paused`?t.pausedText??cn.paused:e===`resuming`?t.resumingText??cn.resuming:cn[e])(e),t,e),H()},onStreamingChanged(e){e||($?.getMessages().length===0?Fc():Mc()),oa=e,As(e),H(),$&&ts(K,$.getMessages(),we),e||(Eo(!0),Io(),Ji=!0,$&&Xi($.getMessages(),tn(r))),So(),on(e?`Responding…`:`Response complete.`),gs()},onVoiceStatusChanged(e){if(A.emit(`voice:status`,{status:e,timestamp:Date.now()}),e!==`disconnected`&&!ms(r.voiceRecognition?.provider))return;let t=$.getVoiceNotice();switch(t&&bl(t,1e4),e){case`listening`:if(!Ua){let e=$.getVoiceDisclosure();e&&(Ua=!0,L()?(Wa=q.placeholder,q.placeholder=e,on(e)):bl(e,1e4))}Wu(),Bu();break;case`processing`:Wu(),Vu();break;case`speaking`:Wu(),Hu();break;default:e===`idle`&&$.isBargeInActive()?(Wu(),Bu(),X?.setAttribute(`aria-label`,`End voice session`)):(Ga.active=!1,Ua=!1,Wa!==null&&(q.placeholder=Wa,Wa=null),Wu(),Ya(`system`),Ja||Xa())}},onArtifactsState(e){Pr=e,e.artifacts.length===0&&(Br=!1),rh()?.updateInlineArtifactBlocks(K,e.artifacts,{suppressTransition:oa}),hi(),ro()},onHistoryStateChanged(e){V(e)},onHistoryNotice(e){Qe(e)},onReconnect(e){let{executionId:t,lastEventId:n}=e.handle;e.phase===`paused`?A.emit(`stream:paused`,{executionId:t,after:n}):e.phase===`resuming`?A.emit(`stream:resuming`,{executionId:t,after:n,attempt:e.attempt??1}):A.emit(`stream:resumed`,{executionId:t,after:n})}},pc),Wr.current=$,Q.push(()=>$.cancel()),Q.push(()=>{$.destroy(),dc?.destroy(),dc=null});let Lc=null;if($.onReadAloudChange((e,t)=>{Sr=e,Cr=t,Er();let n=e??Lc;e&&(Lc=e);let r=n?$.getMessages().find(e=>e.id===n)??null:null;A.emit(`message:read-aloud`,{messageId:n,message:r,state:t,timestamp:Date.now()}),t===`idle`&&(Lc=null)}),m=!0,Oa=!0,r.voiceRecognition?.enabled===!0&&ms(r.voiceRecognition.provider))try{$.setupVoice()}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Runtype voice setup failed:`,e)}let Rc=null,zc=null,Bc=!1,Vc=$.getHistoryState(),Hc=()=>r.features?.history?.enabled===!0,Uc=e=>{e&&(nn.textContent=``,nn.textContent=e)},Wc=()=>{p.forEach(e=>e()),p=[];let t=Rc,n=t?.railCollapseShortcut();t&&n&&p.push(d.register({id:`history-rail-collapse`,combo:n.combo,scope:r.features?.history?.rail?.collapseShortcutScope===`page`?`page`:`widget`,when:()=>Je&&Ye===`rail`&&t.railCollapsible()||t.railTriggerApplies(),run:()=>t.railOverlayMode()?t.toggleRailPinned():t.toggleRailCollapsed()}));for(let t of r.layout?.header?.trailingActions??[])t.shortcut&&p.push(d.register({id:`header-action-${t.id}`,combo:t.shortcut,run:()=>{let n=e.querySelector(`[data-persona-header-action="${t.id}"]`);n?n.click():r.layout?.header?.onAction?.(t.id)}}));for(let e of u)for(let t of e.shortcuts??[])p.push(d.register({...t,id:`${e.id}:${t.id}`}))};Wc();let Gc=null,Kc=!1,qc=()=>{if(!xt)return;let e=r.layout?.header?.titleSource===`conversation`,t=e&&Gc?.trim()||null;xt.textContent=t??r.launcher?.title??`Chat Assistant`;let n=xt.closest(`.persona-combo-btn`);if(!n)return;let i=!e||$.getActiveConversationId()!==null;n.setAttribute(`data-persona-menu-locked`,i?`false`:`true`),n.setAttribute(`aria-haspopup`,i?`true`:`false`),i||n.setAttribute(`aria-expanded`,`false`),n.style.cursor=i?`pointer`:`default`;let a=n.querySelector(`svg`);a&&(a.style.display=i?``:`none`)},Jc=e=>{e!==Gc&&(Gc=e,qc())},Yc=e=>{Kc=e?.starred===!0,Jc(e&&e.title.trim()||null),qc()};qc(),W.addEventListener(`persona:title-menu-builtin`,e=>{let t=e.detail?.actionId,n=$.getActiveConversationId();n&&(t===`delete`?$c(e=>e.requestDeleteConversation(n)):t===`star`&&$.canUpdateConversations()&&$c(e=>e.updateHistoryConversation(n,{starred:!Kc})).catch(()=>{}))}),V=e=>{Vc=e,Rc?.historySurface?.view.setNewConversationRequired(e.recovery===`new_conversation_required`),As(e.sendBlocked||oa),Rc?.syncEarlierMessagesPill()},Qe=e=>{(e.code===`history_continuity_reset`||e.code===`conversation_deleted_recovered`)&&(ca.clear(),Lo(),To()),Uc(e.message),Rc?.historySurface?.view.refresh()};let Xc={get actionManager(){return pe},get activeConversationTitle(){return Gc},announceHistory:Uc,get applyRailChrome(){return Ze},set applyRailChrome(e){Ze=e},get artifactSplitRoot(){return $r},get body(){return G},get config(){return r},get container(){return W},get conversationOpenPendingEl(){return Ms},set conversationOpenPendingEl(e){Ms=e},get conversationOpenTakeover(){return Ns},set conversationOpenTakeover(e){Ns=e},currentKeyPrefix:je,destroyCallbacks:Q,eventBus:A,get footer(){return wt},get header(){return Ct},get historyChromeSync(){return H},set historyChromeSync(e){H=e},historyFeatureEnabled:Hc,get historyInternals(){return pc},set historyInternals(e){pc=e},get historyPresentation(){return Ye},set historyPresentation(e){Ye=e},get historySessionState(){return Vc},get historyVisible(){return Je},set historyVisible(e){Je=e},get isStreaming(){return oa},jumpToBottomInstant:ko,get lastAppliedMessages(){return Sc},set lastAppliedMessages(e){Sc=e},get launcherEnabled(){return me},get launcherSurfaceInstance(){return ad},maybeFocusInput:js,messageCache:ca,get messagesWrapper(){return K},mount:e,get open(){return z},panel:U,panelElements:ot,get persistentMetadata(){return ne},set persistentMetadata(e){ne=e},plugins:u,get reapplyHistoryHostChrome(){return Xe},set reapplyHistoryHostChrome(e){Xe=e},repinAnchoredMessage:Vo,resetAnchorState:Lo,restoreScrollPosition:No,resumeAutoScroll:To,runStorageMutation:no,get session(){return $},setActiveConversationSummary:Yc,storageAdapter:j,get suppressScrollSend(){return ka},set suppressScrollSend(e){ka=e},syncScrollToBottomButton:So,updateWelcome:Ks,getHistoryProviderFactory:yg,historyErrors:{HistoryClientError:oc,HistoryProviderError:mc},isDockedMountMode:Cf,renderLucideIcon:F,loadHistoryView:vg,createHeaderIconButton:Lf,attachTooltip:yr},Zc=e=>(!Rc&&!Bc&&(Rc=e.createHistoryShell(Xc),Rc.railCollapseShortcut()&&Wc()),Rc),Qc=()=>{if(Rc)return Promise.resolve(Rc);let e=Zo();return e?Promise.resolve(Zc(e)):(zc??=Yo().then(Zc,e=>{throw zc=null,e}),zc)},$c=e=>{let t=Zo(),n=Rc??(t?Zc(t):null);return n?e(n):Qc().then(t=>{if(!t)throw Error(`[AgentWidget] The widget was destroyed`);return e(t)})},el=()=>{Rc?.syncHistoryPresentation()};Q.push(()=>{Bc=!0}),Hc()&&Qc().catch(()=>{}).finally(N),r.clientToken&&(r.features?.history?.enabled===!0||r.sessionInit===`mount`)&&$.initClientSession().then(()=>{let e=Rc;if(e?.historyAvailable())return $.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{Rc?.syncEarlierMessagesPill()}).catch(e=>{r.debug&&console.warn(`[AgentWidget] Pre-init client session failed:`,e)});let tl=()=>$.warmClientSession(),nl=e=>{let t=r.sessionInit??`input`,n=Zn?.input??q,i=e.target;n&&(e.type===`input`?(t===`input`||t===`focus`)&&i===n&&e.inputType&&n.value.trim():t===`focus`&&(e.type===`keyup`?i===n&&e.key===`Tab`:(Zn?.form??ut)?.contains(i)))&&tl()},il=[`input`,`pointerdown`,`keyup`];il.forEach(t=>e.addEventListener(t,nl));let al,ol,sl=()=>{let e=ol;ol=void 0;try{typeof e==`function`&&e()}catch{}},cl=()=>{let t=r.clientToken&&typeof r.sessionInit==`function`?r.sessionInit:void 0;if(t!==al){sl(),al=t;try{ol=t?.({warm:tl,mount:e})}catch{}}};cl(),Q.push(()=>{il.forEach(t=>e.removeEventListener(t,nl)),sl()}),(De||r.onSSEEvent)&&$.setSSEEventCallback((e,t)=>{r.onSSEEvent?.(e,t),Ke(e,t)});let ul=()=>{let e=r.resume??(te?pc.getStoredResumableHandle?.():null);e&&typeof r.reconnectStream==`function`&&$.resumeFromHandle(e)};re?re.then(e=>{if(e){if(e.metadata&&(ne=Bg(e.metadata),pe.syncFromMetadata()),e.messages?.length){ka=!0;try{$.hydrateMessages(e.messages)}finally{ka=!1}es()}e.artifacts?.length&&$.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),lo(e.draft)}}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to hydrate stored state:`,e)}).finally(()=>{Is=!0,ie(),ul()}):(lo(ae),ul());let dl=()=>{L()&&(z||(r.launcher?.composerBar?.expandOnSubmit??!0)&&ys(!0,`auto`))},pl=(e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[n,r]=await Promise.allSettled([e.finalize(),t.finalize()]),i=[];return n.status===`fulfilled`?i.push(n.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,n.reason),r.status===`fulfilled`?i.push(r.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,r.reason),Gg(i)}}:e:t,ml=()=>{let e=q.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>e.kind===`mention`)?e.contentSegments:void 0},gl=!1,_l=null,vl=()=>{q.value=``,q.style.height=`auto`,yn(),Rl()},yl=null;function bl(e,t=4e3){on(e),!L()&&dt&&(dt.hasAttribute(Ng)||(dt.setAttribute(Pg,``),dt.setAttribute(`role`,`status`),dt.setAttribute(`aria-live`,`polite`),dt.textContent=e,Rr(dt,r.statusIndicator??{},`idle`),yl&&clearTimeout(yl),yl=setTimeout(()=>{if(yl=null,dt?.hasAttribute(Pg)&&(dt.removeAttribute(Pg),dt.removeAttribute(`role`),dt.removeAttribute(`aria-live`),m)){let e=$.getStatus();nt(dt,tt(e),r.statusIndicator??{},e)}},t)))}function xl(){let e=Z.getState().pendingSubmission;e&&(Rn(void 0),q&&(q.value=e.text,q.dispatchEvent(new Event(`input`,{bubbles:!0})),yn()),e.options.selectedModelId&&(Z.setSelectedModelId(e.options.selectedModelId),kn?.repaint()),e.options.activeModeIds?.length&&Dn(e.options.activeModeIds),e.options.quote&&Pn(e.options.quote),q?.focus())}let Sl=e=>{typeof console<`u`&&console.error(`[AgentWidget] composer.onBeforeSend failed; the draft was preserved:`,e)},Cl=(e={})=>{let t=(e.overrideText??q?.value??``).trim();return e.resolveInlineCommand&&t?(vn?.takeInlineCommand(t)??Promise.resolve(null)).then(n=>Tl(e,t,n)):Tl(e,t,null)},Tl=(e,t,n)=>{if(n?.kind===`action`){vl(),vn?.clear(),bn();return}let i=n?.kind===`server`?n.mentions:null,a=n?.kind===`prompt`?n.sendText:t,o=e.pending?.contentParts;if(!yu({text:a,hasAttachments:(_n?.hasAttachments()??!1)||(o?.length??0)>0,attachmentsReady:_n?.isReady()??!0,hasMentions:vn?.hasMentions()??!1,hasServerMentions:!!i,inputDisabled:xs(),sendDisabled:ws()}))return;let s=$.isStreaming()?In():`block`;if(s===`defer-one`&&!e.pending){if(Z.getState().pendingSubmission){bl(`One message is already queued. Edit or remove it first.`);return}El({intent:e,sendText:a,serverMentions:i});return}let c={text:a,mentionRefs:[...vn?.getMentionRefs()??[],...i?.refs??[]],contentSegments:n?.kind===`prompt`?void 0:ml(),options:{...Z.getState().selectedModelId&&{selectedModelId:Z.getState().selectedModelId},...Z.getState().activeModeIds.length>0&&{activeModeIds:[...Z.getState().activeModeIds]},...Z.getState().quote&&{quote:{...Z.getState().quote}}},viaVoice:e.viaVoice};e.pending&&(c.options={...e.pending.options},c.contentSegments=e.pending.contentSegments,c.mentionRefs=[...e.pending.mentionRefs],c.viaVoice=e.pending.viaVoice);let l=()=>{if(o?.length)return[...o];if(!_n?.hasAttachments())return;let e=[..._n.getContentParts()];return c.text&&e.push(ki(c.text)),e};c.contentParts=l();let u=()=>{ha(),dl();let t=vn?.collectForSubmit()??null,n=pl(t,i),a=l();e.consumeDraft!==!1&&vl();let o={selectedModelId:c.options.selectedModelId,activeModeIds:c.options.activeModeIds},u=s===`interrupt`;u&&$.cancel(),$.sendMessage(c.text,{contentParts:a,mentions:n??void 0,contentSegments:c.contentSegments,viaVoice:c.viaVoice,composerOptions:o,...c.options.quote&&{quote:c.options.quote},...u&&{interrupt:!0}}),_n?.hasAttachments()&&_n.clearAttachments(),t&&vn?.clear(),bn();let d=Z.getState().activeModeIds,f=au(d,r.composer?.modes);f.length!==d.length&&Dn(f),Z.getState().quote&&Pn(void 0),uo(),fr.release(),mr()},d=r.composer?.onBeforeSend;if(!d){u();return}let f=new AbortController;_l=f;let p=e=>{_l=null,e.status===`error`?Sl(e.error):e.status===`proceed`&&u()},m=Su(d,c,f.signal);if(!(m instanceof Promise))p(m);else return Z.setPreparing(!0),m.then(p).finally(()=>Z.setPreparing(!1))};function El(e){let t=Z.getState(),n=_n?.hasAttachments()??!1,r=n?[..._n.getContentParts()]:[];n&&e.sendText&&r.push(ki(e.sendText)),Rn(vu({text:e.sendText,contentParts:r.length?r:void 0,mentionRefs:[...vn?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:ml(),options:{...t.selectedModelId&&{selectedModelId:t.selectedModelId},...t.activeModeIds.length>0&&{activeModeIds:[...t.activeModeIds]},...t.quote&&{quote:{...t.quote}}},viaVoice:e.intent.viaVoice})),e.intent.consumeDraft!==!1&&vl(),n&&_n.clearAttachments(),vn?.clear(),bn(),t.quote&&Pn(void 0),uo(),fr.release(),mr(),on(`Message queued. It sends when the response finishes.`)}function Dl(){let e=Z.getState().pendingSubmission;e&&(Rn(void 0),Nl(e.text,{consumeDraft:!1,pending:e}))}function Ol(e){if(r.messageActions?.showEdit!==!0)return;let t=$.getMessages().find(t=>t.id===e);t&&Tc(t)&&pa!==e&&(ha(),pa=e,ma=uu({messageId:e,initialText:t.content,onSave:t=>kl(e,t),onCancel:()=>ha()}),ca.delete(e),ts(K,$.getMessages(),we),ma.focus())}function kl(e,t){let n=ma;pa=null,ma=null,n?.destroy(),ca.delete(e),$.resubmitFrom(e,{reason:`edit`,replacement:{text:t,mentionRefs:[],options:{}}})?Vo():ts(K,$.getMessages(),we)}function Al(e){if($.isStreaming())return;let t=Cc($.getMessages(),e);t&&(ha(),$.resubmitFrom(t,{reason:`retry`})&&Vo())}Dr={regenerate:Al,edit:Ol,quote:e=>{let t=$.getMessages().find(t=>t.id===e)?.content?.trim();t&&(Pn({text:t,messageId:e}),q?.focus())}};let jl=async e=>{if(!gl){gl=!0;try{await Cl({resolveInlineCommand:!0,...e})}finally{gl=!1}}};function Ml(e){ws()||(vl(),Nl(e,{consumeDraft:!1}))}let Nl=(e,t)=>{if(gl)return;gl=!0;let n=()=>{gl=!1};try{let r=Cl({...t,overrideText:e});r instanceof Promise?r.finally(n):n()}catch(e){throw n(),e}},Pl=e=>{e.preventDefault(),$.isStreaming()?($.cancel(),Le?.reset(),Ve?.update()):gl||jl()},Fl=()=>r.features?.composerHistory!==!1,Il={...Ed},Ll=!1,Rl=()=>{Il={...Ed}},zl=()=>$.getMessages().filter(e=>e.role===`user`).map(e=>e.content??``).filter(e=>e.length>0),Bl=e=>{if(!q)return;Ll=!0,q.value=e,q.dispatchEvent(new Event(`input`,{bubbles:!0})),Ll=!1;let t=q.value.length;q.setSelectionRange(t,t)},Vl=e=>{Ll||(e.isComposing||vn?.handleInput(e.inputType??void 0),Rl())},Ul=()=>({submitKey:r.composer?.submitKey,insertNewlineOnTouchEnter:r.composer?.insertNewlineOnTouchEnter,coarsePointer:qi(q)}),Wl=e=>{if(q&&!xs()&&(e.isComposing||!vn?.handleKeydown(e))){if(Fl()&&(e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.shiftKey&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.isComposing){let t=q.selectionStart===0&&q.selectionEnd===0,n=Dd({direction:e.key===`ArrowUp`?`up`:`down`,history:zl(),currentValue:q.value,atStart:t,state:Il});if(Il=n.state,n.handled){e.preventDefault(),n.value!==void 0&&Bl(n.value);return}}if(Yi(e,Ul())){if($.isStreaming()){if(e.preventDefault(),In()===`block`||gl||ws())return;Rl(),jl()}else gl||ws()?e.preventDefault():(Rl(),e.preventDefault(),J.click())}}},ql=e=>{e.key!==`Escape`||e.isComposing||e.composedPath().includes(W)&&(_l?(_l.abort(),_l=null,e.preventDefault(),e.stopImmediatePropagation()):$.isStreaming()&&($.cancel(),Le?.reset(),Ve?.update(),Rl(),e.preventDefault(),e.stopImmediatePropagation()))},Ql=async e=>{if(r.attachments?.enabled!==!0||!_n||xs())return;let t=Ig(e.clipboardData);t.length!==0&&(e.preventDefault(),await _n.handleFiles(t))},eu=null,nu=!1,bu=null,xu=null,Cu=()=>r.voiceRecognition?.completionBehavior===`review`;function wu(e){X?.setAttribute(`data-state`,e),e===`recording`?Nu():Pu()}let Tu=`--persona-voice-level`,Eu=.5,Du=null,Ou=-1,ku=0,Au=()=>{let e=[],t=At??X?.parentElement??null;return t&&e.push(t),wt&&e.push(wt),e},ju=e=>{let t=Math.round(Math.max(0,Math.min(1,e))*100)/100;if(t!==Ou){Ou=t;for(let e of Au())e.style.setProperty(Tu,String(t))}},Mu=()=>{Ou=-1,ku=0;for(let e of Au())e.style.removeProperty(Tu)};function Nu(){if(Du!==null)return;if(typeof requestAnimationFrame!=`function`){ju(m?$.getVoiceLevel()??Eu:Eu);return}let e=()=>{Du=requestAnimationFrame(e);let t=m?$.getVoiceLevel():null;t===null?ju(Eu):(ku+=(t-ku)*.3,ju(ku))};Du=requestAnimationFrame(e)}function Pu(){Du!==null&&(cancelAnimationFrame(Du),Du=null),Mu()}let Fu=()=>typeof window>`u`?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Iu=(e=`user`)=>{if(nu||$.isStreaming())return;let t=Fu();if(!t)return;eu=new t;let n=r.voiceRecognition??{},i=n.pauseDuration??2e3;eu.continuous=n.provider?.browser?.continuous??!0,eu.interimResults=!0,eu.lang=n.provider?.browser?.language??`en-US`;let a=q.value;eu.onresult=e=>{let t=``,n=``;for(let r=0;r<e.results.length;r++){let i=e.results[r],a=i[0].transcript;i.isFinal?t+=a+` `:n=a}let r=a+t+n;q.value=r,yn(),bu&&clearTimeout(bu),(t||n)&&(bu=window.setTimeout(()=>{if(q.value.trim()&&eu&&nu){if(Lu(),Cu())return;jl({viaVoice:!0})}},i))},eu.onerror=e=>{e.error!==`no-speech`&&Lu()},eu.onend=()=>{if(nu){let e=q.value.trim();!Cu()&&e&&e!==a.trim()&&jl({viaVoice:!0}),Lu()}};try{if(eu.start(),nu=!0,Ga.active=!0,e!==`system`&&(Ga.manuallyDeactivated=!1),Ya(e),Xa(),mr(),X){let e=r.voiceRecognition??{};xu={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:e.iconName??`mic`,iconSize:parseFloat(e.iconSize??``)||24};let t=e.recordingBackgroundColor,n=e.recordingIconColor,i=e.recordingBorderColor;if(X.classList.add(`persona-voice-recording`),wu(`recording`),X.style.backgroundColor=t??`var(--persona-voice-recording-bg, #ef4444)`,X.style.color=n??`var(--persona-voice-recording-indicator, #ffffff)`,n){let e=X.querySelector(`svg`);e&&e.setAttribute(`stroke`,n)}i&&(X.style.borderColor=i),X.setAttribute(`aria-label`,`Stop voice recognition`)}}catch{Lu(`system`)}},Lu=(e=`user`)=>{if(nu){if(nu=!1,bu&&=(clearTimeout(bu),null),eu){try{eu.stop()}catch{}eu=null}if(Ga.active=!1,Ya(e),Xa(),mr(),X){if(X.classList.remove(`persona-voice-recording`),wu(`idle`),xu){X.style.backgroundColor=xu.backgroundColor,X.style.color=xu.color,X.style.borderColor=xu.borderColor;let e=X.querySelector(`svg`);e&&e.setAttribute(`stroke`,xu.color||`currentColor`),xu=null}X.setAttribute(`aria-label`,`Start voice recognition`)}}},Ru=null,zu=e=>{let t=t=>{Ru??=t.createMicStateStyles({mic:()=>X,config:()=>r,session:()=>$,get original(){return xu},set original(e){xu=e},setMicState:wu,renderIcon:F,iconFallbackPx:24}),e(Ru)},n=Pc();n?t(n):Nc().then(t,()=>{})},Bu=()=>zu(e=>e.recording()),Vu=()=>zu(e=>e.processing()),Hu=()=>zu(e=>e.speaking()),Wu=()=>zu(e=>e.reset()),Gu=()=>{if(!xs()){if(ms(r.voiceRecognition?.provider)){let e=$.getVoiceStatus(),t=$.getVoiceInterruptionMode();if(t===`none`&&(e===`processing`||e===`speaking`))return;if(t===`cancel`&&(e===`processing`||e===`speaking`)){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{Ga.active=!1,Ga.manuallyDeactivated=!0,Xa(),Ya(`user`),Wu()});return}$.toggleVoice().then(()=>{Ga.active=qa(),Ga.manuallyDeactivated=!Ga.active,Xa(),Ya(`user`),Ga.active?Bu():Wu()})}else if(nu){let e=q.value.trim();Ga.manuallyDeactivated=!0,Xa(),Lu(`user`),e&&!Cu()&&jl()}else Ga.manuallyDeactivated=!1,Xa(),Iu(`user`)}};Vn=Gu;let Ku=()=>$.prewarmVoice(),qu=()=>{let e=r.voiceRecognition;return e?.enabled===!0?e.prewarm??(r.clientToken?`hover`:!1):!1},Ju=e=>{qu()===`hover`&&X?.contains(e.target)&&Ku()},Yu=[`pointerover`,`pointerdown`,`focusin`];Yu.forEach(t=>e.addEventListener(t,Ju));let Xu,Zu=null,Qu,$u=()=>{let e=Qu;Qu=void 0;try{typeof e==`function`&&e()}catch{}},ed=()=>{let t=qu(),n=typeof t==`function`&&X?t:void 0,r=n?X:null;if((n!==Xu||r!==Zu)&&($u(),Xu=n,Zu=r,n&&r))try{Qu=n({warm:Ku,micButton:r,mount:e})}catch{}};ed(),Q.push(()=>{Yu.forEach(t=>e.removeEventListener(t,Ju)),$u()}),X&&Q.push(()=>{ms(r.voiceRecognition?.provider)?($.isVoiceActive()&&$.toggleVoice(),Wu()):Lu(`system`)});let td=A.on(`assistant:complete`,()=>{Z.getState().pendingSubmission&&setTimeout(()=>{$.isStreaming()||Dl()},0)});Q.push(td);let nd=A.on(`assistant:complete`,()=>{Ka&&(Ga.active||Ga.manuallyDeactivated||(Ka!==`assistant`||Ga.lastUserMessageWasVoice)&&setTimeout(()=>{!Ga.active&&!Ga.manuallyDeactivated&&(ms(r.voiceRecognition?.provider)?$.toggleVoice().then(()=>{Ga.active=$.isVoiceActive(),Ya(`auto`),$.isVoiceActive()&&Bu()}):Iu(`auto`))},600))});Q.push(nd);let rd=A.on(`action:resubmit`,()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});Q.push(rd);let id=()=>{ys(!z,`user`)},ad=null,od=null;if(me&&!L()){let{instance:e,element:t}=ym({config:r,plugins:u,onToggle:id});ad=e,e||(od=t)}ad?e.appendChild(ad.element):od&&e.appendChild(od),vs(),ea(),nc(),ec(),As($.isStreaming()),No()||(Rt()===`follow`?Eo(!0):ko()),Za(),he&&(!me||L()?setTimeout(()=>js(),0):z&&setTimeout(()=>js(),200));let sd=null,cd=()=>{sd&&(sd.disconnect(),sd.observe(wt),sd.observe(W),sd.observe(ft))},ld=sn(),ud=()=>{if(L()){pn(),vs();return}let t=Cf(r),n=r.launcher?.sidebarMode??!1,i=e.ownerDocument.defaultView??window,a=r.launcher?.mobileFullscreen??!0,o=r.launcher?.mobileBreakpoint??640,s=i.innerWidth<=o,c=a&&s&&me;try{if(c){jr(),Mr=mi();return}let e=!1;ye&&(ye=!1,jr(),e=!0);let i=mi();if(!e&&i!==Mr&&(jr(),e=!0),Mr=i,e&&ri(),!me&&!t){U.style.height=``,U.style.width=``;return}if(!n&&!t){let e=tm(r);U.style.width=e.width,U.style.maxWidth=e.maxWidth}di(),xi()}finally{pn(),hn();let t=sn();if(t!==ld&&(ld=t,Ks(),ea()),vs(),z&&me){let t=(e.ownerDocument.defaultView??window).innerWidth<=(r.launcher?.mobileBreakpoint??640),n=r.launcher?.sidebarMode??!1,i=r.launcher?.mobileFullscreen??!0,a=Cf(r)&&i&&t,o=n||i&&t&&me||a;if(o&&!Ci){let t=e.getRootNode(),n=t instanceof ShadowRoot?t.host:e.closest(`.persona-host`);n&&!Si&&(Si=vf(n,r.launcher?.zIndex??1e5)),Ci=xf(e.ownerDocument)}else o||(Si?.(),Si=null,Ci?.(),Ci=null)}}};ud();let dd=e.ownerDocument.defaultView??window;if(dd.addEventListener(`resize`,ud),Q.push(()=>dd.removeEventListener(`resize`,ud)),typeof ResizeObserver<`u`){sd=new ResizeObserver(()=>{hn()}),cd(),Q.push(()=>{sd?.disconnect(),sd=null});let e=new ResizeObserver(()=>{el()});e.observe(W),Q.push(()=>e.disconnect())}dd.addEventListener(`resize`,el),Q.push(()=>dd.removeEventListener(`resize`,el)),xa=G.scrollTop;let fd=Fd(G),md=()=>{yi();let e=G.scrollTop,t=Fd(G),n=t<fd;if(fd=t,!zt()){xa=e,So();return}let{action:r,nextLastScrollTop:i}=Ld({following:ya.isFollowing(),currentScrollTop:e,lastScrollTop:xa,nearBottom:Id(G,24),userScrollThreshold:4,isAutoScrolling:Ca||wa||n,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});xa=i,r===`resume`?Mo()||To():r===`pause`&&Co()};if(G.addEventListener(`scroll`,md,{passive:!0}),Q.push(()=>G.removeEventListener(`scroll`,md)),typeof ResizeObserver<`u`){let e=new ResizeObserver(()=>{Ho(),Us(K)});e.observe(K),e.observe(G),Q.push(()=>e.disconnect())}let hd=()=>{zt()&&ya.isFollowing()&&Mo()&&Co()},_d=G.ownerDocument;_d.addEventListener(`selectionchange`,hd),Q.push(()=>{_d.removeEventListener(`selectionchange`,hd)});let Hd=/* @__PURE__ */ new Set([`PageUp`,`PageDown`,`Home`,`End`,`ArrowUp`,`ArrowDown`]),Ud=e=>{Hd.has(e.key)&&(La(),Wt()&&zt()&&ya.isFollowing()&&Co())},Gd=e=>{e.target?.closest(`a, button, [tabindex], input, textarea, select`)&&(La(),Wt()&&zt()&&ya.isFollowing()&&Co())};G.addEventListener(`keydown`,Ud),G.addEventListener(`focusin`,Gd),Q.push(()=>{G.removeEventListener(`keydown`,Ud),G.removeEventListener(`focusin`,Gd)});let Kd=e=>{if(e.deltaY!==0&&La(),!zt())return;let t=Rd({following:ya.isFollowing(),deltaY:e.deltaY,nearBottom:Id(G,24),resumeWhenNearBottom:!0});t===`pause`?Co():t===`resume`&&!Mo()&&To()};G.addEventListener(`wheel`,Kd,{passive:!0}),G.addEventListener(`touchmove`,La,{passive:!0}),G.addEventListener(`pointerdown`,La,{passive:!0}),Q.push(()=>{G.removeEventListener(`touchmove`,La),G.removeEventListener(`pointerdown`,La)}),Q.push(()=>G.removeEventListener(`wheel`,Kd)),Jt.addEventListener(`click`,()=>{Lo(),G.scrollTop=G.scrollHeight,xa=G.scrollTop,To(),Eo(!0),So()}),Q.push(()=>Jt.remove()),Q.push(()=>{ho(),Lo()});let Yd=()=>{Y&&(Pi&&=(Y.removeEventListener(`click`,Pi),null),R()?(Y.style.display=``,Pi=()=>{ys(!1,`user`)},Y.addEventListener(`click`,Pi)):Y.style.display=`none`)};Yd(),(()=>{let{clearChatButton:e}=ot;e&&e.addEventListener(`click`,()=>{let e=Rc;if(e?.historyAvailable()){e.startNewConversation({focusComposer:!0}).catch(e=>{r.debug&&console.warn(`[AgentWidget] New conversation failed:`,e)});return}$.clearMessages(),r.layout?.topFade&&(G.scrollTop=0),G.removeAttribute(`data-persona-top-fade`),ca.clear(),To(),Vt(ot.composerOverlay);try{localStorage.removeItem(Mg),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Mg}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Mg)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let t=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(t),j?.clear&&no(()=>j.clear(),`[AgentWidget] Failed to clear storage adapter:`),ne={},pe.syncFromMetadata(),_n?.clearAttachments(),uo(),Rn(void 0),Pn(void 0),ha(),Ie?.clear(),Le?.reset(),Ve?.update()})})();let Xd=[[`keydown`,Wl],[`input`,Vl],[`input`,yn],[`input`,bn],[`keyup`,bn],[`paste`,Ql],[`focus`,ir]],$d=e=>{if(e)for(let[t,n]of Xd)Zn?.addListener(e,t,n)},ef=e=>{if(e)for(let[t,n]of Xd)Zn?.removeListener(e,t,n)},tf=()=>{Zn&&(Zn.addListener(Zn.form,`submit`,Pl),Zn.addListener(Zn.footer,`click`,bn),$d(q),X&&Zn.addListener(X,`click`,Gu),ed())};tf();let nf=()=>{vn?.onComposerSwap((e,t)=>{ef(t),q=e,Zn&&(Zn.input=e),$d(e),$n(),ks(),yn()})};nf();let rf=!1;function af(){if(!rf){rf=!0;try{let e=q?.value??``,t=wt.ownerDocument??document,n=q?t.activeElement===q:!1;Pu(),Zn?.destroy(),Zn=null,vn?.destroy(),vn=null;let i=null,a=()=>(i=L()?ap({config:r}):rp({config:r}),i.footer),o=Yn(a)??a();rt.replaceComposer(o),wt=rt.composer.footer;let s=i!==null&&o===i.footer;Jn=!s,kt=s?i.setSendButtonMode:()=>{},qn(wt),er(wt),nr(),rr(),ar(),nf(),lr(),ur(),dr(),tf();let c=Ni.indexOf(Ai);if(Ai.destroy(),Ai=Mf(lt),c>=0&&(Ni[c]=Ai),q&&(q.value=e),yn(),bn(),nc(),ea(),As($.isStreaming()),r.statusIndicator?.mode===`transient`&&!L()){let e=$.getStatus();nt(dt,tt(e),r.statusIndicator,e)}Ga.active&&wu(`recording`),jr(),cd(),pn(),mr(),Ds(),n&&q?.focus()}finally{rf=!1}}}let lf=e.ownerDocument??document;lf.addEventListener(`keydown`,ql,!0);let uf=()=>{co()},df=()=>{lf.visibilityState===`hidden`&&co()};typeof window<`u`&&(window.addEventListener(`pagehide`,uf),lf.addEventListener(`visibilitychange`,df),Q.push(()=>{window.removeEventListener(`pagehide`,uf),lf.removeEventListener(`visibilitychange`,df)}));let ff=`persona-attachment-drop-active`,hf=0,gf=()=>{hf=0,W.classList.remove(ff)},yf=()=>r.attachments?.enabled===!0&&_n!==null&&!xs(),bf=e=>{Lg(e.dataTransfer)&&yf()&&(hf++,hf===1&&W.classList.add(ff))},Sf=e=>{Lg(e.dataTransfer)&&yf()&&(hf--,hf<=0&&gf())},Ef=e=>{Lg(e.dataTransfer)&&yf()&&(e.preventDefault(),e.dataTransfer.dropEffect=`copy`)},Of=e=>{if(!Lg(e.dataTransfer)||!yf())return;e.preventDefault(),e.stopPropagation(),gf();let t=Array.from(e.dataTransfer.files??[]);t.length!==0&&_n.handleFiles(t)};W.addEventListener(`dragenter`,bf,!0),W.addEventListener(`dragleave`,Sf,!0),e.addEventListener(`dragover`,Ef,!0),e.addEventListener(`drop`,Of,!0);let kf=e.ownerDocument,Af=e=>{yf()&&e.preventDefault()},Pf=e=>{yf()&&e.preventDefault()};kf.addEventListener(`dragover`,Af),kf.addEventListener(`drop`,Pf),Q.push(()=>{Zn?.destroy(),Zn=null,Pu(),or?.destroy(),or=null,jn?.destroy(),jn=null,Nn?.destroy(),Nn=null,Ln?.destroy(),Ln=null,kn=null,An=null,co(),oo.destroy(),yl&&clearTimeout(yl),ha(),_l?.abort(),_l=null,_n?.destroy(),_n=null,Z.destroy(),lf.removeEventListener(`keydown`,ql,!0),vn?.destroy()}),Q.push(()=>{W.removeEventListener(`dragenter`,bf,!0),W.removeEventListener(`dragleave`,Sf,!0),e.removeEventListener(`dragover`,Ef,!0),e.removeEventListener(`drop`,Of,!0),kf.removeEventListener(`dragover`,Af),kf.removeEventListener(`drop`,Pf),gf()}),Q.push(()=>{$.cancel()}),ad?Q.push(()=>{ad?.destroy()}):od&&Q.push(()=>{od?.remove()});let Ff={update(t){let n=r.future?.v5Defaults===!0,i=r.toolCall,a=r.messageActions,o=r.layout?.messages,s=r.colorScheme,d=r.loadingIndicator,p=r.iterationDisplay,m=r.features?.showReasoning,h=r.features?.showToolCalls,g=r.features?.toolCallDisplay,_=r.features?.reasoningDisplay,v=r.features?.streamAnimation?.type,y=r.features?.history?.enabled===!0,b=r.features?.history?.provider,x=r.getIdentityProof,S=r.clientToken,C=r.contextMentions;r=$h({...r,features:l},t),l=r.features,r=Ih(r),c(),gi(),vd(e,r),dh(e,r),fh(e,r),Ze(),hi(),r.colorScheme!==s&&Ti();let w=Yh.getForInstance(r.plugins);u.length=0,u.push(...w),Wc(),me=r.launcher?.enabled??!0,I=r.launcher?.autoExpand??!1,Te=r.features?.showReasoning??!0,Ee=r.features?.showToolCalls??!0,ke=r.features?.scrollToBottom??{};let T=Rt();Ae=r.features?.scrollBehavior??{},T!==Rt()&&(Lo(),To()),Ba(),gn(),So();let E=De;if(De=r.features?.showEventStreamToggle??!1,De&&!E){if(Ie||(qe(),$.setSSEEventCallback((e,t)=>{r.onSSEEvent?.(e,t),Ke(e,t)})),!Kn&&Ct){let e=r.features?.eventStream?.classNames,t=`persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1`+(e?.toggleButton?` `+e.toggleButton:``);Kn=B(`button`,t),Kn.style.width=`28px`,Kn.style.height=`28px`,Kn.style.color=Bf.actionIconColor,Kn.type=`button`,Kn.setAttribute(`aria-label`,`Event Stream`),Kn.title=`Event Stream`;let n=k(f.Activity,`18px`,`currentColor`,1.5);n&&Kn.appendChild(n);let i=ot.clearChatButtonWrapper,a=ot.closeButtonWrapper,o=i||a;o&&o.parentNode===Ct?Ct.insertBefore(Kn,o):Ct.appendChild(Kn),Kn.addEventListener(`click`,()=>{He?Gn():Wn()})}}else!De&&E&&(Gn(),Kn&&=(Kn.remove(),null),Ie?.clear(),Ne?.destroy(),Ie=null,Ne=null,Le?.reset(),Le=null,ze=null);if(r.launcher?.enabled===!1&&ad&&(ad.destroy(),ad=null),r.launcher?.enabled===!1&&od&&(od.remove(),od=null),r.launcher?.enabled!==!1&&!ad&&!od){let{instance:t,element:n}=ym({config:r,plugins:u,onToggle:id});ad=t,t||(od=n),e.appendChild(n)}ad&&ad.update(r),qc(),St&&r.launcher?.subtitle!==void 0&&(St.textContent=r.launcher.subtitle);let D=r.layout?.header;if(D?.layout!==ve&&Ct){let e=D?np(r,D,{showClose:R(),onClose:()=>ys(!1,`user`)}):Uf({config:r,showClose:R(),onClose:()=>ys(!1,`user`)});rt.replaceHeader(e),Ct=rt.header.element,bt=rt.header.iconHolder,xt=rt.header.headerTitle,St=rt.header.headerSubtitle,Y=rt.header.closeButton,ve=D?.layout,qc()}else if(D){if(bt&&(bt.style.display=D.showIcon===!1?`none`:``),xt&&(xt.style.display=D.showTitle===!1?`none`:``),St&&(St.style.display=D.showSubtitle===!1?`none`:``),Y){let e=R()&&D.showCloseButton!==!1;Y.style.display=e?``:`none`}if(ot.clearChatButtonWrapper){let e=D.showClearChat;if(e!==void 0){ot.clearChatButtonWrapper.style.display=e?``:`none`;let{closeButtonWrapper:t}=ot;t&&!t.classList.contains(`persona-absolute`)&&(e?t.classList.remove(`persona-ml-auto`):t.classList.add(`persona-ml-auto`))}}}let O=r.layout?.showHeader!==!1;Ct&&(Ct.style.display=O?``:`none`);let ee=r.layout?.showFooter!==!1;wt&&(wt.style.display=ee?``:`none`),pn(),So(),me===_e?I!==ge&&ys(I,`auto`):me?ys(I,`auto`):(z=!0,vs()),ge=I,_e=me,ud(),Yd();let j=JSON.stringify(r.toolCall)!==JSON.stringify(i),te=JSON.stringify(r.messageActions)!==JSON.stringify(a),ne=JSON.stringify(r.layout?.messages)!==JSON.stringify(o),re=r.loadingIndicator?.render!==d?.render||r.loadingIndicator?.renderIdle!==d?.renderIdle||r.loadingIndicator?.showBubble!==d?.showBubble,ie=r.iterationDisplay!==p,M=(r.features?.showReasoning??!0)!==(m??!0)||(r.features?.showToolCalls??!0)!==(h??!0)||JSON.stringify(r.features?.toolCallDisplay)!==JSON.stringify(g)||JSON.stringify(r.features?.reasoningDisplay)!==JSON.stringify(_);(r.future?.v5Defaults===!0!==n||j||te||ne||re||ie||M)&&$&&(_a++,ts(K,$.getMessages(),we));let N=r.features?.streamAnimation?.type;if(N!==v&&N&&N!==`none`){let t=Di(N,r.features?.streamAnimation?.plugins);t&&mf(t,e)}let P=r.launcher??{},ae=P.headerIconHidden??!1,oe=r.layout?.header?.showIcon,se=ae||oe===!1,ce=P.headerIconName,de=P.headerIconSize??`40px`;if(bt){let e=Ct,t=e?.querySelector(`.persona-flex-col`);if(se)bt.style.display=`none`,e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(bt.style.display=``,bt.style.height=de,bt.style.width=de,e&&t&&(e.contains(bt)?bt.nextSibling!==t&&(bt.remove(),e.insertBefore(bt,t)):e.insertBefore(bt,t)),ce){let e=parseFloat(de)||24,t=F(ce,e*.6,`currentColor`,1);t?(t.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,t.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,bt.replaceChildren(t)):bt.textContent=P.agentIconText??`💬`}else if(P.iconUrl){let e=bt.querySelector(`img`);if(e)e.src=P.iconUrl,e.style.height=de,e.style.width=de;else{let e=document.createElement(`img`);e.src=P.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=de,e.style.width=de,bt.replaceChildren(e)}}else{let e=bt.querySelector(`svg`),t=bt.querySelector(`img`);(e||t)&&bt.replaceChildren(),bt.textContent=P.agentIconText??`💬`}let n=bt.querySelector(`img`);n&&(n.style.height=de,n.style.width=de)}}let fe=r.layout?.header?.showTitle,he=r.layout?.header?.showSubtitle;if(xt&&(xt.style.display=fe===!1?`none`:``),St&&(St.style.display=he===!1?`none`:``),Y){let e=R()&&r.layout?.header?.showCloseButton!==!1;if(Y.style.display=e?``:`none`,!L()){let e=P.closeButtonSize??``;Y.style.height=e,Y.style.width=e,Y.style.minWidth=e,Y.style.minHeight=e}let t=P.closeButtonPlacement??`inline`,{closeButtonWrapper:n}=ot,i=t===`top-right`,a=n?.classList.contains(`persona-absolute`);if(n&&i!==a){if(n.remove(),i){n.className=`persona-absolute persona-top-4 persona-right-4 persona-z-50`;let e=Rc?.railColumn??W;e.style.position=`relative`,e.appendChild(n)}else{let e=P.clearChat?.placement??`inline`;n.className=(P.clearChat?.enabled??!0)&&e===`inline`?``:`persona-ml-auto`,Ct&&Ct.appendChild(n)}}if(Y.style.color=P.closeButtonColor||Bf.actionIconColor,P.closeButtonBackgroundColor?(Y.style.backgroundColor=P.closeButtonBackgroundColor,Y.classList.remove(`hover:persona-bg-gray-100`)):(Y.style.backgroundColor=``,Y.classList.add(`hover:persona-bg-gray-100`)),P.closeButtonBorderWidth||P.closeButtonBorderColor){let e=P.closeButtonBorderWidth||`0px`,t=P.closeButtonBorderColor||`transparent`;Y.style.border=`${e} solid ${t}`,Y.classList.remove(`persona-border-none`)}else Y.style.border=``,Y.classList.add(`persona-border-none`);P.closeButtonBorderRadius?(Y.style.borderRadius=P.closeButtonBorderRadius,Y.classList.remove(`persona-rounded-full`)):(Y.style.borderRadius=``,Y.classList.add(`persona-rounded-full`)),P.closeButtonPaddingX?(Y.style.paddingLeft=P.closeButtonPaddingX,Y.style.paddingRight=P.closeButtonPaddingX):(Y.style.paddingLeft=``,Y.style.paddingRight=``),P.closeButtonPaddingY?(Y.style.paddingTop=P.closeButtonPaddingY,Y.style.paddingBottom=P.closeButtonPaddingY):(Y.style.paddingTop=``,Y.style.paddingBottom=``),If(Y,P.closeButtonIconName??`x`,{iconSize:L()?rm:void 0,iconText:P.closeButtonIconText??`×`});let o=P.closeButtonTooltipText??`Close chat`,s=P.closeButtonShowTooltip??!0;Y.setAttribute(`aria-label`,o),n&&yr({anchor:Y,trigger:n,text:()=>Y?.getAttribute(`aria-label`)??o,enabled:s})}let{clearChatButton:ye,clearChatButtonWrapper:be}=ot;if(ye){let e=P.clearChat??{},t=e.enabled??!0,n=r.layout?.header?.showClearChat,i=n===void 0?t:n,a=e.placement??`inline`;if(be){be.style.display=i?``:`none`;let{closeButtonWrapper:e}=ot;!L()&&e&&!e.classList.contains(`persona-absolute`)&&(i?e.classList.remove(`persona-ml-auto`):e.classList.add(`persona-ml-auto`));let t=a===`top-right`,n=be.classList.contains(`persona-absolute`);if(!L()&&t!==n&&i){if(be.remove(),t){be.className=`persona-absolute persona-top-4 persona-z-50`,be.style.right=`48px`;let e=Rc?.railColumn??W;e.style.position=`relative`,e.appendChild(be)}else{be.className=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,be.style.right=``;let e=ot.closeButtonWrapper;Ct&&e&&e.parentElement===Ct?Ct.insertBefore(be,e):Ct&&Ct.appendChild(be)}let e=ot.closeButtonWrapper;e&&!e.classList.contains(`persona-absolute`)&&(t?e.classList.add(`persona-ml-auto`):e.classList.remove(`persona-ml-auto`))}}if(i){if(!L()){let t=e.size??``;ye.style.height=t,ye.style.width=t,ye.style.minWidth=t,ye.style.minHeight=t}let t=e.iconColor??``;if(ye.style.color=t||Bf.actionIconColor,If(ye,e.iconName??`refresh-cw`,{iconSize:L()?im:void 0}),e.backgroundColor?(ye.style.backgroundColor=e.backgroundColor,ye.classList.remove(`hover:persona-bg-gray-100`)):(ye.style.backgroundColor=``,ye.classList.add(`hover:persona-bg-gray-100`)),e.borderWidth||e.borderColor){let t=e.borderWidth||`0px`,n=e.borderColor||`transparent`;ye.style.border=`${t} solid ${n}`,ye.classList.remove(`persona-border-none`)}else ye.style.border=``,ye.classList.add(`persona-border-none`);e.borderRadius?(ye.style.borderRadius=e.borderRadius,ye.classList.remove(`persona-rounded-full`)):(ye.style.borderRadius=``,ye.classList.add(`persona-rounded-full`)),e.paddingX?(ye.style.paddingLeft=e.paddingX,ye.style.paddingRight=e.paddingX):(ye.style.paddingLeft=``,ye.style.paddingRight=``),e.paddingY?(ye.style.paddingTop=e.paddingY,ye.style.paddingBottom=e.paddingY):(ye.style.paddingTop=``,ye.style.paddingBottom=``);let n=e.tooltipText??`Clear chat`,r=e.showTooltip??!0;ye.setAttribute(`aria-label`,n),be&&yr({anchor:ye,trigger:be,text:()=>ye?.getAttribute(`aria-label`)??n,enabled:r})}}let xe=r.actionParsers&&r.actionParsers.length?r.actionParsers:[rg],Se=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ag.message,ag.messageAndClick];pe=sg({parsers:xe,handlers:Se,getSessionMetadata:le,updateSessionMetadata:ue,emit:A.emit,documentRef:typeof document<`u`?document:null}),we=Hg(r,pe,Ce),hc(),$.updateConfig(r),cl(),(r.features?.history?.enabled===!0!==y||r.features?.history?.provider!==b||r.getIdentityProof!==x||r.clientToken!==S)&&(Rc?.closeHistory({restoreFocus:!1}),Rc?.installHistoryProvider()),Rc?.syncHistoryChromeImpl(),el(),Hc()&&!Rc&&Qc().catch(()=>{}),ts(K,$.getMessages(),we),ea(),nc(),tc(),As($.isStreaming()),C!==r.contextMentions&&af();let Oe=r.voiceRecognition?.enabled===!0,je=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),Me=ms(r.voiceRecognition?.provider);if(Oe&&(je||Me)){if(!X||!At){let e=sa(r);if(e){X=e.button,At=e.wrapper;let t=Ot&&Ot.parentElement===Dt?Ot:null;Dt?Dt.insertBefore(At,t):ut?.appendChild(At),Zn&&(Zn.micButton=X),Zn?.addListener(X,`click`,Gu),X.disabled=xs()||$.isStreaming()&&!Cs()}}else{let e=r.voiceRecognition??{},t=r.sendButton??{},n=e.iconName??`mic`,i=e.iconSize,a=parseFloat(i??``)||24;X.classList.add(ta),X.classList.toggle(na,!i),X.style.width=i??``,X.style.height=i??``,X.style.minWidth=i??``,X.style.minHeight=i??``;let o=e.iconColor??t.textColor;X.innerHTML=``;let s=F(n,a,o||`currentColor`,1.5);s?X.appendChild(s):X.textContent=`🎤`;let c=e.backgroundColor??t.backgroundColor;c?X.style.backgroundColor=c:X.style.backgroundColor=``,o?X.style.color=o:X.style.color=`var(--persona-text, #111827)`,e.borderWidth?(X.style.borderWidth=e.borderWidth,X.style.borderStyle=`solid`):(X.style.borderWidth=``,X.style.borderStyle=``),e.borderColor?X.style.borderColor=e.borderColor:X.style.borderColor=``,e.paddingX?(X.style.paddingLeft=e.paddingX,X.style.paddingRight=e.paddingX):(X.style.paddingLeft=``,X.style.paddingRight=``),e.paddingY?(X.style.paddingTop=e.paddingY,X.style.paddingBottom=e.paddingY):(X.style.paddingTop=``,X.style.paddingBottom=``);let l=e.tooltipText??`Start voice recognition`,u=e.showTooltip??!1;X.setAttribute(`aria-label`,l),At&&yr({anchor:X,trigger:At,text:()=>X?.getAttribute(`aria-label`)??l,enabled:u}),At.style.display=``,X.disabled=xs()||$.isStreaming()&&!Cs()}}else X&&At&&(At.style.display=`none`,ms(r.voiceRecognition?.provider)?$.isVoiceActive()&&$.toggleVoice():nu&&Lu());if(ed(),r.attachments?.enabled===!0){if(!Mt||!jt){let e=r.attachments??{};Pt||(Pt=B(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),Pt.style.display=`none`,(q.parentElement??ut).insertBefore(Pt,q)),Nt||(Nt=document.createElement(`input`),Nt.type=`file`,Nt.accept=(e.allowedTypes??Hi).join(`,`),Nt.multiple=(e.maxFiles??4)>1,Nt.style.display=`none`,Nt.setAttribute(`aria-label`,`Attach files`),(q.parentElement??ut).insertBefore(Nt,q)),Mt=B(`div`,`persona-send-button-wrapper`),jt=B(`button`,`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${ta} ${na}`),jt.type=`button`,jt.setAttribute(`aria-label`,e.buttonTooltipText??`Attach file`);let t=e.buttonIconName??`paperclip`;jt.style.fontSize=`18px`,jt.style.lineHeight=`1`;let n=F(t,24,`currentColor`,1.5);n?jt.appendChild(n):jt.textContent=`📎`,jt.addEventListener(`click`,e=>{e.preventDefault(),Nt?.click()}),Mt.appendChild(jt);let i=e.buttonTooltipText??`Attach file`;yr({anchor:jt,trigger:Mt,text:()=>jt?.getAttribute(`aria-label`)??i}),Et?Et.append(Mt):ut.appendChild(Mt),Zn&&(Zn.attachmentButton=jt,Zn.attachmentInput=Nt??void 0,Zn.attachmentPreviews=Pt??void 0),!_n&&Nt&&Pt&&(_n=ll.fromConfig(e,Sn),_n.setPreviewsContainer(Pt),Zn?.addListener(Nt,`change`,async()=>{_n&&Nt?.files&&(await _n.handleFileSelect(Nt.files),Nt.value=``)}))}else{Mt.style.display=``;let e=r.attachments??{};Nt&&(Nt.accept=(e.allowedTypes??Hi).join(`,`),Nt.multiple=(e.maxFiles??4)>1),_n&&_n.updateConfig({allowedTypes:e.allowedTypes,maxFileSize:e.maxFileSize,maxFiles:e.maxFiles,adapter:e.adapter})}if(W.querySelector(`.persona-attachment-drop-overlay`)?.remove(),W.appendChild(Ug(r.attachments?.dropOverlay)),jt){let e=r.attachments??{},t=e.buttonTooltipText??`Attach file`;jt.setAttribute(`aria-label`,t),jt.textContent=``;let n=F(e.buttonIconName??`paperclip`,24,`currentColor`,1.5);n?jt.appendChild(n):jt.textContent=`📎`,Mt&&yr({anchor:jt,trigger:Mt,text:()=>jt?.getAttribute(`aria-label`)??t})}}else Mt&&(Mt.style.display=`none`),_n&&_n.clearAttachments(),W.querySelector(`.persona-attachment-drop-overlay`)?.remove();let Pe=r.sendButton??{},Fe=Pe.useIcon??!1,Re=Pe.iconText??`↑`,Be=Pe.iconName,Ve=Pe.tooltipText??`Send message`,Ue=Pe.showTooltip??!1,We=Pe.size,Ge=parseFloat(We??``)||40,Je=Pe.backgroundColor,Ye=Pe.textColor;if(Fe){if(J.style.width=We??``,J.style.height=We??``,J.style.minWidth=We??``,J.style.minHeight=We??``,J.style.fontSize=`18px`,J.style.lineHeight=`1`,Ye?J.style.color=Ye:J.style.color=`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`,!$.isStreaming()){if(J.innerHTML=``,Be){let e=parseFloat(Pe.iconSize??``)||Math.round(Ge*.5),t=Ye?.trim()||`currentColor`,n=Pe.iconStrokeWidth??2,r=F(Be,e,t,n),i=F(Pe.stopIconName??`square`,e,t,n);r&&i?J.appendChild(aa(r,i)):r?J.appendChild(r):J.textContent=Re}else J.textContent=Re}J.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${ta}`,Je?(J.style.backgroundColor=Je,J.classList.remove(`persona-bg-persona-primary`)):(J.style.backgroundColor=``,J.classList.add(`persona-bg-persona-primary`))}else J.textContent=r.copy?.sendButtonLabel??`Send`,J.style.width=``,J.style.height=``,J.style.minWidth=``,J.style.minHeight=``,J.style.fontSize=``,J.style.lineHeight=``,J.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`,Je?(J.style.backgroundColor=Je,J.classList.remove(`persona-bg-persona-accent`)):J.classList.add(`persona-bg-persona-accent`),Ye?J.style.color=Ye:J.classList.add(`persona-text-white`);Pe.borderWidth?(J.style.borderWidth=Pe.borderWidth,J.style.borderStyle=`solid`):(J.style.borderWidth=``,J.style.borderStyle=``),Pe.borderColor?J.style.borderColor=Pe.borderColor:J.style.borderColor=``,Pe.paddingX?(J.style.paddingLeft=Pe.paddingX,J.style.paddingRight=Pe.paddingX):(J.style.paddingLeft=``,J.style.paddingRight=``),Pe.paddingY?(J.style.paddingTop=Pe.paddingY,J.style.paddingBottom=Pe.paddingY):(J.style.paddingTop=``,J.style.paddingBottom=``),$.isStreaming()||J.setAttribute(`aria-label`,Ve),Ds(),Ot&&yr({anchor:J,trigger:Ot,text:()=>J.getAttribute(`aria-label`)??Ve,enabled:Ue}),hr(),bi();let V=iu(Z.getState().activeModeIds,r.composer?.modes);Z.setActiveModeIds(V),wn().length>0!=!!jn&&ur(),jn?.render(V,wn());for(let e of[...Mn.keys()])$l(e,r.composer?.modeGroups)||Mn.delete(e);Mn.forEach(e=>e.repaint()),kn?.repaint(),or?.resolve();let Qe=bd(r,L());if(_i(),Qe){K.style.maxWidth=Qe,K.style.marginLeft=`auto`,K.style.marginRight=`auto`,K.style.width=`100%`,gt.style.maxWidth=Qe,gt.style.marginLeft=`auto`,gt.style.marginRight=`auto`,gt.style.width=`100%`;for(let e of[ut,lt,Pt,dt])e&&(e.style.maxWidth=Qe,e.style.marginLeft=`auto`,e.style.marginRight=`auto`,e.style.width=`100%`)}else{K.style.maxWidth=``,K.style.marginLeft=``,K.style.marginRight=``,K.style.width=``,gt.style.maxWidth=``,gt.style.marginLeft=``,gt.style.marginRight=``,gt.style.width=``;for(let e of[ut,lt,Pt,dt])e&&(e.style.maxWidth=``,e.style.marginLeft=``,e.style.marginRight=``,e.style.width=``)}let H=r.statusIndicator??{};if(zr(dt,ut,H),Rr(dt,H,$?.getStatus()??`idle`),$){let e=$.getStatus();nt(dt,(e=>e===`idle`?H.idleText??cn.idle:e===`connecting`?H.connectingText??cn.connecting:e===`connected`?H.connectedText??cn.connected:e===`error`?H.errorText??cn.error:e===`paused`?H.pausedText??cn.paused:e===`resuming`?H.resumingText??cn.resuming:cn[e])(e),H,e)}dt.classList.remove(`persona-text-left`,`persona-text-center`,`persona-text-right`);let $e=H.align===`left`?`persona-text-left`:H.align===`center`?`persona-text-center`:`persona-text-right`;dt.classList.add($e),$n(),ks(),mr(),Xe()},open(){R()&&ys(!0,`api`)},close(){R()&&ys(!1,`api`)},toggle(){R()&&ys(!z,`api`)},reconnect(){$.reconnectNow()},clearChat(){Fr=!1,o.clear(),i.clear(),a.clear(),s.clear(),$.clearMessages(),r.layout?.topFade&&(G.scrollTop=0),G.removeAttribute(`data-persona-top-fade`),ca.clear(),To();try{localStorage.removeItem(Mg),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Mg}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Mg)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let e=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(e),j?.clear&&no(()=>j.clear(),`[AgentWidget] Failed to clear storage adapter:`),ne={},pe.syncFromMetadata(),_n?.clearAttachments(),uo(),Rn(void 0),Pn(void 0),ha(),Ie?.clear(),Le?.reset(),Ve?.update()},setMessage(e){return!q||$.isStreaming()||xs()?!1:(!z&&R()&&ys(!0,`system`),q.value=e,q.dispatchEvent(new Event(`input`,{bubbles:!0})),!0)},submitMessage(e){if($.isStreaming()||ws())return!1;let t=e?.trim()||q.value.trim();return t?(!z&&R()&&ys(!0,`system`),q.value=``,q.style.height=`auto`,yn(),Nl(t,{consumeDraft:!1}),!0):!1},getComposerState(){return Z.getState()},setQuote(e){let t=e?.text?.trim();t&&Pn({...e,text:t})},clearQuote(){Pn(void 0)},startVoiceRecognition(){return $.isStreaming()?!1:ms(r.voiceRecognition?.provider)?($.isVoiceActive()||$.isBargeInActive()||(!z&&R()&&ys(!0,`system`),Ga.manuallyDeactivated=!1,Xa(),$.toggleVoice().then(()=>{Ga.active=qa(),Xa(),Ya(`user`),Ga.active&&Bu()})),!0):nu?!0:Fu()?(!z&&R()&&ys(!0,`system`),Ga.manuallyDeactivated=!1,Xa(),Iu(`user`),!0):!1},stopVoiceRecognition(){return ms(r.voiceRecognition?.provider)?!$.isVoiceActive()&&!$.isBargeInActive()?!1:(($.isBargeInActive()?$.deactivateBargeIn():$.toggleVoice()).then(()=>{Ga.active=!1,Ga.manuallyDeactivated=!0,Xa(),Ya(`user`),Wu()}),!0):nu?(Ga.manuallyDeactivated=!0,Xa(),Lu(`user`),!0):!1},injectMessage(e){return!z&&R()&&ys(!0,`system`),$.injectMessage(e)},injectAssistantMessage(e){!z&&R()&&ys(!0,`system`);let t=$.injectAssistantMessage(e);return xe&&(xe=!1,Se&&=(clearTimeout(Se),null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),t},injectUserMessage(e){return!z&&R()&&ys(!0,`system`),$.injectUserMessage(e)},injectSystemMessage(e){return!z&&R()&&ys(!0,`system`),$.injectSystemMessage(e)},injectMessageBatch(e){return!z&&R()&&ys(!0,`system`),$.injectMessageBatch(e)},injectComponentDirective(e){return!z&&R()&&ys(!0,`system`),$.injectComponentDirective(e)},injectTestMessage(e){!z&&R()&&ys(!0,`system`),$.injectTestEvent(e)},async connectStream(e,t){return $.connectStream(e,t)},__pushEventStreamEvent(e){De&&(qe(),Ke(e.type,e.payload))},showEventStream(){De&&Wn()},hideEventStream(){He&&Gn()},isEventStreamVisible(){return He},listConversations(e){return $.listConversations(e)},getActiveConversationId(){return $.getActiveConversationId()},openConversation(e,t){return $c(n=>n.openHistoryConversation(e,{focusComposer:t?.focus===!0}))},startNewConversation(e){return $c(t=>t.startNewConversation({focusComposer:e?.focus===!0}))},warmSession(){tl()},deleteConversation(e){return $c(t=>t.deleteHistoryConversation(e))},renameConversation(e,t){return $c(n=>n.updateHistoryConversation(e,{title:t}))},setConversationStarred(e,t){return $c(n=>n.updateHistoryConversation(e,{starred:t}))},clearConversationHistory(e){return $c(t=>t.clearConversationHistory(e))},resetHistoryIdentity(){return $c(e=>e.resetHistoryIdentity())},async getVisitorToken(){let e=dc;if(!e)return null;let t=await e.get();return e===dc?t:null},getHistoryIdentityStatus(){let e=Rc?.historyProvider;return e?e.getIdentityStatus():Hc()?{state:`unavailable`,reason:`ineligible_mode`}:{state:`unavailable`,reason:`history_disabled`}},showHistory(e){return Hc()?$c(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...e?.focus===void 0?{}:{focus:e.focus}})):Promise.resolve()},hideHistory(e){Rc?.closeHistory(e?.restoreFocus===void 0?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible(){return Je},showArtifacts(){ah(r)&&(Fr=!1,Br=!0,hi(),Or?.setMobileOpen(!0))},hideArtifacts(){ah(r)&&(Fr=!0,hi())},upsertArtifact(e){return ah(r)?(Oe(r.features?.artifacts,{artifactType:e.artifactType,...e.artifactType===`markdown`&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})===`panel`&&(Fr=!1,Br=!0),$.upsertArtifact(e)):null},selectArtifact(e){ah(r)&&$.selectArtifact(e)},clearArtifacts(){ah(r)&&$.clearArtifacts()},getArtifacts(){return $?.getArtifacts()??[]},getSelectedArtifactId(){return $?.getSelectedArtifactId()??null},focusInput(){return me&&!z&&!L()||!q?!1:(q.focus(),!0)},async resolveApproval(e,t,n){let r=$.getMessages().find(t=>t.variant===`approval`&&t.approval?.id===e);if(!r?.approval)throw Error(`Approval not found: ${e}`);if(r.approval.toolType===`webmcp`)$.resolveWebMcpApproval(r.id,t);else return $.resolveApproval(r.approval,t,n)},setFollowUpSuggestions(e){ia(e)},clearFollowUpSuggestions(){ra()},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...ne}},updatePersistentMetadata(e){ue(e)},on(e,t){return A.on(e,t)},off(e,t){A.off(e,t)},isOpen(){return R()&&z},isVoiceActive(){return Ga.active},toggleReadAloud(e){$.toggleReadAloud(e)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(e){return $.getReadAloudState(e)},onReadAloudChange(e){return $.onReadAloudChange(e)},getState(){return{open:R()&&z,launcherEnabled:me,voiceActive:Ga.active,streaming:$.isStreaming()}},showCSATFeedback(e){!z&&R()&&ys(!0,`system`);let t=K.querySelector(`.persona-feedback-container`);t&&t.remove();let n=Ag({onSubmit:async(t,n)=>{$.isClientTokenMode()&&await $.submitCSATFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});K.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},showNPSFeedback(e){!z&&R()&&ys(!0,`system`);let t=K.querySelector(`.persona-feedback-container`);t&&t.remove();let n=jg({onSubmit:async(t,n)=>{$.isClientTokenMode()&&await $.submitNPSFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});K.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},async submitCSATFeedback(e,t){return $.submitCSATFeedback(e,t)},async submitNPSFeedback(e,t){return $.submitNPSFeedback(e,t)},destroy(){Mc(),gc!=null&&(clearInterval(gc),gc=null),o.clear(),i.clear(),a.clear(),s.clear(),Q.forEach(e=>e()),it.remove(),at?.remove(),ad?.destroy(),od?.remove(),Pi&&Y.removeEventListener(`click`,Pi)}};if(((n?.debugTools??!1)||r.debug)&&typeof window<`u`){let e=window.AgentWidgetBrowser,t={controller:Ff,getMessages:Ff.getMessages,getStatus:Ff.getStatus,getMetadata:Ff.getPersistentMetadata,updateMetadata:Ff.updatePersistentMetadata,clearHistory:()=>Ff.clearChat(),setVoiceActive:e=>e?Ff.startVoiceRecognition():Ff.stopVoiceRecognition()};window.AgentWidgetBrowser=t,Q.push(()=>{window.AgentWidgetBrowser===t&&(window.AgentWidgetBrowser=e)})}if(typeof window<`u`){let t=e.getAttribute(`data-persona-instance`)||e.id||`persona-`+Math.random().toString(36).slice(2,8),n=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&Ff.focusInput()};if(window.addEventListener(`persona:focusInput`,n),Q.push(()=>{window.removeEventListener(`persona:focusInput`,n)}),De){let e=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&Ff.showEventStream()},n=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&Ff.hideEventStream()};window.addEventListener(`persona:showEventStream`,e),window.addEventListener(`persona:hideEventStream`,n),Q.push(()=>{window.removeEventListener(`persona:showEventStream`,e),window.removeEventListener(`persona:hideEventStream`,n)})}let r=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&Ff.showHistory()},i=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&Ff.hideHistory()};window.addEventListener(`persona:showHistory`,r),window.addEventListener(`persona:hideHistory`,i),Q.push(()=>{window.removeEventListener(`persona:showHistory`,r),window.removeEventListener(`persona:hideHistory`,i)});let a=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&Ff.showArtifacts()},o=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&Ff.hideArtifacts()},s=e=>{let n=e.detail;n?.instanceId&&n.instanceId!==t||n?.artifact&&Ff.upsertArtifact(n.artifact)},c=e=>{let n=e.detail;n?.instanceId&&n.instanceId!==t||typeof n?.id==`string`&&Ff.selectArtifact(n.id)},l=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&Ff.clearArtifacts()};window.addEventListener(`persona:showArtifacts`,a),window.addEventListener(`persona:hideArtifacts`,o),window.addEventListener(`persona:upsertArtifact`,s),window.addEventListener(`persona:selectArtifact`,c),window.addEventListener(`persona:clearArtifacts`,l),Q.push(()=>{window.removeEventListener(`persona:showArtifacts`,a),window.removeEventListener(`persona:hideArtifacts`,o),window.removeEventListener(`persona:upsertArtifact`,s),window.removeEventListener(`persona:selectArtifact`,c),window.removeEventListener(`persona:clearArtifacts`,l)})}let Rf=Rg(r.persistState);if(Rf&&R()){let t=zg(Rf.storage),n=`${Rf.keyPrefix}widget-open`,r=`${Rf.keyPrefix}widget-voice`,i=`${Rf.keyPrefix}widget-voice-mode`;if(t){let a=Rf.persist?.openState&&t.getItem(n)===`true`,o=Rf.persist?.voiceState&&t.getItem(r)===`true`,s=Rf.persist?.voiceState&&t.getItem(i)===`true`;if(a&&(ad?.setPanelOpen(!0,`auto`),setTimeout(()=>{Ff.open(),setTimeout(()=>{if(o||s)Ff.startVoiceRecognition();else if(Rf.persist?.focusInput){let t=e.querySelector(`textarea`);t&&t.focus()}},100)},0)),Rf.persist?.openState&&(A.on(`widget:opened`,()=>{t.setItem(n,`true`)}),A.on(`widget:closed`,()=>{t.setItem(n,`false`)})),Rf.persist?.voiceState&&(A.on(`voice:state`,e=>{t.setItem(r,e.active?`true`:`false`)}),A.on(`user:message`,e=>{t.setItem(i,e.viaVoice?`true`:`false`)})),Rf.clearOnChatClear){let e=()=>{t.removeItem(n),t.removeItem(r),t.removeItem(i)},a=()=>e();window.addEventListener(`persona:clear-chat`,a),Q.push(()=>{window.removeEventListener(`persona:clear-chat`,a)})}}}if(oe&&R()&&(ad?.setPanelOpen(!0,`auto`),setTimeout(()=>{Ff.open()},0)),gs(),!va){let e=E(()=>{$&&(_a++,ca.clear(),ts(K,$.getMessages(),we))});Q.push(e)}b=()=>{$&&(_a++,ca.clear(),ts(K,$.getMessages(),we))},$.getMessages().length>0&&es(),D=()=>{$&&(_a++,ca.clear(),ts(K,$.getMessages(),we))};let zf=ce(()=>{$&&(_a++,ca.clear(),ts(K,$.getMessages(),we))});Q.push(zf);let Vf=ih(()=>{$&&(_a++,ca.clear(),ts(K,$.getMessages(),we),rh()?.updateInlineArtifactBlocks(K,Pr.artifacts,{suppressTransition:!0}),hi())});return Q.push(Vf),Ff};dn();const qg=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let i=/^(\d+(?:\.\d+)?)%$/i.exec(n);return i?Math.max(0,t*parseFloat(i[1])/100):420},Jg=(e,t)=>{t===!1?e.style.maxHeight=``:(e.style.maxHeight=`100vh`,e.style.maxHeight=t)},Yg=(e,t)=>{t===!1?(e.style.position=`relative`,e.style.top=``):(e.style.position=`sticky`,e.style.top=`0`)},Xg=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement(`div`);r.style.cssText=`width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;`,n.appendChild(r);let i=r.offsetHeight>0;r.style.height=`100%`;let a=r.offsetHeight>0;r.remove(),i&&!a&&console.warn(`[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout.`+(t.maxHeight===!1?` The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.`:` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Zg=(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`},Qg=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=``},$g=e=>{e.style.inset=``,e.style.width=``,e.style.height=``,e.style.maxWidth=``,e.style.maxHeight=``,e.style.minWidth=``,Qg(e)},e_=e=>{e.style.transition=``},t_=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=``},n_=e=>{e.style.width=``,e.style.maxWidth=``,e.style.minWidth=``,e.style.flex=`1 1 auto`},r_=(e,t)=>{e.style.width=``,e.style.minWidth=`0`,e.style.maxWidth=``,e.style.boxSizing=``,t.style.alignItems=``},i_=(e,t,n,r,i)=>{i?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},a_=(e,t,n,r,i,a)=>{let o=a?t:e;i===`left`?o.firstElementChild!==r&&o.replaceChildren(r,n):o.lastElementChild!==r&&o.replaceChildren(n,r)},o_=e=>{let t=gd(e),n=t.components?.panel,r=(e,n)=>e==null||e===``?n:Uu(t,e)??e;return{inset:r(n?.inset,Tu),canvasBackground:r(n?.canvasBackground,Eu)}},s_=(e,t,n,r)=>{t?(e.style.boxSizing=`border-box`,e.style.padding=n,e.style.background=r):(e.style.padding=``,e.style.background=``,e.style.boxSizing=``)},c_=(e,t,n,r,i,a,o,s)=>{let c=Tf(a),l=c.reveal===`push`,u=s!=null,d=s?.inset??``,f=s?.canvasBackground??``;i_(e,t,n,r,l),a_(e,t,n,r,c.side,l),e.dataset.personaHostLayout=`docked`,e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=o?`true`:`false`,e.style.width=`100%`,e.style.maxWidth=`100%`,e.style.minWidth=`0`,e.style.height=`100%`,e.style.minHeight=`0`,e.style.position=`relative`,n.style.display=`flex`,n.style.flexDirection=`column`,n.style.minHeight=`0`,n.style.position=`relative`,i.className=`persona-host`,i.style.height=`100%`,i.style.minHeight=`0`,i.style.minWidth=`0`,i.style.display=`flex`,i.style.flexDirection=`column`,i.style.flex=`1 1 auto`;let p=e.ownerDocument.defaultView,m=a?.launcher?.mobileFullscreen??!0,h=a?.launcher?.mobileBreakpoint??640,g=p!=null&&p.innerWidth<=h;if(m&&g&&o)e.dataset.personaDockMobileFullscreen=`true`,e.removeAttribute(`data-persona-dock-reveal`),t_(t),e_(r),$g(r),n_(n),r_(i,r),s_(r,!1,``,``),e.style.display=`flex`,e.style.flexDirection=`column`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,n.style.flex=`1 1 auto`,n.style.width=`100%`,n.style.minWidth=`0`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.position=`fixed`,r.style.inset=`0`,r.style.width=`100%`,r.style.height=`100%`,r.style.maxWidth=`100%`,r.style.minWidth=`0`,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.zIndex=String(a?.launcher?.zIndex??1e5),r.style.transform=`none`,r.style.transition=`none`,r.style.pointerEvents=`auto`,r.style.flex=`none`,l&&(t.style.display=`flex`,t.style.flexDirection=`column`,t.style.width=`100%`,t.style.height=`100%`,t.style.minHeight=`0`,t.style.minWidth=`0`,t.style.flex=`1 1 auto`,t.style.alignItems=`stretch`,t.style.transform=`none`,t.style.marginLeft=`0`,t.style.transition=`none`,n.style.flex=`1 1 auto`,n.style.width=`100%`,n.style.maxWidth=`100%`,n.style.minWidth=`0`);else if(e.removeAttribute(`data-persona-dock-mobile-fullscreen`),$g(r),Jg(r,c.maxHeight),s_(r,u&&o,d,f),c.reveal===`overlay`){e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,e.dataset.personaDockReveal=`overlay`,t_(t),e_(r),n_(n),r_(i,r);let a=c.animate?`transform 180ms ease`:`none`,s=c.side===`right`?`translateX(100%)`:`translateX(-100%)`,l=o?`translateX(0)`:s;r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`none`,r.style.position=`absolute`,r.style.top=`0`,r.style.bottom=`0`,r.style.width=c.width,r.style.maxWidth=c.width,r.style.minWidth=c.width,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.transition=a,r.style.transform=l,r.style.pointerEvents=o?`auto`:`none`,r.style.zIndex=`2`,c.side===`right`?(r.style.right=`0`,r.style.left=``):(r.style.left=`0`,r.style.right=``)}else if(c.reveal===`push`){e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,e.dataset.personaDockReveal=`push`,e_(r),Qg(r),r_(i,r);let a=qg(c.width,e.clientWidth),s=Math.max(0,e.clientWidth),l=c.animate?`margin-left 180ms ease`:`none`,u=c.side===`right`?o?-a:0:o?0:-a;t.style.display=`flex`,t.style.flexDirection=`row`,t.style.flex=`0 0 auto`,t.style.minHeight=`0`,t.style.minWidth=`0`,t.style.alignItems=`stretch`,t.style.height=`100%`,t.style.width=`${s+a}px`,t.style.transition=l,t.style.marginLeft=`${u}px`,t.style.transform=``,n.style.flex=`0 0 auto`,n.style.flexGrow=`0`,n.style.flexShrink=`0`,n.style.width=`${s}px`,n.style.maxWidth=`${s}px`,n.style.minWidth=`${s}px`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 auto`,r.style.flexShrink=`0`,r.style.width=c.width,r.style.minWidth=c.width,r.style.maxWidth=c.width,r.style.position=`relative`,r.style.top=``,r.style.overflow=`hidden`,r.style.transition=`none`,r.style.pointerEvents=o?`auto`:`none`}else{e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=``,t_(t),Qg(r),n_(n),r_(i,r);let a=c.reveal===`emerge`;a?e.dataset.personaDockReveal=`emerge`:e.removeAttribute(`data-persona-dock-reveal`);let s=o?c.width:`0px`,l=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?`, padding 180ms ease`:``}`:`none`,f=!o;if(r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 ${s}`,r.style.width=s,r.style.maxWidth=s,r.style.minWidth=s,r.style.minHeight=`0`,Yg(r,c.maxHeight),r.style.overflow=a||f?`hidden`:`visible`,r.style.transition=l,a){r.style.alignItems=c.side===`right`?`flex-start`:`flex-end`;let t=u?`calc(${qg(c.width,e.clientWidth)}px - (2 * ${d}))`:c.width;i.style.width=t,i.style.minWidth=t,i.style.maxWidth=t,i.style.boxSizing=`border-box`}}},l_=(e,t)=>{let n=e.ownerDocument.createElement(`div`);return Zg(n,t),e.appendChild(n),{mode:`direct`,host:n,shell:null,syncWidgetState:()=>{},updateConfig(e){Zg(n,e)},destroy(){n.remove()}}},u_=(e,t)=>{let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw Error(`Docked widget target must be attached to the DOM`);let i=e.tagName.toUpperCase();if(i===`BODY`||i===`HTML`)throw Error(`Docked widget target must be a concrete container element, not "body" or "html"`);let a=e.nextSibling,o=n.createElement(`div`),s=n.createElement(`div`),c=n.createElement(`div`),l=n.createElement(`aside`),u=n.createElement(`div`),d=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;s.dataset.personaDockRole=`push-track`,c.dataset.personaDockRole=`content`,l.dataset.personaDockRole=`panel`,u.dataset.personaDockRole=`host`,l.appendChild(u),r.insertBefore(o,e),c.appendChild(e);let f=null,p=()=>{f?.disconnect(),f=null},m=null,h=()=>{m=t?.launcher?.detachedPanel===!0?o_(t):null};h();let g=()=>{c_(o,s,c,l,u,t,d,m)},_=null,v=()=>{_?.(),_=null,t?.launcher?.detachedPanel===!0&&t?.colorScheme===`auto`&&(_=yd(()=>{h(),g()}))},y=()=>{p(),Tf(t).reveal===`push`&&typeof ResizeObserver<`u`&&(f=new ResizeObserver(()=>{g()}),f.observe(o))},b=!1,x=()=>{g(),y(),d&&!b&&o.dataset.personaDockMobileFullscreen!==`true`&&(b=!0,Xg(o,Tf(t)))},S=o.ownerDocument.defaultView,C=()=>{x()};return S?.addEventListener(`resize`,C),Tf(t).reveal===`push`?(s.appendChild(c),s.appendChild(l),o.appendChild(s)):(o.appendChild(c),o.appendChild(l)),x(),v(),{mode:`docked`,host:u,shell:o,syncWidgetState(e){let t=!e.launcherEnabled||e.open;d!==t&&(d=t,x())},updateConfig(e){t=e,(t?.launcher?.enabled??!0)===!1&&(d=!0),h(),x(),v()},destroy(){S?.removeEventListener(`resize`,C),_?.(),_=null,p(),r.isConnected&&(a&&a.parentNode===r?r.insertBefore(e,a):r.appendChild(e)),o.remove()}}},d_=(e,t)=>Cf(t)?u_(e,t):l_(e,t),f_=e=>{if(typeof window>`u`||typeof document>`u`)throw Error(`Chat widget can only be mounted in a browser environment`);if(typeof e==`string`){let t=document.querySelector(e);if(!t)throw Error(`Chat widget target "${e}" was not found`);return t}return e},p_=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector(`link[data-persona]`))return;let n=t.head.querySelector(`link[data-persona]`);if(!n)return;let r=n.cloneNode(!0);e.insertBefore(r,e.firstChild)},m_=[],h_=()=>[...m_],g_=e=>{let t=f_(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,i=e.config,a=d_(t,i),o,s=[],c=(e,i)=>{let a=!(i?.launcher?.enabled??!0)||Cf(i),o=r.createElement(`div`);if(o.setAttribute(`data-persona-root`,`true`),a&&(o.style.height=`100%`,o.style.display=`flex`,o.style.flexDirection=`column`,o.style.flex=`1`,o.style.minHeight=`0`,o.style.minWidth=`0`),n){let t=e.attachShadow({mode:`open`});t.appendChild(o),p_(t,r)}else e.appendChild(o),p_(e,r);return t.id&&o.setAttribute(`data-persona-instance`,t.id),o},l=()=>{a.syncWidgetState(o.getState())},u=()=>{s.forEach(e=>e()),s=[o.on(`widget:opened`,l),o.on(`widget:closed`,l)],l()},d=()=>{let t=c(a.host,i);o=Kg(t,i,{debugTools:e.debugTools}),u()},f=()=>{s.forEach(e=>e()),s=[],o.destroy()};d(),e.onChatReady?.();let p=e=>{f(),a.destroy(),a=d_(t,e),i=e,d()},m=new Proxy({update(e){let t=$h(i??{},e),n=Cf(i),r=Cf(t),s=wf(i),c=wf(t);n!==r||s!==c?p(t):(i=t,a.updateConfig(i),o.update(e),l())},destroy(){f(),a.destroy();let t=m_.indexOf(m);t!==-1&&m_.splice(t,1),e.windowKey&&typeof window<`u`&&delete window[e.windowKey]}},{get(e,t,n){if(t===`host`)return a.host;if(t in e)return Reflect.get(e,t,n);let r=o[t];return typeof r==`function`?r.bind(o):r}});return m_.push(m),e.windowKey&&typeof window<`u`&&(window[e.windowKey]=m),m},__=/* @__PURE__ */ new Set([`script`,`style`,`noscript`,`svg`,`path`,`meta`,`link`,`br`,`hr`]),v_=/* @__PURE__ */ new Set([`button`,`a`,`input`,`select`,`textarea`,`details`,`summary`]),y_=/* @__PURE__ */ new Set([`button`,`link`,`menuitem`,`tab`,`option`,`switch`,`checkbox`,`radio`,`combobox`,`listbox`,`slider`,`spinbutton`,`textbox`]),b_=/\b(product|card|item|listing|result)\b/i,x_=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i;function S_(e){let t=typeof e.className==`string`?e.className:``;if(b_.test(t)||e.id&&b_.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith(`data-`)&&b_.test(n.value))return!0}return!1}function C_(e){return x_.test((e.textContent??``).trim())}function w_(e){let t=e.querySelectorAll(`a[href]`);for(let e=0;e<t.length;e++){let n=t[e].getAttribute(`href`)??``;if(n&&n!==`#`&&!n.toLowerCase().startsWith(`javascript:`))return!0}return!1}function T_(e){return!!e.querySelector(`button, [role="button"], input[type="submit"], input[type="button"]`)}function E_(e){let t=e.match(x_);return t?t[0]:null}function D_(e){let t=e.querySelector(`.product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]`)??e.querySelector(`a[href]`);if(t&&t.textContent?.trim()){let e=t.getAttribute(`href`);return{title:t.textContent.trim(),href:e&&e!==`#`?e:null}}let n=e.querySelector(`h1, h2, h3, h4, h5, h6`);return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:``,href:null}}function O_(e){let t=[],n=e=>{let n=e.trim();n&&!t.includes(n)&&t.push(n)};return e.querySelectorAll(`button`).forEach(e=>n(e.textContent??``)),e.querySelectorAll(`[role="button"]`).forEach(e=>n(e.textContent??``)),e.querySelectorAll(`input[type="submit"], input[type="button"]`).forEach(e=>{n(e.value??``)}),t.slice(0,6)}function k_(e){return!S_(e)||!C_(e)||!w_(e)&&!T_(e)?0:5200}function A_(e){return!S_(e)||C_(e)||!w_(e)||(e.textContent??``).trim().length<20||!(e.querySelector(`h1, h2, h3, h4, h5, h6, .title`)||e.querySelector(`.snippet, .description, p`))?0:2800}const j_=[{id:`commerce-card`,scoreElement(e){return k_(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity===`static`){let e=n.text.trim();return!!(e.length===0||x_.test(e)&&e.length<32)}return!0},formatSummary(e,t){if(k_(e)===0)return null;let{title:n,href:r}=D_(e),i=E_((e.textContent??``).trim())??E_(t.text)??``,a=O_(e);return[r&&n?`[${n}](${r})${i?`: ${i}`:``}`:n?`${n}${i?`: ${i}`:``}`:i||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(`, `)}`:``].filter(Boolean).join(`
135
- `)}},{id:`result-card`,scoreElement(e){return A_(e)},formatSummary(e,t){if(A_(e)===0)return null;let{title:n,href:r}=D_(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
136
- `)}}];function M_(){typeof console<`u`&&typeof console.warn==`function`&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function N_(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,r=t.excludeSelector??e.excludeSelector??`.persona-host`,i=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,o=t.root??e.root,s=t.mode??`structured`,c=t.maxCandidates??Math.max(500,n*10),l=e.rules??j_;return s===`simple`&&e.rules&&e.rules.length>0?(M_(),l=[]):s===`simple`&&(l=[]),{mode:s,maxElements:n,maxCandidates:c,excludeSelector:r,maxTextLength:i,visibleOnly:a,root:o,rules:l}}function P_(e){return typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/([^\w-])/g,`\\$1`)}const F_=[`data-testid`,`data-product`,`data-action`,`data-id`,`data-name`,`data-type`];function I_(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`||v_.has(t)||n&&y_.has(n)||e.hasAttribute(`tabindex`)||e.hasAttribute(`onclick`)||e.getAttribute(`contenteditable`)===`true`?`clickable`:`static`}function L_(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 R_(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute(`href`);r&&(t.href=r);let i=e.getAttribute(`aria-label`);i&&(t[`aria-label`]=i);let a=e.getAttribute(`type`);a&&(t.type=a);let o=e.getAttribute(`value`);o&&(t.value=o);let s=e.getAttribute(`name`);s&&(t.name=s);let c=e.getAttribute(`role`);c&&(t.role=c);for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];r.name.startsWith(`data-`)&&(t[r.name]=r.value)}return t}function z_(e){let t=e.tagName.toLowerCase();if(e.id){let t=`#${P_(e.id)}`;try{if(e.ownerDocument.querySelectorAll(t).length===1)return t}catch{}}for(let n of F_){let r=e.getAttribute(n);if(r){let i=`${t}[${n}="${P_(r)}"]`;try{if(e.ownerDocument.querySelectorAll(i).length===1)return i}catch{}}}let n=Array.from(e.classList).filter(e=>e&&!e.startsWith(`persona-`)).slice(0,3);if(n.length>0){let r=`${t}.${n.map(e=>P_(e)).join(`.`)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let i=e.parentElement;if(i){let n=Array.from(i.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(n>=0){let t=`${r}:nth-of-type(${n+1})`;try{if(e.ownerDocument.querySelectorAll(t).length===1)return t}catch{}}}}let r=e.parentElement;if(r){let n=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(n>=0)return`${t}:nth-of-type(${n+1})`}return t}function B_(e){return e===`static`?100:3e3}function V_(e,t){let n=e.tagName.toLowerCase(),r=(e.textContent??``).trim().substring(0,t);return{selector:z_(e),tagName:n,text:r,role:e.getAttribute(`role`),interactivity:I_(e),attributes:R_(e)}}function H_(e,t,n,r){let i=B_(t.interactivity),a=null;for(let o of n){let n=o.scoreElement(e,t,r);n>0&&(i+=n,o.formatSummary&&!a&&(a=o))}return{score:i,formattingRule:a}}function U_(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 W_(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=/* @__PURE__ */ new Set,i=[],a=0,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&i.length<e.maxCandidates;){if(s.nodeType===Node.ELEMENT_NODE){let t=s,c=t.tagName.toLowerCase();if(__.has(c)){s=o.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!L_(t)){s=o.nextNode();continue}let l=V_(t,e.maxTextLength),u=l.text.length>0,d=Object.keys(l.attributes).length>0&&!Object.keys(l.attributes).every(e=>e===`role`);if(!u&&!d||r.has(l.selector)){s=o.nextNode();continue}r.add(l.selector);let{score:f,formattingRule:p}=H_(t,l,e.rules,n);i.push({el:t,domIndex:a,enriched:l,score:f,formattingRule:p}),a+=1}s=o.nextNode()}i.sort((e,t)=>{let n=+(e.enriched.interactivity===`static`),r=+(t.enriched.interactivity===`static`);return n===r?t.score===e.score?e.domIndex-t.domIndex:t.score-e.score:n-r});let c=[];for(let t of i){if(c.length>=e.maxElements)break;U_(c,t)||c.push(t)}return c.sort((e,t)=>{let n=+(e.enriched.interactivity===`static`),r=+(t.enriched.interactivity===`static`);return n===r?n===1&&t.score!==e.score?t.score-e.score:e.domIndex-t.domIndex:n-r}),c.map(e=>{let t;if(e.formattingRule?.formatSummary){let r=e.formattingRule.formatSummary(e.el,e.enriched,n);r&&(t=r)}let r={...e.enriched};return t&&(r.formattedSummary=t),r})}function G_(e,t){let n=[],r=/* @__PURE__ */ new Set,i=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=i.currentNode;for(;a&&n.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let t=a,o=t.tagName.toLowerCase();if(__.has(o)){a=i.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){a=i.nextNode();continue}}catch{}if(e.visibleOnly&&!L_(t)){a=i.nextNode();continue}let s=V_(t,e.maxTextLength),c=s.text.length>0,l=Object.keys(s.attributes).length>0&&!Object.keys(s.attributes).every(e=>e===`role`);if(!c&&!l){a=i.nextNode();continue}r.has(s.selector)||(r.add(s.selector),n.push(s))}a=i.nextNode()}let o=[],s=[];for(let e of n)e.interactivity===`static`?s.push(e):o.push(e);return[...o,...s].slice(0,e.maxElements)}function K_(e={}){let t=N_(e),n=t.root??document.body;return n?t.mode===`simple`?G_(t,n):W_(t,n):[]}function q_(e,t={}){if(e.length===0)return`No page elements found.`;let n=t.mode??`structured`,r=[];if(n===`structured`){let t=e.map(e=>e.formattedSummary).filter(e=>!!e&&e.length>0);t.length>0&&r.push(`Structured summaries:\n${t.map(e=>`- ${e.split(`
133
+ ${oe?`background: transparent !important;`:``}
134
+ `)}if(!o&&!n){let e=i?``:`padding-top: 1.25em !important;`,t=i?``:`z-index: ${r.launcher?.zIndex??1e5} !important;`;at.style.cssText+=`max-height: -moz-available !important; max-height: stretch !important;`+e+t}hn(),pe()},vi=()=>{e.style.setProperty(`--persona-content-max-width`,Ed(r,I()))},yi=!1;function bi(){r.layout?.topFade&&W.scrollTop>1?W.setAttribute(`data-persona-top-fade`,`true`):W.removeAttribute(`data-persona-top-fade`)}let xi=()=>{bi();let t=Dd(r,I());I()&&r.composer?.placement&&r.debug===!0&&!yi&&(yi=!0,console.warn(`[persona] composer.placement is ignored in composer-bar mount mode.`));let n=un();e.setAttribute(`data-persona-composer-placement`,t),e.setAttribute(`data-persona-conversation-state`,dn),e.setAttribute(`data-persona-welcome-anchor`,n.anchor??`bottom`),e.style.setProperty(`--persona-composer-anchor-gap`,n.composerGap??`24px`),gn()},Si=()=>{if(I())return;let t=kf(r),n=r.launcher?.sidebarMode??!1;if(t||n||(r.launcher?.fullHeight??!1)||!he)return;let i=e.ownerDocument.defaultView??window,a=r.launcher?.mobileFullscreen??!0,o=r.launcher?.mobileBreakpoint??640;if(a&&i.innerWidth<=o)return;let s=sm(r);H.style.height=s.height,H.style.maxHeight=s.maxHeight};_i(),wd(e,r),_h(e,r),vh(e,r),vi(),xi(),Mr=()=>{_i(),Si(),wd(e,r),_h(e,r),vh(e,r),vi(),xi(),Pr?e.style.setProperty(`--persona-artifact-welded-outer-radius`,Pr):e.style.removeProperty(`--persona-artifact-welded-outer-radius`),Qe(),Ze()};let Z=[];Z.push(()=>{Ar=!0}),Z.push(()=>{p.forEach(e=>e()),d.destroy()}),Z.push(()=>{document.removeEventListener(`keydown`,$r)}),Z.push(()=>{an!==null&&clearTimeout(an)});let Ci=null,wi=null;Z.push(()=>{Ci?.(),Ci=null,wi?.(),wi=null}),jr&&Z.push(()=>{jr?.disconnect(),jr=null}),Z.push(()=>{ni?.(),ni=null,li(),ti&&=(ti.remove(),null),kr?.element.style.removeProperty(`width`),kr?.element.style.removeProperty(`maxWidth`),kr?.destroy()}),Oe&&Z.push(()=>{Ve=!0,Be=null,We!==null&&(cancelAnimationFrame(We),We=null),He?.destroy(),He=null,Le?.destroy(),Le=null,Pe=null});let Ti=null,Ei=()=>{Ti&&=(Ti(),null),r.colorScheme===`auto`&&(Ti=Td(()=>{wd(e,r)}))};Ei(),Z.push(()=>{Ti&&=(Ti(),null)}),Z.push(()=>{y=!0,v?.()}),Z.push(()=>{C=!0});let Di=!1;Z.push(()=>{Di=!0});let Oi=(t,n)=>{let r=rf(t,n);return r||!$d.includes(t)?r:(Cf().then(r=>{if(Di)return;ef(r.wipe),ef(r.glyphCycle);let i=rf(t,n);i&&bf(i,e)}).catch(()=>{}),null)},ki=r.features?.streamAnimation;if(ki?.type&&ki.type!==`none`){let t=Oi(ki.type,ki.plugins);t&&bf(t,e),Z.push(()=>yf(e))}let ji=Rf(ut),Mi=Rf(ct),Ni=Rf(lt),Pi=[ji,Mi,Ni];Z.push(()=>{Pi.forEach(e=>e.destroy())});let Fi=null,Q,Ii=null,Li=!1,Ri=0,zi=null,Bi=e=>e.reduce((e,t)=>t.role===`user`?e+1:e,0),Vi=e=>{for(let t=e.length-1;t>=0;t--)if(Zt(e[t]))return e[t].id??null;return null},Hi=!1,Wi=()=>{Hi||r.debug!==!0||(Hi=!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".`))},Gi=!1,Yi=!1,Zi=(e,t)=>{Gi||r.debug!==!0||t.enabled&&!t.expose&&(Li||Yi&&(Q.isStreaming()||e.some(Zt)||(Gi=!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.`))))},ta=e=>{if(!Q)return;let t=e??Q.getMessages(),n=e=>{e.render([],Q,K,t)},i=e=>{Pi.forEach(t=>{t!==e&&n(t)})};Ii&&(Bi(t)>Ri||Vi(t)!==zi)&&(Ii=null);let a=nn(r);Zi(t,a);let o=a.enabled?$t(t):null,s=Ii??o,c=Ii?`host`:`agent`;if(s){let e=r.suggestions?.followUps,n=e?.placement??(e?`auto`:`composer`),a=(n===`auto`?I()?`composer`:`after-message`:n)===`after-message`?Ni:ji;i(a),a.render(s,Q,K,t,r.suggestionChipsConfig,{source:c,surface:`followUp`,variant:e?.variant??`chip`,behavior:e?.behavior??`send`,overflow:e?.overflow??`wrap`,maxItems:e?.maxItems??4,config:r,plugins:u,submitPrompt:Nl});return}if(t.some(e=>e.role===`user`)){Pi.forEach(n);return}let l=r.future?.v5Defaults===!0,d=cn(),f=r.suggestions?.starters??(l?{}:void 0);if(f){let e=am(un(),t),a=f.placement??`auto`,o=a===`auto`?e?`welcome`:`composer`:a;if(o===`welcome`&&!e){Wi(),Pi.forEach(n);return}let s=o===`welcome`?Mi:ji;i(s),s.render(f.items??r.suggestionChips,Q,K,t,r.suggestionChipsConfig,{surface:`starter`,variant:f.variant??(l&&!d?`chip`:`card`),behavior:f.behavior??`send`,overflow:f.overflow??`wrap`,maxItems:f.maxItems??(l&&!d?3:4),config:r,plugins:u,submitPrompt:Nl})}else i(ji),ji.render(r.suggestionChips,Q,K,t,r.suggestionChipsConfig,{surface:`starter`,variant:`chip`,behavior:`send`,overflow:`wrap`,maxItems:4,config:r,plugins:u,submitPrompt:Nl})},ia=()=>{Ii&&(Ii=null,ta())},aa=e=>{let t=Array.isArray(e)?[...e]:[];if(!t.length){ia();return}let n=Q?Q.getMessages():[];Ii=t,Li=!0,Ri=Bi(n),zi=Vi(n),ta(n)},sa=!1,la=Fd(),ua=/* @__PURE__ */ new Map,da=/* @__PURE__ */ new Map,fa=/* @__PURE__ */ new Map,ma=null,ha=null;function ga(){if(!ma)return;let e=ma;ma=null,ha?.destroy(),ha=null,la.delete(e),U.querySelector(`#wrapper-${e}`)?.removeAttribute(`data-preserve-runtime`),Q&&$o(G,Q.getMessages(),Te)}let va=0,ya=O()!==null,ba=Bd(),Sa=0,Ca=null,wa=!1,Ta=!1,Ea=0,Da=null,Oa=null,ka=!1,Aa=!1,ja=null,Ma=!0,Na=!1,Fa=null,La=!1,Ra=()=>{La=!0,Ha()},za=null,Ba=null,Va=()=>{e.setAttribute(`data-persona-scrollbar`,Jt()),Jt()!==`on-scroll`&&(Ba!==null&&clearTimeout(Ba),Ba=null,W.removeAttribute(`data-persona-scrollbar-visible`))},Ha=()=>{Jt()===`on-scroll`&&(W.setAttribute(`data-persona-scrollbar-visible`,``),Ba!==null&&clearTimeout(Ba),Ba=setTimeout(()=>{Ba=null,Hd(W,24)&&W.removeAttribute(`data-persona-scrollbar-visible`)},1e3))};Va(),Z.push(()=>{Ba!==null&&clearTimeout(Ba)});let Ua=/* @__PURE__ */ new Map,Wa=!1,Ga=null,$={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};hr();let Ka=r.voiceRecognition?.autoResume??!1,qa=()=>Q.isVoiceActive()||Q.isBargeInActive(),Ja=!1,Ya=e=>{A.emit(`voice:state`,{active:$.active,source:e,timestamp:Date.now()})},Xa=()=>{de(e=>({...e,voiceState:{active:$.active,timestamp:Date.now(),manuallyDeactivated:$.manuallyDeactivated}}))},Za=()=>{if(r.voiceRecognition?.enabled===!1)return;let e=qg(re.voiceState),t=!!e.active,n=Number(e.timestamp??0);$.manuallyDeactivated=!!e.manuallyDeactivated,t&&Date.now()-n<3e4&&setTimeout(()=>{$.active||($.manuallyDeactivated=!1,xs(r.voiceRecognition?.provider)?Q.toggleVoice().then(()=>{$.active=qa(),Ya(`restore`),$.active?Vu():(Xa(),bl(`Tap the mic to resume your voice call`,1e4))}):Lu(`restore`))},xs(r.voiceRecognition?.provider)?0:1e3)},Qa=e=>{Ja=!e.persisted,$.active&&Xa()};typeof window<`u`&&(window.addEventListener(`pagehide`,Qa),Z.push(()=>window.removeEventListener(`pagehide`,Qa)));let $a=()=>Q?Jg(Q.getMessages()).filter(e=>!e.__skipPersist):[],eo=null,to=(e,t)=>{typeof console<`u`&&console.error(e,t)},no=(e,t)=>{let n=()=>{try{let n=e();return!n||typeof n.then!=`function`?null:Promise.resolve(n).catch(e=>{to(t,e)})}catch(e){return to(t,e),null}},r=eo,i=r?r.then(()=>n()??void 0):n();if(!i)return;let a=i.finally(()=>{eo===a&&(eo=null)});eo=a};function ro(e){if(!te?.save)return;let t=e?Jg(e):Q?$a():[],n=ne&&Q?.getResumableHandle();n&&(re={...re,durableResume:{executionId:n.executionId,after:n.lastEventId}});let r={messages:t,metadata:re,artifacts:Fr.artifacts,selectedArtifactId:Fr.selectedId,...io?{draft:io}:{}};no(()=>te.save(r),`[AgentWidget] Failed to persist state:`)}let io,ao=()=>!te?.save||r.persistState===!1?!1:typeof r.persistState!=`object`||r.persistState.persist?.draft!==!1,oo=yu({write:()=>{if(!ao())return;let e=X.getState(),t=_u({text:e.text,mentionRefs:e.mentionRefs,contentSegments:pl(),selectedModelId:e.selectedModelId,activeModeIds:e.activeModeIds,quote:e.quote});JSON.stringify(t)!==JSON.stringify(io)&&(io=t,ro())}});function so(){ao()&&oo.schedule()}function co(){oo.flush()}function lo(e){if(!ao())return;let t=vu(e,{mentionSourceIds:(r.contextMentions?.sources??[]).map(e=>e.id),modelIds:(r.composer?.models??[]).map(e=>e.id),modes:r.composer?.modes??[]});t&&(io=e,K&&!K.value&&(K.value=t.text,K.dispatchEvent(new Event(`input`,{bubbles:!0})),bn()),t.selectedModelId&&(X.setSelectedModelId(t.selectedModelId),An?.repaint()),On(t.activeModeIds??[]),t.quote&&Fn(t.quote),oo.cancel())}function uo(){oo.cancel(),io&&(io=void 0,ao()&&ro())}let fo=null,po=()=>at.querySelector(`#persona-scroll-container`)||W,mo=()=>{fo!==null&&(cancelAnimationFrame(fo),fo=null),wa=!1},ho=()=>{Ca!==null&&(cancelAnimationFrame(Ca),Ca=null),Ta=!1,mo()},go=()=>sa&&bo()&&(zt()!==`anchor-top`||Kt()),_o=()=>{let e=It()||`Jump to latest`,t=go();Yt.toggleAttribute(`data-persona-scroll-to-bottom-streaming`,t),Ea>0?(en.textContent=String(Ea),en.style.display=``,Yt.setAttribute(`aria-label`,`${e} (${Ea} new)`)):(en.textContent=``,en.style.display=`none`,Yt.setAttribute(`aria-label`,t?`${e} (response streaming below)`:e))},vo=()=>{Ea!==0&&(Ea=0,_o())},yo=()=>{let e=Da?.spacerHeight??0;return e<=0?Hd(W,24):Fo(e)-W.scrollTop-W.clientHeight<=24},bo=()=>Bt()?!ba.isFollowing():!yo(),xo=()=>!!Q&&Q.getMessages().length>0,So=()=>{if(!Rt()||et()){Yt.parentNode&&Yt.remove(),Yt.style.display=`none`;return}Yt.parentNode!==U&&U.appendChild(Yt),mn();let e=Vd(W)>0&&bo()&&xo();e?_o():vo(),Yt.style.display=e?``:`none`},Co=()=>{ba.pause()&&(ho(),So())},wo=()=>{ba.resume(),vo(),So()},To=(e=!1)=>{Bt()&&xo()&&ba.isFollowing()&&(e||sa)&&(Ca!==null&&(cancelAnimationFrame(Ca),Ca=null),Ta=!0,Ca=requestAnimationFrame(()=>{Ca=null,Ta=!1,ba.isFollowing()&&Do(po(),e?220:140)}))},Eo=(e,t,n,r=()=>!0)=>{let i=e.scrollTop,a=t(),o=a-i;if(mo(),Math.abs(o)<1){wa=!0,e.scrollTop=a,Sa=e.scrollTop,wa=!1;return}let s=performance.now();wa=!0;let c=e=>1-(1-e)**3,l=u=>{if(!r()){mo();return}let d=t();d!==a&&(a=d,o=a-i);let f=u-s,p=Math.min(f/n,1),m=c(p);e.scrollTop=i+o*m,Sa=e.scrollTop,p<1?fo=requestAnimationFrame(l):(e.scrollTop=a,Sa=e.scrollTop,fo=null,wa=!1)};fo=requestAnimationFrame(l)},Do=(e,t=500)=>{let n=Vd(e)-e.scrollTop;Math.abs(n)<1?Sa=e.scrollTop:Math.abs(n)>=80?(mo(),wa=!0,e.scrollTop=Vd(e),Sa=e.scrollTop,wa=!1):Eo(e,()=>Vd(e),t,()=>ba.isFollowing())},Oo=()=>{if(!xo()){So();return}let e=po();wa=!0,e.scrollTop=Vd(e),Sa=e.scrollTop,wa=!1,So()},Ao=e=>{let t=0,n=e;for(;n&&n!==W;)t+=n.offsetTop,n=n.offsetParent;return t},jo=()=>{let e=W.getRootNode();return(typeof e.getSelection==`function`?e.getSelection():null)??W.ownerDocument.getSelection()},Mo=()=>Gd(jo(),W),No=()=>{if(Wt()!==`last-user-turn`)return!1;let e=Q?.getMessages()??[];if(e.length<2)return!1;let t=[...e].reverse().find(e=>e.role===`user`);if(!t)return!1;let n=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(t.id):t.id.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),r=W.querySelector(`[data-message-id="${n}"]`);if(!r)return!1;let i=Math.min(Math.max(0,Ao(r)-Ut()),Vd(W));return wa=!0,W.scrollTop=i,Sa=W.scrollTop,wa=!1,zt()===`follow`&&!Hd(W,24)&&ba.pause(),So(),!0},Po=e=>{let t=Math.max(0,Math.round(e));tn.style.height=`${t}px`,tn.style.display=t>0?``:`none`,Da&&(Da.spacerHeight=Math.max(0,e))},Fo=e=>{let t=parseFloat(getComputedStyle(W).paddingBottom)||0,n=0;for(let e of Array.from(W.children)){if(e===tn||e.offsetHeight===0)continue;let t=Ao(e)+e.offsetHeight;t>n&&(n=t)}let r=W.scrollHeight-e;return n>0?Math.min(n+t,r):r},Io=()=>{if(!Da||Da.spacerHeight<=0)return;let e=Fo(Da.spacerHeight),t=Math.max(0,Math.round(W.scrollTop)+W.clientHeight-e+24);t<Da.spacerHeight&&(Po(t),So())},Lo=()=>{Oa!==null&&(cancelAnimationFrame(Oa),Oa=null),mo(),Da=null,tn.style.height=`0px`,tn.style.display=`none`},Ro=e=>typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`),zo=e=>W.querySelector(`[data-message-id="${Ro(e)}"]`),Bo=e=>{Oa!==null&&cancelAnimationFrame(Oa),Oa=requestAnimationFrame(()=>{Oa=null;let t=Ro(e),n=W.querySelector(`[data-message-id="${t}"]`);if(!n)return;let r=Ao(n),i=Da?.spacerHeight??0,a=Fo(i),{targetScrollTop:o,spacerHeight:s}=Kd({anchorOffsetTop:r,topOffset:Ut(),viewportHeight:W.clientHeight,contentHeight:a,slack:24});Da={initialSpacerHeight:s,contentHeightAtAnchor:a,spacerHeight:s},Po(s),Eo(W,()=>n.isConnected?Math.max(0,Ao(n)-Ut()):o,220)})},Vo=()=>{if(zt()!==`anchor-top`||!Da||!Fa)return;let e=zo(Fa);if(!e)return;mo();let t=Da.spacerHeight,n=Fo(t),{targetScrollTop:r,spacerHeight:i}=Kd({anchorOffsetTop:Ao(e),topOffset:Ut(),viewportHeight:W.clientHeight,contentHeight:n,slack:24});Da={initialSpacerHeight:i,contentHeightAtAnchor:n,spacerHeight:i},Po(i),wa=!0,W.scrollTop=r,Sa=W.scrollTop,wa=!1,So()},Ho=()=>{if(Bt()){if(!ba.isFollowing()||Hd(W,1))return;To(!sa)}else{if(Da&&Da.initialSpacerHeight>0){let e=W.scrollHeight-Da.spacerHeight,t=qd({initialSpacerHeight:Da.initialSpacerHeight,contentHeightAtAnchor:Da.contentHeightAtAnchor,currentContentHeight:e});t!==Da.spacerHeight&&Po(t)}So()}},Uo=e=>{let t=zt();t===`follow`?(wo(),To(!0)):t===`anchor-top`&&(Ma=!1,Na=!0,La=!1,Fa=e,Bo(e))},Wo=()=>{zt()===`anchor-top`&&(Na?Ma=!1:(Ma=!0,Lo(),wo(),To(!0)))},Go=e=>{if(ja===null)return!0;let t=zo(ja),n=zo(e);if(!t||!n)return!0;let r=Ao(n)-Ao(t);return Ut()+r>W.clientHeight-96},Ko=e=>{if(zt()!==`anchor-top`||!Na||La||Mo())return;let t=ja===null;for(let n of e)if(!t)n.id===ja&&(t=!0);else if(zd(n)){if(n.id===Fa||!Go(n.id))return;Fa=n.id,Bo(n.id);return}},qo=e=>{let t=/* @__PURE__ */ new Map;e.forEach(e=>{let n=Ua.get(e.id);t.set(e.id,{streaming:e.streaming,role:e.role}),!n&&e.role===`assistant`&&(A.emit(`assistant:message`,e),!Aa&&(zt()!==`anchor-top`||Kt())&&bo()&&(Ea+=1,_o(),So(),sn(Ea===1?`1 new message below.`:`${Ea} new messages below.`))),e.role===`assistant`&&n?.streaming&&e.streaming===!1&&A.emit(`assistant:complete`,e),e.variant===`approval`&&e.approval&&(n?e.approval.status!==`pending`&&A.emit(`approval:resolved`,{approval:e.approval,decision:e.approval.status}):A.emit(`approval:requested`,{approval:e.approval,message:e}))}),Ua.clear(),t.forEach((e,t)=>{Ua.set(t,e)})},Jo=(e,t)=>{let n=t===`user`?`user`:`assistant`,i=r.layout?.messages?.[n],a=i?.width??`content`,o=i?.maxWidth??(a===`full`?`var(--persona-message-${n}-max-width, 100%)`:void 0);e.classList.add(`persona-message-row`),e.classList.remove(`persona-message-row-user`,`persona-message-row-assistant`,`persona-message-row-system`,`persona-message-width-content`,`persona-message-width-full`),e.classList.add(`persona-message-row-${t}`,`persona-message-width-${a}`),e.classList.toggle(`persona-justify-end`,t===`user`),e.setAttribute(`data-message-role`,t),e.setAttribute(`data-message-width`,a),o?e.style.setProperty(`--persona-message-row-max-width`,o):e.style.removeProperty(`--persona-message-row-max-width`)},Yo=(e,t)=>{let n=document.createElement(`div`);return n.className=`persona-flex`,n.id=`wrapper-${e}`,n.setAttribute(`data-wrapper-id`,e),Jo(n,t),n},Xo=(e,t,n)=>{let c=/* @__PURE__ */ new Set;for(let e of t){let t=e.variant===`tool`?`tool`:e.variant===`reasoning`?`reasoning`:null;if(!t||hs(r,t)!==`row`)continue;let n=t===`tool`?r.features?.toolCallDisplay:r.features?.reasoningDisplay;n?.expandable!==!1&&(c.add(e.id),o.observe(e,t,t===`tool`?i:a,n))}let l=document.createElement(`div`),d=(()=>{let e=u.find(e=>e.renderLoadingIndicator);if(e?.renderLoadingIndicator)return e.renderLoadingIndicator;if(r.loadingIndicator?.render)return r.loadingIndicator.render})(),f=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),p=/* @__PURE__ */ new Set,m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Set,g=u.some(e=>e.renderAskUserQuestion),v=[],y=[],b=r.enableComponentStreaming!==!1,x=r.approval!==!1,C=[],w=r.messageActions,T=w?.showRegenerate===!0&&w.enabled!==!1&&Gr.current?.isStreaming()!==!0?Ac(t):null,E=w?.showEdit===!0&&w.enabled!==!1,D=w?.showQuote===!0&&w.enabled!==!1,O=null,k=r.features?.reasoningDisplay?.completedVisibility,A=e=>k===`removed`||k===`removed-when-short`&&Ie(e,r.features?.reasoningDisplay?.shortThinkThreshold),te=r.features?.toolCallDisplay?.completedVisibility===`removed`,ne=e=>e.variant===`reasoning`&&e.reasoning?.status===`complete`?A(e.reasoning):te&&e.variant===`tool`&&e.toolCall?.status===`complete`&&!e.toolCall.interrupted;if(t.forEach(t=>{if(ne(t))return;if(p.add(t.id),m.set(t.id,t.role),ma===t.id&&ha){let e=Yo(t.id,t.role);e.setAttribute(`data-persona-message-edit-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),O={messageId:t.id,element:ha.element};return}let o=g&&mt(t),c=x&&t.variant===`approval`&&!!t.approval,f=!o&&t.role===`assistant`&&!t.variant&&b&&Pg(t);!c&&fa.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),fa.delete(t.id)),!f&&da.has(t.id)&&(e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),da.delete(t.id));let w=mt(t)?`:${t.agentMetadata?.askUserQuestionAnswered?`a`:`u`}:${t.agentMetadata?.askUserQuestionAnswers?Object.keys(t.agentMetadata.askUserQuestionAnswers).length:0}`:``,k={canRegenerate:T===t.id,canEdit:E&&jc(t),canQuote:D&&!t.variant&&(t.content?.trim().length??0)>0},A=`${k.canRegenerate?`r`:``}${k.canEdit?`e`:``}${k.canQuote?`q`:``}`,te=Pd(t,va)+w+`:${A}`,re=o||c||f?null:Id(la,t.id,te);if(re){l.appendChild(re.cloneNode(!0)),mt(t)&&t.toolCall?.id&&t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(h.add(t.toolCall.id),Jr(t));return}let ie=null,ae=u.find(e=>!!(t.variant===`reasoning`&&e.renderReasoning||t.variant===`tool`&&e.renderToolCall||!t.variant&&e.renderMessage)),j=r.layout?.messages;if(mt(t)&&t.agentMetadata?.askUserQuestionAnswered===!0){ua.delete(t.id),e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`);return}if(Zt(t)&&nn(r).enabled)return;if(mt(t)&&r.features?.askUserQuestion?.enabled!==!1){let e=u.find(e=>typeof e.renderAskUserQuestion==`function`);if(e&&Gr.current){let n=ua.get(t.id),i=n!==te,a=null;if(i){let{payload:n,complete:i}=gt(t),o=t.id,s=()=>Gr.current?.getMessages().find(e=>e.id===o);a=e.renderAskUserQuestion({message:t,payload:n,complete:i,resolve:e=>{let t=s();t&&Gr.current?.resolveAskUserQuestion(t,e)},dismiss:()=>{let e=s();e?.agentMetadata?.awaitingLocalTool&&(Gr.current?.markAskUserQuestionResolved(e),Gr.current?.resolveAskUserQuestion(e,`(dismissed)`))},config:r})}if(i&&a===null&&n==null){t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(h.add(t.toolCall.id),Jr(t));return}let o=Yo(t.id,t.role);o.setAttribute(`data-ask-plugin-stub`,`true`),o.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(o),v.push({messageId:t.id,fingerprint:te,bubble:a});return}t.agentMetadata?.awaitingLocalTool===!0&&!t.agentMetadata?.askUserQuestionAnswered&&(h.add(t.toolCall.id),Jr(t));return}if(c){let n=S();if(!n){l.appendChild(Yo(t.id,t.role));return}let i=u.find(e=>typeof e.renderApproval==`function`)??_,a=fa.get(t.id)!==te,o=null;if(a&&i?.renderApproval){let e=t.id,a=(t,n)=>{let r=Gr.current?.getMessages().find(t=>t.id===e);r?.approval&&(rs(r.approval)?Gr.current?.resolveWebMcpApproval(r.id,t):Gr.current?.resolveApproval(r.approval,t,n))};o=i.renderApproval({message:t,defaultRenderer:()=>n.createApprovalBubble(t,r,s),config:r,approve:e=>a(`approved`,e),deny:e=>a(`denied`,e)})}if(a&&o===null)e.querySelector(`#wrapper-${t.id}`)?.removeAttribute(`data-preserve-runtime`),fa.delete(t.id),ie=n.createApprovalBubble(t,r,s);else{let e=Yo(t.id,t.role);e.setAttribute(`data-approval-plugin-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),C.push({messageId:t.id,fingerprint:te,bubble:o});return}}else if(ae){if(t.variant===`reasoning`&&t.reasoning&&ae.renderReasoning){if(!Ee)return;ie=ae.renderReasoning({message:t,defaultRenderer:()=>Mm(t,r,a),config:r})}else if(t.variant===`tool`&&t.toolCall&&ae.renderToolCall){if(!De)return;ie=ae.renderToolCall({message:t,defaultRenderer:()=>Um(t,r,i),config:r})}else ae.renderMessage&&(ie=ae.renderMessage({message:t,defaultRenderer:()=>{let e=Rp(t,n,j,r.messageActions,tt,{loadingIndicatorRenderer:d,widgetConfig:r,actionEligibility:k});return t.role!==`user`&&ee(e,t,r,Q),e},config:r}))}if(!ie&&f){let i=Fg(t);if(i){let a=da.get(t.id),o=a!==te,s=r.wrapComponentDirectiveInBubble!==!1&&$m.getOptions(i.component)?.bubbleChrome!==!1,c=null;if(o){let a=jg(i,{config:r,message:t,transform:n});if(a&&i.component===`PersonaArtifactInline`){let n=a.hasAttribute(`data-artifact-inline`)?a:a.querySelector(`[data-artifact-inline]`),r=n?.getAttribute(`data-artifact-inline`)??``,i=typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(r):r,o=r?e.querySelector(`#wrapper-${t.id}`)?.querySelector(`[data-artifact-inline="${i}"]`)??null:null;n&&o&&o!==n&&lh()?.hasLiveInlineArtifactBlock(o)&&(n===a?a=o:n.replaceWith(o))}if(a){if(s){let e=document.createElement(`div`);if(e.className=[`persona-message-bubble`,`persona-rounded-2xl`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-p-4`].join(` `),e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-mb-3 persona-text-sm persona-leading-relaxed`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(a),c=e}else{let e=document.createElement(`div`);if(e.className=`persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch`,e.id=`bubble-${t.id}`,e.setAttribute(`data-message-id`,t.id),e.setAttribute(`data-persona-component-directive`,`true`),t.content&&t.content.trim()){let r=document.createElement(`div`);r.className=`persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full`,r.innerHTML=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),e.appendChild(r)}e.appendChild(a),c=e}}}if(c||a!=null){let e=Yo(t.id,t.role);e.setAttribute(`data-component-directive-stub`,`true`),e.setAttribute(`data-preserve-runtime`,`true`),l.appendChild(e),y.push({messageId:t.id,fingerprint:te,bubble:c});return}}}if(!ie){if(t.variant===`reasoning`&&t.reasoning){if(!Ee)return;ie=Mm(t,r,a)}else if(t.variant===`tool`&&t.toolCall){if(!De)return;ie=Um(t,r,i)}else if(t.variant===`approval`&&t.approval){if(r.approval===!1)return;let e=S();if(!e)return;ie=e.createApprovalBubble(t,r,s)}else{let e=r.layout?.messages;ie=e?.renderUserMessage&&t.role===`user`?e.renderUserMessage({message:t,config:r,streaming:!!t.streaming}):e?.renderAssistantMessage&&t.role===`assistant`?e.renderAssistantMessage({message:t,config:r,streaming:!!t.streaming}):Rp(t,n,e,r.messageActions,tt,{loadingIndicatorRenderer:d,widgetConfig:r,actionEligibility:k}),t.role!==`user`&&ie&&ee(ie,t,r,Q)}}let M=Yo(t.id,t.role);M.appendChild(ie),Ld(la,t.id,te,M),l.appendChild(M)}),st.composerOverlay&&st.composerOverlay.querySelectorAll(`[data-persona-ask-sheet-for]`).forEach(e=>{let t=e.getAttribute(`data-persona-ask-sheet-for`);t&&!h.has(t)&&Ht(st.composerOverlay,t)}),r.features?.toolCallDisplay?.grouped){let e=[],n=[],a=r.features.toolCallDisplay.groupedMode===`summary`;t.forEach(t=>{if(t.variant===`tool`&&t.toolCall&&De){if(te&&t.toolCall.status===`complete`&&!t.toolCall.interrupted)return;n.push(t)}else(t.variant!==`reasoning`||Ee&&(t.reasoning?.status!==`complete`||!A(t.reasoning)))&&((n.length>1||a&&n.length>0)&&e.push(n),n=[])}),(n.length>1||a&&n.length>0)&&e.push(n),e.forEach(e=>{let t=e.map(e=>Array.from(l.children).find(t=>t instanceof HTMLElement&&t.getAttribute(`data-wrapper-id`)===e.id)).filter(e=>!!e);if(t.length<(a?1:2))return;let n=Yo(`tool-group-${e[0].id}`,`assistant`);if(n.setAttribute(`data-persona-tool-group-row`,`true`),r.features?.toolCallDisplay?.groupedMode===`collapsible`){let a=`tool-group-${e[0].id}`,s=e.some(e=>e.toolCall?.status!==`complete`),l={...e[0],id:a,toolCall:{id:a,name:`${e.length} tools`,status:s?`running`:`complete`,chunks:e.flatMap(e=>e.toolCall?.chunks??[]),success:!e.some(e=>e.toolCall?.success===!1),interrupted:!s&&e.some(e=>e.toolCall?.interrupted)}};c.add(a),o.observe(l,`tool`,i,r.features.toolCallDisplay);let u=l.toolCall?.interrupted?`${e.length} tools · Interrupted`:`${s?`Using`:`Used`} ${e.length} tools`,d=r.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall),defaultSummary:u,config:r}),f=ys(l,r,i.has(a),d??u);f.bubble.classList.add(`persona-tool-group`),f.body.dataset.personaToolGroupStack=`true`,t[0].before(n),n.appendChild(f.bubble),t.forEach((e,t)=>{e.style.setProperty(`--persona-message-row-max-width`,`100%`),e.style.setProperty(`--persona-activity-stagger`,`${t*40}ms`),e.classList.add(`persona-activity-group-child`),f.body.appendChild(e)});return}let s=document.createElement(`div`);s.className=`persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2`,s.setAttribute(`data-persona-tool-group`,`true`);let u=document.createElement(`div`);u.className=`persona-tool-group-summary persona-text-xs persona-text-persona-muted`,u.id=`tool-group-summary-${e[0].id}`;let d=`${e.length} ${e.length===1?`tool`:`tools`}`,p=e.some(e=>e.toolCall?.interrupted)?`${d} · Interrupted`:`Called ${d}`,m=r.toolCall?.renderGroupedSummary?.({messages:e,toolCalls:e.map(e=>e.toolCall).filter(e=>!!e),defaultSummary:p,config:r});f(u,m)||(u.textContent=p);let h=document.createElement(`div`);h.className=`persona-tool-group-stack persona-flex persona-flex-col`,h.id=`tool-group-stack-${e[0].id}`,h.setAttribute(`data-persona-tool-group-stack`,`true`),s.appendChild(u),a||s.appendChild(h),n.appendChild(s),t[0].before(n),t.forEach((e,n)=>{if(a){e.remove();return}e.style.setProperty(`--persona-message-row-max-width`,`100%`);let r=document.createElement(`div`);r.className=`persona-tool-group-item persona-relative`,r.setAttribute(`data-persona-tool-group-item`,`true`),n<t.length-1&&r.setAttribute(`data-persona-tool-group-connector`,`true`),r.appendChild(e),h.appendChild(r)})})}o.prune(c),Rd(la,p);let re=e=>e.variant===`tool`&&!De||e.variant===`reasoning`&&!Ee||ne(e),ie=t.some(e=>e.role===`assistant`&&e.streaming&&!re(e)),ae=t.length-1;for(;ae>=0&&re(t[ae]);)ae--;let j=ae>=0?t[ae]:void 0,M=ae<t.length-1,N=j?.role===`assistant`&&!j.streaming&&j.variant!==`approval`&&!M;if(sa&&t.some(e=>e.role===`user`)&&!ie&&!N){let e={config:r,streaming:!0,location:`standalone`,defaultRenderer:Op},t=u.find(e=>e.renderLoadingIndicator),n=null;if(t?.renderLoadingIndicator&&(n=t.renderLoadingIndicator(e)),n===null&&r.loadingIndicator?.render&&(n=r.loadingIndicator.render(e)),n===null&&(n=Op()),n){let e=document.createElement(`div`),t=r.loadingIndicator?.showBubble!==!1,i=r.layout?.messages?.layout??`bubble`;e.className=t?Mp(`assistant`,i).join(` `):[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-text`].join(` `),e.setAttribute(`data-typing-indicator`,`true`),t&&(e.style.color=`var(--persona-message-assistant-text, var(--persona-text))`,i!==`flat`&&(e.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,e.style.borderColor=`var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))`)),e.appendChild(n);let a=Yo(`typing-indicator`,`assistant`);a.appendChild(e),l.appendChild(a)}}if(!sa&&t.length>0){let e=t[t.length-1],n={config:r,lastMessage:e,messageCount:t.length},i=u.find(e=>e.renderIdleIndicator),a=null;if(i?.renderIdleIndicator&&(a=i.renderIdleIndicator(n)),a===null&&r.loadingIndicator?.renderIdle&&(a=r.loadingIndicator.renderIdle(n)),a){let e=document.createElement(`div`);e.className=r.loadingIndicator?.showBubble===!1?[`persona-text-sm`,`persona-leading-relaxed`,`persona-text-persona-primary`].join(` `):[`persona-rounded-2xl`,`persona-text-sm`,`persona-leading-relaxed`,`persona-shadow-sm`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-text-persona-primary`,`persona-px-5`,`persona-py-3`].join(` `),e.setAttribute(`data-idle-indicator`,`true`),e.appendChild(a);let t=Yo(`idle-indicator`,`assistant`);t.appendChild(e),l.appendChild(t)}}if(Js(l),Ad(e,l),Xs(e),O){let{messageId:t,element:n}=O,r=e.querySelector(`#wrapper-${t}`);r&&n.parentElement!==r&&(Jo(r,m.get(t)??`user`),r.replaceChildren(n))}if(v.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of v){let i=e.querySelector(`#wrapper-${t}`);i&&(Jo(i,m.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),ua.set(t,n)))}if(ua.size>0)for(let e of ua.keys())p.has(e)||ua.delete(e);if(y.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of y){let i=e.querySelector(`#wrapper-${t}`);i&&(Jo(i,m.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),da.set(t,n)))}if(da.size>0)for(let e of da.keys())p.has(e)||da.delete(e);if(C.length>0)for(let{messageId:t,fingerprint:n,bubble:r}of C){let i=e.querySelector(`#wrapper-${t}`);i&&(Jo(i,m.get(t)??`assistant`),r!==null&&(i.replaceChildren(r),i.setAttribute(`data-bubble-fp`,n),fa.set(t,n)))}if(fa.size>0)for(let e of fa.keys())p.has(e)||fa.delete(e)},Zo=!1,Qo=()=>{Zo||(Zo=!0,En().catch(()=>{}),T().catch(()=>{Zo=!1}))},$o=(e,t,n)=>{t.length>0&&Qo(),Xo(e,t,n),Dr()},ts=null,is=()=>{if(ts)return;let t=e=>{let t=e.composedPath();t.includes(at)||ot&&t.includes(ot)||_s(!1,`user`)};ts=t,(e.ownerDocument??document).addEventListener(`pointerdown`,t,!0)},as=()=>{ts&&=((e.ownerDocument??document).removeEventListener(`pointerdown`,ts,!0),null)};Z.push(()=>as());let os=null,ss=()=>{if(os)return;let t=e=>{e.key===`Escape`&&(e.isComposing||_s(!1,`user`))};os=t,(e.ownerDocument??document).addEventListener(`keydown`,t,!0)},cs=()=>{os&&=((e.ownerDocument??document).removeEventListener(`keydown`,os,!0),null)};Z.push(()=>cs());let ls=!1,us=/* @__PURE__ */ new Set,ds=()=>r.launcher?.composerBar?.peek?.streamAnimation||r.features?.streamAnimation,fs=()=>{if(!I())return;let t=st.peekBanner,n=st.peekTextNode;if(!t||!n)return;if(R){t.classList.remove(`persona-pill-peek--visible`);return}let r=Q?.getMessages()??[],i;for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.role===`assistant`&&t.content){i=t;break}}if(!i){t.classList.remove(`persona-pill-peek--visible`);return}let a=i.content,o=!!i.streaming,s=ds(),c=Xd(s),l=c.type===`none`?null:Oi(c.type,s?.plugins),u=l?.isAnimating?.(i)===!0,d=l!==null&&(o||u);d&&l&&!us.has(l.name)&&(bf(l,e),us.add(l.name));let f=d&&l?.containerClass?l.containerClass:null,p=n.dataset.personaPeekStreamClass??null;p&&p!==f&&(n.classList.remove(p),delete n.dataset.personaPeekStreamClass),f&&p!==f&&(n.classList.add(f),n.dataset.personaPeekStreamClass=f),d?(n.style.setProperty(`--persona-stream-step`,`${c.speed}ms`),n.style.setProperty(`--persona-stream-duration`,`${c.duration}ms`)):(n.style.removeProperty(`--persona-stream-step`),n.style.removeProperty(`--persona-stream-duration`));let m=d?af(a,c.buffer,l,i,o):a;if(d&&c.placeholder===`skeleton`&&o&&(!m||!m.trim())){let e=document.createElement(`div`),t=mf();t.classList.add(`persona-pill-peek__skeleton`),e.appendChild(t),Ad(n,e)}else{let e=Math.max(0,m.length-100),r=m.length>100?m.slice(-100):m,a=ks(r);if(!d||!l){let e=m.length>100?`…${r}`:r;n.textContent!==e&&(n.textContent=e)}else{let o=a;(l.wrap===`char`||l.wrap===`word`)&&(o=ff(a,l.wrap,`peek-${i.id}`,{skipTags:l.skipTags,startIndex:e}));let s=document.createElement(`div`);if(s.innerHTML=o,l.useCaret&&r.length>0){let e=pf(),t=s.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];n?.parentNode?n.parentNode.insertBefore(e,n.nextSibling):s.appendChild(e)}Ad(n,s),l.onAfterRender?.({container:n,bubble:t,messageId:i.id,message:i,speed:c.speed,duration:c.duration})}}let h=sa||ls;t.classList.toggle(`persona-pill-peek--visible`,h)};if(I()){let e=st.peekBanner;if(e){let t=e=>{e.preventDefault(),e.stopPropagation(),_s(!0,`user`)};e.addEventListener(`pointerdown`,t),Z.push(()=>{e.removeEventListener(`pointerdown`,t)})}let t=()=>{ls||(ls=!0,fs())},n=()=>{ls&&(ls=!1,fs())};H.addEventListener(`pointerenter`,t),H.addEventListener(`pointerleave`,n),Z.push(()=>{H.removeEventListener(`pointerenter`,t),H.removeEventListener(`pointerleave`,n)}),ot&&(ot.addEventListener(`pointerenter`,t),ot.addEventListener(`pointerleave`,n),Z.push(()=>{ot.removeEventListener(`pointerenter`,t),ot.removeEventListener(`pointerleave`,n)}))}let ps=e=>{let t=r.launcher?.composerBar??{},n=t.expandedSize??`anchored`,i=t.bottomOffset??`16px`,a=t.collapsedMaxWidth,o=t.expandedMaxWidth??`880px`,s=t.expandedTopOffset??`5vh`,c=t.modalMaxWidth??`880px`,l=t.modalMaxHeight??`min(90vh, 800px)`,u=`calc(100vw - 32px)`,d=at.style;if(d.left=``,d.right=``,d.top=``,d.bottom=``,d.transform=``,d.width=``,d.maxWidth=``,d.height=``,d.maxHeight=``,ot){let e=ot.style;e.bottom=i,e.width=a??``}e&&n!==`fullscreen`&&(n===`modal`?(d.top=`50%`,d.left=`50%`,d.transform=`translate(-50%, -50%)`,d.bottom=`auto`,d.right=`auto`,d.width=c,d.maxWidth=u,d.maxHeight=l,d.height=l):(d.left=`50%`,d.transform=`translateX(-50%)`,d.bottom=`calc(${i} + var(--persona-pill-area-height, 80px))`,d.top=s,d.width=o,d.maxWidth=u))},ms=()=>{if(R&&Qo(),!L())return;if(I()){let e=(r.launcher?.composerBar??{}).expandedSize??`anchored`,t=R?`expanded`:`collapsed`;at.dataset.state=t,at.dataset.expandedSize=e,ot&&(ot.dataset.state=t,ot.dataset.expandedSize=e),at.style.removeProperty(`display`),at.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),H.classList.remove(`persona-scale-95`,`persona-opacity-0`,`persona-scale-100`,`persona-opacity-100`),ps(R),U.style.display=R?`flex`:`none`,Mr(),R?(is(),ss()):(as(),cs()),fs();return}let t=kf(r),n=e.ownerDocument.defaultView??window,i=r.launcher?.mobileBreakpoint??640,a=r.launcher?.mobileFullscreen??!0,o=n.innerWidth<=i,s=a&&o&&he,c=jf(r).reveal;R?(at.style.removeProperty(`display`),at.style.display=t?`flex`:``,at.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),H.classList.remove(`persona-scale-95`,`persona-opacity-0`),H.classList.add(`persona-scale-100`,`persona-opacity-100`),od?(od.setPanelOpen(!0),od.element.style.display=`none`):sd&&(sd.style.display=`none`)):(t?t&&(c===`overlay`||c===`push`)&&!s?(at.style.removeProperty(`display`),at.style.display=`flex`,at.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),H.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(at.style.setProperty(`display`,`none`,`important`),at.classList.remove(`persona-pointer-events-none`,`persona-opacity-0`),H.classList.remove(`persona-scale-100`,`persona-opacity-100`,`persona-scale-95`,`persona-opacity-0`)):(at.style.display=``,at.classList.add(`persona-pointer-events-none`,`persona-opacity-0`),H.classList.remove(`persona-scale-100`,`persona-opacity-100`),H.classList.add(`persona-scale-95`,`persona-opacity-0`)),od?(od.setPanelOpen(!1),od.element.style.display=t?`none`:``):sd&&(sd.style.display=t?`none`:``))},_s=(t,n=`user`)=>{if(!L()||R===t)return;let i=R;R=t,ms();let a=(()=>{let t=r.launcher?.sidebarMode??!1,n=e.ownerDocument.defaultView??window,i=r.launcher?.mobileFullscreen??!0,a=r.launcher?.mobileBreakpoint??640,o=n.innerWidth<=a,s=kf(r)&&i&&o,c=I()&&(r.launcher?.composerBar?.expandedSize??`fullscreen`)===`fullscreen`;return t||i&&o&&he||s||c})();if(R&&a){if(!Ci){let t=e.getRootNode(),n=t instanceof ShadowRoot?t.host:e.closest(`.persona-host`);n&&(Ci=wf(n,r.launcher?.zIndex??1e5))}wi||=Df(e.ownerDocument)}else R||(Ci?.(),Ci=null,wi?.(),wi=null);R&&(dd(),No()||(zt()===`follow`?To(!0):Oo()));let o={open:R,source:n,timestamp:Date.now()};R&&!i?A.emit(`widget:opened`,o):!R&&i&&A.emit(`widget:closed`,o),A.emit(`widget:state`,{open:R,launcherEnabled:he,voiceActive:$.active,streaming:Q.isStreaming()})},bs={inputDisabled:!1,sendDisabled:!1},Ss=()=>bs.inputDisabled,Cs=()=>xs(r.voiceRecognition?.provider)&&!!Q&&(Q.isBargeInActive()||[`listening`,`processing`,`speaking`].includes(Q.getVoiceStatus())),ws=()=>bs.inputDisabled||bs.sendDisabled,Ts=()=>(bs.inputDisabled?bs.inputReason:void 0)??(bs.sendDisabled?bs.sendReason:void 0);function Es(){if(!q)return;if(X.getState().phase===`streaming`){q.disabled=!1;return}let e=vn?!vn.isReady():!1;q.disabled=ws()||e}function Ds(){if(!kt)return;let e=X.getState(),t=r.sendButton?.visibility===`when-text`&&e.phase!==`streaming`&&e.text.trim().length===0&&e.attachments.length===0;kt.toggleAttribute(`data-persona-send-hidden`,t)}function Os(){let e=Ts();if(I()){let t=dt??Tt;e?t.setAttribute(`title`,e):t.removeAttribute(`title`),Tt.toggleAttribute(Bg,!!e)}else if(e)ft.setAttribute(`role`,`status`),ft.setAttribute(`aria-live`,`polite`),ft.setAttribute(Bg,``),ft.removeAttribute(Vg),ft.textContent=e,zr(ft,r.statusIndicator??{},`idle`);else if(ft.hasAttribute(Bg)&&(ft.removeAttribute(`role`),ft.removeAttribute(`aria-live`),ft.removeAttribute(Bg),m)){let e=Q.getStatus();rt(ft,nt(e),r.statusIndicator??{},e)}}function As(){let e=ea(r.composer?.inputDisabled),t=ea(r.composer?.sendDisabled);bs={inputDisabled:e.disabled,inputReason:e.reason,sendDisabled:t.disabled,sendReason:t.reason},X.setInputDisabled(e.disabled),X.setSendDisabled(t.disabled);let n=X.getState().phase===`streaming`,i=e.disabled,a=n||i;K&&(K instanceof HTMLTextAreaElement?K.disabled=i:K.setAttribute(`contenteditable`,i?`false`:`true`),K.setAttribute(`aria-disabled`,i?`true`:`false`)),Mt&&(Mt.disabled=i),Pt&&(Pt.disabled=i);for(let e of yn?.affordanceButtons??[])e.querySelectorAll(`button`).forEach(e=>{e.disabled=i});Y&&(Y.disabled=i||n&&!Cs()),Pi.forEach(e=>{e.elements.forEach(e=>{e.toggleAttribute(`data-disabled`,a),e instanceof HTMLButtonElement||e.setAttribute(`aria-disabled`,a?`true`:`false`)}),e.buttons.forEach(e=>{e.disabled=a})}),qs.forEach(e=>{e.toggleAttribute(`data-disabled`,a),e instanceof HTMLButtonElement?e.disabled=a:e.setAttribute(`aria-disabled`,a?`true`:`false`),e.querySelectorAll(`button`).forEach(e=>{e.disabled=a})}),Tt.dataset.personaComposerStreaming=n?`true`:`false`,Tt.dataset.personaComposerInputDisabled=i?`true`:`false`,Tt.dataset.personaComposerSendDisabled=ws()?`true`:`false`,Tt.querySelectorAll(`[data-persona-composer-disable-when-streaming]`).forEach(e=>{(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.disabled=n)}),Es(),Os()}let js=e=>{X.setStreaming(e),At(e?`stop`:`send`),As()},Ms=()=>{$.active||K&&K.focus()};A.on(`widget:opened`,()=>{r.autoFocusInput&&setTimeout(()=>Ms(),200)});let Ns=null,Ps=!1,Fs=!pt.hidden,Is=null,Ls=!ie,Rs=null;Z.push(()=>{Rs?.cancel(),Rs=null});let zs=t=>{let n=im(t);if(n===dn)return;dn=n,e.setAttribute(`data-persona-conversation-state`,n);let r=pn();gn(),Ls&&(Rs?.cancel(),Rs=$p(Tt,n===`active`?r:pn(),n===`active`?`drop`:`rise`,un().layout===`centered`?320:260)),Vo()},Bs=null,Vs,Hs=null,Us=null,Ws=!1,Gs=e=>{let t=un(),n=`${t.variant}|${t.layout}|${t.dismiss}|${t.anchor??`bottom`}|${t.align??``}|${t.iconPlacement}|${t.kicker??``}|${t.title}|${t.subtitle}`;(n!==Bs||t.icon!==Vs)&&(Bs=n,Vs=t.icon,Up({host:pt,iconHolder:ht,kicker:vt,title:yt,subtitle:bt,starterSuggestions:ct},t));let i=t.message===void 0?null:`${r.layout?.messages?.layout??`bubble`}|${t.message}`;i!==Hs&&(Hs=i,Xp(_t,t.message,r));let a=e??(Q?Q.getMessages():r.initialMessages);zs(a);let o=Ps,s=!o&&am(t,a),c=s!==Fs;if(Fs=s,Us){Is?.cancel(),Is=null,o!==Ws&&(Ws=o,o?Jp(W,pt,null):qp(W,pt,Us)),Hp(W,pt,!o);return}if(c&&!s&&!o&&t.dismiss===`on-first-message`&&Ls){Is=Qp(pt,e=>{Is===e&&(Is=null),!Fs&&!Us&&(Hp(W,pt,!1),Vo()),e?.cancel()});return}if(Is){if(!s&&!o)return;Is.cancel(),Is=null}let l=!pt.hidden;Hp(W,pt,s),!s&&l&&Vo()},Ks=[],qs=[],Ys=!1,Zs=null,Qs,$s=()=>{qs.length=0;let e=Ks.splice(0,Ks.length);for(let t of e)try{t()}catch(e){console.warn(`[persona] renderWelcome cleanup threw`,e)}};Z.push($s);let ec=(e,t)=>{let n=Nf(e,t);if(!n)return r.debug===!0&&console.warn(`[persona] renderStarter received a suggestion with no label`),z(`span`);let i=r.suggestions?.starters,a=Lf({item:{...n,behavior:n.behavior??i?.behavior??`send`},index:t,surface:`starter`,source:`config`,variant:i?.variant??`card`,streaming:m?Q.isStreaming():!1,config:r,plugins:u,chipsConfig:r.suggestionChipsConfig,session:Q,getTextarea:()=>K,eventTarget:pt,submitPrompt:Nl});return qs.push(a),a},tc=()=>{if(Ys)return;Ys=!0;let e=un();Zs=`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`,Qs=e.icon;try{$s(),Jp(W,pt,Us),Us=null,Ws=!1;let t=Q?Q.getMessages():r.initialMessages,n=am(e,t),i=0,a=null;for(let t of u)if(t.renderWelcome&&(a=t.renderWelcome({config:e,variant:e.variant,visible:n,defaultRenderer:()=>pt,sendMessage:e=>{if(!Q||Q.isStreaming())return;let t=e.trim();t&&Q.sendMessage(t)},requestRender:()=>tc(),renderStarter:e=>ec(e,i++),storage:h(t.id),onCleanup:e=>{Ks.push(e)}}),a))break;a&&a!==pt&&(Us=a,qp(W,pt,a))}finally{Ys=!1}Gs()},nc=()=>{let e=un();(`${e.variant}|${e.layout}|${e.dismiss}|${e.title}|${e.subtitle}|${e.message??``}`!==Zs||e.icon!==Qs)&&tc()},rc=()=>{Gs(),Yn||(K.placeholder=fu(X.getState().activeModeIds,r.composer?.modes)??r.copy?.inputPlaceholder??`How can I help...`,!(r.sendButton?.useIcon??!1)&&!Q?.isStreaming()&&(q.textContent=r.copy?.sendButtonLabel??`Send`)),K.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,K.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`},ic=!!r.setStoredConversationId,ac=e=>de(t=>{let n={...t};return delete n[e],n}),oc=e=>{let t=re[e];return typeof t==`string`?t:null},sc=()=>{let e=re.durableResume;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.executionId==`string`&&t.executionId.length>0&&typeof t.after==`string`&&t.after.length>0?{executionId:t.executionId,after:t.after}:null};r.clientToken&&(r={...r,getStoredSessionId:()=>oc(`sessionId`),setStoredSessionId:e=>{de(t=>({...t,sessionId:e}))},clearStoredSessionId:r.clearStoredSessionId??(()=>ac(`sessionId`)),getStoredConversationId:r.getStoredConversationId??(()=>oc(`conversationId`)),setStoredConversationId:r.setStoredConversationId??(e=>{de(t=>({...t,conversationId:e}))}),clearStoredConversationId:r.clearStoredConversationId??(()=>ac(`conversationId`))});let cc=()=>r.clientToken??null,lc=e=>Sg(e,Me(),r.persistState===!1),dc=cc(),fc=dc?lc(dc):null,pc=()=>{let e=re.pendingDisplayProjections;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.conversationId!=`string`||!Array.isArray(t.messageIds)?null:{conversationId:t.conversationId,messageIds:t.messageIds.filter(e=>typeof e==`string`)}},mc={...fc?{visitorStore:fc}:{},historyBootstrapReady:r.features?.history?.enabled===!0&&!ns()?Promise.all([j,N]).then(()=>{}):j,getStoredMessageCursor:()=>oc(`historyMessageCursor`),setStoredMessageCursor:e=>{e===null?ac(`historyMessageCursor`):de(t=>({...t,historyMessageCursor:e}))},getPendingDisplayProjections:pc,setPendingDisplayProjections:e=>{e?de(t=>({...t,pendingDisplayProjections:e})):ac(`pendingDisplayProjections`)},getStoredResumableHandle:sc,setStoredResumableHandle:e=>{e?de(t=>({...t,durableResume:e})):ac(`durableResume`)},shouldResumeDurableConversation:()=>ne&&sc()!==null,...ic?{}:{getStoredConversationRevision:()=>oc(`conversationRevision`),setStoredConversationRevision:e=>{e===null?ac(`conversationRevision`):de(t=>({...t,conversationRevision:e}))}}};if(ne){let t=r.onExecutionState,n=e.ownerDocument.defaultView,i=!1,a=()=>i=!0,o=()=>i=!1;n?.addEventListener(`pagehide`,a),n?.addEventListener(`pageshow`,o),Z.push(()=>{n?.removeEventListener(`pagehide`,a),n?.removeEventListener(`pageshow`,o)}),r={...r,reconnectStream:r.reconnectStream??(e=>Q.getClient().reconnectClientTokenStream(e)),onExecutionState:e=>{(e||!i)&&mc.setStoredResumableHandle?.(e?{executionId:e.executionId,after:e.lastEventId}:null),t?.(e)}}}let hc=()=>{let e=cc();if(e&&fc?.matches(e,Me(),r.persistState===!1)||!e&&!fc)return;fc?.destroy(),fc=e?lc(e):null;let t={...mc};fc?t.visitorStore=fc:delete t.visitorStore,mc=t,Q.setHistoryInternals(mc)},gc=null,_c=()=>{gc??=setInterval(()=>{let e=G.querySelectorAll(`[data-tool-elapsed]`);if(e.length===0){clearInterval(gc),gc=null;return}let t=Date.now();e.forEach(e=>{let n=Number(e.getAttribute(`data-tool-elapsed`));n&&(e.textContent=e.closest(`.persona-activity-row`)?gs(t-n):ze(t-n))})},100)},yc=(e,t)=>{if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((e,n)=>yc(e,t[n]));let n=e,r=t,i=Object.keys(n),a=Object.keys(r);return i.length===a.length&&i.every(e=>Object.prototype.hasOwnProperty.call(r,e)&&yc(n[e],r[e]))},bc=e=>{let{content:t,rawContent:n,llmContent:r,...i}=e;return i},xc=e=>e.role===`assistant`&&e.streaming===!0&&!e.variant&&!e.toolCall&&!e.tools&&!e.approval&&!e.reasoning&&!e.contentParts&&!e.stopReason&&!Pg(e),Sc=(e,t,n)=>{if(e.length!==t.length)return!1;let r=e[n.index],i=t[n.index];return!r||!i||r.id!==n.id||i.id!==n.id?!1:(!Object.is(r.content,i.content)||!Object.is(r.rawContent,i.rawContent)||!Object.is(r.llmContent,i.llmContent))&&xc(r)&&xc(i)&&yc(bc(r),bc(i))},Cc=null,wc=null,Tc=null,Ec=null,Dc=null,Oc=e=>{if(!ne)return ro(e);Dc=e,queueMicrotask(()=>{Dc===e&&(Dc=null,ro(e))})},Mc=e=>{Cc=e;let t,n;wc=null;for(let r=e.length-1;r>=0;--r){let i=e[r];if(!t&&i.role===`user`&&(t=i),!n&&i.role===`assistant`&&(n=i),!wc&&xc(i)&&(wc={index:r,id:i.id}),t&&n&&wc)break}$o(G,e,Te),lh()?.updateInlineArtifactBlocks(G,Fr.artifacts,{suppressTransition:sa}),_c(),Gs(e),ta(e),To(!sa),qo(e),e.length===0&&(Lo(),Ma=!0,Na=!1,Fa=null,La=!1),!ka||Aa?(ka=!0,ja=t?.id??null,za=n?.id??null):t&&t.id!==ja?(ja=t.id,Uo(t.id)):n&&n.id!==za&&Wo(),n&&(za=n.id),Ko(e);let r=$.lastUserMessageId;t&&t.id!==r&&($.lastUserMessageId=t.id,A.emit(`user:message`,t)),$.lastUserMessageWasVoice=!!t?.viaVoice,Oc(e),fs()},Nc=()=>{Ec!==null&&(cancelAnimationFrame(Ec),Ec=null);let e=Tc;Tc=null,e&&Mc(e)},Pc=()=>{Ec!==null&&cancelAnimationFrame(Ec),Ec=null,Tc=null},Fc=e=>{let t=Tc??Cc;sa&&t&&wc&&Sc(t,e,wc)?(Tc=e,Ec===null&&(Ec=requestAnimationFrame(()=>{Ec=null;let e=Tc;Tc=null,e&&Mc(e)}))):e.length===0?(Pc(),Mc(e)):(Nc(),Mc(e))};Q=new ll(r,{onMessagesChanged(e){Fc(e)},onStatusChanged(e){let t=r.statusIndicator??{};rt(ft,(e=>e===`idle`?t.idleText??ln.idle:e===`connecting`?t.connectingText??ln.connecting:e===`connected`?t.connectedText??ln.connected:e===`error`?t.errorText??ln.error:e===`paused`?t.pausedText??ln.paused:e===`resuming`?t.resumingText??ln.resuming:ln[e])(e),t,e),V()},onStreamingChanged(e){e||(Q?.getMessages().length===0?Pc():Nc()),sa=e,js(e),V(),Q&&$o(G,Q.getMessages(),Te),e||(To(!0),Io(),Yi=!0,Q&&Zi(Q.getMessages(),nn(r))),So(),sn(e?`Responding…`:`Response complete.`),fs()},onVoiceStatusChanged(e){if(A.emit(`voice:status`,{status:e,timestamp:Date.now()}),e!==`disconnected`&&!xs(r.voiceRecognition?.provider))return;let t=Q.getVoiceNotice();switch(t&&bl(t,1e4),e){case`listening`:if(!Wa){let e=Q.getVoiceDisclosure();e&&(Wa=!0,I()?(Ga=K.placeholder,K.placeholder=e,sn(e)):bl(e,1e4))}Wu(),Vu();break;case`processing`:Wu(),Hu();break;case`speaking`:Wu(),Uu();break;default:e===`idle`&&Q.isBargeInActive()?(Wu(),Vu(),Y?.setAttribute(`aria-label`,`End voice session`)):($.active=!1,Wa=!1,Ga!==null&&(K.placeholder=Ga,Ga=null),Wu(),Ya(`system`),Ja||Xa())}},onArtifactsState(e){Fr=e,e.artifacts.length===0&&(Vr=!1),lh()?.updateInlineArtifactBlocks(G,e.artifacts,{suppressTransition:sa}),gi(),ro()},onHistoryStateChanged(e){B(e)},onHistoryNotice(e){$e(e)},onReconnect(e){let{executionId:t,lastEventId:n}=e.handle;e.phase===`paused`?A.emit(`stream:paused`,{executionId:t,after:n}):e.phase===`resuming`?A.emit(`stream:resuming`,{executionId:t,after:n,attempt:e.attempt??1}):A.emit(`stream:resumed`,{executionId:t,after:n})}},mc),Gr.current=Q,Z.push(()=>Q.cancel()),Z.push(()=>{Q.destroy(),fc?.destroy(),fc=null});let Ic=null;if(Q.onReadAloudChange((e,t)=>{Cr=e,wr=t,Dr();let n=e??Ic;e&&(Ic=e);let r=n?Q.getMessages().find(e=>e.id===n)??null:null;A.emit(`message:read-aloud`,{messageId:n,message:r,state:t,timestamp:Date.now()}),t===`idle`&&(Ic=null)}),m=!0,ka=!0,r.voiceRecognition?.enabled===!0&&xs(r.voiceRecognition.provider))try{Q.setupVoice()}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Runtype voice setup failed:`,e)}let Lc=null,Rc=null,Vc=!1,Hc=Q.getHistoryState(),Uc=()=>r.features?.history?.enabled===!0,Wc=e=>{e&&(rn.textContent=``,rn.textContent=e)},Gc=()=>{p.forEach(e=>e()),p=[];let t=Lc,n=t?.railCollapseShortcut();t&&n&&p.push(d.register({id:`history-rail-collapse`,combo:n.combo,scope:r.features?.history?.rail?.collapseShortcutScope===`page`?`page`:`widget`,when:()=>Ye&&Xe===`rail`&&t.railCollapsible()||t.railTriggerApplies(),run:()=>t.railOverlayMode()?t.toggleRailPinned():t.toggleRailCollapsed()}));for(let t of r.layout?.header?.trailingActions??[])t.shortcut&&p.push(d.register({id:`header-action-${t.id}`,combo:t.shortcut,run:()=>{let n=e.querySelector(`[data-persona-header-action="${t.id}"]`);n?n.click():r.layout?.header?.onAction?.(t.id)}}));for(let e of u)for(let t of e.shortcuts??[])p.push(d.register({...t,id:`${e.id}:${t.id}`}))};Gc();let Kc=null,qc=!1,Jc=()=>{if(!St)return;let e=r.layout?.header?.titleSource===`conversation`,t=e&&Kc?.trim()||null;St.textContent=t??r.launcher?.title??`Chat Assistant`;let n=St.closest(`.persona-combo-btn`);if(!n)return;let i=!e||Q.getActiveConversationId()!==null;n.setAttribute(`data-persona-menu-locked`,i?`false`:`true`),n.setAttribute(`aria-haspopup`,i?`true`:`false`),i||n.setAttribute(`aria-expanded`,`false`),n.style.cursor=i?`pointer`:`default`;let a=n.querySelector(`svg`);a&&(a.style.display=i?``:`none`)},Yc=e=>{e!==Kc&&(Kc=e,Jc())},Xc=e=>{qc=e?.starred===!0,Yc(e&&e.title.trim()||null),Jc()};Jc(),U.addEventListener(`persona:title-menu-builtin`,e=>{let t=e.detail?.actionId,n=Q.getActiveConversationId();n&&(t===`delete`?el(e=>e.requestDeleteConversation(n)):t===`star`&&Q.canUpdateConversations()&&el(e=>e.updateHistoryConversation(n,{starred:!qc})).catch(()=>{}))}),B=e=>{Hc=e,Lc?.historySurface?.view.setNewConversationRequired(e.recovery===`new_conversation_required`),js(e.sendBlocked||sa),Lc?.syncEarlierMessagesPill()},$e=e=>{(e.code===`history_continuity_reset`||e.code===`conversation_deleted_recovered`)&&(la.clear(),Lo(),wo()),Wc(e.message),Lc?.historySurface?.view.refresh()};let Zc={get actionManager(){return me},get activeConversationTitle(){return Kc},announceHistory:Wc,get applyRailChrome(){return Qe},set applyRailChrome(e){Qe=e},get artifactSplitRoot(){return ei},get body(){return W},get config(){return r},get container(){return U},get conversationOpenPendingEl(){return Ns},set conversationOpenPendingEl(e){Ns=e},get conversationOpenTakeover(){return Ps},set conversationOpenTakeover(e){Ps=e},currentKeyPrefix:Me,destroyCallbacks:Z,eventBus:A,get footer(){return Tt},get header(){return wt},get historyChromeSync(){return V},set historyChromeSync(e){V=e},historyFeatureEnabled:Uc,get historyInternals(){return mc},set historyInternals(e){mc=e},get historyPresentation(){return Xe},set historyPresentation(e){Xe=e},get historySessionState(){return Hc},get historyVisible(){return Ye},set historyVisible(e){Ye=e},get isStreaming(){return sa},jumpToBottomInstant:Oo,get lastAppliedMessages(){return Cc},set lastAppliedMessages(e){Cc=e},get launcherEnabled(){return he},get launcherSurfaceInstance(){return od},maybeFocusInput:Ms,messageCache:la,get messagesWrapper(){return G},mount:e,get open(){return R},panel:H,panelElements:st,get persistentMetadata(){return re},set persistentMetadata(e){re=e},plugins:u,get reapplyHistoryHostChrome(){return Ze},set reapplyHistoryHostChrome(e){Ze=e},repinAnchoredMessage:Vo,resetAnchorState:Lo,restoreScrollPosition:No,resumeAutoScroll:wo,runStorageMutation:no,get session(){return Q},setActiveConversationSummary:Xc,storageAdapter:te,get suppressScrollSend(){return Aa},set suppressScrollSend(e){Aa=e},syncScrollToBottomButton:So,updateWelcome:Gs,getHistoryProviderFactory:Eg,historyErrors:{HistoryClientError:uc,HistoryProviderError:vc},isDockedMountMode:kf,renderLucideIcon:P,loadHistoryView:Tg,createHeaderIconButton:Uf,attachTooltip:br},Qc=e=>(!Lc&&!Vc&&(Lc=e.createHistoryShell(Zc),Lc.railCollapseShortcut()&&Gc()),Lc),$c=()=>{if(Lc)return Promise.resolve(Lc);let e=ns();return e?Promise.resolve(Qc(e)):(Rc??=es().then(Qc,e=>{throw Rc=null,e}),Rc)},el=e=>{let t=ns(),n=Lc??(t?Qc(t):null);return n?e(n):$c().then(t=>{if(!t)throw Error(`[AgentWidget] The widget was destroyed`);return e(t)})},tl=()=>{Lc?.syncHistoryPresentation()};Z.push(()=>{Vc=!0}),Uc()&&$c().catch(()=>{}).finally(M),r.clientToken&&(r.features?.history?.enabled===!0||r.sessionInit===`mount`)&&Q.initClientSession().then(()=>{let e=Lc;if(e?.historyAvailable())return Q.reconcileBootConversation({scope:e.historyScope()})}).then(()=>{Lc?.syncEarlierMessagesPill()}).catch(e=>{r.debug&&console.warn(`[AgentWidget] Pre-init client session failed:`,e)});let nl=()=>Q.warmClientSession(),rl=e=>{let t=r.sessionInit??`input`,n=Qn?.input??K,i=e.target;n&&(e.type===`input`?(t===`input`||t===`focus`)&&i===n&&e.inputType&&n.value.trim():t===`focus`&&(e.type===`keyup`?i===n&&e.key===`Tab`:(Qn?.form??dt)?.contains(i)))&&nl()},il=[`input`,`pointerdown`,`keyup`];il.forEach(t=>e.addEventListener(t,rl));let al,ol,sl=()=>{let e=ol;ol=void 0;try{typeof e==`function`&&e()}catch{}},cl=()=>{let t=r.clientToken&&typeof r.sessionInit==`function`?r.sessionInit:void 0;if(t!==al){sl(),al=t;try{ol=t?.({warm:nl,mount:e})}catch{}}};cl(),Z.push(()=>{il.forEach(t=>e.removeEventListener(t,rl)),sl()}),(Oe||r.onSSEEvent)&&Q.setSSEEventCallback((e,t)=>{r.onSSEEvent?.(e,t),qe(e,t)});let ul=()=>{let e=r.resume??(ne?mc.getStoredResumableHandle?.():null);e&&typeof r.reconnectStream==`function`&&Q.resumeFromHandle(e)};ie?ie.then(e=>{if(e){if(e.metadata&&(re=qg(e.metadata),me.syncFromMetadata()),e.messages?.length){Aa=!0;try{Q.hydrateMessages(e.messages)}finally{Aa=!1}Qo()}e.artifacts?.length&&Q.hydrateArtifacts(e.artifacts,e.selectedArtifactId??null),lo(e.draft)}}).catch(e=>{typeof console<`u`&&console.error(`[AgentWidget] Failed to hydrate stored state:`,e)}).finally(()=>{Ls=!0,ae(),ul()}):(lo(oe),ul());let dl=()=>{I()&&(R||(r.launcher?.composerBar?.expandOnSubmit??!0)&&_s(!0,`auto`))},fl=(e,t)=>e?t?{refs:[...e.refs,...t.refs],finalize:async()=>{let[n,r]=await Promise.allSettled([e.finalize(),t.finalize()]),i=[];return n.status===`fulfilled`?i.push(n.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,n.reason),r.status===`fulfilled`?i.push(r.value):console.warn(`[Persona] a mention bundle failed to finalize; sending without it`,r.reason),Qg(i)}}:e:t,pl=()=>{let e=K.getInlineMessageFields?.();if(e)return e.contentSegments.some(e=>e.kind===`mention`)?e.contentSegments:void 0},ml=!1,gl=null,_l=()=>{K.value=``,K.style.height=`auto`,bn(),zl()},yl=null;function bl(e,t=4e3){sn(e),!I()&&ft&&(ft.hasAttribute(Bg)||(ft.setAttribute(Vg,``),ft.setAttribute(`role`,`status`),ft.setAttribute(`aria-live`,`polite`),ft.textContent=e,zr(ft,r.statusIndicator??{},`idle`),yl&&clearTimeout(yl),yl=setTimeout(()=>{if(yl=null,ft?.hasAttribute(Vg)&&(ft.removeAttribute(Vg),ft.removeAttribute(`role`),ft.removeAttribute(`aria-live`),m)){let e=Q.getStatus();rt(ft,nt(e),r.statusIndicator??{},e)}},t)))}function Sl(){let e=X.getState().pendingSubmission;e&&(zn(void 0),K&&(K.value=e.text,K.dispatchEvent(new Event(`input`,{bubbles:!0})),bn()),e.options.selectedModelId&&(X.setSelectedModelId(e.options.selectedModelId),An?.repaint()),e.options.activeModeIds?.length&&On(e.options.activeModeIds),e.options.quote&&Fn(e.options.quote),K?.focus())}let Cl=e=>{typeof console<`u`&&console.error(`[AgentWidget] composer.onBeforeSend failed; the draft was preserved:`,e)},wl=(e={})=>{let t=(e.overrideText??K?.value??``).trim();return e.resolveInlineCommand&&t?(yn?.takeInlineCommand(t)??Promise.resolve(null)).then(n=>Tl(e,t,n)):Tl(e,t,null)},Tl=(e,t,n)=>{if(n?.kind===`action`){_l(),yn?.clear(),xn();return}let i=n?.kind===`server`?n.mentions:null,a=n?.kind===`prompt`?n.sendText:t,o=e.pending?.contentParts;if(!Tu({text:a,hasAttachments:(vn?.hasAttachments()??!1)||(o?.length??0)>0,attachmentsReady:vn?.isReady()??!0,hasMentions:yn?.hasMentions()??!1,hasServerMentions:!!i,inputDisabled:Ss(),sendDisabled:ws()}))return;let s=Q.isStreaming()?Ln():`block`;if(s===`defer-one`&&!e.pending){if(X.getState().pendingSubmission){bl(`One message is already queued. Edit or remove it first.`);return}El({intent:e,sendText:a,serverMentions:i});return}let c={text:a,mentionRefs:[...yn?.getMentionRefs()??[],...i?.refs??[]],contentSegments:n?.kind===`prompt`?void 0:pl(),options:{...X.getState().selectedModelId&&{selectedModelId:X.getState().selectedModelId},...X.getState().activeModeIds.length>0&&{activeModeIds:[...X.getState().activeModeIds]},...X.getState().quote&&{quote:{...X.getState().quote}}},viaVoice:e.viaVoice};e.pending&&(c.options={...e.pending.options},c.contentSegments=e.pending.contentSegments,c.mentionRefs=[...e.pending.mentionRefs],c.viaVoice=e.pending.viaVoice);let l=()=>{if(o?.length)return[...o];if(!vn?.hasAttachments())return;let e=[...vn.getContentParts()];return c.text&&e.push(Ai(c.text)),e};c.contentParts=l();let u=()=>{ga(),dl();let t=yn?.collectForSubmit()??null,n=fl(t,i),a=l();e.consumeDraft!==!1&&_l();let o={selectedModelId:c.options.selectedModelId,activeModeIds:c.options.activeModeIds},u=s===`interrupt`;u&&Q.cancel(),Q.sendMessage(c.text,{contentParts:a,mentions:n??void 0,contentSegments:c.contentSegments,viaVoice:c.viaVoice,composerOptions:o,...c.options.quote&&{quote:c.options.quote},...u&&{interrupt:!0}}),vn?.hasAttachments()&&vn.clearAttachments(),t&&yn?.clear(),xn();let d=X.getState().activeModeIds,f=du(d,r.composer?.modes);f.length!==d.length&&On(f),X.getState().quote&&Fn(void 0),uo(),pr.release(),hr()},d=r.composer?.onBeforeSend;if(!d){u();return}let f=new AbortController;gl=f;let p=e=>{gl=null,e.status===`error`?Cl(e.error):e.status===`proceed`&&u()},m=Ou(d,c,f.signal);if(!(m instanceof Promise))p(m);else return X.setPreparing(!0),m.then(p).finally(()=>X.setPreparing(!1))};function El(e){let t=X.getState(),n=vn?.hasAttachments()??!1,r=n?[...vn.getContentParts()]:[];n&&e.sendText&&r.push(Ai(e.sendText)),zn(wu({text:e.sendText,contentParts:r.length?r:void 0,mentionRefs:[...yn?.getMentionRefs()??[],...e.serverMentions?.refs??[]],contentSegments:pl(),options:{...t.selectedModelId&&{selectedModelId:t.selectedModelId},...t.activeModeIds.length>0&&{activeModeIds:[...t.activeModeIds]},...t.quote&&{quote:{...t.quote}}},viaVoice:e.intent.viaVoice})),e.intent.consumeDraft!==!1&&_l(),n&&vn.clearAttachments(),yn?.clear(),xn(),t.quote&&Fn(void 0),uo(),pr.release(),hr(),sn(`Message queued. It sends when the response finishes.`)}function Dl(){let e=X.getState().pendingSubmission;e&&(zn(void 0),Pl(e.text,{consumeDraft:!1,pending:e}))}function Ol(e){if(r.messageActions?.showEdit!==!0)return;let t=Q.getMessages().find(t=>t.id===e);t&&jc(t)&&ma!==e&&(ga(),ma=e,ha=gu({messageId:e,initialText:t.content,onSave:t=>kl(e,t),onCancel:()=>ga()}),la.delete(e),$o(G,Q.getMessages(),Te),ha.focus())}function kl(e,t){let n=ha;ma=null,ha=null,n?.destroy(),la.delete(e),Q.resubmitFrom(e,{reason:`edit`,replacement:{text:t,mentionRefs:[],options:{}}})?Vo():$o(G,Q.getMessages(),Te)}function jl(e){if(Q.isStreaming())return;let t=kc(Q.getMessages(),e);t&&(ga(),Q.resubmitFrom(t,{reason:`retry`})&&Vo())}Or={regenerate:jl,edit:Ol,quote:e=>{let t=Q.getMessages().find(t=>t.id===e)?.content?.trim();t&&(Fn({text:t,messageId:e}),K?.focus())}};let Ml=async e=>{if(!ml){ml=!0;try{await wl({resolveInlineCommand:!0,...e})}finally{ml=!1}}};function Nl(e){ws()||(_l(),Pl(e,{consumeDraft:!1}))}let Pl=(e,t)=>{if(ml)return;ml=!0;let n=()=>{ml=!1};try{let r=wl({...t,overrideText:e});r instanceof Promise?r.finally(n):n()}catch(e){throw n(),e}},Fl=e=>{e.preventDefault(),Q.isStreaming()?(Q.cancel(),Re?.reset(),He?.update()):ml||Ml()},Il=()=>r.features?.composerHistory!==!1,Ll={...Md},Rl=!1,zl=()=>{Ll={...Md}},Bl=()=>Q.getMessages().filter(e=>e.role===`user`).map(e=>e.content??``).filter(e=>e.length>0),Vl=e=>{if(!K)return;Rl=!0,K.value=e,K.dispatchEvent(new Event(`input`,{bubbles:!0})),Rl=!1;let t=K.value.length;K.setSelectionRange(t,t)},Hl=e=>{Rl||(e.isComposing||yn?.handleInput(e.inputType??void 0),zl())},Ul=()=>({submitKey:r.composer?.submitKey,insertNewlineOnTouchEnter:r.composer?.insertNewlineOnTouchEnter,coarsePointer:Ji(K)}),Wl=e=>{if(K&&!Ss()&&(e.isComposing||!yn?.handleKeydown(e))){if(Il()&&(e.key===`ArrowUp`||e.key===`ArrowDown`)&&!e.shiftKey&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.isComposing){let t=K.selectionStart===0&&K.selectionEnd===0,n=Nd({direction:e.key===`ArrowUp`?`up`:`down`,history:Bl(),currentValue:K.value,atStart:t,state:Ll});if(Ll=n.state,n.handled){e.preventDefault(),n.value!==void 0&&Vl(n.value);return}}if(Xi(e,Ul())){if(Q.isStreaming()){if(e.preventDefault(),Ln()===`block`||ml||ws())return;zl(),Ml()}else ml||ws()?e.preventDefault():(zl(),e.preventDefault(),q.click())}}},Gl=e=>{e.key!==`Escape`||e.isComposing||e.composedPath().includes(U)&&(gl?(gl.abort(),gl=null,e.preventDefault(),e.stopImmediatePropagation()):Q.isStreaming()&&(Q.cancel(),Re?.reset(),He?.update(),zl(),e.preventDefault(),e.stopImmediatePropagation()))},Kl=async e=>{if(r.attachments?.enabled!==!0||!vn||Ss())return;let t=Ug(e.clipboardData);t.length!==0&&(e.preventDefault(),await vn.handleFiles(t))},ql=null,Yl=!1,Xl=null,$l=null,iu=()=>r.voiceRecognition?.completionBehavior===`review`;function ou(e){Y?.setAttribute(`data-state`,e),e===`recording`?Pu():Fu()}let cu=`--persona-voice-level`,Eu=.5,Du=null,ku=-1,Au=0,ju=()=>{let e=[],t=jt??Y?.parentElement??null;return t&&e.push(t),Tt&&e.push(Tt),e},Mu=e=>{let t=Math.round(Math.max(0,Math.min(1,e))*100)/100;if(t!==ku){ku=t;for(let e of ju())e.style.setProperty(cu,String(t))}},Nu=()=>{ku=-1,Au=0;for(let e of ju())e.style.removeProperty(cu)};function Pu(){if(Du!==null)return;if(typeof requestAnimationFrame!=`function`){Mu(m?Q.getVoiceLevel()??Eu:Eu);return}let e=()=>{Du=requestAnimationFrame(e);let t=m?Q.getVoiceLevel():null;t===null?Mu(Eu):(Au+=(t-Au)*.3,Mu(Au))};Du=requestAnimationFrame(e)}function Fu(){Du!==null&&(cancelAnimationFrame(Du),Du=null),Nu()}let Iu=()=>typeof window>`u`?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Lu=(e=`user`)=>{if(Yl||Q.isStreaming())return;let t=Iu();if(!t)return;ql=new t;let n=r.voiceRecognition??{},i=n.pauseDuration??2e3;ql.continuous=n.provider?.browser?.continuous??!0,ql.interimResults=!0,ql.lang=n.provider?.browser?.language??`en-US`;let a=K.value;ql.onresult=e=>{let t=``,n=``;for(let r=0;r<e.results.length;r++){let i=e.results[r],a=i[0].transcript;i.isFinal?t+=a+` `:n=a}let r=a+t+n;K.value=r,bn(),Xl&&clearTimeout(Xl),(t||n)&&(Xl=window.setTimeout(()=>{if(K.value.trim()&&ql&&Yl){if(Ru(),iu())return;Ml({viaVoice:!0})}},i))},ql.onerror=e=>{e.error!==`no-speech`&&Ru()},ql.onend=()=>{if(Yl){let e=K.value.trim();!iu()&&e&&e!==a.trim()&&Ml({viaVoice:!0}),Ru()}};try{if(ql.start(),Yl=!0,$.active=!0,e!==`system`&&($.manuallyDeactivated=!1),Ya(e),Xa(),hr(),Y){let e=r.voiceRecognition??{};$l={backgroundColor:Y.style.backgroundColor,color:Y.style.color,borderColor:Y.style.borderColor,iconName:e.iconName??`mic`,iconSize:parseFloat(e.iconSize??``)||24};let t=e.recordingBackgroundColor,n=e.recordingIconColor,i=e.recordingBorderColor;if(Y.classList.add(`persona-voice-recording`),ou(`recording`),Y.style.backgroundColor=t??`var(--persona-voice-recording-bg, #ef4444)`,Y.style.color=n??`var(--persona-voice-recording-indicator, #ffffff)`,n){let e=Y.querySelector(`svg`);e&&e.setAttribute(`stroke`,n)}i&&(Y.style.borderColor=i),Y.setAttribute(`aria-label`,`Stop voice recognition`)}}catch{Ru(`system`)}},Ru=(e=`user`)=>{if(Yl){if(Yl=!1,Xl&&=(clearTimeout(Xl),null),ql){try{ql.stop()}catch{}ql=null}if($.active=!1,Ya(e),Xa(),hr(),Y){if(Y.classList.remove(`persona-voice-recording`),ou(`idle`),$l){Y.style.backgroundColor=$l.backgroundColor,Y.style.color=$l.color,Y.style.borderColor=$l.borderColor;let e=Y.querySelector(`svg`);e&&e.setAttribute(`stroke`,$l.color||`currentColor`),$l=null}Y.setAttribute(`aria-label`,`Start voice recognition`)}}},zu=null,Bu=e=>{let t=t=>{zu??=t.createMicStateStyles({mic:()=>Y,config:()=>r,session:()=>Q,get original(){return $l},set original(e){$l=e},setMicState:ou,renderIcon:P,iconFallbackPx:24}),e(zu)},n=Bc();n?t(n):zc().then(t,()=>{})},Vu=()=>Bu(e=>e.recording()),Hu=()=>Bu(e=>e.processing()),Uu=()=>Bu(e=>e.speaking()),Wu=()=>Bu(e=>e.reset()),Gu=()=>{if(!Ss()){if(xs(r.voiceRecognition?.provider)){let e=Q.getVoiceStatus(),t=Q.getVoiceInterruptionMode();if(t===`none`&&(e===`processing`||e===`speaking`))return;if(t===`cancel`&&(e===`processing`||e===`speaking`)){Q.stopVoicePlayback();return}if(Q.isBargeInActive()){Q.stopVoicePlayback(),Q.deactivateBargeIn().then(()=>{$.active=!1,$.manuallyDeactivated=!0,Xa(),Ya(`user`),Wu()});return}Q.toggleVoice().then(()=>{$.active=qa(),$.manuallyDeactivated=!$.active,Xa(),Ya(`user`),$.active?Vu():Wu()})}else if(Yl){let e=K.value.trim();$.manuallyDeactivated=!0,Xa(),Ru(`user`),e&&!iu()&&Ml()}else $.manuallyDeactivated=!1,Xa(),Lu(`user`)}};Hn=Gu;let Ku=()=>Q.prewarmVoice(),qu=()=>{let e=r.voiceRecognition;return e?.enabled===!0?e.prewarm??(r.clientToken?`hover`:!1):!1},Ju=e=>{qu()===`hover`&&Y?.contains(e.target)&&Ku()},Xu=[`pointerover`,`pointerdown`,`focusin`];Xu.forEach(t=>e.addEventListener(t,Ju));let Zu,Qu=null,$u,ed=()=>{let e=$u;$u=void 0;try{typeof e==`function`&&e()}catch{}},td=()=>{let t=qu(),n=typeof t==`function`&&Y?t:void 0,r=n?Y:null;if((n!==Zu||r!==Qu)&&(ed(),Zu=n,Qu=r,n&&r))try{$u=n({warm:Ku,micButton:r,mount:e})}catch{}};td(),Z.push(()=>{Xu.forEach(t=>e.removeEventListener(t,Ju)),ed()}),Y&&Z.push(()=>{xs(r.voiceRecognition?.provider)?(Q.isVoiceActive()&&Q.toggleVoice(),Wu()):Ru(`system`)});let nd=A.on(`assistant:complete`,()=>{X.getState().pendingSubmission&&setTimeout(()=>{Q.isStreaming()||Dl()},0)});Z.push(nd);let rd=A.on(`assistant:complete`,()=>{Ka&&($.active||$.manuallyDeactivated||(Ka!==`assistant`||$.lastUserMessageWasVoice)&&setTimeout(()=>{!$.active&&!$.manuallyDeactivated&&(xs(r.voiceRecognition?.provider)?Q.toggleVoice().then(()=>{$.active=Q.isVoiceActive(),Ya(`auto`),Q.isVoiceActive()&&Vu()}):Lu(`auto`))},600))});Z.push(rd);let id=A.on(`action:resubmit`,()=>{setTimeout(()=>{Q&&!Q.isStreaming()&&Q.continueConversation()},100)});Z.push(id);let ad=()=>{_s(!R,`user`)},od=null,sd=null;if(he&&!I()){let{instance:e,element:t}=Tm({config:r,plugins:u,onToggle:ad});od=e,e||(sd=t)}od?e.appendChild(od.element):sd&&e.appendChild(sd),ms(),ta(),rc(),tc(),js(Q.isStreaming()),No()||(zt()===`follow`?To(!0):Oo()),Za(),ge&&(!he||I()?setTimeout(()=>Ms(),0):R&&setTimeout(()=>Ms(),200));let cd=null,ld=()=>{cd&&(cd.disconnect(),cd.observe(Tt),cd.observe(U),cd.observe(pt))},ud=cn(),dd=()=>{if(I()){mn(),ms();return}let t=kf(r),n=r.launcher?.sidebarMode??!1,i=e.ownerDocument.defaultView??window,a=r.launcher?.mobileFullscreen??!0,o=r.launcher?.mobileBreakpoint??640,s=i.innerWidth<=o,c=a&&s&&he;try{if(c){Mr(),Nr=hi();return}let e=!1;be&&(be=!1,Mr(),e=!0);let i=hi();if(!e&&i!==Nr&&(Mr(),e=!0),Nr=i,e&&ii(),!he&&!t){H.style.height=``,H.style.width=``;return}if(!n&&!t){let e=sm(r);H.style.width=e.width,H.style.maxWidth=e.maxWidth}fi(),Si()}finally{mn(),gn();let t=cn();if(t!==ud&&(ud=t,Gs(),ta()),ms(),R&&he){let t=(e.ownerDocument.defaultView??window).innerWidth<=(r.launcher?.mobileBreakpoint??640),n=r.launcher?.sidebarMode??!1,i=r.launcher?.mobileFullscreen??!0,a=kf(r)&&i&&t,o=n||i&&t&&he||a;if(o&&!wi){let t=e.getRootNode(),n=t instanceof ShadowRoot?t.host:e.closest(`.persona-host`);n&&!Ci&&(Ci=wf(n,r.launcher?.zIndex??1e5)),wi=Df(e.ownerDocument)}else o||(Ci?.(),Ci=null,wi?.(),wi=null)}}};dd();let fd=e.ownerDocument.defaultView??window;if(fd.addEventListener(`resize`,dd),Z.push(()=>fd.removeEventListener(`resize`,dd)),typeof ResizeObserver<`u`){cd=new ResizeObserver(()=>{gn()}),ld(),Z.push(()=>{cd?.disconnect(),cd=null});let e=new ResizeObserver(()=>{tl()});e.observe(U),Z.push(()=>e.disconnect())}fd.addEventListener(`resize`,tl),Z.push(()=>fd.removeEventListener(`resize`,tl)),Sa=W.scrollTop;let pd=Vd(W),md=()=>{bi();let e=W.scrollTop,t=Vd(W),n=t<pd;if(pd=t,!Bt()){Sa=e,So();return}let{action:r,nextLastScrollTop:i}=Ud({following:ba.isFollowing(),currentScrollTop:e,lastScrollTop:Sa,nearBottom:Hd(W,24),userScrollThreshold:4,isAutoScrolling:wa||Ta||n,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});Sa=i,r===`resume`?Mo()||wo():r===`pause`&&Co()};if(W.addEventListener(`scroll`,md,{passive:!0}),Z.push(()=>W.removeEventListener(`scroll`,md)),typeof ResizeObserver<`u`){let e=new ResizeObserver(()=>{Ho(),Xs(G)});e.observe(G),e.observe(W),Z.push(()=>e.disconnect())}let hd=()=>{Bt()&&ba.isFollowing()&&Mo()&&Co()},gd=W.ownerDocument;gd.addEventListener(`selectionchange`,hd),Z.push(()=>{gd.removeEventListener(`selectionchange`,hd)});let _d=/* @__PURE__ */ new Set([`PageUp`,`PageDown`,`Home`,`End`,`ArrowUp`,`ArrowDown`]),vd=e=>{_d.has(e.key)&&(Ra(),Gt()&&Bt()&&ba.isFollowing()&&Co())},bd=e=>{e.target?.closest(`a, button, [tabindex], input, textarea, select`)&&(Ra(),Gt()&&Bt()&&ba.isFollowing()&&Co())};W.addEventListener(`keydown`,vd),W.addEventListener(`focusin`,bd),Z.push(()=>{W.removeEventListener(`keydown`,vd),W.removeEventListener(`focusin`,bd)});let xd=e=>{if(e.deltaY!==0&&Ra(),!Bt())return;let t=Wd({following:ba.isFollowing(),deltaY:e.deltaY,nearBottom:Hd(W,24),resumeWhenNearBottom:!0});t===`pause`?Co():t===`resume`&&!Mo()&&wo()};W.addEventListener(`wheel`,xd,{passive:!0}),W.addEventListener(`touchmove`,Ra,{passive:!0}),W.addEventListener(`pointerdown`,Ra,{passive:!0}),Z.push(()=>{W.removeEventListener(`touchmove`,Ra),W.removeEventListener(`pointerdown`,Ra)}),Z.push(()=>W.removeEventListener(`wheel`,xd)),Yt.addEventListener(`click`,()=>{Lo(),W.scrollTop=W.scrollHeight,Sa=W.scrollTop,wo(),To(!0),So()}),Z.push(()=>Yt.remove()),Z.push(()=>{ho(),Lo()});let Cd=()=>{J&&(Fi&&=(J.removeEventListener(`click`,Fi),null),L()?(J.style.display=``,Fi=()=>{_s(!1,`user`)},J.addEventListener(`click`,Fi)):J.style.display=`none`)};Cd(),(()=>{let{clearChatButton:e}=st;e&&e.addEventListener(`click`,()=>{let e=Lc;if(e?.historyAvailable()){e.startNewConversation({focusComposer:!0}).catch(e=>{r.debug&&console.warn(`[AgentWidget] New conversation failed:`,e)});return}Q.clearMessages(),r.layout?.topFade&&(W.scrollTop=0),W.removeAttribute(`data-persona-top-fade`),la.clear(),wo(),Ht(st.composerOverlay);try{localStorage.removeItem(zg),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${zg}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==zg)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let t=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(t),te?.clear&&no(()=>te.clear(),`[AgentWidget] Failed to clear storage adapter:`),re={},me.syncFromMetadata(),vn?.clearAttachments(),uo(),zn(void 0),Fn(void 0),ga(),Le?.clear(),Re?.reset(),He?.update()})})();let Jd=[[`keydown`,Wl],[`input`,Hl],[`input`,bn],[`input`,xn],[`keyup`,xn],[`paste`,Kl],[`focus`,ar]],Yd=e=>{if(e)for(let[t,n]of Jd)Qn?.addListener(e,t,n)},Zd=e=>{if(e)for(let[t,n]of Jd)Qn?.removeListener(e,t,n)},Qd=()=>{Qn&&(Qn.addListener(Qn.form,`submit`,Fl),Qn.addListener(Qn.footer,`click`,xn),Yd(K),Y&&Qn.addListener(Y,`click`,Gu),td())};Qd();let tf=()=>{yn?.onComposerSwap((e,t)=>{Zd(t),K=e,Qn&&(Qn.input=e),Yd(e),er(),As(),bn()})};tf();let nf=!1;function of(){if(!nf){nf=!0;try{let e=K?.value??``,t=Tt.ownerDocument??document,n=K?t.activeElement===K:!1;Fu(),Qn?.destroy(),Qn=null,yn?.destroy(),yn=null;let i=null,a=()=>(i=I()?dp({config:r}):lp({config:r}),i.footer),o=Xn(a)??a();it.replaceComposer(o),Tt=it.composer.footer;let s=i!==null&&o===i.footer;Yn=!s,At=s?i.setSendButtonMode:()=>{},Jn(Tt),tr(Tt),rr(),ir(),or(),tf(),ur(),dr(),fr(),Qd();let c=Pi.indexOf(ji);if(ji.destroy(),ji=Rf(ut),c>=0&&(Pi[c]=ji),K&&(K.value=e),bn(),xn(),rc(),ta(),js(Q.isStreaming()),r.statusIndicator?.mode===`transient`&&!I()){let e=Q.getStatus();rt(ft,nt(e),r.statusIndicator,e)}$.active&&ou(`recording`),Mr(),ld(),mn(),hr(),Ds(),n&&K?.focus()}finally{nf=!1}}}let sf=e.ownerDocument??document;sf.addEventListener(`keydown`,Gl,!0);let cf=()=>{co()},lf=()=>{sf.visibilityState===`hidden`&&co()};typeof window<`u`&&(window.addEventListener(`pagehide`,cf),sf.addEventListener(`visibilitychange`,lf),Z.push(()=>{window.removeEventListener(`pagehide`,cf),sf.removeEventListener(`visibilitychange`,lf)}));let uf=`persona-attachment-drop-active`,df=0,hf=()=>{df=0,U.classList.remove(uf)},gf=()=>r.attachments?.enabled===!0&&vn!==null&&!Ss(),_f=e=>{Wg(e.dataTransfer)&&gf()&&(df++,df===1&&U.classList.add(uf))},vf=e=>{Wg(e.dataTransfer)&&gf()&&(df--,df<=0&&hf())},xf=e=>{Wg(e.dataTransfer)&&gf()&&(e.preventDefault(),e.dataTransfer.dropEffect=`copy`)},Sf=e=>{if(!Wg(e.dataTransfer)||!gf())return;e.preventDefault(),e.stopPropagation(),hf();let t=Array.from(e.dataTransfer.files??[]);t.length!==0&&vn.handleFiles(t)};U.addEventListener(`dragenter`,_f,!0),U.addEventListener(`dragleave`,vf,!0),e.addEventListener(`dragover`,xf,!0),e.addEventListener(`drop`,Sf,!0);let Tf=e.ownerDocument,Ef=e=>{gf()&&e.preventDefault()},Of=e=>{gf()&&e.preventDefault()};Tf.addEventListener(`dragover`,Ef),Tf.addEventListener(`drop`,Of),Z.push(()=>{Qn?.destroy(),Qn=null,Fu(),sr?.destroy(),sr=null,Mn?.destroy(),Mn=null,Pn?.destroy(),Pn=null,Rn?.destroy(),Rn=null,An=null,jn=null,co(),oo.destroy(),yl&&clearTimeout(yl),ga(),gl?.abort(),gl=null,vn?.destroy(),vn=null,X.destroy(),sf.removeEventListener(`keydown`,Gl,!0),yn?.destroy()}),Z.push(()=>{U.removeEventListener(`dragenter`,_f,!0),U.removeEventListener(`dragleave`,vf,!0),e.removeEventListener(`dragover`,xf,!0),e.removeEventListener(`drop`,Sf,!0),Tf.removeEventListener(`dragover`,Ef),Tf.removeEventListener(`drop`,Of),hf()}),Z.push(()=>{Q.cancel()}),od?Z.push(()=>{od?.destroy()}):sd&&Z.push(()=>{sd?.remove()});let Mf={update(t){let n=r.future?.v5Defaults===!0,i=r.toolCall,a=r.messageActions,o=r.layout?.messages,s=r.colorScheme,d=r.loadingIndicator,p=r.iterationDisplay,m=r.features?.showReasoning,h=r.features?.showToolCalls,g=r.features?.toolCallDisplay,_=r.features?.reasoningDisplay,v=r.features?.streamAnimation?.type,y=r.features?.history?.enabled===!0,b=r.features?.history?.provider,x=r.getIdentityProof,S=r.clientToken,C=r.contextMentions;r=ag({...r,features:l},t),l=r.features,r=Hh(r),c(),_i(),wd(e,r),_h(e,r),vh(e,r),Qe(),gi(),r.colorScheme!==s&&Ei();let w=tg.getForInstance(r.plugins);u.length=0,u.push(...w),Gc(),he=r.launcher?.enabled??!0,F=r.launcher?.autoExpand??!1,Ee=r.features?.showReasoning??!0,De=r.features?.showToolCalls??!0,Ae=r.features?.scrollToBottom??{};let T=zt();je=r.features?.scrollBehavior??{},T!==zt()&&(Lo(),wo()),Va(),_n(),So();let E=Oe;if(Oe=r.features?.showEventStreamToggle??!1,Oe&&!E){if(Le||(Je(),Q.setSSEEventCallback((e,t)=>{r.onSSEEvent?.(e,t),qe(e,t)})),!qn&&wt){let e=r.features?.eventStream?.classNames,t=`persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1`+(e?.toggleButton?` `+e.toggleButton:``);qn=z(`button`,t),qn.style.width=`28px`,qn.style.height=`28px`,qn.style.color=Kf.actionIconColor,qn.type=`button`,qn.setAttribute(`aria-label`,`Event Stream`),qn.title=`Event Stream`;let n=k(f.Activity,`18px`,`currentColor`,1.5);n&&qn.appendChild(n);let i=st.clearChatButtonWrapper,a=st.closeButtonWrapper,o=i||a;o&&o.parentNode===wt?wt.insertBefore(qn,o):wt.appendChild(qn),qn.addEventListener(`click`,()=>{Ue?Kn():Gn()})}}else!Oe&&E&&(Kn(),qn&&=(qn.remove(),null),Le?.clear(),Pe?.destroy(),Le=null,Pe=null,Re?.reset(),Re=null,Be=null);if(r.launcher?.enabled===!1&&od&&(od.destroy(),od=null),r.launcher?.enabled===!1&&sd&&(sd.remove(),sd=null),r.launcher?.enabled!==!1&&!od&&!sd){let{instance:t,element:n}=Tm({config:r,plugins:u,onToggle:ad});od=t,t||(sd=n),e.appendChild(n)}od&&od.update(r),Jc(),Ct&&r.launcher?.subtitle!==void 0&&(Ct.textContent=r.launcher.subtitle);let D=r.layout?.header;if(D?.layout!==ye&&wt){let e=D?cp(r,D,{showClose:L(),onClose:()=>_s(!1,`user`)}):Yf({config:r,showClose:L(),onClose:()=>_s(!1,`user`)});it.replaceHeader(e),wt=it.header.element,xt=it.header.iconHolder,St=it.header.headerTitle,Ct=it.header.headerSubtitle,J=it.header.closeButton,ye=D?.layout,Jc()}else if(D){if(xt&&(xt.style.display=D.showIcon===!1?`none`:``),St&&(St.style.display=D.showTitle===!1?`none`:``),Ct&&(Ct.style.display=D.showSubtitle===!1?`none`:``),J){let e=L()&&D.showCloseButton!==!1;J.style.display=e?``:`none`}if(st.clearChatButtonWrapper){let e=D.showClearChat;if(e!==void 0){st.clearChatButtonWrapper.style.display=e?``:`none`;let{closeButtonWrapper:t}=st;t&&!t.classList.contains(`persona-absolute`)&&(e?t.classList.remove(`persona-ml-auto`):t.classList.add(`persona-ml-auto`))}}}let O=r.layout?.showHeader!==!1;wt&&(wt.style.display=O?``:`none`);let ee=r.layout?.showFooter!==!1;Tt&&(Tt.style.display=ee?``:`none`),mn(),So(),he===ve?F!==_e&&_s(F,`auto`):he?_s(F,`auto`):(R=!0,ms()),_e=F,ve=he,dd(),Cd();let te=JSON.stringify(r.toolCall)!==JSON.stringify(i),ne=JSON.stringify(r.messageActions)!==JSON.stringify(a),re=JSON.stringify(r.layout?.messages)!==JSON.stringify(o),ie=r.loadingIndicator?.render!==d?.render||r.loadingIndicator?.renderIdle!==d?.renderIdle||r.loadingIndicator?.showBubble!==d?.showBubble,ae=r.iterationDisplay!==p,j=(r.features?.showReasoning??!0)!==(m??!0)||(r.features?.showToolCalls??!0)!==(h??!0)||JSON.stringify(r.features?.toolCallDisplay)!==JSON.stringify(g)||JSON.stringify(r.features?.reasoningDisplay)!==JSON.stringify(_);(r.future?.v5Defaults===!0!==n||te||ne||re||ie||ae||j)&&Q&&(va++,$o(G,Q.getMessages(),Te));let M=r.features?.streamAnimation?.type;if(M!==v&&M&&M!==`none`){let t=Oi(M,r.features?.streamAnimation?.plugins);t&&bf(t,e)}let N=r.launcher??{},oe=N.headerIconHidden??!1,se=r.layout?.header?.showIcon,ce=oe||se===!1,le=N.headerIconName,fe=N.headerIconSize??`40px`;if(xt){let e=wt,t=e?.querySelector(`.persona-flex-col`);if(ce)xt.style.display=`none`,e&&t&&!e.contains(t)&&e.insertBefore(t,e.firstChild);else{if(xt.style.display=``,xt.style.height=fe,xt.style.width=fe,e&&t&&(e.contains(xt)?xt.nextSibling!==t&&(xt.remove(),e.insertBefore(xt,t)):e.insertBefore(xt,t)),le){let e=parseFloat(fe)||24,t=P(le,e*.6,`currentColor`,1);t?(t.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,t.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,xt.replaceChildren(t)):xt.textContent=N.agentIconText??`💬`}else if(N.iconUrl){let e=xt.querySelector(`img`);if(e)e.src=N.iconUrl,e.style.height=fe,e.style.width=fe;else{let e=document.createElement(`img`);e.src=N.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=fe,e.style.width=fe,xt.replaceChildren(e)}}else{let e=xt.querySelector(`svg`),t=xt.querySelector(`img`);(e||t)&&xt.replaceChildren(),xt.textContent=N.agentIconText??`💬`}let n=xt.querySelector(`img`);n&&(n.style.height=fe,n.style.width=fe)}}let pe=r.layout?.header?.showTitle,ge=r.layout?.header?.showSubtitle;if(St&&(St.style.display=pe===!1?`none`:``),Ct&&(Ct.style.display=ge===!1?`none`:``),J){let e=L()&&r.layout?.header?.showCloseButton!==!1;if(J.style.display=e?``:`none`,!I()){let e=N.closeButtonSize??``;J.style.height=e,J.style.width=e,J.style.minWidth=e,J.style.minHeight=e}let t=N.closeButtonPlacement??`inline`,{closeButtonWrapper:n}=st,i=t===`top-right`,a=n?.classList.contains(`persona-absolute`);if(n&&i!==a){if(n.remove(),i){n.className=`persona-absolute persona-top-4 persona-right-4 persona-z-50`;let e=Lc?.railColumn??U;e.style.position=`relative`,e.appendChild(n)}else{let e=N.clearChat?.placement??`inline`;n.className=(N.clearChat?.enabled??!0)&&e===`inline`?``:`persona-ml-auto`,wt&&wt.appendChild(n)}}if(J.style.color=N.closeButtonColor||Kf.actionIconColor,N.closeButtonBackgroundColor?(J.style.backgroundColor=N.closeButtonBackgroundColor,J.classList.remove(`hover:persona-bg-gray-100`)):(J.style.backgroundColor=``,J.classList.add(`hover:persona-bg-gray-100`)),N.closeButtonBorderWidth||N.closeButtonBorderColor){let e=N.closeButtonBorderWidth||`0px`,t=N.closeButtonBorderColor||`transparent`;J.style.border=`${e} solid ${t}`,J.classList.remove(`persona-border-none`)}else J.style.border=``,J.classList.add(`persona-border-none`);N.closeButtonBorderRadius?(J.style.borderRadius=N.closeButtonBorderRadius,J.classList.remove(`persona-rounded-full`)):(J.style.borderRadius=``,J.classList.add(`persona-rounded-full`)),N.closeButtonPaddingX?(J.style.paddingLeft=N.closeButtonPaddingX,J.style.paddingRight=N.closeButtonPaddingX):(J.style.paddingLeft=``,J.style.paddingRight=``),N.closeButtonPaddingY?(J.style.paddingTop=N.closeButtonPaddingY,J.style.paddingBottom=N.closeButtonPaddingY):(J.style.paddingTop=``,J.style.paddingBottom=``),Hf(J,N.closeButtonIconName??`x`,{iconSize:I()?lm:void 0,iconText:N.closeButtonIconText??`×`});let o=N.closeButtonTooltipText??`Close chat`,s=N.closeButtonShowTooltip??!0;J.setAttribute(`aria-label`,o),n&&br({anchor:J,trigger:n,text:()=>J?.getAttribute(`aria-label`)??o,enabled:s})}let{clearChatButton:be,clearChatButtonWrapper:xe}=st;if(be){let e=N.clearChat??{},t=e.enabled??!0,n=r.layout?.header?.showClearChat,i=n===void 0?t:n,a=e.placement??`inline`;if(xe){xe.style.display=i?``:`none`;let{closeButtonWrapper:e}=st;!I()&&e&&!e.classList.contains(`persona-absolute`)&&(i?e.classList.remove(`persona-ml-auto`):e.classList.add(`persona-ml-auto`));let t=a===`top-right`,n=xe.classList.contains(`persona-absolute`);if(!I()&&t!==n&&i){if(xe.remove(),t){xe.className=`persona-absolute persona-top-4 persona-z-50`,xe.style.right=`48px`;let e=Lc?.railColumn??U;e.style.position=`relative`,e.appendChild(xe)}else{xe.className=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,xe.style.right=``;let e=st.closeButtonWrapper;wt&&e&&e.parentElement===wt?wt.insertBefore(xe,e):wt&&wt.appendChild(xe)}let e=st.closeButtonWrapper;e&&!e.classList.contains(`persona-absolute`)&&(t?e.classList.add(`persona-ml-auto`):e.classList.remove(`persona-ml-auto`))}}if(i){if(!I()){let t=e.size??``;be.style.height=t,be.style.width=t,be.style.minWidth=t,be.style.minHeight=t}let t=e.iconColor??``;if(be.style.color=t||Kf.actionIconColor,Hf(be,e.iconName??`refresh-cw`,{iconSize:I()?um:void 0}),e.backgroundColor?(be.style.backgroundColor=e.backgroundColor,be.classList.remove(`hover:persona-bg-gray-100`)):(be.style.backgroundColor=``,be.classList.add(`hover:persona-bg-gray-100`)),e.borderWidth||e.borderColor){let t=e.borderWidth||`0px`,n=e.borderColor||`transparent`;be.style.border=`${t} solid ${n}`,be.classList.remove(`persona-border-none`)}else be.style.border=``,be.classList.add(`persona-border-none`);e.borderRadius?(be.style.borderRadius=e.borderRadius,be.classList.remove(`persona-rounded-full`)):(be.style.borderRadius=``,be.classList.add(`persona-rounded-full`)),e.paddingX?(be.style.paddingLeft=e.paddingX,be.style.paddingRight=e.paddingX):(be.style.paddingLeft=``,be.style.paddingRight=``),e.paddingY?(be.style.paddingTop=e.paddingY,be.style.paddingBottom=e.paddingY):(be.style.paddingTop=``,be.style.paddingBottom=``);let n=e.tooltipText??`Clear chat`,r=e.showTooltip??!0;be.setAttribute(`aria-label`,n),xe&&br({anchor:be,trigger:xe,text:()=>be?.getAttribute(`aria-label`)??n,enabled:r})}}let Se=r.actionParsers&&r.actionParsers.length?r.actionParsers:[lg],Ce=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[dg.message,dg.messageAndClick];me=pg({parsers:Se,handlers:Ce,getSessionMetadata:ue,updateSessionMetadata:de,emit:A.emit,documentRef:typeof document<`u`?document:null}),Te=Yg(r,me,we),hc(),Q.updateConfig(r),cl(),(r.features?.history?.enabled===!0!==y||r.features?.history?.provider!==b||r.getIdentityProof!==x||r.clientToken!==S)&&(Lc?.closeHistory({restoreFocus:!1}),Lc?.installHistoryProvider()),Lc?.syncHistoryChromeImpl(),tl(),Uc()&&!Lc&&$c().catch(()=>{}),$o(G,Q.getMessages(),Te),ta(),rc(),nc(),js(Q.isStreaming()),C!==r.contextMentions&&of();let ke=r.voiceRecognition?.enabled===!0,Me=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),Ne=xs(r.voiceRecognition?.provider);if(ke&&(Me||Ne)){if(!Y||!jt){let e=ca(r);if(e){Y=e.button,jt=e.wrapper;let t=kt&&kt.parentElement===Ot?kt:null;Ot?Ot.insertBefore(jt,t):dt?.appendChild(jt),Qn&&(Qn.micButton=Y),Qn?.addListener(Y,`click`,Gu),Y.disabled=Ss()||Q.isStreaming()&&!Cs()}}else{let e=r.voiceRecognition??{},t=r.sendButton??{},n=e.iconName??`mic`,i=e.iconSize,a=parseFloat(i??``)||24;Y.classList.add(na),Y.classList.toggle(ra,!i),Y.style.width=i??``,Y.style.height=i??``,Y.style.minWidth=i??``,Y.style.minHeight=i??``;let o=e.iconColor??t.textColor;Y.innerHTML=``;let s=P(n,a,o||`currentColor`,1.5);s?Y.appendChild(s):Y.textContent=`🎤`;let c=e.backgroundColor??t.backgroundColor;c?Y.style.backgroundColor=c:Y.style.backgroundColor=``,o?Y.style.color=o:Y.style.color=`var(--persona-text, #111827)`,e.borderWidth?(Y.style.borderWidth=e.borderWidth,Y.style.borderStyle=`solid`):(Y.style.borderWidth=``,Y.style.borderStyle=``),e.borderColor?Y.style.borderColor=e.borderColor:Y.style.borderColor=``,e.paddingX?(Y.style.paddingLeft=e.paddingX,Y.style.paddingRight=e.paddingX):(Y.style.paddingLeft=``,Y.style.paddingRight=``),e.paddingY?(Y.style.paddingTop=e.paddingY,Y.style.paddingBottom=e.paddingY):(Y.style.paddingTop=``,Y.style.paddingBottom=``);let l=e.tooltipText??`Start voice recognition`,u=e.showTooltip??!1;Y.setAttribute(`aria-label`,l),jt&&br({anchor:Y,trigger:jt,text:()=>Y?.getAttribute(`aria-label`)??l,enabled:u}),jt.style.display=``,Y.disabled=Ss()||Q.isStreaming()&&!Cs()}}else Y&&jt&&(jt.style.display=`none`,xs(r.voiceRecognition?.provider)?Q.isVoiceActive()&&Q.toggleVoice():Yl&&Ru());if(td(),r.attachments?.enabled===!0){if(!Nt||!Mt){let e=r.attachments??{};Ft||(Ft=z(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`),Ft.style.display=`none`,(K.parentElement??dt).insertBefore(Ft,K)),Pt||(Pt=document.createElement(`input`),Pt.type=`file`,Pt.accept=(e.allowedTypes??Ui).join(`,`),Pt.multiple=(e.maxFiles??4)>1,Pt.style.display=`none`,Pt.setAttribute(`aria-label`,`Attach files`),(K.parentElement??dt).insertBefore(Pt,K)),Nt=z(`div`,`persona-send-button-wrapper`),Mt=z(`button`,`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${na} ${ra}`),Mt.type=`button`,Mt.setAttribute(`aria-label`,e.buttonTooltipText??`Attach file`);let t=e.buttonIconName??`paperclip`;Mt.style.fontSize=`18px`,Mt.style.lineHeight=`1`;let n=P(t,24,`currentColor`,1.5);n?Mt.appendChild(n):Mt.textContent=`📎`,Mt.addEventListener(`click`,e=>{e.preventDefault(),Pt?.click()}),Nt.appendChild(Mt);let i=e.buttonTooltipText??`Attach file`;br({anchor:Mt,trigger:Nt,text:()=>Mt?.getAttribute(`aria-label`)??i}),Dt?Dt.append(Nt):dt.appendChild(Nt),Qn&&(Qn.attachmentButton=Mt,Qn.attachmentInput=Pt??void 0,Qn.attachmentPreviews=Ft??void 0),!vn&&Pt&&Ft&&(vn=hl.fromConfig(e,Cn),vn.setPreviewsContainer(Ft),Qn?.addListener(Pt,`change`,async()=>{vn&&Pt?.files&&(await vn.handleFileSelect(Pt.files),Pt.value=``)}))}else{Nt.style.display=``;let e=r.attachments??{};Pt&&(Pt.accept=(e.allowedTypes??Ui).join(`,`),Pt.multiple=(e.maxFiles??4)>1),vn&&vn.updateConfig({allowedTypes:e.allowedTypes,maxFileSize:e.maxFileSize,maxFiles:e.maxFiles,adapter:e.adapter})}if(U.querySelector(`.persona-attachment-drop-overlay`)?.remove(),U.appendChild(Xg(r.attachments?.dropOverlay)),Mt){let e=r.attachments??{},t=e.buttonTooltipText??`Attach file`;Mt.setAttribute(`aria-label`,t),Mt.textContent=``;let n=P(e.buttonIconName??`paperclip`,24,`currentColor`,1.5);n?Mt.appendChild(n):Mt.textContent=`📎`,Nt&&br({anchor:Mt,trigger:Nt,text:()=>Mt?.getAttribute(`aria-label`)??t})}}else Nt&&(Nt.style.display=`none`),vn&&vn.clearAttachments(),U.querySelector(`.persona-attachment-drop-overlay`)?.remove();let Fe=r.sendButton??{},Ie=Fe.useIcon??!1,ze=Fe.iconText??`↑`,Ve=Fe.iconName,He=Fe.tooltipText??`Send message`,We=Fe.showTooltip??!1,Ge=Fe.size,Ke=parseFloat(Ge??``)||40,Ye=Fe.backgroundColor,Xe=Fe.textColor;if(Ie){if(q.style.width=Ge??``,q.style.height=Ge??``,q.style.minWidth=Ge??``,q.style.minHeight=Ge??``,q.style.fontSize=`18px`,q.style.lineHeight=`1`,Xe?q.style.color=Xe:q.style.color=`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`,!Q.isStreaming()){if(q.innerHTML=``,Ve){let e=parseFloat(Fe.iconSize??``)||Math.round(Ke*.5),t=Xe?.trim()||`currentColor`,n=Fe.iconStrokeWidth??2,r=P(Ve,e,t,n),i=P(Fe.stopIconName??`square`,e,t,n);r&&i?q.appendChild(oa(r,i)):r?q.appendChild(r):q.textContent=ze}else q.textContent=ze}q.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${na}`,Ye?(q.style.backgroundColor=Ye,q.classList.remove(`persona-bg-persona-primary`)):(q.style.backgroundColor=``,q.classList.add(`persona-bg-persona-primary`))}else q.textContent=r.copy?.sendButtonLabel??`Send`,q.style.width=``,q.style.height=``,q.style.minWidth=``,q.style.minHeight=``,q.style.fontSize=``,q.style.lineHeight=``,q.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`,Ye?(q.style.backgroundColor=Ye,q.classList.remove(`persona-bg-persona-accent`)):q.classList.add(`persona-bg-persona-accent`),Xe?q.style.color=Xe:q.classList.add(`persona-text-white`);Fe.borderWidth?(q.style.borderWidth=Fe.borderWidth,q.style.borderStyle=`solid`):(q.style.borderWidth=``,q.style.borderStyle=``),Fe.borderColor?q.style.borderColor=Fe.borderColor:q.style.borderColor=``,Fe.paddingX?(q.style.paddingLeft=Fe.paddingX,q.style.paddingRight=Fe.paddingX):(q.style.paddingLeft=``,q.style.paddingRight=``),Fe.paddingY?(q.style.paddingTop=Fe.paddingY,q.style.paddingBottom=Fe.paddingY):(q.style.paddingTop=``,q.style.paddingBottom=``),Q.isStreaming()||q.setAttribute(`aria-label`,He),Ds(),kt&&br({anchor:q,trigger:kt,text:()=>q.getAttribute(`aria-label`)??He,enabled:We}),gr(),xi();let B=uu(X.getState().activeModeIds,r.composer?.modes);X.setActiveModeIds(B),Tn().length>0!=!!Mn&&dr(),Mn?.render(B,Tn());for(let e of[...Nn.keys()])au(e,r.composer?.modeGroups)||Nn.delete(e);Nn.forEach(e=>e.repaint()),An?.repaint(),sr?.resolve();let $e=Ed(r,I());if(vi(),$e){G.style.maxWidth=$e,G.style.marginLeft=`auto`,G.style.marginRight=`auto`,G.style.width=`100%`,_t.style.maxWidth=$e,_t.style.marginLeft=`auto`,_t.style.marginRight=`auto`,_t.style.width=`100%`;for(let e of[dt,ut,Ft,ft])e&&(e.style.maxWidth=$e,e.style.marginLeft=`auto`,e.style.marginRight=`auto`,e.style.width=`100%`)}else{G.style.maxWidth=``,G.style.marginLeft=``,G.style.marginRight=``,G.style.width=``,_t.style.maxWidth=``,_t.style.marginLeft=``,_t.style.marginRight=``,_t.style.width=``;for(let e of[dt,ut,Ft,ft])e&&(e.style.maxWidth=``,e.style.marginLeft=``,e.style.marginRight=``,e.style.width=``)}let V=r.statusIndicator??{};if(Br(ft,dt,V),zr(ft,V,Q?.getStatus()??`idle`),Q){let e=Q.getStatus();rt(ft,(e=>e===`idle`?V.idleText??ln.idle:e===`connecting`?V.connectingText??ln.connecting:e===`connected`?V.connectedText??ln.connected:e===`error`?V.errorText??ln.error:e===`paused`?V.pausedText??ln.paused:e===`resuming`?V.resumingText??ln.resuming:ln[e])(e),V,e)}ft.classList.remove(`persona-text-left`,`persona-text-center`,`persona-text-right`);let et=V.align===`left`?`persona-text-left`:V.align===`center`?`persona-text-center`:`persona-text-right`;ft.classList.add(et),er(),As(),hr(),Ze()},open(){L()&&_s(!0,`api`)},close(){L()&&_s(!1,`api`)},toggle(){L()&&_s(!R,`api`)},reconnect(){Q.reconnectNow()},clearChat(){Ir=!1,o.clear(),i.clear(),a.clear(),s.clear(),Q.clearMessages(),r.layout?.topFade&&(W.scrollTop=0),W.removeAttribute(`data-persona-top-fade`),la.clear(),wo();try{localStorage.removeItem(zg),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${zg}`)}catch(e){console.error(`[AgentWidget] Failed to clear default localStorage:`,e)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==zg)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(e){console.error(`[AgentWidget] Failed to clear custom localStorage:`,e)}let e=new CustomEvent(`persona:clear-chat`,{detail:{timestamp:(/* @__PURE__ */ new Date()).toISOString()}});window.dispatchEvent(e),te?.clear&&no(()=>te.clear(),`[AgentWidget] Failed to clear storage adapter:`),re={},me.syncFromMetadata(),vn?.clearAttachments(),uo(),zn(void 0),Fn(void 0),ga(),Le?.clear(),Re?.reset(),He?.update()},setMessage(e){return!K||Q.isStreaming()||Ss()?!1:(!R&&L()&&_s(!0,`system`),K.value=e,K.dispatchEvent(new Event(`input`,{bubbles:!0})),!0)},submitMessage(e){if(Q.isStreaming()||ws())return!1;let t=e?.trim()||K.value.trim();return t?(!R&&L()&&_s(!0,`system`),K.value=``,K.style.height=`auto`,bn(),Pl(t,{consumeDraft:!1}),!0):!1},getComposerState(){return X.getState()},setQuote(e){let t=e?.text?.trim();t&&Fn({...e,text:t})},clearQuote(){Fn(void 0)},startVoiceRecognition(){return Q.isStreaming()?!1:xs(r.voiceRecognition?.provider)?(Q.isVoiceActive()||Q.isBargeInActive()||(!R&&L()&&_s(!0,`system`),$.manuallyDeactivated=!1,Xa(),Q.toggleVoice().then(()=>{$.active=qa(),Xa(),Ya(`user`),$.active&&Vu()})),!0):Yl?!0:Iu()?(!R&&L()&&_s(!0,`system`),$.manuallyDeactivated=!1,Xa(),Lu(`user`),!0):!1},stopVoiceRecognition(){return xs(r.voiceRecognition?.provider)?!Q.isVoiceActive()&&!Q.isBargeInActive()?!1:((Q.isBargeInActive()?Q.deactivateBargeIn():Q.toggleVoice()).then(()=>{$.active=!1,$.manuallyDeactivated=!0,Xa(),Ya(`user`),Wu()}),!0):Yl?($.manuallyDeactivated=!0,Xa(),Ru(`user`),!0):!1},injectMessage(e){return!R&&L()&&_s(!0,`system`),Q.injectMessage(e)},injectAssistantMessage(e){!R&&L()&&_s(!0,`system`);let t=Q.injectAssistantMessage(e);return Se&&(Se=!1,Ce&&=(clearTimeout(Ce),null),setTimeout(()=>{Q&&!Q.isStreaming()&&Q.continueConversation()},100)),t},injectUserMessage(e){return!R&&L()&&_s(!0,`system`),Q.injectUserMessage(e)},injectSystemMessage(e){return!R&&L()&&_s(!0,`system`),Q.injectSystemMessage(e)},injectMessageBatch(e){return!R&&L()&&_s(!0,`system`),Q.injectMessageBatch(e)},injectComponentDirective(e){return!R&&L()&&_s(!0,`system`),Q.injectComponentDirective(e)},injectTestMessage(e){!R&&L()&&_s(!0,`system`),Q.injectTestEvent(e)},async connectStream(e,t){return Q.connectStream(e,t)},__pushEventStreamEvent(e){Oe&&(Je(),qe(e.type,e.payload))},showEventStream(){Oe&&Gn()},hideEventStream(){Ue&&Kn()},isEventStreamVisible(){return Ue},listConversations(e){return Q.listConversations(e)},getActiveConversationId(){return Q.getActiveConversationId()},openConversation(e,t){return el(n=>n.openHistoryConversation(e,{focusComposer:t?.focus===!0}))},startNewConversation(e){return el(t=>t.startNewConversation({focusComposer:e?.focus===!0}))},warmSession(){nl()},deleteConversation(e){return el(t=>t.deleteHistoryConversation(e))},renameConversation(e,t){return el(n=>n.updateHistoryConversation(e,{title:t}))},setConversationStarred(e,t){return el(n=>n.updateHistoryConversation(e,{starred:t}))},clearConversationHistory(e){return el(t=>t.clearConversationHistory(e))},resetHistoryIdentity(){return el(e=>e.resetHistoryIdentity())},async getVisitorToken(){let e=fc;if(!e)return null;let t=await e.get();return e===fc?t:null},getHistoryIdentityStatus(){let e=Lc?.historyProvider;return e?e.getIdentityStatus():Uc()?{state:`unavailable`,reason:`ineligible_mode`}:{state:`unavailable`,reason:`history_disabled`}},showHistory(e){return Uc()?el(t=>t.openHistory({...e?.returnSurface?{returnSurface:e.returnSurface}:{},...e?.focus===void 0?{}:{focus:e.focus}})):Promise.resolve()},hideHistory(e){Lc?.closeHistory(e?.restoreFocus===void 0?void 0:{restoreFocus:e.restoreFocus})},isHistoryVisible(){return Ye},showArtifacts(){dh(r)&&(Ir=!1,Vr=!0,gi(),kr?.setMobileOpen(!0))},hideArtifacts(){dh(r)&&(Ir=!0,gi())},upsertArtifact(e){return dh(r)?(ke(r.features?.artifacts,{artifactType:e.artifactType,...e.artifactType===`markdown`&&e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}})===`panel`&&(Ir=!1,Vr=!0),Q.upsertArtifact(e)):null},selectArtifact(e){dh(r)&&Q.selectArtifact(e)},clearArtifacts(){dh(r)&&Q.clearArtifacts()},getArtifacts(){return Q?.getArtifacts()??[]},getSelectedArtifactId(){return Q?.getSelectedArtifactId()??null},focusInput(){return he&&!R&&!I()||!K?!1:(K.focus(),!0)},async resolveApproval(e,t,n){let r=Q.getMessages().find(t=>t.variant===`approval`&&t.approval?.id===e);if(!r?.approval)throw Error(`Approval not found: ${e}`);if(rs(r.approval))Q.resolveWebMcpApproval(r.id,t);else return Q.resolveApproval(r.approval,t,n)},setFollowUpSuggestions(e){aa(e)},clearFollowUpSuggestions(){ia()},getMessages(){return Q.getMessages()},getStatus(){return Q.getStatus()},getPersistentMetadata(){return{...re}},updatePersistentMetadata(e){de(e)},on(e,t){return A.on(e,t)},off(e,t){A.off(e,t)},isOpen(){return L()&&R},isVoiceActive(){return $.active},toggleReadAloud(e){Q.toggleReadAloud(e)},stopReadAloud(){Q.stopSpeaking()},getReadAloudState(e){return Q.getReadAloudState(e)},onReadAloudChange(e){return Q.onReadAloudChange(e)},getState(){return{open:L()&&R,launcherEnabled:he,voiceActive:$.active,streaming:Q.isStreaming()}},showCSATFeedback(e){!R&&L()&&_s(!0,`system`);let t=G.querySelector(`.persona-feedback-container`);t&&t.remove();let n=Lg({onSubmit:async(t,n)=>{Q.isClientTokenMode()&&await Q.submitCSATFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});G.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},showNPSFeedback(e){!R&&L()&&_s(!0,`system`);let t=G.querySelector(`.persona-feedback-container`);t&&t.remove();let n=Rg({onSubmit:async(t,n)=>{Q.isClientTokenMode()&&await Q.submitNPSFeedback(t,n),e?.onSubmit?.(t,n)},onDismiss:e?.onDismiss,...e});G.appendChild(n),n.scrollIntoView({behavior:`smooth`,block:`end`})},async submitCSATFeedback(e,t){return Q.submitCSATFeedback(e,t)},async submitNPSFeedback(e,t){return Q.submitNPSFeedback(e,t)},destroy(){Nc(),gc!=null&&(clearInterval(gc),gc=null),o.clear(),i.clear(),a.clear(),s.clear(),Z.forEach(e=>e()),at.remove(),ot?.remove(),od?.destroy(),sd?.remove(),Fi&&J.removeEventListener(`click`,Fi)}};if(((n?.debugTools??!1)||r.debug)&&typeof window<`u`){let e=window.AgentWidgetBrowser,t={controller:Mf,getMessages:Mf.getMessages,getStatus:Mf.getStatus,getMetadata:Mf.getPersistentMetadata,updateMetadata:Mf.updatePersistentMetadata,clearHistory:()=>Mf.clearChat(),setVoiceActive:e=>e?Mf.startVoiceRecognition():Mf.stopVoiceRecognition()};window.AgentWidgetBrowser=t,Z.push(()=>{window.AgentWidgetBrowser===t&&(window.AgentWidgetBrowser=e)})}if(typeof window<`u`){let t=e.getAttribute(`data-persona-instance`)||e.id||`persona-`+Math.random().toString(36).slice(2,8),n=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&Mf.focusInput()};if(window.addEventListener(`persona:focusInput`,n),Z.push(()=>{window.removeEventListener(`persona:focusInput`,n)}),Oe){let e=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&Mf.showEventStream()},n=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&Mf.hideEventStream()};window.addEventListener(`persona:showEventStream`,e),window.addEventListener(`persona:hideEventStream`,n),Z.push(()=>{window.removeEventListener(`persona:showEventStream`,e),window.removeEventListener(`persona:hideEventStream`,n)})}let r=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&Mf.showHistory()},i=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&Mf.hideHistory()};window.addEventListener(`persona:showHistory`,r),window.addEventListener(`persona:hideHistory`,i),Z.push(()=>{window.removeEventListener(`persona:showHistory`,r),window.removeEventListener(`persona:hideHistory`,i)});let a=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&Mf.showArtifacts()},o=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&Mf.hideArtifacts()},s=e=>{let n=e.detail;n?.instanceId&&n.instanceId!==t||n?.artifact&&Mf.upsertArtifact(n.artifact)},c=e=>{let n=e.detail;n?.instanceId&&n.instanceId!==t||typeof n?.id==`string`&&Mf.selectArtifact(n.id)},l=e=>{let n=e.detail;(!n?.instanceId||n.instanceId===t)&&Mf.clearArtifacts()};window.addEventListener(`persona:showArtifacts`,a),window.addEventListener(`persona:hideArtifacts`,o),window.addEventListener(`persona:upsertArtifact`,s),window.addEventListener(`persona:selectArtifact`,c),window.addEventListener(`persona:clearArtifacts`,l),Z.push(()=>{window.removeEventListener(`persona:showArtifacts`,a),window.removeEventListener(`persona:hideArtifacts`,o),window.removeEventListener(`persona:upsertArtifact`,s),window.removeEventListener(`persona:selectArtifact`,c),window.removeEventListener(`persona:clearArtifacts`,l)})}let Pf=Gg(r.persistState);if(Pf&&L()){let t=Kg(Pf.storage),n=`${Pf.keyPrefix}widget-open`,r=`${Pf.keyPrefix}widget-voice`,i=`${Pf.keyPrefix}widget-voice-mode`;if(t){let a=Pf.persist?.openState&&t.getItem(n)===`true`,o=Pf.persist?.voiceState&&t.getItem(r)===`true`,s=Pf.persist?.voiceState&&t.getItem(i)===`true`;if(a&&(od?.setPanelOpen(!0,`auto`),setTimeout(()=>{Mf.open(),setTimeout(()=>{if(o||s)Mf.startVoiceRecognition();else if(Pf.persist?.focusInput){let t=e.querySelector(`textarea`);t&&t.focus()}},100)},0)),Pf.persist?.openState&&(A.on(`widget:opened`,()=>{t.setItem(n,`true`)}),A.on(`widget:closed`,()=>{t.setItem(n,`false`)})),Pf.persist?.voiceState&&(A.on(`voice:state`,e=>{t.setItem(r,e.active?`true`:`false`)}),A.on(`user:message`,e=>{t.setItem(i,e.viaVoice?`true`:`false`)})),Pf.clearOnChatClear){let e=()=>{t.removeItem(n),t.removeItem(r),t.removeItem(i)},a=()=>e();window.addEventListener(`persona:clear-chat`,a),Z.push(()=>{window.removeEventListener(`persona:clear-chat`,a)})}}}if(se&&L()&&(od?.setPanelOpen(!0,`auto`),setTimeout(()=>{Mf.open()},0)),fs(),!ya){let e=E(()=>{Q&&(va++,la.clear(),$o(G,Q.getMessages(),Te))});Z.push(e)}b=()=>{Q&&(va++,la.clear(),$o(G,Q.getMessages(),Te))},Q.getMessages().length>0&&Qo(),D=()=>{Q&&(va++,la.clear(),$o(G,Q.getMessages(),Te))};let Ff=le(()=>{Q&&(va++,la.clear(),$o(G,Q.getMessages(),Te))});Z.push(Ff);let If=uh(()=>{Q&&(va++,la.clear(),$o(G,Q.getMessages(),Te),lh()?.updateInlineArtifactBlocks(G,Fr.artifacts,{suppressTransition:!0}),gi())});return Z.push(If),Mf};fn();const e_=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let i=/^(\d+(?:\.\d+)?)%$/i.exec(n);return i?Math.max(0,t*parseFloat(i[1])/100):420},t_=(e,t)=>{t===!1?e.style.maxHeight=``:(e.style.maxHeight=`100vh`,e.style.maxHeight=t)},n_=(e,t)=>{t===!1?(e.style.position=`relative`,e.style.top=``):(e.style.position=`sticky`,e.style.top=`0`)},r_=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement(`div`);r.style.cssText=`width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;`,n.appendChild(r);let i=r.offsetHeight>0;r.style.height=`100%`;let a=r.offsetHeight>0;r.remove(),i&&!a&&console.warn(`[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout.`+(t.maxHeight===!1?` The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.`:` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},i_=(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`},a_=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=``},o_=e=>{e.style.inset=``,e.style.width=``,e.style.height=``,e.style.maxWidth=``,e.style.maxHeight=``,e.style.minWidth=``,a_(e)},s_=e=>{e.style.transition=``},c_=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=``},l_=e=>{e.style.width=``,e.style.maxWidth=``,e.style.minWidth=``,e.style.flex=`1 1 auto`},u_=(e,t)=>{e.style.width=``,e.style.minWidth=`0`,e.style.maxWidth=``,e.style.boxSizing=``,t.style.alignItems=``},d_=(e,t,n,r,i)=>{i?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},f_=(e,t,n,r,i,a)=>{let o=a?t:e;i===`left`?o.firstElementChild!==r&&o.replaceChildren(r,n):o.lastElementChild!==r&&o.replaceChildren(n,r)},p_=e=>{let t=Sd(e),n=t.components?.panel,r=(e,n)=>e==null||e===``?n:Yu(t,e)??e;return{inset:r(n?.inset,ju),canvasBackground:r(n?.canvasBackground,Mu)}},m_=(e,t,n,r)=>{t?(e.style.boxSizing=`border-box`,e.style.padding=n,e.style.background=r):(e.style.padding=``,e.style.background=``,e.style.boxSizing=``)},h_=(e,t,n,r,i,a,o,s)=>{let c=jf(a),l=c.reveal===`push`,u=s!=null,d=s?.inset??``,f=s?.canvasBackground??``;d_(e,t,n,r,l),f_(e,t,n,r,c.side,l),e.dataset.personaHostLayout=`docked`,e.dataset.personaDockSide=c.side,e.dataset.personaDockOpen=o?`true`:`false`,e.style.width=`100%`,e.style.maxWidth=`100%`,e.style.minWidth=`0`,e.style.height=`100%`,e.style.minHeight=`0`,e.style.position=`relative`,n.style.display=`flex`,n.style.flexDirection=`column`,n.style.minHeight=`0`,n.style.position=`relative`,i.className=`persona-host`,i.style.height=`100%`,i.style.minHeight=`0`,i.style.minWidth=`0`,i.style.display=`flex`,i.style.flexDirection=`column`,i.style.flex=`1 1 auto`;let p=e.ownerDocument.defaultView,m=a?.launcher?.mobileFullscreen??!0,h=a?.launcher?.mobileBreakpoint??640,g=p!=null&&p.innerWidth<=h;if(m&&g&&o)e.dataset.personaDockMobileFullscreen=`true`,e.removeAttribute(`data-persona-dock-reveal`),c_(t),s_(r),o_(r),l_(n),u_(i,r),m_(r,!1,``,``),e.style.display=`flex`,e.style.flexDirection=`column`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,n.style.flex=`1 1 auto`,n.style.width=`100%`,n.style.minWidth=`0`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.position=`fixed`,r.style.inset=`0`,r.style.width=`100%`,r.style.height=`100%`,r.style.maxWidth=`100%`,r.style.minWidth=`0`,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.zIndex=String(a?.launcher?.zIndex??1e5),r.style.transform=`none`,r.style.transition=`none`,r.style.pointerEvents=`auto`,r.style.flex=`none`,l&&(t.style.display=`flex`,t.style.flexDirection=`column`,t.style.width=`100%`,t.style.height=`100%`,t.style.minHeight=`0`,t.style.minWidth=`0`,t.style.flex=`1 1 auto`,t.style.alignItems=`stretch`,t.style.transform=`none`,t.style.marginLeft=`0`,t.style.transition=`none`,n.style.flex=`1 1 auto`,n.style.width=`100%`,n.style.maxWidth=`100%`,n.style.minWidth=`0`);else if(e.removeAttribute(`data-persona-dock-mobile-fullscreen`),o_(r),t_(r,c.maxHeight),m_(r,u&&o,d,f),c.reveal===`overlay`){e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,e.dataset.personaDockReveal=`overlay`,c_(t),s_(r),l_(n),u_(i,r);let a=c.animate?`transform 180ms ease`:`none`,s=c.side===`right`?`translateX(100%)`:`translateX(-100%)`,l=o?`translateX(0)`:s;r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`none`,r.style.position=`absolute`,r.style.top=`0`,r.style.bottom=`0`,r.style.width=c.width,r.style.maxWidth=c.width,r.style.minWidth=c.width,r.style.minHeight=`0`,r.style.overflow=`hidden`,r.style.transition=a,r.style.transform=l,r.style.pointerEvents=o?`auto`:`none`,r.style.zIndex=`2`,c.side===`right`?(r.style.right=`0`,r.style.left=``):(r.style.left=`0`,r.style.right=``)}else if(c.reveal===`push`){e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=`hidden`,e.dataset.personaDockReveal=`push`,s_(r),a_(r),u_(i,r);let a=e_(c.width,e.clientWidth),s=Math.max(0,e.clientWidth),l=c.animate?`margin-left 180ms ease`:`none`,u=c.side===`right`?o?-a:0:o?0:-a;t.style.display=`flex`,t.style.flexDirection=`row`,t.style.flex=`0 0 auto`,t.style.minHeight=`0`,t.style.minWidth=`0`,t.style.alignItems=`stretch`,t.style.height=`100%`,t.style.width=`${s+a}px`,t.style.transition=l,t.style.marginLeft=`${u}px`,t.style.transform=``,n.style.flex=`0 0 auto`,n.style.flexGrow=`0`,n.style.flexShrink=`0`,n.style.width=`${s}px`,n.style.maxWidth=`${s}px`,n.style.minWidth=`${s}px`,r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 auto`,r.style.flexShrink=`0`,r.style.width=c.width,r.style.minWidth=c.width,r.style.maxWidth=c.width,r.style.position=`relative`,r.style.top=``,r.style.overflow=`hidden`,r.style.transition=`none`,r.style.pointerEvents=o?`auto`:`none`}else{e.style.display=`flex`,e.style.flexDirection=`row`,e.style.alignItems=`stretch`,e.style.overflow=``,c_(t),a_(r),l_(n),u_(i,r);let a=c.reveal===`emerge`;a?e.dataset.personaDockReveal=`emerge`:e.removeAttribute(`data-persona-dock-reveal`);let s=o?c.width:`0px`,l=c.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?`, padding 180ms ease`:``}`:`none`,f=!o;if(r.style.display=`flex`,r.style.flexDirection=`column`,r.style.flex=`0 0 ${s}`,r.style.width=s,r.style.maxWidth=s,r.style.minWidth=s,r.style.minHeight=`0`,n_(r,c.maxHeight),r.style.overflow=a||f?`hidden`:`visible`,r.style.transition=l,a){r.style.alignItems=c.side===`right`?`flex-start`:`flex-end`;let t=u?`calc(${e_(c.width,e.clientWidth)}px - (2 * ${d}))`:c.width;i.style.width=t,i.style.minWidth=t,i.style.maxWidth=t,i.style.boxSizing=`border-box`}}},g_=(e,t)=>{let n=e.ownerDocument.createElement(`div`);return i_(n,t),e.appendChild(n),{mode:`direct`,host:n,shell:null,syncWidgetState:()=>{},updateConfig(e){i_(n,e)},destroy(){n.remove()}}},__=(e,t)=>{let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw Error(`Docked widget target must be attached to the DOM`);let i=e.tagName.toUpperCase();if(i===`BODY`||i===`HTML`)throw Error(`Docked widget target must be a concrete container element, not "body" or "html"`);let a=e.nextSibling,o=n.createElement(`div`),s=n.createElement(`div`),c=n.createElement(`div`),l=n.createElement(`aside`),u=n.createElement(`div`),d=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;s.dataset.personaDockRole=`push-track`,c.dataset.personaDockRole=`content`,l.dataset.personaDockRole=`panel`,u.dataset.personaDockRole=`host`,l.appendChild(u),r.insertBefore(o,e),c.appendChild(e);let f=null,p=()=>{f?.disconnect(),f=null},m=null,h=()=>{m=t?.launcher?.detachedPanel===!0?p_(t):null};h();let g=()=>{h_(o,s,c,l,u,t,d,m)},_=null,v=()=>{_?.(),_=null,t?.launcher?.detachedPanel===!0&&t?.colorScheme===`auto`&&(_=Td(()=>{h(),g()}))},y=()=>{p(),jf(t).reveal===`push`&&typeof ResizeObserver<`u`&&(f=new ResizeObserver(()=>{g()}),f.observe(o))},b=!1,x=()=>{g(),y(),d&&!b&&o.dataset.personaDockMobileFullscreen!==`true`&&(b=!0,r_(o,jf(t)))},S=o.ownerDocument.defaultView,C=()=>{x()};return S?.addEventListener(`resize`,C),jf(t).reveal===`push`?(s.appendChild(c),s.appendChild(l),o.appendChild(s)):(o.appendChild(c),o.appendChild(l)),x(),v(),{mode:`docked`,host:u,shell:o,syncWidgetState(e){let t=!e.launcherEnabled||e.open;d!==t&&(d=t,x())},updateConfig(e){t=e,(t?.launcher?.enabled??!0)===!1&&(d=!0),h(),x(),v()},destroy(){S?.removeEventListener(`resize`,C),_?.(),_=null,p(),r.isConnected&&(a&&a.parentNode===r?r.insertBefore(e,a):r.appendChild(e)),o.remove()}}},v_=(e,t)=>kf(t)?__(e,t):g_(e,t),y_=e=>{if(typeof window>`u`||typeof document>`u`)throw Error(`Chat widget can only be mounted in a browser environment`);if(typeof e==`string`){let t=document.querySelector(e);if(!t)throw Error(`Chat widget target "${e}" was not found`);return t}return e},b_=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector(`link[data-persona]`))return;let n=t.head.querySelector(`link[data-persona]`);if(!n)return;let r=n.cloneNode(!0);e.insertBefore(r,e.firstChild)},x_=[],S_=()=>[...x_],C_=e=>{let t=y_(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,i=e.config,a=v_(t,i),o,s=[],c=(e,i)=>{let a=!(i?.launcher?.enabled??!0)||kf(i),o=r.createElement(`div`);if(o.setAttribute(`data-persona-root`,`true`),a&&(o.style.height=`100%`,o.style.display=`flex`,o.style.flexDirection=`column`,o.style.flex=`1`,o.style.minHeight=`0`,o.style.minWidth=`0`),n){let t=e.attachShadow({mode:`open`});t.appendChild(o),b_(t,r)}else e.appendChild(o),b_(e,r);return t.id&&o.setAttribute(`data-persona-instance`,t.id),o},l=()=>{a.syncWidgetState(o.getState())},u=()=>{s.forEach(e=>e()),s=[o.on(`widget:opened`,l),o.on(`widget:closed`,l)],l()},d=()=>{let t=c(a.host,i);o=$g(t,i,{debugTools:e.debugTools}),u()},f=()=>{s.forEach(e=>e()),s=[],o.destroy()};d(),e.onChatReady?.();let p=e=>{f(),a.destroy(),a=v_(t,e),i=e,d()},m=new Proxy({update(e){let t=ag(i??{},e),n=kf(i),r=kf(t),s=Af(i),c=Af(t);n!==r||s!==c?p(t):(i=t,a.updateConfig(i),o.update(e),l())},destroy(){f(),a.destroy();let t=x_.indexOf(m);t!==-1&&x_.splice(t,1),e.windowKey&&typeof window<`u`&&delete window[e.windowKey]}},{get(e,t,n){if(t===`host`)return a.host;if(t in e)return Reflect.get(e,t,n);let r=o[t];return typeof r==`function`?r.bind(o):r}});return x_.push(m),e.windowKey&&typeof window<`u`&&(window[e.windowKey]=m),m},w_=/* @__PURE__ */ new Set([`script`,`style`,`noscript`,`svg`,`path`,`meta`,`link`,`br`,`hr`]),T_=/* @__PURE__ */ new Set([`button`,`a`,`input`,`select`,`textarea`,`details`,`summary`]),E_=/* @__PURE__ */ new Set([`button`,`link`,`menuitem`,`tab`,`option`,`switch`,`checkbox`,`radio`,`combobox`,`listbox`,`slider`,`spinbutton`,`textbox`]),D_=/\b(product|card|item|listing|result)\b/i,O_=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i;function k_(e){let t=typeof e.className==`string`?e.className:``;if(D_.test(t)||e.id&&D_.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith(`data-`)&&D_.test(n.value))return!0}return!1}function A_(e){return O_.test((e.textContent??``).trim())}function j_(e){let t=e.querySelectorAll(`a[href]`);for(let e=0;e<t.length;e++){let n=t[e].getAttribute(`href`)??``;if(n&&n!==`#`&&!n.toLowerCase().startsWith(`javascript:`))return!0}return!1}function M_(e){return!!e.querySelector(`button, [role="button"], input[type="submit"], input[type="button"]`)}function N_(e){let t=e.match(O_);return t?t[0]:null}function P_(e){let t=e.querySelector(`.product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]`)??e.querySelector(`a[href]`);if(t&&t.textContent?.trim()){let e=t.getAttribute(`href`);return{title:t.textContent.trim(),href:e&&e!==`#`?e:null}}let n=e.querySelector(`h1, h2, h3, h4, h5, h6`);return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:``,href:null}}function F_(e){let t=[],n=e=>{let n=e.trim();n&&!t.includes(n)&&t.push(n)};return e.querySelectorAll(`button`).forEach(e=>n(e.textContent??``)),e.querySelectorAll(`[role="button"]`).forEach(e=>n(e.textContent??``)),e.querySelectorAll(`input[type="submit"], input[type="button"]`).forEach(e=>{n(e.value??``)}),t.slice(0,6)}function I_(e){return!k_(e)||!A_(e)||!j_(e)&&!M_(e)?0:5200}function L_(e){return!k_(e)||A_(e)||!j_(e)||(e.textContent??``).trim().length<20||!(e.querySelector(`h1, h2, h3, h4, h5, h6, .title`)||e.querySelector(`.snippet, .description, p`))?0:2800}const R_=[{id:`commerce-card`,scoreElement(e){return I_(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity===`static`){let e=n.text.trim();return!!(e.length===0||O_.test(e)&&e.length<32)}return!0},formatSummary(e,t){if(I_(e)===0)return null;let{title:n,href:r}=P_(e),i=N_((e.textContent??``).trim())??N_(t.text)??``,a=F_(e);return[r&&n?`[${n}](${r})${i?`: ${i}`:``}`:n?`${n}${i?`: ${i}`:``}`:i||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(`, `)}`:``].filter(Boolean).join(`
135
+ `)}},{id:`result-card`,scoreElement(e){return L_(e)},formatSummary(e,t){if(L_(e)===0)return null;let{title:n,href:r}=P_(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
136
+ `)}}];function z_(){typeof console<`u`&&typeof console.warn==`function`&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function B_(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,r=t.excludeSelector??e.excludeSelector??`.persona-host`,i=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,o=t.root??e.root,s=t.mode??`structured`,c=t.maxCandidates??Math.max(500,n*10),l=e.rules??R_;return s===`simple`&&e.rules&&e.rules.length>0?(z_(),l=[]):s===`simple`&&(l=[]),{mode:s,maxElements:n,maxCandidates:c,excludeSelector:r,maxTextLength:i,visibleOnly:a,root:o,rules:l}}function V_(e){return typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/([^\w-])/g,`\\$1`)}const H_=[`data-testid`,`data-product`,`data-action`,`data-id`,`data-name`,`data-type`];function U_(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`||T_.has(t)||n&&E_.has(n)||e.hasAttribute(`tabindex`)||e.hasAttribute(`onclick`)||e.getAttribute(`contenteditable`)===`true`?`clickable`:`static`}function W_(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 G_(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute(`href`);r&&(t.href=r);let i=e.getAttribute(`aria-label`);i&&(t[`aria-label`]=i);let a=e.getAttribute(`type`);a&&(t.type=a);let o=e.getAttribute(`value`);o&&(t.value=o);let s=e.getAttribute(`name`);s&&(t.name=s);let c=e.getAttribute(`role`);c&&(t.role=c);for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];r.name.startsWith(`data-`)&&(t[r.name]=r.value)}return t}function K_(e){let t=e.tagName.toLowerCase();if(e.id){let t=`#${V_(e.id)}`;try{if(e.ownerDocument.querySelectorAll(t).length===1)return t}catch{}}for(let n of H_){let r=e.getAttribute(n);if(r){let i=`${t}[${n}="${V_(r)}"]`;try{if(e.ownerDocument.querySelectorAll(i).length===1)return i}catch{}}}let n=Array.from(e.classList).filter(e=>e&&!e.startsWith(`persona-`)).slice(0,3);if(n.length>0){let r=`${t}.${n.map(e=>V_(e)).join(`.`)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let i=e.parentElement;if(i){let n=Array.from(i.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(n>=0){let t=`${r}:nth-of-type(${n+1})`;try{if(e.ownerDocument.querySelectorAll(t).length===1)return t}catch{}}}}let r=e.parentElement;if(r){let n=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(n>=0)return`${t}:nth-of-type(${n+1})`}return t}function q_(e){return e===`static`?100:3e3}function J_(e,t){let n=e.tagName.toLowerCase(),r=(e.textContent??``).trim().substring(0,t);return{selector:K_(e),tagName:n,text:r,role:e.getAttribute(`role`),interactivity:U_(e),attributes:G_(e)}}function Y_(e,t,n,r){let i=q_(t.interactivity),a=null;for(let o of n){let n=o.scoreElement(e,t,r);n>0&&(i+=n,o.formatSummary&&!a&&(a=o))}return{score:i,formattingRule:a}}function X_(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 Z_(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=/* @__PURE__ */ new Set,i=[],a=0,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&i.length<e.maxCandidates;){if(s.nodeType===Node.ELEMENT_NODE){let t=s,c=t.tagName.toLowerCase();if(w_.has(c)){s=o.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!W_(t)){s=o.nextNode();continue}let l=J_(t,e.maxTextLength),u=l.text.length>0,d=Object.keys(l.attributes).length>0&&!Object.keys(l.attributes).every(e=>e===`role`);if(!u&&!d||r.has(l.selector)){s=o.nextNode();continue}r.add(l.selector);let{score:f,formattingRule:p}=Y_(t,l,e.rules,n);i.push({el:t,domIndex:a,enriched:l,score:f,formattingRule:p}),a+=1}s=o.nextNode()}i.sort((e,t)=>{let n=+(e.enriched.interactivity===`static`),r=+(t.enriched.interactivity===`static`);return n===r?t.score===e.score?e.domIndex-t.domIndex:t.score-e.score:n-r});let c=[];for(let t of i){if(c.length>=e.maxElements)break;X_(c,t)||c.push(t)}return c.sort((e,t)=>{let n=+(e.enriched.interactivity===`static`),r=+(t.enriched.interactivity===`static`);return n===r?n===1&&t.score!==e.score?t.score-e.score:e.domIndex-t.domIndex:n-r}),c.map(e=>{let t;if(e.formattingRule?.formatSummary){let r=e.formattingRule.formatSummary(e.el,e.enriched,n);r&&(t=r)}let r={...e.enriched};return t&&(r.formattedSummary=t),r})}function Q_(e,t){let n=[],r=/* @__PURE__ */ new Set,i=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=i.currentNode;for(;a&&n.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let t=a,o=t.tagName.toLowerCase();if(w_.has(o)){a=i.nextNode();continue}if(e.excludeSelector)try{if(t.closest(e.excludeSelector)){a=i.nextNode();continue}}catch{}if(e.visibleOnly&&!W_(t)){a=i.nextNode();continue}let s=J_(t,e.maxTextLength),c=s.text.length>0,l=Object.keys(s.attributes).length>0&&!Object.keys(s.attributes).every(e=>e===`role`);if(!c&&!l){a=i.nextNode();continue}r.has(s.selector)||(r.add(s.selector),n.push(s))}a=i.nextNode()}let o=[],s=[];for(let e of n)e.interactivity===`static`?s.push(e):o.push(e);return[...o,...s].slice(0,e.maxElements)}function $_(e={}){let t=B_(e),n=t.root??document.body;return n?t.mode===`simple`?Q_(t,n):Z_(t,n):[]}function ev(e,t={}){if(e.length===0)return`No page elements found.`;let n=t.mode??`structured`,r=[];if(n===`structured`){let t=e.map(e=>e.formattedSummary).filter(e=>!!e&&e.length>0);t.length>0&&r.push(`Structured summaries:\n${t.map(e=>`- ${e.split(`
137
137
  `).join(`
138
138
  `)}`).join(`
139
139
  `)}`)}let i={clickable:[],navigable:[],input:[],static:[]};for(let t of e)n===`structured`&&t.formattedSummary||i[t.interactivity].push(t);if(i.clickable.length>0){let e=i.clickable.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}" (clickable)`);r.push(`Interactive elements:\n${e.join(`
@@ -142,7 +142,7 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
142
142
  `)}`)}if(i.static.length>0){let e=i.static.map(e=>`- ${e.selector}: "${e.text.substring(0,100)}"`);r.push(`Content:\n${e.join(`
143
143
  `)}`)}return r.join(`
144
144
 
145
- `)}wi();const J_={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`}}},Y_={components:{panel:{borderRadius:`0`,shadow:`none`}}},X_={id:`shop`,label:`Shopping Assistant`,config:{theme:J_,launcher:{title:`Shopping Assistant`,subtitle:`Here to help you find what you need`,agentIconText:`🛍️`,position:`bottom-right`,width:pi},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`]}},Z_={id:`minimal`,label:`Minimal`,config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:`minimal`,showCloseButton:!1},messages:{layout:`minimal`}},theme:Y_}},Q_={id:`fullscreen`,label:`Fullscreen Assistant`,config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:`minimal`,showCloseButton:!1},contentMaxWidth:`72ch`},theme:Y_}},$_={shop:X_,minimal:Z_,fullscreen:Q_};function ev(e){return $_[e]}Ae(),Gt(),sn(),nn(),Ce(),Ze(),Ui(),An(),I(),wi();var tv=g_;function nv(){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 rv(){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 iv(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:sv(e.colors.primary,.95),100:sv(e.colors.primary,.9),200:sv(e.colors.primary,.8),300:sv(e.colors.primary,.7),400:sv(e.colors.primary,.6),500:e.colors.primary,600:sv(e.colors.primary,.8),700:sv(e.colors.primary,.7),800:sv(e.colors.primary,.6),900:sv(e.colors.primary,.5),950:sv(e.colors.primary,.45)}}),{...t,palette:n}}}}function av(){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 ov(){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 sv(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),i=parseInt(e.slice(5,7),16),a=Math.round(n+(255-n)*(1-t)),o=Math.round(r+(255-r)*(1-t)),s=Math.round(i+(255-i)*(1-t));return`#${a.toString(16).padStart(2,`0`)}${o.toString(16).padStart(2,`0`)}${s.toString(16).padStart(2,`0`)}`}function cv(e){return{name:e.name,version:e.version,transform:e.transform||(e=>e),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}An();function lv(e){return e?.cdnBase?.trim().replace(/\/+$/,``).replace(/[\\'"<>`]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`)}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${kn}/dist`}function uv(e){if(e!==void 0)return typeof e==`string`?e:Array.isArray(e)?`[${e.map(e=>e.toString()).join(`, `)}]`:e.toString()}function dv(e){if(e)return{getHeaders:uv(e.getHeaders),onFeedback:uv(e.onFeedback),onCopy:uv(e.onCopy),requestMiddleware:uv(e.requestMiddleware),actionHandlers:uv(e.actionHandlers),actionParsers:uv(e.actionParsers),postprocessMessage:uv(e.postprocessMessage),contextProviders:uv(e.contextProviders),streamParser:uv(e.streamParser)}}const fv=`({ text, message }: any) => {
145
+ `)}Ti();const tv={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`}}},nv={components:{panel:{borderRadius:`0`,shadow:`none`}}},rv={id:`shop`,label:`Shopping Assistant`,config:{theme:tv,launcher:{title:`Shopping Assistant`,subtitle:`Here to help you find what you need`,agentIconText:`🛍️`,position:`bottom-right`,width:mi},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`]}},iv={id:`minimal`,label:`Minimal`,config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:`minimal`,showCloseButton:!1},messages:{layout:`minimal`}},theme:nv}},av={id:`fullscreen`,label:`Fullscreen Assistant`,config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:`minimal`,showCloseButton:!1},contentMaxWidth:`72ch`},theme:nv}},ov={shop:rv,minimal:iv,fullscreen:av};function sv(e){return ov[e]}je(),Kt(),cn(),rn(),we(),Qe(),Wi(),Va(),jn(),F(),Ti();var cv=C_;function lv(){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 uv(){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 dv(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:mv(e.colors.primary,.95),100:mv(e.colors.primary,.9),200:mv(e.colors.primary,.8),300:mv(e.colors.primary,.7),400:mv(e.colors.primary,.6),500:e.colors.primary,600:mv(e.colors.primary,.8),700:mv(e.colors.primary,.7),800:mv(e.colors.primary,.6),900:mv(e.colors.primary,.5),950:mv(e.colors.primary,.45)}}),{...t,palette:n}}}}function fv(){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 pv(){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 mv(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),i=parseInt(e.slice(5,7),16),a=Math.round(n+(255-n)*(1-t)),o=Math.round(r+(255-r)*(1-t)),s=Math.round(i+(255-i)*(1-t));return`#${a.toString(16).padStart(2,`0`)}${o.toString(16).padStart(2,`0`)}${s.toString(16).padStart(2,`0`)}`}function hv(e){return{name:e.name,version:e.version,transform:e.transform||(e=>e),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}jn();function gv(e){return e?.cdnBase?.trim().replace(/\/+$/,``).replace(/[\\'"<>`]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`)}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${An}/dist`}function _v(e){if(e!==void 0)return typeof e==`string`?e:Array.isArray(e)?`[${e.map(e=>e.toString()).join(`, `)}]`:e.toString()}function vv(e){if(e)return{getHeaders:_v(e.getHeaders),onFeedback:_v(e.onFeedback),onCopy:_v(e.onCopy),requestMiddleware:_v(e.requestMiddleware),actionHandlers:_v(e.actionHandlers),actionParsers:_v(e.actionParsers),postprocessMessage:_v(e.postprocessMessage),contextProviders:_v(e.contextProviders),streamParser:_v(e.streamParser)}}const yv=`({ text, message }: any) => {
146
146
  const jsonSource = (message as any).rawContent || text || message.content;
147
147
  if (!jsonSource || typeof jsonSource !== 'string') return null;
148
148
  let cleanJson = jsonSource
@@ -155,7 +155,7 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
155
155
  if (parsed.action) return { type: parsed.action, payload: parsed };
156
156
  } catch (e) { return null; }
157
157
  return null;
158
- }`,pv=`function(ctx) {
158
+ }`,bv=`function(ctx) {
159
159
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
160
160
  if (!jsonSource || typeof jsonSource !== 'string') return null;
161
161
  var cleanJson = jsonSource
@@ -168,7 +168,7 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
168
168
  if (parsed.action) return { type: parsed.action, payload: parsed };
169
169
  } catch (e) { return null; }
170
170
  return null;
171
- }`,mv=`(action: any, context: any) => {
171
+ }`,xv=`(action: any, context: any) => {
172
172
  if (action.type !== 'nav_then_click') return;
173
173
  const payload = action.payload || action.raw || {};
174
174
  const url = payload?.page;
@@ -185,7 +185,7 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
185
185
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
186
186
  window.location.href = targetUrl;
187
187
  return { handled: true, displayText: text };
188
- }`,hv=`function(action, context) {
188
+ }`,Sv=`function(action, context) {
189
189
  if (action.type !== 'nav_then_click') return;
190
190
  var payload = action.payload || action.raw || {};
191
191
  var url = payload.page;
@@ -202,27 +202,27 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
202
202
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
203
203
  window.location.href = targetUrl;
204
204
  return { handled: true, displayText: text };
205
- }`;function gv(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 _v(e){return e.parserType??gv(e.streamParser)??`plain`}function vv(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([e,r])=>{typeof r==`string`&&n.push(`${t} ${e}: "${r}",`)}),n.push(`${t}},`)),n}function yv(e,t,n){let r=[],i=e.messageActions&&Object.entries(e.messageActions).some(([e,t])=>e!==`onFeedback`&&e!==`onCopy`&&t!==void 0),a=n?.onFeedback||n?.onCopy;return(i||a)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([e,n])=>{e!==`onFeedback`&&e!==`onCopy`&&(typeof n==`string`?r.push(`${t} ${e}: "${n}",`):typeof n==`boolean`&&r.push(`${t} ${e}: ${n},`))}),n?.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function bv(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,i=e.markdown.disableDefaultStyles!==void 0;(r||i)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([e,r])=>{typeof r==`string`?n.push(`${t} ${e}: "${r}",`):typeof r==`boolean`&&n.push(`${t} ${e}: ${r},`)}),n.push(`${t} },`)),i&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function xv(e,t){if(!e.suggestions)return[];let n=JSON.stringify(e.suggestions,null,2).split(`
206
- `);return n.map((e,r)=>`${r===0?`${t}suggestions: `:t}${e}${r===n.length-1?`,`:``}`)}function Sv(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(e=>e!==`render`),i=e.layout.messages&&Object.keys(e.layout.messages).some(e=>e!==`renderUserMessage`&&e!==`renderAssistantMessage`);(r||i)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([e,r])=>{e!==`render`&&(typeof r==`string`?n.push(`${t} ${e}: "${r}",`):typeof r==`boolean`&&n.push(`${t} ${e}: ${r},`))}),n.push(`${t} },`)),i&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([e,r])=>{e!==`renderUserMessage`&&e!==`renderAssistantMessage`&&(e===`avatar`&&typeof r==`object`&&r?(n.push(`${t} avatar: {`),Object.entries(r).forEach(([e,r])=>{typeof r==`string`?n.push(`${t} ${e}: "${r}",`):typeof r==`boolean`&&n.push(`${t} ${e}: ${r},`)}),n.push(`${t} },`)):e===`timestamp`&&typeof r==`object`&&r?Object.entries(r).some(([e])=>e!==`format`)&&(n.push(`${t} timestamp: {`),Object.entries(r).forEach(([e,r])=>{e!==`format`&&(typeof r==`string`?n.push(`${t} ${e}: "${r}",`):typeof r==`boolean`&&n.push(`${t} ${e}: ${r},`))}),n.push(`${t} },`)):typeof r==`string`?n.push(`${t} ${e}: "${r}",`):typeof r==`boolean`&&n.push(`${t} ${e}: ${r},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Cv(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 wv(e,t,n){Object.entries(t).forEach(([t,r])=>{r!==void 0&&typeof r!=`function`&&(Array.isArray(r)?e.push(`${n}${t}: ${JSON.stringify(r)},`):r&&typeof r==`object`?(e.push(`${n}${t}: {`),wv(e,r,`${n} `),e.push(`${n}},`)):e.push(`${n}${t}: ${JSON.stringify(r)},`))})}function Tv(e,t,n,r){n&&(e.push(`${r}${t}: {`),wv(e,n,`${r} `),e.push(`${r}},`))}function Ev(e,t,n){t.future?.v5Defaults!==void 0&&e.push(`${n}future: { v5Defaults: ${t.future.v5Defaults===!0} },`)}function Dv(e){return(e?.target??`body`).replace(/\\/g,`\\\\`).replace(/'/g,`\\'`)}function Ov(e,t=`esm`,n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let i=n?{...n,hooks:dv(n.hooks)}:void 0;return t===`esm`?kv(r,i):t===`script-installer`?Nv(r,i):t===`script-advanced`?Fv(r,i):t===`react-component`?Av(r,i):t===`react-advanced`?jv(r,i):Pv(r,i)}function kv(e,t){let n=t?.hooks,r=_v(e),i=r!==`plain`,a=[`import '@runtypelabs/persona/widget.css';`,`import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';`,``,`initAgentWidget({`,` target: '${Dv(t)}',`,` config: {`];return e.apiUrl&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.agentId&&a.push(` agentId: "${e.agentId}",`),e.target&&a.push(` target: "${e.target}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),i&&a.push(` parserType: "${r}",`),Ev(a,e,` `),e.theme&&typeof e.theme==`object`&&Object.keys(e.theme).length>0&&Tv(a,`theme`,e.theme,` `),e.launcher&&Tv(a,`launcher`,e.launcher,` `),e.copy&&(a.push(` copy: {`),Object.entries(e.copy).forEach(([e,t])=>{a.push(` ${e}: "${t}",`)}),a.push(` },`)),e.sendButton&&(a.push(` sendButton: {`),Object.entries(e.sendButton).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):typeof t==`boolean`&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.voiceRecognition&&(a.push(` voiceRecognition: {`),Object.entries(e.voiceRecognition).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):(typeof t==`boolean`||typeof t==`number`)&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.statusIndicator&&(a.push(` statusIndicator: {`),Object.entries(e.statusIndicator).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):typeof t==`boolean`&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.features&&(a.push(` features: {`),Object.entries(e.features).forEach(([e,t])=>{a.push(` ${e}: ${t},`)}),a.push(` },`)),a.push(...xv(e,` `)),e.suggestionChips&&e.suggestionChips.length>0&&(a.push(` suggestionChips: [`),e.suggestionChips.forEach(e=>{a.push(` "${e}",`)}),a.push(` ],`)),e.suggestionChipsConfig&&(a.push(` suggestionChipsConfig: {`),e.suggestionChipsConfig.fontFamily&&a.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&a.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&a.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&a.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),a.push(` },`)),a.push(...vv(e,` `)),a.push(...yv(e,` `,n)),a.push(...bv(e,` `)),a.push(...Sv(e,` `)),a.push(...Cv(n,` `)),e.debug&&a.push(` debug: ${e.debug},`),n?.postprocessMessage?a.push(` postprocessMessage: ${n.postprocessMessage}`):a.push(` postprocessMessage: ({ text }) => markdownPostprocessor(text)`),a.push(` }`),a.push(`});`),a.join(`
207
- `)}function Av(e,t){let n=t?.hooks,r=_v(e),i=r!==`plain`,a=[`// ChatWidget.tsx`,`'use client'; // Required for Next.js - remove for Vite/CRA`,``,`import { useEffect } from 'react';`,`import '@runtypelabs/persona/widget.css';`,`import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';`,`import type { AgentWidgetInitHandle } from '@runtypelabs/persona';`,``,`export function ChatWidget() {`,` useEffect(() => {`,` let handle: AgentWidgetInitHandle | null = null;`,``,` handle = initAgentWidget({`,` target: '${Dv(t)}',`,` config: {`];return e.apiUrl&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.agentId&&a.push(` agentId: "${e.agentId}",`),e.target&&a.push(` target: "${e.target}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),i&&a.push(` parserType: "${r}",`),Ev(a,e,` `),e.theme&&typeof e.theme==`object`&&Object.keys(e.theme).length>0&&Tv(a,`theme`,e.theme,` `),e.launcher&&Tv(a,`launcher`,e.launcher,` `),e.copy&&(a.push(` copy: {`),Object.entries(e.copy).forEach(([e,t])=>{a.push(` ${e}: "${t}",`)}),a.push(` },`)),e.sendButton&&(a.push(` sendButton: {`),Object.entries(e.sendButton).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):typeof t==`boolean`&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.voiceRecognition&&(a.push(` voiceRecognition: {`),Object.entries(e.voiceRecognition).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):(typeof t==`boolean`||typeof t==`number`)&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.statusIndicator&&(a.push(` statusIndicator: {`),Object.entries(e.statusIndicator).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):typeof t==`boolean`&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.features&&(a.push(` features: {`),Object.entries(e.features).forEach(([e,t])=>{a.push(` ${e}: ${t},`)}),a.push(` },`)),a.push(...xv(e,` `)),e.suggestionChips&&e.suggestionChips.length>0&&(a.push(` suggestionChips: [`),e.suggestionChips.forEach(e=>{a.push(` "${e}",`)}),a.push(` ],`)),e.suggestionChipsConfig&&(a.push(` suggestionChipsConfig: {`),e.suggestionChipsConfig.fontFamily&&a.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&a.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&a.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&a.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),a.push(` },`)),a.push(...vv(e,` `)),a.push(...yv(e,` `,n)),a.push(...bv(e,` `)),a.push(...Sv(e,` `)),a.push(...Cv(n,` `)),e.debug&&a.push(` debug: ${e.debug},`),n?.postprocessMessage?a.push(` postprocessMessage: ${n.postprocessMessage}`):a.push(` postprocessMessage: ({ text }) => markdownPostprocessor(text)`),a.push(` }`),a.push(` });`),a.push(``),a.push(` // Cleanup on unmount`),a.push(` return () => {`),a.push(` if (handle) {`),a.push(` handle.destroy();`),a.push(` }`),a.push(` };`),a.push(` }, []);`),a.push(``),a.push(` return null; // Widget injects itself into the DOM`),a.push(`}`),a.push(``),a.push(`// Usage in your app:`),a.push(`// import { ChatWidget } from './components/ChatWidget';`),a.push(`//`),a.push(`// export default function App() {`),a.push(`// return (`),a.push(`// <div>`),a.push(`// {/* Your app content */}`),a.push(`// <ChatWidget />`),a.push(`// </div>`),a.push(`// );`),a.push(`// }`),a.join(`
208
- `)}function jv(e,t){let n=t?.hooks,r=[`// ChatWidgetAdvanced.tsx`,`'use client'; // Required for Next.js - remove for Vite/CRA`,``,`import { useEffect } from 'react';`,`import '@runtypelabs/persona/widget.css';`,`import {`,` initAgentWidget,`,` createFlexibleJsonStreamParser,`,` defaultJsonActionParser,`,` defaultActionHandlers,`,` markdownPostprocessor`,`} from '@runtypelabs/persona';`,`import type { AgentWidgetInitHandle } from '@runtypelabs/persona';`,``,`const STORAGE_KEY = 'chat-widget-state';`,`const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';`,``,`// Types for DOM elements`,`interface PageElement {`,` type: string;`,` tagName: string;`,` selector: string;`,` innerText: string;`,` href?: string;`,`}`,``,`interface DOMContext {`,` page_elements: PageElement[];`,` page_element_count: number;`,` element_types: Record<string, number>;`,` page_url: string;`,` page_title: string;`,` timestamp: string;`,`}`,``,`// DOM context provider - extracts page elements for AI context`,`const collectDOMContext = (): DOMContext => {`,` const selectors = {`,` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`,` links: 'a[href]',`,` inputs: 'input, textarea, select'`,` };`,``,` const elements: PageElement[] = [];`,` Object.entries(selectors).forEach(([type, selector]) => {`,` document.querySelectorAll(selector).forEach((element) => {`,` if (!(element instanceof HTMLElement)) return;`,` `,` // Exclude elements within the widget`,` const widgetHost = element.closest('.persona-host');`,` if (widgetHost) return;`,` `,` const text = element.innerText?.trim();`,` if (!text) return;`,``,` const selectorString =`," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :",` element.tagName.toLowerCase();`,``,` const elementData: PageElement = {`,` type,`,` tagName: element.tagName.toLowerCase(),`,` selector: selectorString,`,` innerText: text.substring(0, 200)`,` };`,``,` if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {`,` elementData.href = element.href;`,` }`,``,` elements.push(elementData);`,` });`,` });`,``,` const counts = elements.reduce((acc, el) => {`,` acc[el.type] = (acc[el.type] || 0) + 1;`,` return acc;`,` }, {} as Record<string, number>);`,``,` return {`,` page_elements: elements.slice(0, 50),`,` page_element_count: elements.length,`,` element_types: counts,`,` page_url: window.location.href,`,` page_title: document.title,`,` timestamp: new Date().toISOString()`,` };`,`};`,``,`export function ChatWidgetAdvanced() {`,` useEffect(() => {`,` let handle: AgentWidgetInitHandle | null = null;`,``,` // Load saved state`,` const loadSavedMessages = () => {`,` const savedState = localStorage.getItem(STORAGE_KEY);`,` if (savedState) {`,` try {`,` const { messages } = JSON.parse(savedState);`,` return messages || [];`,` } catch (e) {`,` console.error('Failed to load saved state:', e);`,` }`,` }`,` return [];`,` };`,``,` handle = initAgentWidget({`,` target: '${Dv(t)}',`,` config: {`];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),Ev(r,e,` `),e.theme&&typeof e.theme==`object`&&Object.keys(e.theme).length>0&&Tv(r,`theme`,e.theme,` `),e.launcher&&Tv(r,`launcher`,e.launcher,` `),e.copy&&(r.push(` copy: {`),Object.entries(e.copy).forEach(([e,t])=>{r.push(` ${e}: "${t}",`)}),r.push(` },`)),e.sendButton&&(r.push(` sendButton: {`),Object.entries(e.sendButton).forEach(([e,t])=>{typeof t==`string`?r.push(` ${e}: "${t}",`):typeof t==`boolean`&&r.push(` ${e}: ${t},`)}),r.push(` },`)),e.voiceRecognition&&(r.push(` voiceRecognition: {`),Object.entries(e.voiceRecognition).forEach(([e,t])=>{typeof t==`string`?r.push(` ${e}: "${t}",`):(typeof t==`boolean`||typeof t==`number`)&&r.push(` ${e}: ${t},`)}),r.push(` },`)),e.statusIndicator&&(r.push(` statusIndicator: {`),Object.entries(e.statusIndicator).forEach(([e,t])=>{typeof t==`string`?r.push(` ${e}: "${t}",`):typeof t==`boolean`&&r.push(` ${e}: ${t},`)}),r.push(` },`)),e.features&&(r.push(` features: {`),Object.entries(e.features).forEach(([e,t])=>{r.push(` ${e}: ${t},`)}),r.push(` },`)),r.push(...xv(e,` `)),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(` suggestionChips: [`),e.suggestionChips.forEach(e=>{r.push(` "${e}",`)}),r.push(` ],`)),e.suggestionChipsConfig&&(r.push(` suggestionChipsConfig: {`),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(` },`)),r.push(...vv(e,` `)),r.push(...yv(e,` `,n)),r.push(...bv(e,` `)),r.push(...Sv(e,` `)),n?.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(` initialMessages: loadSavedMessages(),`),n?.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(` // Flexible JSON stream parser for handling structured actions`),r.push(` streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {
205
+ }`;function Cv(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 wv(e){return e.parserType??Cv(e.streamParser)??`plain`}function Tv(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([e,r])=>{typeof r==`string`&&n.push(`${t} ${e}: "${r}",`)}),n.push(`${t}},`)),n}function Ev(e,t,n){let r=[],i=e.messageActions&&Object.entries(e.messageActions).some(([e,t])=>e!==`onFeedback`&&e!==`onCopy`&&t!==void 0),a=n?.onFeedback||n?.onCopy;return(i||a)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([e,n])=>{e!==`onFeedback`&&e!==`onCopy`&&(typeof n==`string`?r.push(`${t} ${e}: "${n}",`):typeof n==`boolean`&&r.push(`${t} ${e}: ${n},`))}),n?.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function Dv(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,i=e.markdown.disableDefaultStyles!==void 0;(r||i)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([e,r])=>{typeof r==`string`?n.push(`${t} ${e}: "${r}",`):typeof r==`boolean`&&n.push(`${t} ${e}: ${r},`)}),n.push(`${t} },`)),i&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Ov(e,t){if(!e.suggestions)return[];let n=JSON.stringify(e.suggestions,null,2).split(`
206
+ `);return n.map((e,r)=>`${r===0?`${t}suggestions: `:t}${e}${r===n.length-1?`,`:``}`)}function kv(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(e=>e!==`render`),i=e.layout.messages&&Object.keys(e.layout.messages).some(e=>e!==`renderUserMessage`&&e!==`renderAssistantMessage`);(r||i)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([e,r])=>{e!==`render`&&(typeof r==`string`?n.push(`${t} ${e}: "${r}",`):typeof r==`boolean`&&n.push(`${t} ${e}: ${r},`))}),n.push(`${t} },`)),i&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([e,r])=>{e!==`renderUserMessage`&&e!==`renderAssistantMessage`&&(e===`avatar`&&typeof r==`object`&&r?(n.push(`${t} avatar: {`),Object.entries(r).forEach(([e,r])=>{typeof r==`string`?n.push(`${t} ${e}: "${r}",`):typeof r==`boolean`&&n.push(`${t} ${e}: ${r},`)}),n.push(`${t} },`)):e===`timestamp`&&typeof r==`object`&&r?Object.entries(r).some(([e])=>e!==`format`)&&(n.push(`${t} timestamp: {`),Object.entries(r).forEach(([e,r])=>{e!==`format`&&(typeof r==`string`?n.push(`${t} ${e}: "${r}",`):typeof r==`boolean`&&n.push(`${t} ${e}: ${r},`))}),n.push(`${t} },`)):typeof r==`string`?n.push(`${t} ${e}: "${r}",`):typeof r==`boolean`&&n.push(`${t} ${e}: ${r},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Av(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 jv(e,t,n){Object.entries(t).forEach(([t,r])=>{r!==void 0&&typeof r!=`function`&&(Array.isArray(r)?e.push(`${n}${t}: ${JSON.stringify(r)},`):r&&typeof r==`object`?(e.push(`${n}${t}: {`),jv(e,r,`${n} `),e.push(`${n}},`)):e.push(`${n}${t}: ${JSON.stringify(r)},`))})}function Mv(e,t,n,r){n&&(e.push(`${r}${t}: {`),jv(e,n,`${r} `),e.push(`${r}},`))}function Nv(e,t,n){t.future?.v5Defaults!==void 0&&e.push(`${n}future: { v5Defaults: ${t.future.v5Defaults===!0} },`)}function Pv(e){return(e?.target??`body`).replace(/\\/g,`\\\\`).replace(/'/g,`\\'`)}function Fv(e,t=`esm`,n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let i=n?{...n,hooks:vv(n.hooks)}:void 0;return t===`esm`?Iv(r,i):t===`script-installer`?Bv(r,i):t===`script-advanced`?Hv(r,i):t===`react-component`?Lv(r,i):t===`react-advanced`?Rv(r,i):Vv(r,i)}function Iv(e,t){let n=t?.hooks,r=wv(e),i=r!==`plain`,a=[`import '@runtypelabs/persona/widget.css';`,`import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';`,``,`initAgentWidget({`,` target: '${Pv(t)}',`,` config: {`];return e.apiUrl&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.agentId&&a.push(` agentId: "${e.agentId}",`),e.target&&a.push(` target: "${e.target}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),i&&a.push(` parserType: "${r}",`),Nv(a,e,` `),e.theme&&typeof e.theme==`object`&&Object.keys(e.theme).length>0&&Mv(a,`theme`,e.theme,` `),e.launcher&&Mv(a,`launcher`,e.launcher,` `),e.copy&&(a.push(` copy: {`),Object.entries(e.copy).forEach(([e,t])=>{a.push(` ${e}: "${t}",`)}),a.push(` },`)),e.sendButton&&(a.push(` sendButton: {`),Object.entries(e.sendButton).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):typeof t==`boolean`&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.voiceRecognition&&(a.push(` voiceRecognition: {`),Object.entries(e.voiceRecognition).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):(typeof t==`boolean`||typeof t==`number`)&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.statusIndicator&&(a.push(` statusIndicator: {`),Object.entries(e.statusIndicator).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):typeof t==`boolean`&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.features&&(a.push(` features: {`),Object.entries(e.features).forEach(([e,t])=>{a.push(` ${e}: ${t},`)}),a.push(` },`)),a.push(...Ov(e,` `)),e.suggestionChips&&e.suggestionChips.length>0&&(a.push(` suggestionChips: [`),e.suggestionChips.forEach(e=>{a.push(` "${e}",`)}),a.push(` ],`)),e.suggestionChipsConfig&&(a.push(` suggestionChipsConfig: {`),e.suggestionChipsConfig.fontFamily&&a.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&a.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&a.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&a.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),a.push(` },`)),a.push(...Tv(e,` `)),a.push(...Ev(e,` `,n)),a.push(...Dv(e,` `)),a.push(...kv(e,` `)),a.push(...Av(n,` `)),e.debug&&a.push(` debug: ${e.debug},`),n?.postprocessMessage?a.push(` postprocessMessage: ${n.postprocessMessage}`):a.push(` postprocessMessage: ({ text }) => markdownPostprocessor(text)`),a.push(` }`),a.push(`});`),a.join(`
207
+ `)}function Lv(e,t){let n=t?.hooks,r=wv(e),i=r!==`plain`,a=[`// ChatWidget.tsx`,`'use client'; // Required for Next.js - remove for Vite/CRA`,``,`import { useEffect } from 'react';`,`import '@runtypelabs/persona/widget.css';`,`import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';`,`import type { AgentWidgetInitHandle } from '@runtypelabs/persona';`,``,`export function ChatWidget() {`,` useEffect(() => {`,` let handle: AgentWidgetInitHandle | null = null;`,``,` handle = initAgentWidget({`,` target: '${Pv(t)}',`,` config: {`];return e.apiUrl&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.agentId&&a.push(` agentId: "${e.agentId}",`),e.target&&a.push(` target: "${e.target}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),i&&a.push(` parserType: "${r}",`),Nv(a,e,` `),e.theme&&typeof e.theme==`object`&&Object.keys(e.theme).length>0&&Mv(a,`theme`,e.theme,` `),e.launcher&&Mv(a,`launcher`,e.launcher,` `),e.copy&&(a.push(` copy: {`),Object.entries(e.copy).forEach(([e,t])=>{a.push(` ${e}: "${t}",`)}),a.push(` },`)),e.sendButton&&(a.push(` sendButton: {`),Object.entries(e.sendButton).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):typeof t==`boolean`&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.voiceRecognition&&(a.push(` voiceRecognition: {`),Object.entries(e.voiceRecognition).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):(typeof t==`boolean`||typeof t==`number`)&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.statusIndicator&&(a.push(` statusIndicator: {`),Object.entries(e.statusIndicator).forEach(([e,t])=>{typeof t==`string`?a.push(` ${e}: "${t}",`):typeof t==`boolean`&&a.push(` ${e}: ${t},`)}),a.push(` },`)),e.features&&(a.push(` features: {`),Object.entries(e.features).forEach(([e,t])=>{a.push(` ${e}: ${t},`)}),a.push(` },`)),a.push(...Ov(e,` `)),e.suggestionChips&&e.suggestionChips.length>0&&(a.push(` suggestionChips: [`),e.suggestionChips.forEach(e=>{a.push(` "${e}",`)}),a.push(` ],`)),e.suggestionChipsConfig&&(a.push(` suggestionChipsConfig: {`),e.suggestionChipsConfig.fontFamily&&a.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&a.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&a.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&a.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),a.push(` },`)),a.push(...Tv(e,` `)),a.push(...Ev(e,` `,n)),a.push(...Dv(e,` `)),a.push(...kv(e,` `)),a.push(...Av(n,` `)),e.debug&&a.push(` debug: ${e.debug},`),n?.postprocessMessage?a.push(` postprocessMessage: ${n.postprocessMessage}`):a.push(` postprocessMessage: ({ text }) => markdownPostprocessor(text)`),a.push(` }`),a.push(` });`),a.push(``),a.push(` // Cleanup on unmount`),a.push(` return () => {`),a.push(` if (handle) {`),a.push(` handle.destroy();`),a.push(` }`),a.push(` };`),a.push(` }, []);`),a.push(``),a.push(` return null; // Widget injects itself into the DOM`),a.push(`}`),a.push(``),a.push(`// Usage in your app:`),a.push(`// import { ChatWidget } from './components/ChatWidget';`),a.push(`//`),a.push(`// export default function App() {`),a.push(`// return (`),a.push(`// <div>`),a.push(`// {/* Your app content */}`),a.push(`// <ChatWidget />`),a.push(`// </div>`),a.push(`// );`),a.push(`// }`),a.join(`
208
+ `)}function Rv(e,t){let n=t?.hooks,r=[`// ChatWidgetAdvanced.tsx`,`'use client'; // Required for Next.js - remove for Vite/CRA`,``,`import { useEffect } from 'react';`,`import '@runtypelabs/persona/widget.css';`,`import {`,` initAgentWidget,`,` createFlexibleJsonStreamParser,`,` defaultJsonActionParser,`,` defaultActionHandlers,`,` markdownPostprocessor`,`} from '@runtypelabs/persona';`,`import type { AgentWidgetInitHandle } from '@runtypelabs/persona';`,``,`const STORAGE_KEY = 'chat-widget-state';`,`const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';`,``,`// Types for DOM elements`,`interface PageElement {`,` type: string;`,` tagName: string;`,` selector: string;`,` innerText: string;`,` href?: string;`,`}`,``,`interface DOMContext {`,` page_elements: PageElement[];`,` page_element_count: number;`,` element_types: Record<string, number>;`,` page_url: string;`,` page_title: string;`,` timestamp: string;`,`}`,``,`// DOM context provider - extracts page elements for AI context`,`const collectDOMContext = (): DOMContext => {`,` const selectors = {`,` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`,` links: 'a[href]',`,` inputs: 'input, textarea, select'`,` };`,``,` const elements: PageElement[] = [];`,` Object.entries(selectors).forEach(([type, selector]) => {`,` document.querySelectorAll(selector).forEach((element) => {`,` if (!(element instanceof HTMLElement)) return;`,` `,` // Exclude elements within the widget`,` const widgetHost = element.closest('.persona-host');`,` if (widgetHost) return;`,` `,` const text = element.innerText?.trim();`,` if (!text) return;`,``,` const selectorString =`," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :",` element.tagName.toLowerCase();`,``,` const elementData: PageElement = {`,` type,`,` tagName: element.tagName.toLowerCase(),`,` selector: selectorString,`,` innerText: text.substring(0, 200)`,` };`,``,` if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {`,` elementData.href = element.href;`,` }`,``,` elements.push(elementData);`,` });`,` });`,``,` const counts = elements.reduce((acc, el) => {`,` acc[el.type] = (acc[el.type] || 0) + 1;`,` return acc;`,` }, {} as Record<string, number>);`,``,` return {`,` page_elements: elements.slice(0, 50),`,` page_element_count: elements.length,`,` element_types: counts,`,` page_url: window.location.href,`,` page_title: document.title,`,` timestamp: new Date().toISOString()`,` };`,`};`,``,`export function ChatWidgetAdvanced() {`,` useEffect(() => {`,` let handle: AgentWidgetInitHandle | null = null;`,``,` // Load saved state`,` const loadSavedMessages = () => {`,` const savedState = localStorage.getItem(STORAGE_KEY);`,` if (savedState) {`,` try {`,` const { messages } = JSON.parse(savedState);`,` return messages || [];`,` } catch (e) {`,` console.error('Failed to load saved state:', e);`,` }`,` }`,` return [];`,` };`,``,` handle = initAgentWidget({`,` target: '${Pv(t)}',`,` config: {`];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),Nv(r,e,` `),e.theme&&typeof e.theme==`object`&&Object.keys(e.theme).length>0&&Mv(r,`theme`,e.theme,` `),e.launcher&&Mv(r,`launcher`,e.launcher,` `),e.copy&&(r.push(` copy: {`),Object.entries(e.copy).forEach(([e,t])=>{r.push(` ${e}: "${t}",`)}),r.push(` },`)),e.sendButton&&(r.push(` sendButton: {`),Object.entries(e.sendButton).forEach(([e,t])=>{typeof t==`string`?r.push(` ${e}: "${t}",`):typeof t==`boolean`&&r.push(` ${e}: ${t},`)}),r.push(` },`)),e.voiceRecognition&&(r.push(` voiceRecognition: {`),Object.entries(e.voiceRecognition).forEach(([e,t])=>{typeof t==`string`?r.push(` ${e}: "${t}",`):(typeof t==`boolean`||typeof t==`number`)&&r.push(` ${e}: ${t},`)}),r.push(` },`)),e.statusIndicator&&(r.push(` statusIndicator: {`),Object.entries(e.statusIndicator).forEach(([e,t])=>{typeof t==`string`?r.push(` ${e}: "${t}",`):typeof t==`boolean`&&r.push(` ${e}: ${t},`)}),r.push(` },`)),e.features&&(r.push(` features: {`),Object.entries(e.features).forEach(([e,t])=>{r.push(` ${e}: ${t},`)}),r.push(` },`)),r.push(...Ov(e,` `)),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(` suggestionChips: [`),e.suggestionChips.forEach(e=>{r.push(` "${e}",`)}),r.push(` ],`)),e.suggestionChipsConfig&&(r.push(` suggestionChipsConfig: {`),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(` },`)),r.push(...Tv(e,` `)),r.push(...Ev(e,` `,n)),r.push(...Dv(e,` `)),r.push(...kv(e,` `)),n?.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(` initialMessages: loadSavedMessages(),`),n?.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(` // Flexible JSON stream parser for handling structured actions`),r.push(` streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {
209
209
  if (!parsed || typeof parsed !== 'object') return null;
210
210
  if (parsed.action === 'nav_then_click') return 'Navigating...';
211
211
  if (parsed.action === 'message') return parsed.text || '';
212
212
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
213
213
  return parsed.text || null;
214
- }),`)),n?.actionParsers?(r.push(` // Action parsers (custom merged with defaults)`),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(` // Built-in parser for markdown-wrapped JSON`),r.push(` ${fv}`),r.push(` ],`)):(r.push(` // Action parsers to detect JSON actions in responses`),r.push(` actionParsers: [`),r.push(` defaultJsonActionParser,`),r.push(` // Parser for markdown-wrapped JSON`),r.push(` ${fv}`),r.push(` ],`)),n?.actionHandlers?(r.push(` // Action handlers (custom merged with defaults)`),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(` defaultActionHandlers.message,`),r.push(` defaultActionHandlers.messageAndClick,`),r.push(` // Built-in handler for nav_then_click action`),r.push(` ${mv}`),r.push(` ],`)):(r.push(` // Action handlers for navigation and other actions`),r.push(` actionHandlers: [`),r.push(` defaultActionHandlers.message,`),r.push(` defaultActionHandlers.messageAndClick,`),r.push(` // Handler for nav_then_click action`),r.push(` ${mv}`),r.push(` ],`)),n?.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(` postprocessMessage: ({ text }) => markdownPostprocessor(text),`),n?.requestMiddleware?(r.push(` // Request middleware (custom merged with DOM context)`),r.push(` requestMiddleware: ({ payload, config }) => {`),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(` const merged = customResult || payload;`),r.push(` return {`),r.push(` ...merged,`),r.push(` metadata: { ...merged.metadata, ...collectDOMContext() }`),r.push(` };`),r.push(` }`)):(r.push(` requestMiddleware: ({ payload }) => {`),r.push(` return {`),r.push(` ...payload,`),r.push(` metadata: collectDOMContext()`),r.push(` };`),r.push(` }`)),r.push(` }`),r.push(` });`),r.push(``),r.push(` // Save state on message events`),r.push(` const handleMessage = () => {`),r.push(` const session = handle?.getSession?.();`),r.push(` if (session) {`),r.push(` localStorage.setItem(STORAGE_KEY, JSON.stringify({`),r.push(` messages: session.messages,`),r.push(` timestamp: new Date().toISOString()`),r.push(` }));`),r.push(` }`),r.push(` };`),r.push(``),r.push(` // Clear state on clear chat`),r.push(` const handleClearChat = () => {`),r.push(` localStorage.removeItem(STORAGE_KEY);`),r.push(` localStorage.removeItem(PROCESSED_ACTIONS_KEY);`),r.push(` };`),r.push(``),r.push(` window.addEventListener('persona:message', handleMessage);`),r.push(` window.addEventListener('persona:clear-chat', handleClearChat);`),r.push(``),r.push(` // Cleanup on unmount`),r.push(` return () => {`),r.push(` window.removeEventListener('persona:message', handleMessage);`),r.push(` window.removeEventListener('persona:clear-chat', handleClearChat);`),r.push(` if (handle) {`),r.push(` handle.destroy();`),r.push(` }`),r.push(` };`),r.push(` }, []);`),r.push(``),r.push(` return null; // Widget injects itself into the DOM`),r.push(`}`),r.push(``),r.push(`// Usage: Collects DOM context for AI-powered navigation`),r.push(`// Features:`),r.push(`// - Extracts page elements (products, buttons, links)`),r.push(`// - Persists chat history across page loads`),r.push(`// - Handles navigation actions (nav_then_click)`),r.push(`// - Processes structured JSON actions from AI`),r.push(`//`),r.push(`// Example usage in Next.js:`),r.push(`// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';`),r.push(`//`),r.push(`// export default function RootLayout({ children }) {`),r.push(`// return (`),r.push(`// <html lang="en">`),r.push(`// <body>`),r.push(`// {children}`),r.push(`// <ChatWidgetAdvanced />`),r.push(`// </body>`),r.push(`// </html>`),r.push(`// );`),r.push(`// }`),r.join(`
215
- `)}function Mv(e){let t=_v(e),n=t!==`plain`,r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.agentId&&(r.agentId=e.agentId),e.target&&(r.target=e.target),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.future?.v5Defaults!==void 0&&(r.future={v5Defaults:e.future.v5Defaults===!0}),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),e.suggestions&&(r.suggestions=e.suggestions),e.suggestionChips?.length>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let t={};Object.entries(e.toolCall).forEach(([e,n])=>{typeof n==`string`&&(t[e]=n)}),Object.keys(t).length>0&&(r.toolCall=t)}if(e.messageActions){let t={};Object.entries(e.messageActions).forEach(([e,n])=>{e!==`onFeedback`&&e!==`onCopy`&&n!==void 0&&(typeof n==`string`||typeof n==`boolean`)&&(t[e]=n)}),Object.keys(t).length>0&&(r.messageActions=t)}if(e.markdown){let t={};e.markdown.options&&(t.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(t.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(t).length>0&&(r.markdown=t)}if(e.layout){let t={};if(e.layout.header){let n={};Object.entries(e.layout.header).forEach(([e,t])=>{e!==`render`&&(typeof t==`string`||typeof t==`boolean`)&&(n[e]=t)}),Object.keys(n).length>0&&(t.header=n)}if(e.layout.messages){let n={};Object.entries(e.layout.messages).forEach(([e,t])=>{if(e!==`renderUserMessage`&&e!==`renderAssistantMessage`){if(e===`avatar`&&typeof t==`object`&&t)n.avatar=t;else if(e===`timestamp`&&typeof t==`object`&&t){let e={};Object.entries(t).forEach(([t,n])=>{t!==`format`&&(typeof n==`string`||typeof n==`boolean`)&&(e[t]=n)}),Object.keys(e).length>0&&(n.timestamp=e)}else(typeof t==`string`||typeof t==`boolean`)&&(n[e]=t)}}),Object.keys(n).length>0&&(t.messages=n)}Object.keys(t).length>0&&(r.layout=t)}return r}function Nv(e,t){let n=Mv(e),r=t?.windowKey||t?.target?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,i=JSON.stringify(r,null,0).replace(/'/g,`&#39;`);return`<script src="${lv(t)}/install.global.js" data-config='${i}'><\/script>`}function Pv(e,t){let n=t?.hooks,r=_v(e),i=r!==`plain`,a=lv(t),o=[`<!-- Load CSS -->`,`<link rel="stylesheet" href="${a}/widget.css" />`,``,`<!-- Load JavaScript -->`,`<script src="${a}/index.global.js"><\/script>`,``,`<!-- Initialize widget -->`,`<script>`,` var handle = window.AgentWidget.initAgentWidget({`,` target: '${Dv(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[],` config: {`];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),i&&o.push(` parserType: "${r}",`),Ev(o,e,` `),e.theme&&typeof e.theme==`object`&&Object.keys(e.theme).length>0&&Tv(o,`theme`,e.theme,` `),e.launcher&&Tv(o,`launcher`,e.launcher,` `),e.copy&&(o.push(` copy: {`),Object.entries(e.copy).forEach(([e,t])=>{o.push(` ${e}: "${t}",`)}),o.push(` },`)),e.sendButton&&(o.push(` sendButton: {`),Object.entries(e.sendButton).forEach(([e,t])=>{typeof t==`string`?o.push(` ${e}: "${t}",`):typeof t==`boolean`&&o.push(` ${e}: ${t},`)}),o.push(` },`)),e.voiceRecognition&&(o.push(` voiceRecognition: {`),Object.entries(e.voiceRecognition).forEach(([e,t])=>{typeof t==`string`?o.push(` ${e}: "${t}",`):(typeof t==`boolean`||typeof t==`number`)&&o.push(` ${e}: ${t},`)}),o.push(` },`)),e.statusIndicator&&(o.push(` statusIndicator: {`),Object.entries(e.statusIndicator).forEach(([e,t])=>{typeof t==`string`?o.push(` ${e}: "${t}",`):typeof t==`boolean`&&o.push(` ${e}: ${t},`)}),o.push(` },`)),e.features&&(o.push(` features: {`),Object.entries(e.features).forEach(([e,t])=>{o.push(` ${e}: ${t},`)}),o.push(` },`)),o.push(...xv(e,` `)),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(` suggestionChips: [`),e.suggestionChips.forEach(e=>{o.push(` "${e}",`)}),o.push(` ],`)),e.suggestionChipsConfig&&(o.push(` suggestionChipsConfig: {`),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(` },`)),o.push(...vv(e,` `)),o.push(...yv(e,` `,n)),o.push(...bv(e,` `)),o.push(...Sv(e,` `)),o.push(...Cv(n,` `)),e.debug&&o.push(` debug: ${e.debug},`),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(` postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)`),o.push(` }`),o.push(` });`),o.push(`<\/script>`),o.join(`
216
- `)}function Fv(e,t){let n=t?.hooks,r=Mv(e),i=[`<script>`,`(function() {`,` 'use strict';`,``,` // Configuration`,` var CONFIG = ${JSON.stringify(r,null,2).split(`
214
+ }),`)),n?.actionParsers?(r.push(` // Action parsers (custom merged with defaults)`),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(` // Built-in parser for markdown-wrapped JSON`),r.push(` ${yv}`),r.push(` ],`)):(r.push(` // Action parsers to detect JSON actions in responses`),r.push(` actionParsers: [`),r.push(` defaultJsonActionParser,`),r.push(` // Parser for markdown-wrapped JSON`),r.push(` ${yv}`),r.push(` ],`)),n?.actionHandlers?(r.push(` // Action handlers (custom merged with defaults)`),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(` defaultActionHandlers.message,`),r.push(` defaultActionHandlers.messageAndClick,`),r.push(` // Built-in handler for nav_then_click action`),r.push(` ${xv}`),r.push(` ],`)):(r.push(` // Action handlers for navigation and other actions`),r.push(` actionHandlers: [`),r.push(` defaultActionHandlers.message,`),r.push(` defaultActionHandlers.messageAndClick,`),r.push(` // Handler for nav_then_click action`),r.push(` ${xv}`),r.push(` ],`)),n?.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(` postprocessMessage: ({ text }) => markdownPostprocessor(text),`),n?.requestMiddleware?(r.push(` // Request middleware (custom merged with DOM context)`),r.push(` requestMiddleware: ({ payload, config }) => {`),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(` const merged = customResult || payload;`),r.push(` return {`),r.push(` ...merged,`),r.push(` metadata: { ...merged.metadata, ...collectDOMContext() }`),r.push(` };`),r.push(` }`)):(r.push(` requestMiddleware: ({ payload }) => {`),r.push(` return {`),r.push(` ...payload,`),r.push(` metadata: collectDOMContext()`),r.push(` };`),r.push(` }`)),r.push(` }`),r.push(` });`),r.push(``),r.push(` // Save state on message events`),r.push(` const handleMessage = () => {`),r.push(` const session = handle?.getSession?.();`),r.push(` if (session) {`),r.push(` localStorage.setItem(STORAGE_KEY, JSON.stringify({`),r.push(` messages: session.messages,`),r.push(` timestamp: new Date().toISOString()`),r.push(` }));`),r.push(` }`),r.push(` };`),r.push(``),r.push(` // Clear state on clear chat`),r.push(` const handleClearChat = () => {`),r.push(` localStorage.removeItem(STORAGE_KEY);`),r.push(` localStorage.removeItem(PROCESSED_ACTIONS_KEY);`),r.push(` };`),r.push(``),r.push(` window.addEventListener('persona:message', handleMessage);`),r.push(` window.addEventListener('persona:clear-chat', handleClearChat);`),r.push(``),r.push(` // Cleanup on unmount`),r.push(` return () => {`),r.push(` window.removeEventListener('persona:message', handleMessage);`),r.push(` window.removeEventListener('persona:clear-chat', handleClearChat);`),r.push(` if (handle) {`),r.push(` handle.destroy();`),r.push(` }`),r.push(` };`),r.push(` }, []);`),r.push(``),r.push(` return null; // Widget injects itself into the DOM`),r.push(`}`),r.push(``),r.push(`// Usage: Collects DOM context for AI-powered navigation`),r.push(`// Features:`),r.push(`// - Extracts page elements (products, buttons, links)`),r.push(`// - Persists chat history across page loads`),r.push(`// - Handles navigation actions (nav_then_click)`),r.push(`// - Processes structured JSON actions from AI`),r.push(`//`),r.push(`// Example usage in Next.js:`),r.push(`// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';`),r.push(`//`),r.push(`// export default function RootLayout({ children }) {`),r.push(`// return (`),r.push(`// <html lang="en">`),r.push(`// <body>`),r.push(`// {children}`),r.push(`// <ChatWidgetAdvanced />`),r.push(`// </body>`),r.push(`// </html>`),r.push(`// );`),r.push(`// }`),r.join(`
215
+ `)}function zv(e){let t=wv(e),n=t!==`plain`,r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.agentId&&(r.agentId=e.agentId),e.target&&(r.target=e.target),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.future?.v5Defaults!==void 0&&(r.future={v5Defaults:e.future.v5Defaults===!0}),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),e.suggestions&&(r.suggestions=e.suggestions),e.suggestionChips?.length>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let t={};Object.entries(e.toolCall).forEach(([e,n])=>{typeof n==`string`&&(t[e]=n)}),Object.keys(t).length>0&&(r.toolCall=t)}if(e.messageActions){let t={};Object.entries(e.messageActions).forEach(([e,n])=>{e!==`onFeedback`&&e!==`onCopy`&&n!==void 0&&(typeof n==`string`||typeof n==`boolean`)&&(t[e]=n)}),Object.keys(t).length>0&&(r.messageActions=t)}if(e.markdown){let t={};e.markdown.options&&(t.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(t.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(t).length>0&&(r.markdown=t)}if(e.layout){let t={};if(e.layout.header){let n={};Object.entries(e.layout.header).forEach(([e,t])=>{e!==`render`&&(typeof t==`string`||typeof t==`boolean`)&&(n[e]=t)}),Object.keys(n).length>0&&(t.header=n)}if(e.layout.messages){let n={};Object.entries(e.layout.messages).forEach(([e,t])=>{if(e!==`renderUserMessage`&&e!==`renderAssistantMessage`){if(e===`avatar`&&typeof t==`object`&&t)n.avatar=t;else if(e===`timestamp`&&typeof t==`object`&&t){let e={};Object.entries(t).forEach(([t,n])=>{t!==`format`&&(typeof n==`string`||typeof n==`boolean`)&&(e[t]=n)}),Object.keys(e).length>0&&(n.timestamp=e)}else(typeof t==`string`||typeof t==`boolean`)&&(n[e]=t)}}),Object.keys(n).length>0&&(t.messages=n)}Object.keys(t).length>0&&(r.layout=t)}return r}function Bv(e,t){let n=zv(e),r=t?.windowKey||t?.target?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,i=JSON.stringify(r,null,0).replace(/'/g,`&#39;`);return`<script src="${gv(t)}/install.global.js" data-config='${i}'><\/script>`}function Vv(e,t){let n=t?.hooks,r=wv(e),i=r!==`plain`,a=gv(t),o=[`<!-- Load CSS -->`,`<link rel="stylesheet" href="${a}/widget.css" />`,``,`<!-- Load JavaScript -->`,`<script src="${a}/index.global.js"><\/script>`,``,`<!-- Initialize widget -->`,`<script>`,` var handle = window.AgentWidget.initAgentWidget({`,` target: '${Pv(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[],` config: {`];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),i&&o.push(` parserType: "${r}",`),Nv(o,e,` `),e.theme&&typeof e.theme==`object`&&Object.keys(e.theme).length>0&&Mv(o,`theme`,e.theme,` `),e.launcher&&Mv(o,`launcher`,e.launcher,` `),e.copy&&(o.push(` copy: {`),Object.entries(e.copy).forEach(([e,t])=>{o.push(` ${e}: "${t}",`)}),o.push(` },`)),e.sendButton&&(o.push(` sendButton: {`),Object.entries(e.sendButton).forEach(([e,t])=>{typeof t==`string`?o.push(` ${e}: "${t}",`):typeof t==`boolean`&&o.push(` ${e}: ${t},`)}),o.push(` },`)),e.voiceRecognition&&(o.push(` voiceRecognition: {`),Object.entries(e.voiceRecognition).forEach(([e,t])=>{typeof t==`string`?o.push(` ${e}: "${t}",`):(typeof t==`boolean`||typeof t==`number`)&&o.push(` ${e}: ${t},`)}),o.push(` },`)),e.statusIndicator&&(o.push(` statusIndicator: {`),Object.entries(e.statusIndicator).forEach(([e,t])=>{typeof t==`string`?o.push(` ${e}: "${t}",`):typeof t==`boolean`&&o.push(` ${e}: ${t},`)}),o.push(` },`)),e.features&&(o.push(` features: {`),Object.entries(e.features).forEach(([e,t])=>{o.push(` ${e}: ${t},`)}),o.push(` },`)),o.push(...Ov(e,` `)),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(` suggestionChips: [`),e.suggestionChips.forEach(e=>{o.push(` "${e}",`)}),o.push(` ],`)),e.suggestionChipsConfig&&(o.push(` suggestionChipsConfig: {`),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(` },`)),o.push(...Tv(e,` `)),o.push(...Ev(e,` `,n)),o.push(...Dv(e,` `)),o.push(...kv(e,` `)),o.push(...Av(n,` `)),e.debug&&o.push(` debug: ${e.debug},`),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(` postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)`),o.push(` }`),o.push(` });`),o.push(`<\/script>`),o.join(`
216
+ `)}function Hv(e,t){let n=t?.hooks,r=zv(e),i=[`<script>`,`(function() {`,` 'use strict';`,``,` // Configuration`,` var CONFIG = ${JSON.stringify(r,null,2).split(`
217
217
  `).map((e,t)=>t===0?e:` `+e).join(`
218
- `)};`,``,` // Constants`,` var CDN_BASE = '${lv(t)}';`,` var STORAGE_KEY = 'chat-widget-state';`,` var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';`,``,` // DOM context provider - extracts page elements for AI context`,` var domContextProvider = function() {`,` var selectors = {`,` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`,` links: 'a[href]',`,` inputs: 'input, textarea, select'`,` };`,``,` var elements = [];`,` Object.entries(selectors).forEach(function(entry) {`,` var type = entry[0], selector = entry[1];`,` document.querySelectorAll(selector).forEach(function(element) {`,` if (!(element instanceof HTMLElement)) return;`,` var widgetHost = element.closest('.persona-host');`,` if (widgetHost) return;`,` var text = element.innerText ? element.innerText.trim() : '';`,` if (!text) return;`,``,` var selectorString = element.id ? '#' + element.id :`,` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`,` element.tagName.toLowerCase();`,``,` var elementData = {`,` type: type,`,` tagName: element.tagName.toLowerCase(),`,` selector: selectorString,`,` innerText: text.substring(0, 200)`,` };`,``,` if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {`,` elementData.href = element.href;`,` }`,` elements.push(elementData);`,` });`,` });`,``,` var counts = elements.reduce(function(acc, el) {`,` acc[el.type] = (acc[el.type] || 0) + 1;`,` return acc;`,` }, {});`,``,` return {`,` page_elements: elements.slice(0, 50),`,` page_element_count: elements.length,`,` element_types: counts,`,` page_url: window.location.href,`,` page_title: document.title,`,` timestamp: new Date().toISOString()`,` };`,` };`,``,` // Load CSS dynamically`,` var loadCSS = function() {`,` if (document.querySelector('link[data-persona]')) return;`,` var link = document.createElement('link');`,` link.rel = 'stylesheet';`,` link.href = CDN_BASE + '/widget.css';`,` link.setAttribute('data-persona', 'true');`,` document.head.appendChild(link);`,` };`,``,` // Load JS dynamically`,` var loadJS = function(callback) {`,` if (window.AgentWidget) { callback(); return; }`,` var script = document.createElement('script');`,` script.src = CDN_BASE + '/index.global.js';`,` script.onload = callback;`,` script.onerror = function() { console.error('Failed to load AgentWidget'); };`,` document.head.appendChild(script);`,` };`,``,` // Create widget config with advanced features`,` var createWidgetConfig = function(agentWidget) {`,` var widgetConfig = Object.assign({}, CONFIG);`,``];return n?.getHeaders&&(i.push(` widgetConfig.getHeaders = ${n.getHeaders};`),i.push(``)),n?.contextProviders&&(i.push(` widgetConfig.contextProviders = ${n.contextProviders};`),i.push(``)),n?.streamParser?i.push(` widgetConfig.streamParser = ${n.streamParser};`):(i.push(` // Flexible JSON stream parser for handling structured actions`),i.push(` widgetConfig.streamParser = function() {`),i.push(` return agentWidget.createFlexibleJsonStreamParser(function(parsed) {
218
+ `)};`,``,` // Constants`,` var CDN_BASE = '${gv(t)}';`,` var STORAGE_KEY = 'chat-widget-state';`,` var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';`,``,` // DOM context provider - extracts page elements for AI context`,` var domContextProvider = function() {`,` var selectors = {`,` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`,` links: 'a[href]',`,` inputs: 'input, textarea, select'`,` };`,``,` var elements = [];`,` Object.entries(selectors).forEach(function(entry) {`,` var type = entry[0], selector = entry[1];`,` document.querySelectorAll(selector).forEach(function(element) {`,` if (!(element instanceof HTMLElement)) return;`,` var widgetHost = element.closest('.persona-host');`,` if (widgetHost) return;`,` var text = element.innerText ? element.innerText.trim() : '';`,` if (!text) return;`,``,` var selectorString = element.id ? '#' + element.id :`,` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`,` element.tagName.toLowerCase();`,``,` var elementData = {`,` type: type,`,` tagName: element.tagName.toLowerCase(),`,` selector: selectorString,`,` innerText: text.substring(0, 200)`,` };`,``,` if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {`,` elementData.href = element.href;`,` }`,` elements.push(elementData);`,` });`,` });`,``,` var counts = elements.reduce(function(acc, el) {`,` acc[el.type] = (acc[el.type] || 0) + 1;`,` return acc;`,` }, {});`,``,` return {`,` page_elements: elements.slice(0, 50),`,` page_element_count: elements.length,`,` element_types: counts,`,` page_url: window.location.href,`,` page_title: document.title,`,` timestamp: new Date().toISOString()`,` };`,` };`,``,` // Load CSS dynamically`,` var loadCSS = function() {`,` if (document.querySelector('link[data-persona]')) return;`,` var link = document.createElement('link');`,` link.rel = 'stylesheet';`,` link.href = CDN_BASE + '/widget.css';`,` link.setAttribute('data-persona', 'true');`,` document.head.appendChild(link);`,` };`,``,` // Load JS dynamically`,` var loadJS = function(callback) {`,` if (window.AgentWidget) { callback(); return; }`,` var script = document.createElement('script');`,` script.src = CDN_BASE + '/index.global.js';`,` script.onload = callback;`,` script.onerror = function() { console.error('Failed to load AgentWidget'); };`,` document.head.appendChild(script);`,` };`,``,` // Create widget config with advanced features`,` var createWidgetConfig = function(agentWidget) {`,` var widgetConfig = Object.assign({}, CONFIG);`,``];return n?.getHeaders&&(i.push(` widgetConfig.getHeaders = ${n.getHeaders};`),i.push(``)),n?.contextProviders&&(i.push(` widgetConfig.contextProviders = ${n.contextProviders};`),i.push(``)),n?.streamParser?i.push(` widgetConfig.streamParser = ${n.streamParser};`):(i.push(` // Flexible JSON stream parser for handling structured actions`),i.push(` widgetConfig.streamParser = function() {`),i.push(` return agentWidget.createFlexibleJsonStreamParser(function(parsed) {
219
219
  if (!parsed || typeof parsed !== 'object') return null;
220
220
  if (parsed.action === 'nav_then_click') return 'Navigating...';
221
221
  if (parsed.action === 'message') return parsed.text || '';
222
222
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
223
223
  return parsed.text || null;
224
- });`),i.push(` };`)),i.push(``),n?.actionParsers?(i.push(` // Action parsers (custom merged with defaults)`),i.push(` var customParsers = ${n.actionParsers};`),i.push(` widgetConfig.actionParsers = customParsers.concat([`),i.push(` agentWidget.defaultJsonActionParser,`),i.push(` ${pv}`),i.push(` ]);`)):(i.push(` // Action parsers to detect JSON actions in responses`),i.push(` widgetConfig.actionParsers = [`),i.push(` agentWidget.defaultJsonActionParser,`),i.push(` ${pv}`),i.push(` ];`)),i.push(``),n?.actionHandlers?(i.push(` // Action handlers (custom merged with defaults)`),i.push(` var customHandlers = ${n.actionHandlers};`),i.push(` widgetConfig.actionHandlers = customHandlers.concat([`),i.push(` agentWidget.defaultActionHandlers.message,`),i.push(` agentWidget.defaultActionHandlers.messageAndClick,`),i.push(` ${hv}`),i.push(` ]);`)):(i.push(` // Action handlers for navigation and other actions`),i.push(` widgetConfig.actionHandlers = [`),i.push(` agentWidget.defaultActionHandlers.message,`),i.push(` agentWidget.defaultActionHandlers.messageAndClick,`),i.push(` ${hv}`),i.push(` ];`)),i.push(``),n?.requestMiddleware?(i.push(` // Request middleware (custom merged with DOM context)`),i.push(` widgetConfig.requestMiddleware = function(ctx) {`),i.push(` var customResult = (${n.requestMiddleware})(ctx);`),i.push(` var merged = customResult || ctx.payload;`),i.push(` return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });`),i.push(` };`)):(i.push(` // Send DOM context with each request`),i.push(` widgetConfig.requestMiddleware = function(ctx) {`),i.push(` return Object.assign({}, ctx.payload, { metadata: domContextProvider() });`),i.push(` };`)),i.push(``),n?.postprocessMessage?i.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(i.push(` // Markdown postprocessor`),i.push(` widgetConfig.postprocessMessage = function(ctx) {`),i.push(` return agentWidget.markdownPostprocessor(ctx.text);`),i.push(` };`)),i.push(``),(n?.onFeedback||n?.onCopy)&&(i.push(` // Message action callbacks`),i.push(` widgetConfig.messageActions = widgetConfig.messageActions || {};`),n?.onFeedback&&i.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&i.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),i.push(``)),i.push(` return widgetConfig;`,` };`,``,` // Initialize widget`,` var init = function() {`,` var agentWidget = window.AgentWidget;`,` if (!agentWidget) {`,` console.error('AgentWidget not loaded');`,` return;`,` }`,``,` var widgetConfig = createWidgetConfig(agentWidget);`,``,` // Load saved state`,` var savedState = localStorage.getItem(STORAGE_KEY);`,` if (savedState) {`,` try {`,` var parsed = JSON.parse(savedState);`,` widgetConfig.initialMessages = parsed.messages || [];`,` } catch (e) {`,` console.error('Failed to load saved state:', e);`,` }`,` }`,``,` // Initialize widget`,` var handle = agentWidget.initAgentWidget({`,` target: '${Dv(t)}',`,` useShadowDom: false,`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[],` config: widgetConfig`,` });`,``,` // Save state on message events`,` window.addEventListener('persona:message', function() {`,` var session = handle.getSession ? handle.getSession() : null;`,` if (session) {`,` localStorage.setItem(STORAGE_KEY, JSON.stringify({`,` messages: session.messages,`,` timestamp: new Date().toISOString()`,` }));`,` }`,` });`,``,` // Clear state on clear chat`,` window.addEventListener('persona:clear-chat', function() {`,` localStorage.removeItem(STORAGE_KEY);`,` localStorage.removeItem(PROCESSED_ACTIONS_KEY);`,` });`,` };`,``,` // Wait for framework hydration to complete (Next.js, Nuxt, etc.)`,` // This prevents the framework from removing dynamically added CSS during reconciliation`,` var waitForHydration = function(callback) {`,` var executed = false;`,` `,` var execute = function() {`,` if (executed) return;`,` executed = true;`,` callback();`,` };`,``,` var afterDom = function() {`,` // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)`,` if (typeof requestIdleCallback !== 'undefined') {`,` requestIdleCallback(function() {`,` // Double requestAnimationFrame ensures at least one full paint cycle completed`,` requestAnimationFrame(function() {`,` requestAnimationFrame(execute);`,` });`,` }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway`,` } else {`,` // Strategy 2: Fallback for Safari (no requestIdleCallback)`,` // 300ms is typically enough for hydration on most pages`,` setTimeout(execute, 300);`,` }`,` };`,``,` if (document.readyState === 'loading') {`,` document.addEventListener('DOMContentLoaded', afterDom);`,` } else {`,` // DOM already ready, but still wait for potential hydration`,` afterDom();`,` }`,` };`,``,` // Boot sequence: wait for hydration, then load CSS and JS, then initialize`,` // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation`,` waitForHydration(function() {`,` loadCSS();`,` loadJS(function() {`,` init();`,` });`,` });`,`})();`,`<\/script>`),i.join(`
225
- `)}H(),A();const Iv={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Lv=.1,Rv=.15,zv=1.5;function Bv(){if(document.querySelector(`style[data-persona-dc-styles]`))return;let e=document.createElement(`style`);e.setAttribute(`data-persona-dc-styles`,``),e.textContent=`
224
+ });`),i.push(` };`)),i.push(``),n?.actionParsers?(i.push(` // Action parsers (custom merged with defaults)`),i.push(` var customParsers = ${n.actionParsers};`),i.push(` widgetConfig.actionParsers = customParsers.concat([`),i.push(` agentWidget.defaultJsonActionParser,`),i.push(` ${bv}`),i.push(` ]);`)):(i.push(` // Action parsers to detect JSON actions in responses`),i.push(` widgetConfig.actionParsers = [`),i.push(` agentWidget.defaultJsonActionParser,`),i.push(` ${bv}`),i.push(` ];`)),i.push(``),n?.actionHandlers?(i.push(` // Action handlers (custom merged with defaults)`),i.push(` var customHandlers = ${n.actionHandlers};`),i.push(` widgetConfig.actionHandlers = customHandlers.concat([`),i.push(` agentWidget.defaultActionHandlers.message,`),i.push(` agentWidget.defaultActionHandlers.messageAndClick,`),i.push(` ${Sv}`),i.push(` ]);`)):(i.push(` // Action handlers for navigation and other actions`),i.push(` widgetConfig.actionHandlers = [`),i.push(` agentWidget.defaultActionHandlers.message,`),i.push(` agentWidget.defaultActionHandlers.messageAndClick,`),i.push(` ${Sv}`),i.push(` ];`)),i.push(``),n?.requestMiddleware?(i.push(` // Request middleware (custom merged with DOM context)`),i.push(` widgetConfig.requestMiddleware = function(ctx) {`),i.push(` var customResult = (${n.requestMiddleware})(ctx);`),i.push(` var merged = customResult || ctx.payload;`),i.push(` return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });`),i.push(` };`)):(i.push(` // Send DOM context with each request`),i.push(` widgetConfig.requestMiddleware = function(ctx) {`),i.push(` return Object.assign({}, ctx.payload, { metadata: domContextProvider() });`),i.push(` };`)),i.push(``),n?.postprocessMessage?i.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(i.push(` // Markdown postprocessor`),i.push(` widgetConfig.postprocessMessage = function(ctx) {`),i.push(` return agentWidget.markdownPostprocessor(ctx.text);`),i.push(` };`)),i.push(``),(n?.onFeedback||n?.onCopy)&&(i.push(` // Message action callbacks`),i.push(` widgetConfig.messageActions = widgetConfig.messageActions || {};`),n?.onFeedback&&i.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&i.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),i.push(``)),i.push(` return widgetConfig;`,` };`,``,` // Initialize widget`,` var init = function() {`,` var agentWidget = window.AgentWidget;`,` if (!agentWidget) {`,` console.error('AgentWidget not loaded');`,` return;`,` }`,``,` var widgetConfig = createWidgetConfig(agentWidget);`,``,` // Load saved state`,` var savedState = localStorage.getItem(STORAGE_KEY);`,` if (savedState) {`,` try {`,` var parsed = JSON.parse(savedState);`,` widgetConfig.initialMessages = parsed.messages || [];`,` } catch (e) {`,` console.error('Failed to load saved state:', e);`,` }`,` }`,``,` // Initialize widget`,` var handle = agentWidget.initAgentWidget({`,` target: '${Pv(t)}',`,` useShadowDom: false,`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[],` config: widgetConfig`,` });`,``,` // Save state on message events`,` window.addEventListener('persona:message', function() {`,` var session = handle.getSession ? handle.getSession() : null;`,` if (session) {`,` localStorage.setItem(STORAGE_KEY, JSON.stringify({`,` messages: session.messages,`,` timestamp: new Date().toISOString()`,` }));`,` }`,` });`,``,` // Clear state on clear chat`,` window.addEventListener('persona:clear-chat', function() {`,` localStorage.removeItem(STORAGE_KEY);`,` localStorage.removeItem(PROCESSED_ACTIONS_KEY);`,` });`,` };`,``,` // Wait for framework hydration to complete (Next.js, Nuxt, etc.)`,` // This prevents the framework from removing dynamically added CSS during reconciliation`,` var waitForHydration = function(callback) {`,` var executed = false;`,` `,` var execute = function() {`,` if (executed) return;`,` executed = true;`,` callback();`,` };`,``,` var afterDom = function() {`,` // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)`,` if (typeof requestIdleCallback !== 'undefined') {`,` requestIdleCallback(function() {`,` // Double requestAnimationFrame ensures at least one full paint cycle completed`,` requestAnimationFrame(function() {`,` requestAnimationFrame(execute);`,` });`,` }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway`,` } else {`,` // Strategy 2: Fallback for Safari (no requestIdleCallback)`,` // 300ms is typically enough for hydration on most pages`,` setTimeout(execute, 300);`,` }`,` };`,``,` if (document.readyState === 'loading') {`,` document.addEventListener('DOMContentLoaded', afterDom);`,` } else {`,` // DOM already ready, but still wait for potential hydration`,` afterDom();`,` }`,` };`,``,` // Boot sequence: wait for hydration, then load CSS and JS, then initialize`,` // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation`,` waitForHydration(function() {`,` loadCSS();`,` loadJS(function() {`,` init();`,` });`,` });`,`})();`,`<\/script>`),i.join(`
225
+ `)}V(),A();const Uv={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Wv=.1,Gv=.15,Kv=1.5;function qv(){if(document.querySelector(`style[data-persona-dc-styles]`))return;let e=document.createElement(`style`);e.setAttribute(`data-persona-dc-styles`,``),e.textContent=`
226
226
  /* ── Root ── */
227
227
  .persona-dc-root {
228
228
  display: flex;
@@ -463,9 +463,9 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
463
463
  min-height: 300px;
464
464
  }
465
465
  }
466
- `,document.head.appendChild(e)}function Vv(e,t){let n=e.clientWidth-48-40,r=e.clientHeight-48-40;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function Hv(e,t,n,r,i){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=i===`mobile`?`${32*r}px`:`10px`,t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin=`top left`,t.style.transform=`scale(${r})`}function Uv(e,t){let{items:n,initialIndex:r=0,initialDevice:i=`desktop`,initialColorScheme:a=`light`,showZoomControls:o=!0,showDeviceToggle:s=!0,showColorSchemeToggle:c=!0,onChange:l}=t;if(n.length===0)throw Error(`createDemoCarousel: items array must not be empty`);Bv();let u=Math.max(0,Math.min(r,n.length-1)),d=i,p=a,m=null,h=1,g=!1,_=B(`div`,`persona-dc-root`),v=B(`div`,`persona-dc-toolbar`),y=B(`div`,`persona-dc-toolbar-lead`),b=B(`div`,`persona-dc-toolbar-trail`),x=Kf({icon:`chevron-left`,label:`Previous demo`,size:14,onClick:()=>ue(-1)}),S=B(`div`);S.style.position=`relative`;let C=B(`button`,`persona-dc-title-btn`);C.type=`button`,C.setAttribute(`aria-expanded`,`false`),C.setAttribute(`aria-haspopup`,`listbox`);let w=B(`span`,`persona-dc-title-text`),T=B(`span`,`persona-dc-title-chevron`),E=k(f.ChevronDown,12,`currentColor`,2);E&&T.appendChild(E),C.append(w,T);let D=B(`div`,`persona-dc-dropdown`);D.setAttribute(`role`,`listbox`),D.style.display=`none`;let O=!1;function ee(){D.innerHTML=``;for(let e=0;e<n.length;e++){let t=n[e],r=B(`button`,`persona-dc-dropdown-item`);r.type=`button`,r.setAttribute(`role`,`option`),r.setAttribute(`aria-current`,e===u?`true`:`false`);let i=B(`span`);if(i.textContent=t.title,r.appendChild(i),t.description){let e=B(`span`,`persona-dc-dropdown-desc`);e.textContent=t.description,r.appendChild(e)}r.addEventListener(`click`,()=>{j(),de(e)}),D.appendChild(r)}}function A(){O=!O,D.style.display=O?``:`none`,C.setAttribute(`aria-expanded`,O?`true`:`false`),O&&ee()}function j(){O&&(O=!1,D.style.display=`none`,C.setAttribute(`aria-expanded`,`false`))}C.addEventListener(`click`,e=>{e.stopPropagation(),A()});let te=()=>j();document.addEventListener(`click`,te),S.append(C,D);let ne=Kf({icon:`chevron-right`,label:`Next demo`,size:14,onClick:()=>ue(1)}),re=B(`span`,`persona-dc-counter`);y.append(x,S,ne,re);let ie=null;s&&(ie=Jf({items:[{id:`desktop`,icon:`monitor`,label:`Desktop`},{id:`mobile`,icon:`smartphone`,label:`Mobile`}],selectedId:d,onSelect:e=>{d=e,oe.dataset.device=d,m=null,fe()}}),b.appendChild(ie.element));let M=null;if(o){let e=B(`div`,`persona-dc-zoom-controls`),t=Kf({icon:`minus`,label:`Zoom out`,size:14,onClick:()=>{m=Math.max(Rv,(m??h)-Lv),fe()}});M=B(`span`,`persona-dc-zoom-level`),M.title=`Reset to 100%`,M.style.cursor=`pointer`,M.addEventListener(`click`,()=>{m=1,fe()});let n=Kf({icon:`plus`,label:`Zoom in`,size:14,onClick:()=>{m=Math.min(zv,(m??h)+Lv),fe()}}),r=Kf({icon:`maximize`,label:`Fit to view`,size:14,onClick:()=>{m=null,fe()}});e.append(t,M,n,r),b.appendChild(e)}if(c){let e=B(`div`,`persona-dc-separator`);b.appendChild(e);let t=Jf({items:[{id:`light`,icon:`sun`,label:`Light`},{id:`dark`,icon:`moon`,label:`Dark`}],selectedId:p,onSelect:e=>{p=e,oe.dataset.colorScheme=p,ce()}});b.appendChild(t.element)}let N=B(`div`,`persona-dc-separator`);b.appendChild(N);let P=Kf({icon:`external-link`,label:`Open in new tab`,size:14,onClick:()=>{window.open(n[u].url,`_blank`)}});b.appendChild(P),v.append(y,b);let ae=B(`div`,`persona-dc-stage`),oe=B(`div`,`persona-dc-iframe-wrapper`);oe.dataset.device=d,oe.dataset.colorScheme=p;let se=B(`iframe`,`persona-dc-iframe`);se.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-forms`),se.setAttribute(`loading`,`lazy`),se.title=n[u].title,oe.appendChild(se),ae.appendChild(oe),_.append(v,ae),e.appendChild(_);function ce(){try{let e=se.contentDocument?.body;if(!e)return;p===`dark`?e.classList.add(`theme-dark`):e.classList.remove(`theme-dark`)}catch{}}se.addEventListener(`load`,()=>ce());function le(){let e=n[u];w.textContent=e.title,re.textContent=`${u+1} / ${n.length}`,se.title=e.title}function ue(e){de(((u+e)%n.length+n.length)%n.length)}function de(e){e<0||e>=n.length||(u=e,se.src=n[u].url,le(),l?.(u,n[u]))}function fe(){if(g)return;let e=Iv[d]??Iv.desktop;h=Vv(ae,e);let t=Math.max(Rv,Math.min(zv,m??h));Hv(oe,se,e,t,d),M&&(M.textContent=`${Math.round(t*100)}%`)}let pe=new ResizeObserver(()=>fe());pe.observe(ae),le(),se.src=n[u].url,requestAnimationFrame(()=>fe());function me(){g||(g=!0,pe.disconnect(),document.removeEventListener(`click`,te),_.remove())}return{element:_,goTo:de,next:()=>ue(1),prev:()=>ue(-1),getIndex:()=>u,setDevice(e){d=e,oe.dataset.device=e,ie?.setSelected(e),m=null,fe()},setColorScheme(e){p=e,oe.dataset.colorScheme=e},setZoom(e){m=e,fe()},destroy:me}}zc(),An();const Wv=16e3,Gv=/* @__PURE__ */ new Map([[`idle_timeout`,`Voice call ended after a quiet period.`],[`max_duration`,`This voice call reached its time limit.`],[`provider_ended`,`The voice session ended.`],[`quota`,`Voice is unavailable right now.`],[`auth_expired`,`Voice session expired. Tap the mic to reconnect.`]]),Kv=[`provider_error`,`server_restart`],qv=`Voice connection lost.`;function Jv(e,t){let n=t.slice(0,4e3).trim(),r=8e3-(n?n.length+2:0)-20,i=[];for(let t of e.slice(-12).reverse()){let e=t.content.replace(/\s+/g,` `).trim();if(!e)continue;e.length>2e3&&(e=`${e.slice(0,1999)}…`);let n=`${t.role===`user`?`User`:`Assistant`}: ${e}`;if(n.length+1>r)break;r-=n.length+1,i.unshift(n)}let a=i.length>0?[`Conversation so far:\n${i.join(`
466
+ `,document.head.appendChild(e)}function Jv(e,t){let n=e.clientWidth-48-40,r=e.clientHeight-48-40;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function Yv(e,t,n,r,i){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=i===`mobile`?`${32*r}px`:`10px`,t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin=`top left`,t.style.transform=`scale(${r})`}function Xv(e,t){let{items:n,initialIndex:r=0,initialDevice:i=`desktop`,initialColorScheme:a=`light`,showZoomControls:o=!0,showDeviceToggle:s=!0,showColorSchemeToggle:c=!0,onChange:l}=t;if(n.length===0)throw Error(`createDemoCarousel: items array must not be empty`);qv();let u=Math.max(0,Math.min(r,n.length-1)),d=i,p=a,m=null,h=1,g=!1,_=z(`div`,`persona-dc-root`),v=z(`div`,`persona-dc-toolbar`),y=z(`div`,`persona-dc-toolbar-lead`),b=z(`div`,`persona-dc-toolbar-trail`),x=Qf({icon:`chevron-left`,label:`Previous demo`,size:14,onClick:()=>de(-1)}),S=z(`div`);S.style.position=`relative`;let C=z(`button`,`persona-dc-title-btn`);C.type=`button`,C.setAttribute(`aria-expanded`,`false`),C.setAttribute(`aria-haspopup`,`listbox`);let w=z(`span`,`persona-dc-title-text`),T=z(`span`,`persona-dc-title-chevron`),E=k(f.ChevronDown,12,`currentColor`,2);E&&T.appendChild(E),C.append(w,T);let D=z(`div`,`persona-dc-dropdown`);D.setAttribute(`role`,`listbox`),D.style.display=`none`;let O=!1;function ee(){D.innerHTML=``;for(let e=0;e<n.length;e++){let t=n[e],r=z(`button`,`persona-dc-dropdown-item`);r.type=`button`,r.setAttribute(`role`,`option`),r.setAttribute(`aria-current`,e===u?`true`:`false`);let i=z(`span`);if(i.textContent=t.title,r.appendChild(i),t.description){let e=z(`span`,`persona-dc-dropdown-desc`);e.textContent=t.description,r.appendChild(e)}r.addEventListener(`click`,()=>{te(),fe(e)}),D.appendChild(r)}}function A(){O=!O,D.style.display=O?``:`none`,C.setAttribute(`aria-expanded`,O?`true`:`false`),O&&ee()}function te(){O&&(O=!1,D.style.display=`none`,C.setAttribute(`aria-expanded`,`false`))}C.addEventListener(`click`,e=>{e.stopPropagation(),A()});let ne=()=>te();document.addEventListener(`click`,ne),S.append(C,D);let re=Qf({icon:`chevron-right`,label:`Next demo`,size:14,onClick:()=>de(1)}),ie=z(`span`,`persona-dc-counter`);y.append(x,S,re,ie);let ae=null;s&&(ae=ep({items:[{id:`desktop`,icon:`monitor`,label:`Desktop`},{id:`mobile`,icon:`smartphone`,label:`Mobile`}],selectedId:d,onSelect:e=>{d=e,se.dataset.device=d,m=null,pe()}}),b.appendChild(ae.element));let j=null;if(o){let e=z(`div`,`persona-dc-zoom-controls`),t=Qf({icon:`minus`,label:`Zoom out`,size:14,onClick:()=>{m=Math.max(Gv,(m??h)-Wv),pe()}});j=z(`span`,`persona-dc-zoom-level`),j.title=`Reset to 100%`,j.style.cursor=`pointer`,j.addEventListener(`click`,()=>{m=1,pe()});let n=Qf({icon:`plus`,label:`Zoom in`,size:14,onClick:()=>{m=Math.min(Kv,(m??h)+Wv),pe()}}),r=Qf({icon:`maximize`,label:`Fit to view`,size:14,onClick:()=>{m=null,pe()}});e.append(t,j,n,r),b.appendChild(e)}if(c){let e=z(`div`,`persona-dc-separator`);b.appendChild(e);let t=ep({items:[{id:`light`,icon:`sun`,label:`Light`},{id:`dark`,icon:`moon`,label:`Dark`}],selectedId:p,onSelect:e=>{p=e,se.dataset.colorScheme=p,le()}});b.appendChild(t.element)}let M=z(`div`,`persona-dc-separator`);b.appendChild(M);let N=Qf({icon:`external-link`,label:`Open in new tab`,size:14,onClick:()=>{window.open(n[u].url,`_blank`)}});b.appendChild(N),v.append(y,b);let oe=z(`div`,`persona-dc-stage`),se=z(`div`,`persona-dc-iframe-wrapper`);se.dataset.device=d,se.dataset.colorScheme=p;let ce=z(`iframe`,`persona-dc-iframe`);ce.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-forms`),ce.setAttribute(`loading`,`lazy`),ce.title=n[u].title,se.appendChild(ce),oe.appendChild(se),_.append(v,oe),e.appendChild(_);function le(){try{let e=ce.contentDocument?.body;if(!e)return;p===`dark`?e.classList.add(`theme-dark`):e.classList.remove(`theme-dark`)}catch{}}ce.addEventListener(`load`,()=>le());function ue(){let e=n[u];w.textContent=e.title,ie.textContent=`${u+1} / ${n.length}`,ce.title=e.title}function de(e){fe(((u+e)%n.length+n.length)%n.length)}function fe(e){e<0||e>=n.length||(u=e,ce.src=n[u].url,ue(),l?.(u,n[u]))}function pe(){if(g)return;let e=Uv[d]??Uv.desktop;h=Jv(oe,e);let t=Math.max(Gv,Math.min(Kv,m??h));Yv(se,ce,e,t,d),j&&(j.textContent=`${Math.round(t*100)}%`)}let me=new ResizeObserver(()=>pe());me.observe(oe),ue(),ce.src=n[u].url,requestAnimationFrame(()=>pe());function he(){g||(g=!0,me.disconnect(),document.removeEventListener(`click`,ne),_.remove())}return{element:_,goTo:fe,next:()=>de(1),prev:()=>de(-1),getIndex:()=>u,setDevice(e){d=e,se.dataset.device=e,ae?.setSelected(e),m=null,pe()},setColorScheme(e){p=e,se.dataset.colorScheme=e},setZoom(e){m=e,pe()},destroy:he}}Gc(),jn();const Zv=16e3,Qv=/* @__PURE__ */ new Map([[`idle_timeout`,`Voice call ended after a quiet period.`],[`max_duration`,`This voice call reached its time limit.`],[`provider_ended`,`The voice session ended.`],[`quota`,`Voice is unavailable right now.`],[`auth_expired`,`Voice session expired. Tap the mic to reconnect.`]]),$v=[`provider_error`,`server_restart`],ey=`Voice connection lost.`;function ty(e,t){let n=t.slice(0,4e3).trim(),r=8e3-(n?n.length+2:0)-20,i=[];for(let t of e.slice(-12).reverse()){let e=t.content.replace(/\s+/g,` `).trim();if(!e)continue;e.length>2e3&&(e=`${e.slice(0,1999)}…`);let n=`${t.role===`user`?`User`:`Assistant`}: ${e}`;if(n.length+1>r)break;r-=n.length+1,i.unshift(n)}let a=i.length>0?[`Conversation so far:\n${i.join(`
467
467
  `)}`]:[];return n&&a.push(n),a.join(`
468
468
 
469
- `)}function Yv(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===1380533830?new Uint8Array(e,44):new Uint8Array(e)}function Xv(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 Zv(e){return Xv(e).replace(/^ws/i,`http`)}function Qv(e){return typeof e!=`number`||!Number.isFinite(e)?3e4:Math.min(6e5,Math.max(3e4,Math.round(e)))}var $v=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e){this.config=e,this.type=`runtype`,this.#e=null,this.#t=null,this.#n=[],this.#r=null,this.#i=null,this.#a=null,this.#o=[],this.#s=0,this.#c=null,this.#l=!1,this.#u=!1,this.#d=0,this.#f=!1,this.#p=-1/0,this.#m=null,this.#h=!1,this.#g=!1,this.#_=0,this.#v=0,this.#b=!1,this.bridge=null,this.#x=!1,this.#S=/* @__PURE__ */ new Set,this.#C=/* @__PURE__ */ new Map,this.#w=/* @__PURE__ */ new Set,this.#E=null,this.#D=null,this.#k=!1,this.#A=!1,this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F=/* @__PURE__ */ new Set,this.#I=/* @__PURE__ */ new Set,this.#L=null,this.#R=!1,this.#z=/* @__PURE__ */ new Set,this.#B=/* @__PURE__ */ new Set,this.#V=null,this.#H=/* @__PURE__ */ new Set,this.#U=null,this.#W=/* @__PURE__ */ new Map,this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}async connect(){}setSessionBridge(e){this.bridge=e}prewarm(){if(this.#l||this.#m)return;let e=this.config?.agentId,t=this.config?.clientToken,n=this.config?.host;if(!e||!t||!n)return;let r=Date.now();if(!(r-this.#p<3e4)){this.#p=r;try{this.config?.prewarmMode===`attach`?this.#Z(n,e,t):this.#X(n,e,t)}catch{}}}#X(e,t,n){if(typeof fetch!=`function`)return;let r=`${Zv(e)}/v1/client/agents/${encodeURIComponent(t)}/voice/prewarm`;fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${n}`},keepalive:!0}).catch(()=>{})}#Z(e,t,n){let r=new URLSearchParams,i=this.config?.attachIdleMs,a=Qv(i);i!==void 0&&r.set(`attachIdleMs`,String(a));let o=new WebSocket(this.#te(e,t,r),[`runtype.bearer`,`runtype.attach`,n]);o.binaryType=`arraybuffer`;let s=()=>{},c={ws:o,state:`connecting`,ready:new Promise(e=>{s=e}),settle:s,openedAt:0,idleTimer:void 0};this.#m=c,o.onopen=()=>{this.#m===c&&(c.state=o.protocol===`runtype.attach`?`attached`:`live`,c.openedAt=Date.now(),this.#Q(c,a),c.state===`attached`&&o.send(`{"type":"ping"}`),c.settle())},o.onmessage=e=>{if(this.#m!==c||typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}t.type===`attached`&&typeof t.idleMs==`number`&&this.#Q(c,t.idleMs-(Date.now()-c.openedAt))},o.onerror=()=>{},o.onclose=()=>{this.#m===c&&this.#$()}}#Q(e,t){clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{this.#m===e&&this.#$()},Math.max(0,t))}#$(){let e=this.#m;if(!e)return;this.#m=null,clearTimeout(e.idleTimer);let{ws:t}=e;if(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,e.settle(),t.readyState===WebSocket.CONNECTING||t.readyState===WebSocket.OPEN)try{t.close(1e3,`prewarm released`)}catch{}}async#ee(){let e=this.#m;if(!e)return null;if(e.state===`connecting`){let t;await Promise.race([e.ready,new Promise(e=>{t=setTimeout(e,5e3)})]),clearTimeout(t)}return this.#m===e?e.state===`connecting`||e.ws.readyState!==WebSocket.OPEN?(this.#$(),null):(this.#m=null,clearTimeout(e.idleTimer),{ws:e.ws,live:e.state===`live`}):null}#te(e,t,n){let r=[`partial_transcript`,`context`];this.bridge&&this.config?.clientDelegation!==!1&&(r.push(`client_delegation`,`delegation_update`,`delegation_read_back`,`delegation_stream`),this.bridge.clientTools?.()&&r.push(`client_tools`)),n&&r.unshift(`attach`);let i=new URLSearchParams({voiceProtocol:`runtype-browser-v1`,clientVersion:`persona/${kn}`,voiceCapabilities:`full-duplex-v1`,clientCapabilities:r.join(`,`)});return n?.forEach((e,t)=>i.set(t,e)),`${Xv(e)}/ws/agents/${encodeURIComponent(t)}/voice?${i}`}async startListening(){if(this.#l)return;let e=this.#A;e||(this.#k=!1,this.#D=null),this.#A=!1;let t=this.config?.agentId,n=this.config?.clientToken,r=this.config?.host;if(!t)throw Error(`Runtype voice requires an agentId`);if(!n)throw Error(`Runtype voice requires a clientToken`);if(!r)throw Error(`Runtype voice requires a host (or widget apiUrl)`);let i=++this.#d;this.#f=!1,this.#l=!0;try{let a=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Wv,channelCount:1,echoCancellation:!0}});if(i!==this.#d){a.getTracks().forEach(e=>e.stop());return}this.#r=a;let o=new(window.AudioContext||window.webkitAudioContext)({sampleRate:Wv});if(this.#t=o,o.state===`suspended`){if(await Promise.race([o.resume().catch(()=>{}),new Promise(t=>setTimeout(t,e?500:1e3))]),i!==this.#d)return;if(o.state!==`running`)throw Error(e?this.#D=`${qv} Tap the mic to reconnect.`:`Audio blocked until a tap`)}let s=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Rc(24e3);if(i!==this.#d){s.destroy(),a.getTracks().forEach(e=>e.stop()),o.close().catch(()=>{});return}this.#c=s,this.#he(),this.#ie(o,a,i);let c=await this.#ee();if(i!==this.#d){c?.ws.close(1e3,`client ended call`);return}if(c){let{ws:e}=c;this.#e=e,this.#ne(e,i),c.live||e.send(`{"type":"start"}`),this.#ae(e),this.#be(`listening`);return}let l=new WebSocket(this.#te(r,t),[`runtype.bearer`,n]);l.binaryType=`arraybuffer`,this.#e=l,l.onopen=()=>{i===this.#d&&(this.#ae(l),this.#be(`listening`))},this.#ne(l,i)}catch(e){throw this.#ye(),this.#xe(e),this.#be(`error`),e}}#ne(e,t){e.onmessage=e=>this.#oe(e,t),e.onerror=()=>{t!==this.#d||this.#E||(this.#xe(/* @__PURE__ */ Error(`Voice connection failed`)),this.#be(`error`),this.#ye())},e.onclose=e=>{if(this.#f){this.#f=!1;return}if(t!==this.#d)return;let n=this.#E??(e.code===4408?{reason:`idle_timeout`}:null);if(n)this.#re(n.reason,n.message);else{if(e.code!==1e3){let t=e.code?` (code ${e.code})`:``;this.#xe(/* @__PURE__ */ Error(`Voice connection closed${t}`)),this.#be(`error`)}else this.#be(`idle`);this.#ye()}}}#re(e,t){let n=Kv.includes(e)&&!this.#k;if(this.#ye(),n)this.#k=!0,this.#l=!0,this.#D=e===`provider_error`?`${qv} Reconnecting…`:`Reconnecting…`,this.#O=setTimeout(()=>{this.#l=!1,this.#A=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#be(`idle`);else{if(Kv.includes(e))return this.#D=qv,this.#xe(/* @__PURE__ */ Error(qv)),this.#be(`error`);if(e===`error`)return this.#be(`error`);this.#D=e===`quota`&&t||Gv.get(e)||null,this.#be(`idle`)}}takeNotice(){let e=this.#D;return this.#D=null,e}getDisclosure(){let e=this.config?.disclosureText;return this.#l&&this.#h&&e!==!1?e||`You're talking to an AI assistant. Voice is processed by OpenAI.`:null}async stopListening(){this.#ye(),this.#be(`idle`)}async disconnect(){this.#ye(),this.#be(`disconnected`),this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}stopPlayback(){this.#ve();let e=this.#e;e&&e.readyState===WebSocket.OPEN&&(this.#h&&(this.#_=Date.now()+2e3,e.send(`{"type":"cancel"}`)),this.#be(`listening`))}getInterruptionMode(){return`barge-in`}isBargeInActive(){return this.#l}onLevel(e){this.#n.push(e)}async deactivateBargeIn(){this.#ye(),this.#be(`idle`)}#ie(e,t,n){let r=e.createMediaStreamSource(t);this.#i=r;let i=e.createScriptProcessor(4096,1,1);this.#a=i,i.onaudioprocess=e=>{if(n!==this.#d)return;let t=this.#e,r=t?.readyState===WebSocket.OPEN;if(t&&!r&&t.readyState!==WebSocket.CONNECTING)return;let i=e.inputBuffer.getChannelData(0),a=new Int16Array(i.length),o=0;for(let e=0;e<i.length;e++){let t=Math.max(-1,Math.min(1,i[e]));o+=t*t,a[e]=t<0?t*32768:t*32767}if(t&&r)this.#ae(t),t.send(a.buffer);else for(this.#o.push(a.buffer),this.#s+=a.byteLength;this.#s>256e3;)this.#s-=this.#o.shift().byteLength;if(this.#n.length>0){let e=Math.sqrt(o/i.length),t=Math.max(0,Math.min(1,e*4));for(let e of this.#n)e(t)}},r.connect(i),i.connect(e.destination)}#ae(e){for(let t of this.#o)e.send(t);this.#o=[],this.#s=0}#oe(e,t){if(t!==this.#d)return;if(e.data instanceof ArrayBuffer){this.#pe(e.data,t);return}let n;try{n=JSON.parse(e.data)}catch{return}switch(n.type){case`session_config`:n.speechMode&&(this.#h=n.speechMode===`speech_to_speech`,this.#c?.setContinuousMode?.(this.#h)),Array.isArray(n.capabilities)&&(this.#S=new Set(n.capabilities)),typeof n.callId==`string`&&(this.#T=n.callId),this.#x=this.#h&&this.#S.has(`client_delegation`)&&!!this.bridge,this.#h&&!this.#u&&this.#be(`listening`),this.#S.has(`context`)&&!this.#j&&(this.#j=!0,this.#M=this.#se()),this.#x&&this.#S.has(`client_tools`)&&!this.#V&&(this.#V=this.bridge?.clientTools?.()?.open({send:e=>{let n=this.#e;return t!==this.#d||n?.readyState!==WebSocket.OPEN?!1:(n.send(JSON.stringify(e)),!0)},cancelled:e=>this.#w.has(e)}).catch(()=>null)??null);break;case`client_tool_call`:{let e=String(n.delegationId);this.#V&&!this.#W.has(e)&&(this.#W.set(e,this.#U),this.#F.add(e)),this.#V?.then(e=>e?.call(n));break}case`transcript_update`:{let e=n.role===`assistant`?`assistant`:`user`,r=n.utteranceId??n.turnId;if(!r||e===`assistant`&&this.#me())break;let i=String(r);if(e===`user`)n.final===!0&&(this.#ce(t),this.#U={id:i,text:String(n.text??``)}),this.#R=!1;else{if(this.#S.has(`delegation_read_back`)){let e=n.delegationId;(typeof e==`string`&&this.#F.has(e)&&!this.#z.has(i)||this.#R&&!this.#z.has(i))&&(this.#B.add(i),this.#R=!1)}else this.#R&&!this.#z.has(i)&&(this.#B.add(i),this.#R=!1);if(this.#z.add(i),this.#B.has(i))break}this.#Se(e,n.text??``,n.final===!0,{turnId:i,...typeof n.startMs==`number`&&{startMs:n.startMs},...typeof n.endMs==`number`&&{endMs:n.endMs},...this.#x&&{caption:!0}});break}case`delegation_started`:case`delegation_completed`:{let e=String(n.delegationId??n.turnId);if(n.type===`delegation_started`){this.#ce(t),this.#H.add(e),this.#F.delete(e),this.#W.delete(e)&&this.#V?.then(t=>t?.abort(e));let r=n.input;this.#x&&r&&this.#fe(e,{delegationId:e,userText:String(r.text??``),userUtteranceIds:Array.isArray(r.userUtteranceIds)?r.userUtteranceIds.filter(e=>typeof e==`string`):[],messages:Array.isArray(r.messages)?r.messages:[]},t)}else if(n.route===`direct`&&this.#V&&!this.#H.has(e)){let t=this.#W.get(e)??this.#U;this.#W.delete(e),this.#H.add(e),this.#F.add(e),this.bridge?.recordDirectTurn?.({delegationId:e,userText:t?.text??``,userUtteranceIds:t?[t.id]:[],assistantText:typeof n.text==`string`?n.text:``})}n.type===`delegation_completed`&&n.speak!==!1&&this.#F.has(e)&&!this.#I.delete(e)&&!this.#S.has(`delegation_read_back`)&&this.#ue(e),this.#g=n.type===`delegation_started`,!this.#u&&!this.#me()&&this.#be(this.#g?`processing`:`listening`);break}case`delegation_progress`:{let e=String(n.delegationId);this.#F.has(e)&&!this.#I.has(e)&&!this.#w.has(e)&&(this.#I.add(e),this.#ue(e));break}case`delegation_cancelled`:this.#de(String(n.delegationId),n.reason!==`session_ending`&&n.reason!==`provider_cancelled`);break;case`warning`:console.warn(`[Persona voice] ${n.code}: ${n.message??``}`,this.#T??``),n.delegationId&&(n.code===`UNKNOWN_DELEGATION`||n.code===`LATE_RESULT_LIMIT`)&&this.#de(String(n.delegationId));break;case`audio_clear`:this.#ve(),this.#_=0,this.#be(`listening`);break;case`transcript_interim`:this.#be(`listening`),this.#Se(`user`,n.text??``,!1);break;case`transcript_final`:{let e=n.role===`assistant`?`assistant`:`user`;this.#be(e===`user`?`processing`:`speaking`),this.#Se(e,n.text??``,!0);break}case`audio_end`:this.#c?this.#c.markStreamEnd():(this.#u=!1,this.#be(`listening`));break;case`metrics`:this.#Ce({llmMs:n.llm_ms,ttsMs:n.tts_ms,firstAudioMs:n.first_audio_ms,totalMs:n.total_ms});break;case`error`:this.#xe(Error(n.error||`Voice error`)),this.#be(`error`);break;case`session_end`:this.#E={reason:String(n.reason),...typeof n.message==`string`&&{message:n.message}}}}async#se(){let e=this.bridge?.getHistory()??[],t=``;try{let e=this.config?.callContext;t=String((typeof e==`function`?await e():e)??``)}catch{}return Jv(e,t)}#ce(e){let t=this.#M;if(!t)return;this.#M=null;let n=!1,r=t.then(t=>{let r=this.#e;!n&&t&&e===this.#d&&r?.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:`context`,text:t}))});this.#N={done:r,drop:()=>n=!0}}async#le(){let e=this.#N;if(!e)return;let t,n=await Promise.race([e.done.then(()=>!1),new Promise(e=>{t=setTimeout(()=>e(!0),2e3)})]);clearTimeout(t),n&&e.drop()}#ue(e){this.#R=!0,this.#L=e}#de(e,t=!1){this.#w.add(e),this.#L===e&&(this.#R=!1),this.#I.delete(e),this.#H.has(e)||this.#F.delete(e),this.#V?.then(t=>t?.abort(e)),this.bridge?.dropDelegation?.(e,t),this.#C.get(e)?.abort()}#fe(e,t,n){let r=this.bridge,i=({type:t,...r})=>{let i=this.#e;return n!==this.#d||i?.readyState!==WebSocket.OPEN||this.#w.has(e)?!1:(i.send(JSON.stringify({type:t,delegationId:e,...r})),!0)},a=(e,t,n,r=0)=>i({type:e,status:t,text:n,...r>0&&{streamedChars:r}});this.#P=this.#P.then(async()=>{if(n!==this.#d||this.#w.has(e))return;let o=null,s=this.#S.has(`delegation_stream`)&&this.#S.has(`delegation_read_back`),c=t=>{o=(o??this.#le()).then(()=>{i({type:`delegation_delta`,text:t})&&this.#F.add(e)})},l=await r.runDelegatedTurn(s?{...t,stream:c}:t).catch(()=>({status:`failed`,text:``}));await this.#le(),await o;let u=s?l.streamedChars??0:0,d=!!l.followUp,f=d&&this.#S.has(`delegation_update`);if(!a(f?`delegation_update`:`delegation_result`,d&&!f?`completed`:l.status,l.text,u)||(l.status!==`failed`&&l.inChat!==!1&&this.#F.add(e),!l.followUp))return;let p=new AbortController;this.#C.set(e,p),l.followUp({signal:p.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,54e4),readBack:f,onUpdate:e=>a(`delegation_update`,`pending_approval`,e)}).then(t=>{this.#C.delete(e),f&&t&&!p.signal.aborted&&a(`delegation_result`,t.status,t.text)})})}#pe(e,t){if(t!==this.#d||!this.#c||this.#me())return;let n=Yv(e);n.length!==0&&(this.#u||(this.#u=!0,this.#be(`speaking`)),this.#he(),this.#c.enqueue(n),this.#h&&this.#ge(n.length))}#me(){return Date.now()<this.#_}#he(){if(this.#b||!this.#c)return;this.#b=!0;let e=this.#d;this.#c.onFinished(()=>{e===this.#d&&(this.#b=!1,this.#_e())})}#ge(e){let t=Date.now();this.#v=Math.max(t,this.#v)+e/48,clearTimeout(this.#y),this.#y=setTimeout(()=>this.#_e(),this.#v-t+300)}#_e(){this.#u=!1,this.#v=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#be(this.#g?`processing`:`listening`)}#ve(){this.#c?.flush(),this.#b=!1,this.#he(),this.#u=!1,this.#v=0,clearTimeout(this.#y)}#ye(){this.#d+=1,this.#l=!1,this.#u=!1,this.#$(),this.#h=!1,this.#g=!1,this.#x=!1,this.#S=/* @__PURE__ */ new Set;for(let e of this.#C.values())e.abort();if(this.#C.clear(),this.#w.clear(),this.#T=void 0,this.#E=null,clearTimeout(this.#O),this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F.clear(),this.#I.clear(),this.#L=null,this.#R=!1,this.#z.clear(),this.#B.clear(),this.#V?.then(e=>e?.close()),this.#V=null,this.#H.clear(),this.#W.clear(),this.#U=null,this.#b=!1,this.#_=0,this.#v=0,clearTimeout(this.#y),this.#o=[],this.#s=0,this.#a&&=(this.#a.onaudioprocess=null,this.#a.disconnect(),null),this.#i&&=(this.#i.disconnect(),null),this.#r&&=(this.#r.getTracks().forEach(e=>e.stop()),null),this.#t&&=(this.#t.close().catch(()=>{}),null),this.#c&&=(this.#c.destroy(),null),this.#e){this.#f=!0;try{this.#e.close(1e3,`client ended call`)}catch{}this.#e=null}}onResult(e){this.#G.push(e)}onError(e){this.#K.push(e)}onStatusChange(e){this.#q.push(e)}onTranscript(e){this.#J.push(e)}onMetrics(e){this.#Y.push(e)}#be(e){this.#q.forEach(t=>t(e))}#xe(e){this.#K.forEach(t=>t(e))}#Se(e,t,n,r){this.#J.forEach(i=>i(e,t,n,r))}#Ce(e){this.#Y.forEach(t=>t(e))}},ey=class{#e;#t;#n;#r;#i;#a;constructor(e={}){this.config=e,this.type=`browser`,this.#e=null,this.#t=[],this.#n=[],this.#r=[],this.#i=!1,this.#a=typeof window<`u`?window:void 0}async connect(){this.#r.forEach(e=>e(`connected`))}async startListening(){try{if(this.#i)throw Error(`Already listening`);if(!this.#a)throw Error(`Window object not available`);let e=this.#a.SpeechRecognition||this.#a.webkitSpeechRecognition;if(!e)throw Error(`Browser speech recognition not supported`);this.#e=new e,this.#e.lang=this.config?.language||`en-US`,this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.onresult=e=>{let t=Array.from(e.results).map(e=>e[0]).map(e=>e.transcript).join(``),n=e.results[e.results.length-1].isFinal;this.#t.forEach(e=>e({text:t,confidence:n?.8:.5,provider:`browser`})),n&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=e=>{this.#n.forEach(t=>t(Error(e.error))),this.#r.forEach(e=>e(`error`))},this.#e.onstart=()=>{this.#i=!0,this.#r.forEach(e=>e(`listening`))},this.#e.onend=()=>{this.#i=!1,this.#r.forEach(e=>e(`idle`))},this.#e.start()}catch(e){throw this.#n.forEach(t=>t(e)),this.#r.forEach(e=>e(`error`)),e}}async stopListening(){this.#e&&=(this.#e.stop(),null),this.#i=!1,this.#r.forEach(e=>e(`idle`))}onResult(e){this.#t.push(e)}onError(e){this.#n.push(e)}onStatusChange(e){this.#r.push(e)}async disconnect(){await this.stopListening(),this.#r.forEach(e=>e(`disconnected`))}static isSupported(){return`SpeechRecognition`in window||`webkitSpeechRecognition`in window}};function ty(e){switch(e.type){case`runtype`:if(!e.runtype)throw Error(`Runtype voice provider requires configuration`);return new $v(e.runtype);case`browser`:if(!ey.isSupported())throw Error(`Browser speech recognition not supported`);return new ey(e.browser||{});case`custom`:{let t=e.custom;if(!t)throw Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t==`function`?t():t;if(!n||typeof n.startListening!=`function`)throw Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw Error(`Unknown voice provider type: ${e.type}`)}}function ny(e){if(e?.type===`custom`&&e.custom)return ty({type:`custom`,custom:e.custom});if(e?.type===`runtype`&&e.runtype)return ty({type:`runtype`,runtype:e.runtype});if(ey.isSupported())return ty({type:`browser`,browser:e?.browser||{language:`en-US`}});throw Error(`No supported voice providers available`)}function ry(e){try{return ny(e),!0}catch{return!1}}const iy=(e,t)=>({ok:!1,reason:e,message:t}),ay=e=>e.startsWith(`webmcp:`)?e.slice(7):e,oy={warn(e,...t){typeof console<`u`&&typeof console.warn==`function`&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};var sy=class{#e;#t;#n=!1;#r=null;#i=!1;#a;constructor(e,t){this.config=e,this.#a=t,this.#e=e.onConfirm??null,this.#t=3e4}setConfirmHandler(e){this.#e=e}isOperational(){return this.config.enabled!==!0||!this.#n?!1:this.#l()!==null}async snapshotForDispatch(){if(await this.#s(),this.config.enabled!==!0)return[];let e=this.#l();if(!e)return[];let t;try{t=(await e.getTools()).filter(yy)}catch(e){return oy.warn(`getTools() threw: shipping an empty WebMCP snapshot.`,e),[]}this.#a.recordToolDisplayTitles(t);let n=typeof location<`u`?location.origin:``;return t.filter(e=>this.#d(e.name)).map(e=>{let t=uy(e.annotations);return{name:e.name,description:e.description,parametersSchema:dy(e.inputSchema),origin:`webmcp`,...n?{pageOrigin:n}:{},...t?{annotations:t}:{},...t?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(e,t,n){let r=await this.#o(e,t,n,!1);return r.ok?fy(r.raw):my(r.message)}async executeVoiceToolCall(e,t,n={}){let r=await this.#o(e,t,n.signal,n.autoConfirmReadOnly===!0);return r.ok?gy(r.raw):{status:r.reason===`aborted`?`failed`:r.reason,error:{message:r.message}}}watchToolChanges(e){let t=!1,n=null;return this.#s().then(()=>{if(t||this.config.enabled!==!0)return;let r=this.#l();r&&typeof r.addEventListener==`function`&&(n=r,n.addEventListener(`toolchange`,e))}),()=>{t=!0,n?.removeEventListener(`toolchange`,e),n=null}}async#o(e,t,n,r){if(await this.#s(),this.config.enabled!==!0)return iy(`failed`,`WebMCP is not enabled on this widget.`);let i=this.#l();if(!i){let e=typeof document<`u`&&!!document.modelContext;return iy(`failed`,e?`WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).`:`WebMCP bridge is not operational on this page (document.modelContext not available).`)}let a=ay(e),o;try{o=(await i.getTools()).filter(yy)}catch(e){let t=e instanceof Error?e.message:String(e);return iy(`failed`,`Failed to read WebMCP registry: ${t}`)}this.#a.recordToolDisplayTitles(o);let s=o.find(e=>e.name===a);if(!s)return iy(`stale`,`WebMCP tool not registered on this page: ${a}`);if(!this.#d(a))return iy(`stale`,`WebMCP tool not allowed by client allowlist: ${a}`);if(n?.aborted)return iy(`aborted`,`Aborted by cancel()`);let c=this.#a.getToolDisplayTitle(a),l=uy(s.annotations),u={toolName:a,args:t,description:s.description,...l?{annotations:l}:{},...c?{title:c}:{},...n?{signal:n}:{},reason:`gate`};if(!(r&&l?.readOnlyHint===!0)&&!await this.#u(u))return iy(`denied`,`User declined the tool call.`);if(n?.aborted)return iy(`aborted`,`Aborted by cancel()`);let d=new AbortController,f=!1,p=setTimeout(()=>{f=!0,d.abort()},this.#t),m=()=>d.abort();n&&(n.aborted?d.abort():n.addEventListener(`abort`,m,{once:!0}));try{return{ok:!0,raw:await i.executeTool(s,py(t),{signal:d.signal})}}catch(e){if(f)return iy(`timeout`,`WebMCP tool '${a}' timed out after ${this.#t}ms`);if(n?.aborted)return iy(`aborted`,`Aborted by cancel()`);let t=e instanceof Error?e.message:String(e);return iy(`failed`,t)}finally{clearTimeout(p),n&&n.removeEventListener(`abort`,m)}}#s(){return this.config.enabled===!0?(this.#r||=this.#c(),this.#r):Promise.resolve()}async#c(){try{if(this.#l()){this.#n=!0;return}let e=await this.#a.loadPolyfill();`initializeWebMCPPolyfill`in e?e.initializeWebMCPPolyfill():e.installWebMCP(),this.#n=!0}catch(e){oy.warn(`Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.`,e),this.#n=!1}}#l(){if(typeof document>`u`)return null;let e=document.modelContext;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.getTools!=`function`||typeof t.executeTool!=`function`?(this.#i||(this.#i=!0,oy.warn(`document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).`)),null):e}async#u(e){let t=this.#e??_y;try{return await t(e)}catch(t){return oy.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,t),!1}}#d(e){let t=this.config.allowlist;return!t||t.length===0||t.some(t=>cy(e,t))}};const cy=(e,t)=>{if(t===`*`)return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`^`+n.replace(/\*/g,`.*`)+`$`).test(e)},ly={type:`object`,properties:{}},uy=e=>{if(!e||typeof e!=`object`)return;let t={};for(let n of[`readOnlyHint`,`destructiveHint`,`consequentialHint`,`untrustedContentHint`,`idempotentHint`,`openWorldHint`,`debugging`]){let r=e[n];typeof r==`boolean`&&(t[n]=r)}return Object.keys(t).length>0?t:void 0},dy=e=>{if(e===void 0||e===``)return{...ly};if(typeof e==`object`)return e!==null&&!Array.isArray(e)?e:{...ly};try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{...ly}}catch{return{...ly}}},fy=e=>{if(e==null)return{content:[{type:`text`,text:``}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:`text`,text:e}]}}return typeof t==`object`&&t&&Array.isArray(t.content)?t:{content:[{type:`text`,text:typeof t==`string`?t:by(t)}]}},py=e=>{let t;try{t=JSON.stringify(e)??`{}`}catch{t=`{}`}let n=JSON.parse(t);if(typeof n!=`object`||!n)throw TypeError(`WebMCP tool arguments must be an object or array.`);return Object.defineProperty(n,Symbol.toPrimitive,{value:()=>t}),n},my=e=>({isError:!0,content:[{type:`text`,text:e}]}),hy=e=>Array.isArray(e)?e.map(e=>e&&typeof e==`object`&&typeof e.text==`string`?e.text:``).filter(Boolean).join(`
470
- `):``,gy=e=>{if(e==null)return{status:`completed`};let t;try{t=JSON.parse(e)}catch{return{status:`completed`,result:e}}return typeof t==`object`&&t&&t.isError===!0?{status:`failed`,error:{message:hy(t.content)||`The page tool reported an error.`}}:t===void 0?{status:`completed`}:{status:`completed`,result:t}},_y=async e=>{if(typeof window>`u`||typeof window.confirm!=`function`)return!1;let t=vy(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`\n\nArguments:\n${t}`:``)+(e.description?`\n\n${e.description}`:``);return window.confirm(n)},vy=e=>{if(e==null)return``;try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+`…`:t}catch{return String(e)}},yy=e=>(e.window===void 0||typeof window<`u`&&e.window===window)&&(e.origin===void 0||typeof location<`u`&&e.origin===location.origin),by=e=>{if(e===void 0)return``;try{return JSON.stringify(e)}catch{return String(e)}};Ce();var xy=class extends sy{constructor(e){super(e,{recordToolDisplayTitles:L,getToolDisplayTitle:be,loadPolyfill:Se})}};function Sy(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}function Cy(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n.startsWith(r)?0:e.replace(/([a-z])([A-Z])/g,`$1 $2`).split(/[\s\-_/.]+/).some(e=>e.toLowerCase().startsWith(r))?1:Sy(r,n)?2:3}function wy(e,t){let n=e.recencyScore??0,r=t.recencyScore??0;return r===n?e.label.localeCompare(t.label):r-n}function Ty(e,t){let n=t.trim();if(!n)return[...e].sort(wy);let r=[];for(let t of e){let e=Cy(t.label,n);e!==3&&r.push({item:t,tier:e})}return r.sort((e,t)=>e.tier===t.tier?wy(e.item,t.item):e.tier-t.tier),r.map(e=>e.item)}function Ey(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 Dy(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>Ty(e.items,t),resolve:e.resolve}}function Oy(e){let t=e.commands.map(e=>({id:e.name,label:e.name,description:e.description,iconName:e.iconName,command:e.kind??`prompt`,insertMode:e.insertMode,submitOnSelect:e.submitOnSelect,action:e.action,commandArgsPlaceholder:e.argsPlaceholder})),n=new Map(e.commands.map(e=>[e.name,e])),r=new Map(t.map(e=>[e.id,e]));return{id:e.id,label:e.label,matchCommand:e=>r.get(e),resolveOn:`submit`,search:e=>Ty(t,Ey(e).name),resolve:(e,t)=>{let r=n.get(e.id);return r?r.kind===`server`?{context:(typeof r.data==`function`?r.data(t.args):r.data)??{}}:{insertText:typeof r.prompt==`function`?r.prompt(t.args):r.prompt??``}:{}}}}function ky(e,t){let n=t.orientation??`horizontal`,r=n===`vertical`?`ArrowUp`:`ArrowLeft`,i=n===`vertical`?`ArrowDown`:`ArrowRight`;e.setAttribute(`role`,`tablist`);let a=[],o=!1,s=e=>{typeof e.scrollIntoView==`function`&&e.scrollIntoView({block:`nearest`,inline:`nearest`})},c=e=>{let t=e;return a.findIndex(e=>e===t||e.contains(t))},l=e=>{let n=c(e.target);if(n<0)return;let o=n;if(e.key===i)o=Math.min(n+1,a.length-1);else if(e.key===r)o=Math.max(n-1,0);else if(e.key===`Home`)o=0;else if(e.key===`End`)o=a.length-1;else return;e.preventDefault(),o!==n&&t.onSelect(o)},u=e=>{let t=c(e.target);t>=0&&s(a[t])};return e.addEventListener(`keydown`,l),e.addEventListener(`focusin`,u),{beforeRender(){o=typeof document<`u`&&e.contains(document.activeElement)},render(e,t){if(a=e,e.forEach((e,n)=>{e.setAttribute(`role`,`tab`);let r=n===t;e.setAttribute(`aria-selected`,r?`true`:`false`),e.tabIndex=r||t<0&&n===0?0:-1}),o){let n=(t>=0?e[t]:void 0)??e[0];n&&typeof n.focus==`function`&&(s(n),n.focus())}},destroy(){e.removeEventListener(`keydown`,l),e.removeEventListener(`focusin`,u)}}}I(),Ce(),Ze(),Gt(),nn(),sn(),An(),wi(),Ui(),exports.ASK_USER_QUESTION_CLIENT_TOOL=an,exports.ASK_USER_QUESTION_PARAMETERS_SCHEMA=rn,exports.ASK_USER_QUESTION_TOOL_NAME=$e,exports.AgentWidgetClient=pc,exports.AgentWidgetSession=rl,exports.AttachmentManager=ll,exports.BrowserSpeechEngine=Dc,exports.DEFAULT_COMPONENTS=Bu,exports.DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH=mi,exports.DEFAULT_FLOATING_LAUNCHER_WIDTH=pi,exports.DEFAULT_PALETTE=Pu,exports.DEFAULT_SEMANTIC=Lu,exports.DEFAULT_WIDGET_CONFIG=Ci,exports.HistoryProviderError=mc,exports.PRESETS=$_,exports.PRESET_FULLSCREEN=Q_,exports.PRESET_MINIMAL=Z_,exports.PRESET_SHOP=X_,exports.ReadAloudController=Oc,exports.SUGGEST_REPLIES_CLIENT_TOOL=Jt,exports.SUGGEST_REPLIES_PARAMETERS_SCHEMA=qt,exports.SUGGEST_REPLIES_TOOL_NAME=Kt,exports.THEME_ZONES=ed,exports.VERSION=kn,exports.WEBMCP_TOOL_PREFIX=ve,exports.WebMcpBridge=xy,exports.accessibilityPlugin=nv,exports.animationsPlugin=rv,exports.applyFeaturePreferences=Fh,exports.applyThemeVariables=vd,exports.attachHeaderToContainer=Wf,exports.brandPlugin=iv,exports.buildComposer=rp,exports.buildDefaultHeader=Zf,exports.buildHeader=Uf,exports.buildHeaderWithLayout=np,exports.buildMinimalHeader=$f,exports.builtInClientToolsForDispatch=on,exports.canonicalArtifactDisplayMode=we,exports.collectEnrichedPageContext=K_,exports.componentRegistry=qm,exports.createActionManager=sg,exports.createAgentExperience=Kg,exports.createAskUserQuestionBubble=zt,exports.createBestAvailableVoiceProvider=ny,exports.createBubbleWithLayout=Np,exports.createCSATFeedback=Ag,exports.createComboButton=Xf,exports.createComponentMiddleware=Tg,exports.createComponentStreamParser=Sg,exports.createDefaultSanitizer=As,exports.createDemoCarousel=Uv,exports.createDirectivePostprocessor=Es,exports.createDropdownMenu=Gf,exports.createFlexibleJsonStreamParser=Ye,exports.createIconButton=Kf,exports.createImagePart=Ai,exports.createJsonStreamParser=Je,exports.createLabelButton=qf,exports.createLocalStorageAdapter=dg,exports.createMarkdownProcessor=vs,exports.createMarkdownProcessorFromConfig=ys,exports.createMessageActions=jp,exports.createNPSFeedback=jg,exports.createPlainTextParser=Ke,exports.createPlugin=cv,exports.createRegexJsonParser=qe,exports.createRovingTablist=ky,exports.createSlashCommandsSource=Oy,exports.createSplitButton=Yf,exports.createStandardBubble=Mp,exports.createStaticMentionSource=Dy,exports.createTextPart=ki,exports.createTheme=Ju,exports.createThemeObserver=yd,exports.createToggleGroup=Jf,exports.createTypingIndicator=Sp,exports.createVoiceProvider=ty,exports.createWidgetHostLayout=d_,exports.createXmlParser=Xe,exports.default=tv,exports.defaultActionHandlers=ag,exports.defaultJsonActionParser=rg,exports.defaultMentionFilter=Ty,exports.defaultParseRules=j_,exports.detectColorScheme=dd,exports.directivePostprocessor=Ds,exports.ensureAskUserQuestionSheet=Bt,exports.escapeHtml=Ss,exports.extractComponentDirectiveFromMessage=Og,exports.fileToImagePart=ji,exports.formatEnrichedContext=q_,exports.generateAssistantMessageId=ec,exports.generateCodeSnippet=Ov,exports.generateMessageId=Qs,exports.generateStableSelector=z_,exports.generateUserMessageId=$s,exports.getActiveTheme=gd,exports.getAgentWidgetHandles=h_,exports.getColorScheme=pd,exports.getDisplayText=Ei,exports.getHeaderLayout=tp,exports.getImageParts=Oi,exports.getPreset=ev,exports.hasComponentDirective=Dg,exports.hasImages=Di,exports.headerLayouts=ep,exports.highContrastPlugin=ov,exports.initAgentWidget=g_,exports.isAskUserQuestionMessage=pt,exports.isComponentDirectiveType=Cg,exports.isDockedMountMode=Cf,exports.isHistoryProviderError=hc,exports.isSuggestRepliesMessage=Xt,exports.isVoiceSupported=ry,exports.isWebMcpToolName=xe,exports.isWelcomeVisible=$p,exports.latestAgentSuggestions=Qt,exports.listRegisteredStreamAnimations=Xd,exports.loadMarkdownParsers=T,exports.markdownPostprocessor=xs,exports.mergeWithDefaults=fi,exports.normalizeContent=Ti,exports.normalizeMediaType=Te,exports.onMarkdownParsersReady=E,exports.parseAskUserQuestionPayload=ht,exports.parseSuggestRepliesPayload=Zt,exports.parseWidgetPreferenceSlice=kh,exports.pickBestVoice=Ec,exports.pluginRegistry=Yh,exports.reducedMotionPlugin=av,exports.registerIcons=ue,exports.registerStreamAnimationPlugin=Jd,exports.removeAskUserQuestionSheet=Vt,exports.renderComponentDirective=wg,exports.renderLoadingIndicatorWithFallback=Cp,exports.renderLucideIcon=F,exports.resolveArtifactDisplay=De,exports.resolveArtifactDisplayMode=Oe,exports.resolveConfigPreferences=Ih,exports.resolveDockConfig=Tf,exports.resolveSanitizer=js,exports.resolveTokens=Wu,exports.resolveWelcomeConfig=Zp,exports.stripWebMcpPrefix=z,exports.themeToCssVariables=$u,exports.unregisterStreamAnimationPlugin=Yd,exports.validateImageFile=Mi,exports.validateTheme=Gu;
469
+ `)}function ny(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===1380533830?new Uint8Array(e,44):new Uint8Array(e)}function ry(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 iy(e){return ry(e).replace(/^ws/i,`http`)}function ay(e){return typeof e!=`number`||!Number.isFinite(e)?3e4:Math.min(6e5,Math.max(3e4,Math.round(e)))}var oy=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e){this.config=e,this.type=`runtype`,this.#e=null,this.#t=null,this.#n=[],this.#r=null,this.#i=null,this.#a=null,this.#o=[],this.#s=0,this.#c=null,this.#l=!1,this.#u=!1,this.#d=0,this.#f=!1,this.#p=-1/0,this.#m=null,this.#h=!1,this.#g=!1,this.#_=0,this.#v=0,this.#b=!1,this.bridge=null,this.#x=!1,this.#S=/* @__PURE__ */ new Set,this.#C=/* @__PURE__ */ new Map,this.#w=/* @__PURE__ */ new Set,this.#E=null,this.#D=null,this.#k=!1,this.#A=!1,this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F=/* @__PURE__ */ new Set,this.#I=/* @__PURE__ */ new Set,this.#L=null,this.#R=!1,this.#z=/* @__PURE__ */ new Set,this.#B=/* @__PURE__ */ new Set,this.#V=null,this.#H=/* @__PURE__ */ new Set,this.#U=null,this.#W=/* @__PURE__ */ new Map,this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}async connect(){}setSessionBridge(e){this.bridge=e}prewarm(){if(this.#l||this.#m)return;let e=this.config?.agentId,t=this.config?.clientToken,n=this.config?.host;if(!e||!t||!n)return;let r=Date.now();if(!(r-this.#p<3e4)){this.#p=r;try{this.config?.prewarmMode===`attach`?this.#Z(n,e,t):this.#X(n,e,t)}catch{}}}#X(e,t,n){if(typeof fetch!=`function`)return;let r=`${iy(e)}/v1/client/agents/${encodeURIComponent(t)}/voice/prewarm`;fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${n}`},keepalive:!0}).catch(()=>{})}#Z(e,t,n){let r=new URLSearchParams,i=this.config?.attachIdleMs,a=ay(i);i!==void 0&&r.set(`attachIdleMs`,String(a));let o=new WebSocket(this.#te(e,t,r),[`runtype.bearer`,`runtype.attach`,n]);o.binaryType=`arraybuffer`;let s=()=>{},c={ws:o,state:`connecting`,ready:new Promise(e=>{s=e}),settle:s,openedAt:0,idleTimer:void 0};this.#m=c,o.onopen=()=>{this.#m===c&&(c.state=o.protocol===`runtype.attach`?`attached`:`live`,c.openedAt=Date.now(),this.#Q(c,a),c.state===`attached`&&o.send(`{"type":"ping"}`),c.settle())},o.onmessage=e=>{if(this.#m!==c||typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}t.type===`attached`&&typeof t.idleMs==`number`&&this.#Q(c,t.idleMs-(Date.now()-c.openedAt))},o.onerror=()=>{},o.onclose=()=>{this.#m===c&&this.#$()}}#Q(e,t){clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{this.#m===e&&this.#$()},Math.max(0,t))}#$(){let e=this.#m;if(!e)return;this.#m=null,clearTimeout(e.idleTimer);let{ws:t}=e;if(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,e.settle(),t.readyState===WebSocket.CONNECTING||t.readyState===WebSocket.OPEN)try{t.close(1e3,`prewarm released`)}catch{}}async#ee(){let e=this.#m;if(!e)return null;if(e.state===`connecting`){let t;await Promise.race([e.ready,new Promise(e=>{t=setTimeout(e,5e3)})]),clearTimeout(t)}return this.#m===e?e.state===`connecting`||e.ws.readyState!==WebSocket.OPEN?(this.#$(),null):(this.#m=null,clearTimeout(e.idleTimer),{ws:e.ws,live:e.state===`live`}):null}#te(e,t,n){let r=`partial_transcript,context`;this.bridge&&this.config?.clientDelegation!==!1&&(r+=`,client_delegation,delegation_update,delegation_read_back,delegation_stream`,this.bridge.clientTools?.()&&(r+=`,client_tools,prior_tool_results`)),n&&(r=`attach,${r}`);let i=new URLSearchParams({voiceProtocol:`runtype-browser-v1`,clientVersion:`persona/${An}`,voiceCapabilities:`full-duplex-v1`,clientCapabilities:r});return n?.forEach((e,t)=>i.set(t,e)),`${ry(e)}/ws/agents/${encodeURIComponent(t)}/voice?${i}`}async startListening(){if(this.#l)return;let e=this.#A;e||(this.#k=!1,this.#D=null),this.#A=!1;let t=this.config?.agentId,n=this.config?.clientToken,r=this.config?.host;if(!t)throw Error(`Runtype voice requires an agentId`);if(!n)throw Error(`Runtype voice requires a clientToken`);if(!r)throw Error(`Runtype voice requires a host (or widget apiUrl)`);let i=++this.#d;this.#f=!1,this.#l=!0;try{let a=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Zv,channelCount:1,echoCancellation:!0}});if(i!==this.#d){a.getTracks().forEach(e=>e.stop());return}this.#r=a;let o=new(window.AudioContext||window.webkitAudioContext)({sampleRate:Zv});if(this.#t=o,o.state===`suspended`){if(await Promise.race([o.resume().catch(()=>{}),new Promise(t=>setTimeout(t,e?500:1e3))]),i!==this.#d)return;if(o.state!==`running`)throw Error(e?this.#D=`${ey} Tap the mic to reconnect.`:`Audio blocked until a tap`)}let s=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Wc(24e3);if(i!==this.#d){s.destroy(),a.getTracks().forEach(e=>e.stop()),o.close().catch(()=>{});return}this.#c=s,this.#he(),this.#ie(o,a,i);let c=await this.#ee();if(i!==this.#d){c?.ws.close(1e3,`client ended call`);return}if(c){let{ws:e}=c;this.#e=e,this.#ne(e,i),c.live||e.send(`{"type":"start"}`),this.#ae(e),this.#be(`listening`);return}let l=new WebSocket(this.#te(r,t),[`runtype.bearer`,n]);l.binaryType=`arraybuffer`,this.#e=l,l.onopen=()=>{i===this.#d&&(this.#ae(l),this.#be(`listening`))},this.#ne(l,i)}catch(e){throw this.#ye(),this.#xe(e),this.#be(`error`),e}}#ne(e,t){e.onmessage=e=>this.#oe(e,t),e.onerror=()=>{t!==this.#d||this.#E||(this.#xe(/* @__PURE__ */ Error(`Voice connection failed`)),this.#be(`error`),this.#ye())},e.onclose=e=>{if(this.#f){this.#f=!1;return}if(t!==this.#d)return;let n=this.#E??(e.code===4408?{reason:`idle_timeout`}:null);if(n)this.#re(n.reason,n.message);else{if(e.code!==1e3){let t=e.code?` (code ${e.code})`:``;this.#xe(/* @__PURE__ */ Error(`Voice connection closed${t}`)),this.#be(`error`)}else this.#be(`idle`);this.#ye()}}}#re(e,t){let n=$v.includes(e)&&!this.#k;if(this.#ye(),n)this.#k=!0,this.#l=!0,this.#D=e===`provider_error`?`${ey} Reconnecting…`:`Reconnecting…`,this.#O=setTimeout(()=>{this.#l=!1,this.#A=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#be(`idle`);else{if($v.includes(e))return this.#D=ey,this.#xe(/* @__PURE__ */ Error(ey)),this.#be(`error`);if(e===`error`)return this.#be(`error`);this.#D=e===`quota`&&t||Qv.get(e)||null,this.#be(`idle`)}}takeNotice(){let e=this.#D;return this.#D=null,e}getDisclosure(){let e=this.config?.disclosureText;return this.#l&&this.#h&&e!==!1?e||`You're talking to an AI assistant. Voice is processed by OpenAI.`:null}async stopListening(){this.#ye(),this.#be(`idle`)}async disconnect(){this.#ye(),this.#be(`disconnected`),this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}stopPlayback(){this.#ve();let e=this.#e;e&&e.readyState===WebSocket.OPEN&&(this.#h&&(this.#_=Date.now()+2e3,e.send(`{"type":"cancel"}`)),this.#be(`listening`))}getInterruptionMode(){return`barge-in`}isBargeInActive(){return this.#l}onLevel(e){this.#n.push(e)}async deactivateBargeIn(){this.#ye(),this.#be(`idle`)}#ie(e,t,n){let r=e.createMediaStreamSource(t);this.#i=r;let i=e.createScriptProcessor(4096,1,1);this.#a=i,i.onaudioprocess=e=>{if(n!==this.#d)return;let t=this.#e,r=t?.readyState===WebSocket.OPEN;if(t&&!r&&t.readyState!==WebSocket.CONNECTING)return;let i=e.inputBuffer.getChannelData(0),a=new Int16Array(i.length),o=0;for(let e=0;e<i.length;e++){let t=Math.max(-1,Math.min(1,i[e]));o+=t*t,a[e]=t<0?t*32768:t*32767}if(t&&r)this.#ae(t),t.send(a.buffer);else for(this.#o.push(a.buffer),this.#s+=a.byteLength;this.#s>256e3;)this.#s-=this.#o.shift().byteLength;if(this.#n.length>0){let e=Math.sqrt(o/i.length),t=Math.max(0,Math.min(1,e*4));for(let e of this.#n)e(t)}},r.connect(i),i.connect(e.destination)}#ae(e){for(let t of this.#o)e.send(t);this.#o=[],this.#s=0}#oe(e,t){if(t!==this.#d)return;if(e.data instanceof ArrayBuffer){this.#pe(e.data,t);return}let n;try{n=JSON.parse(e.data)}catch{return}switch(n.type){case`session_config`:n.speechMode&&(this.#h=n.speechMode===`speech_to_speech`,this.#c?.setContinuousMode?.(this.#h)),Array.isArray(n.capabilities)&&(this.#S=new Set(n.capabilities)),typeof n.callId==`string`&&(this.#T=n.callId),this.#x=this.#h&&this.#S.has(`client_delegation`)&&!!this.bridge,this.#h&&!this.#u&&this.#be(`listening`),this.#S.has(`context`)&&!this.#j&&(this.#j=!0,this.#M=this.#se()),this.#x&&this.#S.has(`client_tools`)&&!this.#V&&(this.#V=this.bridge.clientTools?.()?.open({send:e=>{let n=this.#e;return t!==this.#d||n?.readyState!==WebSocket.OPEN?!1:(n.send(JSON.stringify(e)),!0)},cancelled:e=>this.#w.has(e)}).catch(()=>null)??null);break;case`client_tool_call`:{let e=String(n.delegationId);this.#V&&!this.#W.has(e)&&(this.#W.set(e,this.#U),this.#F.add(e)),this.#V?.then(e=>e?.call(n));break}case`transcript_update`:{let e=n.role===`assistant`?`assistant`:`user`,r=n.utteranceId??n.turnId;if(!r||e===`assistant`&&this.#me())break;let i=String(r);if(e===`user`)n.final===!0&&(this.#ce(t),this.#U={id:i,text:String(n.text??``)}),this.#R=!1;else{if(this.#S.has(`delegation_read_back`)){let e=n.delegationId;(typeof e==`string`&&this.#F.has(e)&&!this.#z.has(i)||this.#R&&!this.#z.has(i))&&(this.#B.add(i),this.#R=!1)}else this.#R&&!this.#z.has(i)&&(this.#B.add(i),this.#R=!1);if(this.#z.add(i),this.#B.has(i))break}this.#Se(e,n.text??``,n.final===!0,{turnId:i,...typeof n.startMs==`number`&&{startMs:n.startMs},...typeof n.endMs==`number`&&{endMs:n.endMs},...this.#x&&{caption:!0}});break}case`delegation_started`:case`delegation_completed`:{let e=String(n.delegationId??n.turnId);if(n.type===`delegation_started`){this.#ce(t),this.#H.add(e),this.#F.delete(e),this.#W.delete(e)&&this.#V?.then(t=>t?.abort(e));let r=n.input;this.#x&&r&&this.#fe(e,{delegationId:e,userText:String(r.text??``),userUtteranceIds:Array.isArray(r.userUtteranceIds)?r.userUtteranceIds.filter(e=>typeof e==`string`):[],messages:Array.isArray(r.messages)?r.messages:[],priorToolResults:r.priorToolResults},t)}else if(n.route===`direct`&&this.#V&&!this.#H.has(e)){let t=this.#W.get(e)??this.#U;this.#W.delete(e),this.#H.add(e),this.#F.add(e),this.bridge?.recordDirectTurn?.({delegationId:e,userText:t?.text??``,userUtteranceIds:t?[t.id]:[],assistantText:typeof n.text==`string`?n.text:``})}n.type===`delegation_completed`&&n.speak!==!1&&this.#F.has(e)&&!this.#I.delete(e)&&!this.#S.has(`delegation_read_back`)&&this.#ue(e),this.#g=n.type===`delegation_started`,!this.#u&&!this.#me()&&this.#be(this.#g?`processing`:`listening`);break}case`delegation_progress`:{let e=String(n.delegationId);this.#F.has(e)&&!this.#I.has(e)&&!this.#w.has(e)&&(this.#I.add(e),this.#ue(e));break}case`delegation_cancelled`:this.#de(String(n.delegationId),n.reason!==`session_ending`&&n.reason!==`provider_cancelled`);break;case`warning`:console.warn(`[Persona voice] ${n.code}: ${n.message??``}`,this.#T??``),n.delegationId&&(n.code===`UNKNOWN_DELEGATION`||n.code===`LATE_RESULT_LIMIT`)&&this.#de(String(n.delegationId));break;case`audio_clear`:this.#ve(),this.#_=0,this.#be(`listening`);break;case`transcript_interim`:this.#be(`listening`),this.#Se(`user`,n.text??``,!1);break;case`transcript_final`:{let e=n.role===`assistant`?`assistant`:`user`;this.#be(e===`user`?`processing`:`speaking`),this.#Se(e,n.text??``,!0);break}case`audio_end`:this.#c?this.#c.markStreamEnd():(this.#u=!1,this.#be(`listening`));break;case`metrics`:this.#Ce({llmMs:n.llm_ms,ttsMs:n.tts_ms,firstAudioMs:n.first_audio_ms,totalMs:n.total_ms});break;case`error`:this.#xe(Error(n.error||`Voice error`)),this.#be(`error`);break;case`session_end`:this.#E={reason:String(n.reason),...typeof n.message==`string`&&{message:n.message}}}}async#se(){let e=this.bridge?.getHistory()??[],t=``;try{let e=this.config?.callContext;t=String((typeof e==`function`?await e():e)??``)}catch{}return ty(e,t)}#ce(e){let t=this.#M;if(!t)return;this.#M=null;let n=!1,r=t.then(t=>{let r=this.#e;!n&&t&&e===this.#d&&r?.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:`context`,text:t}))});this.#N={done:r,drop:()=>n=!0}}async#le(){let e=this.#N;if(!e)return;let t,n=await Promise.race([e.done.then(()=>!1),new Promise(e=>{t=setTimeout(()=>e(!0),2e3)})]);clearTimeout(t),n&&e.drop()}#ue(e){this.#R=!0,this.#L=e}#de(e,t=!1){this.#w.add(e),this.#L===e&&(this.#R=!1),this.#I.delete(e),this.#H.has(e)||this.#F.delete(e),this.#V?.then(t=>t?.abort(e)),this.bridge?.dropDelegation?.(e,t),this.#C.get(e)?.abort()}#fe(e,t,n){let r=this.bridge,i=({type:t,...r})=>{let i=this.#e;return n!==this.#d||i?.readyState!==WebSocket.OPEN||this.#w.has(e)?!1:(i.send(JSON.stringify({type:t,delegationId:e,...r})),!0)},a=(e,t,n,r=0)=>i({type:e,status:t,text:n,...r>0&&{streamedChars:r}});this.#P=this.#P.then(async()=>{if(n!==this.#d||this.#w.has(e))return;let o=null,s=this.#S.has(`delegation_stream`)&&this.#S.has(`delegation_read_back`),c=t=>{o=(o??this.#le()).then(()=>{i({type:`delegation_delta`,text:t})&&this.#F.add(e)})},l=await r.runDelegatedTurn(s?{...t,stream:c}:t).catch(()=>({status:`failed`,text:``}));await this.#le(),await o;let u=s?l.streamedChars??0:0,d=!!l.followUp,f=d&&this.#S.has(`delegation_update`);if(!a(f?`delegation_update`:`delegation_result`,d&&!f?`completed`:l.status,l.text,u)||(l.status!==`failed`&&l.inChat!==!1&&this.#F.add(e),!l.followUp))return;let p=new AbortController;this.#C.set(e,p),l.followUp({signal:p.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,54e4),readBack:f,onUpdate:e=>a(`delegation_update`,`pending_approval`,e)}).then(t=>{this.#C.delete(e),f&&t&&!p.signal.aborted&&a(`delegation_result`,t.status,t.text)})})}#pe(e,t){if(t!==this.#d||!this.#c||this.#me())return;let n=ny(e);n.length!==0&&(this.#u||(this.#u=!0,this.#be(`speaking`)),this.#he(),this.#c.enqueue(n),this.#h&&this.#ge(n.length))}#me(){return Date.now()<this.#_}#he(){if(this.#b||!this.#c)return;this.#b=!0;let e=this.#d;this.#c.onFinished(()=>{e===this.#d&&(this.#b=!1,this.#_e())})}#ge(e){let t=Date.now();this.#v=Math.max(t,this.#v)+e/48,clearTimeout(this.#y),this.#y=setTimeout(()=>this.#_e(),this.#v-t+300)}#_e(){this.#u=!1,this.#v=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#be(this.#g?`processing`:`listening`)}#ve(){this.#c?.flush(),this.#b=!1,this.#he(),this.#u=!1,this.#v=0,clearTimeout(this.#y)}#ye(){this.#d+=1,this.#l=!1,this.#u=!1,this.#$(),this.#h=!1,this.#g=!1,this.#x=!1,this.#S=/* @__PURE__ */ new Set;for(let e of this.#C.values())e.abort();if(this.#C.clear(),this.#w.clear(),this.#T=void 0,this.#E=null,clearTimeout(this.#O),this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F.clear(),this.#I.clear(),this.#L=null,this.#R=!1,this.#z.clear(),this.#B.clear(),this.#V?.then(e=>e?.close()),this.#V=null,this.#H.clear(),this.#W.clear(),this.#U=null,this.#b=!1,this.#_=0,this.#v=0,clearTimeout(this.#y),this.#o=[],this.#s=0,this.#a&&=(this.#a.onaudioprocess=null,this.#a.disconnect(),null),this.#i&&=(this.#i.disconnect(),null),this.#r&&=(this.#r.getTracks().forEach(e=>e.stop()),null),this.#t&&=(this.#t.close().catch(()=>{}),null),this.#c&&=(this.#c.destroy(),null),this.#e){this.#f=!0;try{this.#e.close(1e3,`client ended call`)}catch{}this.#e=null}}onResult(e){this.#G.push(e)}onError(e){this.#K.push(e)}onStatusChange(e){this.#q.push(e)}onTranscript(e){this.#J.push(e)}onMetrics(e){this.#Y.push(e)}#be(e){this.#q.forEach(t=>t(e))}#xe(e){this.#K.forEach(t=>t(e))}#Se(e,t,n,r){this.#J.forEach(i=>i(e,t,n,r))}#Ce(e){this.#Y.forEach(t=>t(e))}},sy=class{#e;#t;#n;#r;#i;#a;constructor(e={}){this.config=e,this.type=`browser`,this.#e=null,this.#t=[],this.#n=[],this.#r=[],this.#i=!1,this.#a=typeof window<`u`?window:void 0}async connect(){this.#r.forEach(e=>e(`connected`))}async startListening(){try{if(this.#i)throw Error(`Already listening`);if(!this.#a)throw Error(`Window object not available`);let e=this.#a.SpeechRecognition||this.#a.webkitSpeechRecognition;if(!e)throw Error(`Browser speech recognition not supported`);this.#e=new e,this.#e.lang=this.config?.language||`en-US`,this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.onresult=e=>{let t=Array.from(e.results).map(e=>e[0]).map(e=>e.transcript).join(``),n=e.results[e.results.length-1].isFinal;this.#t.forEach(e=>e({text:t,confidence:n?.8:.5,provider:`browser`})),n&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=e=>{this.#n.forEach(t=>t(Error(e.error))),this.#r.forEach(e=>e(`error`))},this.#e.onstart=()=>{this.#i=!0,this.#r.forEach(e=>e(`listening`))},this.#e.onend=()=>{this.#i=!1,this.#r.forEach(e=>e(`idle`))},this.#e.start()}catch(e){throw this.#n.forEach(t=>t(e)),this.#r.forEach(e=>e(`error`)),e}}async stopListening(){this.#e&&=(this.#e.stop(),null),this.#i=!1,this.#r.forEach(e=>e(`idle`))}onResult(e){this.#t.push(e)}onError(e){this.#n.push(e)}onStatusChange(e){this.#r.push(e)}async disconnect(){await this.stopListening(),this.#r.forEach(e=>e(`disconnected`))}static isSupported(){return`SpeechRecognition`in window||`webkitSpeechRecognition`in window}};function cy(e){switch(e.type){case`runtype`:if(!e.runtype)throw Error(`Runtype voice provider requires configuration`);return new oy(e.runtype);case`browser`:if(!sy.isSupported())throw Error(`Browser speech recognition not supported`);return new sy(e.browser||{});case`custom`:{let t=e.custom;if(!t)throw Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t==`function`?t():t;if(!n||typeof n.startListening!=`function`)throw Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw Error(`Unknown voice provider type: ${e.type}`)}}function ly(e){if(e?.type===`custom`&&e.custom)return cy({type:`custom`,custom:e.custom});if(e?.type===`runtype`&&e.runtype)return cy({type:`runtype`,runtype:e.runtype});if(sy.isSupported())return cy({type:`browser`,browser:e?.browser||{language:`en-US`}});throw Error(`No supported voice providers available`)}function uy(e){try{return ly(e),!0}catch{return!1}}const dy=(e,t)=>({ok:!1,reason:e,message:t}),fy=e=>e.startsWith(`webmcp:`)?e.slice(7):e,py={warn(e,...t){typeof console<`u`&&typeof console.warn==`function`&&console.warn(`[Persona/WebMCP] ${e}`,...t)}};var my=class{#e;#t;#n=!1;#r=null;#i=!1;#a;constructor(e,t){this.config=e,this.#a=t,this.#e=e.onConfirm??null,this.#t=3e4}setConfirmHandler(e){this.#e=e}isOperational(){return this.config.enabled!==!0||!this.#n?!1:this.#l()!==null}async snapshotForDispatch(){if(await this.#s(),this.config.enabled!==!0)return[];let e=this.#l();if(!e)return[];let t;try{t=(await e.getTools()).filter(Ey)}catch(e){return py.warn(`getTools() threw: shipping an empty WebMCP snapshot.`,e),[]}this.#a.recordToolDisplayTitles(t);let n=typeof location<`u`?location.origin:``;return t.filter(e=>this.#d(e.name)).map(e=>{let t=_y(e.annotations);return{name:e.name,description:e.description,parametersSchema:vy(e.inputSchema),origin:`webmcp`,...n?{pageOrigin:n}:{},...t?{annotations:t}:{},...t?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(e,t,n){let r=await this.#o(e,t,n,!1);return r.ok?yy(r.raw):xy(r.message)}async executeVoiceToolCall(e,t,n={}){let r=await this.#o(e,t,n.signal,n.autoConfirmReadOnly===!0);return r.ok?Cy(r.raw):{status:r.reason===`aborted`?`failed`:r.reason,error:{message:r.message}}}watchToolChanges(e){let t=!1,n=null;return this.#s().then(()=>{if(t||this.config.enabled!==!0)return;let r=this.#l();r&&typeof r.addEventListener==`function`&&(n=r,n.addEventListener(`toolchange`,e))}),()=>{t=!0,n?.removeEventListener(`toolchange`,e),n=null}}async#o(e,t,n,r){if(await this.#s(),this.config.enabled!==!0)return dy(`failed`,`WebMCP is not enabled on this widget.`);let i=this.#l();if(!i){let e=typeof document<`u`&&!!document.modelContext;return dy(`failed`,e?`WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).`:`WebMCP bridge is not operational on this page (document.modelContext not available).`)}let a=fy(e),o;try{o=(await i.getTools()).filter(Ey)}catch(e){let t=e instanceof Error?e.message:String(e);return dy(`failed`,`Failed to read WebMCP registry: ${t}`)}this.#a.recordToolDisplayTitles(o);let s=o.find(e=>e.name===a);if(!s)return dy(`stale`,`WebMCP tool not registered on this page: ${a}`);if(!this.#d(a))return dy(`stale`,`WebMCP tool not allowed by client allowlist: ${a}`);if(n?.aborted)return dy(`aborted`,`Aborted by cancel()`);let c=this.#a.getToolDisplayTitle(a),l=_y(s.annotations),u={toolName:a,args:t,description:s.description,...l?{annotations:l}:{},...c?{title:c}:{},...n?{signal:n}:{},reason:`gate`};if(!(r&&l?.readOnlyHint===!0)&&!await this.#u(u))return dy(`denied`,`User declined the tool call.`);if(n?.aborted)return dy(`aborted`,`Aborted by cancel()`);let d=new AbortController,f=!1,p=setTimeout(()=>{f=!0,d.abort()},this.#t),m=()=>d.abort();n&&(n.aborted?d.abort():n.addEventListener(`abort`,m,{once:!0}));try{return{ok:!0,raw:await i.executeTool(s,by(t),{signal:d.signal})}}catch(e){if(f)return dy(`timeout`,`WebMCP tool '${a}' timed out after ${this.#t}ms`);if(n?.aborted)return dy(`aborted`,`Aborted by cancel()`);let t=e instanceof Error?e.message:String(e);return dy(`failed`,t)}finally{clearTimeout(p),n&&n.removeEventListener(`abort`,m)}}#s(){return this.config.enabled===!0?(this.#r||=this.#c(),this.#r):Promise.resolve()}async#c(){try{if(this.#l()){this.#n=!0;return}let e=await this.#a.loadPolyfill();`initializeWebMCPPolyfill`in e?e.initializeWebMCPPolyfill():e.installWebMCP(),this.#n=!0}catch(e){py.warn(`Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.`,e),this.#n=!1}}#l(){if(typeof document>`u`)return null;let e=document.modelContext;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.getTools!=`function`||typeof t.executeTool!=`function`?(this.#i||(this.#i=!0,py.warn(`document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).`)),null):e}async#u(e){let t=this.#e??wy;try{return await t(e)}catch(t){return py.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,t),!1}}#d(e){let t=this.config.allowlist;return!t||t.length===0||t.some(t=>hy(e,t))}};const hy=(e,t)=>{if(t===`*`)return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`^`+n.replace(/\*/g,`.*`)+`$`).test(e)},gy={type:`object`,properties:{}},_y=e=>{if(!e||typeof e!=`object`)return;let t={};for(let n of[`readOnlyHint`,`destructiveHint`,`consequentialHint`,`untrustedContentHint`,`idempotentHint`,`openWorldHint`,`debugging`]){let r=e[n];typeof r==`boolean`&&(t[n]=r)}return Object.keys(t).length>0?t:void 0},vy=e=>{if(e===void 0||e===``)return{...gy};if(typeof e==`object`)return e!==null&&!Array.isArray(e)?e:{...gy};try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{...gy}}catch{return{...gy}}},yy=e=>{if(e==null)return{content:[{type:`text`,text:``}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:`text`,text:e}]}}return typeof t==`object`&&t&&Array.isArray(t.content)?t:{content:[{type:`text`,text:typeof t==`string`?t:Dy(t)}]}},by=e=>{let t;try{t=JSON.stringify(e)??`{}`}catch{t=`{}`}let n=JSON.parse(t);if(typeof n!=`object`||!n)throw TypeError(`WebMCP tool arguments must be an object or array.`);return Object.defineProperty(n,Symbol.toPrimitive,{value:()=>t}),n},xy=e=>({isError:!0,content:[{type:`text`,text:e}]}),Sy=e=>Array.isArray(e)?e.map(e=>e&&typeof e==`object`&&typeof e.text==`string`?e.text:``).filter(Boolean).join(`
470
+ `):``,Cy=e=>{if(e==null)return{status:`completed`};let t;try{t=JSON.parse(e)}catch{return{status:`completed`,result:e}}return typeof t==`object`&&t&&t.isError===!0?{status:`failed`,error:{message:Sy(t.content)||`The page tool reported an error.`}}:t===void 0?{status:`completed`}:{status:`completed`,result:t}},wy=async e=>{if(typeof window>`u`||typeof window.confirm!=`function`)return!1;let t=Ty(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`\n\nArguments:\n${t}`:``)+(e.description?`\n\n${e.description}`:``);return window.confirm(n)},Ty=e=>{if(e==null)return``;try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+`…`:t}catch{return String(e)}},Ey=e=>(e.window===void 0||typeof window<`u`&&e.window===window)&&(e.origin===void 0||typeof location<`u`&&e.origin===location.origin),Dy=e=>{if(e===void 0)return``;try{return JSON.stringify(e)}catch{return String(e)}};we();var Oy=class extends my{constructor(e){super(e,{recordToolDisplayTitles:I,getToolDisplayTitle:xe,loadPolyfill:Ce})}};function ky(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}function Ay(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n.startsWith(r)?0:e.replace(/([a-z])([A-Z])/g,`$1 $2`).split(/[\s\-_/.]+/).some(e=>e.toLowerCase().startsWith(r))?1:ky(r,n)?2:3}function jy(e,t){let n=e.recencyScore??0,r=t.recencyScore??0;return r===n?e.label.localeCompare(t.label):r-n}function My(e,t){let n=t.trim();if(!n)return[...e].sort(jy);let r=[];for(let t of e){let e=Ay(t.label,n);e!==3&&r.push({item:t,tier:e})}return r.sort((e,t)=>e.tier===t.tier?jy(e.item,t.item):e.tier-t.tier),r.map(e=>e.item)}function Ny(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 Py(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>My(e.items,t),resolve:e.resolve}}function Fy(e){let t=e.commands.map(e=>({id:e.name,label:e.name,description:e.description,iconName:e.iconName,command:e.kind??`prompt`,insertMode:e.insertMode,submitOnSelect:e.submitOnSelect,action:e.action,commandArgsPlaceholder:e.argsPlaceholder})),n=new Map(e.commands.map(e=>[e.name,e])),r=new Map(t.map(e=>[e.id,e]));return{id:e.id,label:e.label,matchCommand:e=>r.get(e),resolveOn:`submit`,search:e=>My(t,Ny(e).name),resolve:(e,t)=>{let r=n.get(e.id);return r?r.kind===`server`?{context:(typeof r.data==`function`?r.data(t.args):r.data)??{}}:{insertText:typeof r.prompt==`function`?r.prompt(t.args):r.prompt??``}:{}}}}function Iy(e,t){let n=t.orientation??`horizontal`,r=n===`vertical`?`ArrowUp`:`ArrowLeft`,i=n===`vertical`?`ArrowDown`:`ArrowRight`;e.setAttribute(`role`,`tablist`);let a=[],o=!1,s=e=>{typeof e.scrollIntoView==`function`&&e.scrollIntoView({block:`nearest`,inline:`nearest`})},c=e=>{let t=e;return a.findIndex(e=>e===t||e.contains(t))},l=e=>{let n=c(e.target);if(n<0)return;let o=n;if(e.key===i)o=Math.min(n+1,a.length-1);else if(e.key===r)o=Math.max(n-1,0);else if(e.key===`Home`)o=0;else if(e.key===`End`)o=a.length-1;else return;e.preventDefault(),o!==n&&t.onSelect(o)},u=e=>{let t=c(e.target);t>=0&&s(a[t])};return e.addEventListener(`keydown`,l),e.addEventListener(`focusin`,u),{beforeRender(){o=typeof document<`u`&&e.contains(document.activeElement)},render(e,t){if(a=e,e.forEach((e,n)=>{e.setAttribute(`role`,`tab`);let r=n===t;e.setAttribute(`aria-selected`,r?`true`:`false`),e.tabIndex=r||t<0&&n===0?0:-1}),o){let n=(t>=0?e[t]:void 0)??e[0];n&&typeof n.focus==`function`&&(s(n),n.focus())}},destroy(){e.removeEventListener(`keydown`,l),e.removeEventListener(`focusin`,u)}}}F(),we(),Qe(),Kt(),rn(),cn(),jn(),Ti(),Wi(),exports.ASK_USER_QUESTION_CLIENT_TOOL=on,exports.ASK_USER_QUESTION_PARAMETERS_SCHEMA=an,exports.ASK_USER_QUESTION_TOOL_NAME=et,exports.AgentWidgetClient=_c,exports.AgentWidgetSession=ll,exports.AttachmentManager=hl,exports.BrowserSpeechEngine=Nc,exports.DEFAULT_COMPONENTS=Ku,exports.DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH=hi,exports.DEFAULT_FLOATING_LAUNCHER_WIDTH=mi,exports.DEFAULT_PALETTE=Bu,exports.DEFAULT_SEMANTIC=Uu,exports.DEFAULT_WIDGET_CONFIG=wi,exports.HistoryProviderError=vc,exports.PRESETS=ov,exports.PRESET_FULLSCREEN=av,exports.PRESET_MINIMAL=iv,exports.PRESET_SHOP=rv,exports.ReadAloudController=Pc,exports.SUGGEST_REPLIES_CLIENT_TOOL=Yt,exports.SUGGEST_REPLIES_PARAMETERS_SCHEMA=Jt,exports.SUGGEST_REPLIES_TOOL_NAME=qt,exports.THEME_ZONES=od,exports.VERSION=An,exports.WEBMCP_TOOL_PREFIX=ye,exports.WebMcpBridge=Oy,exports.accessibilityPlugin=lv,exports.animationsPlugin=uv,exports.applyFeaturePreferences=Vh,exports.applyThemeVariables=wd,exports.attachHeaderToContainer=Xf,exports.brandPlugin=dv,exports.buildComposer=lp,exports.buildDefaultHeader=rp,exports.buildHeader=Yf,exports.buildHeaderWithLayout=cp,exports.buildMinimalHeader=ap,exports.builtInClientToolsForDispatch=sn,exports.canonicalArtifactDisplayMode=Te,exports.collectEnrichedPageContext=$_,exports.componentRegistry=$m,exports.createActionManager=pg,exports.createAgentExperience=$g,exports.createAskUserQuestionBubble=Bt,exports.createBestAvailableVoiceProvider=ly,exports.createBubbleWithLayout=zp,exports.createCSATFeedback=Lg,exports.createComboButton=np,exports.createComponentMiddleware=Mg,exports.createComponentStreamParser=kg,exports.createDefaultSanitizer=Ls,exports.createDemoCarousel=Xv,exports.createDirectivePostprocessor=Ns,exports.createDropdownMenu=Zf,exports.createFlexibleJsonStreamParser=Xe,exports.createIconButton=Qf,exports.createImagePart=ji,exports.createJsonStreamParser=Ye,exports.createLabelButton=$f,exports.createLocalStorageAdapter=vg,exports.createMarkdownProcessor=Ts,exports.createMarkdownProcessorFromConfig=Es,exports.createMessageActions=Lp,exports.createNPSFeedback=Rg,exports.createPlainTextParser=qe,exports.createPlugin=hv,exports.createRegexJsonParser=Je,exports.createRovingTablist=Iy,exports.createSlashCommandsSource=Fy,exports.createSplitButton=tp,exports.createStandardBubble=Rp,exports.createStaticMentionSource=Py,exports.createTextPart=Ai,exports.createTheme=ed,exports.createThemeObserver=Td,exports.createToggleGroup=ep,exports.createTypingIndicator=Op,exports.createVoiceProvider=cy,exports.createWidgetHostLayout=v_,exports.createXmlParser=Ze,exports.default=cv,exports.defaultActionHandlers=dg,exports.defaultJsonActionParser=lg,exports.defaultMentionFilter=My,exports.defaultParseRules=R_,exports.detectColorScheme=_d,exports.directivePostprocessor=Ps,exports.ensureAskUserQuestionSheet=Vt,exports.escapeHtml=ks,exports.extractComponentDirectiveFromMessage=Fg,exports.fileToImagePart=Mi,exports.formatEnrichedContext=ev,exports.generateAssistantMessageId=za,exports.generateCodeSnippet=Fv,exports.generateMessageId=La,exports.generateStableSelector=K_,exports.generateUserMessageId=Ra,exports.getActiveTheme=Sd,exports.getAgentWidgetHandles=S_,exports.getColorScheme=yd,exports.getDisplayText=Di,exports.getHeaderLayout=sp,exports.getImageParts=ki,exports.getPreset=sv,exports.hasComponentDirective=Pg,exports.hasImages=Oi,exports.headerLayouts=op,exports.highContrastPlugin=pv,exports.initAgentWidget=C_,exports.isAskUserQuestionMessage=mt,exports.isComponentDirectiveType=Ag,exports.isDockedMountMode=kf,exports.isHistoryProviderError=yc,exports.isSuggestRepliesMessage=Zt,exports.isVoiceSupported=uy,exports.isWebMcpToolName=Se,exports.isWelcomeVisible=am,exports.latestAgentSuggestions=$t,exports.listRegisteredStreamAnimations=nf,exports.loadMarkdownParsers=T,exports.markdownPostprocessor=Os,exports.mergeWithDefaults=pi,exports.normalizeContent=Ei,exports.normalizeMediaType=Ee,exports.onMarkdownParsersReady=E,exports.parseAskUserQuestionPayload=gt,exports.parseSuggestRepliesPayload=Qt,exports.parseWidgetPreferenceSlice=Fh,exports.pickBestVoice=Mc,exports.pluginRegistry=tg,exports.reducedMotionPlugin=fv,exports.registerIcons=de,exports.registerStreamAnimationPlugin=ef,exports.removeAskUserQuestionSheet=Ht,exports.renderComponentDirective=jg,exports.renderLoadingIndicatorWithFallback=kp,exports.renderLucideIcon=P,exports.resolveArtifactDisplay=Oe,exports.resolveArtifactDisplayMode=ke,exports.resolveConfigPreferences=Hh,exports.resolveDockConfig=jf,exports.resolveSanitizer=Rs,exports.resolveTokens=Xu,exports.resolveWelcomeConfig=rm,exports.stripWebMcpPrefix=R,exports.themeToCssVariables=ad,exports.unregisterStreamAnimationPlugin=tf,exports.validateImageFile=Ni,exports.validateTheme=Zu;
471
471
  //# sourceMappingURL=index.cjs.map